gemi 0.125.0 → 0.126.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +1 -1
  4. package/dist/auth/connections/ConnectionsController.d.ts.map +1 -1
  5. package/dist/auth/oauth/GoogleOAuthProvider.d.ts +1 -1
  6. package/dist/auth/oauth/GoogleOAuthProvider.d.ts.map +1 -1
  7. package/dist/auth/oauth/InstagramOAuthProvider.d.ts +1 -1
  8. package/dist/auth/oauth/InstagramOAuthProvider.d.ts.map +1 -1
  9. package/dist/auth/oauth/XOAuthProvider.d.ts.map +1 -1
  10. package/dist/bun/plugin.js +1 -1
  11. package/dist/bun/preload.js +1 -1
  12. package/dist/{chunk-hff9w6rt.js → chunk-094m8mj3.js} +2 -2
  13. package/dist/{chunk-hff9w6rt.js.map → chunk-094m8mj3.js.map} +1 -1
  14. package/dist/chunk-0arss2xy.js +5 -0
  15. package/dist/{chunk-rany5zgk.js.map → chunk-0arss2xy.js.map} +5 -4
  16. package/dist/{chunk-mmqnq1qh.js → chunk-0f0xxqhy.js} +3 -3
  17. package/dist/{chunk-mmqnq1qh.js.map → chunk-0f0xxqhy.js.map} +1 -1
  18. package/dist/chunk-15bmfr7f.js +5 -0
  19. package/dist/{chunk-tabsxzg9.js.map → chunk-15bmfr7f.js.map} +5 -4
  20. package/dist/{chunk-910p6ne6.js → chunk-1dzs05dc.js} +2 -2
  21. package/dist/{chunk-910p6ne6.js.map → chunk-1dzs05dc.js.map} +1 -1
  22. package/dist/{chunk-rmgkc3a2.js → chunk-1eb4p352.js} +2 -2
  23. package/dist/{chunk-rmgkc3a2.js.map → chunk-1eb4p352.js.map} +1 -1
  24. package/dist/{chunk-cwt8e782.js → chunk-1gd1ykgj.js} +3 -3
  25. package/dist/{chunk-cwt8e782.js.map → chunk-1gd1ykgj.js.map} +1 -1
  26. package/dist/{chunk-stn0a56e.js → chunk-1v368y9a.js} +2 -2
  27. package/dist/{chunk-stn0a56e.js.map → chunk-1v368y9a.js.map} +1 -1
  28. package/dist/{chunk-x2j84d06.js → chunk-28bby5pp.js} +2 -2
  29. package/dist/{chunk-x2j84d06.js.map → chunk-28bby5pp.js.map} +1 -1
  30. package/dist/{chunk-gp00enrk.js → chunk-3fyhd641.js} +1 -1
  31. package/dist/{chunk-ex41d03h.js → chunk-43faxwf5.js} +2 -2
  32. package/dist/{chunk-ex41d03h.js.map → chunk-43faxwf5.js.map} +1 -1
  33. package/dist/{chunk-ey1xrbaz.js → chunk-56ryda9y.js} +2 -2
  34. package/dist/{chunk-ey1xrbaz.js.map → chunk-56ryda9y.js.map} +1 -1
  35. package/dist/{chunk-t2t63wa0.js → chunk-5vvfcdpk.js} +2 -2
  36. package/dist/{chunk-t2t63wa0.js.map → chunk-5vvfcdpk.js.map} +1 -1
  37. package/dist/{chunk-p5df4pn7.js → chunk-62zn06wb.js} +2 -2
  38. package/dist/{chunk-p5df4pn7.js.map → chunk-62zn06wb.js.map} +1 -1
  39. package/dist/{chunk-3br5zr7a.js → chunk-7dzprr9b.js} +3 -3
  40. package/dist/{chunk-3br5zr7a.js.map → chunk-7dzprr9b.js.map} +1 -1
  41. package/dist/{chunk-erzfs4t2.js → chunk-7eerqsg2.js} +2 -2
  42. package/dist/{chunk-erzfs4t2.js.map → chunk-7eerqsg2.js.map} +1 -1
  43. package/dist/{chunk-z5nfve1k.js → chunk-7nfprr9v.js} +2 -2
  44. package/dist/{chunk-z5nfve1k.js.map → chunk-7nfprr9v.js.map} +1 -1
  45. package/dist/{chunk-1jcngq6w.js → chunk-7x2n788t.js} +3 -3
  46. package/dist/{chunk-1jcngq6w.js.map → chunk-7x2n788t.js.map} +1 -1
  47. package/dist/{chunk-rwmja4zs.js → chunk-84rbdyhe.js} +2 -2
  48. package/dist/{chunk-rwmja4zs.js.map → chunk-84rbdyhe.js.map} +1 -1
  49. package/dist/chunk-87bmhng2.js +5 -0
  50. package/dist/{chunk-1xmh61fg.js.map → chunk-87bmhng2.js.map} +1 -1
  51. package/dist/{chunk-c0qpv8x7.js → chunk-87jj7n9q.js} +2 -2
  52. package/dist/{chunk-c0qpv8x7.js.map → chunk-87jj7n9q.js.map} +1 -1
  53. package/dist/{chunk-hxn0s3zh.js → chunk-89swy5aq.js} +2 -2
  54. package/dist/{chunk-hxn0s3zh.js.map → chunk-89swy5aq.js.map} +1 -1
  55. package/dist/{chunk-y9f2see3.js → chunk-8df7fn7f.js} +3 -3
  56. package/dist/{chunk-y9f2see3.js.map → chunk-8df7fn7f.js.map} +1 -1
  57. package/dist/{chunk-bny9s44t.js → chunk-99z9d0sa.js} +2 -2
  58. package/dist/{chunk-bny9s44t.js.map → chunk-99z9d0sa.js.map} +1 -1
  59. package/dist/{chunk-by5gwr8x.js → chunk-9hhxy88x.js} +2 -2
  60. package/dist/{chunk-by5gwr8x.js.map → chunk-9hhxy88x.js.map} +1 -1
  61. package/dist/{chunk-yhht1j7f.js → chunk-9x0pgkns.js} +2 -2
  62. package/dist/{chunk-yhht1j7f.js.map → chunk-9x0pgkns.js.map} +1 -1
  63. package/dist/{chunk-dy58aztm.js → chunk-avfntxm1.js} +2 -2
  64. package/dist/{chunk-dy58aztm.js.map → chunk-avfntxm1.js.map} +1 -1
  65. package/dist/{chunk-h8w9mzjj.js → chunk-b2pdqxj3.js} +11 -11
  66. package/dist/{chunk-h8w9mzjj.js.map → chunk-b2pdqxj3.js.map} +3 -4
  67. package/dist/{chunk-j12hpdxk.js → chunk-bghxdjqv.js} +1 -1
  68. package/dist/{chunk-6vz75swk.js → chunk-bhbxhk9e.js} +2 -2
  69. package/dist/{chunk-6vz75swk.js.map → chunk-bhbxhk9e.js.map} +1 -1
  70. package/dist/{chunk-6q6bhkyf.js → chunk-c48gag78.js} +1 -1
  71. package/dist/{chunk-5fh4pvyt.js → chunk-c65rh4k8.js} +2 -2
  72. package/dist/{chunk-5fh4pvyt.js.map → chunk-c65rh4k8.js.map} +1 -1
  73. package/dist/chunk-cwpezdpw.js +57 -0
  74. package/dist/{chunk-eyptwf54.js.map → chunk-cwpezdpw.js.map} +10 -5
  75. package/dist/{chunk-6wgh7nk6.js → chunk-dm7mada7.js} +3 -3
  76. package/dist/{chunk-6wgh7nk6.js.map → chunk-dm7mada7.js.map} +1 -1
  77. package/dist/{chunk-1mxb44n9.js → chunk-ebdkmzm9.js} +2 -2
  78. package/dist/{chunk-1mxb44n9.js.map → chunk-ebdkmzm9.js.map} +1 -1
  79. package/dist/{chunk-xfvegbxn.js → chunk-ecb8qggy.js} +2 -2
  80. package/dist/{chunk-xfvegbxn.js.map → chunk-ecb8qggy.js.map} +1 -1
  81. package/dist/{chunk-p6jbmcrg.js → chunk-etf6h5m1.js} +2 -2
  82. package/dist/{chunk-p6jbmcrg.js.map → chunk-etf6h5m1.js.map} +1 -1
  83. package/dist/{chunk-zq5375wd.js → chunk-ewv1m1sv.js} +3 -3
  84. package/dist/{chunk-zq5375wd.js.map → chunk-ewv1m1sv.js.map} +1 -1
  85. package/dist/{chunk-dxyxd7b3.js → chunk-gv59djt3.js} +2 -2
  86. package/dist/{chunk-dxyxd7b3.js.map → chunk-gv59djt3.js.map} +1 -1
  87. package/dist/{chunk-8tvfmy1a.js → chunk-gxp48t81.js} +4 -4
  88. package/dist/{chunk-8tvfmy1a.js.map → chunk-gxp48t81.js.map} +1 -1
  89. package/dist/{chunk-r923001x.js → chunk-h4755p9h.js} +2 -2
  90. package/dist/{chunk-r923001x.js.map → chunk-h4755p9h.js.map} +1 -1
  91. package/dist/{chunk-q6ah4yjg.js → chunk-hye22tpt.js} +2 -2
  92. package/dist/{chunk-q6ah4yjg.js.map → chunk-hye22tpt.js.map} +1 -1
  93. package/dist/{chunk-eq5svwca.js → chunk-jg3kg55f.js} +2 -2
  94. package/dist/{chunk-eq5svwca.js.map → chunk-jg3kg55f.js.map} +1 -1
  95. package/dist/{chunk-s4semb89.js → chunk-k6gvbvyw.js} +1 -1
  96. package/dist/{chunk-vhvvjaj3.js → chunk-kzk5r6v4.js} +3 -3
  97. package/dist/{chunk-vhvvjaj3.js.map → chunk-kzk5r6v4.js.map} +1 -1
  98. package/dist/{chunk-ghcvztxn.js → chunk-m63v6aze.js} +2 -2
  99. package/dist/{chunk-ghcvztxn.js.map → chunk-m63v6aze.js.map} +1 -1
  100. package/dist/{chunk-khdkrfxp.js → chunk-mj4n5mar.js} +2 -2
  101. package/dist/{chunk-khdkrfxp.js.map → chunk-mj4n5mar.js.map} +1 -1
  102. package/dist/{chunk-kcsa57km.js → chunk-mj7h1dgh.js} +2 -2
  103. package/dist/{chunk-kcsa57km.js.map → chunk-mj7h1dgh.js.map} +1 -1
  104. package/dist/{chunk-cpem1j1x.js → chunk-mpt5jg4e.js} +2 -2
  105. package/dist/{chunk-cpem1j1x.js.map → chunk-mpt5jg4e.js.map} +1 -1
  106. package/dist/{chunk-3kxe9geg.js → chunk-n8mxsfc2.js} +3 -3
  107. package/dist/{chunk-3kxe9geg.js.map → chunk-n8mxsfc2.js.map} +1 -1
  108. package/dist/{chunk-n3z83qhq.js → chunk-nrf23yan.js} +2 -2
  109. package/dist/{chunk-n3z83qhq.js.map → chunk-nrf23yan.js.map} +1 -1
  110. package/dist/{chunk-sv125fqq.js → chunk-nv2t87c3.js} +2 -2
  111. package/dist/{chunk-sv125fqq.js.map → chunk-nv2t87c3.js.map} +1 -1
  112. package/dist/{chunk-j10a0m7q.js → chunk-p0ccxfkq.js} +1 -1
  113. package/dist/{chunk-crnfxn9n.js → chunk-p7abyc0b.js} +2 -2
  114. package/dist/{chunk-crnfxn9n.js.map → chunk-p7abyc0b.js.map} +1 -1
  115. package/dist/{chunk-hzen9gh4.js → chunk-psdyfaf1.js} +2 -2
  116. package/dist/{chunk-hzen9gh4.js.map → chunk-psdyfaf1.js.map} +1 -1
  117. package/dist/{chunk-knq4ack4.js → chunk-q9mxjh10.js} +2 -2
  118. package/dist/{chunk-knq4ack4.js.map → chunk-q9mxjh10.js.map} +1 -1
  119. package/dist/{chunk-7zj6bk9a.js → chunk-qmcjh6de.js} +2 -2
  120. package/dist/{chunk-7zj6bk9a.js.map → chunk-qmcjh6de.js.map} +1 -1
  121. package/dist/{chunk-k1ebt28j.js → chunk-qy3s6pwz.js} +2 -2
  122. package/dist/{chunk-k1ebt28j.js.map → chunk-qy3s6pwz.js.map} +1 -1
  123. package/dist/{chunk-j5rwv09s.js → chunk-ravssmdy.js} +2 -2
  124. package/dist/{chunk-j5rwv09s.js.map → chunk-ravssmdy.js.map} +1 -1
  125. package/dist/{chunk-rvspb96n.js → chunk-rtb64x14.js} +3 -3
  126. package/dist/{chunk-rvspb96n.js.map → chunk-rtb64x14.js.map} +1 -1
  127. package/dist/{chunk-ayfjjgv2.js → chunk-rvdsaqdv.js} +1 -1
  128. package/dist/{chunk-7vrrgxwm.js → chunk-s0kns9q1.js} +3 -3
  129. package/dist/{chunk-7vrrgxwm.js.map → chunk-s0kns9q1.js.map} +1 -1
  130. package/dist/{chunk-entpqjyn.js → chunk-s2krqtwj.js} +2 -2
  131. package/dist/{chunk-entpqjyn.js.map → chunk-s2krqtwj.js.map} +1 -1
  132. package/dist/{chunk-xe2pm36q.js → chunk-s2y2b8tz.js} +2 -2
  133. package/dist/{chunk-xe2pm36q.js.map → chunk-s2y2b8tz.js.map} +1 -1
  134. package/dist/{chunk-t6qpm2j7.js → chunk-t8kzaxaa.js} +2 -2
  135. package/dist/{chunk-t6qpm2j7.js.map → chunk-t8kzaxaa.js.map} +1 -1
  136. package/dist/{chunk-0x1s02r1.js → chunk-v1eeh7a7.js} +3 -3
  137. package/dist/{chunk-0x1s02r1.js.map → chunk-v1eeh7a7.js.map} +1 -1
  138. package/dist/{chunk-npbf06c1.js → chunk-v7nw1g2n.js} +2 -2
  139. package/dist/{chunk-npbf06c1.js.map → chunk-v7nw1g2n.js.map} +1 -1
  140. package/dist/{chunk-b7a22evs.js → chunk-v80890xx.js} +3 -3
  141. package/dist/{chunk-b7a22evs.js.map → chunk-v80890xx.js.map} +1 -1
  142. package/dist/{chunk-p7mvp5nf.js → chunk-w4111j5d.js} +2 -2
  143. package/dist/{chunk-p7mvp5nf.js.map → chunk-w4111j5d.js.map} +1 -1
  144. package/dist/{chunk-m7pghdcy.js → chunk-wat33wxh.js} +2 -2
  145. package/dist/{chunk-m7pghdcy.js.map → chunk-wat33wxh.js.map} +1 -1
  146. package/dist/{chunk-1n40bdxf.js → chunk-x5vpjzpp.js} +2 -2
  147. package/dist/{chunk-1n40bdxf.js.map → chunk-x5vpjzpp.js.map} +1 -1
  148. package/dist/{chunk-g52fcwca.js → chunk-xe2cfmyb.js} +2 -2
  149. package/dist/{chunk-g52fcwca.js.map → chunk-xe2cfmyb.js.map} +1 -1
  150. package/dist/{chunk-jykkqwcy.js → chunk-ych1dv5q.js} +3 -3
  151. package/dist/{chunk-jykkqwcy.js.map → chunk-ych1dv5q.js.map} +1 -1
  152. package/dist/{chunk-ap3g6rbw.js → chunk-yffm8nxa.js} +2 -2
  153. package/dist/{chunk-ap3g6rbw.js.map → chunk-yffm8nxa.js.map} +1 -1
  154. package/dist/{chunk-6gwxvmjv.js → chunk-yg8se4vs.js} +3 -3
  155. package/dist/{chunk-6gwxvmjv.js.map → chunk-yg8se4vs.js.map} +1 -1
  156. package/dist/chunk-zbvdkh6q.js +10 -0
  157. package/dist/{chunk-b4x1dt3s.js.map → chunk-zbvdkh6q.js.map} +4 -3
  158. package/dist/{chunk-s4xg69r9.js → chunk-zy5gxk1g.js} +2 -2
  159. package/dist/{chunk-s4xg69r9.js.map → chunk-zy5gxk1g.js.map} +1 -1
  160. package/dist/client/index.js +46 -21
  161. package/dist/client/index.js.map +1 -1
  162. package/dist/client/useQuery.d.ts +9 -0
  163. package/dist/client/useQuery.d.ts.map +1 -1
  164. package/dist/config/index.js +1 -1
  165. package/dist/console/run.js +2 -2
  166. package/dist/console/run.js.map +1 -1
  167. package/dist/container/index.js +2 -2
  168. package/dist/container/index.js.map +1 -1
  169. package/dist/database/index.js +2 -2
  170. package/dist/database/index.js.map +1 -1
  171. package/dist/email/index.js +2 -2
  172. package/dist/email/index.js.map +1 -1
  173. package/dist/facades/Cache.d.ts +36 -0
  174. package/dist/facades/Cache.d.ts.map +1 -0
  175. package/dist/facades/Url.d.ts +12 -1
  176. package/dist/facades/Url.d.ts.map +1 -1
  177. package/dist/facades/index.d.ts +1 -0
  178. package/dist/facades/index.d.ts.map +1 -1
  179. package/dist/facades/index.js +2 -2
  180. package/dist/facades/index.js.map +1 -1
  181. package/dist/foundation/index.js +2 -2
  182. package/dist/foundation/index.js.map +1 -1
  183. package/dist/http/Metadata.d.ts.map +1 -1
  184. package/dist/http/index.js +2 -2
  185. package/dist/http/index.js.map +1 -1
  186. package/dist/i18n/dictionaryRuntime.js +2 -2
  187. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  188. package/dist/i18n/index.js +2 -2
  189. package/dist/i18n/index.js.map +1 -1
  190. package/dist/kernel/index.js +3 -3
  191. package/dist/kernel/index.js.map +3 -3
  192. package/dist/kernel/providers.d.ts +2 -2
  193. package/dist/kernel/providers.d.ts.map +1 -1
  194. package/dist/orm/index.js +2 -2
  195. package/dist/orm/index.js.map +1 -1
  196. package/dist/server/index.js +2 -2
  197. package/dist/server/index.js.map +1 -1
  198. package/dist/services/cache/CacheManager.d.ts +115 -0
  199. package/dist/services/cache/CacheManager.d.ts.map +1 -0
  200. package/dist/services/cache/CacheServiceProvider.d.ts +5 -0
  201. package/dist/services/cache/CacheServiceProvider.d.ts.map +1 -0
  202. package/dist/services/cache/CacheStore.d.ts +26 -0
  203. package/dist/services/cache/CacheStore.d.ts.map +1 -0
  204. package/dist/services/cache/MemoryCacheStore.d.ts +36 -0
  205. package/dist/services/cache/MemoryCacheStore.d.ts.map +1 -0
  206. package/dist/services/cache/RedisCacheStore.d.ts +54 -0
  207. package/dist/services/cache/RedisCacheStore.d.ts.map +1 -0
  208. package/dist/services/cache/config.d.ts +35 -0
  209. package/dist/services/cache/config.d.ts.map +1 -0
  210. package/dist/services/index.d.ts +6 -0
  211. package/dist/services/index.d.ts.map +1 -1
  212. package/dist/services/index.js +9 -9
  213. package/dist/services/index.js.map +5 -5
  214. package/dist/services/queue/work.js +2 -2
  215. package/dist/services/queue/work.js.map +1 -1
  216. package/dist/stats/route-table.js +1 -1
  217. package/dist/support/index.js +2 -2
  218. package/dist/support/index.js.map +1 -1
  219. package/dist/utils/appOrigin.d.ts +19 -0
  220. package/dist/utils/appOrigin.d.ts.map +1 -0
  221. package/dist/vitest/index.js +1 -1
  222. package/package.json +1 -1
  223. package/dist/chunk-1xmh61fg.js +0 -5
  224. package/dist/chunk-b4x1dt3s.js +0 -10
  225. package/dist/chunk-eyptwf54.js +0 -57
  226. package/dist/chunk-rany5zgk.js +0 -5
  227. package/dist/chunk-tabsxzg9.js +0 -5
  228. /package/dist/{chunk-gp00enrk.js.map → chunk-3fyhd641.js.map} +0 -0
  229. /package/dist/{chunk-j12hpdxk.js.map → chunk-bghxdjqv.js.map} +0 -0
  230. /package/dist/{chunk-6q6bhkyf.js.map → chunk-c48gag78.js.map} +0 -0
  231. /package/dist/{chunk-s4semb89.js.map → chunk-k6gvbvyw.js.map} +0 -0
  232. /package/dist/{chunk-j10a0m7q.js.map → chunk-p0ccxfkq.js.map} +0 -0
  233. /package/dist/{chunk-ayfjjgv2.js.map → chunk-rvdsaqdv.js.map} +0 -0
@@ -1,57 +0,0 @@
1
- // @bun
2
- import{sg as ZQ}from"./chunk-3kxe9geg.js";import{Mg as $Q}from"./chunk-cwt8e782.js";import{$g as aX,Dh as n3,Kh as e$,Ng as sZ,Oh as IX,Ph as v$,Qh as fG,Rg as MG,Rh as pG,Sg as l7,Tg as i7,Th as hG,Ug as n4,Vg as c4,Yg as d4,Zg as u4,_g as gZ,ah as NG,bh as B7,ch as m,hh as C,ih as BJ,jh as t$,kh as o4,lh as s3,nh as O$,oh as p,ph as _4}from"./chunk-6wgh7nk6.js";import{Wh as g1,Xh as W0,Yh as p1,Zh as n7}from"./chunk-erzfs4t2.js";import{bi as R9,ci as b4,di as N}from"./chunk-tabsxzg9.js";import{gi as UX,ji as f3}from"./chunk-rvspb96n.js";import{ni as u9,qi as wG}from"./chunk-y9f2see3.js";import{Ii as K$,Ni as m1}from"./chunk-ap3g6rbw.js";import{$i as tz}from"./chunk-entpqjyn.js";import{cj as bG}from"./chunk-rany5zgk.js";import{dj as EZ}from"./chunk-sv125fqq.js";import{ej as u3,fj as L1,gj as U$,hj as rG,ij as tG,kj as fZ,lj as gG,uj as eG}from"./chunk-vhvvjaj3.js";import{Jj as V$}from"./chunk-npbf06c1.js";import{Oj as UG,Tj as d5}from"./chunk-ex41d03h.js";import{_j as BG,dk as i}from"./chunk-kcsa57km.js";import{ek as vZ,hk as T}from"./chunk-6gwxvmjv.js";import{pk as p5}from"./chunk-xe2pm36q.js";import{qk as cG}from"./chunk-z5nfve1k.js";import{Ck as HG}from"./chunk-xfvegbxn.js";import{Hk as R4}from"./chunk-hxn0s3zh.js";function g3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function m3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function OQ($){return"total"in $&&"partial"in $&&"body"in $}function X7(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function cZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":u4($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function DQ($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(OQ($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function l4($,Z){if($ instanceof Response)return $;if(!$)return X7();let J=await DQ($),{body:W,start:j,end:Y,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return X7()}let{range:G}=Z;if(G){if(z<=0)return cZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=c4(G,z);if(!F)return cZ(z);W=W.slice(F.start,F.end+1),j=F.start,Y=F.end,X=!0}}}let Q=Boolean(G)&&X,K=Q?206:J.status,O=new Headers;if(O.set("Accept-Ranges","bytes"),O.set("Content-Type",J.type||"application/octet-stream"),O.set("X-Content-Type-Options","nosniff"),Q)O.set("Content-Range",d4(j,Y,z)),O.set("Content-Length",String(Y-j+1));else if(z>=0)O.set("Content-Length",String(z));if(J.name)O.set("Content-Disposition",m3(J.name,J.download));if(J.etag)O.set("ETag",J.etag);if(J.lastModified)O.set("Last-Modified",J.lastModified.toUTCString());for(let[F,B]of Object.entries(J.extraHeaders))O.set(F,B);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:O})}return new Response(W,{status:K,headers:O})}class i$ extends W0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var G7={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function uZ($){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 G7)))return Math.floor(Number(J[1])*(G7[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var dZ=new WeakMap;function K7($){return dZ.has($)}function F7($){return dZ.get($)?.limit??null}function O7($){let Z=dZ.get($);return Z?Z.read>Z.limit:!1}function BQ($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function s4($,Z){let J=BQ($);if(J!==null&&J>Z)throw new i$(Z)}function p3($,Z,J={}){let W=dZ.get($);if(W)W.limit=Z;else{let j={limit:Z,read:0,stream:void 0,used:!1};dZ.set($,j),VQ($,j)}if(J.checkDeclared!==!1)s4($,Z)}function UQ($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function i4($,Z){if(Z.stream!==void 0)return Z.stream;let J=UQ($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(j){W??=J.getReader();let{done:Y,value:z}=await W.read();if(Y){j.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new i$(Z.limit);j.error(X),W.cancel(X).catch(()=>{});return}j.enqueue(z)},cancel(j){return W?W.cancel(j):J.cancel(j)}},{highWaterMark:0}),Z.stream}async function l$($,Z){if(s4($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=i4($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),j=[],Y=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;j.push(Q),Y+=Q.byteLength}let z=new Uint8Array(Y),X=0;for(let G of j)z.set(G,X),X+=G.byteLength;return z}function Q7($){return $.headers.get("Content-Type")??""}function VQ($,Z){let J=(W,j)=>Object.defineProperty($,W,{configurable:!0,...j});J("body",{get:()=>i4($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>l$($,Z)}),J("arrayBuffer",{value:async()=>{let W=await l$($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await l$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await l$($,Z)))}),J("blob",{value:async()=>new Blob([await l$($,Z)],{type:Q7($)})}),J("formData",{value:async()=>new Response(await l$($,Z),{headers:{"Content-Type":Q7($)}}).formData()}),J("clone",{value:()=>{s4($,Z.limit);let W=i4($,Z),j=null;if(W){let[Y,z]=W.tee();Z.stream=Y,j=z}return new Request($.url,{method:$.method,headers:$.headers,body:j,signal:$.signal,duplex:"half"})}})}function D7($){return g3($)}class j0{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(!D7(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(D7(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class U7{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=l0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of B7($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(O7($.rawRequest))throw new i$(F7($.rawRequest));throw J}}}class V7{constructor(...$){return new j0(...$)}}class T7 extends j0{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=n4(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let j=await super.run($);return await l4(j,{range:W,method:J?.method})}catch(j){if(j instanceof o4)return cZ(j.total);throw j}finally{if(Z)Z.rangeRequest=null}}}class M7{constructor(...$){return new T7(...$)}}class H7{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new j0("GET",$,"list"),post:new j0("POST",$,"store")},this.second={get:new j0("GET",$,"show"),put:new j0("PUT",$,"update"),delete:new j0("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 b0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new j0("GET",$,Z)}post($,Z){return new j0("POST",$,Z)}put($,Z){return new j0("PUT",$,Z)}patch($,Z){return new j0("PATCH",$,Z)}delete($,Z){return new j0("DELETE",$,Z)}resource($){return new H7($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${TQ($)}.`);return MQ($,this)}file($,Z){return new V7("GET",$,Z)}stream($,Z){return new M7("GET",$,Z)}proxy($,Z={}){return new U7($,Z)}}function TQ($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function MQ($,Z){let J={stream:new j0("POST",$,"stream"),attach:new j0("POST",$,"attach"),stop:new j0("POST",$,"stop"),upload:new j0("POST",$,"upload")};return class extends b0{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(j){if(j.stream)J.stream.middleware(j.stream);if(j.attach)J.attach.middleware(j.attach);if(j.stop)J.stop.middleware(j.stop);if(j.upload)J.upload.middleware(j.upload);return this}}}var q1="access_token";function Q$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function h3($,Z){let J=Q$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var HQ=/^[A-Za-z0-9_-]+$/,IQ=/^:[A-Za-z_][A-Za-z0-9_]*$/,I7=/^[A-Za-z0-9_-]{1,128}$/,LQ=/^[A-Za-z0-9_.:-]+$/;class h extends Error{constructor($){super($);this.name="InvalidChannelError"}}function L7($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function s$($){if(typeof $!=="string"||$.length===0)throw new h("A channel pattern must be a non-empty string.");if($.length>255)throw new h(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(IQ.test(W)){let j=W.slice(1);if(J.has(j))throw new h(`The channel pattern "${$}" names the param "${j}" twice.`);J.add(j);continue}if(W.startsWith("__"))throw new h(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!HQ.test(W))throw new h(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function lZ($,Z={}){let J=s$($),W=new Set,j=J.map((Y)=>{if(!Y.startsWith(":"))return Y;let z=Y.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new h(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!I7.test(G))throw new h(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let Y of Object.keys(Z))if(!W.has(Y))throw new h(`The channel "${$}" has no param "${Y}".`);if(j.length>255)throw new h(`The topic built from "${$}" is longer than 255 characters.`);return j}function a4($){if(s$($).some((J)=>J.startsWith(":")))throw new h(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function P7($){if(typeof $!=="string"||$.length===0||$.length>64||!LQ.test($))throw new h(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function N7($,Z){if($===Z)return!0;if($===F0)return Z.startsWith(`${F0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((j,Y)=>j===W[Y]||j.startsWith(":")&&I7.test(W[Y]))}var F0="user";function n$($){let Z=typeof $==="object"&&$!==null?$.id:$;return lZ(`${F0}.:id`,{id:Z})}class r{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class c3 extends r{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return p3(this.req.rawRequest,uZ(Z)),{}}}function PQ($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,j=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,j.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var NQ={"body-limit":c3};class v1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:uZ($.bodyLimit)}get aliases(){return{...NQ,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!K7($))p3($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[j,Y]of PQ($).entries())if(typeof j==="string"){let z=J[j];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...Y),runsOnRefusal:_7(z)})}}else if(g3(j)){let z=new j(Z);W.push({run:z.run.bind(z),runsOnRefusal:_7(j)})}else W.push({run:j,runsOnRefusal:!1});return(async()=>{let j={};for(let Y=0;Y<W.length;Y++)try{j={...j,...await W[Y].run()}}catch(z){throw await _Q(W.slice(Y+1)),z}return j})()}}function _7($){return $?.runsOnRefusal===!0}async function _Q($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class d3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class A7{static __brand="ChannelRouter";channels={};public(){return new d3("public")}private($){return new d3("private",$)}async authorize($,Z,J={},W={}){try{AQ(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let j=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!f7(j))return{ok:!1,code:"unknown_channel"};let Y=null;try{if(Z===F0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else Y=lZ(Z,J??{})}catch(G){if(G instanceof h)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return N.exit(()=>u3.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(j.middlewares.length>0)await T(v1).runMiddleware(j.middlewares);if(Z===F0){let Q=await C7(X);if(!Q)return{ok:!1,code:"denied"};if(Y=n$(Q),j.visibility==="private"&&j.authorizer){if(await x7(j.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}if(j.visibility==="private"){if((j.authorizer?await x7(j.authorizer,X,z):await C7(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}catch(Q){if(SQ(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function CQ($,Z,J={},W={}){let j=typeof $==="function"?new $:$;E7(j);let Y=W.as,z,X=null;if(Y instanceof Request)z=Y;else if(Y&&typeof Y==="object"&&Y.rawRequest instanceof Request)z=Y.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=Y?{user:Y}:null;return(await j.authorize(z,Z,J,{carried:X})).ok}function f7($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function C7($){if(!N.getStore().user&&Q$($)===null)return null;try{return await R0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function x7($,Z,J){if(xQ($))return new $().authorize(Z,J);return $(Z,J)}function xQ($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function SQ($){return $?.kind===g1||m1($)||K$($)}var S7=new WeakSet;function AQ($){if(S7.has($))return;E7($),S7.add($)}function E7($){let Z=Object.entries($.channels),J=[];for(let[W,j]of Z){if(!f7(j))throw new h(`The channel "${W}" is not declared with this.public() or this.private().`);let Y=s$(W);if(Y[0].startsWith(":"))throw new h(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==F0&&Y.length===2&&Y[0]===F0)throw new h(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==F0&&j.visibility==="private"&&!j.authorizer&&Y.some((z)=>z.startsWith(":")))throw new h(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===F0?[F0,":id"]:Y})}for(let W=0;W<J.length;W++)for(let j=W+1;j<J.length;j++)if(fQ(J[W].segments,J[j].segments))throw new h(`The channel patterns "${J[W].pattern}" and "${J[j].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function fQ($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class r4{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class t4{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class e4{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class b7{static __brand="McpRouter";routes={};scopes;param($){return new r4($.as,$.input,$.bind)}fromTool($,Z={}){return new e4($,Z)}fromApiRoute($,Z,J){return new t4($,Z,J)}}function O0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let j=W.endsWith("?")||W.endsWith("*"),Y=j?W.slice(0,-1):W,z=Z[Y];if(z===void 0){if(j)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 $J extends W0{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 M1{static to($,...Z){let[J={}]=Z,{search:W={},params:j={},permanent:Y,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new $J([O0($,j)||"/",X.toString()].filter(Boolean).join("?"),z??(Y?301:307))}static external($,Z=307){throw new $J($,Z)}}var R7=Symbol.for("gemi.HttpResponse");class F${kind;body;status;headers;[R7]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return EQ(J),new F$("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 F$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let j of Z)J.append("Set-Cookie",j);this.headers.forEach((j,Y)=>{if(Y.toLowerCase()!=="set-cookie")J.set(Y,j)});for(let j of this.headers.getSetCookie())J.append("Set-Cookie",j);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function EQ($){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 o$($){return typeof $==="object"&&$!==null&&$[R7]===!0}function bQ($,Z,J={}){return F$.error($,Z,J)}class w7{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:j=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return M1.to(J,{permanent:W,status:j}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function ZJ($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,j=J?$.name:$.name??$.file?.name,Y=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",Y||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(j)Z.set("Content-Disposition",m3(j,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class k7{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function y7($,Z){if(o$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class q7{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(j)=>{return new J()[W](j)}}}async run($,Z){let J=y7(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=l0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class v7{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends H1{routes=J??{}};else if(Array.isArray(Z)){let[W,j]=Z;this.handler=(Y)=>{return new W()[j](Y)},this.children=class extends H1{routes=J??{}}}else this.children=class extends H1{routes=Z},this.handler=()=>({})}async run($,Z){let J=y7(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=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class H1{middlewares=[];featureGates=[];routes={};view($,Z){return new q7($,Z)}file($){return new k7($)}redirect($){return new w7($)}layout($,Z,J){return new v7($,Z,J)}}function RQ($){return $}function wQ(){return{aliases:{},global:[],bodyLimit:null}}var W1="redirect";function j1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),j=`${J.pathname}${W}`.replaceAll(":","%3A");return j.startsWith("//")?Z:j}catch{return Z}}function a$($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function kQ($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,j,...Y]=W.split("/");if(T(i).supportedLocales.includes(j))W=`/${Y.join("/")}`;return Z?`${W}${J.search}`:W}function yQ($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function l3($,Z){let J=Z||T(A).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let j=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let Y=kQ($,!W);if(W||!yQ(new URL(Y,j).pathname,j.pathname))j.searchParams.set(W1,Y)}return W?j.href:`${j.pathname}${j.search}`}class g7 extends r{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await h3(T(A),J);if(!W)throw new O$({redirectTo:l3(J,$)});return Z.setUser(W),{}}}var WJ="gemi_same_site",JJ="private, no-cache, no-store, max-age=0, must-revalidate";class i3 extends r{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(WJ))return{};if(Q$(Z))return{};let j=J.headers.get("Sec-Fetch-Site");if(j&&j!=="cross-site")return{};throw W.searchParams.set(WJ,"1"),new m7(`${W.pathname}${W.search}`)}}class m7 extends W0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=qQ($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":JJ,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":JJ}},viewData:{status:200,data:{},headers:{"Cache-Control":JJ},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function qQ($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class p7 extends r{async run(...$){let[Z="public",J="864000",...W]=$,j=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)j="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")j="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")j="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",j);return{}}}var h7={"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 c7 extends r{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={...h7,...this.config.origins[Z]};for(let[W,j]of Object.entries(J))$.ctx().setHeaders(W,j)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...h7,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,j]of Object.entries(J))$.ctx().setHeaders(W,j)}return{}}}var vQ="Rate limit exceeded";class h1 extends W0{result;retryAfter;constructor($,Z=vQ){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?jJ($):{}};this.payload={api:{status:429,data:{error:{...p1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function jJ($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class Y1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,j=Z.cost??1;if(d7("window",W),d7("limit",J),!Number.isFinite(j)||j<0)throw Error(`Rate limiter cost must be zero or greater, got ${j}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:j})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new h1(W,typeof J==="function"?J(W):J);return W}}function d7($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class s7 extends r{async run($,Z){let J=gQ();if(!J)return{};let W=await J.consume(this.key(),{limit:u7($)??this.config.limit,window:u7(Z)??this.config.window});if(this.config.headers!==!1){let j=this.req.ctx?.();if(j)for(let[Y,z]of Object.entries(jJ(W)))j.setHeaders(Y,z)}if(!W.allowed)throw new h1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=l7(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${r$(this.req)}:${this.req.routePath??"*"}`}}function gQ(){try{let $=T();return $.bound(Y1)?$.make(Y1):null}catch{return null}}function r$($){let Z=i7($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function u7($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class o7 extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new YJ;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new YJ;return{}}}class YJ extends W0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:n7("csrf","Invalid CSRF token",403)}},view:{}}}class a7{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class r7{all($,Z){return!0}}class zJ{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new t$:new s3}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends r{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let j;if(J!==void 0){if(j=$.thread?await $.thread(J,Z):null,j===null||j===void 0)throw this.refusal()}if(W!==void 0){let Y=await $.body(W,Z);if(await this.authorize(Z,Y),J!==void 0&&String(j)!==String(Y))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,j)}}}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 t$:$ instanceof s3}}function mQ($){return new zJ($)}async function o3($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,j]=await eQ($.body),z=W.length>=2&&W[0]===31&&W[1]===139?j.pipeThrough(new DecompressionStream("gzip")):j;return tQ(z,Z,J,$.url)}async function tQ($,Z,J,W){let j=$.getReader(),Y=[],z=0;try{for(;;){let{done:Q,value:K}=await j.read();if(Q)break;if(z+K.byteLength>Z){if(!J)throw new n3(W,Z);Y.push(K.subarray(0,Z-z)),z=Z;break}Y.push(K),z+=K.byteLength}}finally{j.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of Y)X.set(Q,G),G+=Q.byteLength;return X}async function eQ($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,j=new ReadableStream({start(Y){if(J.done)Y.close();else Y.enqueue(W)},async pull(Y){let z=await Z.read();if(z.done)Y.close();else Y.enqueue(z.value)},cancel(Y){return Z.cancel(Y)}});return[W,j]}function a3($){return new TextDecoder("utf-8").decode($)}var $K={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function D$($){return $.replace(/[&<>"']/g,(Z)=>$K[Z])}var ZK={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function XJ($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return ZK[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function GJ($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function t7($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let j=$.indexOf("<",W);if(j===-1){Z.text(XJ($.slice(W)));return}if(j>W)Z.text(XJ($.slice(W,j)));if($.startsWith("<!--",j)){let Y=$.indexOf("-->",j+4);if(Y===-1)return;W=Y+3}else if($.startsWith("<![CDATA[",j)){let Y=$.indexOf("]]>",j+9);if(Y===-1)return;Z.text($.slice(j+9,Y)),W=Y+3}else if($.startsWith("<?",j)){let Y=$.indexOf("?>",j+2);if(Y===-1)return;W=Y+2}else if($.startsWith("<!",j)){let Y=$.indexOf(">",j+2);if(Y===-1)return;let z=$.indexOf("[",j+2);if(z!==-1&&z<Y){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=Y+1}else if($[j+1]==="/"){let Y=$.indexOf(">",j+2);if(Y===-1)return;Z.close(GJ($.slice(j+2,Y).trim())),W=Y+1}else{let Y=JK($,j+1);if(Y===-1)return;let z=$.slice(j+1,Y),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=GJ(z.slice(0,G));if(Q){if(Z.open(Q,WK(z.slice(G)),X),X)Z.close(Q)}W=Y+1}}}function JK($,Z){let J=null;for(let W=Z;W<$.length;W++){let j=$[W];if(J){if(j===J)J=null}else if(j==='"'||j==="'")J=j;else if(j===">")return W}return-1}function WK($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[GJ(W[1])]=XJ(W[2]??W[3]??"");return Z}class Y0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var W9="http://www.sitemaps.org/schemas/sitemap/0.9",jK="http://www.w3.org/1999/xhtml",FJ=`<?xml version="1.0" encoding="UTF-8"?>
3
- `,e7=`<urlset xmlns="${W9}" xmlns:xhtml="${jK}">
4
- `,$9=`</urlset>
5
- `,B$=50000,iZ=52428800,Z9=2048,YK=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),zK=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,XK="application/xml; charset=utf-8",J9=new TextEncoder;function OJ($,Z){let J;try{J=new URL($)}catch{throw new Y0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new Y0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>Z9)throw new Y0(`Sitemap: ${Z} is over ${Z9} characters: "${W.slice(0,80)}\u2026".`);return W}function j9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new Y0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!zK.test($))throw new Y0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function GK($){let Z=OJ($.loc,"loc"),J=`<url><loc>${D$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${D$(j9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!YK.has($.changefreq))throw new Y0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new Y0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let j=W.hrefLang?.trim();if(!j)throw new Y0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let Y=OJ(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${D$(j)}" href="${D$(Y)}"/>`}return`${J}</url>
6
- `}function QK($){let Z=$.maxUrls??B$,J=$.maxBytes??iZ;if(!Number.isInteger(Z)||Z<1||Z>B$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${B$}.`);if(!Number.isInteger(J)||J<1||J>iZ)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${iZ}.`);return{maxUrls:Z,maxBytes:J}}function Y9($,Z={}){let{maxUrls:J,maxBytes:W}=QK(Z),j=J9.encode(FJ+e7+$9).byteLength,Y=[],z=[],X=j,G=()=>{Y.push(FJ+e7+z.join("")+$9),z=[],X=j};for(let Q of $){let K=GK(Q),O=J9.encode(K).byteLength;if(j+O>W)throw new Y0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+O>W)G();z.push(K),X+=O}if(z.length>0||Y.length===0)G();return Y}function z9($){let Z="",J=0;for(let W of $){if(++J>B$)throw new Y0(`Sitemap: an index can list at most ${B$} sitemaps.`);let j=OJ(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${D$(j)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${D$(j9(W.lastmod,j))}</lastmod>`;Z+=`</sitemap>
7
- `}return`${FJ}<sitemapindex xmlns="${W9}">
8
- ${Z}</sitemapindex>
9
- `}function QJ($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",XK);return new Response($,{status:Z,headers:W})}function KK($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function FK($,Z={}){let J=Y9($,Z),W=KK(Z.page);if(W!==null){let Y=J[W-1];return Y?QJ(Y,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return QJ(J[0],200,Z.headers);let j=Z.pageUrl;if(!j)throw new Y0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return QJ(z9(J.map((Y,z)=>({loc:j(z+1)}))),200,Z.headers)}function KJ($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function X9($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let F=[];for(let B of W.split(/\r?\n/)){if(F.length>=J)break;let D=B.trim()?KJ(B):null;if(D)F.push({loc:D})}if(F.length===0&&W.length>0)throw new Y0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:F}}let j=null,Y=[],z=[],X=[],G=null,Q=null,K="",O=()=>j==="index"?z.length:Y.length;if(t7(W,{stopped:()=>O()>=J,open(F,B){let D=X[X.length-1];if(X.push(F),j===null){if(F==="urlset")j="urlset";else if(F==="sitemapindex")j="index";return}if(j==="urlset"&&F==="url"&&D==="urlset"||j==="index"&&F==="sitemap"&&D==="sitemapindex")G={};else if(G&&(D==="url"||D==="sitemap")&&(F==="loc"||F==="lastmod"||F==="changefreq"||F==="priority"))Q=F,K="";else if(G&&j==="urlset"&&D==="url"&&F==="link"){let U=B.href?KJ(B.href):null;if(B.rel?.toLowerCase()==="alternate"&&B.hreflang&&U)(G.alternates??=[]).push({hrefLang:B.hreflang,href:U})}},close(F){let B=X.lastIndexOf(F);if(B===-1)return;if(X.length=B,Q&&F===Q&&G)G[Q]=K.trim(),Q=null;else if(G&&(F==="url"||F==="sitemap")){let D=G;G=null,Q=null;let U=D.loc?KJ(D.loc):null;if(!U)return;if(j==="index"){z.push(D.lastmod?{loc:U,lastmod:D.lastmod}:{loc:U});return}let V={loc:U};if(D.lastmod)V.lastmod=D.lastmod;if(D.changefreq)V.changefreq=D.changefreq;let M=D.priority?Number(D.priority):NaN;if(Number.isFinite(M))V.priority=M;if(D.alternates)V.alternates=D.alternates;Y.push(V)}},text(F){if(Q)K+=F}}),j===null)throw new Y0("Sitemap: the document has no <urlset> or <sitemapindex>.");return j==="index"?{kind:j,sitemaps:z}:{kind:j,urls:Y}}async function*OK($,Z={}){let{maxUrls:J=B$,maxSitemaps:W=50,maxDepth:j=3,maxSize:Y=iZ,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,K=0,O=0;while(G.length>0&&O<J&&K<W){let F=G.shift(),B=F.url.replace(/#.*$/,"");if(Q.has(B))continue;Q.add(B),K++;let D;try{let U=await e$(F.url,{...X,maxSize:Y});if(!U.ok)throw U.body?.cancel().catch(()=>{}),new Y0(`Sitemap: ${F.url} answered ${U.status}.`,F.url,U.status);let V=a3(await o3(U,Y));D=X9(V,{maxUrls:Math.max(J-O,W-K)})}catch(U){if(F.depth===0||!z||X.signal?.aborted)throw U;z(U,F.url);continue}if(D.kind==="index"){if(F.depth>=j)continue;G=D.sitemaps.slice(0,W-K).map((V)=>({url:V.loc,depth:F.depth+1})).concat(G);continue}for(let U of D.urls)if(yield{...U,sitemap:F.url},++O>=J)return}}var G9={response:FK,chunk:Y9,index:z9,parse:X9,read:OK,MAX_URLS:B$,MAX_BYTES:iZ};var DK=512000,BK=new TextEncoder;function Q9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function K9($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let j=$.codePointAt(J);if(j>65535)J++;for(let Y of BK.encode(String.fromCodePoint(j)))Z+=`%${Y.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function UK($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,j=0,Y=0,z=-1,X=0;while(Y<Z.length)if(j<W.length&&W[j]!=="*"&&W[j]===Z[Y])j++,Y++;else if(j<W.length&&W[j]==="*")z=j++,X=Y;else if(j===W.length&&!J)return!0;else if(z!==-1)j=z+1,Y=++X;else return!1;while(j<W.length&&W[j]==="*")j++;return j===W.length}class $Z{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=Q9($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let j=new URL(String($));J=j.pathname+j.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=K9(J);let W=null;for(let j of this.groupsFor(Z))for(let Y of j.rules){if(!UK(Y.path,J))continue;let z=Y.path.length,X=Y.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var VK={"user-agent":"user-agent",useragent:"user-agent","user agent":"user-agent",allow:"allow",disallow:"disallow",dissallow:"disallow",disalow:"disallow",sitemap:"sitemap","site-map":"sitemap","crawl-delay":"crawl-delay"};function F9($,Z={}){let J=[],W=[],j=null,Y=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),G=(X===-1?z:z.slice(0,X)).trim(),Q=G.indexOf(":");if(Q===-1)continue;let K=VK[G.slice(0,Q).trim().toLowerCase()],O=G.slice(Q+1).trim();if(!K)continue;if(K==="sitemap"){if(!O||/\s/.test(O))continue;try{let F=Z.url?new URL(O,Z.url):new URL(O);if(F.protocol==="http:"||F.protocol==="https:")W.push(F.href)}catch{}continue}if(K==="user-agent"){if(!Y||!j)j={userAgents:[],rules:[]},J.push(j),Y=!0;let F=Q9(O);if(F)j.userAgents.push(F);continue}if(!j)continue;if(Y=!1,K==="crawl-delay"){let F=Number(O);if(Number.isFinite(F)&&F>=0)j.crawlDelay=F;continue}if(!O)continue;j.rules.push({type:K,path:K9(O)})}return new $Z(J,W)}async function TK($,Z={}){let{maxSize:J=DK,...W}=Z,j=new URL("/robots.txt",$),Y=await e$(j,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=Y.status;if(z===429||z>=500)return Y.body?.cancel().catch(()=>{}),new $Z([],[],"unreachable");if(z>=400)return Y.body?.cancel().catch(()=>{}),new $Z([],[],"unavailable");let X=await o3(Y,J,!0),G=a3(X);if(X.byteLength>=J)G=G.slice(0,Math.max(0,G.lastIndexOf(`
10
- `)));return F9(G,{url:Y.url})}function DJ($){return $===void 0?[]:typeof $==="string"?[$]:$}function r3($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
- `}function O9($){let Z=[];for(let W of $.rules??[]){let j=DJ(W.userAgent);if(j.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let Y=j.map((X)=>r3("User-agent",X)).join(""),z=[...DJ(W.allow).map((X)=>["Allow",X]),...DJ(W.disallow).map((X)=>["Disallow",X])];for(let[X,G]of z){if(!G.startsWith("/")&&!G.startsWith("*"))throw TypeError(`Robots: ${X} "${G}" must start with "/" or "*".`);Y+=r3(X,G)}if(z.length===0)Y+=`Disallow:
12
- `;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);Y+=r3("Crawl-delay",String(W.crawlDelay))}Z.push(Y)}let J=($.sitemaps??[]).map((W)=>{let j;try{j=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return r3("Sitemap",j.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function MK($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(O9($),{status:200,headers:J})}var D9={response:MK,text:O9,parse:F9,fetch:TK};import{createHmac as B9,randomBytes as HK}from"crypto";var UJ="v2.";function VJ($){return $.startsWith(UJ)}function ZZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function U9($){let Z=HK(16).toString("hex"),J=B9("sha256",ZZ()).update(`${$}:${Z}`).digest("hex");return`${UJ}${J}`}function t3($,Z){let J=B9("sha256",ZZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${UJ}${J}`}import{createHash as PK,createHmac as NK,randomInt as _K,timingSafeEqual as M9}from"crypto";function V9($,Z){return Math.floor($/Z)*Z}function IK($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function TJ($,Z,J,W){return Z*IK(J,W)+$}function LK($){let{current:Z,previous:J,elapsed:W,window:j,limit:Y,cost:z}=$,X=Y-z;if(X<0)return j;let G=Math.max(0,j-W);if(J>0){let K=j*(1-(X-Z)/J);if(K<=j)return Math.max(0,Math.ceil(K-W))}if(Z<=X)return G;if(Z<=0)return G;let Q=j*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function T9($){let{allowed:Z,current:J,previous:W,now:j,elapsed:Y,window:z,limit:X,cost:G}=$;if(Z){let K=TJ(J,W,Y,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-K)),resetAt:j-Y+z,retryAfter:0}}let Q=LK({current:J,previous:W,elapsed:Y,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:j+Q,retryAfter:Q}}class MJ{}class HJ extends MJ{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,j=$.cost??1,Y=Date.now(),z=V9(Y,W),X=Y-z,G=this.roll(Z,W,z);G.limit=J;let K=TJ(G.current,G.previous,X,W)+j<=J;if(K)G.current+=j;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(Y);return T9({allowed:K,current:G.current,previous:G.previous,now:Y,elapsed:X,window:W,limit:J,cost:j})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,j]of this.buckets)if($-j.windowStart>=j.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,j],Y)=>({key:W,order:Y,spent:j.limit>0?(j.current+j.previous)/j.limit:0}));J.sort((W,j)=>W.spent-j.spent||W.order-j.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var L9="h1.";function e3($,Z,J){let W=NK("sha256",ZZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${L9}${W}`}function nZ($,Z,J,W){let j=typeof W==="string"?W:"",Y=typeof J==="string"?J:"",z=Y.startsWith(L9),X=e3($,Z,j),G=Buffer.from(z?X:j),Q=Buffer.from(Y);if(G.length!==Q.length||j===""||Y==="")return M9(G,G),!1;return M9(G,Q)}function P9($){let Z="";for(let J=0;J<$;J++)Z+=String(_K(0,10));return Z}var N9=320;function oZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>N9)return null;return Z.toLowerCase()}function $6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>N9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var H9=null;function _9(){try{let $=T();if(typeof $?.bound==="function"&&$.bound(Y1))return $.make(Y1)}catch{}return H9??=new Y1({driver:new HJ,limit:1000,window:60}),H9}function I9($){return $.length<=64?$:`sha256:${PK("sha256").update($).digest("hex")}`}async function JZ($,Z,J,W){let j=_9(),Y=[[`auth:code-${$}:ip:${I9(r$(J))}`,W.perIp]];if(Z!==null)Y.push([`auth:code-${$}:email:${I9(Z)}`,W.perEmail]);for(let[z,X]of Y){if(!X)continue;let[G,Q]=X,K=await j.consume(z,{limit:G,window:Q});if(!K.allowed)throw new h1(K)}}async function C9($,Z,J,W=10){let j=Math.max(86400,Math.ceil(W*60*(J+1)));return(await _9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:j})).allowed}import{randomBytes as LJ}from"crypto";class IJ extends C{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 Z6($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let j=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${j}, got ${Z}`)}}function CK($={}){for(let Z of["password","magicLink"]){let J=$?.[Z];if(J!==void 0&&typeof J!=="boolean")throw Error(`auth.${Z} must be true or false, got ${JSON.stringify(J)}`)}}function PJ($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,j=$.maxAttempts??5;return Z6("length",Z,4,12),Z6("expiresInMinutes",J,1),Z6("linkExpiresInMinutes",W,1),Z6("maxAttempts",j,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:j,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 xK($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function x9($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function S9($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature } with an OAuthProvider.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function UM($){return $}function A9($={}){return CK($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:IJ,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:xK,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>LJ(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return LJ(32).toString("hex")},generateMagicLinkToken:()=>LJ(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:PJ($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var SK=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),AK=new Set(["svg","math"]);function f9($){return $===32||$===9||$===10||$===12||$===13}function E9($){return $>=65&&$<=90||$>=97&&$<=122}function J6($){return $>=65&&$<=90?$+32:$}function b9(){let $="data",Z="",J=!1,W="",j=0,Y=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,K=()=>{if(!J&&SK.has(Z)){$="rawText",W=`</${Z}`,j=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(AK.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},O=(F)=>{switch($){case"data":if(F===60)$="tagOpen";return;case"tagOpen":if(F===33)$="bang",Y=0;else if(F===47)$="endTagOpen";else if(E9(F))$="tagName",J=!1,z=!1,Z=String.fromCharCode(J6(F));else if(F===63)$="bogus";else if(F===60)$="tagOpen";else $="data";return;case"endTagOpen":if(E9(F))$="tagName",J=!0,z=!1,Z=String.fromCharCode(J6(F));else if(F===62)$="data";else $="bogus";return;case"tagName":if(f9(F)||F===47)$="inTag",z=F===47;else if(F===62)K();else Z+=String.fromCharCode(J6(F));return;case"inTag":if(F===62){K();return}if(z=F===47,F===34)$="attrDouble";else if(F===39)$="attrSingle";return;case"attrDouble":if(F===34)$="inTag";z=!1;return;case"attrSingle":if(F===39)$="inTag";z=!1;return;case"bang":if(F===45){if(Y+=1,Y===2)$="comment",Y=0}else if(F===62)$="data";else $="bogus";return;case"bogus":if(F===62)$="data";return;case"comment":if(F===45)Y=Y<2?Y+1:2;else if(F===62&&Y>=2)$="data",Y=0;else Y=0;return;case"rawText":{if(j<W.length){if(J6(F)===W.charCodeAt(j))j+=1;else j=F===60?1:0;return}if(F===62)$="data",Z="";else if(f9(F)||F===47)$="inTag",Z="";else j=F===60?1:0;return}}};return{scanToInsertionPoint(F){for(let B=0;B<F.length;B++){if(Q())return B;O(F[B])}return F.length},write(F){for(let B=0;B<F.length;B++)O(F[B])},isSafe:Q}}function I1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function fK($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${I1([$.path,$.variantKey,$.data])})</script>`}function EK($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${I1([$.id,$.locale,$.strings])})</script>`}function NJ($,Z,J={},W){let j=new TextEncoder,Y=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;Y.push(fK(D))}),W?.onUse((D)=>{Y.push(EK(D))});let Q=$.getReader(),K=b9(),O=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},F=(D)=>{while(Y.length>0){let U=j.encode(Y.shift());K.write(U),O(D,U)}},B=(D,U)=>{if(Y.length===0){K.write(U),O(D,U);return}let V=K.scanToInsertionPoint(U);if(V>0)O(D,U.subarray(0,V));if(K.isSafe())F(D);let M=U.subarray(V);if(M.length>0)K.write(M),O(D,M)};return new ReadableStream({async pull(D){let U;try{U=await Q.read()}catch(L){throw G(),L}let{done:V,value:M}=U;if(V){F(D),D.close(),G();return}if(!z){if(z=!0,K.write(M),O(D,M),J.onShell?.(),K.isSafe())F(D);return}B(D,M)},cancel(D){return G(),Q.cancel(D)}})}var bK=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function W6($){if(!$)return!1;return bK.test($)}async function w9($,Z=()=>{}){let J=N.getStore(),W=J?.req??null,j=null;if(W?.rawRequest?.url)try{j=new URL(W.rawRequest.url).pathname}catch{j=null}return{user:J?.user??null,attributes:await RK($,Z),request:{path:j,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:R9(),isBot:W6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function k9($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function RK($,Z){if(!$.context)return{};try{let J=N.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 y9($,Z){return`${$}:${Z}`}function _J($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function q9($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function v9($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let Y;try{Y=Z.when(J)}catch(z){return W.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 j=kK($,Z,J,W.buckets);return q9(j,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function wK($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function kK($,Z,J,W){let j=y9(Z.salt??$,wK(J));if(!W)return _J(j);let Y=W.get(j);if(Y!==void 0)return Y;let z=_J(j);return W.set(j,z),z}class g9 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 CJ{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}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 g9(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 W of $??[]){let j=typeof W?.key==="string"?W.key:null;if(!j){this.warn("Ignoring a feature row with no `key`.");continue}if(!(j in this.declared)){this.warn(`Feature row "${j}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(j,W.active===!0);let Y=yK(W);if(Y)J.set(j,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 yK($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let j=W instanceof Date?W:new Date(W);if(!Number.isNaN(j.getTime()))Z.updatedAt=j}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class qK{}class vK 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 xJ 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 m9 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 p9{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 c1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new CJ($.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(([W,j])=>({key:W,describe:j.describe,rollout:j.rollout,targeted:j.when!==void 0,serverOnly:j.serverOnly,salt:j.salt,active:$.get(W),...Z.get(W)}))}}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{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new m9(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=gK(J.actor),j=this.config.source;if(typeof j.write!=="function")throw new xJ(j.constructor?.name||"an anonymous source");let{actorRecorded:Y}=await j.write($,Z,{actor:W});if(W!==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 p9(this,k9($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),j=W?.get($);if(j)return j;let Y=this.declared[$];if(!Y)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=v9($,Y,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,J){let W={};for(let[j,Y]of Object.entries(this.declared)){if(J.clientOnly&&Y.serverOnly)continue;W[j]=(await this.evaluateIn(j,$,Z)).value}return W}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 $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await w9(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=N.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=N.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(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}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 gK($){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`.")}async function h9($){if($===void 0)return!0;return await T(c1).enabled($)}async function WZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=x9($[Z]);if(!J||!await h9(J.feature))return null;return J.provider}async function c9($){let Z=[];for(let J of Object.keys($))if(await WZ($,J))Z.push(J);return Z}function SJ($){if($&&typeof $==="object")delete $.password;return $}function mK(){return new Proxy({},{get:($,Z)=>u9(Z)})}var d9=new WeakMap;function l9($){if($&&typeof $==="object"){for(let Z of Object.values($))l9(Z);Object.freeze($)}return $}var pK={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},hK=l9({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:pK});class AJ{models;constructor($=mK()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return hK}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??U$(),W=T(V$).connection(J),j=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await L1()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||L1())return j();let z=(d9.get(W)??Promise.resolve()).then(j,j);return d9.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return SJ(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return SJ(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?SJ(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 lD}from"crypto";function w0($,Z,J,W,j){return i0(Z,XW($,Z),J,W,j)}function i0($,Z,J,W,j,Y){let z=wJ(Z,J,W);if(j&&Z!==z)throw RangeError(uY($,Z,J,W,Y));return z}function XW($,Z){let J=$[Z];if(J===void 0)throw TypeError(G8(Z));return J}function B0($){return $!==null&&/object|function/.test(typeof $)}function q0($,Z=Map){let J=new Z;return(W,...j)=>{if(J.has(W))return J.get(W);let Y=$(W,...j);return J.set(W,Y),Y}}function hJ($){return I$({name:$},1)}function I$($,Z){return a0((J)=>({value:J,configurable:1,writable:!Z}),$)}function GW($){return a0((Z)=>({get:Z,configurable:1}),$)}function H6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function KZ($,Z){let J={},W=$.length;for(let j of Z)J[$[--W]]=j;return J}function a0($,Z,J){let W={};for(let j in Z)W[j]=$(Z[j],j,J);return W}function j3($,Z,J){let W={};for(let j=0;j<Z.length;j++){let Y=Z[j];W[Y]=$(Y,j,J)}return W}function cK($,Z,J){let W={};for(let j=0;j<$.length;j++)W[Z[j]]=J[$[j]];return W}function g0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function cJ($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function dJ($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function QW($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function KW($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function FW($,Z,J){let W={...J};for(let j=0;j<Z;j++)W[$[j]]=0;return W}function R($,...Z){return(...J)=>$(...Z,...J)}function i9($){return $[0].toUpperCase()+$.substring(1)}function Y3($){return $.slice().sort()}function K6($,Z){return String(Z).padStart($,"0")}function d1($,Z){return Math.sign($-Z)}function wJ($,Z,J){return Math.min(Math.max($,Z),J)}function N1($,Z){return[Math.floor($/Z),rZ($,Z)]}function rZ($,Z){return($%Z+Z)%Z}function i1($,Z){return[I6($,Z),uJ($,Z)]}function I6($,Z){return Math.trunc($/Z)||0}function uJ($,Z){return $%Z||0}function j6($){return Math.abs($%1)===0.5}function OW($,Z,J){let W=0,j=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=X1[X],K=c/Q,[O,F]=i1(G,K);W+=F*Q,j+=O}let[Y,z]=i1(W,c);return[j+Y,z]}function L6($,Z,J){let W={};for(let j=Z;j>=0;j--){let Y=X1[j];W[J[j]]=I6($,Y),$=uJ($,Y)}return W}function DW($){return $===w?Z4:[]}function BW($){return $===w?U3:[]}function UW($){return $===w?["year","day"]:[]}function VW($){if($!==void 0)return t($)}function TW($){if($!==void 0)return r0($)}function lJ($){if($!==void 0)return z3($)}function r0($){return IW(z3($))}function z3($){return HW(wF($))}function iJ($){if($==null)throw TypeError("Cannot be null or undefined");return $}function MW($,Z){if(Z==null)throw RangeError(G8($));return Z}function C1($){if(!B0($))throw TypeError(dY);return $}function P6($,Z,J=$){if(typeof Z!==$)throw TypeError(O3(J,Z));return Z}function HW($,Z="number"){if(!Number.isInteger($))throw RangeError(jF(Z,$));return $||0}function IW($,Z="number"){if($<=0)throw RangeError(YF(Z,$));return $}function sJ($){if(typeof $=="symbol")throw TypeError(QF);return String($)}function F6($,Z){return B0($)?String($):t($,Z)}function N6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(GF($));return $}function LW($,Z="number"){if(typeof $=="bigint")throw TypeError(XF(Z));if($=Number($),!Number.isFinite($))throw RangeError(zF(Z,$));return $}function N0($,Z){return Math.trunc(LW($,Z))||0}function PW($,Z){return HW(LW($,Z),Z)}function s9($,Z){return IW(N0($,Z),Z)}function nJ($,Z){let[J,W]=i1(Z,c),j=$+J,Y=Math.sign(j);return Y&&Y===-Math.sign(W)&&(j-=Y,W+=Y*c),[j,W]}function YZ($,Z,J=1){return nJ($[0]+Z[0]*J,$[1]+Z[1]*J)}function zZ($,Z){return nJ($[0],$[1]+Z)}function c0($,Z){return YZ(Z,$,-1)}function C0($,Z){return d1($[0],Z[0])||d1($[1],Z[1])}function NW($,Z,J){return C0($,Z)===-1||C0($,J)===1}function _6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function XZ($,Z=1){let J=c/Z,[W,j]=i1($,J);return[W,j*Z]}function _W($,Z=1){let[J,W]=$,j=Math.floor(W/Z),Y=c/Z;return BigInt(J)*BigInt(Y)+BigInt(j)}function d0($,Z=1,J){let[W,j]=$,[Y,z]=i1(j,Z);return W*(c/Z)+(Y+(J?z/Z:0))}function oJ($,Z,J=N1){let[W,j]=$,[Y,z]=J(j,Z);return[W*(c/Z)+Y,z]}function aJ($,Z){let J=$.formatToParts(Z),W={};for(let j of J)W[j.type]=j.value;return W}function rJ($){return w0($,"isoYear",W3,J3,1),$.isoYear===W3?w0($,"isoMonth",4,12,1):$.isoYear===J3&&w0($,"isoMonth",1,9,1),$}function u1($){return x1({...$,...o0,isoHour:12}),$}function x1($){let Z=w0($,"isoYear",W3,J3,1),J=Z===W3?1:Z===J3?-1:0;return J&&u0(_0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function u0($){if(!$||NW($,pF,mF))throw RangeError(r6);return $}function s1($){return OW($,5,Z1)[1]}function C6($){let[Z,J]=N1($,c);return[L6(J,5,Z1),Z]}function CW($){return xW($)[0]}function xW($){return oJ($,n0)}function x0($){return FZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function _0($){let Z=x0($);if(Z!==void 0){let[J,W]=i1(Z,y0);return[J,W*G1+($.isoMicrosecond||0)*f$+($.isoNanosecond||0)]}}function tJ($,Z){let[J,W]=C6(s1($)-Z);return u0(_0({...$,isoDay:$.isoDay+W,...J}))}function O6(...$){return FZ(...$)/Zz}function FZ(...$){let[Z,J]=SW(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function SW($,Z=1,J=1,W=0,j=0,Y=0,z=0){let X=$===W3?1:$===J3?-1:0,G=new Date;return G.setUTCHours(W,j,Y,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function o1($,Z){let[J,W]=zZ($,Z);W<0&&(W+=c,J-=1);let[j,Y]=N1(W,G1),[z,X]=N1(Y,f$);return x6(J*y0+j,z,X)}function x6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-gF)/y0)*Math.sign($),j=new Date($-W*y0);return KZ(W4,[j.getUTCFullYear(),j.getUTCMonth()+1,j.getUTCDate()+W,j.getUTCHours(),j.getUTCMinutes(),j.getUTCSeconds(),j.getUTCMilliseconds(),Z,J])}function AW($){return[$.isoYear,$.isoMonth,$.isoDay]}function fW(){return P1}function eJ($,Z){switch(Z){case 2:return $2($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function EW($){return $2($)?366:365}function $2($){return $%4==0&&($%100!=0||$%400==0)}function bW($){let[Z,J]=SW($.isoYear,$.isoMonth,$.isoDay);return rZ(Z.getUTCDay()-J,7)||7}function RW({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function dK($){let Z=x0($);if(Z<cF)return RW($);let J=aJ(x8(GZ),Z),{era:W,eraYear:j}=dj(J,GZ);return[W,j]}function S6($){return L$($),A6($,1),$}function L$($){return wW($,1),$}function n9($){return KW(M8,$,wW($))}function wW($,Z){let{isoYear:J}=$,W=w0($,"isoMonth",1,fW(),Z);return{isoYear:J,isoMonth:W,isoDay:w0($,"isoDay",1,eJ(J,W),Z)}}function A6($,Z){return KZ(Z1,[w0($,"isoHour",0,23,Z),w0($,"isoMinute",0,59,Z),w0($,"isoSecond",0,59,Z),w0($,"isoMillisecond",0,999,Z),w0($,"isoMicrosecond",0,999,Z),w0($,"isoNanosecond",0,999,Z)])}function q($){return $===void 0?0:Mz(C1($))}function X3($,Z=0){$=t0($);let J=Hz($),W=tF($,Z);return[Mz($),W,J]}function Z2($){return Hz(t0($))}function kW($){return $=t0($),L8($,9,6,1)}function OZ($,Z,J,W=9,j=0,Y=4){Z=t0(Z);let z=L8(Z,W,j),X=j2(Z),G=T3(Z,Y),Q=V3(Z,W,j,1);return z==null?z=Math.max(J,Q):gW(z,Q),X=Y2(X,Q,1),$&&(G=((K)=>K<4?(K+2)%4:K)(G)),[z,Q,X,G]}function f6($,Z=6,J){let W=j2($=z2($,M6)),j=T3($,7),Y=V3($,Z);return Y=MW(M6,Y),W=Y2(W,Y,void 0,J),[Y,W,j]}function J2($){return P8(t0($))}function yW($,Z){return W2(t0($),Z)}function W2($,Z=4){let J=vW($);return[T3($,4),...qW(V3($,Z),J)]}function qW($,Z){return $!=null?[X1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function j2($){let Z=$[tZ];return Z===void 0?1:N0(Z,tZ)}function Y2($,Z,J,W){let j=W?c:X1[Z+1];if(j){let Y=X1[Z];if(j%(($=i0(tZ,$,1,j/Y-(W?0:1),1))*Y))throw RangeError(O3(tZ,$))}else $=i0(tZ,$,1,J?1e9:1,1);return $}function vW($){let Z=$[RJ];if(Z!==void 0){if(typeof Z!="number"){if(sJ(Z)==="auto")return;throw RangeError(O3(RJ,Z))}Z=i0(RJ,Math.floor(Z),0,9,1)}return Z}function t0($){return $===void 0?{}:C1($)}function z2($,Z){return typeof $=="string"?{[Z]:$}:C1($)}function z0($){if($!==void 0){if(B0($))return Object.assign(Object.create(null),$);throw TypeError(dY)}}function E6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:uF[Z]})}function X2($,Z,J=9,W=0,j){let Y=Z[$];if(Y===void 0)return j?W:void 0;if(Y=sJ(Y),Y==="auto")return j?W:null;let z=vJ[Y];if(z===void 0&&(z=qF[Y]),z===void 0)throw RangeError(sY($,Y,vJ));return i0($,z,W,J,1,B3),z}function P$($,Z,J,W=0){let j=J[$];if(j===void 0)return W;let Y=sJ(j),z=Z[Y];if(z===void 0)throw RangeError(sY($,Y,Z));return z}function gW($,Z){if(Z>$)throw RangeError(AF)}function U0($){return{branding:Y4,epochNanoseconds:$}}function H0($,Z,J){return{branding:E1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:b$,calendar:Z,...g0(Bz,$)}}function G0($,Z=$.calendar){return{branding:E$,calendar:Z,...g0(H8,$)}}function M$($,Z=$.calendar){return{branding:IZ,calendar:Z,...g0(H8,$)}}function D6($,Z=$.calendar){return{branding:LZ,calendar:Z,...g0(H8,$)}}function e0($){return{branding:j4,...g0(Dz,$)}}function s($){return{branding:z4,sign:a1($),...g0(U8,$)}}function mW($){return CW($.epochNanoseconds)}function b6($){return oJ($.epochNanoseconds,G1)[0]}function pW($){return _W($.epochNanoseconds,f$)}function hW($){return _W($.epochNanoseconds)}function cW($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:t($.id)}function DZ($,Z){return $===Z||T0($)===T0(Z)}function dW($,Z,J,W,j){let Y=H$(W),[z,X]=((V,M)=>{let L=M((V=z2(V,pJ))[Vz]),H=rF(V);return H=MW(pJ,H),[H,L]})(j,$);if($3(Math.max(z,Y),X))return o9(W,z);if(!X)throw RangeError(t6);let[G,Q,K]=v6(Z,J,X),O=b2(K),F=g6(K),B=R2(K),D=F(Q,G,W),U=B(Q,G,D,z);return $3(z,X)?o9(U,z):((V,M,L,H,S,f,E)=>{let x=a1(V),[P,I]=G2(H,T8(L,V),L,x,S,f,E),k=Q2(M,P,I);return V[v[L]]+k*x})(U,O(D),z,Q,G,O,F)}function o9($,Z){return d0(D0($),X1[Z],1)}function G2($,Z,J,W,j,Y,z){let X=v[J],G={...Z,[X]:Z[X]+W},Q=z($,j,Z),K=z($,j,G);return[Y(Q),Y(K)]}function Q2($,Z,J){let W=d0(c0(Z,J));if(!W)throw RangeError(D3);return d0(c0(Z,$))/W}function uW($,Z){let[J,W,j]=f6(Z,5,1);return U0(w6($.epochNanoseconds,J,W,j,1))}function lW($,Z,J){let{epochNanoseconds:W,timeZone:j,calendar:Y}=Z,[z,X,G]=f6(J);if(z===0&&X===1)return Z;let Q=$(j);if(z===6)W=((K,O,F,B)=>{let D=S0(F,O),[U,V]=K(D),M=F.epochNanoseconds,L=v0(O,U),H=v0(O,V);if(NW(M,L,H))throw RangeError(D3);return $j(Q2(M,L,H),B)?H:L})(tW,Q,Z,G);else{let K=Q.getOffsetNanosecondsFor(W);W=_$(Q,aW(o1(W,K),z,X,G),K,2,0,1)}return H0(W,j,Y)}function iW($,Z){return X0(aW($,...f6(Z)),$.calendar)}function sW($,Z){let[J,W,j]=f6(Z,5);var Y;return e0((Y=j,K2($,G3(J,W),Y)[0]))}function nW($,Z){let J=$(Z.timeZone),W=S0(Z,J),[j,Y]=tW(W),z=d0(c0(v0(J,j),v0(J,Y)),$4,1);if(z<=0)throw RangeError(D3);return z}function oW($,Z){let{timeZone:J,calendar:W}=Z,j=((Y,z,X)=>v0(z,Y(S0(X,z))))(eW,$(J),Z);return H0(j,J,W)}function aW($,Z,J,W){return rW($,G3(Z,J),W)}function rW($,Z,J){let[W,j]=K2($,Z,J);return x1({...C$($,j),...W})}function K2($,Z,J){return C6(n1(s1($),Z,J))}function B6($){return n1($,e6,7)}function G3($,Z){return X1[$]*Z}function tW($){let Z=eW($);return[Z,C$(Z,1)]}function eW($){return vF(6,$)}function uK($,Z,J){let W=Math.min(H$($),6);return UZ(k6(D0($,W),Z,J),W)}function R6($,Z,J,W,j,Y,z,X,G,Q){if(W===0&&j===1)return $;let K=$3(W,X)?m6(X)&&W<6&&J>=6?iK:lK:sK,[O,F,B]=K($,Z,J,W,j,Y,z,X,G,Q);return B&&W!==7&&(O=((D,U,V,M,L,H,S,f)=>{let E=a1(D);for(let x=M+1;x<=V;x++){if(x===7&&V!==7)continue;let P=T8(x,D);P[v[x]]+=E;let I=d0(c0(S(f(L,H,P)),U));if(I&&Math.sign(I)!==E)break;D=P}return D})(O,F,J,Math.max(6,W),z,X,G,Q)),O}function w6($,Z,J,W,j){if(Z===6){let Y=((z)=>z[0]+z[1]/c)($);return[n1(Y,J,W),0]}return k6($,G3(Z,J),W,j)}function k6($,Z,J,W){let[j,Y]=$;W&&Y<0&&(Y+=c,j-=1);let[z,X]=N1(n1(Y,Z,J),c);return nJ(j+z,X)}function n1($,Z,J){return $j($/Z,J)*Z}function $j($,Z){return ZO[Z]($)}function lK($,Z,J,W,j,Y){let z=a1($),X=D0($),G=w6(X,W,j,Y),Q=c0(X,G),K=Math.sign(G[0]-X[0])===z,O=UZ(G,Math.min(J,6));return[{...$,...O},YZ(Z,Q),K]}function iK($,Z,J,W,j,Y,z,X,G,Q){let K=a1($),O=d0(D0($,5)),F=G3(W,j),B=n1(O,F,Y),[D,U]=G2(z,{...$,...V8},6,K,X,G,Q),V=B-d0(c0(D,U)),M=0;V&&Math.sign(V)!==K?Z=zZ(D,B):(M+=K,B=n1(V,F,Y),Z=zZ(U,B));let L=h6(B);return[{...$,...L,days:$.days+M},Z,Boolean(M)]}function sK($,Z,J,W,j,Y,z,X,G,Q){let K=a1($),O=v[W],F=T8(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let B=I6($[O],j)*j;F[O]=B;let[D,U]=G2(z,F,W,j*K,X,G,Q),V=B+Q2(Z,D,U)*K*j,M=n1(V,j,Y),L=Math.sign(M-V)===K;return F[O]=M,[F,L?U:D,L]}function F2($,Z,J,W){let[j,Y,z,X]=((Q)=>{let K=W2(Q=t0(Q));return[Q.timeZone,...K]})(W),G=j!==void 0;return((Q,K,O,F,B,D)=>{O=k6(O,B,F,1);let U=K.getOffsetNanosecondsFor(O);return M2(o1(O,U),D)+(Q?N$(B6(U)):"Z")})(G,Z(G?$(j):R$),J.epochNanoseconds,Y,z,X)}function O2($,Z,J){let[W,j,Y,z,X,G]=((Q)=>{Q=t0(Q);let K=P8(Q),O=vW(Q),F=$O(Q),B=T3(Q,4),D=V3(Q,4);return[K,eF(Q),F,B,...qW(D,O)]})(J);return((Q,K,O,F,B,D,U,V,M,L)=>{F=k6(F,M,V,1);let H=Q(O).getOffsetNanosecondsFor(F);return M2(o1(F,H),L)+N$(B6(H),U)+((S,f)=>f!==1?"["+(f===2?"!":"")+T0(S)+"]":"")(O,D)+H2(K,B)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,j,Y,z,X,G)}function D2($,Z){let[J,W,j,Y]=((Q)=>(Q=t0(Q),[P8(Q),...W2(Q)]))(Z);return z=$.calendar,X=J,G=Y,M2(rW($,j,W),G)+H2(z,X);var z,X,G}function B2($,Z){return J=$.calendar,W=$,j=J2(Z),U6(W)+H2(J,j);var J,W,j}function U2($,Z){return Zj($.calendar,Jj,$,J2(Z))}function V2($,Z){return Zj($.calendar,nK,$,J2(Z))}function T2($,Z){let[J,W,j]=yW(Z);return Y=j,Wj(K2($,W,J)[0],Y);var Y}function y6($,Z){let[J,W,j]=yW(Z,3);return W>1&&($={...$,...uK($,W,J)}),((Y,z)=>{let{sign:X}=Y,G=X===-1?A0(Y):Y,{hours:Q,minutes:K}=G,[O,F]=oJ(D0(G,3),n0,i1);Fj(O);let B=I2(F,z),D=z>=0||!X||B;return(X<0?"-":"")+"P"+a9({Y:T$(G.years),M:T$(G.months),W:T$(G.weeks),D:T$(G.days)})+(Q||K||O||D?"T"+a9({H:T$(Q),M:T$(K),S:T$(O,D)+B}):"")})($,j)}function Zj($,Z,J,W){let j=T0($),Y=W>1||W===0&&j!==w;return W===1?j===w?Z(J):U6(J):Y?U6(J)+jj(j,W===2):Z(J)}function a9($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function M2($,Z){return U6($)+"T"+Wj($,Z)}function U6($){return Jj($)+"-"+s0($.isoDay)}function Jj($){let{isoYear:Z}=$;return(Z<0||Z>9999?Yj(Z)+K6(6,Math.abs(Z)):K6(4,Z))+"-"+s0($.isoMonth)}function nK($){return s0($.isoMonth)+"-"+s0($.isoDay)}function Wj($,Z){let J=[s0($.isoHour),s0($.isoMinute)];return Z!==-1&&J.push(s0($.isoSecond)+((W,j,Y,z)=>I2(W*G1+j*f$+Y,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function N$($,Z=0){if(Z===1)return"";let[J,W]=N1(Math.abs($),$4),[j,Y]=N1(W,e6),[z,X]=N1(Y,n0);return Yj($)+s0(J)+":"+s0(j)+(z||X?":"+s0(z)+I2(X):"")}function H2($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==w)return jj(J,Z===2)}return""}function jj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function I2($,Z){let J=K6(9,$);return J=Z===void 0?J.replace(jO,""):J.slice(0,Z),J?"."+J:""}function Yj($){return $<0?"-":"+"}function T$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function oK($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),j=o1(J,W);return{calendar:$.calendar,...j,offsetNanoseconds:W}}function zj($,Z){let J=S0(Z,$);return{calendar:Z.calendar,...g0(Bz,J),offset:N$(J.offsetNanoseconds),timeZone:Z.timeZone}}function _$($,Z,J,W=0,j=0,Y,z){if(J!==void 0&&W===1&&(W===1||z))return tJ(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,K,O,F)=>{let B=_0(K);F&&(O=B6(O));for(let D of Q){let U=d0(c0(D,B));if(F&&(U=B6(U)),U===O)return D}})(X,Z,J,Y);if(G!==void 0)return G;if(W===0)throw RangeError(PF)}return z?_0(Z):v0($,Z,j,X)}function v0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(NF);if(W.length)return W[J===3?1:0];let j=_0(Z),Y=((X,G)=>{let Q=X.getOffsetNanosecondsFor(zZ(G,-c));return P2(X.getOffsetNanosecondsFor(zZ(G,c))-Q)})($,j),z=Y*(J===2?-1:1);return(W=$.getPossibleInstantsFor(o1(j,z)))[J===2?0:W.length-1]}function L2($){if(Math.abs($)>=c)throw RangeError(IF);return $}function P2($){if($>c)throw RangeError(LF);return $}function N2($,Z,J){return U0(u0(YZ(Z.epochNanoseconds,((W)=>{if(Oj(W))throw RangeError(xF);return D0(W,5)})($?A0(J):J))))}function _2($,Z,J,W,j,Y=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...f2(z,X,W,J?A0(j):j,Y)}}function C2($,Z,J,W,j=Object.create(null)){let{calendar:Y}=J;return X0(E2($(Y),J,Z?A0(W):W,j),Y)}function x2($,Z,J,W,j){let{calendar:Y}=J;return G0(q6($(Y),J,Z?A0(W):W,j),Y)}function S2($,Z,J,W,j=Object.create(null)){let Y=J.calendar,z=$(Y),X=eZ(z,J);Z&&(W=p6(W)),W.sign<0&&(X=z.dateAdd(X,{...M0,months:1}),X=C$(X,-1));let G=z.dateAdd(X,W,j);return M$(eZ(z,G),Y)}function A2($,Z,J){return e0(Xj(Z,$?A0(J):J)[0])}function f2($,Z,J,W,j){let Y=D0(W,5),z=J.epochNanoseconds;if(Oj(W)){let X=S0(J,$);z=YZ(v0($,{...q6(Z,X,{...W,...V8},j),...g0(Z1,X)}),Y)}else z=YZ(z,Y),q(j);return{epochNanoseconds:u0(z)}}function E2($,Z,J,W){let[j,Y]=Xj(Z,J);return x1({...q6($,Z,{...J,...V8,days:J.days+Y},W),...j})}function q6($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);q(W);let j=J.days+D0(J,5)[0];return j?u1(C$(Z,j)):Z}function eZ($,Z,J=1){return C$(Z,J-$.day(Z))}function Xj($,Z){let[J,W]=D0(Z,5),[j,Y]=C6(s1($)+W);return[j,J+Y]}function C$($,Z){return Z?{...$,...x6(x0($)+Z*y0)}:$}function v6($,Z,J){let W=$(J.calendar);return m6(J)?[J,W,Z(J.timeZone)]:[{...J,...o0},W]}function b2($){return $?cW:_0}function g6($){return $?R(f2,$):E2}function R2($){return $?R(rK,$):tK}function m6($){return $&&$.epochNanoseconds}function $3($,Z){return $<=6-(m6(Z)?1:0)}function w2($,Z,J,W,j,Y,z){let X=$(t0(z).relativeTo),G=Math.max(H$(j),H$(Y));if($3(G,X))return s(BZ(((U,V,M,L)=>{let H=YZ(D0(U),D0(V),L?-1:1);if(!Number.isFinite(H[0]))throw RangeError(r6);return{...M0,...UZ(H,M)}})(j,Y,G,W)));if(!X)throw RangeError(t6);W&&(Y=A0(Y));let[Q,K,O]=v6(Z,J,X),F=g6(O),B=R2(O),D=F(K,Q,j);return s(B(K,Q,F(K,D,Y),G))}function Gj($,Z,J,W,j){let Y=H$(W),[z,X,G,Q,K]=((E,x,P)=>{E=z2(E,M6);let I=L8(E),k=P(E[Vz]),g=j2(E),y1=T3(E,7),Z0=V3(E);if(I===void 0&&Z0===void 0)throw RangeError(SF);return Z0==null&&(Z0=0),I==null&&(I=Math.max(Z0,x)),gW(I,Z0),g=Y2(g,Z0,1),[I,Z0,g,y1,k]})(j,Y,$),O=Math.max(Y,z);if(!m6(K)&&O<=6)return s(BZ(((E,x,P,I,k)=>{let g=w6(D0(E),P,I,k);return{...M0,...UZ(g,x)}})(W,z,X,G,Q)));if(!K)throw RangeError(t6);let[F,B,D]=v6(Z,J,K),U=b2(D),V=g6(D),M=R2(D),L=V(B,F,W),H=M(B,F,L,z),S=W.sign,f=a1(H);if(S&&f&&S!==f)throw RangeError(D3);return f&&(H=R6(H,U(L),z,X,G,Q,B,F,U,V)),s(H)}function Qj($){return $.sign===-1?p6($):$}function p6($){return s(A0($))}function A0($){let Z={};for(let J of v)Z[J]=-1*$[J]||0;return Z}function Kj($){return!$.sign}function a1($,Z=v){let J=0;for(let W of Z){let j=Math.sign($[W]);if(j){if(J&&J!==j)throw RangeError(CF);J=j}}return J}function BZ($){for(let Z of yF)i0(Z,$[Z],-WW,WW,1);return Fj(d0(D0($),n0)),$}function Fj($){if(!Number.isSafeInteger($))throw RangeError(_F)}function D0($,Z=6){return OW($,Z,v)}function UZ($,Z=6){let[J,W]=$,j=L6(W,Z,v);if(j[v[Z]]+=J*(c/X1[Z]),!Number.isFinite(j[v[Z]]))throw RangeError(r6);return j}function h6($,Z=5){return L6($,Z,v)}function Oj($){return Boolean(a1($,Oz))}function H$($){let Z=9;for(;Z>0&&!$[v[Z]];Z--);return Z}function aK($,Z){return[$,Z]}function r9($){let Z=Math.floor($/G6)*G6;return[Z,Z+G6]}function Dj($){let Z=r1($=F6($));if(!Z)throw RangeError(k0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(k0($));J=VZ(Z.offset)}return Z.timeZone&&v2(Z.timeZone,1),U0(tJ(S6(Z),J))}function Bj($){let Z=r1(t($));if(!Z)throw RangeError(k0($));if(Z.timeZone)return Nj(Z,Z.offset?VZ(Z.offset):void 0);if(Z.m)throw RangeError(k0($));return Cj(Z)}function Uj($,Z){let J=r1(t($));if(!J||!J.timeZone)throw RangeError(k0($));let{offset:W}=J,j=W?VZ(W):void 0,[,Y,z]=X3(Z);return Nj(J,j,Y,z)}function VZ($){let Z=v2($);if(Z===void 0)throw RangeError(k0($));return Z}function Vj($){let Z=r1(t($));if(!Z||Z.m)throw RangeError(k0($));return X0(_j(Z))}function c6($){let Z=r1(t($));if(!Z||Z.m)throw RangeError(k0($));return G0(Z.p?_j(Z):Cj(Z))}function Tj($,Z){let J=y2(t(Z));if(J)return k2(J),M$(rJ(L$(J)));let W=c6(Z);return M$(eZ($(W.calendar),W))}function k2($){if($.calendar!==w)throw RangeError(_1($.calendar))}function Mj($,Z){let J=q2(t(Z));if(J)return k2(J),D6(L$(J));let W=c6(Z),{calendar:j}=W,Y=$(j),[z,X,G]=Y.h(W),[Q,K]=Y.I(z,X),[O,F]=Y.N(Q,K,G);return D6(u1(Y.P(O,F,G)),j)}function Hj($){let Z,J=((W)=>{let j=QO.exec(W);return j?(d6(j[10]),Aj(j)):void 0})(t($));if(!J){if(J=r1($),!J)throw RangeError(k0($));if(!J.p)throw RangeError(k0($));if(J.m)throw RangeError(_1("Z"));k2(J)}if((Z=y2($))&&n9(Z))throw RangeError(k0($));if((Z=q2($))&&n9(Z))throw RangeError(k0($));return e0(A6(J,1))}function Ij($){let Z=((J)=>{let W=OO.exec(J);return W?((j)=>{function Y(K,O,F){let B=0,D=0;if(F&&([B,G]=N1(G,X1[F])),K!==void 0){if(X)throw RangeError(_1(K));D=((U)=>{let V=parseInt(U);if(!Number.isFinite(V))throw RangeError(_1(U));return V})(K),z=1,O&&(G=g2(O)*(X1[F]/n0),X=1)}return B+D}let z=0,X=0,G=0,Q={...KZ(v,[Y(j[2]),Y(j[3]),Y(j[4]),Y(j[5]),Y(j[6],j[7],5),Y(j[8],j[9],4),Y(j[10],j[11],3)]),...L6(G,2,v)};if(!z)throw RangeError(lY(v));return m2(j[1])<0&&(Q=A0(Q)),Q})(W):void 0})(t($));if(!Z)throw RangeError(k0($));return s(BZ(Z))}function Lj($){let Z=r1($)||y2($)||q2($);return Z?Z.calendar:$}function Pj($){let Z=r1($);return Z&&(Z.timeZone||Z.m&&R$||Z.offset)||$}function Nj($,Z,J=0,W=0){let j=u6($.timeZone),Y=X4(j);return H0(_$(Y,S6($),Z,J,W,!Y.v,$.m),j,Q3($.calendar))}function _j($){return xj(x1(S6($)))}function Cj($){return xj(u1(L$($)))}function xj($){return{...$,calendar:Q3($.calendar)}}function r1($){let Z=GO.exec($);return Z?((J)=>{let W=J[10],j=(W||"").toUpperCase()==="Z";return{isoYear:Sj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...Aj(J.slice(5)),...d6(J[16]),p:Boolean(J[6]),m:j,offset:j?void 0:W}})(Z):void 0}function y2($){let Z=zO.exec($);return Z?((J)=>({isoYear:Sj(J),isoMonth:parseInt(J[4]),isoDay:1,...d6(J[5])}))(Z):void 0}function q2($){let Z=XO.exec($);return Z?((J)=>({isoYear:QZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...d6(J[3])}))(Z):void 0}function v2($,Z){let J=KO.exec($);return J?((W,j)=>{let Y=W[4]||W[5];if(j&&Y)throw RangeError(_1(Y));return L2((jZ(W[2])*$4+jZ(W[3])*e6+jZ(W[4])*n0+g2(W[5]||""))*m2(W[1]))})(J,Z):void 0}function Sj($){let Z=m2($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(_1(-0));return Z*J}function Aj($){let Z=jZ($[3]);return{...C6(g2($[4]||""))[0],isoHour:jZ($[1]),isoMinute:jZ($[2]),isoSecond:Z===60?59:Z}}function d6($){let Z,J,W=[];if($.replace(FO,(j,Y,z)=>{let X=Boolean(Y),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")W.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(_1(j))}else{if(J)throw RangeError(_1(j));J=G}return""}),W.length>1&&Z)throw RangeError(_1($));return{timeZone:J,calendar:W[0]||w}}function g2($){return parseInt($.padEnd(9,"0"))}function TZ($){return new RegExp(`^${$}$`,"i")}function m2($){return $&&$!=="+"?-1:1}function jZ($){return $===void 0?0:parseInt($)}function fj($){return u6(t($))}function u6($){let Z=p2($);return typeof Z=="number"?N$(Z):Z?((J)=>{if(BO.test(J))throw RangeError(HF);return J.toLowerCase().split("/").map((W,j)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(Y,z)=>Y.length<=2&&!j||Y==="in"||Y==="chat"?Y.toUpperCase():Y.length>2||!z?i9(Y).replace(/island|noronha|murdo|rivadavia|urville/,i9):Y)).join("/")})($):R$}function t9($){let Z=p2($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:R$}function p2($){let Z=v2($=$.toUpperCase(),1);return Z!==void 0?Z:$!==R$?DO($):void 0}function h2($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function c2($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function Ej($,Z,J,W,j,Y){let z=$(t0(Y).relativeTo),X=Math.max(H$(W),H$(j));if(KW(v,W,j))return 0;if($3(X,z))return C0(D0(W),D0(j));if(!z)throw RangeError(t6);let[G,Q,K]=v6(Z,J,z),O=b2(K),F=g6(K);return C0(O(F(Q,G,W)),O(F(Q,G,j)))}function d2($,Z){return x$($,Z)||l6($,Z)}function x$($,Z){return d1(x0($),x0(Z))}function l6($,Z){return d1(s1($),s1(Z))}function bj($,Z){return!h2($,Z)}function Rj($,Z){return!c2($,Z)&&!!i6($.timeZone,Z.timeZone)&&DZ($.calendar,Z.calendar)}function wj($,Z){return!d2($,Z)&&DZ($.calendar,Z.calendar)}function kj($,Z){return!x$($,Z)&&DZ($.calendar,Z.calendar)}function yj($,Z){return!x$($,Z)&&DZ($.calendar,Z.calendar)}function qj($,Z){return!x$($,Z)&&DZ($.calendar,Z.calendar)}function vj($,Z){return!l6($,Z)}function i6($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return t9(J)===t9(W)}catch(j){}}function u2($,Z,J,W){let j=OZ($,z0(W),3,5),Y=s6(Z.epochNanoseconds,J.epochNanoseconds,...j);return s($?A0(Y):Y)}function l2($,Z,J,W,j,Y){let z=o6(W.calendar,j.calendar),X=z0(Y),[G,Q,K,O]=OZ(J,X,5),F=W.epochNanoseconds,B=j.epochNanoseconds,D=C0(B,F),U;if(D)if(G<6)U=s6(F,B,G,Q,K,O);else{let V=Z(((L,H)=>{if(!i6(L,H))throw RangeError(rY);return L})(W.timeZone,j.timeZone)),M=$(z);U=mj(M,V,W,j,D,G,X),U=R6(U,B,G,Q,K,O,M,W,cW,R(f2,V))}else U=M0;return s(J?A0(U):U)}function i2($,Z,J,W,j){let Y=o6(J.calendar,W.calendar),z=z0(j),[X,G,Q,K]=OZ(Z,z,6),O=_0(J),F=_0(W),B=C0(F,O),D;if(B)if(X<=6)D=s6(O,F,X,G,Q,K);else{let U=$(Y);D=pj(U,J,W,B,X,z),D=R6(D,F,X,G,Q,K,U,J,_0,E2)}else D=M0;return s(Z?A0(D):D)}function s2($,Z,J,W,j){let Y=o6(J.calendar,W.calendar),z=z0(j);return gj(Z,()=>$(Y),J,W,...OZ(Z,z,6,9,6),z)}function n2($,Z,J,W,j){let Y=o6(J.calendar,W.calendar),z=z0(j),X=OZ(Z,z,9,9,8),G=$(Y);return gj(Z,()=>G,eZ(G,J),eZ(G,W),...X,z)}function gj($,Z,J,W,j,Y,z,X,G){let Q=_0(J),K=_0(W),O;if(C0(K,Q))if(j===6)O=s6(Q,K,j,Y,z,X);else{let F=Z();O=F.dateUntil(J,W,j,G),Y===6&&z===1||(O=R6(O,K,j,Y,z,X,F,J,_0,q6))}else O=M0;return s($?A0(O):O)}function o2($,Z,J,W){let j=z0(W),[Y,z,X,G]=OZ($,j,5,5),Q=n1(a2(Z,J),G3(z,X),G),K={...M0,...h6(Q,Y)};return s($?A0(K):K)}function rK($,Z,J,W,j,Y){let z=C0(W.epochNanoseconds,J.epochNanoseconds);return z?j<6?hj(J.epochNanoseconds,W.epochNanoseconds,j):mj(Z,$,J,W,z,j,Y):M0}function tK($,Z,J,W,j){let Y=_0(Z),z=_0(J),X=C0(z,Y);return X?W<=6?hj(Y,z,W):pj($,Z,J,X,W,j):M0}function mj($,Z,J,W,j,Y,z){let[X,G,Q]=((F,B,D,U)=>{function V(){return x={...C$(H,f++*-U),...L},P=v0(F,x),C0(S,P)===-U}let M=S0(B,F),L=g0(Z1,M),H=S0(D,F),S=D.epochNanoseconds,f=0,E=a2(M,H),x,P;if(Math.sign(E)===-U&&f++,V()&&(U===-1||V()))throw RangeError(D3);let I=d0(c0(P,S));return[M,x,I]})(Z,J,W,j);var K,O;return{...Y===6?(K=X,O=G,{...M0,days:cj(K,O)}):$.dateUntil(X,G,Y,z),...h6(Q)}}function pj($,Z,J,W,j,Y){let[z,X,G]=((Q,K,O)=>{let F=K,B=a2(Q,K);return Math.sign(B)===-O&&(F=C$(K,-O),B+=c*O),[Q,F,B]})(Z,J,W);return{...$.dateUntil(z,X,j,Y),...h6(G)}}function s6($,Z,J,W,j,Y){return{...M0,...UZ(w6(c0($,Z),W,j,Y),J)}}function hj($,Z,J){return{...M0,...UZ(c0($,Z),J)}}function cj($,Z){return n6(x0($),x0(Z))}function n6($,Z){return Math.trunc((Z-$)/y0)}function a2($,Z){return s1(Z)-s1($)}function o6($,Z){if(!DZ($,Z))throw RangeError(F8);return $}function eK($){function Z(j){return((Y,z)=>({...dj(Y,z),F:Y.month,day:parseInt(Y.day)}))(aJ(J,j),W)}let J=x8($),W=V6($);return{id:$,O:$F(Z),B:ZF(Z)}}function $F($){return q0((Z)=>{let J=x0(Z);return $(J)},WeakMap)}function ZF($){let Z=$(0).year-hF;return q0((J)=>{let W,j=FZ(J-Z),Y=[],z=[];do j+=400*y0;while((W=$(j)).year<=J);do j+=(1-W.day)*y0,W.year===J&&(Y.push(j),z.push(W.F)),j-=y0;while((W=$(j)).year>=J);return{k:Y.reverse(),C:$z(z.reverse())}})}function dj($,Z){let J,W,j=uj($);if($.era){let Y=Qz[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"),W=j,j=oj(W,Y[J]||0))}return{era:J,eraYear:W,year:j}}function uj($){return parseInt($.relatedYear||$.year)}function kJ($){let{year:Z,F:J,day:W}=this.O($),{C:j}=this.B(Z);return[Z,j[J]+1,W]}function Z3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*y0}function Y6($){let Z=$W(this,$),J=$W(this,$-1),W=Z.length;if(W>J.length){let j=aj(this);if(j<0)return-j;for(let Y=0;Y<W;Y++)if(Z[Y]!==J[Y])return Y+1}}function z6($){return n6(Z3.call(this,$),Z3.call(this,$+1))}function e9($,Z){let{k:J}=this.B($),W=Z+1,j=J;return W>J.length&&(W=1,j=this.B($+1).k),n6(J[Z-1],j[W-1])}function X6($){return this.B($).k.length}function $W($,Z){return Object.keys($.B(Z).C)}function lj($){return Q3(t($))}function Q3($){if(($=$.toLowerCase())!==w&&$!==J4&&V6($)!==V6(x8($).resolvedOptions().calendar))throw RangeError(MF($));return $}function V6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function ij($){return this.R($)[0]}function sj($){return this.R($)[1]}function r2($){let[Z]=this.h($);return n6(this.q(Z),x0($))+1}function nj($){let Z=VO.exec($);if(!Z)throw RangeError(VF($));return[parseInt(Z[1]),Boolean(Z[2])]}function T6($,Z,J){return $+(Z||J&&$>=J?1:0)}function yJ($,Z){return $-(Z&&$>=Z?1:0)}function oj($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function qJ($){return Qz[rj($)]}function aj($){return RF[rj($)]}function rj($){return V6($.id||w)}function tj($,Z,J,W){let j=t1(J,W,$1,[],Yz);if(j.timeZone!==void 0){let Y=J.dateFromFields(j),z=S$(j),X=$(j.timeZone);return{epochNanoseconds:_$(Z(X),{...Y,...z},j.offset!==void 0?VZ(j.offset):void 0),timeZone:X}}return{...J.dateFromFields(j),...o0}}function ej($,Z,J,W,j,Y){let z=t1(J,j,$1,Wz,Yz),X=$(z.timeZone),[G,Q,K]=X3(Y),O=J.dateFromFields(z,E6(Y,G)),F=S$(z,G);return H0(_$(Z(X),{...O,...F},z.offset!==void 0?VZ(z.offset):void 0,Q,K),X,W)}function $Y($,Z,J){let W=t1($,Z,$1,[],f1),j=q(J);return X0(x1({...$.dateFromFields(W,E6(J,j)),...S$(W,j)}))}function t2($,Z,J,W=[]){let j=t1($,Z,$1,W);return $.dateFromFields(j,J)}function e2($,Z,J,W){let j=t1($,Z,B8,W);return $.yearMonthFromFields(j,J)}function $8($,Z,J,W,j=[]){let Y=t1($,J,$1,j);return Z&&Y.month!==void 0&&Y.monthCode===void 0&&Y.year===void 0&&(Y.year=QZ),$.monthDayFromFields(Y,W)}function ZY($,Z){let J=q(Z);return e0(S$(z1($,gJ,[],1),J))}function JY($){let Z=z1($,U8);return s(BZ({...M0,...Z}))}function t1($,Z,J,W=[],j=[]){return z1(Z,[...$.fields(J),...j].sort(),W)}function z1($,Z,J,W=!J){let j={},Y,z=0;for(let X of Z){if(X===Y)throw RangeError(KF(X));if(X==="constructor"||X==="__proto__")throw RangeError(Q8(X));let G=$[X];if(G!==void 0)z=1,jW[X]&&(G=jW[X](G,X)),j[X]=G;else if(J){if(J.includes(X))throw TypeError(G8(X));j[X]=Gz[X]}Y=X}if(W&&!z)throw TypeError(lY(Z));return j}function S$($,Z){return A6(IO({...Gz,...$}),Z)}function WY($,Z,J,W,j,Y){let z=z0(Y),{calendar:X,timeZone:G}=J;return H0(((Q,K,O,F,B)=>{let D=K3(Q,O,F,$1,jz,Jz),[U,V,M]=X3(B,2);return _$(K,{...Q.dateFromFields(D,E6(B,U)),...S$(D,U)},VZ(D.offset),V,M)})($(X),Z(G),W,j,z),G,X)}function jY($,Z,J,W,j){let Y=z0(j);return X0(((z,X,G,Q)=>{let K=K3(z,X,G,$1,f1),O=q(Q);return x1({...z.dateFromFields(K,E6(Q,O)),...S$(K,O)})})($(Z.calendar),J,W,Y))}function YY($,Z,J,W,j){let Y=z0(j);return((z,X,G,Q)=>{let K=K3(z,X,G,$1);return z.dateFromFields(K,Q)})($(Z.calendar),J,W,Y)}function zY($,Z,J,W,j){let Y=z0(j);return M$(((z,X,G,Q)=>{let K=K3(z,X,G,B8);return z.yearMonthFromFields(K,Q)})($(Z.calendar),J,W,Y))}function XY($,Z,J,W,j){let Y=z0(j);return((z,X,G,Q)=>{let K=K3(z,X,G,$1);return z.monthDayFromFields(K,Q)})($(Z.calendar),J,W,Y)}function GY($,Z,J){return e0(((W,j,Y)=>{let z=q(Y);return S$({...g0(gJ,W),...z1(j,gJ)},z)})($,Z,J))}function QY($,Z){return s((J=$,W=Z,BZ({...J,...z1(W,U8)})));var J,W}function K3($,Z,J,W,j=[],Y=[]){let z=[...$.fields(W),...j].sort(),X=z1(Z,z,Y),G=z1(J,z);return X=$.mergeFields(X,G),z1(X,z,[])}function Z8($,Z){let J=t1($,Z,Xz);return $.monthDayFromFields(J)}function J8($,Z,J){let W=t1($,Z,zz);return $.yearMonthFromFields(W,J)}function KY($,Z,J,W,j){Z=g0(J=$.fields(J),Z),W=z1(W,j=$.fields(j),[]);let Y=$.mergeFields(Z,W);return Y=z1(Y,[...J,...j].sort(),[]),$.dateFromFields(Y)}function fJ($,Z){let{era:J,eraYear:W,year:j}=Z,Y=qJ($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(OF);if(!Y)throw RangeError(FF);let z=Y[J];if(z===void 0)throw RangeError(BF(J));let X=oj(W,z);if(j!==void 0&&j!==X)throw RangeError(DF);j=X}else if(j===void 0)throw TypeError(UF(Y));return j}function EJ($,Z,J,W){let{month:j,monthCode:Y}=Z;if(Y!==void 0){let z=((X,G,Q,K)=>{let O=X.U(Q),[F,B]=nj(G),D=T6(F,B,O);if(B){let U=aj(X);if(U===void 0)throw RangeError(aZ);if(U>0){if(D>U)throw RangeError(aZ);if(O===void 0){if(K===1)throw RangeError(aZ);D--}}else{if(D!==-U)throw RangeError(aZ);if(O===void 0&&K===1)throw RangeError(aZ)}}return D})($,Y,J,W);if(j!==void 0&&j!==z)throw RangeError(oY);j=z,W=1}else if(j===void 0)throw TypeError(TF);return i0("month",j,1,$.L(J),W)}function ZW($,Z,J,W,j){return w0(Z,"day",1,$.j(W,J),j)}function bJ($,Z,J,W){let j=0,Y=[];for(let z of J)Z[z]!==void 0?j=1:Y.push(z);if(Object.assign($,Z),j)for(let z of W||Y)delete $[z]}function FY($){return U0(u0(_6(N6($))))}function OY($,Z,J,W,j=w){return H0(u0(_6(N6(J))),Z(W),$(j))}function DY($,Z,J,W,j=0,Y=0,z=0,X=0,G=0,Q=0,K=w){return X0(x1(S6(a0(N0,KZ(W4,[Z,J,W,j,Y,z,X,G,Q])))),$(K))}function BY($,Z,J,W,j=w){return G0(u1(L$(a0(N0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(j))}function UY($,Z,J,W=w,j=1){let Y=N0(Z),z=N0(J),X=$(W);return M$(rJ(L$({isoYear:Y,isoMonth:z,isoDay:N0(j)})),X)}function VY($,Z,J,W=w,j=QZ){let Y=N0(Z),z=N0(J),X=$(W);return D6(u1(L$({isoYear:N0(j),isoMonth:Y,isoDay:z})),X)}function TY($=0,Z=0,J=0,W=0,j=0,Y=0){return e0(A6(a0(N0,KZ(Z1,[$,Z,J,W,j,Y])),1))}function MY($=0,Z=0,J=0,W=0,j=0,Y=0,z=0,X=0,G=0,Q=0){return s(BZ(a0(PW,KZ(v,[$,Z,J,W,j,Y,z,X,G,Q]))))}function W8($,Z,J=w){return H0($.epochNanoseconds,Z,J)}function HY($){return U0($.epochNanoseconds)}function j8($,Z){return X0(S0(Z,$))}function Y8($,Z){return G0(S0(Z,$))}function IY($,Z,J){return J8($(Z.calendar),J)}function LY($,Z,J){return Z8($(Z.calendar),J)}function z8($,Z){return e0(S0(Z,$))}function PY($,Z,J,W){let j=((Y,z,X,G)=>{let Q=Z2(G);return v0(Y(z),X,Q)})($,J,Z,W);return H0(u0(j),J,Z.calendar)}function NY($,Z,J){let W=$(Z.calendar);return M$({...Z,...J8(W,J)})}function _Y($,Z,J){return Z8($(Z.calendar),J)}function CY($,Z,J,W,j){let Y=$(j.timeZone),z=j.plainTime,X=z!==void 0?Z(z):o0;return H0(v0(J(Y),{...W,...X}),Y,W.calendar)}function xY($,Z=o0){return X0(x1({...$,...Z}))}function SY($,Z,J){return J8($(Z.calendar),J)}function AY($,Z,J){return Z8($(Z.calendar),J)}function fY($,Z,J,W){return((j,Y,z)=>KY(j,Y,zz,C1(z),U3))($(Z.calendar),J,W)}function EY($,Z,J,W){return((j,Y,z)=>KY(j,Y,Xz,C1(z),Z4))($(Z.calendar),J,W)}function bY($,Z,J,W,j){let Y=C1(j),z=Z(Y.plainDate),X=$(Y.timeZone);return H0(v0(J(X),{...z,...W}),X,z.calendar)}function RY($,Z){return X0(x1({...$,...Z}))}function wY($){return U0(u0(XZ($,n0)))}function kY($){return U0(u0(XZ($,G1)))}function yY($){return U0(u0(_6(N6($),f$)))}function qY($){return U0(u0(_6(N6($))))}function vY($,Z,J=o0){let W=Z.timeZone,j=$(W),Y={...S0(Z,j),...J};return H0(_$(j,Y,Y.offsetNanoseconds,2),W,Z.calendar)}function gY($,Z,J){let W=Z.timeZone,j=$(W),Y={...S0(Z,j),...J},z=cY(Z.calendar,J.calendar);return H0(_$(j,Y,Y.offsetNanoseconds,2),W,z)}function mY($,Z=o0){return X0({...$,...Z})}function pY($,Z){return X0({...$,...Z},cY($.calendar,Z.calendar))}function a6($,Z){return{...$,calendar:Z}}function hY($,Z){return{...$,timeZone:Z}}function cY($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===w)return Z;if(W===w)return $;throw RangeError(F8)}function JF($,Z){return(J)=>J===w?$:J===J4||J===GZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),UO(J))}function A$($,Z,J){let W=new Set(J);return(j)=>(((Y,z)=>{for(let X of z)if(X in Y)return 1;return 0})(j=cJ(W,j),$)||Object.assign(j,Z),J&&(j.timeZone=R$,["full","long"].includes(j.timeStyle)&&(j.timeStyle="medium")),j)}function S1($,Z=X8){let[J,,,W]=$;return(j,Y=qO,...z)=>{let X=Z(W&&W(...z),j,Y,J),G=X.resolvedOptions();return[X,...WF($,G,z)]}}function X8($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(fF);J.timeZone=$}return new e1(Z,J)}function WF($,Z,J){let[,W,j]=$;return J.map((Y)=>(Y.calendar&&((z,X,G)=>{if((G||z!==w)&&z!==X)throw RangeError(F8)})(T0(Y.calendar),Z.calendar,j),W(Y,Z)))}function MZ($){let Z=F3();return o1(Z,$.getOffsetNanosecondsFor(Z))}function F3(){return XZ(Date.now(),G1)}function A1(){return zW||(zW=new e1().resolvedOptions().timeZone)}var jF=($,Z)=>`Non-integer ${$}: ${Z}`,YF=($,Z)=>`Non-positive ${$}: ${Z}`,zF=($,Z)=>`Non-finite ${$}: ${Z}`,XF=($)=>`Cannot convert bigint to ${$}`,GF=($)=>`Invalid bigint: ${$}`,QF="Cannot convert Symbol to string",dY="Invalid object",uY=($,Z,J,W,j)=>j?uY($,j[Z],j[J],j[W]):O3($,Z)+`; must be between ${J}-${W}`,O3=($,Z)=>`Invalid ${$}: ${Z}`,G8=($)=>`Missing ${$}`,Q8=($)=>`Invalid field ${$}`,KF=($)=>`Duplicate field ${$}`,lY=($)=>"No valid fields: "+$.join(),iY="Invalid bag",sY=($,Z,J)=>O3($,Z)+"; must be "+Object.keys(J).join(),nY="Cannot use valueOf",K8="Invalid calling context",FF="Forbidden era/eraYear",OF="Mismatching era/eraYear",DF="Mismatching year/eraYear",BF=($)=>`Invalid era: ${$}`,UF=($)=>"Missing year"+($?"/era/eraYear":""),VF=($)=>`Invalid monthCode: ${$}`,oY="Mismatching month/monthCode",TF="Missing month/monthCode",JW="Cannot guess year",aZ="Invalid leap month",aY="Invalid protocol",D3="Invalid protocol results",F8="Mismatching Calendars",MF=($)=>`Invalid Calendar: ${$}`,rY="Mismatching TimeZones",HF="Forbidden ICU TimeZone",IF="Out-of-bounds offset",LF="Out-of-bounds TimeZone gap",PF="Invalid TimeZone offset",NF="Ambiguous offset",r6="Out-of-bounds date",_F="Out-of-bounds duration",CF="Cannot mix duration signs",t6="Missing relativeTo",xF="Cannot use large units",SF="Required smallestUnit or largestUnit",AF="smallestUnit > largestUnit",k0=($)=>`Cannot parse: ${$}`,_1=($)=>`Invalid substring: ${$}`,tY=($)=>`Cannot format ${$}`,eY="Mismatching types for formatting",fF="Cannot specify TimeZone",$z=R(j3,($,Z)=>Z),HZ=R(j3,($,Z,J)=>J),s0=R(K6,2),vJ={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},B3=Object.keys(vJ),y0=86400000,Zz=1000,f$=1000,G1=1e6,n0=1e9,e6=60000000000,$4=3600000000000,c=86400000000000,X1=[1,f$,G1,n0,e6,$4,c],f1=B3.slice(0,6),gJ=Y3(f1),Jz=["offset"],Wz=["timeZone"],jz=f1.concat(Jz),Yz=jz.concat(Wz),mJ=["era","eraYear"],EF=mJ.concat(["year"]),Z4=["year"],O8=["monthCode"],D8=["month"].concat(O8),U3=["day"],B8=D8.concat(Z4),zz=O8.concat(Z4),$1=U3.concat(B8),bF=U3.concat(D8),Xz=U3.concat(O8),Gz=HZ(f1,0),w="iso8601",J4="gregory",GZ="japanese",Qz={[J4]:{bce:-1,ce:0},[GZ]:{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}},RF={chinese:13,dangi:13,hebrew:-6},t=R(P6,"string"),Kz=R(P6,"boolean"),wF=R(P6,"number"),Fz=R(P6,"function"),v=B3.map(($)=>$+"s"),U8=Y3(v),kF=v.slice(0,6),Oz=v.slice(6),yF=Oz.slice(1),qF=$z(v),M0=HZ(v,0),V8=HZ(kF,0),T8=R(FW,v),Z1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],M8=["isoDay","isoMonth","isoYear"],W4=Z1.concat(M8),H8=Y3(M8),Dz=Y3(Z1),Bz=Y3(W4),o0=HZ(Dz,0),vF=R(FW,W4),e1=Intl.DateTimeFormat,Uz="en-GB",I8=1e8,gF=I8*y0,mF=[I8,0],pF=[-I8,0],J3=275760,W3=-271821,hF=1970,QZ=1972,P1=12,cF=FZ(1868,9,8),dF=q0(dK,WeakMap),M6="smallestUnit",pJ="unit",tZ="roundingIncrement",RJ="fractionalSecondDigits",Vz="relativeTo",Tz={constrain:0,reject:1},uF=Object.keys(Tz),lF={compatible:0,reject:1,earlier:2,later:3},iF={reject:0,use:1,prefer:2,ignore:3},sF={auto:0,never:1,critical:2,always:3},nF={auto:0,never:1,critical:2},oF={auto:0,never:1},aF={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},V3=R(X2,M6),L8=R(X2,"largestUnit"),rF=R(X2,pJ),Mz=R(P$,"overflow",Tz),Hz=R(P$,"disambiguation",lF),tF=R(P$,"offset",iF),P8=R(P$,"calendarName",sF),eF=R(P$,"timeZoneName",nF),$O=R(P$,"offset",oF),T3=R(P$,"roundingMode",aF),IZ="PlainYearMonth",LZ="PlainMonthDay",E$="PlainDate",b$="PlainDateTime",j4="PlainTime",E1="ZonedDateTime",Y4="Instant",z4="Duration",ZO=[Math.floor,($)=>j6($)?Math.floor($):Math.round($),Math.ceil,($)=>j6($)?Math.ceil($):Math.round($),Math.trunc,($)=>j6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>j6($)?($=Math.trunc($)||0)+$%2:Math.round($)],R$="UTC",G6=5184000,JO=O6(1847),WO=O6(new Date().getUTCFullYear()+10),jO=/0+$/,S0=q0(oK,WeakMap),WW=4294967295,X4=q0(($)=>{let Z=p2($);return typeof Z=="object"?new Lz(Z):new Iz(Z||0)});class Iz{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[tJ($,this.v)]}l(){}}class Lz{constructor($){this.$=((Z)=>{function J(G){let Q=wJ(G,z,X),[K,O]=r9(Q),F=j(K),B=j(O);return F===B?F:W(Y(K,O),F,B,G)}function W(G,Q,K,O){let F,B;for(;(O===void 0||(F=O<G[0]?Q:O>=G[1]?K:void 0)===void 0)&&(B=G[1]-G[0]);){let D=G[0]+Math.floor(B/2);Z(D)===K?G[1]=D:G[0]=D+1}return F}let j=q0(Z),Y=q0(aK),z=JO,X=WO;return{G(G){let Q=J(G-86400),K=J(G+86400),O=G-Q,F=G-K;if(Q===K)return[O];let B=J(O);return B===J(F)?[G-B]:Q>K?[O,F]:[]},V:J,l(G,Q){let K=wJ(G,z,X),[O,F]=r9(K),B=G6*Q,D=Q<0?()=>F>z||(z=K,0):()=>O<X||(X=K,0);for(;D();){let U=j(O),V=j(F);if(U!==V){let M=Y(O,F);W(M,U,V);let L=M[0];if((d1(L,G)||1)===Q)return L}O+=B,F+=B}}}})(((Z)=>(J)=>{let W=aJ(Z,J*Zz);return O6(uj(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(CW($))*n0}getPossibleInstantsFor($){let[Z,J]=[O6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*G1+W.isoMicrosecond*f$+W.isoNanosecond];var W;return this.$.G(Z).map((j)=>u0(zZ(XZ(j,n0),J)))}l($,Z){let[J,W]=xW($),j=this.$.l(J+(Z>0||W?1:0),Z);if(j!==void 0)return XZ(j,n0)}}var N8="([+\u2212-])",Q6="(?:[.,](\\d{1,9}))?",Pz=`(?:(?:${N8}(\\d{6}))|(\\d{4}))-?(\\d{2})`,_8="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+Q6+")?)?",C8=N8+_8,YO=Pz+"-?(\\d{2})(?:[T ]"+_8+"(Z|"+C8+")?)?",Nz="\\[(!?)([^\\]]*)\\]",G4=`((?:${Nz}){0,9})`,zO=TZ(Pz+G4),XO=TZ("(?:--)?(\\d{2})-?(\\d{2})"+G4),GO=TZ(YO+G4),QO=TZ("T?"+_8+"(?:"+C8+")?"+G4),KO=TZ(C8),FO=new RegExp(Nz,"g"),OO=TZ(`${N8}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${Q6}H)?(?:(\\d+)${Q6}M)?(?:(\\d+)${Q6}S)?)?`),DO=q0(($)=>new e1(Uz,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),BO=/^(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$/,UO=q0(eK),x8=q0(($)=>new e1(Uz,{calendar:$,timeZone:R$,era:"short",year:"numeric",month:"short",day:"numeric"})),VO=/^M(\d{2})(L?)$/,TO={era:F6,eraYear:N0,year:N0,month:s9,monthCode:F6,day:s9},MO=HZ(f1,N0),HO=HZ(v,PW),jW=Object.assign({},TO,MO,HO,{offset:F6}),IO=R(cK,f1,Z1),YW={dateAdd($,Z,J){let W=q(J),j,{years:Y,months:z,weeks:X,days:G}=Z;if(G+=D0(Z,5)[0],Y||z)j=((Q,K,O,F,B)=>{let[D,U,V]=Q.h(K);if(O){let[M,L]=Q.I(D,U);D+=O,U=T6(M,L,Q.U(D)),U=i0("month",U,1,Q.L(D),B)}return F&&([D,U]=Q._(D,U,F)),V=i0("day",V,1,Q.j(D,U),B),Q.q(D,U,V)})(this,$,Y,z,W);else{if(!X&&!G)return $;j=x0($)}return j+=(7*X+G)*y0,u1(x6(j))},dateUntil($,Z,J){if(J<=7){let G=0,Q=cj({...$,...o0},{...Z,...o0});return J===7&&([G,Q]=i1(Q,7)),{...M0,weeks:G,days:Q}}let W=this.h($),j=this.h(Z),[Y,z,X]=((G,Q,K,O,F,B,D)=>{let U=F-Q,V=B-K,M=D-O;if(U||V){let L=Math.sign(U||V),H=G.j(F,B),S=0;if(Math.sign(M)===-L){let f=H;[F,B]=G._(F,B,-L),U=F-Q,V=B-K,H=G.j(F,B),S=L<0?-f:H}if(M=D-Math.min(O,H)+S,U){let[f,E]=G.I(Q,K),[x,P]=G.I(F,B);if(V=x-f||Number(P)-Number(E),Math.sign(V)===-L){let I=L<0&&-G.L(F);U=(F-=L)-Q,V=B-T6(f,E,G.U(F))+(I||G.L(F))}}}return[U,V,M]})(this,...W,...j);return J===8&&(z+=this.J(Y,W[0]),Y=0),{...M0,years:Y,months:z,days:X}},dateFromFields($,Z){let J=q(Z),W=fJ(this,$),j=EJ(this,$,W,J),Y=ZW(this,$,j,W,J);return G0(u1(this.P(W,j,Y)),this.id||w)},yearMonthFromFields($,Z){let J=q(Z),W=fJ(this,$),j=EJ(this,$,W,J);return M$(rJ(this.P(W,j,1)),this.id||w)},monthDayFromFields($,Z){let J=q(Z),W=!this.id,{monthCode:j,year:Y,month:z}=$,X,G,Q,K,O;if(j!==void 0){[X,G]=nj(j),O=XW($,"day");let F=this.N(X,G,O);if(!F)throw RangeError(JW);if([Q,K]=F,z!==void 0&&z!==K)throw RangeError(oY);W&&(K=i0("month",K,1,P1,1),O=i0("day",O,1,eJ(Y!==void 0?Y:Q,K),J))}else{Q=Y===void 0&&W?QZ:fJ(this,$),K=EJ(this,$,Q,J),O=ZW(this,$,K,Q,J);let F=this.U(Q);G=K===F,X=yJ(K,F);let B=this.N(X,G,O);if(!B)throw RangeError(JW);[Q,K]=B}return D6(u1(this.P(Q,K,O)),this.id||w)},fields($){return qJ(this)&&$.includes("year")?[...$,...mJ]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return bJ(J,Z,D8),qJ(this)&&(bJ(J,Z,EF),this.id===GZ&&bJ(J,Z,bF,mJ)),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:r2,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,j]=this.I(Z,J);return((Y,z)=>"M"+s0(Y)+(z?"L":""))(W,j)},dayOfWeek:bW,daysInWeek(){return 7}},LO={dayOfYear:r2,h:AW,q:FZ},PO=Object.assign({},LO,{weekOfYear:ij,yearOfWeek:sj,R($){function Z(B){return(7-B<W?7:0)-B}function J(B){let D=EW(F+B),U=B||1,V=Z(rZ(G+D*U,7));return K=(D+(V-Q)*U)/7}let W=this.id?1:4,j=bW($),Y=this.dayOfYear($),z=rZ(j-1,7),X=Y-1,G=rZ(z-X,7),Q=Z(G),K,O=Math.floor((X-Q)/7)+1,F=$.isoYear;return O?O>J(0)&&(O=1,F++):(O=J(-1),F--),[O,F,K]}}),NO={dayOfYear:r2,h:kJ,q:Z3,weekOfYear:ij,yearOfWeek:sj,R(){return[]}},PZ=JF(Object.assign({},YW,PO,{h:AW,ee($){return this.id===J4?RW($):this.id===GZ?dF($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[QZ,$]},K:$2,U(){},L:fW,J:($)=>$*P1,j:eJ,X:EW,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:FZ,_:($,Z,J)=>($+=I6(J,P1),(Z+=uJ(J,P1))<1?($--,Z+=P1):Z>P1&&($++,Z-=P1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},YW,NO,{h:kJ,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=Y6.call(this,$);return[yJ(Z,J),J===Z]},N($,Z,J){let[W,j,Y]=kJ.call(this,{isoYear:QZ,isoMonth:P1,isoDay:31}),z=Y6.call(this,W),X=j===z;(d1($,yJ(j,z))||d1(Number(Z),Number(X))||d1(J,Y))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,K=Y6.call(this,Q),O=T6($,Z,K);if(Z===(O===K)&&J<=e9.call(this,Q,O))return[Q,O]}},K($){let Z=z6.call(this,$);return Z>z6.call(this,$-1)&&Z>z6.call(this,$+1)},U:Y6,L:X6,J($,Z){let J=Z+$,W=Math.sign($),j=W<0?-1:0,Y=0;for(let z=Z;z!==J;z+=W)Y+=X6.call(this,z+j);return Y},j:e9,X:z6,P($,Z,J){return x6(Z3.call(this,$,Z,J))},q:Z3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(r6);if(J<0)for(;Z<1;)Z+=X6.call(this,--$);else{let W;for(;Z>(W=X6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),l1="numeric",NZ=["timeZoneName"],_z={month:l1,day:l1},S8={year:l1,month:l1},A8=Object.assign({},S8,{day:l1}),f8={hour:l1,minute:l1,second:l1},E8=Object.assign({},A8,f8),_O=Object.assign({},E8,{timeZoneName:"short"}),CO=Object.keys(S8),xO=Object.keys(_z),SO=Object.keys(A8),AO=Object.keys(f8),b8=["dateStyle"],fO=CO.concat(b8),EO=xO.concat(b8),R8=SO.concat(b8,["weekday"]),M3=AO.concat(["dayPeriod","timeStyle"]),w8=R8.concat(M3),bO=w8.concat(NZ),RO=NZ.concat(M3),wO=NZ.concat(R8),kO=NZ.concat(["day","weekday"],M3),yO=NZ.concat(["year","weekday"],M3),qO={},k8=[A$(w8,E8),b6],Cz=[A$(bO,_O),b6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(rY);return J}],y8=[A$(w8,E8,NZ),x0],q8=[A$(R8,A8,RO),x0],v8=[A$(M3,f8,wO),($)=>s1($)/G1],g8=[A$(fO,S8,kO),x0,1],m8=[A$(EO,_z,yO),x0,1],zW;function F1($,Z,J,W,j){function Y(...G){if(!(this instanceof Y))throw TypeError(K8);fz(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...K){return G.call(this,X(this),...K)},hJ(Q))}function X(G){let Q=P0(G);if(!Q||Q.branding!==$)throw TypeError(K8);return Q}return Object.defineProperties(Y.prototype,{...GW(a0(z,J)),...I$(a0(z,W)),...H6("Temporal."+$)}),Object.defineProperties(Y,{...I$(j),...hJ($)}),[Y,(G)=>{let Q=Object.create(Y.prototype);return fz(Q,G),Q},X]}function Rz($){return $=$.concat("id").sort(),(Z)=>{if(!QW(Z,$))throw TypeError(aY);return Z}}function SZ($){if(P0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(iY);return $}function Q4($,Z){let J={};for(let W in $)J[W]=({o:j},Y)=>{let z=P0(Y)||{},{branding:X}=z,G=X===E$||Z.includes(X)?z:E0(Y);return j[W](G)};return J}function c8($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:j}=W;return(Y=j,typeof Y=="string"?PZ(Y):(z=Y,Object.assign(Object.create(tO),{i:z})))[J](W);var Y,z};return Z}function j$(){throw TypeError(nY)}function I3({calendar:$}){return typeof $=="string"?new r8($):$}function xz($,Z){if(Z=z0(Z),B0($)){let W=P0($);if(W&&W.branding===LZ)return q(Z),W;let j=yz($);return $8(V4(j||w),!j,$,Z)}let J=Mj(PZ,$);return q(Z),J}function wz($,Z,J){return W=Z.call($,f0(U0(J))),L2(z3(W));var W}function K4($,Z=mz){let J=Object.keys(Z).sort(),W={};for(let j of J)W[j]=R(Z[j],$,Fz($[j]));return W}function d($,Z){return typeof $=="string"?X4($):K4($,Z)}function K0($){return d($,h8)}function Q1($){if(B0($)){let Z=P0($);if(Z)switch(Z.branding){case Y4:return Z;case E1:return U0(Z.epochNanoseconds)}}return Dj($)}function Sz($,Z,J){let W=Z.l(Q1(J).epochNanoseconds,$);return W?f0(U0(W)):null}function l($){return B0($)?(P0($)||{}).timeZone||jD($):((Z)=>u6(Pj(t(Z))))($)}function $$($,Z){if(B0($)){let J=P0($)||{};switch(J.branding){case j4:return q(Z),J;case b$:return q(Z),e0(J);case E1:return q(Z),z8(K0,J)}return ZY($,Z)}return q(Z),Hj($)}function d8($){return $===void 0?void 0:$$($)}function _Z($,Z){if(Z=z0(Z),B0($)){let W=P0($);return W&&W.branding===IZ?(q(Z),W):e2(B4(L3($)),$,Z)}let J=Tj(PZ,$);return q(Z),J}function Z$($,Z){if(Z=z0(Z),B0($)){let W=P0($)||{};switch(W.branding){case b$:return q(Z),W;case E$:return q(Z),X0({...W,...o0});case E1:return q(Z),j8(K0,W)}return $Y(U4(L3($)),$,Z)}let J=Vj($);return q(Z),J}function E0($,Z){if(Z=z0(Z),B0($)){let W=P0($)||{};switch(W.branding){case E$:return q(Z),W;case b$:return q(Z),G0(W);case E1:return q(Z),Y8(K0,W)}return t2(U4(L3($)),$,Z)}let J=c6($);return q(Z),J}function kz($,Z,J){return r0(Z.call($,$0(G0(J,$))))}function O1($){return(Z)=>typeof Z=="string"?PZ(Z):((J,W)=>{let j=Object.keys(W).sort(),Y={};for(let z of j)Y[z]=R(W[z],J,J[z]);return Y})(Z,$)}function e($){if(B0($)){let Z=P0($);return Z&&Z.branding===z4?Z:JY($)}return Ij($)}function H3($){if($!==void 0){if(B0($)){let Z=P0($)||{};switch(Z.branding){case E1:case E$:return Z;case b$:return G0(Z)}let J=L3($);return{...tj(l,d,U4(J),$),calendar:J}}return Bj($)}}function L3($){return yz($)||w}function yz($){let{calendar:Z}=$;if(Z!==void 0)return L0(Z)}function L0($){return B0($)?(P0($)||{}).calendar||HD($):((Z)=>Q3(Lj(t(Z))))($)}function CZ($,Z){if(Z=z0(Z),B0($)){let J=P0($);if(J&&J.branding===E1)return X3(Z),J;let W=L3($);return ej(l,d,U4(W),W,$,Z)}return Uj($,Z)}function Az($){return a0((Z)=>(J)=>Z(p8(J)),$)}function p8($){return S0($,K0)}function vO(){let $=e1.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(e1),W=function(j,Y={}){if(!(this instanceof W))return new W(j,Y);t8.set(this,((z,X={})=>{let G=new e1(z,X),Q=G.resolvedOptions(),K=Q.locale,O=g0(Object.keys(X),Q),F=q0(pO),B=(...D)=>{let U,V=D.map((M,L)=>{let H=P0(M),S=(H||{}).branding;if(L&&U&&U!==S)throw TypeError(eY);return U=S,H});return U?F(U)(K,O,...V):[G,...D]};return B.u=G,B})(j,Y))};for(let j in Z){let Y=Z[j],z=j.startsWith("format")&&gO(j);typeof Y.value=="function"?Y.value=j==="constructor"?W:z||mO(j):z&&(Y.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function gO($){return function(...Z){let J=t8.get(this),[W,...j]=J(...Z);return W[$](...j)}}function mO($){return function(...Z){return t8.get(this).u[$](...Z)}}function pO($){let Z=hO[$];if(!Z)throw TypeError(tY($));return S1(Z,q0(X8))}var hO={Instant:k8,PlainDateTime:y8,PlainDate:q8,PlainTime:v8,PlainYearMonth:g8,PlainMonthDay:m8},cO=S1(k8),dO=S1(Cz),uO=S1(y8),lO=S1(q8),iO=S1(v8),sO=S1(g8),nO=S1(m8),u8={era:VW,eraYear:lJ,year:z3,month:r0,daysInMonth:r0,daysInYear:r0,inLeapYear:Kz,monthsInYear:r0},O4={monthCode:t},l8={day:r0},qz={dayOfWeek:r0,dayOfYear:r0,weekOfYear:TW,yearOfWeek:lJ,daysInWeek:r0},vz=Object.assign({},u8,O4,l8,qz),F4=new WeakMap,P0=F4.get.bind(F4),fz=F4.set.bind(F4),oO={...Q4(u8,[IZ]),...Q4(qz,[]),...Q4(O4,[IZ,LZ]),...Q4(l8,[LZ])},i8=c8(vz),aO=c8({...u8,...O4}),rO=c8({...O4,...l8}),P3={calendarId:($)=>T0($.calendar)},tO=a0(($,Z)=>function(J){let{i:W}=this;return $(W[Z]($0(G0(J,W))))},vz),eO=j3(($)=>(Z)=>Z[$],v.concat("sign")),s8=j3(($,Z)=>(J)=>J[Z1[Z]],f1),gz={epochSeconds:mW,epochMilliseconds:b6,epochMicroseconds:pW,epochNanoseconds:hW},N3=R(cJ,new Set(["branding"])),[$D,xZ,ZD]=F1(LZ,R(VY,L0),{...P3,...rO},{getISOFields:N3,getCalendar:I3,with($,Z,J){return xZ(XY(VD,$,this,SZ(Z),J))},equals:($,Z)=>qj($,xz(Z)),toPlainDate($,Z){return $0(EY(_3,$,this,Z))},toLocaleString($,Z,J){let[W,j]=nO(Z,J,$);return W.format(j)},toString:V2,toJSON:($)=>V2($),valueOf:j$},{from:($,Z)=>xZ(xz($,Z))}),mz={getOffsetNanosecondsFor:wz,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,I0(X0(J,w)))].map((Y)=>WD(Y).epochNanoseconds),j=W.length;return j>1&&(W.sort(C0),P2(d0(c0(W[0],W[j-1])))),W}},h8={getOffsetNanosecondsFor:wz},[JD,f0,WD]=F1(Y4,FY,gz,{add:($,Z)=>f0(N2(0,$,e(Z))),subtract:($,Z)=>f0(N2(1,$,e(Z))),until:($,Z,J)=>u(u2(0,$,Q1(Z),J)),since:($,Z,J)=>u(u2(1,$,Q1(Z),J)),round:($,Z)=>f0(uW($,Z)),equals:($,Z)=>bj($,Q1(Z)),toZonedDateTime($,Z){let J=C1(Z);return Q0(W8($,l(J.timeZone),L0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(W8($,l(Z))),toLocaleString($,Z,J){let[W,j]=cO(Z,J,$);return W.format(j)},toString:($,Z)=>F2(l,K0,$,Z),toJSON:($)=>F2(l,K0,$),valueOf:j$},{from:($)=>f0(Q1($)),fromEpochSeconds:($)=>f0(wY($)),fromEpochMilliseconds:($)=>f0(kY($)),fromEpochMicroseconds:($)=>f0(yY($)),fromEpochNanoseconds:($)=>f0(qY($)),compare:($,Z)=>h2(Q1($),Q1(Z))}),[D4,sM]=F1("TimeZone",($)=>{let Z=fj($);return{branding:"TimeZone",id:Z,o:X4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(Z$(Z)).map((J)=>f0(U0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(Q1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=Q1(Z).epochNanoseconds,W=K4(this,h8).getOffsetNanosecondsFor(J);return N$(W)},getPlainDateTimeFor($,Z,J=w){let W=Q1(Z).epochNanoseconds,j=K4(this,h8).getOffsetNanosecondsFor(W);return I0(X0(o1(W,j),L0(J)))},getInstantFor($,Z,J){let W=Z$(Z),j=Z2(J),Y=K4(this);return f0(U0(v0(Y,W,j)))},getNextTransition:({o:$},Z)=>Sz(1,$,Z),getPreviousTransition:({o:$},Z)=>Sz(-1,$,Z),equals($,Z){return!!i6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new D4(Z):Z}}),jD=Rz(Object.keys(mz)),[YD,J$]=F1(j4,TY,s8,{getISOFields:N3,with($,Z,J){return J$(GY(this,SZ(Z),J))},add:($,Z)=>J$(A2(0,$,e(Z))),subtract:($,Z)=>J$(A2(1,$,e(Z))),until:($,Z,J)=>u(o2(0,$,$$(Z),J)),since:($,Z,J)=>u(o2(1,$,$$(Z),J)),round:($,Z)=>J$(sW($,Z)),equals:($,Z)=>vj($,$$(Z)),toZonedDateTime:($,Z)=>Q0(bY(l,E0,d,$,Z)),toPlainDateTime:($,Z)=>I0(RY($,E0(Z))),toLocaleString($,Z,J){let[W,j]=iO(Z,J,$);return W.format(j)},toString:T2,toJSON:($)=>T2($),valueOf:j$},{from:($,Z)=>J$($$($,Z)),compare:($,Z)=>l6($$($),$$(Z))}),[zD,W$,XD]=F1(IZ,R(UY,L0),{...P3,...aO},{getISOFields:N3,getCalendar:I3,with($,Z,J){return W$(zY(UD,$,this,SZ(Z),J))},add:($,Z,J)=>W$(S2(Ez,0,$,e(Z),J)),subtract:($,Z,J)=>W$(S2(Ez,1,$,e(Z),J)),until:($,Z,J)=>u(n2(bz,0,$,_Z(Z),J)),since:($,Z,J)=>u(n2(bz,1,$,_Z(Z),J)),equals:($,Z)=>yj($,_Z(Z)),toPlainDate($,Z){return $0(fY(_3,$,this,Z))},toLocaleString($,Z,J){let[W,j]=sO(Z,J,$);return W.format(j)},toString:U2,toJSON:($)=>U2($),valueOf:j$},{from:($,Z)=>W$(_Z($,Z)),compare:($,Z)=>x$(_Z($),_Z(Z))}),[GD,I0]=F1(b$,R(DY,L0),{...P3,...i8,...s8},{getISOFields:N3,getCalendar:I3,with($,Z,J){return I0(jY(_3,$,this,SZ(Z),J))},withCalendar:($,Z)=>I0(a6($,L0(Z))),withPlainDate:($,Z)=>I0(pY($,E0(Z))),withPlainTime:($,Z)=>I0(mY($,d8(Z))),add:($,Z,J)=>I0(C2(w$,0,$,e(Z),J)),subtract:($,Z,J)=>I0(C2(w$,1,$,e(Z),J)),until:($,Z,J)=>u(i2(K1,0,$,Z$(Z),J)),since:($,Z,J)=>u(i2(K1,1,$,Z$(Z),J)),round:($,Z)=>I0(iW($,Z)),equals:($,Z)=>wj($,Z$(Z)),toZonedDateTime:($,Z,J)=>Q0(PY(d,$,l(Z),J)),toPlainDate:($)=>$0(G0($)),toPlainTime:($)=>J$(e0($)),toPlainYearMonth($){return W$(NY(B4,$,this))},toPlainMonthDay($){return xZ(_Y(V4,$,this))},toLocaleString($,Z,J){let[W,j]=uO(Z,J,$);return W.format(j)},toString:D2,toJSON:($)=>D2($),valueOf:j$},{from:($,Z)=>I0(Z$($,Z)),compare:($,Z)=>d2(Z$($),Z$(Z))}),[QD,$0,pz]=F1(E$,R(BY,L0),{...P3,...i8},{getISOFields:N3,getCalendar:I3,with($,Z,J){return $0(YY(_3,$,this,SZ(Z),J))},withCalendar:($,Z)=>$0(a6($,L0(Z))),add:($,Z,J)=>$0(x2(w$,0,$,e(Z),J)),subtract:($,Z,J)=>$0(x2(w$,1,$,e(Z),J)),until:($,Z,J)=>u(s2(K1,0,$,E0(Z),J)),since:($,Z,J)=>u(s2(K1,1,$,E0(Z),J)),equals:($,Z)=>kj($,E0(Z)),toZonedDateTime($,Z){let J=!B0(Z)||Z instanceof D4?{timeZone:Z}:Z;return Q0(CY(l,$$,d,$,J))},toPlainDateTime:($,Z)=>I0(xY($,d8(Z))),toPlainYearMonth($){return W$(SY(B4,$,this))},toPlainMonthDay($){return xZ(AY(V4,$,this))},toLocaleString($,Z,J){let[W,j]=lO(Z,J,$);return W.format(j)},toString:B2,toJSON:($)=>B2($),valueOf:j$},{from:($,Z)=>$0(E0($,Z)),compare:($,Z)=>x$(E0($),E0(Z))}),n8={fields($,Z,J){return[...Z.call($,J)]}},hz=Object.assign({dateFromFields($,Z,J,W){return pz(Z.call($,Object.assign(Object.create(null),J),W))}},n8),cz=Object.assign({yearMonthFromFields($,Z,J,W){return XD(Z.call($,Object.assign(Object.create(null),J),W))}},n8),dz=Object.assign({monthDayFromFields($,Z,J,W){return ZD(Z.call($,Object.assign(Object.create(null),J),W))}},n8),o8={mergeFields($,Z,J,W){return C1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},KD=Object.assign({},hz,o8),FD=Object.assign({},cz,o8),OD=Object.assign({},dz,o8),a8={dateAdd($,Z,J,W,j){return pz(Z.call($,$0(G0(J,$)),u(s(W)),j))}},uz=Object.assign({},a8,{dateUntil($,Z,J,W,j,Y){return MD(Z.call($,$0(G0(J,$)),$0(G0(W,$)),Object.assign(Object.create(null),Y,{largestUnit:B3[j]})))}}),DD=Object.assign({},a8,{day:kz}),BD=Object.assign({},uz,{day:kz}),B4=O1(cz),U4=O1(hz),V4=O1(dz),UD=O1(FD),_3=O1(KD),VD=O1(OD),w$=O1(a8),K1=O1(uz),Ez=O1(DD),bz=O1(BD),[TD,u,MD]=F1(z4,MY,{...eO,blank:Kj},{with:($,Z)=>u(QY($,Z)),negated:($)=>u(p6($)),abs:($)=>u(Qj($)),add:($,Z,J)=>u(w2(H3,K1,d,0,$,e(Z),J)),subtract:($,Z,J)=>u(w2(H3,K1,d,1,$,e(Z),J)),round:($,Z)=>u(Gj(H3,K1,d,$,Z)),total:($,Z)=>dW(H3,K1,d,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):y6($)},toString:y6,toJSON:($)=>y6($),valueOf:j$},{from:($)=>u(e($)),compare:($,Z,J)=>Ej(H3,w$,d,e($),e(Z),J)}),lz={toString:($)=>$.id,toJSON:($)=>$.id,...oO,dateAdd:({id:$,o:Z},J,W,j)=>$0(G0(Z.dateAdd(E0(J),e(W),j),$)),dateUntil:({o:$},Z,J,W)=>u(s($.dateUntil(E0(Z),E0(J),kW(W)))),dateFromFields:({id:$,o:Z},J,W)=>$0(t2(Z,J,W,UW($))),yearMonthFromFields:({id:$,o:Z},J,W)=>W$(e2(Z,J,W,DW($))),monthDayFromFields:({id:$,o:Z},J,W)=>xZ($8(Z,0,J,W,BW($))),fields({o:$},Z){let J=new Set($1),W=[];for(let j of Z){if(t(j),!J.has(j))throw RangeError(Q8(j));J.delete(j),W.push(j)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(dJ(iJ(Z)),dJ(iJ(J)))},[r8]=F1("Calendar",($)=>{let Z=lj($);return{branding:"Calendar",id:Z,o:PZ(Z)}},{id:($)=>$.id},lz,{from($){let Z=L0($);return typeof Z=="string"?new r8(Z):Z}}),HD=Rz(Object.keys(lz).slice(4)),[ID,Q0]=F1(E1,R(OY,L0,l),{...gz,...P3,...Az(i8),...Az(s8),offset:($)=>N$(p8($).offsetNanoseconds),offsetNanoseconds:($)=>p8($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>nW(d,$)},{getISOFields:($)=>zj(K0,$),getCalendar:I3,getTimeZone:({timeZone:$})=>typeof $=="string"?new D4($):$,with($,Z,J){return Q0(WY(_3,d,$,this,SZ(Z),J))},withCalendar:($,Z)=>Q0(a6($,L0(Z))),withTimeZone:($,Z)=>Q0(hY($,l(Z))),withPlainDate:($,Z)=>Q0(gY(d,$,E0(Z))),withPlainTime:($,Z)=>Q0(vY(d,$,d8(Z))),add:($,Z,J)=>Q0(_2(w$,d,0,$,e(Z),J)),subtract:($,Z,J)=>Q0(_2(w$,d,1,$,e(Z),J)),until:($,Z,J)=>u(s(l2(K1,d,0,$,CZ(Z),J))),since:($,Z,J)=>u(s(l2(K1,d,1,$,CZ(Z),J))),round:($,Z)=>Q0(lW(d,$,Z)),startOfDay:($)=>Q0(oW(d,$)),equals:($,Z)=>Rj($,CZ(Z)),toInstant:($)=>f0(HY($)),toPlainDateTime:($)=>I0(j8(K0,$)),toPlainDate:($)=>$0(Y8(K0,$)),toPlainTime:($)=>J$(z8(K0,$)),toPlainYearMonth($){return W$(IY(B4,$,this))},toPlainMonthDay($){return xZ(LY(V4,$,this))},toLocaleString($,Z,J={}){let[W,j]=dO(Z,J,$);return W.format(j)},toString:($,Z)=>O2(K0,$,Z),toJSON:($)=>O2(K0,$),valueOf:j$},{from:($,Z)=>Q0(CZ($,Z)),compare:($,Z)=>c2(CZ($),CZ(Z))}),LD=Object.defineProperties({},{...H6("Temporal.Now"),...I$({timeZoneId:()=>A1(),instant:()=>f0(U0(F3())),zonedDateTime:($,Z=A1())=>Q0(H0(F3(),l(Z),L0($))),zonedDateTimeISO:($=A1())=>Q0(H0(F3(),l($),w)),plainDateTime:($,Z=A1())=>I0(X0(MZ(K0(l(Z))),L0($))),plainDateTimeISO:($=A1())=>I0(X0(MZ(K0(l($))),w)),plainDate:($,Z=A1())=>$0(G0(MZ(K0(l(Z))),L0($))),plainDateISO:($=A1())=>$0(G0(MZ(K0(l($))),w)),plainTimeISO:($=A1())=>J$(e0(MZ(K0(l($)))))})}),AZ=Object.defineProperties({},{...H6("Temporal"),...I$({PlainYearMonth:zD,PlainMonthDay:$D,PlainDate:QD,PlainTime:YD,PlainDateTime:GD,ZonedDateTime:ID,Instant:JD,Calendar:r8,TimeZone:D4,Duration:TD,Now:LD})}),PD=vO(),t8=new WeakMap,ND=Object.defineProperties(Object.create(Intl),I$({DateTimeFormat:PD}));var tM="gemi.v1",iz="/__gemi/socket",e8="x-gemi-socket",eM=/^[A-Za-z0-9_-]{1,32}$/,$H={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function WH($){return $}function sz(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:iz,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as _D,randomBytes as CD}from"crypto";function xD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(_D("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var SD="__control",$5=250,AD=1e4,fD=15000;class Z5{config;prefix;controlChannel;instanceId=CD(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??xD(),this.controlChannel=this.prefix+SD,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=C3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),fD,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${nz(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(AD,$5*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max($5,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;C3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${nz(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??ED(Math.min(Z,$5));await C3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let j=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(j,j),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let j=this.subscriber;this.active.delete($);try{await C3(j.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(Y){if(this.subscriber===j)this.drop(j);throw Y}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await C3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(j){if(this.subscriber===W)this.drop(W);throw j}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function C3($,Z,J){let W;return Promise.race([$,new Promise((j,Y)=>{W=setTimeout(()=>Y(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function ED($){return new Promise((Z)=>setTimeout(Z,$))}function nz($){return $ instanceof Error?$.message:String($)}import{createHmac as bD,hkdfSync as RD,randomBytes as oz}from"crypto";function az($){return bD("sha256",wD()).update($).digest("base64url").slice(0,22)}var T4=null;function wD(){let $=process.env.SECRET||void 0;if(T4&&T4.secret===$)return T4.key;let Z=$?Buffer.from(RD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):oz(32);return T4={secret:$,key:Z},Z}function GH(){return oz(16).toString("base64url")}var kD=/^[A-Za-z0-9_-]{8,64}$/;function J5($){return typeof $==="string"&&kD.test($)}function rz($,Z,J,W){let j={op:"ev",t:$,ev:Z};if(J!==void 0)j.d=J;if(W)j.x=W;return JSON.stringify(j)}class ez extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class m0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=EZ(sz(),$),this.driver=vD(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new x3(this,M4($,Z[0]),null)}toUser($){return new x3(this,{topic:n$($),pattern:F0},null)}toOthers($){return new $X(this,qD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),j=$.broadcastWith(),Y=J.map((z)=>this.prepare(M4(z,void 0),W,j,null));for(let{sent:z,frame:X}of Y)this.hand(z,X)}send($,Z,J,W){let{sent:j,frame:Y}=this.prepare($,Z,J,W);this.hand(j,Y)}prepare($,Z,J,W){P7(Z);let j;try{j=rz($.topic,Z,J,W?az(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,j),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(j).d,...W?{except:W}:{}},frame:j}}hand($,Z){fZ(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=yD($);fZ(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new ez(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class x3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class $X{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new x3(this.manager,M4($,Z[0]),this.except)}toUser($){return new x3(this.manager,{topic:n$($),pattern:F0},this.except)}}function M4($,Z){if(L7($))return{topic:a4($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:lZ($,Z??{}),pattern:$};if($===F0)throw new h('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:a4($)}}function yD($){if($&&typeof $==="object"&&"user"in $)return{user:n$($.user).slice(F0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:M4($.channel,$.params).topic};throw new h("Broadcast.revoke takes { user } or { channel }.")}function qD($){if($===null||$===void 0)return null;if(typeof $==="string")return J5($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(e8);return J5(J)?J:null}function vD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new tz;if(J==="redis"){let W=Z?.config.get("redis",{})??{},j=$.redis??{};return new Z5({url:j.url??W.url??process.env.REDIS_URL,options:j.options??W.options,prefix:j.prefix,subscribeTimeoutMs:j.subscribeTimeoutMs,healthCheckMs:j.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class W5 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class gD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as j5,createHmac as mD,randomBytes as ZX,timingSafeEqual as jX}from"crypto";var A3=600,H4="gemi_oauth",pD=`__Host-${H4}`;function bZ($,Z=H4){if(Z===H4)return $?pD:H4;return $?`__Host-${Z}`:Z}function S3($){return $.toString("base64url")}function YX($){return mD("sha256",ZZ()).update(`gemi-oauth-state:${$}`).digest()}function JX($,Z){let J=j5("sha256").update($).digest(),W=j5("sha256").update(Z).digest();return jX(J,W)&&$.length===Z.length}function I4($,Z=Date.now(),J={}){let W=S3(ZX(32)),j=S3(ZX(32)),Y=hD(j),z={provider:$,state:W,codeVerifier:j,expiresAt:Z+A3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:j,codeChallenge:Y,cookieValue:cD(z)}}function hD($){return S3(j5("sha256").update($).digest())}function cD($){let Z=S3(Buffer.from(JSON.stringify($)));return`${Z}.${S3(YX(Z))}`}function dD($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),j=YX(J);if(W.length!==j.length||!jX(W,j))return null;try{let Y=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof Y?.provider!=="string"||typeof Y?.state!=="string"||typeof Y?.codeVerifier!=="string"||typeof Y?.expiresAt!=="number"||Y.subject!==void 0&&typeof Y.subject!=="string"||Y.returnTo!==void 0&&typeof Y.returnTo!=="string")return null;return Y}catch{return null}}var Y$=new Map,WX=1e4;function uD($,Z,J){if(Y$.size>=WX){for(let[W,j]of Y$)if(j<=J)Y$.delete(W);while(Y$.size>=WX){let W=Y$.keys().next().value;if(W===void 0)break;Y$.delete(W)}}Y$.set($,Z)}function L4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=dD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=JX(J.state,$.returnedState),j=JX(J.provider,$.provider);if(!W||!j)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(Y$.has(J.state))return{ok:!1,reason:"invalid_state"};return uD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var Y5=new WeakMap;function iD($){let Z=Y5.get($);if(!Z)Z=$(lD(32).toString("hex")),Y5.set($,Z),Z.catch(()=>Y5.delete($));return Z}async function z5($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await iD($.hashPassword))}catch{}return!1}async function k$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...j}=J;await $.onAuthenticated({...Z,user:j})}class G5 extends Error{}function X5($){return typeof $==="string"&&$!==""?$:null}function zX($){return oZ($)}var sD=256;function XX($){return typeof $==="string"&&$!==""&&$.length<=sD?$:null}var P4="intended_url";function QX($){if($.cookies.get(P4))$.ctx().setCookie(P4,"",{maxAge:-1})}function GX($){let Z=$.cookies.get(P4);if(!Z)return null;QX($);try{return j1(decodeURIComponent(Z),"")||null}catch{return null}}class Q5 extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class KX extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class FX extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function b1($){if(T(A).config[$]===!1)throw new W0("Not found",{status:404})}class n extends sZ{async me(){let $=await R0.user();if(!$)throw new BJ;return $}async verifyEmail($=new C){b1("password");let Z=await $.input(),{userProvider:J}=T(A),W=X5(Z.get("token"));if(!W)return{email:null};let j=await J.findUserByVerificationToken(W);if(!j)return{email:null};return await J.verifyUser(j.email),{email:j.email}}async signInWithMagicLink($=new C){let Z=T(A),{userProvider:J}=Z,W=X5($.search.get("token")),j=null;try{j=oZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await JZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!j||!W||!await Z.verifyMagicLinkToken(j,W))return{error:"Invalid token"};await J.verifyUser(j);let Y=await Z.createOrUpdateSession({email:j});return $.ctx().setCookie("access_token",Y.token,T(A).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON()),await k$(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),{session:Y}}async verifyPinRequest($){b1("magicLink");let Z=T(A),J=await $.input(),{email:W,pin:j}=J.toJSON(),Y=oZ(W),z=XX(j);if(await JZ("verify",Y,$,Z.config.emailCode.verifyLimit),!Y||!z)throw new m({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(Y,z);if(X.status==="too_many_attempts")throw new m({pin:["Too many attempts"]});if(X.status!=="ok")throw new m({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(Y),Y}async signInWithPinV2($=new C){let Z=T(A),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,T(A).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await k$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=T(A),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,T(A).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await k$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new Q5){b1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),j=J.toLowerCase().trim(),Y=T(A),z=await Y.userProvider.findUserByEmailAddress(j,Y.config.verifyEmail),X=typeof W==="string"&&await z5(Y.config,W,z?.password);if(!z||!X)throw new m({invalid_credentials:["Invalid credentials"]});let G=await Y.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,T(A).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await k$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...K}=z;return K}async signIn($=new Q5){b1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),j=J.toLowerCase().trim(),Y=T(A),z=await Y.userProvider.findUserByEmailAddress(j,Y.config.verifyEmail),X=typeof W==="string"&&await z5(Y.config,W,z?.password);if(!z||!X)throw new m({invalid_credentials:["Invalid credentials"]});let G=await Y.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,T(A).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await k$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...K}=z;return K}async signUp(){b1("password");let $=T(A),{userProvider:Z,config:J}=$,W=new J.signUpRequest,j=await W.input(),{email:Y,password:z,name:X,invitationId:G}=j.toJSON(),Q=zX(Y);if(!Q)throw new m({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new m({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new m({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(Q,!1))throw new m({email:["Email address already exists"]});let O=await J.hashPassword(z),F=T(i).detectLocale(W),B;if(G)B=await Z.findInvitation(G,Q);let D,U="";if(B)D=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let V=await Z.createUser({email:Q,name:X,password:O,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:B.organizationId,userId:V.id,organizationRole:B.role}),await J.onUserCreated(V),V});else U=await J.generateEmailVerificationToken(Q),D=await Z.transaction(async()=>{let V=await Z.createUser({email:Q,name:X,password:O,verificationToken:U,locale:F});return await J.onUserCreated(V),V});return await J.onSignUp(D,U,W.search.toJSON()),D}async signOut($=new C){let Z=Q$($),J=T(A),{config:W}=J,j=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",T(A).accessTokenCookieOptions($,new Date(0))),T(A).cookieDomain($))$.ctx().setCookie("access_token","",{...T(A).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(j?.user)nD(j.user),j.user.extension=await W.extendSession(j.user),await W.onSignOut(j.user);return{}}async forgotPassword($=new KX){b1("password");let Z=await $.input(),J=zX(Z.get("email"));if(!J)return{};let{userProvider:W,config:j}=T(A),Y=await W.findUserByEmailAddress(J,j.verifyEmail);if(!Y)return{};let z=await j.generateForgotPasswordToken(Y);return await W.createPasswordResetToken({user:Y,token:z}),await j.onForgotPassword(Y,z),{}}async resetPassword($=new FX){b1("password");let{userProvider:Z,config:J}=T(A),W=await $.input(),{password:j,token:Y}=W.toJSON(),z=X5(Y),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new m({token:["Invalid token"]});if(AZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(AZ.Now.instant()).sign>=0)throw new m({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!Q)throw new m({email:["User not found"]});let K=await J.hashPassword(j);return await Z.updateUserPassword({id:Q.id,password:K}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q),{}}async changePassword($=new C){b1("password");let{userProvider:Z,config:J}=T(A),W=await R0.user(),j=await $.input(),{oldPassword:Y,newPassword:z}=j.toJSON();if(typeof z!=="string")throw new m({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof Y==="string"&&await z5(J,Y,X?.password)))throw new m({oldPassword:["Incorrect password"]});let Q=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:Q}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=T(A).config.oauthProviders,W=Object.hasOwn(J,Z),j=await WZ(J,Z);if(!j){if(W)throw new W0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let Y=a$($.rawRequest),z=j1($.search.get(W1),"");if(z)$.ctx().setCookie(P4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:600});else QX($);let{state:X,codeChallenge:G,cookieValue:Q}=I4(Z);return $.ctx().setCookie(bZ(Y),Q,{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:A3}),{destination:await j.getRedirectUrl($,{state:X,codeChallenge:G,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=T(A),{userProvider:W,config:j}=J,Y=Object.hasOwn(j.oauthProviders,Z),z=await WZ(j.oauthProviders,Z);if(Y&&!z)throw new W0("Not found",{status:404});let X=a$($.rawRequest),G=bZ(X),Q=$.cookies.get(G);if(Q!==void 0&&Q!==null)$.ctx().setCookie(G,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let K=$.search.get("error");if(K)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(K)?K:"provider_error");let O=L4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in O)return console.error(`Authentication error: OAuth callback refused (${O.reason})`),this.oauthFailure($,O.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let F;try{F=await z.onCallback($,{state:O.payload.state,codeVerifier:O.payload.codeVerifier})}catch(I){if(I instanceof W5)return this.oauthFailure($,I.code);return console.error("Authentication error: OAuth provider callback failed",I),this.oauthFailure($,"provider_error")}let{name:B,username:D,providerId:U,emailVerified:V}=F??{},M=typeof F?.email==="string"?F.email:void 0,L=M?$6(M):null,H=U?await W.findUserBySocialAccount(Z,U):null,S="signin",f=!H&&!L&&!M&&!!U&&z.createUsersWithoutEmail===!0;if(!H&&f){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{H=await this.createOAuthUserWithoutEmail({provider:Z,providerId:U,name:B,username:D,locale:T(i).detectLocale($)}),S="signup"}catch(I){let k=await W.findUserBySocialAccount(Z,U);if(!k)throw I;H=k}}if(!H){if(!L)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,M?"invalid_email":U?"missing_email":"no_identity");if(V===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let I=T(i).detectLocale($);try{let k=await this.linkOAuthAccount({provider:Z,providerId:U,email:L,rawEmail:M,name:B,username:D,locale:I,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(k==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(k==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(k)H=k.user,S=k.action}catch(k){let g=U?await W.findUserBySocialAccount(Z,U):null;if(!g)throw k;H=g}if(!H)return this.oauthFailure($,"account_conflict")}let E=await J.createOrUpdateSessionV2({email:H.email,id:H.id});if($.ctx().setCookie("access_token",E.token,T(A).accessTokenCookieOptions($,E.expiresAt)),S==="signup")await j.onSignUp(H,"",$.search.toJSON());else await j.onSignIn(H,$.search.toJSON());await k$(J.config,{session:E,user:H,isNewUser:S==="signup",method:"oauth",req:$});let x=GX($)??j.redirectPath,P=j.oauthCompleteProfilePath?j1(j.oauthCompleteProfilePath,""):"";if(P&&!H.email){let I=new URL(P,"http://gemi.invalid");I.searchParams.set(W1,x),x=`${I.pathname}${I.search}${I.hash}`}return{session:E,redirectTo:x}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=T(A);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W),W})}oauthFailure($,Z){let J=GX($),W=T(A).config.oauthFailurePath;if(W){let j=j1(W,"");if(j){let Y=new URL(j,"http://gemi.invalid");if(Y.searchParams.set("error",Z),J)Y.searchParams.set(W1,J);M1.external(`${Y.pathname}${Y.search}${Y.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:j,name:Y,username:z,locale:X}=$,{userProvider:G,config:Q}=T(A),K=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),O=await G.findUserByEmailAddress(W,!1),F=j?.trim();if(!O&&F&&F!==W)O=await G.findUserByEmailAddress(F,!1);if(O){if($.linkExisting===!1)return"account_exists";if(!J)return{user:O,action:"signin"};let D=await G.findSocialAccounts(O.id,Z);if(D.some((V)=>V.providerId===J))return{user:O,action:"signin"};if(D.some((V)=>V.providerId))return console.error(`Authentication error: user ${O.id} is already linked to a different ${Z} account`),null;let U=D[0];if(U){if(!await G.claimSocialAccount(U,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(K(O.id));return{user:O,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let D=await G.createUser({email:W,name:Y,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(K(D.id));return await Q.onUserCreated(D),D}),action:"signup"}}async createMagicLinkToken($=new C){b1("magicLink");let Z=await $.input(),J=oZ(Z.get("email")),W=T(A),{uniformMagicLinkResponse:j,requestLimit:Y}=W.config.emailCode;if(await JZ("request",J,$,Y),!J)return{email:null};let{user:z,pin:X,token:G}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:G}),{email:J};return{email:j?J:null}}async requestEmailCode($=new C){let Z=T(A),J=Z.config.emailCode;if(!J.enabled)throw new W0("Not found",{status:404});let W=await $.input(),j=$6(W.get("email"));if(await JZ("request",j,$,J.requestLimit),!j)throw new m({email:["Invalid email"]});let Y=await Z.userProvider.findUserByEmailAddress(j,!1);if(Y||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(j,J.length);await J.send({email:j,code:z,token:X,isNewUser:!Y,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=T(A),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new W0("Not found",{status:404});let j=await $.input(),{email:Y,code:z,name:X}=j.toJSON(),G=$6(Y),Q=XX(z);if(await JZ("verify",G,$,W.emailCode.verifyLimit),!G||!Q)throw new m({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(K.status==="too_many_attempts")throw new m({code:["too_many_attempts"]});if(K.status!=="ok")throw new m({code:["invalid_code"]});let O=K.row,F=await J.findUserByEmailAddress(G,!1),B=!1;if(F){if(!await J.claimMagicLinkToken(O.id))throw new m({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let U=T(i).detectLocale($);try{F=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(O.id))throw new G5;let V=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await W.onUserCreated(V),V}),B=!0}catch(V){if(V instanceof G5)throw new m({code:["invalid_code"]});throw V}}else throw await J.claimMagicLinkToken(O.id),new m({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:F.id});return $.ctx().setCookie("access_token",D.token,T(A).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON()),await k$(Z.config,{session:D,isNewUser:B,method:"email-code",req:$}),{session:D,isNewUser:B}}}function nD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=T();if(typeof J?.bound!=="function"||!J.bound(m0))return;J.make(m0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var OX="gemi_oauth_connection";class N4 extends sZ{async connect($=new C){let Z=String($.params.provider??""),W=T(f3).providers[Z],j=await R0.user(),Y=j1($.search.get(W1),"");if(!W)return this.finish(Y,Z,"unknown_provider");let z=a$($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=I4(DX(Z),Date.now(),{subject:String(j.id),...Y?{returnTo:Y}:{}});return $.ctx().setCookie(bZ(z,OX),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:A3}),M1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:BX($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=T(f3),W=await R0.user(),j=a$($.rawRequest),Y=bZ(j,OX),z=$.cookies.get(Y);if(z!==void 0&&z!==null)$.ctx().setCookie(Y,"",{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:-1});let X=L4({provider:DX(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=J.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let K=$.search.get("error");if(K)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(K)?K:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(G,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(G,Z,"user_mismatch");let O=$.search.get("code");if(!O)return this.finish(G,Z,"missing_code");try{let F=await Q.exchangeCode({code:O,codeVerifier:X.payload.codeVerifier,redirectUri:BX($,Z,Q.config.redirectUri)}),B=await J.save(W,Z,F);await T(A).config.onConnected({user:W,provider:Z,connection:B,profile:F.profile??null,req:$})}catch(F){if(F instanceof UX)return console.error(`OAuth connection to ${Z} failed: ${F.message}`),this.finish(G,Z,F.providerError??F.code);throw F}return this.finish(G,Z)}finish($,Z,J){let W=$||j1(T(A).config.redirectPath,"/"),j=new URL(W,"http://gemi.invalid");if(j.searchParams.set("connection",Z),J)j.searchParams.set("connection_error",J);throw M1.external(`${j.pathname}${j.search}${j.hash}`),Error("unreachable: Redirect.external throws")}}function DX($){return`connection:${$}`}function BX($,Z,J){if(J)return J;return`${(process.env.HOST_NAME||new URL($.rawRequest.url).origin).replace(/\/$/,"")}/auth/connections/${encodeURIComponent(Z)}/callback`}class VX extends H1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[n,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[n,"oauthCallback"])}}class TX extends H1{middlewares=["cache:private"];routes={"/:provider":this.redirect([N4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([N4,"callback"]).middleware([i3,"auth"])}}class K5 extends H1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[n,"signInWithMagicLink"]),"/oauth":VX,"/connections":TX}}class F5 extends b0{middlewares=["cache:private"];routes={"/sign-in":this.post(n,"signIn"),"/sign-in-v2":this.post(n,"signInV2"),"/sign-up":this.post(n,"signUp"),"/sign-out":this.post(n,"signOut"),"/forgot-password":this.post(n,"forgotPassword"),"/reset-password":this.post(n,"resetPassword"),"/change-password":this.post(n,"changePassword"),"/verify-email":this.post(n,"verifyEmail"),"/me":this.get(n,"me").middleware(["auth"]),"/magic-link":this.post(n,"createMagicLinkToken"),"/sign-in-with-pin":this.post(n,"signInWithPin"),"/sign-in-with-pin-v2":this.post(n,"signInWithPinV2"),"/email-code":this.post(n,"requestEmailCode"),"/email-code/verify":this.post(n,"verifyEmailCode")}}class O5 extends b0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await T(i).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=T(i),j=J??W.detectLocale($),Y=W.getPageTranslations(j,Z);return $.ctx().setCookie("i18n-locale",j,{expires:new Date(Date.now()+31536000000)}),{[j]:Y}})}}class D5{}class B5 extends D5{async resize($,Z){let{height:J,width:W,quality:j,fit:Y}=Z;return await(await _4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:Y}).webp({quality:j>0?j:80,force:!0}).toBuffer()}}function TI($){return $}function MX(){return{driver:new B5}}class U5 extends b0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),j=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 G=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,Q=await fetch(G);if(!Q.ok)return new Response(JSON.stringify({error:"Image not found",info:G}),{headers:{"Content-Type":"application/json"},status:404});let K=Buffer.from(await Q.arrayBuffer()),O=await T(HX).resize(K,{height:j,width:W,fit:Y,quality:z});Q.headers.delete("Content-Type"),Q.headers.delete("Content-Length");let F=new Headers(Q.headers);return F.set("Content-Type","image/webp"),F.set("Content-Length",`${O.byteLength}`),new Response(new Uint8Array(O),{headers:F})})}}class HX{static token="image";driver;constructor($={}){this.driver=$.driver??MX().driver}resize($,Z){return this.driver.resize($,Z)}}class V5 extends b0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(T(IX).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function SI($){return $}function LX(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function PX(){return{partialRendering:!0,localeRouting:"prefix",onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function oD($){return"run"in $}function aD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function rD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function tD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function eD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function NX($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function T5($,Z="",J=[]){let W={};function j(Y,z,X,G,Q){let K=Y==="/"?"":Y,O=Z==="/"?"":Z,F=(`${O}${K}`===""?"/":`${O}${K}`).replaceAll("//","/");if(!W[F])W[F]={};W[F][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{}},W[F].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[Y,z]of Object.entries($)){if(eD(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])j(Y,G,X.run.bind(X),X.middlewares);continue}if(oD(z)){let X=z,G=X.method,Q=X.middlewares,K=X.run.bind(X);if(j(Y,G,K,Q,X.source),NX(z))j(Y,"HEAD",K,Q,X.source)}if(aD(z))for(let[X,G]of Object.entries(z)){let Q=G,K=Q.middlewares,O=Q.run.bind(Q);if(j(Y,X,O,K,Q.source),X==="get"&&NX(Q))j(Y,"HEAD",O,K,Q.source)}if(tD(z)){let X=new z,G=T5(X.routes,`${Z}${Y}`,X.middlewares);for(let[Q,K]of Object.entries(G))W[Q.replaceAll("//","/")]=K}if(rD(z)){let{first:X,second:G}=z;for(let[Q,K]of Object.entries(X)){let O=K.middlewares,F=K.run.bind(K),[B,...D]=Y.split("/").reverse();if(!B.startsWith(":"))throw Error("Resource route must end with a dynamic segment");j(D.reverse().join("/"),Q,F,O,K.source)}for(let[Q,K]of Object.entries(G)){let O=K.middlewares,F=K.run.bind(K);j(Y,Q,F,O,K.source)}}}return Object.fromEntries(Object.entries(W).sort(([Y],[z])=>{let X=Y.split("/").length+Y.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}function C4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function M5($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function H5($){let Z=C4($);return Z.length>1?Z.replace(/\/$/,""):Z}function _X($,Z){return Z.map((J)=>({...J,path:H5(M5($,J.path))}))}function x4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let j=W;if("children"in j){let Y=new j.children,z=x4(Y.routes);for(let[X,{exec:G,middleware:Q,segments:K,features:O,static:F}]of Object.entries(z)){let B=M5(J,X),D=(U)=>j.run.call(j,U,J);Z[C4(B)]={exec:[D,...G],middleware:[...j.middlewares,...Q],features:[...j.featureGates,...O],viewPath:j.viewPath,segments:[{path:H5(J),viewPath:j.viewPath,...j.alwaysRuns?{alwaysRun:!0}:{}},..._X(J,K)],...F?{static:F}:{}}}}else{let Y=(z)=>j.run.call(j,z,J);Z[C4(J)]={exec:[Y],middleware:j.middlewares,features:j.featureGates,viewPath:j.viewPath,segments:[{path:H5(J),viewPath:j.viewPath}],..."staticOptions"in j&&j.staticOptions?{static:j.staticOptions}:{}}}}else{let j=new W,Y=x4(j.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:K,features:O,static:F}]of Object.entries(Y)){let B=M5(J,z);Z[C4(B)]={exec:X,middleware:[...j.middlewares,...G],features:[...j.featureGates,...O],viewPath:Q,segments:_X(J,K),...F?{static:F}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let j=J.split("/").length+J.split(":").length,Y=W.split("/").length+W.split(":").length;return j-Y}))}var $B=Object.defineProperty,_=($,Z)=>$B($,"name",{value:Z,configurable:!0}),kZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,j,Y){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=j,this.modifier=Y}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};_(kZ,"Part");var ZB=/[$_\p{ID_Start}]/u,JB=/[$_\u200C\u200D\p{ID_Continue}]/u,L5=".*";function CX($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}_(CX,"isASCII");function _5($,Z=!1){let J=[],W=0;for(;W<$.length;){let j=$[W],Y=_(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(j==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(j==="+"||j==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(j==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(j==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(j==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(j===":"){let z="",X=W+1;for(;X<$.length;){let G=$.substr(X,1);if(X===W+1&&ZB.test(G)||X!==W+1&&JB.test(G)){z+=$[X++];continue}break}if(!z){Y(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(j==="("){let z=1,X="",G=W+1,Q=!1;if($[G]==="?"){Y(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!CX($[G],!1)){Y(`Invalid character '${$[G]}' at ${G}.`),Q=!0;break}if($[G]==="\\"){X+=$[G++]+$[G++];continue}if($[G]===")"){if(z--,z===0){G++;break}}else if($[G]==="("&&(z++,$[G+1]!=="?")){Y(`Capturing groups are not allowed at ${G}`),Q=!0;break}X+=$[G++]}if(Q)continue;if(z){Y(`Unbalanced pattern at ${W}`);continue}if(!X){Y(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=G;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}_(_5,"lexer");function C5($,Z={}){let J=_5($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${p0(Z.delimiter)}]+?`,j=[],Y=0,z=0,X="",G=new Set,Q=_((H)=>{if(z<J.length&&J[z].type===H)return J[z++].value},"tryConsume"),K=_(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),O=_((H)=>{let S=Q(H);if(S!==void 0)return S;let{type:f,index:E}=J[z];throw TypeError(`Unexpected ${f} at ${E}, expected ${H}`)},"mustConsume"),F=_(()=>{let H="",S;for(;S=Q("CHAR")??Q("ESCAPED_CHAR");)H+=S;return H},"consumeText"),B=_((H)=>H,"DefaultEncodePart"),D=Z.encodePart||B,U="",V=_((H)=>{U+=H},"appendToPendingFixedValue"),M=_(()=>{U.length&&(j.push(new kZ(3,"","",D(U),"",3)),U="")},"maybeAddPartFromPendingFixedValue"),L=_((H,S,f,E,x)=>{let P=3;switch(x){case"?":P=1;break;case"*":P=0;break;case"+":P=2;break}if(!S&&!f&&P===3){V(H);return}if(M(),!S&&!f){if(!H)return;j.push(new kZ(3,"","",D(H),"",P));return}let I;f?f==="*"?I=L5:I=f:I=W;let k=2;I===W?(k=1,I=""):I===L5&&(k=0,I="");let g;if(S?g=S:f&&(g=Y++),G.has(g))throw TypeError(`Duplicate name '${g}'.`);G.add(g),j.push(new kZ(k,g,D(H),I,D(E),P))},"addPart");for(;z<J.length;){let H=Q("CHAR"),S=Q("NAME"),f=Q("REGEX");if(!S&&!f&&(f=Q("ASTERISK")),S||f){let x=H??"";Z.prefixes.indexOf(x)===-1&&(V(x),x=""),M();let P=K();L(x,S,f,"",P);continue}let E=H??Q("ESCAPED_CHAR");if(E){V(E);continue}if(Q("OPEN")){let x=F(),P=Q("NAME"),I=Q("REGEX");!P&&!I&&(I=Q("ASTERISK"));let k=F();O("CLOSE");let g=K();L(x,P,I,k,g);continue}M(),O("END")}return j}_(C5,"parse");function p0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(p0,"escapeString");function P5($){return $&&$.ignoreCase?"ui":"u"}_(P5,"flags");function xX($,Z,J){return x5(C5($,J),Z,J)}_(xX,"stringToRegexp");function y$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}_(y$,"modifierToString");function x5($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=p0(X.value):W+=`(?:${p0(X.value)})${y$(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${p0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=L5),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${Q})${y$(X.modifier)}`:W+=`((?:${Q})${y$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${p0(X.prefix)}(${Q})${p0(X.suffix)})`,W+=y$(X.modifier);continue}W+=`(?:${p0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=p0(X.suffix),W+=p0(X.prefix),W+=`(?:${Q}))*)${p0(X.suffix)})`,X.modifier===0&&(W+="?")}let j=`[${p0(J.endsWith)}]|$`,Y=`[${p0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${Y}?`),J.endsWith.length?W+=`(?=${j})`:W+="$",new RegExp(W,P5(J));J.strict||(W+=`(?:${Y}(?=${j}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${Y}|${j})`),new RegExp(W,P5(J))}_(x5,"partsToRegexp");var X$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},WB={delimiter:".",prefixes:"",sensitive:!0,strict:!0},jB={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function SX($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}_(SX,"isAbsolutePathname");function S5($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}_(S5,"maybeStripPrefix");function AX($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}_(AX,"maybeStripSuffix");function A5($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}_(A5,"treatAsIPv6Hostname");var fX=["ftp","file","http","https","ws","wss"];function f5($){if(!$)return!0;for(let Z of fX)if($.test(Z))return!0;return!1}_(f5,"isSpecialScheme");function EX($,Z){if($=S5($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}_(EX,"canonicalizeHash");function bX($,Z){if($=S5($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}_(bX,"canonicalizeSearch");function RX($,Z){return Z||$===""?$:A5($)?R5($):b5($)}_(RX,"canonicalizeHostname");function wX($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}_(wX,"canonicalizePassword");function kX($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}_(kX,"canonicalizeUsername");function yX($,Z,J){if(J||$==="")return $;if(Z&&!fX.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}_(yX,"canonicalizePathname");function qX($,Z,J){return E5(Z)===$&&($=""),J||$===""?$:w5($)}_(qX,"canonicalizePort");function vX($,Z){return $=AX($,":"),Z||$===""?$:S4($)}_(vX,"canonicalizeProtocol");function E5($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}_(E5,"defaultPortForProtocol");function S4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}_(S4,"protocolEncodeCallback");function gX($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}_(gX,"usernameEncodeCallback");function mX($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}_(mX,"passwordEncodeCallback");function b5($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}_(b5,"hostnameEncodeCallback");function R5($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}_(R5,"ipv6HostnameEncodeCallback");function w5($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}_(w5,"portEncodeCallback");function pX($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}_(pX,"standardURLPathnameEncodeCallback");function hX($){return $===""?$:new URL(`data:${$}`).pathname}_(hX,"pathURLPathnameEncodeCallback");function cX($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}_(cX,"searchEncodeCallback");function dX($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}_(dX,"hashEncodeCallback");var uX=class{#Y;#W=[];#Z={};#$=0;#j=1;#Q=0;#X=0;#D=0;#B=0;#U=!1;constructor($){this.#Y=$}get result(){return this.#Z}parse(){for(this.#W=_5(this.#Y,!0);this.#$<this.#W.length;this.#$+=this.#j){if(this.#j=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#H(),this.#K()?this.#J(9,1):this.#F()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#O(5);continue}this.#J(10,0);break}if(this.#D>0)if(this.#x())this.#D-=1;else continue;if(this.#C()){this.#D+=1;continue}switch(this.#X){case 0:this.#I()&&this.#O(1);break;case 1:if(this.#I()){this.#f();let $=7,Z=1;this.#P()?($=2,Z=3):this.#U&&($=2),this.#J($,Z)}break;case 2:this.#T()?this.#O(3):(this.#M()||this.#F()||this.#K())&&this.#O(5);break;case 3:this.#N()?this.#J(4,1):this.#T()&&this.#J(5,1);break;case 4:this.#T()&&this.#J(5,1);break;case 5:this.#S()?this.#B+=1:this.#A()&&(this.#B-=1),this.#_()&&!this.#B?this.#J(6,1):this.#M()?this.#J(7,0):this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#M()?this.#J(7,0):this.#F()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#F()?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.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#G();break;case 2:break;case 3:this.#Z.username=this.#G();break;case 4:this.#Z.password=this.#G();break;case 5:this.#Z.hostname=this.#G();break;case 6:this.#Z.port=this.#G();break;case 7:this.#Z.pathname=this.#G();break;case 8:this.#Z.search=this.#G();break;case 9:this.#Z.hash=this.#G();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#U?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#L($,Z)}#L($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#j=0}#H(){this.#$=this.#Q,this.#j=0}#O($){this.#H(),this.#X=$}#V($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#V($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#I(){return this.#z(this.#$,":")}#P(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#T(){return this.#z(this.#$,"@")}#N(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#F(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#V(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#C(){return this.#W[this.#$].type=="OPEN"}#x(){return this.#W[this.#$].type=="CLOSE"}#S(){return this.#z(this.#$,"[")}#A(){return this.#z(this.#$,"]")}#G(){let $=this.#W[this.#$],Z=this.#V(this.#Q).index;return this.#Y.substring(Z,$.index)}#f(){let $={};Object.assign($,X$),$.encodePart=S4;let Z=xX(this.#G(),void 0,$);this.#U=f5(Z)}};_(uX,"Parser");var I5=["protocol","username","password","hostname","port","pathname","search","hash"],z$="*";function N5($,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}}_(N5,"extractValues");function D1($,Z){return Z?wZ($):$}_(D1,"processBaseURLString");function RZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=D1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=D1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=D1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=D1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=D1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=D1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=D1(W.search.substring(1,W.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=D1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=vX(Z.protocol,J)),typeof Z.username=="string"&&($.username=kX(Z.username,J)),typeof Z.password=="string"&&($.password=wX(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=RX(Z.hostname,J)),typeof Z.port=="string"&&($.port=qX(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!SX($.pathname,J)){let j=W.pathname.lastIndexOf("/");j>=0&&($.pathname=D1(W.pathname.substring(0,j+1),J)+$.pathname)}$.pathname=yX($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=bX(Z.search,J)),typeof Z.hash=="string"&&($.hash=EX(Z.hash,J)),$}_(RZ,"applyInit");function wZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}_(wZ,"escapePatternString");function lX($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(lX,"escapeRegexpString");function iX($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${lX(Z.delimiter)}]+?`,j=/[$_\u200C\u200D\p{ID_Continue}]/u,Y="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){Y+=wZ(X.value);continue}Y+=`{${wZ(X.value)}}${y$(X.modifier)}`;continue}let G=X.hasCustomName(),Q=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),K=z>0?$[z-1]:null,O=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&O&&!O.prefix.length&&!O.suffix.length)if(O.type===3){let F=O.value.length>0?O.value[0]:"";Q=j.test(F)}else Q=!O.hasCustomName();if(!Q&&!X.prefix.length&&K&&K.type===3){let F=K.value[K.value.length-1];Q=Z.prefixes.includes(F)}Q&&(Y+="{"),Y+=wZ(X.prefix),G&&(Y+=`:${X.name}`),X.type===2?Y+=`(${X.value})`:X.type===1?G||(Y+=`(${W})`):X.type===0&&(!G&&(!K||K.type===3||K.modifier!==3||Q||X.prefix!=="")?Y+="*":Y+=`(${J})`),X.type===1&&G&&X.suffix.length&&j.test(X.suffix[0])&&(Y+="\\"),Y+=wZ(X.suffix),Q&&(Y+="}"),X.modifier!==3&&(Y+=y$(X.modifier))}return Y}_(iX,"partsToPattern");var k5=class{#Y;#W={};#Z={};#$={};#j={};#Q=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new uX($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let j={ignoreCase:J.ignoreCase===!0},Y={pathname:z$,protocol:z$,username:z$,password:z$,hostname:z$,port:z$,search:z$,hash:z$};this.#Y=RZ(Y,$,!0),E5(this.#Y.protocol)===this.#Y.port&&(this.#Y.port="");let z;for(z of I5){if(!(z in this.#Y))continue;let X={},G=this.#Y[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,X$),X.encodePart=S4;break;case"username":Object.assign(X,X$),X.encodePart=gX;break;case"password":Object.assign(X,X$),X.encodePart=mX;break;case"hostname":Object.assign(X,WB),A5(G)?X.encodePart=R5:X.encodePart=b5;break;case"port":Object.assign(X,X$),X.encodePart=w5;break;case"pathname":f5(this.#W.protocol)?(Object.assign(X,jB,j),X.encodePart=pX):(Object.assign(X,X$,j),X.encodePart=hX);break;case"search":Object.assign(X,X$,j),X.encodePart=cX;break;case"hash":Object.assign(X,X$,j),X.encodePart=dX;break}try{this.#j[z]=C5(G,X),this.#W[z]=x5(this.#j[z],this.#Z[z],X),this.#$[z]=iX(this.#j[z],X),this.#Q=this.#Q||this.#j[z].some((Q)=>Q.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#Y[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.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=RZ(J,$,!1):J=RZ(J,N5($,Z),!1)}catch{return!1}let W;for(W of I5)if(!this.#W[W].exec(J[W]))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=RZ(J,$,!1):J=RZ(J,N5($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let j;for(j of I5){let Y=this.#W[j].exec(J[j]);if(!Y)return null;let z={};for(let[X,G]of this.#Z[j].entries())if(typeof G=="string"||typeof G=="number"){let Q=Y[X+1];z[G]=Q}W[j]={input:J[j]??"",groups:z}}return W}static compareComponent($,Z,J){let W=_((X,G)=>{for(let Q of["type","modifier","prefix","value","suffix"]){if(X[Q]<G[Q])return-1;if(X[Q]===G[Q])continue;return 1}return 0},"comparePart"),j=new kZ(3,"","","","",3),Y=new kZ(0,"","","","",3),z=_((X,G)=>{let Q=0;for(;Q<Math.min(X.length,G.length);++Q){let K=W(X[Q],G[Q]);if(K)return K}return X.length===G.length?0:W(X[Q]??j,G[Q]??j)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#j[$],[Y]):!Z.#$[$]&&J.#$[$]?z([Y],J.#j[$]):z(Z.#j[$],J.#j[$])}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.#Q}};_(k5,"URLPattern");function E3($,Z){for(let[J,W]of Object.entries($)){let j=new k5({pathname:J});if(j.test({pathname:Z}))return{routePath:J,params:j.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var q$={startIndex:0,carriedViews:[]};function sX($,Z){let J=O0($.path,Z);return J.includes("*")?null:J}function YB($,Z){if(!$)return q$;if($.search!==Z.search)return q$;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let j=$.segments[W],Y=Z.segments[W];if(Y.alwaysRun)break;if(j.viewPath!==Y.viewPath)break;let z=sX(j,$.params),X=sX(Y,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return q$;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:j})=>j)}}function zB($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let j=`/${W.join("/")}`;return j==="/"?"/":j.replace(/\/$/,"")}function nX($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:j,to:Y}=$;if(!W)return q$;let z;try{z=new URL(W,j)}catch{return q$}if(z.origin!==j)return q$;let X=E3(Z,zB(z.pathname,J));if(!X)return q$;return YB({segments:X.route.segments,params:X.params,search:z.search},Y)}var y5="x-gemi-from";import{createElement as w1,Fragment as FG}from"react";function XB($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function A4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let j=W.viewPath;if("children"in W){Z[J]=[j];let Y=new W.children,z=A4(Y.routes);for(let[X,G]of Object.entries(z)){let Q=J==="/"?X:`${J}${X}`,K=X==="/"&&J!=="/"?J:Q;Z[K]=[j,...G]}if(Z[J].length===1)delete Z[J]}else Z[J]=[j]}else{let j=new W,Y=A4(j.routes);for(let[z,X]of Object.entries(Y)){let G=J==="/"?z:`${J}${z}`,Q=z==="/"&&J!=="/"?J:G;Z[Q]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[XB(J),W]))}function f4($,Z){let[J,W]=Z,j=$.find(([Y])=>Y===J);if(!j){$.push([J,[...W]]);return}for(let Y of W)f4(j[1],Y)}function E4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let j=W.viewPath;if(j==="__")continue;if(j==="REDIRECT")continue;if(j==="FILE")continue;if("children"in W){let Y=new W.children,z=E4(Y.routes);f4(Z,[j,z])}else f4(Z,[j,[]])}else{let j=new W,Y=E4(j.routes);for(let z of Y)f4(Z,z)}return Z}function q5($){let Z=[];for(let[J,W]of $)Z.push(J,...q5(W).flat());return Array.from(new Set(Z))}class G$ extends p{static getFacadeAccessor(){return i}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??G$.locale(),$.timeZone??G$.timeZone())}static setLocale($=G$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let j=N.getStore();if(Z.cookie!==!1)j.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return j.setLocale(W),W}}class v5{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function oX($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var GB=50;class yZ{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 j=JSON.stringify($.data)?.length??0;Z=j>=1024?`${(j/1024).toFixed(1)} kB`:`${j} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.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}"${W})\` 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 W=Z.params??{},j=new URLSearchParams(oX(Z.search??{}));j.delete("json"),j.sort();let Y=O0($,W),z=j.toString(),X=this.keyFor(Y,z),G=this.entries.get(X);if(G)return G;let Q;if(J==="render"&&this.renderStartedAt!==null){let B=Math.round(performance.now()-this.renderStartedAt);if(B>GB)Q=B}let K,O=new Promise((B)=>{K=B}),F={path:Y,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:O,source:J,startedAt:this.elapsed()};return this.entries.set(X,F),this.fetcher($,W,j).then((B)=>{F.status="resolved",F.data=B},(B)=>{F.status="rejected",F.error=B}).then(()=>{if(F.settledAt=this.elapsed(),this.maybeLogLateDiscovery(F),F.status==="rejected"&&this.failListener)this.failListener(F);if(this.settleListener)this.settleListener(F);else this.settledBacklog.push(F);K()}),F}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 R1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,j){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=j;this.name="QueryError"}}function qZ(){let $=JSON.stringify({error:p1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function g5(){return{status:403,error:{message:"Forbidden"}}}function b3($){let Z=vZ.getStore();return(J,W,j)=>{let Y=new URL($.url).origin,z=[O0(J,W),j.toString()].filter((K)=>K.length>0).join("?"),X=new Request(`${Y}/${z}`,{headers:$.headers,signal:$.signal}),G=aX($);if(G)gZ(X,G);let Q=new C(X,W);return vZ.run(Z,()=>N.run(Q,async()=>{try{let K=await T(J1).dispatchers(G).api.getRouteData(J);if(o$(K)){if(!K.ok)throw new R1(O0(J,W),j.toString(),K.status,K.body);return K.body}if(K instanceof Response){let O=await K.json().catch(()=>null);if(!K.ok)throw new R1(O0(J,W),j.toString(),K.status,O);return O}return K}catch(K){if(K instanceof R1)throw K;let O=new R1(O0(J,W),j.toString(),500,{message:K instanceof Error?K.message:String(K)});throw O.cause=K,O}}))}}var QB=new Set(["script","style","template","title"]),KB=/\shidden([\s=/]|$)/i,FB=/"[^"]*"|'[^']*'/g;function OB($){let Z=0,J=0,W=0,j=0;while(j<$.length){let Y=$.indexOf("<",j),z=Y===-1?$.length:Y;if(z>j){let O=$.slice(j,z).replace(/\s+/g,"").length;if(W>0)J+=O;else Z+=O}if(Y===-1)break;if($.startsWith("<!--",Y)){let O=$.indexOf("-->",Y+4);j=O===-1?$.length:O+3;continue}let X=$.indexOf(">",Y);if(X===-1)break;let G=$.slice(Y+1,X);j=X+1;let Q=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!Q)continue;let K=G.startsWith("/");if(!K&&QB.has(Q)&&!G.endsWith("/")){let O=$.indexOf(`</${Q}`,j);j=O===-1?$.length:O;continue}if(Q!=="div")continue;if(K){if(W>0)W-=1}else if(W>0)W+=1;else if(KB.test(G.replace(FB,'""')))W=1}return{shellChars:Z,deferredChars:J}}var DB=1000,BB=64;function UB($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function VB($,Z){if(Z.deferredChars<DB)return null;if(Z.shellChars>=BB)return null;return`[gemi] GET ${$} streams ${UB(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 rX($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let j=VB(J,W);if(!j)return;Z.add(J),$(j)}}}function tX(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),OB(Z)}}}function eX($,Z,J=1e4,W){let j=new TextEncoder,Y=()=>{};return new ReadableStream({start(z){let X=!1,G=(K)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:K})};Y=G,z.enqueue(j.encode(`${JSON.stringify($)}
14
- `)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(j.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
15
- `))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){Y(!1)}})}import{Fragment as TL,createContext as TB,createElement as ML,lazy as HL,use as IL,useContext as LL}from"react";function $G($){return{islands:[],render:$,instances:new WeakMap,count:0}}var R3="gemi-slot",ZG="data-slot",JG="data-gemi-slot";var MB=Symbol.for("gemi.staticRender"),WG=globalThis[MB]??=TB(null);import{createHash as zG}from"crypto";var m5='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';var HB="gemi-islands",fL=`'sha256-${zG("sha256").update(p5).digest("base64")}'`;function jG($,Z,J,W){if(!J)return $;let j=W?$.lastIndexOf(Z):$.indexOf(Z);return j===-1?$+J:$.slice(0,j)+J+$.slice(j)}var YG=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),EL=`'sha256-${zG("sha256").update(m5).digest("base64")}'`,IB='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',LB="gemi-static";function XG($,Z,J,W,j){let Y=new Set,z=[];if(J)z=Z.islands.map((F)=>{let B=F.module?J(F.module):void 0;if(!B)return console.error(`[gemi] island ${F.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(F.load==="eager")for(let D of B.preload)Y.add(D);return{s:B.src,e:F.export,l:F.load}});let X=z.some((F)=>F!==null);if(!X&&!j)return $;let Q=(j?`<meta name="${LB}" content="${YG(j.identity)}"${j.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...Y].map((F)=>`<link rel="modulepreload" href="${YG(F)}"/>`).join(""),K=j?m5:p5,O=(X?`<script type="application/json" id="${HB}">${I1({i:z})}</script>`:"")+`<script type="module">${W?IB+K:K}</script>`;return jG(jG($,"</head>",Q,!1),"</body>",O,!0)}function PB($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let j=J.exec($);j;j=J.exec($))if(W+=j[1]?-1:1,W===0)return J.lastIndex;return-1}function GG($){let Z=`<template ${JG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=PB($,J);if(W===-1)break;let j=J+Z.length,Y=$.slice(j,$.indexOf('"',j)),z=$.indexOf(">",j)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${R3} ${ZG}="${Y}" style="display:contents"></${R3}>`;$=$.split(G).join(`<${R3} style="display:contents">${X}</${R3}>`)}return $}function QG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function KG($,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 NB=async()=>(await import("./chunk-1jcngq6w.js")).default,h5,w3=async(...$)=>{return h5??=import("react-dom/server.browser").catch((Z)=>{throw h5=void 0,Z}),(await h5).renderToReadableStream(...$)},OG=1e4,DG="no-locale",_B=`
16
- !function(){try{var d=document.documentElement,c=d.classList;
17
- c.remove('light','dark');
18
- var e=localStorage.getItem('theme');
19
- if('system'===e||(!e&&'system'===defaultTheme)){
20
- var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
21
- if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
22
- else{d.style.colorScheme='light';c.add('light')}
23
- }else if(e){
24
- c.add(e||'')
25
- }}catch(e){}}()
26
- `;async function CB($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var u5="/assets";function xB($){return $===u5||$.startsWith(`${u5}/`)}function SB($){let Z=$.filter(xB);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${u5}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function AB($){let Z=T(J1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function c5($){let{status:Z=400,error:J,body:W,...j}=$;return new Response(W??J?.message,{...j,status:Z})}function fB($){let{status:Z=400,data:J,directive:W,headers:j}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:j,status:Z})}class k3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=rX();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=PX();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":K5};this.flatViewRoutes=x4(J),SB(Object.keys(this.flatViewRoutes)),this.routeManifest=A4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=E4(J),this.flatComponentTree=q5(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let j=this.flatViewRoutes[W].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}this.root=$.root}async passesFeatureGates($){let Z=T(c1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)b4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{v$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:j}=$,Y=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let K of J?.[Q]??[])G.add(K);return[...G].map((Q)=>w1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return Y();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(j);if(!X)X=Y(),z.byRoute.set(j,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:j,data:Y,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(j,{static:!0,layout:W.layout});z.markRenderStart();let K=d5(),O=new AbortController,F=setTimeout(()=>O.abort(),OG),B=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=$G(async(U,V)=>{let M=await w3(U,{signal:O.signal,identifierPrefix:V,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});return await M.allReady.catch(()=>{}),await new Response(M).text()});try{let U;if(W.navigation){let L=W.navigation===!0?{}:W.navigation,H=L.version?String(await J(()=>L.version(Z))):"";U={identity:[W.layout??"",$.buildId??"",H].join("|"),prefetch:L.prefetch==="none"?"none":"intent"}}let V=await w3(w1(WG.Provider,{value:D,children:w1(FG,{children:[...Q,w1(this.root,{data:Y,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:G,key:"root"})]})}),{signal:O.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});await V.allReady.catch(()=>{});let M=GG(await new Response(V).text());return new Response(XG(M,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",U),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(O.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:j,headers:Y,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:K,noStream:O,url:F,user:B,viewData:D,breadcrumbs:U,urlLocaleSegment:V,meta:M,isOgRequest:L,appId:H,features:S,staticView:f}=$,E=G.replace(`/${V}`,""),x={kind:"view",data:{meta:M,pageData:{[E]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:B},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:V,pathname:j,params:X,currentPath:G,searchParams:F.search,is404:!j?!0:!1,domain:Z.domain?AB(Z):null},appId:H,features:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},P=this.root,I=this.routeManifest[j];return async(k)=>{let{bootstrapModules:g=[],loaders:y1,getStyles:Z0,viewImportMap:o,cssManifest:y,ogMap:V0,viewModules:g$,clientEntry:m$,modulePreloadManifest:pZ,assetBase:U1,resolveIsland:p$,buildId:h$}=k,a=m$?[]:g,q3=(J0)=>[J0,`window.loaders=${y1}`,...m$?[`import(${JSON.stringify(m$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(L){let J0=null,d$=null;for(let u$ of I??[])if(typeof V0[u$]==="function")d$=u$,J0=V0[u$];if(!J0)return new Response("Not found",{status:404});let WQ=Object.values(x.data.pageData)[0];try{await w3(w1(J0,WQ[d$]),{onError:()=>{}})}catch(u$){let{fonts:jQ,...YQ}=u$.satoriOptions,zQ=await Promise.all(jQ.map((v3)=>{return CB(v3.name,v3.weight,v3.style).then((FQ)=>({...v3,data:FQ}))})),z7=new Headers(Y);z7.set("Content-Type","image/png");let[XQ,GQ]=await Promise.all([NB(),_4("Rendering an OG image")]),QQ=await XQ(u$.jsx,{...YQ,fonts:zQ}),KQ=await GQ(Buffer.from(QQ)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(KQ),{headers:z7})}return new Response("data")}if(f&&j)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:f,currentViews:I,data:x.data,serverQueries:Q,headers:Y,getStyles:Z0,viewImportMap:o,viewModules:g$,resolveIsland:p$,buildId:h$});if(x.data.cssManifest=y,x.data.modulePreloadManifest=pZ??{},U1&&U1!=="/")x.data.assetBase=U1;let h4=this.modulePreloadLinks({clientEntry:m$,modulePreloadManifest:pZ,views:I??["404"],routeKey:j??"404"}),c$=await Z0(I);x.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let V1=new AbortController,hZ=setTimeout(()=>V1.abort(),OG),T1=W6(K)||O,b=Bun.env.NODE_ENV!=="production"&&!T1&&j&&this.shellReporter.shouldObserve(j)?tX():null,h0=d5();try{let J0=await w3(w1(FG,{children:[...h4,...c$,w1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:_B}}),w1(P,{data:x.data,viewImportMap:o,viewModules:g$,serverQueries:Q,dictionarySink:h0,key:"root"})]}),{bootstrapScriptContent:q3(`window.__GEMI_DATA__ = ${I1(x.data)}`),bootstrapModules:a,signal:V1.signal,...T1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(d$){if(Bun.env.NODE_ENV!=="production")console.error(d$)}});if(J0.allReady.catch(()=>{}).finally(()=>clearTimeout(hZ)),T1)await J0.allReady.catch(()=>{});return new Response(NJ(J0,Q,{onShell:T1?void 0:()=>Q.markShell(),onChunk:b?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(V1.signal.aborted)),b)this.shellReporter.report(j,b.measure())})},h0),{status:!j?$.refusedStatus??404:200,headers:Y})}catch(J0){if(clearTimeout(hZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(V1.signal.aborted))),J0;let d$=await w3(w1("div"),{bootstrapScriptContent:q3(`window.error= ${I1(J0.message)}; window.stack_trace=${I1(J0.stack)};window.__GEMI_DATA__ = ${I1(x.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...a]:a});return new Response(NJ(d$,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(V1.signal.aborted)))}),{status:!j?$.refusedStatus??404:200,headers:Y})}}}viewRefusalStatus($,Z,J){if(K$(Z))return 404;if(Z?.kind===g1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(m1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof R1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),j=J.pathname.endsWith(".og"),Y=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=Y.split("/"),G=Y,Q=null,K=null,O=T(i),F=E3(this.flatViewRoutes,Y),B=O.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(DG);if(B&&O.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,K=z;if(B&&!j&&K===null&&!(K===null&&F!==null)){let P=BG(z,O.supportedLocales,O.defaultLocale);if(P){let I=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${P}${I}${W?".json":""}${J.search}`}})}}if(B&&!j){let P=T(i).detectLocale(new C($,{},"view",G));if(K===null&&P!==O.defaultLocale){let I=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${P}${I}${J.search}`}})}}G=G.replace("//","/");let U=[],V=[],M=null,L={},H=null,S=!1,f=[],E;try{let P=E3(this.flatViewRoutes,G);if(K&&P?.route.middleware.includes(DG))P=null;if(P){if(M=P.routePath,L=P.params,U=P.route.exec,V=P.route.middleware,f=P.route.features,S=V.includes("no-stream"),E=P.route.static,W&&this.partialRendering){let I=$.headers.get(y5),k=nX({flatViewRoutes:this.flatViewRoutes,supportedLocales:T(i).supportedLocales,from:I,origin:J.origin,to:{segments:P.route.segments,params:L,search:J.search}});if(k.startIndex>0)U=U.slice(k.startIndex),H={from:I,carriedViews:k.carriedViews}}}}catch(P){throw P}if(E&&W)return new Response("Not found",{status:404});let x=new C($,L,"view",M);return this.hooks.onRequestStart(x),await N.run(x,async()=>{let P=null,I=N.getStore(),k=vZ.getStore(),g=(y)=>vZ.run(k,()=>N.runWith(I,y));I.serverQueries=new yZ(b3($));let y1=new Set;I.serverQueries.onQueryFail((y)=>{y1.add(y.error);try{g(()=>Promise.resolve(this.hooks.onRequestFail(o,y.error)).catch(()=>{}))}catch{}});let Z0=QG(E);if(K){let y=K.replaceAll("/","");G$.setLocale(y,{cookie:Z0.locale})}else if(O.isLocaleAware&&!B)I.setLocale(O.defaultLocale);else G$.setLocale(void 0,{cookie:Z0.locale});let o=I.req;if(Z0.session)b4();try{let y=null;try{await T(v1).runMiddleware(V)}catch(b){if(y=this.viewRefusalStatus(o,b,y1),y===null)throw b}if(y!==null||f.length>0&&!await this.passesFeatureGates(f))M=null,U=[],o.routePath="";let V0=T(i),g$=V0.isEnabled,m$=V0.isLocaleAware,pZ=new C($,o.params),U1={defaultLocale:V0.defaultLocale,timeZone:V0.detectTimeZone(pZ)};if(m$){let b=null;if(K)b=K.replaceAll("/",""),I.setLocale(b);else if(!B)b=I.locale??V0.defaultLocale;else b=V0.detectLocale(pZ),I.setLocale(b);let h0=g$?V0.getPageTranslations(b,o.routePath):{};U1={...U1,supportedLocales:V0.supportedLocales,currentLocale:b,dictionary:{[b]:h0},defaultLocale:V0.defaultLocale,...B?{}:{localeRouting:"off"}}}await UG(U1.currentLocale??"");let p$;try{p$=await Promise.all(U.map((b)=>b(o)))}catch(b){if(y=this.viewRefusalStatus(o,b,y1),y===null)throw b;M=null,U=[],o.routePath="",p$=[]}let{cookies:h$,headers:a}=I;if(y!==null)a.set("Cache-Control","no-store");P={data:p$,cookies:h$,headers:a,user:I.user,prefetchedData:I.serverQueries.snapshotResolved(),currentPathName:M,params:o.params,urlLocaleSegment:Q,meta:I.renderMeta(),appId:T(v5).id,features:await T(c1).forClient()};let{params:q3,user:h4}=P,c$={},V1={};for(let b of p$??[]){let[h0,J0]=Object.entries(b)?.[0]??[];if(!h0||!J0)continue;V1[`${h0}:${M}`]=J0.breadcrumb,c$[h0]=J0}let hZ=c$.FILE;if(hZ){for(let b of h$)a.append("Set-Cookie",b.toString());try{await this.onRequestEnd(o)}catch(b){v$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await ZJ(hZ,a)}if(W){a.set("Content-Type","application/x-ndjson; charset=utf-8"),a.append("Vary",y5),h$.forEach((h0)=>a.append("Set-Cookie",h0.toString())),await this.hooks.onRequestEnd(o);let b={meta:H&&!I.metadata.touched?null:P.meta,data:{[G]:c$},breadcrumbs:V1,prefetchedData:I.serverQueries.snapshotResolved(),i18n:U1,features:P.features,is404:!M,appId:P.appId,partial:H};return new Response(eX(b,I.serverQueries,void 0,({aborted:h0})=>g(()=>this.completeStream(o,I.serverQueries.summarize(h0)))),{headers:a})}if(a.set("Content-Type","text/html; charset=utf-8"),!S&&!(E&&M))a.append("Vary","User-Agent");let T1=Boolean(E&&M);if(!T1||Z0.session)b4();for(let b of h$)a.append("Set-Cookie",b.toString());if(!T1||Z0.csrf){let b=Bun.CSRF.generate(process.env.SECRET);a.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(o,{mintSession:!T1||Z0.session})}catch(b){v$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(T1)KG(a,E);return await this.render({req:o,runInRequestScope:g,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:a,i18n:U1,params:q3,pathname:J.pathname,serverQueries:I.serverQueries,userAgent:$.headers.get("user-agent"),noStream:S,url:J,user:h4,viewData:c$,breadcrumbs:V1,urlLocaleSegment:Q,meta:P.meta,appId:P.appId,features:P.features,isOgRequest:j,staticView:M?E:void 0,refusedStatus:y??void 0})}catch(y){if(y.kind===g1){let V0=W?fB(y.payload.viewData??y.payload.api):c5(y.payload.view);for(let g$ of I.cookies)V0.headers.append("Set-Cookie",g$.toString());return V0}if(!y1.has(y))this.hooks.onRequestFail(o,y);if(m1(y))return console.error(y),W?qZ():c5(g5());if(y instanceof R1&&y.status===403)return W?qZ():c5(g5());throw y}},Z)}}function l5(){let $=JSON.stringify({error:p1("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 IG extends b0{routes={"/api-routes":this.get(()=>{let $=T(w4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[j,Y]of Object.entries(W)){let{exec:z,middleware:X}=Y;Z.push({path:J,method:j,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=T(k3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:j}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:j,middleware:W});return Z})}}var EB=new Set([q1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),bB=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,RB=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function wB($,Z,J,W){for(let[j,Y]of Object.entries(J.headers??{})){if(Y===void 0||Y===null)continue;let z=j.toLowerCase();if(EB.has(z)||z.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.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(j,Y)}for(let[j,Y]of Object.entries(J.cookies??{})){if(Y===void 0||Y===null)continue;if(j===q1)throw Error(`dispatchAs: credentials may not set the "${q1}" cookie. The access token stays the initiator's.`);if(!bB.test(j)||!RB.test(Y))throw Error(`dispatchAs: "${j}" is not a cookie a Cookie header can carry.`);Z.push(`${j}=${Y}`)}}function kB($,Z){let J=$.body.getReader(),W=!1,j=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},Y=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){j(),z.error(G);return}if(X.done){j();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{j()}}},{highWaterMark:0});return new Response(Y,{status:$.status,statusText:$.statusText,headers:$.headers})}function VG($){let{status:Z=400,data:J,headers:W}=$,j=new Headers({"Content-Type":"application/json",...W});if(!j.has("Cache-Control"))j.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:j})}function TG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let j=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&j.length===0)return $;let Y=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of j)z.append("Set-Cookie",X)};try{return Y($.headers),$}catch{let z=new Headers($.headers);return Y(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class w4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=LX();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=T5({"/":$.rootRouter,"/auth":F5,"/__gemi__/services/i18n":O5,"/__gemi__/services/logs":V5,"/__gemi__/services/image":U5,"/__gemi__/debug":IG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=HG(Z.pathname),W={},j;for(let[Y]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:Y});if(z.test({pathname:J})){j=Y,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:j}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await T(v1).runMiddleware(W)}catch(j){if(j.kind===g1)return VG(j.payload.api);else{if(K$(j))return l5();if(this.onRequestFail(Z,j),console.error(j),m1(j))return qZ();throw j}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),j={};try{j=await W()}catch(Y){if(Y.kind===g1)return VG(Y.payload.api);if(K$(Y))return l5();if(this.onRequestFail(J.req,Y),console.error(Y),m1(Y))return qZ();throw Y}return j}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(j){v$.error(j?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(j)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((j)=>{console.error(j)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),j=this.flatRoutes[W];if(!j||!j[$.method])return new Response(JSON.stringify({error:p1("not_found","Not found",404)}),{status:404});let Y=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(Y);return await N.run(Y,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,Y,W)};try{let Q=T(i);if(Q.isEnabled){let U=Q.detectLocale(Y);z.setLocale(U)}z.setRequest(Y),T(v1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,Y);if(K instanceof Response){let U=TG(K,z.headers,z.cookies);return await G(),U}let O=await this.getRouteData(W),F=z.headers,B=z.cookies;if(O instanceof Response){let U=TG(O,F,B);if(this.isOpenEndedBody($,U)){let V=kB(U,()=>this.endRequest(z,Y,W));return X=!0,V}return await G(),U}let D=(o$(O)?O:F$.json(O)).toResponse(F,B);return await G(),D}catch(Q){if(!X)try{await G()}catch(K){console.error(K)}throw Q}},Z)}async dispatchAs($,Z,J,W,j){let Y=new URL($.rawRequest.url).origin,z=new URL(`${Y}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==Y||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=j?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,K=[],O=G?null:$.cookies.get(q1);if(O)K.push(`${q1}=${O}`);if(j?.credentials)wB(Q,K,j.credentials,G!==void 0);if(K.length>0)Q.set("Cookie",K.join("; "));let F=G?null:$.headers.get(q1);if(F)Q.set(q1,F);let B=$.headers.get("User-Agent");if(B)Q.set("User-Agent",B);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let U=new Request(z,{method:Z,headers:Q,body:D,...j?.signal?{signal:j.signal}:{}});if(MG(U,r$($),G?.grant,j?.progress),$.domain)gZ(U,$.domain);let V=G?{user:G.user}:void 0;return N.exit(()=>u3.exit(()=>this.handleApiRequest(U,V)))}}import{timingSafeEqual as yB}from"crypto";var y4="",n5="*",qB=60000,vB=1e4,i5=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,k4=16,LG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s5="x-forwarded-host";function PG($){return $.startsWith(":")}function o5($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&yB(J,W)}function gB($){if(!$)return null;if($===!0)return{header:s5,secret:null};return{header:($.hostHeader??s5).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function mB($){if(!$||$===!0)return;let{hostHeader:Z,secret:J}=$;if(Z!==void 0&&(typeof Z!=="string"||!LG.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"||!LG.test(J.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${J.header}".`);if(J.header.toLowerCase()===(Z??s5).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<k4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${k4} characters. A guessable one lets any client name its own host.`)}function B1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function pB($){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 hB($){let Z=B1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((Y)=>i5.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<k4)throw Error(`\`route.domains.ask.secret\` must be at least ${k4} characters. A guessable one is worse than leaving \`ask\` out.`);mB($.trustProxy);let W=new Set,j=null;for(let Y of $.groups??[]){let{subdomain:z}=Y;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),PG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(j)throw Error(`\`route.domains\` declares two param subdomains, "${j.subdomain}" and "${z}"; a host could match either.`);j=Y;continue}if(Y.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>i5.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&j&&!j.exists)throw Error(`\`route.domains.ask\` is set, so "${j.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class a5{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){hB($),this.root=B1($.root),this.hostTrust=gB($.trustProxy);for(let Z of $.groups??[])if(PG(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??qB,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!o5($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return B1(this.forwardedHost($))??B1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),j=this.forwardedHost($),Y=j&&B1(j)?pB(j):null;return`${W}://${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:n5,params:{},custom:!0};return null}async allows($,Z){let J=B1($);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:y4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),j=this.fixed.get(W);if(j)return{host:$,group:j.subdomain,params:{},custom:!1};if(this.param&&i5.test(W)){let Y={[this.param.name]:W};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 W=this.inFlight.get($);if(W)return W;let j=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,j);let Y;try{Y=await j}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=vB)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=B1($);if(Z)this.cache.delete(Z)}}}var cB="/__gemi__/domains/ask";class J1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(y4,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new a5(J);let W=(j)=>({api:j.api?new w4({...Z.api,...j.api}):$.api,view:j.view?new k3({...Z.view,...j.view}):$.view});for(let j of J.groups??[])this.groups.set(j.subdomain,W(j));if(J.custom?.fallback)this.groups.set(n5,W(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)NG($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return gZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==cB)return null;if(!o5(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??y4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function q4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var _G=600000;function CG($,Z){return[t3($,Z),t3($,Z-1)]}class A{static token="auth";config;provider;constructor($={},Z=new AJ){S9($.oauthProviders),this.config={...EZ(A9($),$),emailCode:PJ($.emailCode)},this.provider=Z}async oauthProvider($){return await WZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await c9(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=T().bound(J1)?T(J1).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"?T(J1).resolver?.root:B1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??B1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!VJ($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),j=q4(J.expiresAt),Y=q4(J.absoluteExpiresAt);if(j<=W||Y<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let j=Date.now(),Y=Math.floor(j/_G),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=t3($,Y),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:K,userAgent:Z,...this.freshLifetime(j)}),!0}))z=Q}if(!z){for(let Q of CG($,Y))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(VJ($)||!this.config.migrateLegacySession){let j=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),j}let J=Math.floor(Date.now()/_G),W=CG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let j=await this.userProvider.findSession({token:$,userAgent:Z});for(let Y of W){if(j?.user)break;j=await this.userProvider.findSession({token:Y,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let Y of W)await this.userProvider.deleteSession({token:Y});return j})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),j=await this.userProvider.updateSession({token:$.token,expiresAt:W}),Y=this.requestCarryingCookie($.token);if(Y)Y.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(Y,W));if(!j)return $;return{...$,expiresAt:j.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new O$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),j=U9(J),Y=await this.userProvider.createSessionV2({token:j,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:j,userAgent:W??""});return z?.user?z:Y}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),W=await this.config.generateCode($),j=typeof W==="string"&&W!==""?W:P9(Z);return await this.userProvider.createMagicLinkToken({email:$,token:e3("link",$,J),pin:e3("pin",$,j)}),{email:$,pin:j,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:j}=this.config.emailCode,Y=await this.userProvider.findMagicLinkTokenByEmail($);if(!Y)return nZ("pin",$,null,Z),{status:"invalid"};let z=q4(Y.createdAt);if(z+W*60000<=Date.now())return nZ("pin",$,null,Z),{status:"expired"};if(!await C9(Y.id,z,j,W))return await this.userProvider.claimMagicLinkToken(Y.id),{status:"too_many_attempts"};if(!nZ("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($),W=nZ("link",$,J?.token,Z);if(!J||!W)return!1;if(q4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class R0 extends p{static getFacadeAccessor(){return A}static async user(){let $=await R0.userOrNull();if($)return $;throw new O$({redirectTo:l3(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await h3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return j1(Z?.search.get(W1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await R0.user();if(!await $(Z))throw new t$}static async guardSafe($){let Z=await R0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class v4{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new yZ(b3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=v4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){v4.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new yZ(b3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function xG($,Z,J="/"){let W=new URL($.origin),j=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,Y=new URL(J.startsWith("/")?J:`/${J}`,W),z=dB(j);if(!z)throw Error(`"${j}" 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 dB($){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 SG{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 W=T(J1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let j=N.getStore()?.req?.rawRequest,Y=j?W.publicOrigin(j):process.env.HOST_NAME;if(!Y)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` for the protocol.");return xG({root:W.root,origin:Y},$,O0(String(Z),J[0]??{}))}}class AG{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static fonts($){N.getStore().metadata.fonts($)}}var uB={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class k1 extends p{static getFacadeAccessor(){return fG}static get client(){return this.getFacadeRoot().client}static get($){return k1.client.get($)}static set($,Z){return k1.client.set($,Z)}static del(...$){return k1.client.del(...$)}static exists($){return k1.client.exists($)}static incr($){return k1.client.incr($)}static expire($,Z){return k1.client.expire($,Z)}static ttl($){return k1.client.ttl($)}}class EG extends p{static getFacadeAccessor(){return Y1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class RG extends p{static getFacadeAccessor(){return bG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class kG extends p{static getFacadeAccessor(){return wG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class yG extends p{static getFacadeAccessor(){return f3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function oN($){return $}function qG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function g4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function r5($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,j]of J){let Y=Number(j);if(j!==""&&Number.isSafeInteger(Y)&&Y>=0)Z.set(W,Y)}return Z}var{SQL:lB}=globalThis.Bun;function iB(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var sB=async($)=>{let Z=new lB($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,j)=>Z.listen(J,W,j),close:()=>Z.close({timeout:1})}},nB=async($)=>{let Z;try{Z=(await import("./chunk-6q6bhkyf.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,j,Y)=>J.listen(W,j,Y),close:()=>J.end({timeout:1}).catch(()=>{})}},vG=($)=>iB()?sB($):nB($);var oB=/^[A-Za-z_][A-Za-z0-9_]*$/;class t5{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",j=Z.notifyChannel??"gemi_changes";for(let z of[J,W,j])if(!oB.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=W,this.notifyChannel=j,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=Y,this.listener=Z.listener??vG}async createTable(){for(let $ of aB(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let j=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return j();let Y=this.sqliteTurn.then(j);return this.sqliteTurn=Y.catch(()=>{}),Y}let W=this.append(J,$,Z);return gG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),j=$.unsafe(`"${this.entriesTable}"`),[Y]=await $`
27
- INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
28
- ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
29
- RETURNING seq
30
- `,z=Number(Y.seq);if(await $`
31
- INSERT INTO ${j} (channel, seq, data, created_at)
32
- VALUES (${Z}, ${z}, ${JSON.stringify(J??null)}, ${Date.now()})
33
- `,z>this.retain)await $`DELETE FROM ${j} 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((j)=>[j,0]));if($.length===0)return Z;let J=this.sql,W=await J`
34
- SELECT channel, seq FROM ${J.unsafe(`"${this.headsTable}"`)}
35
- WHERE channel IN ${J([...$])}
36
- `;for(let j of W)Z.set(j.channel,Number(j.seq));return Z}async read($,Z,J){let W=this.sql,[j]=await W`
37
- SELECT seq FROM ${W.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
38
- `,Y=j?Number(j.seq):0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(Z===Y)return{entries:[],head:Y,gap:!1};let z=await W`
39
- SELECT seq, data FROM ${W.unsafe(`"${this.entriesTable}"`)}
40
- WHERE channel = ${$} AND seq > ${Z}
41
- ORDER BY seq
42
- LIMIT ${J}
43
- `;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:Y,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:Y,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let j=W.indexOf(" "),Y=Number(W.slice(0,j));if(j>0&&Number.isInteger(Y))$(W.slice(j+1),Y)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=L1();if($===void 0||U$()!==this.connection)return;return $}}function aB($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
44
- "channel" TEXT NOT NULL PRIMARY KEY,
45
- "seq" BIGINT NOT NULL
46
- )`,`CREATE TABLE IF NOT EXISTS "${Z}" (
47
- "channel" TEXT NOT NULL,
48
- "seq" BIGINT NOT NULL,
49
- "data" TEXT NOT NULL,
50
- "created_at" BIGINT NOT NULL,
51
- PRIMARY KEY ("channel", "seq")
52
- )`]}class e5{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 W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),j=W?.head??0;if(Z>j)return{entries:[],head:j,gap:!0};if(!W||Z===j)return{entries:[],head:j,gap:!1};let Y=W.entries[0]?.seq??j+1;if(Y>Z+1)return{entries:[],head:j,gap:!0};let z=Z+1-Y;return{entries:W.entries.slice(z,z+J),head:j,gap:!1}}}var dG=new TextEncoder;function mG($,Z){return dG.encode(`id: ${$}
53
- data: ${JSON.stringify(Z)}
54
-
55
- `)}function uG($,Z,J,W){let j=Z instanceof Request?Z:Z.rawRequest,Y=W.cursor??j.headers.get("Last-Event-ID")??new URL(j.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:Y,signal:j.signal})}catch(F){if(!(F instanceof m4))throw F;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,G=!1,Q=!1,K=(F)=>{if(X)clearInterval(X);if(X=null,z.close(),Q)return;Q=!0;try{F.close()}catch{}},O=new ReadableStream({start(F){X=setInterval(()=>{if(cG())return K(F);try{F.enqueue(dG.encode(pG))}catch{K(F)}},$.config.keepaliveInterval)},async pull(F){try{if(!G){if(await z.ready(),G=!0,!Q)F.enqueue(mG(z.cursor,{type:"ready"}));return}let B=await z.next();if(B.done||Q)return K(F);F.enqueue(mG(z.cursor,B.value))}catch(B){if(!Q)console.error("[gemi] A change feed stream failed.",B);K(F)}},cancel(){if(Q=!0,X)clearInterval(X);X=null,z.close()}});return new Response(O,{headers:hG()})}var lG=255,iG=500,rB=30000;class m4 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class J7{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=iG;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=EZ(qG(),$),this.driver=eB(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){Z7($);let J=Z===void 0?null:Z;if(L1()!==void 0&&!this.driver.joinsTransaction?.())return fZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return fZ(()=>this.wake($,W)),W}async head($){return Z7($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=$7($);return g4(await this.driver.heads(Z))}subscribe($,Z={}){let J=$7($);if(this.all.size>=this.config.maxSubscriptions)throw new m4(this.config.maxSubscriptions);let W=new sG(this,J,tB(Z.cursor),this.config,Z.signal);this.all.add(W);for(let j of J){let Y=this.followers.get(j);if(!Y)this.followers.set(j,Y=new Set);Y.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return uG(this,$,$7(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[W,j]of J)this.wake(W,j)}}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=iG,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,rB)}}}class sG{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,W,j){this.manager=$;this.config=W;this.signal=j;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(j?.aborted)this.close();else j?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return g4(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 W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),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:W,head:j,gap:Y}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(Y){this.readTo.set($,j),this.pending.push({type:"reset",channel:$,seq:j});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function Z7($){if(typeof $!=="string"||$===""||$.length>lG)throw Error(`A change feed channel is a string of 1 to ${lG} characters; got ${JSON.stringify($)}.`)}function $7($){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)Z7(J);return Z}function tB($){if($===void 0||$===null)return new Map;if(typeof $==="string")return r5($);let Z=$ instanceof Map?[...$]:Object.entries($);return r5(g4(new Map(Z)))}function eB($,Z){if($==="memory")return new e5;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 t5(Z.make(V$));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 nG extends p{static getFacadeAccessor(){return J7}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 y3 extends m0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(m0)?$.make(m0):void 0;if(Z instanceof y3)return Z;let J=new y3($,Z);return $.instance(m0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(m0,this.previous);return}this.application.forget(m0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${W7($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${W7($,Z,J)} not to have been broadcast, but it was broadcast ${j7(W.length)}: ${Y7(W)}.`)}assertSentTimes($,Z,J,W){let j=this.matching($,J,W);if(j.length===Z)return;throw Error(`Expected ${W7($,J,W)} to have been broadcast ${j7(Z)}, but it was broadcast ${j7(j.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${Y7(this.sent)}.`)}matching($,Z,J){return s$($),this.sent.filter((W)=>(W.pattern===$||N7($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${Y7(this.sent)}.`}}function W7($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function j7($){return`${$} ${$===1?"time":"times"}`}function Y7($){return $.map((Z)=>`${Z.topic} ${Z.event}(${$U(Z.data)})`).join(", ")}function $U($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class oG extends p{static getFacadeAccessor(){return m0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return y3.install(T())}}class aG extends p{static getFacadeAccessor(){return c1}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 p4{bound;constructor($){this.bound=$}get name(){return this.bound??U$()}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 eG(J.sql,(W)=>rG(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-j10a0m7q.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:j}=ZQ($,$Q(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,j)}handle(){let $=L1();if($===void 0)return;return U$()===this.name?$:void 0}connection($=this.name){return tG($),T(V$).connection($)}}var mZ=new p4;class JQ extends p{static getFacadeAccessor(){return V$}static connection($){return new p4($)}static get sql(){return mZ.sql}static get dialect(){return mZ.dialect}static query($){return mZ.query($)}static execute($){return mZ.execute($)}static transaction($){return mZ.transaction($)}static schema(){return mZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as Md,cZ as Nd,l4 as Od,i$ as Pd,uZ as Qd,b0 as Rd,h3 as Sd,UJ as Td,VJ as Ud,U9 as Vd,h1 as Wd,Y1 as Xd,r as Yd,s7 as Zd,r$ as _d,V9 as $d,T9 as ae,MJ as be,HJ as ce,e3 as de,nZ as ee,CK as fe,UM as ge,A9 as he,y9 as ie,_J as je,q9 as ke,v9 as le,wK as me,g9 as ne,CJ as oe,qK as pe,vK as qe,xJ as re,m9 as se,p9 as te,c1 as ue,h9 as ve,hK as we,AJ as xe,WJ as ye,i3 as ze,M1 as Ae,F$ as Be,bQ as Ce,ZJ as De,H1 as Ee,G$ as Fe,v4 as Ge,SG as He,AG as Ie,uB as Je,k1 as Ke,EG as Le,RG as Me,kG as Ne,yG as Oe,oN as Pe,qG as Qe,g4 as Re,r5 as Se,t5 as Te,e5 as Ue,m4 as Ve,J7 as We,sG as Xe,nG as Ye,h as Ze,lZ as _e,tM as $e,e8 as af,eM as bf,$H as cf,WH as df,sz as ef,Z5 as ff,az as gf,GH as hf,ez as if,m0 as jf,x3 as kf,$X as lf,oG as mf,aG as nf,p4 as of,JQ as pf,W5 as qf,gD as rf,D5 as sf,B5 as tf,TI as uf,MX as vf,HX as wf,c3 as xf,v1 as yf,SI as zf,LX as Af,PX as Bf,v5 as Cf,qZ as Df,g5 as Ef,fL as Ff,EL as Gf,u5 as Hf,xB as If,c5 as Jf,fB as Kf,k3 as Lf,l5 as Mf,VG as Nf,TG as Of,w4 as Pf,J1 as Qf,A as Rf,R0 as Sf,d3 as Tf,A7 as Uf,CQ as Vf,C7 as Wf,E7 as Xf,r4 as Yf,t4 as Zf,e4 as _f,b7 as $f,RQ as ag,wQ as bg,g7 as cg,p7 as dg,c7 as eg,o7 as fg,a7 as gg,r7 as hg,zJ as ig,mQ as jg,Y0 as kg,G9 as lg,$Z as mg,D9 as ng};
56
-
57
- //# debugId=EC91E57CC0E9295864756E2164756E21