gemi 0.166.1 → 0.168.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 (210) hide show
  1. package/dist/ai/Agent.d.ts +3 -5
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +16 -2
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/Prompt.d.ts +15 -1
  6. package/dist/ai/Prompt.d.ts.map +1 -1
  7. package/dist/ai/index.d.ts +1 -1
  8. package/dist/ai/index.d.ts.map +1 -1
  9. package/dist/ai/index.js +32 -32
  10. package/dist/ai/index.js.map +4 -4
  11. package/dist/app/index.js +1 -1
  12. package/dist/bin/gemi.js +405 -376
  13. package/dist/bin/gemi.js.map +5 -4
  14. package/dist/bun/plugin.js +1 -1
  15. package/dist/bun/preload.js +1 -1
  16. package/dist/{chunk-eyv6hss6.js → chunk-0q65jzhv.js} +2 -2
  17. package/dist/{chunk-eyv6hss6.js.map → chunk-0q65jzhv.js.map} +1 -1
  18. package/dist/{chunk-p3qbym3v.js → chunk-0wet87jm.js} +2 -2
  19. package/dist/{chunk-p3qbym3v.js.map → chunk-0wet87jm.js.map} +1 -1
  20. package/dist/{chunk-4fzevafk.js → chunk-0wk992a5.js} +2 -2
  21. package/dist/{chunk-4fzevafk.js.map → chunk-0wk992a5.js.map} +1 -1
  22. package/dist/{chunk-q4vtjdea.js → chunk-17272ccy.js} +3 -3
  23. package/dist/{chunk-q4vtjdea.js.map → chunk-17272ccy.js.map} +1 -1
  24. package/dist/{chunk-w4at2d5d.js → chunk-1h6g1hkg.js} +2 -2
  25. package/dist/{chunk-w4at2d5d.js.map → chunk-1h6g1hkg.js.map} +1 -1
  26. package/dist/{chunk-hdt8cwsv.js → chunk-21hppqtb.js} +2 -2
  27. package/dist/{chunk-hdt8cwsv.js.map → chunk-21hppqtb.js.map} +1 -1
  28. package/dist/{chunk-qec3g4w3.js → chunk-2v7wq01w.js} +2 -2
  29. package/dist/{chunk-qec3g4w3.js.map → chunk-2v7wq01w.js.map} +1 -1
  30. package/dist/{chunk-qeayzybn.js → chunk-2xtkh8bh.js} +19 -19
  31. package/dist/{chunk-qeayzybn.js.map → chunk-2xtkh8bh.js.map} +3 -3
  32. package/dist/{chunk-0hfvwzd1.js → chunk-31np60bx.js} +2 -2
  33. package/dist/{chunk-0hfvwzd1.js.map → chunk-31np60bx.js.map} +1 -1
  34. package/dist/{chunk-mbkje42z.js → chunk-3682hkq0.js} +2 -2
  35. package/dist/{chunk-mbkje42z.js.map → chunk-3682hkq0.js.map} +1 -1
  36. package/dist/{chunk-fnj2hc5v.js → chunk-3rp908gn.js} +1 -1
  37. package/dist/{chunk-3xj1e3ns.js → chunk-44y62yav.js} +3 -3
  38. package/dist/{chunk-3xj1e3ns.js.map → chunk-44y62yav.js.map} +1 -1
  39. package/dist/{chunk-c3cdj9y7.js → chunk-4mtqbcc5.js} +2 -2
  40. package/dist/{chunk-c3cdj9y7.js.map → chunk-4mtqbcc5.js.map} +1 -1
  41. package/dist/{chunk-80703vks.js → chunk-4qpyz627.js} +2 -2
  42. package/dist/{chunk-80703vks.js.map → chunk-4qpyz627.js.map} +1 -1
  43. package/dist/{chunk-4rnpvajg.js → chunk-4tt14jnx.js} +2 -2
  44. package/dist/{chunk-4rnpvajg.js.map → chunk-4tt14jnx.js.map} +1 -1
  45. package/dist/{chunk-efjk5aq7.js → chunk-5n21z4n8.js} +2 -2
  46. package/dist/{chunk-efjk5aq7.js.map → chunk-5n21z4n8.js.map} +1 -1
  47. package/dist/{chunk-pk4drzc9.js → chunk-5nz46dyw.js} +2 -2
  48. package/dist/{chunk-pk4drzc9.js.map → chunk-5nz46dyw.js.map} +1 -1
  49. package/dist/{chunk-6tbs7yc1.js → chunk-6t1t7h05.js} +2 -2
  50. package/dist/{chunk-6tbs7yc1.js.map → chunk-6t1t7h05.js.map} +1 -1
  51. package/dist/{chunk-tms2g9at.js → chunk-777v6242.js} +1 -1
  52. package/dist/{chunk-kcgnjzqr.js → chunk-8b9ks729.js} +3 -3
  53. package/dist/{chunk-kcgnjzqr.js.map → chunk-8b9ks729.js.map} +1 -1
  54. package/dist/{chunk-8f4jkpv7.js → chunk-8hfyscnn.js} +1 -1
  55. package/dist/{chunk-4587ab6m.js → chunk-978pc27j.js} +2 -2
  56. package/dist/{chunk-4587ab6m.js.map → chunk-978pc27j.js.map} +1 -1
  57. package/dist/{chunk-y1ks8ahw.js → chunk-9aj6eavs.js} +2 -2
  58. package/dist/{chunk-y1ks8ahw.js.map → chunk-9aj6eavs.js.map} +1 -1
  59. package/dist/{chunk-xw5d66ec.js → chunk-9akefv1y.js} +2 -2
  60. package/dist/{chunk-xw5d66ec.js.map → chunk-9akefv1y.js.map} +1 -1
  61. package/dist/{chunk-y6x52vkb.js → chunk-9ft0ayhf.js} +2 -2
  62. package/dist/{chunk-y6x52vkb.js.map → chunk-9ft0ayhf.js.map} +1 -1
  63. package/dist/{chunk-m5hd632w.js → chunk-9wcv7e1a.js} +2 -2
  64. package/dist/{chunk-h5whhrds.js.map → chunk-9wcv7e1a.js.map} +1 -1
  65. package/dist/{chunk-8rnvw8xr.js → chunk-a053eza0.js} +2 -2
  66. package/dist/{chunk-8rnvw8xr.js.map → chunk-a053eza0.js.map} +1 -1
  67. package/dist/{chunk-c0dvdfm0.js → chunk-a9frf7ym.js} +2 -2
  68. package/dist/{chunk-c0dvdfm0.js.map → chunk-a9frf7ym.js.map} +1 -1
  69. package/dist/{chunk-2jk0f4sj.js → chunk-aj1jrwwh.js} +2 -2
  70. package/dist/{chunk-2jk0f4sj.js.map → chunk-aj1jrwwh.js.map} +1 -1
  71. package/dist/{chunk-h11r8h31.js → chunk-bb3fdgwt.js} +11 -11
  72. package/dist/{chunk-h11r8h31.js.map → chunk-bb3fdgwt.js.map} +3 -3
  73. package/dist/{chunk-36yp8364.js → chunk-c46vhvk4.js} +2 -2
  74. package/dist/{chunk-36yp8364.js.map → chunk-c46vhvk4.js.map} +1 -1
  75. package/dist/{chunk-5x9b1ema.js → chunk-df2zeevj.js} +2 -2
  76. package/dist/{chunk-5x9b1ema.js.map → chunk-df2zeevj.js.map} +1 -1
  77. package/dist/{chunk-ndyafsv6.js → chunk-drwjwtmj.js} +2 -2
  78. package/dist/{chunk-ndyafsv6.js.map → chunk-drwjwtmj.js.map} +1 -1
  79. package/dist/{chunk-wypncj52.js → chunk-ecdjbd2w.js} +3 -3
  80. package/dist/{chunk-wypncj52.js.map → chunk-ecdjbd2w.js.map} +1 -1
  81. package/dist/{chunk-6cw6tn57.js → chunk-embwksec.js} +2 -2
  82. package/dist/{chunk-6cw6tn57.js.map → chunk-embwksec.js.map} +1 -1
  83. package/dist/{chunk-fdfy25mv.js → chunk-esjt9q54.js} +2 -2
  84. package/dist/{chunk-fdfy25mv.js.map → chunk-esjt9q54.js.map} +1 -1
  85. package/dist/chunk-f4nanvkm.js +5 -0
  86. package/dist/{chunk-8v6y52et.js.map → chunk-f4nanvkm.js.map} +1 -1
  87. package/dist/{chunk-b8qfypzq.js → chunk-fb77hwk0.js} +3 -3
  88. package/dist/{chunk-b8qfypzq.js.map → chunk-fb77hwk0.js.map} +1 -1
  89. package/dist/{chunk-fva651jp.js → chunk-fcbgshf5.js} +2 -2
  90. package/dist/{chunk-fva651jp.js.map → chunk-fcbgshf5.js.map} +1 -1
  91. package/dist/{chunk-f6mwnw81.js → chunk-g1jfc50d.js} +3 -3
  92. package/dist/{chunk-f6mwnw81.js.map → chunk-g1jfc50d.js.map} +1 -1
  93. package/dist/{chunk-0psf0chk.js → chunk-g548q257.js} +2 -2
  94. package/dist/{chunk-0psf0chk.js.map → chunk-g548q257.js.map} +1 -1
  95. package/dist/{chunk-wjff0d08.js → chunk-gjwf07hy.js} +3 -3
  96. package/dist/{chunk-wjff0d08.js.map → chunk-gjwf07hy.js.map} +1 -1
  97. package/dist/{chunk-2ewe42dq.js → chunk-gwphn604.js} +3 -3
  98. package/dist/{chunk-2ewe42dq.js.map → chunk-gwphn604.js.map} +1 -1
  99. package/dist/{chunk-xed7yf6h.js → chunk-hgpvfhtp.js} +1 -1
  100. package/dist/{chunk-h5whhrds.js → chunk-hwpp9b7f.js} +2 -2
  101. package/dist/{chunk-m5hd632w.js.map → chunk-hwpp9b7f.js.map} +1 -1
  102. package/dist/{chunk-vqf4s99d.js → chunk-jd079awh.js} +2 -2
  103. package/dist/{chunk-vqf4s99d.js.map → chunk-jd079awh.js.map} +1 -1
  104. package/dist/{chunk-1ap3vcrr.js → chunk-jxx9mctk.js} +2 -2
  105. package/dist/{chunk-1ap3vcrr.js.map → chunk-jxx9mctk.js.map} +1 -1
  106. package/dist/{chunk-mj429x94.js → chunk-k87tqe29.js} +2 -2
  107. package/dist/{chunk-mj429x94.js.map → chunk-k87tqe29.js.map} +1 -1
  108. package/dist/{chunk-1k4rvfza.js → chunk-kbw6y0ag.js} +2 -2
  109. package/dist/{chunk-1k4rvfza.js.map → chunk-kbw6y0ag.js.map} +1 -1
  110. package/dist/{chunk-pr2enaz5.js → chunk-krdq5s4y.js} +2 -2
  111. package/dist/{chunk-pr2enaz5.js.map → chunk-krdq5s4y.js.map} +1 -1
  112. package/dist/{chunk-7ysw97gp.js → chunk-m6sj1q1q.js} +2 -2
  113. package/dist/{chunk-7ysw97gp.js.map → chunk-m6sj1q1q.js.map} +1 -1
  114. package/dist/{chunk-hgvt5084.js → chunk-m950vw4c.js} +2 -2
  115. package/dist/{chunk-hgvt5084.js.map → chunk-m950vw4c.js.map} +1 -1
  116. package/dist/{chunk-873k84dt.js → chunk-mm45shzv.js} +2 -2
  117. package/dist/{chunk-873k84dt.js.map → chunk-mm45shzv.js.map} +1 -1
  118. package/dist/{chunk-6q15sx3h.js → chunk-p56zntmt.js} +3 -3
  119. package/dist/{chunk-6q15sx3h.js.map → chunk-p56zntmt.js.map} +1 -1
  120. package/dist/{chunk-8yxjrjef.js → chunk-q01p8ta3.js} +2 -2
  121. package/dist/{chunk-8yxjrjef.js.map → chunk-q01p8ta3.js.map} +1 -1
  122. package/dist/{chunk-p97w2388.js → chunk-q3511sb5.js} +2 -2
  123. package/dist/{chunk-p97w2388.js.map → chunk-q3511sb5.js.map} +1 -1
  124. package/dist/{chunk-kfdy4vv1.js → chunk-q788x8pm.js} +2 -2
  125. package/dist/{chunk-kfdy4vv1.js.map → chunk-q788x8pm.js.map} +1 -1
  126. package/dist/{chunk-23670kw5.js → chunk-rpdekb8t.js} +2 -2
  127. package/dist/{chunk-23670kw5.js.map → chunk-rpdekb8t.js.map} +1 -1
  128. package/dist/{chunk-j7k0nzqz.js → chunk-s4fb4njt.js} +2 -2
  129. package/dist/{chunk-j7k0nzqz.js.map → chunk-s4fb4njt.js.map} +1 -1
  130. package/dist/{chunk-7yh908jj.js → chunk-s71e6k9m.js} +3 -3
  131. package/dist/{chunk-7yh908jj.js.map → chunk-s71e6k9m.js.map} +1 -1
  132. package/dist/{chunk-6eb6jgdv.js → chunk-sdn3dmpp.js} +4 -4
  133. package/dist/{chunk-6eb6jgdv.js.map → chunk-sdn3dmpp.js.map} +1 -1
  134. package/dist/{chunk-fxd7pqk3.js → chunk-sp77zwpn.js} +2 -2
  135. package/dist/{chunk-fxd7pqk3.js.map → chunk-sp77zwpn.js.map} +1 -1
  136. package/dist/{chunk-82jhqxx7.js → chunk-sv86v56c.js} +3 -3
  137. package/dist/{chunk-82jhqxx7.js.map → chunk-sv86v56c.js.map} +1 -1
  138. package/dist/{chunk-bym06a64.js → chunk-sxf94q13.js} +2 -2
  139. package/dist/{chunk-bym06a64.js.map → chunk-sxf94q13.js.map} +1 -1
  140. package/dist/{chunk-pd3qbf8r.js → chunk-ta2wsjz6.js} +2 -2
  141. package/dist/{chunk-pd3qbf8r.js.map → chunk-ta2wsjz6.js.map} +1 -1
  142. package/dist/{chunk-58k1zstz.js → chunk-thbs63gy.js} +1 -1
  143. package/dist/{chunk-71prz4rp.js → chunk-vfvjfw5k.js} +2 -2
  144. package/dist/{chunk-71prz4rp.js.map → chunk-vfvjfw5k.js.map} +1 -1
  145. package/dist/{chunk-sca3tpce.js → chunk-vnk4vaer.js} +3 -3
  146. package/dist/{chunk-sca3tpce.js.map → chunk-vnk4vaer.js.map} +1 -1
  147. package/dist/{chunk-f9nmn8x7.js → chunk-wc2sg9ny.js} +2 -2
  148. package/dist/{chunk-f9nmn8x7.js.map → chunk-wc2sg9ny.js.map} +1 -1
  149. package/dist/{chunk-rzqxkm9r.js → chunk-wp9hw3we.js} +2 -2
  150. package/dist/{chunk-rzqxkm9r.js.map → chunk-wp9hw3we.js.map} +1 -1
  151. package/dist/{chunk-4w9gbe11.js → chunk-wt1yzzbw.js} +1 -1
  152. package/dist/{chunk-d29dcs3e.js → chunk-xkas0yp8.js} +3 -3
  153. package/dist/{chunk-d29dcs3e.js.map → chunk-xkas0yp8.js.map} +1 -1
  154. package/dist/{chunk-j1yhtwsk.js → chunk-y3s05q6b.js} +2 -2
  155. package/dist/{chunk-j1yhtwsk.js.map → chunk-y3s05q6b.js.map} +1 -1
  156. package/dist/chunk-ys8nk9ga.js +15 -0
  157. package/dist/{chunk-ty9s0z7q.js.map → chunk-ys8nk9ga.js.map} +3 -3
  158. package/dist/{chunk-0gzqhjyg.js → chunk-z4dhd5pk.js} +2 -2
  159. package/dist/{chunk-0gzqhjyg.js.map → chunk-z4dhd5pk.js.map} +1 -1
  160. package/dist/{chunk-xxbkp90v.js → chunk-z5g56ds0.js} +3 -3
  161. package/dist/{chunk-xxbkp90v.js.map → chunk-z5g56ds0.js.map} +1 -1
  162. package/dist/{chunk-bzrhc7q3.js → chunk-zqptpk90.js} +2 -2
  163. package/dist/{chunk-bzrhc7q3.js.map → chunk-zqptpk90.js.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/index.js +2 -2
  174. package/dist/facades/index.js.map +1 -1
  175. package/dist/foundation/index.js +2 -2
  176. package/dist/foundation/index.js.map +1 -1
  177. package/dist/http/HttpRequest.d.ts +6 -0
  178. package/dist/http/HttpRequest.d.ts.map +1 -1
  179. package/dist/http/index.js +2 -2
  180. package/dist/http/index.js.map +1 -1
  181. package/dist/i18n/dictionaryRuntime.js +2 -2
  182. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  183. package/dist/i18n/index.js +2 -2
  184. package/dist/i18n/index.js.map +1 -1
  185. package/dist/kernel/index.js +2 -2
  186. package/dist/kernel/index.js.map +1 -1
  187. package/dist/orm/index.js +2 -2
  188. package/dist/orm/index.js.map +1 -1
  189. package/dist/probe/index.js +2 -2
  190. package/dist/probe/index.js.map +1 -1
  191. package/dist/server/index.js +2 -2
  192. package/dist/server/index.js.map +1 -1
  193. package/dist/services/index.js +2 -2
  194. package/dist/services/index.js.map +1 -1
  195. package/dist/services/queue/work.js +2 -2
  196. package/dist/services/queue/work.js.map +1 -1
  197. package/dist/services/router/serverQueryFetcher.d.ts.map +1 -1
  198. package/dist/stats/route-table.js +1 -1
  199. package/dist/support/index.js +2 -2
  200. package/dist/support/index.js.map +1 -1
  201. package/dist/vitest/index.js +1 -1
  202. package/package.json +1 -1
  203. package/dist/chunk-8v6y52et.js +0 -5
  204. package/dist/chunk-ty9s0z7q.js +0 -15
  205. /package/dist/{chunk-fnj2hc5v.js.map → chunk-3rp908gn.js.map} +0 -0
  206. /package/dist/{chunk-tms2g9at.js.map → chunk-777v6242.js.map} +0 -0
  207. /package/dist/{chunk-8f4jkpv7.js.map → chunk-8hfyscnn.js.map} +0 -0
  208. /package/dist/{chunk-xed7yf6h.js.map → chunk-hgpvfhtp.js.map} +0 -0
  209. /package/dist/{chunk-58k1zstz.js.map → chunk-thbs63gy.js.map} +0 -0
  210. /package/dist/{chunk-4w9gbe11.js.map → chunk-wt1yzzbw.js.map} +0 -0
@@ -1,26 +1,26 @@
1
1
  // @bun
2
- import{kh as HK}from"./chunk-sca3tpce.js";import{Eh as LK}from"./chunk-d29dcs3e.js";import{Di as _1,Fh as z3,Hi as LQ,Ii as n$,Jh as PG,Ji as o$,Kh as qW,Ki as aG,Lh as yW,Mh as D8,Mi as rG,Nh as G8,Qh as K8,Rh as B8,Sh as oZ,Th as aQ,Uh as IJ,Vh as jW,Wh as h,ai as C,bi as q8,ci as KZ,di as O8,ei as Q6,gi as I$,hi as g,ii as h4,qi as G6,wi as K6}from"./chunk-ty9s0z7q.js";import{Pi as s1,Qi as J0,Ri as o1,Si as gW}from"./chunk-efjk5aq7.js";import{Ti as l$,Ui as xJ,Yi as NY,Zi as s4,_i as N}from"./chunk-w4at2d5d.js";import{bj as zQ,ej as c3}from"./chunk-7yh908jj.js";import{ij as wY,lj as dG}from"./chunk-b8qfypzq.js";import{Dj as N$,Ij as n1}from"./chunk-1ap3vcrr.js";import{Wj as cX}from"./chunk-j7k0nzqz.js";import{Xj as a$,_j as pG}from"./chunk-6tbs7yc1.js";import{$j as L1}from"./chunk-c0dvdfm0.js";import{ak as Y6,bk as d0,ck as x1,dk as lJ,ek as OK,gk as pZ,hk as nG,qk as iJ}from"./chunk-2ewe42dq.js";import{Fk as C1}from"./chunk-hgvt5084.js";import{Kk as LG,Pk as OJ}from"./chunk-4587ab6m.js";import{$k as o,Wk as OG}from"./chunk-71prz4rp.js";import{al as nZ,dl as H}from"./chunk-kcgnjzqr.js";import{ll as VJ}from"./chunk-fxd7pqk3.js";import{ml as tG}from"./chunk-xw5d66ec.js";import{wl as QJ}from"./chunk-23670kw5.js";import{xl as $8,zl as TG}from"./chunk-vqf4s99d.js";import{El as n4}from"./chunk-m5hd632w.js";function t3($){return typeof $==="function"&&$.prototype!==void 0}var aJ=Symbol.for("gemi.HttpResponse"),EK=new Set([301,302,303,307,308]);class j1{kind;body;status;headers;[aJ]=!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 oJ(J,"json"),new j1("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 j1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!EK.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new j1("empty",void 0,J,Y)}static noContent($={}){return new j1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return oJ(J,"text"),new j1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function oJ($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function u1($){return typeof $==="object"&&$!==null&&$[aJ]===!0}function bK($,Z,J={}){return j1.error($,Z,J)}function s0($){return typeof $==="string"?[$]:$}function e3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function RK($){return"total"in $&&"partial"in $&&"body"in $}function rJ(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":B8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function fK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RK($))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 F8($,Z){if($ instanceof Response)return $;if(!$)return rJ();let J=await fK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return rJ()}let{range:Q}=Z;if(Q){if(z<=0)return Z3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=G8(Q,z);if(!B)return Z3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let G=Boolean(Q)&&X,K=G?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),G)F.set("Content-Range",K8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",e3(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:F})}return new Response(W,{status:K,headers:F})}class jZ extends J0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var tJ={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function W3($){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 tJ)))return Math.floor(Number(J[1])*(tJ[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var J3=new WeakMap;function $W($){return J3.has($)}function ZW($){return J3.get($)?.limit??null}function JW($){let Z=J3.get($);return Z?Z.read>Z.limit:!1}function kK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function U8($,Z){let J=kK($);if(J!==null&&J>Z)throw new jZ(Z)}function $6($,Z,J={}){let W=J3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};J3.set($,Y),qK($,Y)}if(J.checkDeclared!==!1)U8($,Z)}function wK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function V8($,Z){if(Z.stream!==void 0)return Z.stream;let J=wK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new jZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function YZ($,Z){if(U8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=V8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function eJ($){return $.headers.get("Content-Type")??""}function qK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>V8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>YZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await YZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await YZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await YZ($,Z)))}),J("blob",{value:async()=>new Blob([await YZ($,Z)],{type:eJ($)})}),J("formData",{value:async()=>new Response(await YZ($,Z),{headers:{"Content-Type":eJ($)}}).formData()}),J("clone",{value:()=>{U8($,Z.limit);let W=V8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function WW($){return t3($)}class i{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(!WW(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(WW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=s0($),this}}class zW{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=s0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of jW($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(JW($.rawRequest))throw new jZ(ZW($.rawRequest));throw J}}}class XW{constructor(...$){return new i(...$)}}class QW extends i{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=D8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(u1(Y))return Y;return await F8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof O8)return Z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class GW{constructor(...$){return new QW(...$)}}class KW{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new i("GET",$,"list"),post:new i("POST",$,"store")},this.second={get:new i("GET",$,"show"),put:new i("PUT",$,"update"),delete:new i("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 I0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new i("GET",$,Z)}post($,Z){return new i("POST",$,Z)}put($,Z){return new i("PUT",$,Z)}patch($,Z){return new i("PATCH",$,Z)}delete($,Z){return new i("DELETE",$,Z)}resource($){return new KW($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${YW($)}.`);return yK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${YW($)}.`);return vK($)}file($,Z){return new XW("GET",$,Z)}stream($,Z){return new GW("GET",$,Z)}proxy($,Z={}){return new zW($,Z)}}function YW($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function yK($){let Z={stream:new i("POST",$,"stream"),attach:new i("POST",$,"attach"),stop:new i("POST",$,"stop"),upload:new i("POST",$,"upload")};return class extends I0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function vK($){let Z={start:new i("POST",$,"voiceStart"),update:new i("PATCH",$,"voiceUpdate"),end:new i("DELETE",$,"voiceEnd")};return class extends I0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var l1="access_token";function T$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Z6($,Z){let J=T$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var gK=/^[A-Za-z0-9_-]+$/,mK=/^:[A-Za-z_][A-Za-z0-9_]*$/,BW=/^[A-Za-z0-9_-]{1,128}$/,hK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function FW($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function zZ($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(mK.test(W)){let Y=W.slice(1);if(J.has(Y))throw new p(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new p(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!gK.test(W))throw new p(`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 Y3($,Z={}){let J=zZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!BW.test(Q))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function L8($){if(zZ($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function VW($){if(typeof $!=="string"||$.length===0||$.length>64||!hK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function UW($,Z){if($===Z)return!0;if($===K0)return Z.startsWith(`${K0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&BW.test(W[j]))}var K0="user";function XZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return Y3(`${K0}.:id`,{id:Z})}class t{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class J6 extends t{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return $6(this.req.rawRequest,W3(Z)),{}}}function pK($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var cK={"body-limit":J6};class i1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:W3($.bodyLimit)}get aliases(){return{...cK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!$W($))$6($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of pK($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:DW(z)})}}else if(t3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:DW(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await dK(W.slice(j+1)),z}return Y})()}}function DW($){return $?.runsOnRefusal===!0}async function dK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class W6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...s0($)],this}events(...$){return this}}class MW{static __brand="ChannelRouter";channels={};public(){return new W6("public")}private($){return new W6("private",$)}async authorize($,Z,J={},W={}){try{sK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!PW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===K0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=Y3(Z,J??{})}catch(Q){if(Q instanceof p)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return N.exit(()=>Y6.exit(()=>N.run(X,async()=>{let Q=N.getStore();try{if(Y.middlewares.length>0)await H(i1).runMiddleware(Y.middlewares);if(Z===K0){let G=await OW(X);if(!G)return{ok:!1,code:"denied"};if(j=XZ(G),Y.visibility==="private"&&Y.authorizer){if(await LW(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await LW(Y.authorizer,X,z):await OW(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(iK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function uK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;TW(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function PW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function OW($){if(!N.getStore().user&&T$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function LW($,Z,J){if(lK($))return new $().authorize(Z,J);return $(Z,J)}function lK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function iK($){return $?.kind===s1||n1($)||N$($)}var HW=new WeakSet;function sK($){if(HW.has($))return;TW($),HW.add($)}function TW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!PW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=zZ(W);if(j[0].startsWith(":"))throw new p(`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!==K0&&j.length===2&&j[0]===K0)throw new p(`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!==K0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`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===K0?[K0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(nK(J[W].segments,J[Y].segments))throw new p(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function nK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class H8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class j6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class M8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function oK($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function aK($,Z){let J=oK($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class NW{static __brand="McpRouter";routes={};scopes;param($){return new H8($.as,$.input,$.bind)}fromTool($,Z={}){return new M8($,Z)}fromApiRoute($,Z,J){return new j6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,K=Object.keys(Y??{});if(K.length===0)throw Error(`${G}: declare at least one audience.`);let F={},B=new Map;for(let U of K){let{name:V,casing:D,description:O,params:L,files:T,...P}=Y[U],_=V??(D?aK(W,D):W);if(B.has(_))throw Error(`${G}: the audiences "${B.get(_)}" and "${U}" are both named "${_}". Give one its own name or casing.`);B.set(_,U);let A=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof A!=="string")throw Error(`${G}: the audience "${U}" has no description, and there is no shared one.`);let E={...Q,...P,description:A};if(z||L)E.params={...z,...L};if(X||T)E.files={...X,...T};F[_]=new j6($,Z,E)}return F}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class P8 extends J0{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 N1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new P8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new P8($,Z)}}class IW{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return N1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function T8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",e3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class _W{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=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function xW($,Z){if(u1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class CW{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=xW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=s0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class AW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends I1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends I1{routes=J??{}}}else this.children=class extends I1{routes=Z},this.handler=()=>({})}async run($,Z){let J=xW(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=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class I1{middlewares=[];featureGates=[];routes={};view($,Z){return new CW($,Z)}file($){return new _W($)}redirect($){return new IW($)}layout($,Z,J){return new AW($,Z,J)}}function rK($){return $}function tK(){return{aliases:{},global:[],bodyLimit:null}}var z1="redirect";function X1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function QZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function eK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(o).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function $B($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function z6($,Z){let J=Z||H(b).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=eK($,!W);if(W||!$B(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(z1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class SW extends t{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await Z6(H(b),J);if(!W)throw new I$({redirectTo:z6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",N8="private, no-cache, no-store, max-age=0, must-revalidate";class X6 extends t{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(I8))return{};if(T$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new EW(`${W.pathname}${W.search}`)}}class EW extends J0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=ZB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":N8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":N8}},viewData:{status:200,data:{},headers:{"Cache-Control":N8},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 ZB($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class bW extends t{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var RW={"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 fW extends t{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={...RW,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...RW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var JB="Rate limit exceeded";class a1 extends J0{result;retryAfter;constructor($,Z=JB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?_8($):{}};this.payload={api:{status:429,data:{error:{...o1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function _8($){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 Q1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(kW("window",W),kW("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new a1(W,typeof J==="function"?J(W):J);return W}}function kW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as x8}from"net";function _$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return x8(j)===6?j:null}if(x8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&x8(J[1])===4?J[1]:null}class vW extends t{async run($,Z){let J=WB();if(!J)return{};let W=await J.consume(this.key(),{limit:wW($)??this.config.limit,window:wW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(_8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new a1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=qW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${GZ(this.req)}:${this.req.routePath??"*"}`}}function WB(){try{let $=H();return $.bound(Q1)?$.make(Q1):null}catch{return null}}function GZ($){let Z=yW($.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)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function wW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class mW extends t{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new C8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new C8;return{}}}class C8 extends J0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:gW("csrf","Invalid CSRF token",403)}},view:{}}}class hW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class pW{all($,Z){return!0}}class A8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new KZ:new Q6}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 t{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof KZ:$ instanceof Q6}}function YB($){return new A8($)}async function B6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await LB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return OB(z,Z,J,$.url)}async function OB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:K}=await Y.read();if(G)break;if(z+K.byteLength>Z){if(!J)throw new K6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function LB($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function F6($){return new TextDecoder("utf-8").decode($)}var HB={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function x$($){return $.replace(/[&<>"']/g,(Z)=>HB[Z])}var MB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function S8($){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 MB[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 E8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function cW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(S8($.slice(W)));return}if(Y>W)Z.text(S8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(E8($.slice(Y+2,j).trim())),W=j+1}else{let j=PB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=E8(z.slice(0,Q));if(G){if(Z.open(G,TB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function PB($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function TB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[E8(W[1])]=S8(W[2]??W[3]??"");return Z}class W0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var sW="http://www.sitemaps.org/schemas/sitemap/0.9",NB="http://www.w3.org/1999/xhtml",f8=`<?xml version="1.0" encoding="UTF-8"?>
2
+ import{lh as HK}from"./chunk-vnk4vaer.js";import{Fh as LK}from"./chunk-xkas0yp8.js";import{Ei as _1,Gh as z3,Ii as LQ,Ji as n$,Kh as PG,Ki as o$,Lh as qW,Li as aG,Mh as yW,Nh as D8,Ni as rG,Oh as G8,Rh as K8,Sh as B8,Th as oZ,Uh as aQ,Vh as IJ,Wh as jW,Xh as h,bi as C,ci as q8,di as KZ,ei as O8,fi as Q6,hi as I$,ii as g,ji as h4,ri as G6,xi as K6}from"./chunk-ys8nk9ga.js";import{Qi as s1,Ri as J0,Si as o1,Ti as gW}from"./chunk-5n21z4n8.js";import{$i as N,Ui as l$,Vi as xJ,Zi as NY,_i as s4}from"./chunk-1h6g1hkg.js";import{cj as zQ,fj as c3}from"./chunk-s71e6k9m.js";import{jj as wY,mj as dG}from"./chunk-fb77hwk0.js";import{Ej as N$,Jj as n1}from"./chunk-jxx9mctk.js";import{Xj as cX}from"./chunk-s4fb4njt.js";import{$j as pG,Yj as a$}from"./chunk-6t1t7h05.js";import{ak as L1}from"./chunk-a9frf7ym.js";import{bk as Y6,ck as d0,dk as x1,ek as lJ,fk as OK,hk as pZ,ik as nG,rk as iJ}from"./chunk-gwphn604.js";import{Gk as C1}from"./chunk-m950vw4c.js";import{Lk as LG,Qk as OJ}from"./chunk-978pc27j.js";import{Xk as OG,al as d}from"./chunk-vfvjfw5k.js";import{bl as nZ,el as H}from"./chunk-8b9ks729.js";import{ml as VJ}from"./chunk-sp77zwpn.js";import{nl as tG}from"./chunk-9akefv1y.js";import{xl as QJ}from"./chunk-rpdekb8t.js";import{Al as TG,yl as $8}from"./chunk-jd079awh.js";import{Fl as n4}from"./chunk-9wcv7e1a.js";function t3($){return typeof $==="function"&&$.prototype!==void 0}var aJ=Symbol.for("gemi.HttpResponse"),EK=new Set([301,302,303,307,308]);class j1{kind;body;status;headers;[aJ]=!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 oJ(J,"json"),new j1("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 j1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!EK.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new j1("empty",void 0,J,Y)}static noContent($={}){return new j1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return oJ(J,"text"),new j1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function oJ($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function u1($){return typeof $==="object"&&$!==null&&$[aJ]===!0}function bK($,Z,J={}){return j1.error($,Z,J)}function s0($){return typeof $==="string"?[$]:$}function e3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function RK($){return"total"in $&&"partial"in $&&"body"in $}function rJ(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":B8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function fK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RK($))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 F8($,Z){if($ instanceof Response)return $;if(!$)return rJ();let J=await fK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return rJ()}let{range:Q}=Z;if(Q){if(z<=0)return Z3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=G8(Q,z);if(!K)return Z3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),G)F.set("Content-Range",K8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",e3(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[K,V]of Object.entries(J.extraHeaders))F.set(K,V);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:F})}return new Response(W,{status:B,headers:F})}class jZ extends J0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var tJ={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function W3($){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 tJ)))return Math.floor(Number(J[1])*(tJ[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var J3=new WeakMap;function $W($){return J3.has($)}function ZW($){return J3.get($)?.limit??null}function JW($){let Z=J3.get($);return Z?Z.read>Z.limit:!1}function kK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function U8($,Z){let J=kK($);if(J!==null&&J>Z)throw new jZ(Z)}function $6($,Z,J={}){let W=J3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};J3.set($,Y),qK($,Y)}if(J.checkDeclared!==!1)U8($,Z)}function wK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function V8($,Z){if(Z.stream!==void 0)return Z.stream;let J=wK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new jZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function YZ($,Z){if(U8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=V8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function eJ($){return $.headers.get("Content-Type")??""}function qK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>V8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>YZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await YZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await YZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await YZ($,Z)))}),J("blob",{value:async()=>new Blob([await YZ($,Z)],{type:eJ($)})}),J("formData",{value:async()=>new Response(await YZ($,Z),{headers:{"Content-Type":eJ($)}}).formData()}),J("clone",{value:()=>{U8($,Z.limit);let W=V8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function WW($){return t3($)}class s{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(!WW(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(WW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=s0($),this}}class zW{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=s0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of jW($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(JW($.rawRequest))throw new jZ(ZW($.rawRequest));throw J}}}class XW{constructor(...$){return new s(...$)}}class QW extends s{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=D8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(u1(Y))return Y;return await F8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof O8)return Z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class GW{constructor(...$){return new QW(...$)}}class KW{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new s("GET",$,"list"),post:new s("POST",$,"store")},this.second={get:new s("GET",$,"show"),put:new s("PUT",$,"update"),delete:new s("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 I0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new s("GET",$,Z)}post($,Z){return new s("POST",$,Z)}put($,Z){return new s("PUT",$,Z)}patch($,Z){return new s("PATCH",$,Z)}delete($,Z){return new s("DELETE",$,Z)}resource($){return new KW($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${YW($)}.`);return yK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${YW($)}.`);return vK($)}file($,Z){return new XW("GET",$,Z)}stream($,Z){return new GW("GET",$,Z)}proxy($,Z={}){return new zW($,Z)}}function YW($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function yK($){let Z={stream:new s("POST",$,"stream"),attach:new s("POST",$,"attach"),stop:new s("POST",$,"stop"),upload:new s("POST",$,"upload")};return class extends I0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function vK($){let Z={start:new s("POST",$,"voiceStart"),update:new s("PATCH",$,"voiceUpdate"),end:new s("DELETE",$,"voiceEnd")};return class extends I0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var l1="access_token";function T$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Z6($,Z){let J=T$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var gK=/^[A-Za-z0-9_-]+$/,mK=/^:[A-Za-z_][A-Za-z0-9_]*$/,BW=/^[A-Za-z0-9_-]{1,128}$/,hK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function FW($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function zZ($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(mK.test(W)){let Y=W.slice(1);if(J.has(Y))throw new p(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new p(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!gK.test(W))throw new p(`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 Y3($,Z={}){let J=zZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!BW.test(Q))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function L8($){if(zZ($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function VW($){if(typeof $!=="string"||$.length===0||$.length>64||!hK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function UW($,Z){if($===Z)return!0;if($===K0)return Z.startsWith(`${K0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&BW.test(W[j]))}var K0="user";function XZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return Y3(`${K0}.:id`,{id:Z})}class t{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class J6 extends t{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return $6(this.req.rawRequest,W3(Z)),{}}}function pK($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var cK={"body-limit":J6};class i1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:W3($.bodyLimit)}get aliases(){return{...cK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!$W($))$6($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of pK($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:DW(z)})}}else if(t3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:DW(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await dK(W.slice(j+1)),z}return Y})()}}function DW($){return $?.runsOnRefusal===!0}async function dK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class W6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...s0($)],this}events(...$){return this}}class MW{static __brand="ChannelRouter";channels={};public(){return new W6("public")}private($){return new W6("private",$)}async authorize($,Z,J={},W={}){try{sK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!PW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===K0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=Y3(Z,J??{})}catch(Q){if(Q instanceof p)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return N.exit(()=>Y6.exit(()=>N.run(X,async()=>{let Q=N.getStore();try{if(Y.middlewares.length>0)await H(i1).runMiddleware(Y.middlewares);if(Z===K0){let G=await OW(X);if(!G)return{ok:!1,code:"denied"};if(j=XZ(G),Y.visibility==="private"&&Y.authorizer){if(await LW(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await LW(Y.authorizer,X,z):await OW(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(iK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function uK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;TW(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function PW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function OW($){if(!N.getStore().user&&T$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function LW($,Z,J){if(lK($))return new $().authorize(Z,J);return $(Z,J)}function lK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function iK($){return $?.kind===s1||n1($)||N$($)}var HW=new WeakSet;function sK($){if(HW.has($))return;TW($),HW.add($)}function TW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!PW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=zZ(W);if(j[0].startsWith(":"))throw new p(`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!==K0&&j.length===2&&j[0]===K0)throw new p(`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!==K0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`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===K0?[K0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(nK(J[W].segments,J[Y].segments))throw new p(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function nK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class H8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class j6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class M8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function oK($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function aK($,Z){let J=oK($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class NW{static __brand="McpRouter";routes={};scopes;param($){return new H8($.as,$.input,$.bind)}fromTool($,Z={}){return new M8($,Z)}fromApiRoute($,Z,J){return new j6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let F={},K=new Map;for(let V of B){let{name:U,casing:D,description:O,params:L,files:T,...P}=Y[V],_=U??(D?aK(W,D):W);if(K.has(_))throw Error(`${G}: the audiences "${K.get(_)}" and "${V}" are both named "${_}". Give one its own name or casing.`);K.set(_,V);let A=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof A!=="string")throw Error(`${G}: the audience "${V}" has no description, and there is no shared one.`);let E={...Q,...P,description:A};if(z||L)E.params={...z,...L};if(X||T)E.files={...X,...T};F[_]=new j6($,Z,E)}return F}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class P8 extends J0{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 N1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new P8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new P8($,Z)}}class IW{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return N1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function T8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",e3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class _W{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=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function xW($,Z){if(u1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class CW{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=xW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=s0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class AW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends I1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends I1{routes=J??{}}}else this.children=class extends I1{routes=Z},this.handler=()=>({})}async run($,Z){let J=xW(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=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class I1{middlewares=[];featureGates=[];routes={};view($,Z){return new CW($,Z)}file($){return new _W($)}redirect($){return new IW($)}layout($,Z,J){return new AW($,Z,J)}}function rK($){return $}function tK(){return{aliases:{},global:[],bodyLimit:null}}var z1="redirect";function X1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function QZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function eK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(d).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function $B($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function z6($,Z){let J=Z||H(b).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=eK($,!W);if(W||!$B(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(z1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class SW extends t{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await Z6(H(b),J);if(!W)throw new I$({redirectTo:z6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",N8="private, no-cache, no-store, max-age=0, must-revalidate";class X6 extends t{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(I8))return{};if(T$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new EW(`${W.pathname}${W.search}`)}}class EW extends J0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=ZB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":N8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":N8}},viewData:{status:200,data:{},headers:{"Cache-Control":N8},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 ZB($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class bW extends t{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var RW={"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 fW extends t{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={...RW,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...RW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var JB="Rate limit exceeded";class a1 extends J0{result;retryAfter;constructor($,Z=JB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?_8($):{}};this.payload={api:{status:429,data:{error:{...o1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function _8($){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 Q1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(kW("window",W),kW("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new a1(W,typeof J==="function"?J(W):J);return W}}function kW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as x8}from"net";function _$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return x8(j)===6?j:null}if(x8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&x8(J[1])===4?J[1]:null}class vW extends t{async run($,Z){let J=WB();if(!J)return{};let W=await J.consume(this.key(),{limit:wW($)??this.config.limit,window:wW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(_8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new a1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=qW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${GZ(this.req)}:${this.req.routePath??"*"}`}}function WB(){try{let $=H();return $.bound(Q1)?$.make(Q1):null}catch{return null}}function GZ($){let Z=yW($.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)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function wW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class mW extends t{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new C8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new C8;return{}}}class C8 extends J0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:gW("csrf","Invalid CSRF token",403)}},view:{}}}class hW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class pW{all($,Z){return!0}}class A8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new KZ:new Q6}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 t{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof KZ:$ instanceof Q6}}function YB($){return new A8($)}async function B6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await LB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return OB(z,Z,J,$.url)}async function OB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new K6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function LB($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function F6($){return new TextDecoder("utf-8").decode($)}var HB={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function x$($){return $.replace(/[&<>"']/g,(Z)=>HB[Z])}var MB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function S8($){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 MB[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 E8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function cW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(S8($.slice(W)));return}if(Y>W)Z.text(S8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(E8($.slice(Y+2,j).trim())),W=j+1}else{let j=PB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=E8(z.slice(0,Q));if(G){if(Z.open(G,TB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function PB($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function TB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[E8(W[1])]=S8(W[2]??W[3]??"");return Z}class W0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var sW="http://www.sitemaps.org/schemas/sitemap/0.9",NB="http://www.w3.org/1999/xhtml",f8=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `,dW=`<urlset xmlns="${sW}" xmlns:xhtml="${NB}">
4
4
  `,uW=`</urlset>
5
5
  `,C$=50000,j3=52428800,lW=2048,IB=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),_B=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,xB="application/xml; charset=utf-8",iW=new TextEncoder;function k8($,Z){let J;try{J=new URL($)}catch{throw new W0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new W0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>lW)throw new W0(`Sitemap: ${Z} is over ${lW} characters: "${W.slice(0,80)}\u2026".`);return W}function nW($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new W0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!_B.test($))throw new W0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function CB($){let Z=k8($.loc,"loc"),J=`<url><loc>${x$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${x$(nW($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!IB.has($.changefreq))throw new W0(`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 W0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new W0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=k8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${x$(Y)}" href="${x$(j)}"/>`}return`${J}</url>
6
- `}function AB($){let Z=$.maxUrls??C$,J=$.maxBytes??j3;if(!Number.isInteger(Z)||Z<1||Z>C$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${C$}.`);if(!Number.isInteger(J)||J<1||J>j3)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${j3}.`);return{maxUrls:Z,maxBytes:J}}function oW($,Z={}){let{maxUrls:J,maxBytes:W}=AB(Z),Y=iW.encode(f8+dW+uW).byteLength,j=[],z=[],X=Y,Q=()=>{j.push(f8+dW+z.join("")+uW),z=[],X=Y};for(let G of $){let K=CB(G),F=iW.encode(K).byteLength;if(Y+F>W)throw new W0(`Sitemap: the entry for ${G.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+F>W)Q();z.push(K),X+=F}if(z.length>0||j.length===0)Q();return j}function aW($){let Z="",J=0;for(let W of $){if(++J>C$)throw new W0(`Sitemap: an index can list at most ${C$} sitemaps.`);let Y=k8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${x$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${x$(nW(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
6
+ `}function AB($){let Z=$.maxUrls??C$,J=$.maxBytes??j3;if(!Number.isInteger(Z)||Z<1||Z>C$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${C$}.`);if(!Number.isInteger(J)||J<1||J>j3)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${j3}.`);return{maxUrls:Z,maxBytes:J}}function oW($,Z={}){let{maxUrls:J,maxBytes:W}=AB(Z),Y=iW.encode(f8+dW+uW).byteLength,j=[],z=[],X=Y,Q=()=>{j.push(f8+dW+z.join("")+uW),z=[],X=Y};for(let G of $){let B=CB(G),F=iW.encode(B).byteLength;if(Y+F>W)throw new W0(`Sitemap: the entry for ${G.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+F>W)Q();z.push(B),X+=F}if(z.length>0||j.length===0)Q();return j}function aW($){let Z="",J=0;for(let W of $){if(++J>C$)throw new W0(`Sitemap: an index can list at most ${C$} sitemaps.`);let Y=k8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${x$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${x$(nW(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
7
7
  `}return`${f8}<sitemapindex xmlns="${sW}">
8
8
  ${Z}</sitemapindex>
9
- `}function b8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",xB);return new Response($,{status:Z,headers:W})}function SB($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function EB($,Z={}){let J=oW($,Z),W=SB(Z.page);if(W!==null){let j=J[W-1];return j?b8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return b8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new W0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return b8(aW(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function R8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function rW($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let B=[];for(let U of W.split(/\r?\n/)){if(B.length>=J)break;let V=U.trim()?R8(U):null;if(V)B.push({loc:V})}if(B.length===0&&W.length>0)throw new W0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:B}}let Y=null,j=[],z=[],X=[],Q=null,G=null,K="",F=()=>Y==="index"?z.length:j.length;if(cW(W,{stopped:()=>F()>=J,open(B,U){let V=X[X.length-1];if(X.push(B),Y===null){if(B==="urlset")Y="urlset";else if(B==="sitemapindex")Y="index";return}if(Y==="urlset"&&B==="url"&&V==="urlset"||Y==="index"&&B==="sitemap"&&V==="sitemapindex")Q={};else if(Q&&(V==="url"||V==="sitemap")&&(B==="loc"||B==="lastmod"||B==="changefreq"||B==="priority"))G=B,K="";else if(Q&&Y==="urlset"&&V==="url"&&B==="link"){let D=U.href?R8(U.href):null;if(U.rel?.toLowerCase()==="alternate"&&U.hreflang&&D)(Q.alternates??=[]).push({hrefLang:U.hreflang,href:D})}},close(B){let U=X.lastIndexOf(B);if(U===-1)return;if(X.length=U,G&&B===G&&Q)Q[G]=K.trim(),G=null;else if(Q&&(B==="url"||B==="sitemap")){let V=Q;Q=null,G=null;let D=V.loc?R8(V.loc):null;if(!D)return;if(Y==="index"){z.push(V.lastmod?{loc:D,lastmod:V.lastmod}:{loc:D});return}let O={loc:D};if(V.lastmod)O.lastmod=V.lastmod;if(V.changefreq)O.changefreq=V.changefreq;let L=V.priority?Number(V.priority):NaN;if(Number.isFinite(L))O.priority=L;if(V.alternates)O.alternates=V.alternates;j.push(O)}},text(B){if(G)K+=B}}),Y===null)throw new W0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*bB($,Z={}){let{maxUrls:J=C$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=j3,onError:z,...X}=Z,Q=[{url:String($),depth:0}],G=new Set,K=0,F=0;while(Q.length>0&&F<J&&K<W){let B=Q.shift(),U=B.url.replace(/#.*$/,"");if(G.has(U))continue;G.add(U),K++;let V;try{let D=await _1(B.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new W0(`Sitemap: ${B.url} answered ${D.status}.`,B.url,D.status);let O=F6(await B6(D,j));V=rW(O,{maxUrls:Math.max(J-F,W-K)})}catch(D){if(B.depth===0||!z||X.signal?.aborted)throw D;z(D,B.url);continue}if(V.kind==="index"){if(B.depth>=Y)continue;Q=V.sitemaps.slice(0,W-K).map((O)=>({url:O.loc,depth:B.depth+1})).concat(Q);continue}for(let D of V.urls)if(yield{...D,sitemap:B.url},++F>=J)return}}var tW={response:EB,chunk:oW,index:aW,parse:rW,read:bB,MAX_URLS:C$,MAX_BYTES:j3};var RB=512000,fB=new TextEncoder;function eW($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function $Y($){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 Y=$.codePointAt(J);if(Y>65535)J++;for(let j of fB.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function kB($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class BZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=eW($)||"*";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 Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=$Y(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!kB(j.path,J))continue;let z=j.path.length,X=j.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 wB={"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 ZY($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),Q=(X===-1?z:z.slice(0,X)).trim(),G=Q.indexOf(":");if(G===-1)continue;let K=wB[Q.slice(0,G).trim().toLowerCase()],F=Q.slice(G+1).trim();if(!K)continue;if(K==="sitemap"){if(!F||/\s/.test(F))continue;try{let B=Z.url?new URL(F,Z.url):new URL(F);if(B.protocol==="http:"||B.protocol==="https:")W.push(B.href)}catch{}continue}if(K==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let B=eW(F);if(B)Y.userAgents.push(B);continue}if(!Y)continue;if(j=!1,K==="crawl-delay"){let B=Number(F);if(Number.isFinite(B)&&B>=0)Y.crawlDelay=B;continue}if(!F)continue;Y.rules.push({type:K,path:$Y(F)})}return new BZ(J,W)}async function qB($,Z={}){let{maxSize:J=RB,...W}=Z,Y=new URL("/robots.txt",$),j=await _1(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new BZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new BZ([],[],"unavailable");let X=await B6(j,J,!0),Q=F6(X);if(X.byteLength>=J)Q=Q.slice(0,Math.max(0,Q.lastIndexOf(`
9
+ `}function b8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",xB);return new Response($,{status:Z,headers:W})}function SB($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function EB($,Z={}){let J=oW($,Z),W=SB(Z.page);if(W!==null){let j=J[W-1];return j?b8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return b8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new W0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return b8(aW(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function R8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function rW($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let K=[];for(let V of W.split(/\r?\n/)){if(K.length>=J)break;let U=V.trim()?R8(V):null;if(U)K.push({loc:U})}if(K.length===0&&W.length>0)throw new W0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:K}}let Y=null,j=[],z=[],X=[],Q=null,G=null,B="",F=()=>Y==="index"?z.length:j.length;if(cW(W,{stopped:()=>F()>=J,open(K,V){let U=X[X.length-1];if(X.push(K),Y===null){if(K==="urlset")Y="urlset";else if(K==="sitemapindex")Y="index";return}if(Y==="urlset"&&K==="url"&&U==="urlset"||Y==="index"&&K==="sitemap"&&U==="sitemapindex")Q={};else if(Q&&(U==="url"||U==="sitemap")&&(K==="loc"||K==="lastmod"||K==="changefreq"||K==="priority"))G=K,B="";else if(Q&&Y==="urlset"&&U==="url"&&K==="link"){let D=V.href?R8(V.href):null;if(V.rel?.toLowerCase()==="alternate"&&V.hreflang&&D)(Q.alternates??=[]).push({hrefLang:V.hreflang,href:D})}},close(K){let V=X.lastIndexOf(K);if(V===-1)return;if(X.length=V,G&&K===G&&Q)Q[G]=B.trim(),G=null;else if(Q&&(K==="url"||K==="sitemap")){let U=Q;Q=null,G=null;let D=U.loc?R8(U.loc):null;if(!D)return;if(Y==="index"){z.push(U.lastmod?{loc:D,lastmod:U.lastmod}:{loc:D});return}let O={loc:D};if(U.lastmod)O.lastmod=U.lastmod;if(U.changefreq)O.changefreq=U.changefreq;let L=U.priority?Number(U.priority):NaN;if(Number.isFinite(L))O.priority=L;if(U.alternates)O.alternates=U.alternates;j.push(O)}},text(K){if(G)B+=K}}),Y===null)throw new W0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*bB($,Z={}){let{maxUrls:J=C$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=j3,onError:z,...X}=Z,Q=[{url:String($),depth:0}],G=new Set,B=0,F=0;while(Q.length>0&&F<J&&B<W){let K=Q.shift(),V=K.url.replace(/#.*$/,"");if(G.has(V))continue;G.add(V),B++;let U;try{let D=await _1(K.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new W0(`Sitemap: ${K.url} answered ${D.status}.`,K.url,D.status);let O=F6(await B6(D,j));U=rW(O,{maxUrls:Math.max(J-F,W-B)})}catch(D){if(K.depth===0||!z||X.signal?.aborted)throw D;z(D,K.url);continue}if(U.kind==="index"){if(K.depth>=Y)continue;Q=U.sitemaps.slice(0,W-B).map((O)=>({url:O.loc,depth:K.depth+1})).concat(Q);continue}for(let D of U.urls)if(yield{...D,sitemap:K.url},++F>=J)return}}var tW={response:EB,chunk:oW,index:aW,parse:rW,read:bB,MAX_URLS:C$,MAX_BYTES:j3};var RB=512000,fB=new TextEncoder;function eW($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function $Y($){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 Y=$.codePointAt(J);if(Y>65535)J++;for(let j of fB.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function kB($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class BZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=eW($)||"*";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 Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=$Y(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!kB(j.path,J))continue;let z=j.path.length,X=j.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 wB={"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 ZY($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),Q=(X===-1?z:z.slice(0,X)).trim(),G=Q.indexOf(":");if(G===-1)continue;let B=wB[Q.slice(0,G).trim().toLowerCase()],F=Q.slice(G+1).trim();if(!B)continue;if(B==="sitemap"){if(!F||/\s/.test(F))continue;try{let K=Z.url?new URL(F,Z.url):new URL(F);if(K.protocol==="http:"||K.protocol==="https:")W.push(K.href)}catch{}continue}if(B==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let K=eW(F);if(K)Y.userAgents.push(K);continue}if(!Y)continue;if(j=!1,B==="crawl-delay"){let K=Number(F);if(Number.isFinite(K)&&K>=0)Y.crawlDelay=K;continue}if(!F)continue;Y.rules.push({type:B,path:$Y(F)})}return new BZ(J,W)}async function qB($,Z={}){let{maxSize:J=RB,...W}=Z,Y=new URL("/robots.txt",$),j=await _1(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new BZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new BZ([],[],"unavailable");let X=await B6(j,J,!0),Q=F6(X);if(X.byteLength>=J)Q=Q.slice(0,Math.max(0,Q.lastIndexOf(`
10
10
  `)));return ZY(Q,{url:j.url})}function w8($){return $===void 0?[]:typeof $==="string"?[$]:$}function V6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
11
  `}function JY($){let Z=[];for(let W of $.rules??[]){let Y=w8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>V6("User-agent",X)).join(""),z=[...w8(W.allow).map((X)=>["Allow",X]),...w8(W.disallow).map((X)=>["Disallow",X])];for(let[X,Q]of z){if(!Q.startsWith("/")&&!Q.startsWith("*"))throw TypeError(`Robots: ${X} "${Q}" must start with "/" or "*".`);j+=V6(X,Q)}if(z.length===0)j+=`Disallow:
12
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.`);j+=V6("Crawl-delay",String(W.crawlDelay))}Z.push(j)}let J=($.sitemaps??[]).map((W)=>{let Y;try{Y=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return V6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function yB($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(JY($),{status:200,headers:J})}var WY={response:yB,text:JY,parse:ZY,fetch:qB};import{createHmac as YY,randomBytes as vB}from"crypto";var y8="v2.";function v8($){return $.startsWith(y8)}function FZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function jY($){let Z=vB(16).toString("hex"),J=YY("sha256",FZ()).update(`${$}:${Z}`).digest("hex");return`${y8}${J}`}function U6($,Z){let J=YY("sha256",FZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${y8}${J}`}import{createHash as hB,createHmac as pB,randomInt as cB,timingSafeEqual as QY}from"crypto";function zY($,Z){return Math.floor($/Z)*Z}function gB($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function g8($,Z,J,W){return Z*gB(J,W)+$}function mB($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let K=Y*(1-(X-Z)/J);if(K<=Y)return Math.max(0,Math.ceil(K-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function XY($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let K=g8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-K)),resetAt:Y-j+z,retryAfter:0}}let G=mB({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class m8{}class h8 extends m8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=zY(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let K=g8(Q.current,Q.previous,X,W)+Y<=J;if(K)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return XY({allowed:K,current:Q.current,previous:Q.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}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,Y]of this.buckets)if($-Y.windowStart>=Y.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,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var BY="h1.";function D6($,Z,J){let W=pB("sha256",FZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${BY}${W}`}function VZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(BY),X=D6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return QY(Q,Q),!1;return QY(Q,G)}function FY($){let Z="";for(let J=0;J<$;J++)Z+=String(cB(0,10));return Z}var VY=320;function X3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>VY)return null;return Z.toLowerCase()}function O6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>VY)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var GY=null;function UY(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(Q1))return $.make(Q1)}catch{}return GY??=new Q1({driver:new h8,limit:1000,window:60}),GY}function KY($){return $.length<=64?$:`sha256:${hB("sha256").update($).digest("hex")}`}async function UZ($,Z,J,W){let Y=UY(),j=[[`auth:code-${$}:ip:${KY(GZ(J))}`,W.perIp]];if(Z!==null)j.push([`auth:code-${$}:email:${KY(Z)}`,W.perEmail]);for(let[z,X]of j){if(!X)continue;let[Q,G]=X,K=await Y.consume(z,{limit:Q,window:G});if(!K.allowed)throw new a1(K)}}async function DY($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await UY().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as c8}from"crypto";class p8 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 Q3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function dB($={}){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 d8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return Q3("length",Z,4,12),Q3("expiresInMinutes",J,1),Q3("linkExpiresInMinutes",W,1),Q3("maxAttempts",Y,1),Q3("activeCodes",j,1,5),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes: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:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)})}}async function uB($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function OY($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function LY($){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 FP($){return $}function HY($={}){return dB($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:p8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:uB,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>c8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return c8(32).toString("hex")},generateMagicLinkToken:()=>c8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:d8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var lB=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),iB=new Set(["svg","math"]);function MY($){return $===32||$===9||$===10||$===12||$===13}function PY($){return $>=65&&$<=90||$>=97&&$<=122}function L6($){return $>=65&&$<=90?$+32:$}function TY(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,K=()=>{if(!J&&lB.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(iB.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},F=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(PY(B))$="tagName",J=!1,z=!1,Z=String.fromCharCode(L6(B));else if(B===63)$="bogus";else if(B===60)$="tagOpen";else $="data";return;case"endTagOpen":if(PY(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(L6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(MY(B)||B===47)$="inTag",z=B===47;else if(B===62)K();else Z+=String.fromCharCode(L6(B));return;case"inTag":if(B===62){K();return}if(z=B===47,B===34)$="attrDouble";else if(B===39)$="attrSingle";return;case"attrDouble":if(B===34)$="inTag";z=!1;return;case"attrSingle":if(B===39)$="inTag";z=!1;return;case"bang":if(B===45){if(j+=1,j===2)$="comment",j=0}else if(B===62)$="data";else $="bogus";return;case"bogus":if(B===62)$="data";return;case"comment":if(B===45)j=j<2?j+1:2;else if(B===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(L6(B)===W.charCodeAt(Y))Y+=1;else Y=B===60?1:0;return}if(B===62)$="data",Z="";else if(MY(B)||B===47)$="inTag",Z="";else Y=B===60?1:0;return}}};return{scanToInsertionPoint(B){for(let U=0;U<B.length;U++){if(G())return U;F(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)F(B[U])},isSafe:G}}function G1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function sB($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${G1([$.path,$.variantKey,$.data])})</script>`}function nB($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${G1([$.id,$.locale,$.strings])})</script>`}function u8($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((V)=>{if(V.status!=="resolved")return;j.push(sB(V))}),W?.onUse((V)=>{j.push(nB(V))});let G=$.getReader(),K=TY(),F=(V,D)=>{V.enqueue(D),J.onChunk?.(D)},B=(V)=>{while(j.length>0){let D=Y.encode(j.shift());K.write(D),F(V,D)}},U=(V,D)=>{if(j.length===0){K.write(D),F(V,D);return}let O=K.scanToInsertionPoint(D);if(O>0)F(V,D.subarray(0,O));if(K.isSafe())B(V);let L=D.subarray(O);if(L.length>0)K.write(L),F(V,L)};return new ReadableStream({async pull(V){let D;try{D=await G.read()}catch(T){throw Q(),T}let{done:O,value:L}=D;if(O){B(V),V.close(),Q();return}if(!z){if(z=!0,K.write(L),F(V,L),J.onShell?.(),K.isSafe())B(V);return}U(V,L)},cancel(V){return Q(),G.cancel(V)}})}var oB=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function H6($){if(!$)return!1;return oB.test($)}async function IY($,Z=()=>{}){let J=N.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await aB($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:NY(),isBot:H6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function _Y($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function aB($,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 xY($,Z){return`${$}:${Z}`}function l8($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function CY($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function AY($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=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 j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=tB($,Z,J,W.buckets);return CY(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function rB($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function tB($,Z,J,W){let Y=xY(Z.salt??$,rB(J));if(!W)return l8(Y);let j=W.get(Y);if(j!==void 0)return j;let z=l8(Y);return W.set(Y,z),z}class SY 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 i8{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 SY(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 Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=eB(W);if(j)J.set(Y,j)}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 eB($){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 Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class $F{}class ZF 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 s8 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 EY 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 bY{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 r1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new i8($.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,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.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 EY(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=JF(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new s8(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!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 bY(this,_Y($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),Q=AY($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,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 IY(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 JF($){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 RY($){if($===void 0)return!0;return await H(r1).enabled($)}async function DZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=OY($[Z]);if(!J||!await RY(J.feature))return null;return J.provider}async function fY($){let Z=[];for(let J of Object.keys($))if(await DZ($,J))Z.push(J);return Z}function n8($){if($&&typeof $==="object")delete $.password;return $}function WF(){return new Proxy({},{get:($,Z)=>wY(Z)})}var kY=new WeakMap;function qY($){if($&&typeof $==="object"){for(let Z of Object.values($))qY(Z);Object.freeze($)}return $}var YF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},jF=qY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:YF});class o8{models;constructor($=WF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return jF}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??x1(),W=H(C1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await d0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||d0())return Y();let z=(kY.get(W)??Promise.resolve()).then(Y,Y);return kY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return n8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return n8(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 listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}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?n8(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 GD}from"crypto";function q0($,Z,J,W,Y){return n0(Z,rY($,Z),J,W,Y)}function n0($,Z,J,W,Y,j){let z=$7(Z,J,W);if(Y&&Z!==z)throw RangeError(wz($,Z,J,W,j));return z}function rY($,Z){let J=$[Z];if(J===void 0)throw TypeError(E2(Z));return J}function V0($){return $!==null&&/object|function/.test(typeof $)}function g0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function Q7($){return b$({name:$},1)}function b$($,Z){return t0((J)=>({value:J,configurable:1,writable:!Z}),$)}function tY($){return t0((Z)=>({get:Z,configurable:1}),$)}function w6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function NZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function t0($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function L3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function zF($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function h0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function G7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function K7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function eY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function $5($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function Z5($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function k($,...Z){return(...J)=>$(...Z,...J)}function yY($){return $[0].toUpperCase()+$.substring(1)}function H3($){return $.slice().sort()}function x6($,Z){return String(Z).padStart($,"0")}function t1($,Z){return Math.sign($-Z)}function $7($,Z,J){return Math.min(Math.max($,Z),J)}function S1($,Z){return[Math.floor($/Z),K3($,Z)]}function K3($,Z){return($%Z+Z)%Z}function Z$($,Z){return[q6($,Z),B7($,Z)]}function q6($,Z){return Math.trunc($/Z)||0}function B7($,Z){return $%Z||0}function M6($){return Math.abs($%1)===0.5}function J5($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=B1[X],K=c/G,[F,B]=Z$(Q,K);W+=B*G,Y+=F}let[j,z]=Z$(W,c);return[Y+j,z]}function y6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=B1[Y];W[J[Y]]=q6($,j),$=B7($,j)}return W}function W5($){return $===w?O4:[]}function Y5($){return $===w?S3:[]}function j5($){return $===w?["year","day"]:[]}function z5($){if($!==void 0)return e($)}function X5($){if($!==void 0)return e0($)}function F7($){if($!==void 0)return M3($)}function e0($){return K5(M3($))}function M3($){return G5(rF($))}function V7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function Q5($,Z){if(Z==null)throw RangeError(E2($));return Z}function b1($){if(!V0($))throw TypeError(kz);return $}function v6($,Z,J=$){if(typeof Z!==$)throw TypeError(x3(J,Z));return Z}function G5($,Z="number"){if(!Number.isInteger($))throw RangeError(NF(Z,$));return $||0}function K5($,Z="number"){if($<=0)throw RangeError(IF(Z,$));return $}function U7($){if(typeof $=="symbol")throw TypeError(AF);return String($)}function C6($,Z){return V0($)?String($):e($,Z)}function g6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(CF($));return $}function B5($,Z="number"){if(typeof $=="bigint")throw TypeError(xF(Z));if($=Number($),!Number.isFinite($))throw RangeError(_F(Z,$));return $}function _0($,Z){return Math.trunc(B5($,Z))||0}function F5($,Z){return G5(B5($,Z),Z)}function vY($,Z){return K5(_0($,Z),Z)}function D7($,Z){let[J,W]=Z$(Z,c),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*c),[Y,W]}function LZ($,Z,J=1){return D7($[0]+Z[0]*J,$[1]+Z[1]*J)}function HZ($,Z){return D7($[0],$[1]+Z)}function u0($,Z){return LZ(Z,$,-1)}function C0($,Z){return t1($[0],Z[0])||t1($[1],Z[1])}function V5($,Z,J){return C0($,Z)===-1||C0($,J)===1}function m6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function MZ($,Z=1){let J=c/Z,[W,Y]=Z$($,J);return[W,Y*Z]}function U5($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=c/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function l0($,Z=1,J){let[W,Y]=$,[j,z]=Z$(Y,Z);return W*(c/Z)+(j+(J?z/Z:0))}function O7($,Z,J=S1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(c/Z)+j,z]}function L7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function H7($){return q0($,"isoYear",O3,D3,1),$.isoYear===O3?q0($,"isoMonth",4,12,1):$.isoYear===D3&&q0($,"isoMonth",1,9,1),$}function e1($){return R1({...$,...r0,isoHour:12}),$}function R1($){let Z=q0($,"isoYear",O3,D3,1),J=Z===O3?1:Z===D3?-1:0;return J&&i0(x0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function i0($){if(!$||V5($,YV,WV))throw RangeError(F4);return $}function J$($){return J5($,5,W1)[1]}function h6($){let[Z,J]=S1($,c);return[y6(J,5,W1),Z]}function D5($){return O5($)[0]}function O5($){return O7($,a0)}function A0($){return IZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function x0($){let Z=A0($);if(Z!==void 0){let[J,W]=Z$(Z,v0);return[J,W*F1+($.isoMicrosecond||0)*m$+($.isoNanosecond||0)]}}function M7($,Z){let[J,W]=h6(J$($)-Z);return i0(x0({...$,isoDay:$.isoDay+W,...J}))}function A6(...$){return IZ(...$)/lz}function IZ(...$){let[Z,J]=L5(...$),W=Z.valueOf();if(!isNaN(W))return W-J*v0}function L5($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===O3?1:$===D3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function Y$($,Z){let[J,W]=HZ($,Z);W<0&&(W+=c,J-=1);let[Y,j]=S1(W,F1),[z,X]=S1(j,m$);return p6(J*v0+Y,z,X)}function p6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-JV)/v0)*Math.sign($),Y=new Date($-W*v0);return NZ(H4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function H5($){return[$.isoYear,$.isoMonth,$.isoDay]}function M5(){return A1}function P7($,Z){switch(Z){case 2:return T7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function P5($){return T7($)?366:365}function T7($){return $%4==0&&($%100!=0||$%400==0)}function T5($){let[Z,J]=L5($.isoYear,$.isoMonth,$.isoDay);return K3(Z.getUTCDay()-J,7)||7}function N5({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function XF($){let Z=A0($);if(Z<zV)return N5($);let J=L7(s2(PZ),Z),{era:W,eraYear:Y}=kj(J,PZ);return[W,Y]}function c6($){return R$($),d6($,1),$}function R$($){return I5($,1),$}function gY($){return $5(m2,$,I5($))}function I5($,Z){let{isoYear:J}=$,W=q0($,"isoMonth",1,M5(),Z);return{isoYear:J,isoMonth:W,isoDay:q0($,"isoDay",1,P7(J,W),Z)}}function d6($,Z){return NZ(W1,[q0($,"isoHour",0,23,Z),q0($,"isoMinute",0,59,Z),q0($,"isoSecond",0,59,Z),q0($,"isoMillisecond",0,999,Z),q0($,"isoMicrosecond",0,999,Z),q0($,"isoNanosecond",0,999,Z)])}function v($){return $===void 0?0:QX(b1($))}function P3($,Z=0){$=$1($);let J=GX($),W=OV($,Z);return[QX($),W,J]}function N7($){return GX($1($))}function _5($){return $=$1($),c2($,9,6,1)}function _Z($,Z,J,W=9,Y=0,j=4){Z=$1(Z);let z=c2(Z,W,Y),X=x7(Z),Q=b3(Z,j),G=E3(Z,W,Y,1);return z==null?z=Math.max(J,G):S5(z,G),X=C7(X,G,1),$&&(Q=((K)=>K<4?(K+2)%4:K)(Q)),[z,G,X,Q]}function u6($,Z=6,J){let W=x7($=A7($,k6)),Y=b3($,7),j=E3($,Z);return j=Q5(k6,j),W=C7(W,j,void 0,J),[j,W,Y]}function I7($){return d2($1($))}function x5($,Z){return _7($1($),Z)}function _7($,Z=4){let J=A5($);return[b3($,4),...C5(E3($,Z),J)]}function C5($,Z){return $!=null?[B1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function x7($){let Z=$[B3];return Z===void 0?1:_0(Z,B3)}function C7($,Z,J,W){let Y=W?c:B1[Z+1];if(Y){let j=B1[Z];if(Y%(($=n0(B3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(x3(B3,$))}else $=n0(B3,$,1,J?1e9:1,1);return $}function A5($){let Z=$[e8];if(Z!==void 0){if(typeof Z!="number"){if(U7(Z)==="auto")return;throw RangeError(x3(e8,Z))}Z=n0(e8,Math.floor(Z),0,9,1)}return Z}function $1($){return $===void 0?{}:b1($)}function A7($,Z){return typeof $=="string"?{[Z]:$}:b1($)}function Y0($){if($!==void 0){if(V0($))return Object.assign(Object.create(null),$);throw TypeError(kz)}}function l6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:QV[Z]})}function S7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=U7(j),j==="auto")return Y?W:null;let z=Y7[j];if(z===void 0&&(z=$V[j]),z===void 0)throw RangeError(vz($,j,Y7));return n0($,z,W,J,1,A3),z}function f$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=U7(Y),z=Z[j];if(z===void 0)throw RangeError(vz($,j,Z));return z}function S5($,Z){if(Z>$)throw RangeError(iF)}function U0($){return{branding:P4,epochNanoseconds:$}}function L0($,Z,J){return{branding:q1,calendar:J,timeZone:Z,epochNanoseconds:$}}function j0($,Z=$.calendar){return{branding:p$,calendar:Z,...h0(YX,$)}}function z0($,Z=$.calendar){return{branding:h$,calendar:Z,...h0(h2,$)}}function S$($,Z=$.calendar){return{branding:fZ,calendar:Z,...h0(h2,$)}}function S6($,Z=$.calendar){return{branding:kZ,calendar:Z,...h0(h2,$)}}function Z1($){return{branding:M4,...h0(WX,$)}}function a($){return{branding:T4,sign:j$($),...h0(y2,$)}}function E5($){return D5($.epochNanoseconds)}function i6($){return O7($.epochNanoseconds,F1)[0]}function b5($){return U5($.epochNanoseconds,m$)}function R5($){return U5($.epochNanoseconds)}function f5($){return $.epochNanoseconds}function D0($){return typeof $=="string"?$:e($.id)}function xZ($,Z){return $===Z||D0($)===D0(Z)}function k5($,Z,J,W,Y){let j=E$(W),[z,X]=((O,L)=>{let T=L((O=A7(O,X7))[zX]),P=DV(O);return P=Q5(X7,P),[P,T]})(Y,$);if(V3(Math.max(z,j),X))return mY(W,z);if(!X)throw RangeError(V4);let[Q,G,K]=t6(Z,J,X),F=t7(K),B=e6(K),U=e7(K),V=B(G,Q,W),D=U(G,Q,V,z);return V3(z,X)?mY(D,z):((O,L,T,P,_,A,E)=>{let S=j$(O),[f,M]=E7(P,g2(T,O),T,S,_,A,E),I=b7(L,f,M);return O[m[T]]+I*S})(D,F(V),z,G,Q,F,B)}function mY($,Z){return l0(F0($),B1[Z],1)}function E7($,Z,J,W,Y,j,z){let X=m[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),K=z($,Y,Q);return[j(G),j(K)]}function b7($,Z,J){let W=l0(u0(Z,J));if(!W)throw RangeError(C3);return l0(u0(Z,$))/W}function w5($,Z){let[J,W,Y]=u6(Z,5,1);return U0(n6($.epochNanoseconds,J,W,Y,1))}function q5($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=u6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((K,F,B,U)=>{let V=S0(B,F),[D,O]=K(V),L=B.epochNanoseconds,T=m0(F,D),P=m0(F,O);if(V5(L,T,P))throw RangeError(C3);return u5(b7(L,T,P),U)?P:T})(c5,G,Z,Q);else{let K=G.getOffsetNanosecondsFor(W);W=w$(G,h5(Y$(W,K),z,X,Q),K,2,0,1)}return L0(W,Y,j)}function y5($,Z){return j0(h5($,...u6(Z)),$.calendar)}function v5($,Z){let[J,W,Y]=u6(Z,5);var j;return Z1((j=Y,R7($,T3(J,W),j)[0]))}function g5($,Z){let J=$(Z.timeZone),W=S0(Z,J),[Y,j]=c5(W),z=l0(u0(m0(J,Y),m0(J,j)),D4,1);if(z<=0)throw RangeError(C3);return z}function m5($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>m0(z,j(S0(X,z))))(d5,$(J),Z);return L0(Y,J,W)}function h5($,Z,J,W){return p5($,T3(Z,J),W)}function p5($,Z,J){let[W,Y]=R7($,Z,J);return R1({...q$($,Y),...W})}function R7($,Z,J){return h6(W$(J$($),Z,J))}function E6($){return W$($,U4,7)}function T3($,Z){return B1[$]*Z}function c5($){let Z=d5($);return[Z,q$(Z,1)]}function d5($){return ZV(6,$)}function QF($,Z,J){let W=Math.min(E$($),6);return AZ(o6(F0($,W),Z,J),W)}function s6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let K=V3(W,X)?$4(X)&&W<6&&J>=6?KF:GF:BF,[F,B,U]=K($,Z,J,W,Y,j,z,X,Q,G);return U&&W!==7&&(F=((V,D,O,L,T,P,_,A)=>{let E=j$(V);for(let S=L+1;S<=O;S++){if(S===7&&O!==7)continue;let f=g2(S,V);f[m[S]]+=E;let M=l0(u0(_(A(T,P,f)),D));if(M&&Math.sign(M)!==E)break;V=f}return V})(F,B,J,Math.max(6,W),z,X,Q,G)),F}function n6($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/c)($);return[W$(j,J,W),0]}return o6($,T3(Z,J),W,Y)}function o6($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=c,Y-=1);let[z,X]=S1(W$(j,Z,J),c);return D7(Y+z,X)}function W$($,Z,J){return u5($/Z,J)*Z}function u5($,Z){return MV[Z]($)}function GF($,Z,J,W,Y,j){let z=j$($),X=F0($),Q=n6(X,W,Y,j),G=u0(X,Q),K=Math.sign(Q[0]-X[0])===z,F=AZ(Q,Math.min(J,6));return[{...$,...F},LZ(Z,G),K]}function KF($,Z,J,W,Y,j,z,X,Q,G){let K=j$($),F=l0(F0($,5)),B=T3(W,Y),U=W$(F,B,j),[V,D]=E7(z,{...$,...v2},6,K,X,Q,G),O=U-l0(u0(V,D)),L=0;O&&Math.sign(O)!==K?Z=HZ(V,U):(L+=K,U=W$(O,B,j),Z=HZ(D,U));let T=J4(U);return[{...$,...T,days:$.days+L},Z,Boolean(L)]}function BF($,Z,J,W,Y,j,z,X,Q,G){let K=j$($),F=m[W],B=g2(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=q6($[F],Y)*Y;B[F]=U;let[V,D]=E7(z,B,W,Y*K,X,Q,G),O=U+b7(Z,V,D)*K*Y,L=W$(O,Y,j),T=Math.sign(L-O)===K;return B[F]=L,[B,T?D:V,T]}function f7($,Z,J,W){let[Y,j,z,X]=((G)=>{let K=_7(G=$1(G));return[G.timeZone,...K]})(W),Q=Y!==void 0;return((G,K,F,B,U,V)=>{F=o6(F,U,B,1);let D=K.getOffsetNanosecondsFor(F);return m7(Y$(F,D),V)+(G?k$(E6(D)):"Z")})(Q,Z(Q?$(Y):c$),J.epochNanoseconds,j,z,X)}function k7($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=$1(G);let K=d2(G),F=A5(G),B=HV(G),U=b3(G,4),V=E3(G,4);return[K,LV(G),B,U,...C5(V,F)]})(J);return((G,K,F,B,U,V,D,O,L,T)=>{B=o6(B,L,O,1);let P=G(F).getOffsetNanosecondsFor(B);return m7(Y$(B,P),T)+k$(E6(P),D)+((_,A)=>A!==1?"["+(A===2?"!":"")+D0(_)+"]":"")(F,V)+h7(K,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function w7($,Z){let[J,W,Y,j]=((G)=>(G=$1(G),[d2(G),..._7(G)]))(Z);return z=$.calendar,X=J,Q=j,m7(p5($,Y,W),Q)+h7(z,X);var z,X,Q}function q7($,Z){return J=$.calendar,W=$,Y=I7(Z),b6(W)+h7(J,Y);var J,W,Y}function y7($,Z){return l5($.calendar,i5,$,I7(Z))}function v7($,Z){return l5($.calendar,FF,$,I7(Z))}function g7($,Z){let[J,W,Y]=x5(Z);return j=Y,s5(R7($,W,J)[0],j);var j}function a6($,Z){let[J,W,Y]=x5(Z,3);return W>1&&($={...$,...QF($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?E0(j):j,{hours:G,minutes:K}=Q,[F,B]=O7(F0(Q,3),a0,Z$);Zj(F);let U=p7(B,z),V=z>=0||!X||U;return(X<0?"-":"")+"P"+hY({Y:A$(Q.years),M:A$(Q.months),W:A$(Q.weeks),D:A$(Q.days)})+(G||K||F||V?"T"+hY({H:A$(G),M:A$(K),S:A$(F,V)+U}):"")})($,Y)}function l5($,Z,J,W){let Y=D0($),j=W>1||W===0&&Y!==w;return W===1?Y===w?Z(J):b6(J):j?b6(J)+n5(Y,W===2):Z(J)}function hY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function m7($,Z){return b6($)+"T"+s5($,Z)}function b6($){return i5($)+"-"+o0($.isoDay)}function i5($){let{isoYear:Z}=$;return(Z<0||Z>9999?o5(Z)+x6(6,Math.abs(Z)):x6(4,Z))+"-"+o0($.isoMonth)}function FF($){return o0($.isoMonth)+"-"+o0($.isoDay)}function s5($,Z){let J=[o0($.isoHour),o0($.isoMinute)];return Z!==-1&&J.push(o0($.isoSecond)+((W,Y,j,z)=>p7(W*F1+Y*m$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function k$($,Z=0){if(Z===1)return"";let[J,W]=S1(Math.abs($),D4),[Y,j]=S1(W,U4),[z,X]=S1(j,a0);return o5($)+o0(J)+":"+o0(Y)+(z||X?":"+o0(z)+p7(X):"")}function h7($,Z){if(Z!==1){let J=D0($);if(Z>1||Z===0&&J!==w)return n5(J,Z===2)}return""}function n5($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function p7($,Z){let J=x6(9,$);return J=Z===void 0?J.replace(NV,""):J.slice(0,Z),J?"."+J:""}function o5($){return $<0?"-":"+"}function A$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function VF($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=Y$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function a5($,Z){let J=S0(Z,$);return{calendar:Z.calendar,...h0(YX,J),offset:k$(J.offsetNanoseconds),timeZone:Z.timeZone}}function w$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return M7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,K,F,B)=>{let U=x0(K);B&&(F=E6(F));for(let V of G){let D=l0(u0(V,U));if(B&&(D=E6(D)),D===F)return V}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(hF)}return z?x0(Z):m0($,Z,Y,X)}function m0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(pF);if(W.length)return W[J===3?1:0];let Y=x0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(HZ(Q,-c));return d7(X.getOffsetNanosecondsFor(HZ(Q,c))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(Y$(Y,z)))[J===2?0:W.length-1]}function c7($){if(Math.abs($)>=c)throw RangeError(gF);return $}function d7($){if($>c)throw RangeError(mF);return $}function u7($,Z,J){return U0(i0(LZ(Z.epochNanoseconds,((W)=>{if(Jj(W))throw RangeError(uF);return F0(W,5)})($?E0(J):J))))}function l7($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...a7(z,X,W,J?E0(Y):Y,j)}}function i7($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return j0(r7($(j),J,Z?E0(W):W,Y),j)}function s7($,Z,J,W,Y){let{calendar:j}=J;return z0(r6($(j),J,Z?E0(W):W,Y),j)}function n7($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=F3(z,J);Z&&(W=Z4(W)),W.sign<0&&(X=z.dateAdd(X,{...O0,months:1}),X=q$(X,-1));let Q=z.dateAdd(X,W,Y);return S$(F3(z,Q),j)}function o7($,Z,J){return Z1(r5(Z,$?E0(J):J)[0])}function a7($,Z,J,W,Y){let j=F0(W,5),z=J.epochNanoseconds;if(Jj(W)){let X=S0(J,$);z=LZ(m0($,{...r6(Z,X,{...W,...v2},Y),...h0(W1,X)}),j)}else z=LZ(z,j),v(Y);return{epochNanoseconds:i0(z)}}function r7($,Z,J,W){let[Y,j]=r5(Z,J);return R1({...r6($,Z,{...J,...v2,days:J.days+j},W),...Y})}function r6($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);v(W);let Y=J.days+F0(J,5)[0];return Y?e1(q$(Z,Y)):Z}function F3($,Z,J=1){return q$(Z,J-$.day(Z))}function r5($,Z){let[J,W]=F0(Z,5),[Y,j]=h6(J$($)+W);return[Y,J+j]}function q$($,Z){return Z?{...$,...p6(A0($)+Z*v0)}:$}function t6($,Z,J){let W=$(J.calendar);return $4(J)?[J,W,Z(J.timeZone)]:[{...J,...r0},W]}function t7($){return $?f5:x0}function e6($){return $?k(a7,$):r7}function e7($){return $?k(DF,$):OF}function $4($){return $&&$.epochNanoseconds}function V3($,Z){return $<=6-($4(Z)?1:0)}function $2($,Z,J,W,Y,j,z){let X=$($1(z).relativeTo),Q=Math.max(E$(Y),E$(j));if(V3(Q,X))return a(CZ(((D,O,L,T)=>{let P=LZ(F0(D),F0(O),T?-1:1);if(!Number.isFinite(P[0]))throw RangeError(F4);return{...O0,...AZ(P,L)}})(Y,j,Q,W)));if(!X)throw RangeError(V4);W&&(j=E0(j));let[G,K,F]=t6(Z,J,X),B=e6(F),U=e7(F),V=B(K,G,Y);return a(U(K,G,B(K,V,j),Q))}function t5($,Z,J,W,Y){let j=E$(W),[z,X,Q,G,K]=((E,S,f)=>{E=A7(E,k6);let M=c2(E),I=f(E[zX]),y=x7(E),H$=b3(E,7),T0=E3(E);if(M===void 0&&T0===void 0)throw RangeError(lF);return T0==null&&(T0=0),M==null&&(M=Math.max(T0,S)),S5(M,T0),y=C7(y,T0,1),[M,T0,y,H$,I]})(Y,j,$),F=Math.max(j,z);if(!$4(K)&&F<=6)return a(CZ(((E,S,f,M,I)=>{let y=n6(F0(E),f,M,I);return{...O0,...AZ(y,S)}})(W,z,X,Q,G)));if(!K)throw RangeError(V4);let[B,U,V]=t6(Z,J,K),D=t7(V),O=e6(V),L=e7(V),T=O(U,B,W),P=L(U,B,T,z),_=W.sign,A=j$(P);if(_&&A&&_!==A)throw RangeError(C3);return A&&(P=s6(P,D(T),z,X,Q,G,U,B,D,O)),a(P)}function e5($){return $.sign===-1?Z4($):$}function Z4($){return a(E0($))}function E0($){let Z={};for(let J of m)Z[J]=-1*$[J]||0;return Z}function $j($){return!$.sign}function j$($,Z=m){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(dF);J=Y}}return J}function CZ($){for(let Z of eF)n0(Z,$[Z],-sY,sY,1);return Zj(l0(F0($),a0)),$}function Zj($){if(!Number.isSafeInteger($))throw RangeError(cF)}function F0($,Z=6){return J5($,Z,m)}function AZ($,Z=6){let[J,W]=$,Y=y6(W,Z,m);if(Y[m[Z]]+=J*(c/B1[Z]),!Number.isFinite(Y[m[Z]]))throw RangeError(F4);return Y}function J4($,Z=5){return y6($,Z,m)}function Jj($){return Boolean(j$($,JX))}function E$($){let Z=9;for(;Z>0&&!$[m[Z]];Z--);return Z}function UF($,Z){return[$,Z]}function pY($){let Z=Math.floor($/I6)*I6;return[Z,Z+I6]}function Wj($){let Z=z$($=C6($));if(!Z)throw RangeError(y0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(y0($));J=SZ(Z.offset)}return Z.timeZone&&Y2(Z.timeZone,1),U0(M7(c6(Z),J))}function Yj($){let Z=z$(e($));if(!Z)throw RangeError(y0($));if(Z.timeZone)return Vj(Z,Z.offset?SZ(Z.offset):void 0);if(Z.m)throw RangeError(y0($));return Dj(Z)}function jj($,Z){let J=z$(e($));if(!J||!J.timeZone)throw RangeError(y0($));let{offset:W}=J,Y=W?SZ(W):void 0,[,j,z]=P3(Z);return Vj(J,Y,j,z)}function SZ($){let Z=Y2($);if(Z===void 0)throw RangeError(y0($));return Z}function zj($){let Z=z$(e($));if(!Z||Z.m)throw RangeError(y0($));return j0(Uj(Z))}function W4($){let Z=z$(e($));if(!Z||Z.m)throw RangeError(y0($));return z0(Z.p?Uj(Z):Dj(Z))}function Xj($,Z){let J=J2(e(Z));if(J)return Z2(J),S$(H7(R$(J)));let W=W4(Z);return S$(F3($(W.calendar),W))}function Z2($){if($.calendar!==w)throw RangeError(E1($.calendar))}function Qj($,Z){let J=W2(e(Z));if(J)return Z2(J),S6(R$(J));let W=W4(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,K]=j.I(z,X),[F,B]=j.N(G,K,Q);return S6(e1(j.P(F,B,Q)),Y)}function Gj($){let Z,J=((W)=>{let Y=AV.exec(W);return Y?(Y4(Y[10]),Hj(Y)):void 0})(e($));if(!J){if(J=z$($),!J)throw RangeError(y0($));if(!J.p)throw RangeError(y0($));if(J.m)throw RangeError(E1("Z"));Z2(J)}if((Z=J2($))&&gY(Z))throw RangeError(y0($));if((Z=W2($))&&gY(Z))throw RangeError(y0($));return Z1(d6(J,1))}function Kj($){let Z=((J)=>{let W=bV.exec(J);return W?((Y)=>{function j(K,F,B){let U=0,V=0;if(B&&([U,Q]=S1(Q,B1[B])),K!==void 0){if(X)throw RangeError(E1(K));V=((D)=>{let O=parseInt(D);if(!Number.isFinite(O))throw RangeError(E1(D));return O})(K),z=1,F&&(Q=j2(F)*(B1[B]/a0),X=1)}return U+V}let z=0,X=0,Q=0,G={...NZ(m,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...y6(Q,2,m)};if(!z)throw RangeError(qz(m));return z2(Y[1])<0&&(G=E0(G)),G})(W):void 0})(e($));if(!Z)throw RangeError(y0($));return a(CZ(Z))}function Bj($){let Z=z$($)||J2($)||W2($);return Z?Z.calendar:$}function Fj($){let Z=z$($);return Z&&(Z.timeZone||Z.m&&c$||Z.offset)||$}function Vj($,Z,J=0,W=0){let Y=j4($.timeZone),j=N4(Y);return L0(w$(j,c6($),Z,J,W,!j.v,$.m),Y,N3($.calendar))}function Uj($){return Oj(R1(c6($)))}function Dj($){return Oj(e1(R$($)))}function Oj($){return{...$,calendar:N3($.calendar)}}function z$($){let Z=CV.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:Lj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...Hj(J.slice(5)),...Y4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function J2($){let Z=_V.exec($);return Z?((J)=>({isoYear:Lj(J),isoMonth:parseInt(J[4]),isoDay:1,...Y4(J[5])}))(Z):void 0}function W2($){let Z=xV.exec($);return Z?((J)=>({isoYear:TZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...Y4(J[3])}))(Z):void 0}function Y2($,Z){let J=SV.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(E1(j));return c7((OZ(W[2])*D4+OZ(W[3])*U4+OZ(W[4])*a0+j2(W[5]||""))*z2(W[1]))})(J,Z):void 0}function Lj($){let Z=z2($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(E1(-0));return Z*J}function Hj($){let Z=OZ($[3]);return{...h6(j2($[4]||""))[0],isoHour:OZ($[1]),isoMinute:OZ($[2]),isoSecond:Z===60?59:Z}}function Y4($){let Z,J,W=[];if($.replace(EV,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(E1(Y))}else{if(J)throw RangeError(E1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(E1($));return{timeZone:J,calendar:W[0]||w}}function j2($){return parseInt($.padEnd(9,"0"))}function EZ($){return new RegExp(`^${$}$`,"i")}function z2($){return $&&$!=="+"?-1:1}function OZ($){return $===void 0?0:parseInt($)}function Mj($){return j4(e($))}function j4($){let Z=X2($);return typeof Z=="number"?k$(Z):Z?((J)=>{if(fV.test(J))throw RangeError(vF);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?yY(j).replace(/island|noronha|murdo|rivadavia|urville/,yY):j)).join("/")})($):c$}function cY($){let Z=X2($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:c$}function X2($){let Z=Y2($=$.toUpperCase(),1);return Z!==void 0?Z:$!==c$?RV($):void 0}function Q2($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function G2($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function Pj($,Z,J,W,Y,j){let z=$($1(j).relativeTo),X=Math.max(E$(W),E$(Y));if($5(m,W,Y))return 0;if(V3(X,z))return C0(F0(W),F0(Y));if(!z)throw RangeError(V4);let[Q,G,K]=t6(Z,J,z),F=t7(K),B=e6(K);return C0(F(B(G,Q,W)),F(B(G,Q,Y)))}function K2($,Z){return y$($,Z)||z4($,Z)}function y$($,Z){return t1(A0($),A0(Z))}function z4($,Z){return t1(J$($),J$(Z))}function Tj($,Z){return!Q2($,Z)}function Nj($,Z){return!G2($,Z)&&!!X4($.timeZone,Z.timeZone)&&xZ($.calendar,Z.calendar)}function Ij($,Z){return!K2($,Z)&&xZ($.calendar,Z.calendar)}function _j($,Z){return!y$($,Z)&&xZ($.calendar,Z.calendar)}function xj($,Z){return!y$($,Z)&&xZ($.calendar,Z.calendar)}function Cj($,Z){return!y$($,Z)&&xZ($.calendar,Z.calendar)}function Aj($,Z){return!z4($,Z)}function X4($,Z){if($===Z)return 1;let J=D0($),W=D0(Z);if(J===W)return 1;try{return cY(J)===cY(W)}catch(Y){}}function B2($,Z,J,W){let Y=_Z($,Y0(W),3,5),j=Q4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return a($?E0(j):j)}function F2($,Z,J,W,Y,j){let z=K4(W.calendar,Y.calendar),X=Y0(j),[Q,G,K,F]=_Z(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,V=C0(U,B),D;if(V)if(Q<6)D=Q4(B,U,Q,G,K,F);else{let O=Z(((T,P)=>{if(!X4(T,P))throw RangeError(pz);return T})(W.timeZone,Y.timeZone)),L=$(z);D=Ej(L,O,W,Y,V,Q,X),D=s6(D,U,Q,G,K,F,L,W,f5,k(a7,O))}else D=O0;return a(J?E0(D):D)}function V2($,Z,J,W,Y){let j=K4(J.calendar,W.calendar),z=Y0(Y),[X,Q,G,K]=_Z(Z,z,6),F=x0(J),B=x0(W),U=C0(B,F),V;if(U)if(X<=6)V=Q4(F,B,X,Q,G,K);else{let D=$(j);V=bj(D,J,W,U,X,z),V=s6(V,B,X,Q,G,K,D,J,x0,r7)}else V=O0;return a(Z?E0(V):V)}function U2($,Z,J,W,Y){let j=K4(J.calendar,W.calendar),z=Y0(Y);return Sj(Z,()=>$(j),J,W,..._Z(Z,z,6,9,6),z)}function D2($,Z,J,W,Y){let j=K4(J.calendar,W.calendar),z=Y0(Y),X=_Z(Z,z,9,9,8),Q=$(j);return Sj(Z,()=>Q,F3(Q,J),F3(Q,W),...X,z)}function Sj($,Z,J,W,Y,j,z,X,Q){let G=x0(J),K=x0(W),F;if(C0(K,G))if(Y===6)F=Q4(G,K,Y,j,z,X);else{let B=Z();F=B.dateUntil(J,W,Y,Q),j===6&&z===1||(F=s6(F,K,Y,j,z,X,B,J,x0,r6))}else F=O0;return a($?E0(F):F)}function O2($,Z,J,W){let Y=Y0(W),[j,z,X,Q]=_Z($,Y,5,5),G=W$(L2(Z,J),T3(z,X),Q),K={...O0,...J4(G,j)};return a($?E0(K):K)}function DF($,Z,J,W,Y,j){let z=C0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Rj(J.epochNanoseconds,W.epochNanoseconds,Y):Ej(Z,$,J,W,z,Y,j):O0}function OF($,Z,J,W,Y){let j=x0(Z),z=x0(J),X=C0(z,j);return X?W<=6?Rj(j,z,W):bj($,Z,J,X,W,Y):O0}function Ej($,Z,J,W,Y,j,z){let[X,Q,G]=((B,U,V,D)=>{function O(){return S={...q$(P,A++*-D),...T},f=m0(B,S),C0(_,f)===-D}let L=S0(U,B),T=h0(W1,L),P=S0(V,B),_=V.epochNanoseconds,A=0,E=L2(L,P),S,f;if(Math.sign(E)===-D&&A++,O()&&(D===-1||O()))throw RangeError(C3);let M=l0(u0(f,_));return[L,S,M]})(Z,J,W,Y);var K,F;return{...j===6?(K=X,F=Q,{...O0,days:fj(K,F)}):$.dateUntil(X,Q,j,z),...J4(G)}}function bj($,Z,J,W,Y,j){let[z,X,Q]=((G,K,F)=>{let B=K,U=L2(G,K);return Math.sign(U)===-F&&(B=q$(K,-F),U+=c*F),[G,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...J4(Q)}}function Q4($,Z,J,W,Y,j){return{...O0,...AZ(n6(u0($,Z),W,Y,j),J)}}function Rj($,Z,J){return{...O0,...AZ(u0($,Z),J)}}function fj($,Z){return G4(A0($),A0(Z))}function G4($,Z){return Math.trunc((Z-$)/v0)}function L2($,Z){return J$(Z)-J$($)}function K4($,Z){if(!xZ($,Z))throw RangeError(f2);return $}function LF($){function Z(Y){return((j,z)=>({...kj(j,z),F:j.month,day:parseInt(j.day)}))(L7(J,Y),W)}let J=s2($),W=R6($);return{id:$,O:HF(Z),B:MF(Z)}}function HF($){return g0((Z)=>{let J=A0(Z);return $(J)},WeakMap)}function MF($){let Z=$(0).year-jV;return g0((J)=>{let W,Y=IZ(J-Z),j=[],z=[];do Y+=400*v0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*v0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=v0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:uz(z.reverse())}})}function kj($,Z){let J,W,Y=wj($);if($.era){let j=ez[Z];j!==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=Y,Y=mj(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function wj($){return parseInt($.relatedYear||$.year)}function Z7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function U3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*v0}function P6($){let Z=uY(this,$),J=uY(this,$-1),W=Z.length;if(W>J.length){let Y=hj(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function T6($){return G4(U3.call(this,$),U3.call(this,$+1))}function dY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),G4(J[Z-1],Y[W-1])}function N6($){return this.B($).k.length}function uY($,Z){return Object.keys($.B(Z).C)}function qj($){return N3(e($))}function N3($){if(($=$.toLowerCase())!==w&&$!==L4&&R6($)!==R6(s2($).resolvedOptions().calendar))throw RangeError(yF($));return $}function R6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function yj($){return this.R($)[0]}function vj($){return this.R($)[1]}function H2($){let[Z]=this.h($);return G4(this.q(Z),A0($))+1}function gj($){let Z=wV.exec($);if(!Z)throw RangeError(wF($));return[parseInt(Z[1]),Boolean(Z[2])]}function f6($,Z,J){return $+(Z||J&&$>=J?1:0)}function J7($,Z){return $-(Z&&$>=Z?1:0)}function mj($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function W7($){return ez[pj($)]}function hj($){return aF[pj($)]}function pj($){return R6($.id||w)}function cj($,Z,J,W){let Y=X$(J,W,J1,[],oz);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=v$(Y),X=$(Y.timeZone);return{epochNanoseconds:w$(Z(X),{...j,...z},Y.offset!==void 0?SZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...r0}}function dj($,Z,J,W,Y,j){let z=X$(J,Y,J1,sz,oz),X=$(z.timeZone),[Q,G,K]=P3(j),F=J.dateFromFields(z,l6(j,Q)),B=v$(z,Q);return L0(w$(Z(X),{...F,...B},z.offset!==void 0?SZ(z.offset):void 0,G,K),X,W)}function uj($,Z,J){let W=X$($,Z,J1,[],w1),Y=v(J);return j0(R1({...$.dateFromFields(W,l6(J,Y)),...v$(W,Y)}))}function M2($,Z,J,W=[]){let Y=X$($,Z,J1,W);return $.dateFromFields(Y,J)}function P2($,Z,J,W){let Y=X$($,Z,q2,W);return $.yearMonthFromFields(Y,J)}function T2($,Z,J,W,Y=[]){let j=X$($,J,J1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=TZ),$.monthDayFromFields(j,W)}function lj($,Z){let J=v(Z);return Z1(v$(K1($,j7,[],1),J))}function ij($){let Z=K1($,y2);return a(CZ({...O0,...Z}))}function X$($,Z,J,W=[],Y=[]){return K1(Z,[...$.fields(J),...Y].sort(),W)}function K1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(SF(X));if(X==="constructor"||X==="__proto__")throw RangeError(b2(X));let Q=$[X];if(Q!==void 0)z=1,nY[X]&&(Q=nY[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(E2(X));Y[X]=tz[X]}j=X}if(W&&!z)throw TypeError(qz(Z));return Y}function v$($,Z){return d6(gV({...tz,...$}),Z)}function sj($,Z,J,W,Y,j){let z=Y0(j),{calendar:X,timeZone:Q}=J;return L0(((G,K,F,B,U)=>{let V=I3(G,F,B,J1,nz,iz),[D,O,L]=P3(U,2);return w$(K,{...G.dateFromFields(V,l6(U,D)),...v$(V,D)},SZ(V.offset),O,L)})($(X),Z(Q),W,Y,z),Q,X)}function nj($,Z,J,W,Y){let j=Y0(Y);return j0(((z,X,Q,G)=>{let K=I3(z,X,Q,J1,w1),F=v(G);return R1({...z.dateFromFields(K,l6(G,F)),...v$(K,F)})})($(Z.calendar),J,W,j))}function oj($,Z,J,W,Y){let j=Y0(Y);return((z,X,Q,G)=>{let K=I3(z,X,Q,J1);return z.dateFromFields(K,G)})($(Z.calendar),J,W,j)}function aj($,Z,J,W,Y){let j=Y0(Y);return S$(((z,X,Q,G)=>{let K=I3(z,X,Q,q2);return z.yearMonthFromFields(K,G)})($(Z.calendar),J,W,j))}function rj($,Z,J,W,Y){let j=Y0(Y);return((z,X,Q,G)=>{let K=I3(z,X,Q,J1);return z.monthDayFromFields(K,G)})($(Z.calendar),J,W,j)}function tj($,Z,J){return Z1(((W,Y,j)=>{let z=v(j);return v$({...h0(j7,W),...K1(Y,j7)},z)})($,Z,J))}function ej($,Z){return a((J=$,W=Z,CZ({...J,...K1(W,y2)})));var J,W}function I3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=K1(Z,z,j),Q=K1(J,z);return X=$.mergeFields(X,Q),K1(X,z,[])}function N2($,Z){let J=X$($,Z,rz);return $.monthDayFromFields(J)}function I2($,Z,J){let W=X$($,Z,az);return $.yearMonthFromFields(W,J)}function $z($,Z,J,W,Y){Z=h0(J=$.fields(J),Z),W=K1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=K1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function a8($,Z){let{era:J,eraYear:W,year:Y}=Z,j=W7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(bF);if(!j)throw RangeError(EF);let z=j[J];if(z===void 0)throw RangeError(fF(J));let X=mj(W,z);if(Y!==void 0&&Y!==X)throw RangeError(RF);Y=X}else if(Y===void 0)throw TypeError(kF(j));return Y}function r8($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,K)=>{let F=X.U(G),[B,U]=gj(Q),V=f6(B,U,F);if(U){let D=hj(X);if(D===void 0)throw RangeError(G3);if(D>0){if(V>D)throw RangeError(G3);if(F===void 0){if(K===1)throw RangeError(G3);V--}}else{if(V!==-D)throw RangeError(G3);if(F===void 0&&K===1)throw RangeError(G3)}}return V})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(mz);Y=z,W=1}else if(Y===void 0)throw TypeError(qF);return n0("month",Y,1,$.L(J),W)}function lY($,Z,J,W,Y){return q0(Z,"day",1,$.j(W,J),Y)}function t8($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Zz($){return U0(i0(m6(g6($))))}function Jz($,Z,J,W,Y=w){return L0(i0(m6(g6(J))),Z(W),$(Y))}function Wz($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,K=w){return j0(R1(c6(t0(_0,NZ(H4,[Z,J,W,Y,j,z,X,Q,G])))),$(K))}function Yz($,Z,J,W,Y=w){return z0(e1(R$(t0(_0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function jz($,Z,J,W=w,Y=1){let j=_0(Z),z=_0(J),X=$(W);return S$(H7(R$({isoYear:j,isoMonth:z,isoDay:_0(Y)})),X)}function zz($,Z,J,W=w,Y=TZ){let j=_0(Z),z=_0(J),X=$(W);return S6(e1(R$({isoYear:_0(Y),isoMonth:j,isoDay:z})),X)}function Xz($=0,Z=0,J=0,W=0,Y=0,j=0){return Z1(d6(t0(_0,NZ(W1,[$,Z,J,W,Y,j])),1))}function Qz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return a(CZ(t0(F5,NZ(m,[$,Z,J,W,Y,j,z,X,Q,G]))))}function _2($,Z,J=w){return L0($.epochNanoseconds,Z,J)}function Gz($){return U0($.epochNanoseconds)}function x2($,Z){return j0(S0(Z,$))}function C2($,Z){return z0(S0(Z,$))}function Kz($,Z,J){return I2($(Z.calendar),J)}function Bz($,Z,J){return N2($(Z.calendar),J)}function A2($,Z){return Z1(S0(Z,$))}function Fz($,Z,J,W){let Y=((j,z,X,Q)=>{let G=N7(Q);return m0(j(z),X,G)})($,J,Z,W);return L0(i0(Y),J,Z.calendar)}function Vz($,Z,J){let W=$(Z.calendar);return S$({...Z,...I2(W,J)})}function Uz($,Z,J){return N2($(Z.calendar),J)}function Dz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):r0;return L0(m0(J(j),{...W,...X}),j,W.calendar)}function Oz($,Z=r0){return j0(R1({...$,...Z}))}function Lz($,Z,J){return I2($(Z.calendar),J)}function Hz($,Z,J){return N2($(Z.calendar),J)}function Mz($,Z,J,W){return((Y,j,z)=>$z(Y,j,az,b1(z),S3))($(Z.calendar),J,W)}function Pz($,Z,J,W){return((Y,j,z)=>$z(Y,j,rz,b1(z),O4))($(Z.calendar),J,W)}function Tz($,Z,J,W,Y){let j=b1(Y),z=Z(j.plainDate),X=$(j.timeZone);return L0(m0(J(X),{...z,...W}),X,z.calendar)}function Nz($,Z){return j0(R1({...$,...Z}))}function Iz($){return U0(i0(MZ($,a0)))}function _z($){return U0(i0(MZ($,F1)))}function xz($){return U0(i0(m6(g6($),m$)))}function Cz($){return U0(i0(m6(g6($))))}function Az($,Z,J=r0){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J};return L0(w$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function Sz($,Z,J){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J},z=fz(Z.calendar,J.calendar);return L0(w$(Y,j,j.offsetNanoseconds,2),W,z)}function Ez($,Z=r0){return j0({...$,...Z})}function bz($,Z){return j0({...$,...Z},fz($.calendar,Z.calendar))}function B4($,Z){return{...$,calendar:Z}}function Rz($,Z){return{...$,timeZone:Z}}function fz($,Z){if($===Z)return $;let J=D0($),W=D0(Z);if(J===W||J===w)return Z;if(W===w)return $;throw RangeError(f2)}function PF($,Z){return(J)=>J===w?$:J===L4||J===PZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),kV(J))}function g$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=G7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=c$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function f1($,Z=S2){let[J,,,W]=$;return(Y,j=$U,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...TF($,Q,z)]}}function S2($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(sF);J.timeZone=$}return new Q$(Z,J)}function TF($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==w)&&z!==X)throw RangeError(f2)})(D0(j.calendar),Z.calendar,Y),W(j,Z)))}function bZ($){let Z=_3();return Y$(Z,$.getOffsetNanosecondsFor(Z))}function _3(){return MZ(Date.now(),F1)}function k1(){return aY||(aY=new Q$().resolvedOptions().timeZone)}var NF=($,Z)=>`Non-integer ${$}: ${Z}`,IF=($,Z)=>`Non-positive ${$}: ${Z}`,_F=($,Z)=>`Non-finite ${$}: ${Z}`,xF=($)=>`Cannot convert bigint to ${$}`,CF=($)=>`Invalid bigint: ${$}`,AF="Cannot convert Symbol to string",kz="Invalid object",wz=($,Z,J,W,Y)=>Y?wz($,Y[Z],Y[J],Y[W]):x3($,Z)+`; must be between ${J}-${W}`,x3=($,Z)=>`Invalid ${$}: ${Z}`,E2=($)=>`Missing ${$}`,b2=($)=>`Invalid field ${$}`,SF=($)=>`Duplicate field ${$}`,qz=($)=>"No valid fields: "+$.join(),yz="Invalid bag",vz=($,Z,J)=>x3($,Z)+"; must be "+Object.keys(J).join(),gz="Cannot use valueOf",R2="Invalid calling context",EF="Forbidden era/eraYear",bF="Mismatching era/eraYear",RF="Mismatching year/eraYear",fF=($)=>`Invalid era: ${$}`,kF=($)=>"Missing year"+($?"/era/eraYear":""),wF=($)=>`Invalid monthCode: ${$}`,mz="Mismatching month/monthCode",qF="Missing month/monthCode",iY="Cannot guess year",G3="Invalid leap month",hz="Invalid protocol",C3="Invalid protocol results",f2="Mismatching Calendars",yF=($)=>`Invalid Calendar: ${$}`,pz="Mismatching TimeZones",vF="Forbidden ICU TimeZone",gF="Out-of-bounds offset",mF="Out-of-bounds TimeZone gap",hF="Invalid TimeZone offset",pF="Ambiguous offset",F4="Out-of-bounds date",cF="Out-of-bounds duration",dF="Cannot mix duration signs",V4="Missing relativeTo",uF="Cannot use large units",lF="Required smallestUnit or largestUnit",iF="smallestUnit > largestUnit",y0=($)=>`Cannot parse: ${$}`,E1=($)=>`Invalid substring: ${$}`,cz=($)=>`Cannot format ${$}`,dz="Mismatching types for formatting",sF="Cannot specify TimeZone",uz=k(L3,($,Z)=>Z),RZ=k(L3,($,Z,J)=>J),o0=k(x6,2),Y7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},A3=Object.keys(Y7),v0=86400000,lz=1000,m$=1000,F1=1e6,a0=1e9,U4=60000000000,D4=3600000000000,c=86400000000000,B1=[1,m$,F1,a0,U4,D4,c],w1=A3.slice(0,6),j7=H3(w1),iz=["offset"],sz=["timeZone"],nz=w1.concat(iz),oz=nz.concat(sz),z7=["era","eraYear"],nF=z7.concat(["year"]),O4=["year"],k2=["monthCode"],w2=["month"].concat(k2),S3=["day"],q2=w2.concat(O4),az=k2.concat(O4),J1=S3.concat(q2),oF=S3.concat(w2),rz=S3.concat(k2),tz=RZ(w1,0),w="iso8601",L4="gregory",PZ="japanese",ez={[L4]:{bce:-1,ce:0},[PZ]:{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}},aF={chinese:13,dangi:13,hebrew:-6},e=k(v6,"string"),$X=k(v6,"boolean"),rF=k(v6,"number"),ZX=k(v6,"function"),m=A3.map(($)=>$+"s"),y2=H3(m),tF=m.slice(0,6),JX=m.slice(6),eF=JX.slice(1),$V=uz(m),O0=RZ(m,0),v2=RZ(tF,0),g2=k(Z5,m),W1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],m2=["isoDay","isoMonth","isoYear"],H4=W1.concat(m2),h2=H3(m2),WX=H3(W1),YX=H3(H4),r0=RZ(WX,0),ZV=k(Z5,H4),Q$=Intl.DateTimeFormat,jX="en-GB",p2=1e8,JV=p2*v0,WV=[p2,0],YV=[-p2,0],D3=275760,O3=-271821,jV=1970,TZ=1972,A1=12,zV=IZ(1868,9,8),XV=g0(XF,WeakMap),k6="smallestUnit",X7="unit",B3="roundingIncrement",e8="fractionalSecondDigits",zX="relativeTo",XX={constrain:0,reject:1},QV=Object.keys(XX),GV={compatible:0,reject:1,earlier:2,later:3},KV={reject:0,use:1,prefer:2,ignore:3},BV={auto:0,never:1,critical:2,always:3},FV={auto:0,never:1,critical:2},VV={auto:0,never:1},UV={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},E3=k(S7,k6),c2=k(S7,"largestUnit"),DV=k(S7,X7),QX=k(f$,"overflow",XX),GX=k(f$,"disambiguation",GV),OV=k(f$,"offset",KV),d2=k(f$,"calendarName",BV),LV=k(f$,"timeZoneName",FV),HV=k(f$,"offset",VV),b3=k(f$,"roundingMode",UV),fZ="PlainYearMonth",kZ="PlainMonthDay",h$="PlainDate",p$="PlainDateTime",M4="PlainTime",q1="ZonedDateTime",P4="Instant",T4="Duration",MV=[Math.floor,($)=>M6($)?Math.floor($):Math.round($),Math.ceil,($)=>M6($)?Math.ceil($):Math.round($),Math.trunc,($)=>M6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>M6($)?($=Math.trunc($)||0)+$%2:Math.round($)],c$="UTC",I6=5184000,PV=A6(1847),TV=A6(new Date().getUTCFullYear()+10),NV=/0+$/,S0=g0(VF,WeakMap),sY=4294967295,N4=g0(($)=>{let Z=X2($);return typeof Z=="object"?new BX(Z):new KX(Z||0)});class KX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[M7($,this.v)]}l(){}}class BX{constructor($){this.$=((Z)=>{function J(Q){let G=$7(Q,z,X),[K,F]=pY(G),B=Y(K),U=Y(F);return B===U?B:W(j(K,F),B,U,Q)}function W(Q,G,K,F){let B,U;for(;(F===void 0||(B=F<Q[0]?G:F>=Q[1]?K:void 0)===void 0)&&(U=Q[1]-Q[0]);){let V=Q[0]+Math.floor(U/2);Z(V)===K?Q[1]=V:Q[0]=V+1}return B}let Y=g0(Z),j=g0(UF),z=PV,X=TV;return{G(Q){let G=J(Q-86400),K=J(Q+86400),F=Q-G,B=Q-K;if(G===K)return[F];let U=J(F);return U===J(B)?[Q-U]:G>K?[F,B]:[]},V:J,l(Q,G){let K=$7(Q,z,X),[F,B]=pY(K),U=I6*G,V=G<0?()=>B>z||(z=K,0):()=>F<X||(X=K,0);for(;V();){let D=Y(F),O=Y(B);if(D!==O){let L=j(F,B);W(L,D,O);let T=L[0];if((t1(T,Q)||1)===G)return T}F+=U,B+=U}}}})(((Z)=>(J)=>{let W=L7(Z,J*lz);return A6(wj(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(D5($))*a0}getPossibleInstantsFor($){let[Z,J]=[A6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*F1+W.isoMicrosecond*m$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>i0(HZ(MZ(Y,a0),J)))}l($,Z){let[J,W]=O5($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return MZ(Y,a0)}}var u2="([+\u2212-])",_6="(?:[.,](\\d{1,9}))?",FX=`(?:(?:${u2}(\\d{6}))|(\\d{4}))-?(\\d{2})`,l2="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+_6+")?)?",i2=u2+l2,IV=FX+"-?(\\d{2})(?:[T ]"+l2+"(Z|"+i2+")?)?",VX="\\[(!?)([^\\]]*)\\]",I4=`((?:${VX}){0,9})`,_V=EZ(FX+I4),xV=EZ("(?:--)?(\\d{2})-?(\\d{2})"+I4),CV=EZ(IV+I4),AV=EZ("T?"+l2+"(?:"+i2+")?"+I4),SV=EZ(i2),EV=new RegExp(VX,"g"),bV=EZ(`${u2}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${_6}H)?(?:(\\d+)${_6}M)?(?:(\\d+)${_6}S)?)?`),RV=g0(($)=>new Q$(jX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),fV=/^(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$/,kV=g0(LF),s2=g0(($)=>new Q$(jX,{calendar:$,timeZone:c$,era:"short",year:"numeric",month:"short",day:"numeric"})),wV=/^M(\d{2})(L?)$/,qV={era:C6,eraYear:_0,year:_0,month:vY,monthCode:C6,day:vY},yV=RZ(w1,_0),vV=RZ(m,F5),nY=Object.assign({},qV,yV,vV,{offset:C6}),gV=k(zF,w1,W1),oY={dateAdd($,Z,J){let W=v(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=F0(Z,5)[0],j||z)Y=((G,K,F,B,U)=>{let[V,D,O]=G.h(K);if(F){let[L,T]=G.I(V,D);V+=F,D=f6(L,T,G.U(V)),D=n0("month",D,1,G.L(V),U)}return B&&([V,D]=G._(V,D,B)),O=n0("day",O,1,G.j(V,D),U),G.q(V,D,O)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=A0($)}return Y+=(7*X+Q)*v0,e1(p6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=fj({...$,...r0},{...Z,...r0});return J===7&&([Q,G]=Z$(G,7)),{...O0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,K,F,B,U,V)=>{let D=B-G,O=U-K,L=V-F;if(D||O){let T=Math.sign(D||O),P=Q.j(B,U),_=0;if(Math.sign(L)===-T){let A=P;[B,U]=Q._(B,U,-T),D=B-G,O=U-K,P=Q.j(B,U),_=T<0?-A:P}if(L=V-Math.min(F,P)+_,D){let[A,E]=Q.I(G,K),[S,f]=Q.I(B,U);if(O=S-A||Number(f)-Number(E),Math.sign(O)===-T){let M=T<0&&-Q.L(B);D=(B-=T)-G,O=U-f6(A,E,Q.U(B))+(M||Q.L(B))}}}return[D,O,L]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...O0,years:j,months:z,days:X}},dateFromFields($,Z){let J=v(Z),W=a8(this,$),Y=r8(this,$,W,J),j=lY(this,$,Y,W,J);return z0(e1(this.P(W,Y,j)),this.id||w)},yearMonthFromFields($,Z){let J=v(Z),W=a8(this,$),Y=r8(this,$,W,J);return S$(H7(this.P(W,Y,1)),this.id||w)},monthDayFromFields($,Z){let J=v(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,K,F;if(Y!==void 0){[X,Q]=gj(Y),F=rY($,"day");let B=this.N(X,Q,F);if(!B)throw RangeError(iY);if([G,K]=B,z!==void 0&&z!==K)throw RangeError(mz);W&&(K=n0("month",K,1,A1,1),F=n0("day",F,1,P7(j!==void 0?j:G,K),J))}else{G=j===void 0&&W?TZ:a8(this,$),K=r8(this,$,G,J),F=lY(this,$,K,G,J);let B=this.U(G);Q=K===B,X=J7(K,B);let U=this.N(X,Q,F);if(!U)throw RangeError(iY);[G,K]=U}return S6(e1(this.P(G,K,F)),this.id||w)},fields($){return W7(this)&&$.includes("year")?[...$,...z7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return t8(J,Z,w2),W7(this)&&(t8(J,Z,nF),this.id===PZ&&t8(J,Z,oF,z7)),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:H2,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+o0(j)+(z?"L":""))(W,Y)},dayOfWeek:T5,daysInWeek(){return 7}},mV={dayOfYear:H2,h:H5,q:IZ},hV=Object.assign({},mV,{weekOfYear:yj,yearOfWeek:vj,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let V=P5(B+U),D=U||1,O=Z(K3(Q+V*D,7));return K=(V+(O-G)*D)/7}let W=this.id?1:4,Y=T5($),j=this.dayOfYear($),z=K3(Y-1,7),X=j-1,Q=K3(z-X,7),G=Z(Q),K,F=Math.floor((X-G)/7)+1,B=$.isoYear;return F?F>J(0)&&(F=1,B++):(F=J(-1),B--),[F,B,K]}}),pV={dayOfYear:H2,h:Z7,q:U3,weekOfYear:yj,yearOfWeek:vj,R(){return[]}},wZ=PF(Object.assign({},oY,hV,{h:H5,ee($){return this.id===L4?N5($):this.id===PZ?XV($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[TZ,$]},K:T7,U(){},L:M5,J:($)=>$*A1,j:P7,X:P5,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:IZ,_:($,Z,J)=>($+=q6(J,A1),(Z+=B7(J,A1))<1?($--,Z+=A1):Z>A1&&($++,Z-=A1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},oY,pV,{h:Z7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=P6.call(this,$);return[J7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=Z7.call(this,{isoYear:TZ,isoMonth:A1,isoDay:31}),z=P6.call(this,W),X=Y===z;(t1($,J7(Y,z))||t1(Number(Z),Number(X))||t1(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,K=P6.call(this,G),F=f6($,Z,K);if(Z===(F===K)&&J<=dY.call(this,G,F))return[G,F]}},K($){let Z=T6.call(this,$);return Z>T6.call(this,$-1)&&Z>T6.call(this,$+1)},U:P6,L:N6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=N6.call(this,z+Y);return j},j:dY,X:T6,P($,Z,J){return p6(U3.call(this,$,Z,J))},q:U3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(F4);if(J<0)for(;Z<1;)Z+=N6.call(this,--$);else{let W;for(;Z>(W=N6.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}})),$$="numeric",qZ=["timeZoneName"],UX={month:$$,day:$$},n2={year:$$,month:$$},o2=Object.assign({},n2,{day:$$}),a2={hour:$$,minute:$$,second:$$},r2=Object.assign({},o2,a2),cV=Object.assign({},r2,{timeZoneName:"short"}),dV=Object.keys(n2),uV=Object.keys(UX),lV=Object.keys(o2),iV=Object.keys(a2),t2=["dateStyle"],sV=dV.concat(t2),nV=uV.concat(t2),e2=lV.concat(t2,["weekday"]),R3=iV.concat(["dayPeriod","timeStyle"]),$9=e2.concat(R3),oV=$9.concat(qZ),aV=qZ.concat(R3),rV=qZ.concat(e2),tV=qZ.concat(["day","weekday"],R3),eV=qZ.concat(["year","weekday"],R3),$U={},Z9=[g$($9,r2),i6],DX=[g$(oV,cV),i6,0,($,Z)=>{let J=D0($.timeZone);if(Z&&D0(Z.timeZone)!==J)throw RangeError(pz);return J}],J9=[g$($9,r2,qZ),A0],W9=[g$(e2,o2,aV),A0],Y9=[g$(R3,a2,rV),($)=>J$($)/F1],j9=[g$(sV,n2,tV),A0,1],z9=[g$(nV,UX,eV),A0,1],aY;function D1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(R2);MX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...K){return Q.call(this,X(this),...K)},Q7(G))}function X(Q){let G=P0(Q);if(!G||G.branding!==$)throw TypeError(R2);return G}return Object.defineProperties(j.prototype,{...tY(t0(z,J)),...b$(t0(z,W)),...w6("Temporal."+$)}),Object.defineProperties(j,{...b$(Y),...Q7($)}),[j,(Q)=>{let G=Object.create(j.prototype);return MX(G,Q),G},X]}function NX($){return $=$.concat("id").sort(),(Z)=>{if(!eY(Z,$))throw TypeError(hz);return Z}}function mZ($){if(P0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(yz);return $}function _4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=P0(j)||{},{branding:X}=z,Q=X===h$||Z.includes(X)?z:R0(j);return Y[W](Q)};return J}function G9($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?wZ(j):(z=j,Object.assign(Object.create(OU),{i:z})))[J](W);var j,z};return Z}function V$(){throw TypeError(gz)}function k3({calendar:$}){return typeof $=="string"?new H9($):$}function OX($,Z){if(Z=Y0(Z),V0($)){let W=P0($);if(W&&W.branding===kZ)return v(Z),W;let Y=xX($);return T2(R4(Y||w),!Y,$,Z)}let J=Qj(wZ,$);return v(Z),J}function IX($,Z,J){return W=Z.call($,b0(U0(J))),c7(M3(W));var W}function x4($,Z=EX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=k(Z[Y],$,ZX($[Y]));return W}function d($,Z){return typeof $=="string"?N4($):x4($,Z)}function Q0($){return d($,Q9)}function V1($){if(V0($)){let Z=P0($);if(Z)switch(Z.branding){case P4:return Z;case q1:return U0(Z.epochNanoseconds)}}return Wj($)}function LX($,Z,J){let W=Z.l(V1(J).epochNanoseconds,$);return W?b0(U0(W)):null}function s($){return V0($)?(P0($)||{}).timeZone||NU($):((Z)=>j4(Fj(e(Z))))($)}function G$($,Z){if(V0($)){let J=P0($)||{};switch(J.branding){case M4:return v(Z),J;case p$:return v(Z),Z1(J);case q1:return v(Z),A2(Q0,J)}return lj($,Z)}return v(Z),Gj($)}function K9($){return $===void 0?void 0:G$($)}function yZ($,Z){if(Z=Y0(Z),V0($)){let W=P0($);return W&&W.branding===fZ?(v(Z),W):P2(E4(w3($)),$,Z)}let J=Xj(wZ,$);return v(Z),J}function K$($,Z){if(Z=Y0(Z),V0($)){let W=P0($)||{};switch(W.branding){case p$:return v(Z),W;case h$:return v(Z),j0({...W,...r0});case q1:return v(Z),x2(Q0,W)}return uj(b4(w3($)),$,Z)}let J=zj($);return v(Z),J}function R0($,Z){if(Z=Y0(Z),V0($)){let W=P0($)||{};switch(W.branding){case h$:return v(Z),W;case p$:return v(Z),z0(W);case q1:return v(Z),C2(Q0,W)}return M2(b4(w3($)),$,Z)}let J=W4($);return v(Z),J}function _X($,Z,J){return e0(Z.call($,Z0(z0(J,$))))}function O1($){return(Z)=>typeof Z=="string"?wZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=k(W[z],J,J[z]);return j})(Z,$)}function $0($){if(V0($)){let Z=P0($);return Z&&Z.branding===T4?Z:ij($)}return Kj($)}function f3($){if($!==void 0){if(V0($)){let Z=P0($)||{};switch(Z.branding){case q1:case h$:return Z;case p$:return z0(Z)}let J=w3($);return{...cj(s,d,b4(J),$),calendar:J}}return Yj($)}}function w3($){return xX($)||w}function xX($){let{calendar:Z}=$;if(Z!==void 0)return M0(Z)}function M0($){return V0($)?(P0($)||{}).calendar||vU($):((Z)=>N3(Bj(e(Z))))($)}function vZ($,Z){if(Z=Y0(Z),V0($)){let J=P0($);if(J&&J.branding===q1)return P3(Z),J;let W=w3($);return dj(s,d,b4(W),W,$,Z)}return jj($,Z)}function HX($){return t0((Z)=>(J)=>Z(X9(J)),$)}function X9($){return S0($,Q0)}function ZU(){let $=Q$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(Q$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);M9.set(this,((z,X={})=>{let Q=new Q$(z,X),G=Q.resolvedOptions(),K=G.locale,F=h0(Object.keys(X),G),B=g0(YU),U=(...V)=>{let D,O=V.map((L,T)=>{let P=P0(L),_=(P||{}).branding;if(T&&D&&D!==_)throw TypeError(dz);return D=_,P});return D?B(D)(K,F,...O):[Q,...V]};return U.u=Q,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&JU(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||WU(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function JU($){return function(...Z){let J=M9.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function WU($){return function(...Z){return M9.get(this).u[$](...Z)}}function YU($){let Z=jU[$];if(!Z)throw TypeError(cz($));return f1(Z,g0(S2))}var jU={Instant:Z9,PlainDateTime:J9,PlainDate:W9,PlainTime:Y9,PlainYearMonth:j9,PlainMonthDay:z9},zU=f1(Z9),XU=f1(DX),QU=f1(J9),GU=f1(W9),KU=f1(Y9),BU=f1(j9),FU=f1(z9),B9={era:z5,eraYear:F7,year:M3,month:e0,daysInMonth:e0,daysInYear:e0,inLeapYear:$X,monthsInYear:e0},A4={monthCode:e},F9={day:e0},CX={dayOfWeek:e0,dayOfYear:e0,weekOfYear:X5,yearOfWeek:F7,daysInWeek:e0},AX=Object.assign({},B9,A4,F9,CX),C4=new WeakMap,P0=C4.get.bind(C4),MX=C4.set.bind(C4),VU={..._4(B9,[fZ]),..._4(CX,[]),..._4(A4,[fZ,kZ]),..._4(F9,[kZ])},V9=G9(AX),UU=G9({...B9,...A4}),DU=G9({...A4,...F9}),q3={calendarId:($)=>D0($.calendar)},OU=t0(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Z0(z0(J,W))))},AX),LU=L3(($)=>(Z)=>Z[$],m.concat("sign")),U9=L3(($,Z)=>(J)=>J[W1[Z]],w1),SX={epochSeconds:E5,epochMilliseconds:i6,epochMicroseconds:b5,epochNanoseconds:R5},y3=k(G7,new Set(["branding"])),[HU,gZ,MU]=D1(kZ,k(zz,M0),{...q3,...DU},{getISOFields:y3,getCalendar:k3,with($,Z,J){return gZ(rj(wU,$,this,mZ(Z),J))},equals:($,Z)=>Cj($,OX(Z)),toPlainDate($,Z){return Z0(Pz(v3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=FU(Z,J,$);return W.format(Y)},toString:v7,toJSON:($)=>v7($),valueOf:V$},{from:($,Z)=>gZ(OX($,Z))}),EX={getOffsetNanosecondsFor:IX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,H0(j0(J,w)))].map((j)=>TU(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(C0),d7(l0(u0(W[0],W[Y-1])))),W}},Q9={getOffsetNanosecondsFor:IX},[PU,b0,TU]=D1(P4,Zz,SX,{add:($,Z)=>b0(u7(0,$,$0(Z))),subtract:($,Z)=>b0(u7(1,$,$0(Z))),until:($,Z,J)=>u(B2(0,$,V1(Z),J)),since:($,Z,J)=>u(B2(1,$,V1(Z),J)),round:($,Z)=>b0(w5($,Z)),equals:($,Z)=>Tj($,V1(Z)),toZonedDateTime($,Z){let J=b1(Z);return X0(_2($,s(J.timeZone),M0(J.calendar)))},toZonedDateTimeISO:($,Z)=>X0(_2($,s(Z))),toLocaleString($,Z,J){let[W,Y]=zU(Z,J,$);return W.format(Y)},toString:($,Z)=>f7(s,Q0,$,Z),toJSON:($)=>f7(s,Q0,$),valueOf:V$},{from:($)=>b0(V1($)),fromEpochSeconds:($)=>b0(Iz($)),fromEpochMilliseconds:($)=>b0(_z($)),fromEpochMicroseconds:($)=>b0(xz($)),fromEpochNanoseconds:($)=>b0(Cz($)),compare:($,Z)=>Q2(V1($),V1(Z))}),[S4,uP]=D1("TimeZone",($)=>{let Z=Mj($);return{branding:"TimeZone",id:Z,o:N4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(K$(Z)).map((J)=>b0(U0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(V1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=V1(Z).epochNanoseconds,W=x4(this,Q9).getOffsetNanosecondsFor(J);return k$(W)},getPlainDateTimeFor($,Z,J=w){let W=V1(Z).epochNanoseconds,Y=x4(this,Q9).getOffsetNanosecondsFor(W);return H0(j0(Y$(W,Y),M0(J)))},getInstantFor($,Z,J){let W=K$(Z),Y=N7(J),j=x4(this);return b0(U0(m0(j,W,Y)))},getNextTransition:({o:$},Z)=>LX(1,$,Z),getPreviousTransition:({o:$},Z)=>LX(-1,$,Z),equals($,Z){return!!X4(this,s(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=s($);return typeof Z=="string"?new S4(Z):Z}}),NU=NX(Object.keys(EX)),[IU,B$]=D1(M4,Xz,U9,{getISOFields:y3,with($,Z,J){return B$(tj(this,mZ(Z),J))},add:($,Z)=>B$(o7(0,$,$0(Z))),subtract:($,Z)=>B$(o7(1,$,$0(Z))),until:($,Z,J)=>u(O2(0,$,G$(Z),J)),since:($,Z,J)=>u(O2(1,$,G$(Z),J)),round:($,Z)=>B$(v5($,Z)),equals:($,Z)=>Aj($,G$(Z)),toZonedDateTime:($,Z)=>X0(Tz(s,R0,d,$,Z)),toPlainDateTime:($,Z)=>H0(Nz($,R0(Z))),toLocaleString($,Z,J){let[W,Y]=KU(Z,J,$);return W.format(Y)},toString:g7,toJSON:($)=>g7($),valueOf:V$},{from:($,Z)=>B$(G$($,Z)),compare:($,Z)=>z4(G$($),G$(Z))}),[_U,F$,xU]=D1(fZ,k(jz,M0),{...q3,...UU},{getISOFields:y3,getCalendar:k3,with($,Z,J){return F$(aj(kU,$,this,mZ(Z),J))},add:($,Z,J)=>F$(n7(PX,0,$,$0(Z),J)),subtract:($,Z,J)=>F$(n7(PX,1,$,$0(Z),J)),until:($,Z,J)=>u(D2(TX,0,$,yZ(Z),J)),since:($,Z,J)=>u(D2(TX,1,$,yZ(Z),J)),equals:($,Z)=>xj($,yZ(Z)),toPlainDate($,Z){return Z0(Mz(v3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=BU(Z,J,$);return W.format(Y)},toString:y7,toJSON:($)=>y7($),valueOf:V$},{from:($,Z)=>F$(yZ($,Z)),compare:($,Z)=>y$(yZ($),yZ(Z))}),[CU,H0]=D1(p$,k(Wz,M0),{...q3,...V9,...U9},{getISOFields:y3,getCalendar:k3,with($,Z,J){return H0(nj(v3,$,this,mZ(Z),J))},withCalendar:($,Z)=>H0(B4($,M0(Z))),withPlainDate:($,Z)=>H0(bz($,R0(Z))),withPlainTime:($,Z)=>H0(Ez($,K9(Z))),add:($,Z,J)=>H0(i7(d$,0,$,$0(Z),J)),subtract:($,Z,J)=>H0(i7(d$,1,$,$0(Z),J)),until:($,Z,J)=>u(V2(U1,0,$,K$(Z),J)),since:($,Z,J)=>u(V2(U1,1,$,K$(Z),J)),round:($,Z)=>H0(y5($,Z)),equals:($,Z)=>Ij($,K$(Z)),toZonedDateTime:($,Z,J)=>X0(Fz(d,$,s(Z),J)),toPlainDate:($)=>Z0(z0($)),toPlainTime:($)=>B$(Z1($)),toPlainYearMonth($){return F$(Vz(E4,$,this))},toPlainMonthDay($){return gZ(Uz(R4,$,this))},toLocaleString($,Z,J){let[W,Y]=QU(Z,J,$);return W.format(Y)},toString:w7,toJSON:($)=>w7($),valueOf:V$},{from:($,Z)=>H0(K$($,Z)),compare:($,Z)=>K2(K$($),K$(Z))}),[AU,Z0,bX]=D1(h$,k(Yz,M0),{...q3,...V9},{getISOFields:y3,getCalendar:k3,with($,Z,J){return Z0(oj(v3,$,this,mZ(Z),J))},withCalendar:($,Z)=>Z0(B4($,M0(Z))),add:($,Z,J)=>Z0(s7(d$,0,$,$0(Z),J)),subtract:($,Z,J)=>Z0(s7(d$,1,$,$0(Z),J)),until:($,Z,J)=>u(U2(U1,0,$,R0(Z),J)),since:($,Z,J)=>u(U2(U1,1,$,R0(Z),J)),equals:($,Z)=>_j($,R0(Z)),toZonedDateTime($,Z){let J=!V0(Z)||Z instanceof S4?{timeZone:Z}:Z;return X0(Dz(s,G$,d,$,J))},toPlainDateTime:($,Z)=>H0(Oz($,K9(Z))),toPlainYearMonth($){return F$(Lz(E4,$,this))},toPlainMonthDay($){return gZ(Hz(R4,$,this))},toLocaleString($,Z,J){let[W,Y]=GU(Z,J,$);return W.format(Y)},toString:q7,toJSON:($)=>q7($),valueOf:V$},{from:($,Z)=>Z0(R0($,Z)),compare:($,Z)=>y$(R0($),R0(Z))}),D9={fields($,Z,J){return[...Z.call($,J)]}},RX=Object.assign({dateFromFields($,Z,J,W){return bX(Z.call($,Object.assign(Object.create(null),J),W))}},D9),fX=Object.assign({yearMonthFromFields($,Z,J,W){return xU(Z.call($,Object.assign(Object.create(null),J),W))}},D9),kX=Object.assign({monthDayFromFields($,Z,J,W){return MU(Z.call($,Object.assign(Object.create(null),J),W))}},D9),O9={mergeFields($,Z,J,W){return b1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},SU=Object.assign({},RX,O9),EU=Object.assign({},fX,O9),bU=Object.assign({},kX,O9),L9={dateAdd($,Z,J,W,Y){return bX(Z.call($,Z0(z0(J,$)),u(a(W)),Y))}},wX=Object.assign({},L9,{dateUntil($,Z,J,W,Y,j){return yU(Z.call($,Z0(z0(J,$)),Z0(z0(W,$)),Object.assign(Object.create(null),j,{largestUnit:A3[Y]})))}}),RU=Object.assign({},L9,{day:_X}),fU=Object.assign({},wX,{day:_X}),E4=O1(fX),b4=O1(RX),R4=O1(kX),kU=O1(EU),v3=O1(SU),wU=O1(bU),d$=O1(L9),U1=O1(wX),PX=O1(RU),TX=O1(fU),[qU,u,yU]=D1(T4,Qz,{...LU,blank:$j},{with:($,Z)=>u(ej($,Z)),negated:($)=>u(Z4($)),abs:($)=>u(e5($)),add:($,Z,J)=>u($2(f3,U1,d,0,$,$0(Z),J)),subtract:($,Z,J)=>u($2(f3,U1,d,1,$,$0(Z),J)),round:($,Z)=>u(t5(f3,U1,d,$,Z)),total:($,Z)=>k5(f3,U1,d,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):a6($)},toString:a6,toJSON:($)=>a6($),valueOf:V$},{from:($)=>u($0($)),compare:($,Z,J)=>Pj(f3,d$,d,$0($),$0(Z),J)}),qX={toString:($)=>$.id,toJSON:($)=>$.id,...VU,dateAdd:({id:$,o:Z},J,W,Y)=>Z0(z0(Z.dateAdd(R0(J),$0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>u(a($.dateUntil(R0(Z),R0(J),_5(W)))),dateFromFields:({id:$,o:Z},J,W)=>Z0(M2(Z,J,W,j5($))),yearMonthFromFields:({id:$,o:Z},J,W)=>F$(P2(Z,J,W,W5($))),monthDayFromFields:({id:$,o:Z},J,W)=>gZ(T2(Z,0,J,W,Y5($))),fields({o:$},Z){let J=new Set(J1),W=[];for(let Y of Z){if(e(Y),!J.has(Y))throw RangeError(b2(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(K7(V7(Z)),K7(V7(J)))},[H9]=D1("Calendar",($)=>{let Z=qj($);return{branding:"Calendar",id:Z,o:wZ(Z)}},{id:($)=>$.id},qX,{from($){let Z=M0($);return typeof Z=="string"?new H9(Z):Z}}),vU=NX(Object.keys(qX).slice(4)),[gU,X0]=D1(q1,k(Jz,M0,s),{...SX,...q3,...HX(V9),...HX(U9),offset:($)=>k$(X9($).offsetNanoseconds),offsetNanoseconds:($)=>X9($).offsetNanoseconds,timeZoneId:($)=>D0($.timeZone),hoursInDay:($)=>g5(d,$)},{getISOFields:($)=>a5(Q0,$),getCalendar:k3,getTimeZone:({timeZone:$})=>typeof $=="string"?new S4($):$,with($,Z,J){return X0(sj(v3,d,$,this,mZ(Z),J))},withCalendar:($,Z)=>X0(B4($,M0(Z))),withTimeZone:($,Z)=>X0(Rz($,s(Z))),withPlainDate:($,Z)=>X0(Sz(d,$,R0(Z))),withPlainTime:($,Z)=>X0(Az(d,$,K9(Z))),add:($,Z,J)=>X0(l7(d$,d,0,$,$0(Z),J)),subtract:($,Z,J)=>X0(l7(d$,d,1,$,$0(Z),J)),until:($,Z,J)=>u(a(F2(U1,d,0,$,vZ(Z),J))),since:($,Z,J)=>u(a(F2(U1,d,1,$,vZ(Z),J))),round:($,Z)=>X0(q5(d,$,Z)),startOfDay:($)=>X0(m5(d,$)),equals:($,Z)=>Nj($,vZ(Z)),toInstant:($)=>b0(Gz($)),toPlainDateTime:($)=>H0(x2(Q0,$)),toPlainDate:($)=>Z0(C2(Q0,$)),toPlainTime:($)=>B$(A2(Q0,$)),toPlainYearMonth($){return F$(Kz(E4,$,this))},toPlainMonthDay($){return gZ(Bz(R4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=XU(Z,J,$);return W.format(Y)},toString:($,Z)=>k7(Q0,$,Z),toJSON:($)=>k7(Q0,$),valueOf:V$},{from:($,Z)=>X0(vZ($,Z)),compare:($,Z)=>G2(vZ($),vZ(Z))}),mU=Object.defineProperties({},{...w6("Temporal.Now"),...b$({timeZoneId:()=>k1(),instant:()=>b0(U0(_3())),zonedDateTime:($,Z=k1())=>X0(L0(_3(),s(Z),M0($))),zonedDateTimeISO:($=k1())=>X0(L0(_3(),s($),w)),plainDateTime:($,Z=k1())=>H0(j0(bZ(Q0(s(Z))),M0($))),plainDateTimeISO:($=k1())=>H0(j0(bZ(Q0(s($))),w)),plainDate:($,Z=k1())=>Z0(z0(bZ(Q0(s(Z))),M0($))),plainDateISO:($=k1())=>Z0(z0(bZ(Q0(s($))),w)),plainTimeISO:($=k1())=>B$(Z1(bZ(Q0(s($)))))})}),hZ=Object.defineProperties({},{...w6("Temporal"),...b$({PlainYearMonth:_U,PlainMonthDay:HU,PlainDate:AU,PlainTime:IU,PlainDateTime:CU,ZonedDateTime:gU,Instant:PU,Calendar:H9,TimeZone:S4,Duration:qU,Now:mU})}),hU=ZU(),M9=new WeakMap,pU=Object.defineProperties(Object.create(Intl),b$({DateTimeFormat:hU}));var f4="x-gemi-socket";var aP="gemi.v1",yX="/__gemi/socket",rP=/^[A-Za-z0-9_-]{1,32}$/,tP={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function JT($){return $}function vX(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:yX,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 cU,randomBytes as dU}from"crypto";function uU($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(cU("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var lU="__control",P9=250,iU=1e4,sU=15000;class T9{config;prefix;controlChannel;instanceId=dU(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??uU(),this.controlChannel=this.prefix+lU,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=g3((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 $})(),sU,"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 (${gX(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(iU,P9*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(P9,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;g3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${gX(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??nU(Math.min(Z,P9));await g3(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 Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await g3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await g3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}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 g3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function nU($){return new Promise((Z)=>setTimeout(Z,$))}function gX($){return $ instanceof Error?$.message:String($)}import{createHmac as oU,hkdfSync as aU,randomBytes as mX}from"crypto";function hX($){return oU("sha256",rU()).update($).digest("base64url").slice(0,22)}var k4=null;function rU(){let $=process.env.SECRET||void 0;if(k4&&k4.secret===$)return k4.key;let Z=$?Buffer.from(aU("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):mX(32);return k4={secret:$,key:Z},Z}function XT(){return mX(16).toString("base64url")}var tU=/^[A-Za-z0-9_-]{8,64}$/;function N9($){return typeof $==="string"&&tU.test($)}function pX($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class dX 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 p0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=L1(vX(),$),this.driver=ZD(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 m3(this,w4($,Z[0]),null)}toUser($){return new m3(this,{topic:XZ($),pattern:K0},null)}toOthers($){return new uX(this,$D($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(w4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){VW(Z);let Y;try{Y=pX($.topic,Z,J,W?hX(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){pZ(()=>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=eU($);pZ(()=>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 dX(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 m3{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 uX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new m3(this.manager,w4($,Z[0]),this.except)}toUser($){return new m3(this.manager,{topic:XZ($),pattern:K0},this.except)}}function w4($,Z){if(FW($))return{topic:L8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:Y3($,Z??{}),pattern:$};if($===K0)throw new p('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:L8($)}}function eU($){if($&&typeof $==="object"&&"user"in $)return{user:XZ($.user).slice(K0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:w4($.channel,$.params).topic};throw new p("Broadcast.revoke takes { user } or { channel }.")}function $D($){if($===null||$===void 0)return null;if(typeof $==="string")return N9($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(f4);return N9(J)?J:null}function ZD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new cX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new T9({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.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 I9 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class JD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as _9,createHmac as WD,randomBytes as lX,timingSafeEqual as nX}from"crypto";var p3=600,q4="gemi_oauth",YD=`__Host-${q4}`;function cZ($,Z=q4){if(Z===q4)return $?YD:q4;return $?`__Host-${Z}`:Z}function h3($){return $.toString("base64url")}function oX($){return WD("sha256",FZ()).update(`gemi-oauth-state:${$}`).digest()}function iX($,Z){let J=_9("sha256").update($).digest(),W=_9("sha256").update(Z).digest();return nX(J,W)&&$.length===Z.length}function y4($,Z=Date.now(),J={}){let W=h3(lX(32)),Y=h3(lX(32)),j=jD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+p3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:zD(z)}}function jD($){return h3(_9("sha256").update($).digest())}function zD($){let Z=h3(Buffer.from(JSON.stringify($)));return`${Z}.${h3(oX(Z))}`}function XD($){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"),Y=oX(J);if(W.length!==Y.length||!nX(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string")return null;return j}catch{return null}}var U$=new Map,sX=1e4;function QD($,Z,J){if(U$.size>=sX){for(let[W,Y]of U$)if(Y<=J)U$.delete(W);while(U$.size>=sX){let W=U$.keys().next().value;if(W===void 0)break;U$.delete(W)}}U$.set($,Z)}function v4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=XD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=iX(J.state,$.returnedState),Y=iX(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(U$.has(J.state))return{ok:!1,reason:"invalid_state"};return QD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var x9=new WeakMap;function KD($){let Z=x9.get($);if(!Z)Z=$(GD(32).toString("hex")),x9.set($,Z),Z.catch(()=>x9.delete($));return Z}async function C9($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await KD($.hashPassword))}catch{}return!1}async function u$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class S9 extends Error{}function A9($){return typeof $==="string"&&$!==""?$:null}function aX($){return X3($)}var BD=256;function rX($){return typeof $==="string"&&$!==""&&$.length<=BD?$:null}function tX($){let{password:Z,code:J,...W}=$;return W}var g4="intended_url";function $Q($){if($.cookies.get(g4))$.ctx().setCookie(g4,"",{maxAge:-1})}function eX($){let Z=$.cookies.get(g4);if(!Z)return null;$Q($);try{return X1(decodeURIComponent(Z),"")||null}catch{return null}}class E9 extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class ZQ extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class JQ extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function y1($){if(H(b).config[$]===!1)throw new J0("Not found",{status:404})}class r extends z3{async me(){let $=await w0.user();if(!$)throw new q8;return $}async verifyEmail($=new C){y1("password");let Z=await $.input(),{userProvider:J}=H(b),W=A9(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=H(b),{userProvider:J}=Z,W=A9($.search.get("token")),Y=null;try{Y=X3(decodeURIComponent($.search.get("email")??""))}catch{}if(await UZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,H(b).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await u$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){y1("magicLink");let Z=H(b),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=X3(W),z=rX(Y);if(await UZ("verify",j,$,Z.config.emailCode.verifyLimit),!j||!z)throw new h({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(X.status!=="ok")throw new h({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=H(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,H(b).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await u$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=H(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,H(b).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await u$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new E9){y1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await C9(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,H(b).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await u$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signIn($=new E9){y1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await C9(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,H(b).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await u$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signUp(){y1("password");let $=H(b),{userProvider:Z,config:J}=$,W=new J.signUpRequest,Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G={method:"password",input:tX(Y.toJSON())},K=aX(j);if(!K)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new h({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(K,!1))throw new h({email:["Email address already exists"]});let B=await J.hashPassword(z),U=H(o).detectLocale(W),V;if(Q)V=await Z.findInvitation(Q,K);let D,O="";if(V)D=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let L=await Z.createUser({email:K,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:V.organizationId,userId:L.id,organizationRole:V.role}),await J.onUserCreated(L,G),L});else O=await J.generateEmailVerificationToken(K),D=await Z.transaction(async()=>{let L=await Z.createUser({email:K,name:X,password:B,verificationToken:O,locale:U});return await J.onUserCreated(L,G),L});return await J.onSignUp(D,O,W.search.toJSON()),D}async signOut($=new C){let Z=T$($),J=H(b),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(b).accessTokenCookieOptions($,new Date(0))),H(b).cookieDomain($))$.ctx().setCookie("access_token","",{...H(b).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)FD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user);return{}}async forgotPassword($=new ZQ){y1("password");let Z=await $.input(),J=aX(Z.get("email"));if(!J)return{};let{userProvider:W,config:Y}=H(b),j=await W.findUserByEmailAddress(J,Y.verifyEmail);if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z),{}}async resetPassword($=new JQ){y1("password");let{userProvider:Z,config:J}=H(b),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=A9(j),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new h({token:["Invalid token"]});if(hZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(hZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new h({email:["User not found"]});let K=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:K}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new C){y1("password");let{userProvider:Z,config:J}=H(b),W=await w0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof j==="string"&&await C9(J,j,X?.password)))throw new h({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=H(b).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await DZ(J,Z);if(!Y){if(W)throw new J0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=QZ($.rawRequest),z=X1($.search.get(z1),"");if(z)$.ctx().setCookie(g4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else $Q($);let{state:X,codeChallenge:Q,cookieValue:G}=y4(Z);return $.ctx().setCookie(cZ(j),G,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:p3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=H(b),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await DZ(Y.oauthProviders,Z);if(j&&!z)throw new J0("Not found",{status:404});let X=QZ($.rawRequest),Q=cZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{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 F=v4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in F)return console.error(`Authentication error: OAuth callback refused (${F.reason})`),this.oauthFailure($,F.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let B;try{B=await z.onCallback($,{state:F.payload.state,codeVerifier:F.payload.codeVerifier})}catch(M){if(M instanceof I9)return this.oauthFailure($,M.code);return console.error("Authentication error: OAuth provider callback failed",M),this.oauthFailure($,"provider_error")}let{name:U,username:V,providerId:D,emailVerified:O}=B??{},L=typeof B?.email==="string"?B.email:void 0,T=L?O6(L):null,P=D?await W.findUserBySocialAccount(Z,D):null,_="signin",A=!P&&!T&&!L&&!!D&&z.createUsersWithoutEmail===!0;if(!P&&A){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{P=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:U,username:V,locale:H(o).detectLocale($)}),_="signup"}catch(M){let I=await W.findUserBySocialAccount(Z,D);if(!I)throw M;P=I}}if(!P){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,L?"invalid_email":D?"missing_email":"no_identity");if(O===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let M=H(o).detectLocale($);try{let I=await this.linkOAuthAccount({provider:Z,providerId:D,email:T,rawEmail:L,name:U,username:V,locale:M,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(I==="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(I==="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(I)P=I.user,_=I.action}catch(I){let y=D?await W.findUserBySocialAccount(Z,D):null;if(!y)throw I;P=y}if(!P)return this.oauthFailure($,"account_conflict")}let E=await J.createOrUpdateSessionV2({email:P.email,id:P.id});if($.ctx().setCookie("access_token",E.token,H(b).accessTokenCookieOptions($,E.expiresAt)),_==="signup")await Y.onSignUp(P,"",$.search.toJSON());else await Y.onSignIn(P,$.search.toJSON());await u$(J.config,{session:E,user:P,isNewUser:_==="signup",method:"oauth",req:$});let S=eX($)??Y.redirectPath,f=Y.oauthCompleteProfilePath?X1(Y.oauthCompleteProfilePath,""):"";if(f&&!P.email){let M=new URL(f,"http://gemi.invalid");M.searchParams.set(z1,S),S=`${M.pathname}${M.search}${M.hash}`}return{session:E,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=H(b);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,{method:"oauth",input:{}}),W})}oauthFailure($,Z){let J=eX($),W=H(b).config.oauthFailurePath;if(W){let Y=X1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(z1,J);N1.external(`${j.pathname}${j.search}${j.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:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=H(b),K=(V)=>({provider:Z,userId:V,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),F=await Q.findUserByEmailAddress(W,!1),B=Y?.trim();if(!F&&B&&B!==W)F=await Q.findUserByEmailAddress(B,!1);if(F){if($.linkExisting===!1)return"account_exists";if(!J)return{user:F,action:"signin"};let V=await Q.findSocialAccounts(F.id,Z);if(V.some((O)=>O.providerId===J))return{user:F,action:"signin"};if(V.some((O)=>O.providerId))return console.error(`Authentication error: user ${F.id} is already linked to a different ${Z} account`),null;let D=V[0];if(D){if(!await Q.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(K(F.id));return{user:F,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let V=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(K(V.id));return await G.onUserCreated(V,{method:"oauth",input:{}}),V}),action:"signup"}}async createMagicLinkToken($=new C){y1("magicLink");let Z=await $.input(),J=X3(Z.get("email")),W=H(b),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await UZ("request",J,$,j),!J)return{email:null};let{user:z,pin:X,token:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=H(b),J=Z.config.emailCode;if(!J.enabled)throw new J0("Not found",{status:404});let W=await $.input(),Y=O6(W.get("email"));if(await UZ("request",Y,$,J.requestLimit),!Y)throw new h({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=H(b),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new J0("Not found",{status:404});let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=O6(j),G=rX(z);if(await UZ("verify",Q,$,W.emailCode.verifyLimit),!Q||!G)throw new h({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(K.status==="too_many_attempts")throw new h({code:["too_many_attempts"]});if(K.status!=="ok")throw new h({code:["invalid_code"]});let F=K.row,B=await J.findUserByEmailAddress(Q,!1),U=!1;if(B){if(!await Z.claimOneTimeCode(Q,F.id))throw new h({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let D=H(o).detectLocale($);try{B=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(Q,F.id))throw new S9;let O=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await W.onUserCreated(O,{method:"email-code",input:tX(Y.toJSON())}),O}),U=!0}catch(O){if(O instanceof S9)throw new h({code:["invalid_code"]});throw O}}else throw await Z.claimOneTimeCode(Q,F.id),new h({code:["invalid_code"]});let V=await Z.createOrUpdateSessionV2({email:Q,id:B.id});return $.ctx().setCookie("access_token",V.token,H(b).accessTokenCookieOptions($,V.expiresAt)),await W.onSignIn(V,$.search.toJSON()),await u$(Z.config,{session:V,isNewUser:U,method:"email-code",req:$}),{session:V,isNewUser:U}}}function FD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=H();if(typeof J?.bound!=="function"||!J.bound(p0))return;J.make(p0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var WQ="gemi_oauth_connection";class m4 extends z3{async connect($=new C){let Z=String($.params.provider??""),W=H(c3).providers[Z],Y=await w0.user(),j=X1($.search.get(z1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=QZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=y4(YQ(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(cZ(z,WQ),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:p3}),N1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:jQ($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=H(c3),W=await w0.user(),Y=QZ($.rawRequest),j=cZ(Y,WQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=v4({provider:YQ(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let K=$.search.get("error");if(K)return this.finish(Q,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(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let F=$.search.get("code");if(!F)return this.finish(Q,Z,"missing_code");try{let B=await G.exchangeCode({code:F,codeVerifier:X.payload.codeVerifier,redirectUri:jQ($,Z,G.config.redirectUri)}),U=await J.save(W,Z,B);await H(b).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof zQ)return console.error(`OAuth connection to ${Z} failed: ${B.message}`),this.finish(Q,Z,B.providerError??B.code);throw B}return this.finish(Q,Z)}finish($,Z,J){let W=$||X1(H(b).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw N1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function YQ($){return`connection:${$}`}function jQ($,Z,J){if(J)return J;return`${l$()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function XQ($){return $.magicLink!==!1||$.emailCode?.enabled===!0}function QQ($){return Object.keys($.oauthProviders??{}).length>0}function GQ($={}){let Z=[];if(XQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:$.emailCode?.enabled===!0&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(QQ($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class KQ extends I1{middlewares=["cache:private"];routes={"/:provider":this.redirect([m4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([m4,"callback"]).middleware([X6,"auth"])}}function BQ($={}){let Z=XQ($),J=QQ($);class W extends I1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[r,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[r,"oauthCallback"])}}return class extends I1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[r,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":KQ}}}class b9 extends I0{middlewares=["cache:private"];routes={"/sign-in":this.post(r,"signIn"),"/sign-in-v2":this.post(r,"signInV2"),"/sign-up":this.post(r,"signUp"),"/sign-out":this.post(r,"signOut"),"/forgot-password":this.post(r,"forgotPassword"),"/reset-password":this.post(r,"resetPassword"),"/change-password":this.post(r,"changePassword"),"/verify-email":this.post(r,"verifyEmail"),"/me":this.get(r,"me").middleware(["auth"]),"/magic-link":this.post(r,"createMagicLinkToken"),"/sign-in-with-pin":this.post(r,"signInWithPin"),"/sign-in-with-pin-v2":this.post(r,"signInWithPinV2"),"/email-code":this.post(r,"requestEmailCode"),"/email-code/verify":this.post(r,"verifyEmailCode")}}class R9 extends I0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await H(o).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=H(o),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class f9{}class k9 extends f9{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await h4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function LN($){return $}function FQ(){return{driver:new k9,allowedHosts:[],maxSize:10485760,timeout:1e4}}class G0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var VD=new Set([301,302,303,307,308]),UD="/api/__gemi__/services/image/";async function UQ($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=VQ($,Y);try{for(let z=0;;z++){let X=await DD(j,Z,W),Q=X.headers.get("location");if(VD.has(X.status)&&Q){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new G0(502,"The image redirects too many times");j=VQ(Q,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new G0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new G0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw LD(z,W)}}function VQ($,Z){let J;try{J=new URL($,Z)}catch{throw new G0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new G0(400,"Only http(s) images can be resized");return J}async function DD($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(UD))throw new G0(403,"This image source is not allowed");if(OD($.pathname))throw new G0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return _1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new G0(403,"This image source is not allowed");return _1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function OD($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function LD($,Z){if($ instanceof G0)return $;if(Z.aborted)return new G0(504,"The image took too long to load",{cause:$});if($ instanceof G6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new G0(403,"This image source is not allowed",{cause:$});case"too-large":return new G0(413,"The image is too large",{cause:$});case"timeout":return new G0(504,"The image took too long to load",{cause:$})}return new G0(502,"The image could not be loaded",{cause:$})}class w9 extends I0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return DQ(400,"url query parameter is required");let X=H(OQ),Q=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],G=l$();if(G&&URL.canParse(G))Q.push(new URL(G).origin);let K;try{K=await UQ(J,{ownOrigins:Q,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof G0)return DQ(U.status,U.message);throw U}let F=await X.resize(K.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${F.byteLength}`});if(K.cacheControl)B.set("Cache-Control",K.cacheControl);return new Response(new Uint8Array(F),{headers:B})})}}function DQ($,Z){return Response.json({error:Z},{status:$})}class OQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=FQ();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class q9 extends I0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(LQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function fN($){return $}function HQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function MQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function HD($){return"run"in $}function MD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function PD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function TD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function ND($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function PQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function ID($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function y9($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let K=j==="/"?"":j,F=Z==="/"?"":Z,B=ID((`${F}${K}`===""?"/":`${F}${K}`).replaceAll("//","/"));if(!W[B])W[B]={};W[B][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[B].OPTIONS={exec:()=>{let V=new C().ctx().headers;return new Response(null,{headers:V,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(ND(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(HD(z)){let X=z,Q=X.method,G=X.middlewares,K=X.run.bind(X);if(Y(j,Q,K,G,X.source),PQ(z))Y(j,"HEAD",K,G,X.source)}if(MD(z))for(let[X,Q]of Object.entries(z)){let G=Q,K=G.middlewares,F=G.run.bind(G);if(Y(j,X,F,K,G.source),X==="get"&&PQ(G))Y(j,"HEAD",F,K,G.source)}if(TD(z)){let X=new z,Q=y9(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[G,K]of Object.entries(Q)){let F=G.replaceAll("//","/");W[F]={...W[F],...K}}}if(PD(z)){let{first:X,second:Q}=z;for(let[G,K]of Object.entries(X)){let F=K.middlewares,B=K.run.bind(K),[U,...V]=j.split("/").reverse();if(!U.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(V.reverse().join("/"),G,B,F,K.source)}for(let[G,K]of Object.entries(Q)){let F=K.middlewares,B=K.run.bind(K);Y(j,G,B,F,K.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function p4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function v9($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function g9($){let Z=p4($);return Z.length>1?Z.replace(/\/$/,""):Z}function TQ($,Z){return Z.map((J)=>({...J,path:g9(v9($,J.path))}))}function c4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=c4(j.routes);for(let[X,{exec:Q,middleware:G,segments:K,features:F,static:B}]of Object.entries(z)){let U=v9(J,X),V=(D)=>Y.run.call(Y,D,J);Z[p4(U)]={exec:[V,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...F],viewPath:Y.viewPath,segments:[{path:g9(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...TQ(J,K)],...B?{static:B}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[p4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:g9(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=c4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:K,features:F,static:B}]of Object.entries(j)){let U=v9(J,z);Z[p4(U)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...F],viewPath:G,segments:TQ(J,K),...B?{static:B}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var m9="theme";function NQ($){return $==="light"||$==="dark"||$==="system"}function IQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
13
+ `)}function yB($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(JY($),{status:200,headers:J})}var WY={response:yB,text:JY,parse:ZY,fetch:qB};import{createHmac as YY,randomBytes as vB}from"crypto";var y8="v2.";function v8($){return $.startsWith(y8)}function FZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function jY($){let Z=vB(16).toString("hex"),J=YY("sha256",FZ()).update(`${$}:${Z}`).digest("hex");return`${y8}${J}`}function U6($,Z){let J=YY("sha256",FZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${y8}${J}`}import{createHash as hB,createHmac as pB,randomInt as cB,timingSafeEqual as QY}from"crypto";function zY($,Z){return Math.floor($/Z)*Z}function gB($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function g8($,Z,J,W){return Z*gB(J,W)+$}function mB($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let B=Y*(1-(X-Z)/J);if(B<=Y)return Math.max(0,Math.ceil(B-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function XY($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let B=g8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-B)),resetAt:Y-j+z,retryAfter:0}}let G=mB({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class m8{}class h8 extends m8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=zY(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let B=g8(Q.current,Q.previous,X,W)+Y<=J;if(B)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return XY({allowed:B,current:Q.current,previous:Q.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}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,Y]of this.buckets)if($-Y.windowStart>=Y.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,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var BY="h1.";function D6($,Z,J){let W=pB("sha256",FZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${BY}${W}`}function VZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(BY),X=D6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return QY(Q,Q),!1;return QY(Q,G)}function FY($){let Z="";for(let J=0;J<$;J++)Z+=String(cB(0,10));return Z}var VY=320;function X3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>VY)return null;return Z.toLowerCase()}function O6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>VY)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var GY=null;function UY(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(Q1))return $.make(Q1)}catch{}return GY??=new Q1({driver:new h8,limit:1000,window:60}),GY}function KY($){return $.length<=64?$:`sha256:${hB("sha256").update($).digest("hex")}`}async function UZ($,Z,J,W){let Y=UY(),j=[[`auth:code-${$}:ip:${KY(GZ(J))}`,W.perIp]];if(Z!==null)j.push([`auth:code-${$}:email:${KY(Z)}`,W.perEmail]);for(let[z,X]of j){if(!X)continue;let[Q,G]=X,B=await Y.consume(z,{limit:Q,window:G});if(!B.allowed)throw new a1(B)}}async function DY($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await UY().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as c8}from"crypto";class p8 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 Q3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function dB($={}){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 d8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return Q3("length",Z,4,12),Q3("expiresInMinutes",J,1),Q3("linkExpiresInMinutes",W,1),Q3("maxAttempts",Y,1),Q3("activeCodes",j,1,5),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes: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:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)})}}async function uB($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function OY($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function LY($){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 FP($){return $}function HY($={}){return dB($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:p8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:uB,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>c8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return c8(32).toString("hex")},generateMagicLinkToken:()=>c8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:d8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var lB=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),iB=new Set(["svg","math"]);function MY($){return $===32||$===9||$===10||$===12||$===13}function PY($){return $>=65&&$<=90||$>=97&&$<=122}function L6($){return $>=65&&$<=90?$+32:$}function TY(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,B=()=>{if(!J&&lB.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(iB.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},F=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",j=0;else if(K===47)$="endTagOpen";else if(PY(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(L6(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(PY(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(L6(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(MY(K)||K===47)$="inTag",z=K===47;else if(K===62)B();else Z+=String.fromCharCode(L6(K));return;case"inTag":if(K===62){B();return}if(z=K===47,K===34)$="attrDouble";else if(K===39)$="attrSingle";return;case"attrDouble":if(K===34)$="inTag";z=!1;return;case"attrSingle":if(K===39)$="inTag";z=!1;return;case"bang":if(K===45){if(j+=1,j===2)$="comment",j=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)j=j<2?j+1:2;else if(K===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(L6(K)===W.charCodeAt(Y))Y+=1;else Y=K===60?1:0;return}if(K===62)$="data",Z="";else if(MY(K)||K===47)$="inTag",Z="";else Y=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let V=0;V<K.length;V++){if(G())return V;F(K[V])}return K.length},write(K){for(let V=0;V<K.length;V++)F(K[V])},isSafe:G}}function G1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function sB($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${G1([$.path,$.variantKey,$.data])})</script>`}function nB($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${G1([$.id,$.locale,$.strings])})</script>`}function u8($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((U)=>{if(U.status!=="resolved")return;j.push(sB(U))}),W?.onUse((U)=>{j.push(nB(U))});let G=$.getReader(),B=TY(),F=(U,D)=>{U.enqueue(D),J.onChunk?.(D)},K=(U)=>{while(j.length>0){let D=Y.encode(j.shift());B.write(D),F(U,D)}},V=(U,D)=>{if(j.length===0){B.write(D),F(U,D);return}let O=B.scanToInsertionPoint(D);if(O>0)F(U,D.subarray(0,O));if(B.isSafe())K(U);let L=D.subarray(O);if(L.length>0)B.write(L),F(U,L)};return new ReadableStream({async pull(U){let D;try{D=await G.read()}catch(T){throw Q(),T}let{done:O,value:L}=D;if(O){K(U),U.close(),Q();return}if(!z){if(z=!0,B.write(L),F(U,L),J.onShell?.(),B.isSafe())K(U);return}V(U,L)},cancel(U){return Q(),G.cancel(U)}})}var oB=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function H6($){if(!$)return!1;return oB.test($)}async function IY($,Z=()=>{}){let J=N.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await aB($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:NY(),isBot:H6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function _Y($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function aB($,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 xY($,Z){return`${$}:${Z}`}function l8($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function CY($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function AY($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=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 j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=tB($,Z,J,W.buckets);return CY(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function rB($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function tB($,Z,J,W){let Y=xY(Z.salt??$,rB(J));if(!W)return l8(Y);let j=W.get(Y);if(j!==void 0)return j;let z=l8(Y);return W.set(Y,z),z}class SY 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 i8{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 SY(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 Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=eB(W);if(j)J.set(Y,j)}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 eB($){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 Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class $F{}class ZF 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 s8 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 EY 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 bY{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 r1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new i8($.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,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.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 EY(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=JF(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new s8(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!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 bY(this,_Y($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),Q=AY($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,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 IY(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 JF($){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 RY($){if($===void 0)return!0;return await H(r1).enabled($)}async function DZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=OY($[Z]);if(!J||!await RY(J.feature))return null;return J.provider}async function fY($){let Z=[];for(let J of Object.keys($))if(await DZ($,J))Z.push(J);return Z}function n8($){if($&&typeof $==="object")delete $.password;return $}function WF(){return new Proxy({},{get:($,Z)=>wY(Z)})}var kY=new WeakMap;function qY($){if($&&typeof $==="object"){for(let Z of Object.values($))qY(Z);Object.freeze($)}return $}var YF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},jF=qY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:YF});class o8{models;constructor($=WF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return jF}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??x1(),W=H(C1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await d0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||d0())return Y();let z=(kY.get(W)??Promise.resolve()).then(Y,Y);return kY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return n8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return n8(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 listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}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?n8(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 GD}from"crypto";function q0($,Z,J,W,Y){return n0(Z,rY($,Z),J,W,Y)}function n0($,Z,J,W,Y,j){let z=$7(Z,J,W);if(Y&&Z!==z)throw RangeError(wz($,Z,J,W,j));return z}function rY($,Z){let J=$[Z];if(J===void 0)throw TypeError(E2(Z));return J}function V0($){return $!==null&&/object|function/.test(typeof $)}function g0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function Q7($){return b$({name:$},1)}function b$($,Z){return t0((J)=>({value:J,configurable:1,writable:!Z}),$)}function tY($){return t0((Z)=>({get:Z,configurable:1}),$)}function w6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function NZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function t0($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function L3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function zF($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function h0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function G7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function K7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function eY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function $5($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function Z5($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function k($,...Z){return(...J)=>$(...Z,...J)}function yY($){return $[0].toUpperCase()+$.substring(1)}function H3($){return $.slice().sort()}function x6($,Z){return String(Z).padStart($,"0")}function t1($,Z){return Math.sign($-Z)}function $7($,Z,J){return Math.min(Math.max($,Z),J)}function S1($,Z){return[Math.floor($/Z),K3($,Z)]}function K3($,Z){return($%Z+Z)%Z}function Z$($,Z){return[q6($,Z),B7($,Z)]}function q6($,Z){return Math.trunc($/Z)||0}function B7($,Z){return $%Z||0}function M6($){return Math.abs($%1)===0.5}function J5($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=B1[X],B=c/G,[F,K]=Z$(Q,B);W+=K*G,Y+=F}let[j,z]=Z$(W,c);return[Y+j,z]}function y6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=B1[Y];W[J[Y]]=q6($,j),$=B7($,j)}return W}function W5($){return $===w?O4:[]}function Y5($){return $===w?S3:[]}function j5($){return $===w?["year","day"]:[]}function z5($){if($!==void 0)return e($)}function X5($){if($!==void 0)return e0($)}function F7($){if($!==void 0)return M3($)}function e0($){return K5(M3($))}function M3($){return G5(rF($))}function V7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function Q5($,Z){if(Z==null)throw RangeError(E2($));return Z}function b1($){if(!V0($))throw TypeError(kz);return $}function v6($,Z,J=$){if(typeof Z!==$)throw TypeError(x3(J,Z));return Z}function G5($,Z="number"){if(!Number.isInteger($))throw RangeError(NF(Z,$));return $||0}function K5($,Z="number"){if($<=0)throw RangeError(IF(Z,$));return $}function U7($){if(typeof $=="symbol")throw TypeError(AF);return String($)}function C6($,Z){return V0($)?String($):e($,Z)}function g6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(CF($));return $}function B5($,Z="number"){if(typeof $=="bigint")throw TypeError(xF(Z));if($=Number($),!Number.isFinite($))throw RangeError(_F(Z,$));return $}function _0($,Z){return Math.trunc(B5($,Z))||0}function F5($,Z){return G5(B5($,Z),Z)}function vY($,Z){return K5(_0($,Z),Z)}function D7($,Z){let[J,W]=Z$(Z,c),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*c),[Y,W]}function LZ($,Z,J=1){return D7($[0]+Z[0]*J,$[1]+Z[1]*J)}function HZ($,Z){return D7($[0],$[1]+Z)}function u0($,Z){return LZ(Z,$,-1)}function C0($,Z){return t1($[0],Z[0])||t1($[1],Z[1])}function V5($,Z,J){return C0($,Z)===-1||C0($,J)===1}function m6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function MZ($,Z=1){let J=c/Z,[W,Y]=Z$($,J);return[W,Y*Z]}function U5($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=c/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function l0($,Z=1,J){let[W,Y]=$,[j,z]=Z$(Y,Z);return W*(c/Z)+(j+(J?z/Z:0))}function O7($,Z,J=S1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(c/Z)+j,z]}function L7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function H7($){return q0($,"isoYear",O3,D3,1),$.isoYear===O3?q0($,"isoMonth",4,12,1):$.isoYear===D3&&q0($,"isoMonth",1,9,1),$}function e1($){return R1({...$,...r0,isoHour:12}),$}function R1($){let Z=q0($,"isoYear",O3,D3,1),J=Z===O3?1:Z===D3?-1:0;return J&&i0(x0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function i0($){if(!$||V5($,YV,WV))throw RangeError(F4);return $}function J$($){return J5($,5,W1)[1]}function h6($){let[Z,J]=S1($,c);return[y6(J,5,W1),Z]}function D5($){return O5($)[0]}function O5($){return O7($,a0)}function A0($){return IZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function x0($){let Z=A0($);if(Z!==void 0){let[J,W]=Z$(Z,v0);return[J,W*F1+($.isoMicrosecond||0)*m$+($.isoNanosecond||0)]}}function M7($,Z){let[J,W]=h6(J$($)-Z);return i0(x0({...$,isoDay:$.isoDay+W,...J}))}function A6(...$){return IZ(...$)/lz}function IZ(...$){let[Z,J]=L5(...$),W=Z.valueOf();if(!isNaN(W))return W-J*v0}function L5($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===O3?1:$===D3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function Y$($,Z){let[J,W]=HZ($,Z);W<0&&(W+=c,J-=1);let[Y,j]=S1(W,F1),[z,X]=S1(j,m$);return p6(J*v0+Y,z,X)}function p6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-JV)/v0)*Math.sign($),Y=new Date($-W*v0);return NZ(H4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function H5($){return[$.isoYear,$.isoMonth,$.isoDay]}function M5(){return A1}function P7($,Z){switch(Z){case 2:return T7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function P5($){return T7($)?366:365}function T7($){return $%4==0&&($%100!=0||$%400==0)}function T5($){let[Z,J]=L5($.isoYear,$.isoMonth,$.isoDay);return K3(Z.getUTCDay()-J,7)||7}function N5({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function XF($){let Z=A0($);if(Z<zV)return N5($);let J=L7(s2(PZ),Z),{era:W,eraYear:Y}=kj(J,PZ);return[W,Y]}function c6($){return R$($),d6($,1),$}function R$($){return I5($,1),$}function gY($){return $5(m2,$,I5($))}function I5($,Z){let{isoYear:J}=$,W=q0($,"isoMonth",1,M5(),Z);return{isoYear:J,isoMonth:W,isoDay:q0($,"isoDay",1,P7(J,W),Z)}}function d6($,Z){return NZ(W1,[q0($,"isoHour",0,23,Z),q0($,"isoMinute",0,59,Z),q0($,"isoSecond",0,59,Z),q0($,"isoMillisecond",0,999,Z),q0($,"isoMicrosecond",0,999,Z),q0($,"isoNanosecond",0,999,Z)])}function v($){return $===void 0?0:QX(b1($))}function P3($,Z=0){$=$1($);let J=GX($),W=OV($,Z);return[QX($),W,J]}function N7($){return GX($1($))}function _5($){return $=$1($),c2($,9,6,1)}function _Z($,Z,J,W=9,Y=0,j=4){Z=$1(Z);let z=c2(Z,W,Y),X=x7(Z),Q=b3(Z,j),G=E3(Z,W,Y,1);return z==null?z=Math.max(J,G):S5(z,G),X=C7(X,G,1),$&&(Q=((B)=>B<4?(B+2)%4:B)(Q)),[z,G,X,Q]}function u6($,Z=6,J){let W=x7($=A7($,k6)),Y=b3($,7),j=E3($,Z);return j=Q5(k6,j),W=C7(W,j,void 0,J),[j,W,Y]}function I7($){return d2($1($))}function x5($,Z){return _7($1($),Z)}function _7($,Z=4){let J=A5($);return[b3($,4),...C5(E3($,Z),J)]}function C5($,Z){return $!=null?[B1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function x7($){let Z=$[B3];return Z===void 0?1:_0(Z,B3)}function C7($,Z,J,W){let Y=W?c:B1[Z+1];if(Y){let j=B1[Z];if(Y%(($=n0(B3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(x3(B3,$))}else $=n0(B3,$,1,J?1e9:1,1);return $}function A5($){let Z=$[e8];if(Z!==void 0){if(typeof Z!="number"){if(U7(Z)==="auto")return;throw RangeError(x3(e8,Z))}Z=n0(e8,Math.floor(Z),0,9,1)}return Z}function $1($){return $===void 0?{}:b1($)}function A7($,Z){return typeof $=="string"?{[Z]:$}:b1($)}function Y0($){if($!==void 0){if(V0($))return Object.assign(Object.create(null),$);throw TypeError(kz)}}function l6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:QV[Z]})}function S7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=U7(j),j==="auto")return Y?W:null;let z=Y7[j];if(z===void 0&&(z=$V[j]),z===void 0)throw RangeError(vz($,j,Y7));return n0($,z,W,J,1,A3),z}function f$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=U7(Y),z=Z[j];if(z===void 0)throw RangeError(vz($,j,Z));return z}function S5($,Z){if(Z>$)throw RangeError(iF)}function U0($){return{branding:P4,epochNanoseconds:$}}function L0($,Z,J){return{branding:q1,calendar:J,timeZone:Z,epochNanoseconds:$}}function j0($,Z=$.calendar){return{branding:p$,calendar:Z,...h0(YX,$)}}function z0($,Z=$.calendar){return{branding:h$,calendar:Z,...h0(h2,$)}}function S$($,Z=$.calendar){return{branding:fZ,calendar:Z,...h0(h2,$)}}function S6($,Z=$.calendar){return{branding:kZ,calendar:Z,...h0(h2,$)}}function Z1($){return{branding:M4,...h0(WX,$)}}function a($){return{branding:T4,sign:j$($),...h0(y2,$)}}function E5($){return D5($.epochNanoseconds)}function i6($){return O7($.epochNanoseconds,F1)[0]}function b5($){return U5($.epochNanoseconds,m$)}function R5($){return U5($.epochNanoseconds)}function f5($){return $.epochNanoseconds}function D0($){return typeof $=="string"?$:e($.id)}function xZ($,Z){return $===Z||D0($)===D0(Z)}function k5($,Z,J,W,Y){let j=E$(W),[z,X]=((O,L)=>{let T=L((O=A7(O,X7))[zX]),P=DV(O);return P=Q5(X7,P),[P,T]})(Y,$);if(V3(Math.max(z,j),X))return mY(W,z);if(!X)throw RangeError(V4);let[Q,G,B]=t6(Z,J,X),F=t7(B),K=e6(B),V=e7(B),U=K(G,Q,W),D=V(G,Q,U,z);return V3(z,X)?mY(D,z):((O,L,T,P,_,A,E)=>{let S=j$(O),[f,M]=E7(P,g2(T,O),T,S,_,A,E),I=b7(L,f,M);return O[m[T]]+I*S})(D,F(U),z,G,Q,F,K)}function mY($,Z){return l0(F0($),B1[Z],1)}function E7($,Z,J,W,Y,j,z){let X=m[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),B=z($,Y,Q);return[j(G),j(B)]}function b7($,Z,J){let W=l0(u0(Z,J));if(!W)throw RangeError(C3);return l0(u0(Z,$))/W}function w5($,Z){let[J,W,Y]=u6(Z,5,1);return U0(n6($.epochNanoseconds,J,W,Y,1))}function q5($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=u6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((B,F,K,V)=>{let U=S0(K,F),[D,O]=B(U),L=K.epochNanoseconds,T=m0(F,D),P=m0(F,O);if(V5(L,T,P))throw RangeError(C3);return u5(b7(L,T,P),V)?P:T})(c5,G,Z,Q);else{let B=G.getOffsetNanosecondsFor(W);W=w$(G,h5(Y$(W,B),z,X,Q),B,2,0,1)}return L0(W,Y,j)}function y5($,Z){return j0(h5($,...u6(Z)),$.calendar)}function v5($,Z){let[J,W,Y]=u6(Z,5);var j;return Z1((j=Y,R7($,T3(J,W),j)[0]))}function g5($,Z){let J=$(Z.timeZone),W=S0(Z,J),[Y,j]=c5(W),z=l0(u0(m0(J,Y),m0(J,j)),D4,1);if(z<=0)throw RangeError(C3);return z}function m5($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>m0(z,j(S0(X,z))))(d5,$(J),Z);return L0(Y,J,W)}function h5($,Z,J,W){return p5($,T3(Z,J),W)}function p5($,Z,J){let[W,Y]=R7($,Z,J);return R1({...q$($,Y),...W})}function R7($,Z,J){return h6(W$(J$($),Z,J))}function E6($){return W$($,U4,7)}function T3($,Z){return B1[$]*Z}function c5($){let Z=d5($);return[Z,q$(Z,1)]}function d5($){return ZV(6,$)}function QF($,Z,J){let W=Math.min(E$($),6);return AZ(o6(F0($,W),Z,J),W)}function s6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let B=V3(W,X)?$4(X)&&W<6&&J>=6?KF:GF:BF,[F,K,V]=B($,Z,J,W,Y,j,z,X,Q,G);return V&&W!==7&&(F=((U,D,O,L,T,P,_,A)=>{let E=j$(U);for(let S=L+1;S<=O;S++){if(S===7&&O!==7)continue;let f=g2(S,U);f[m[S]]+=E;let M=l0(u0(_(A(T,P,f)),D));if(M&&Math.sign(M)!==E)break;U=f}return U})(F,K,J,Math.max(6,W),z,X,Q,G)),F}function n6($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/c)($);return[W$(j,J,W),0]}return o6($,T3(Z,J),W,Y)}function o6($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=c,Y-=1);let[z,X]=S1(W$(j,Z,J),c);return D7(Y+z,X)}function W$($,Z,J){return u5($/Z,J)*Z}function u5($,Z){return MV[Z]($)}function GF($,Z,J,W,Y,j){let z=j$($),X=F0($),Q=n6(X,W,Y,j),G=u0(X,Q),B=Math.sign(Q[0]-X[0])===z,F=AZ(Q,Math.min(J,6));return[{...$,...F},LZ(Z,G),B]}function KF($,Z,J,W,Y,j,z,X,Q,G){let B=j$($),F=l0(F0($,5)),K=T3(W,Y),V=W$(F,K,j),[U,D]=E7(z,{...$,...v2},6,B,X,Q,G),O=V-l0(u0(U,D)),L=0;O&&Math.sign(O)!==B?Z=HZ(U,V):(L+=B,V=W$(O,K,j),Z=HZ(D,V));let T=J4(V);return[{...$,...T,days:$.days+L},Z,Boolean(L)]}function BF($,Z,J,W,Y,j,z,X,Q,G){let B=j$($),F=m[W],K=g2(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let V=q6($[F],Y)*Y;K[F]=V;let[U,D]=E7(z,K,W,Y*B,X,Q,G),O=V+b7(Z,U,D)*B*Y,L=W$(O,Y,j),T=Math.sign(L-O)===B;return K[F]=L,[K,T?D:U,T]}function f7($,Z,J,W){let[Y,j,z,X]=((G)=>{let B=_7(G=$1(G));return[G.timeZone,...B]})(W),Q=Y!==void 0;return((G,B,F,K,V,U)=>{F=o6(F,V,K,1);let D=B.getOffsetNanosecondsFor(F);return m7(Y$(F,D),U)+(G?k$(E6(D)):"Z")})(Q,Z(Q?$(Y):c$),J.epochNanoseconds,j,z,X)}function k7($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=$1(G);let B=d2(G),F=A5(G),K=HV(G),V=b3(G,4),U=E3(G,4);return[B,LV(G),K,V,...C5(U,F)]})(J);return((G,B,F,K,V,U,D,O,L,T)=>{K=o6(K,L,O,1);let P=G(F).getOffsetNanosecondsFor(K);return m7(Y$(K,P),T)+k$(E6(P),D)+((_,A)=>A!==1?"["+(A===2?"!":"")+D0(_)+"]":"")(F,U)+h7(B,V)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function w7($,Z){let[J,W,Y,j]=((G)=>(G=$1(G),[d2(G),..._7(G)]))(Z);return z=$.calendar,X=J,Q=j,m7(p5($,Y,W),Q)+h7(z,X);var z,X,Q}function q7($,Z){return J=$.calendar,W=$,Y=I7(Z),b6(W)+h7(J,Y);var J,W,Y}function y7($,Z){return l5($.calendar,i5,$,I7(Z))}function v7($,Z){return l5($.calendar,FF,$,I7(Z))}function g7($,Z){let[J,W,Y]=x5(Z);return j=Y,s5(R7($,W,J)[0],j);var j}function a6($,Z){let[J,W,Y]=x5(Z,3);return W>1&&($={...$,...QF($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?E0(j):j,{hours:G,minutes:B}=Q,[F,K]=O7(F0(Q,3),a0,Z$);Zj(F);let V=p7(K,z),U=z>=0||!X||V;return(X<0?"-":"")+"P"+hY({Y:A$(Q.years),M:A$(Q.months),W:A$(Q.weeks),D:A$(Q.days)})+(G||B||F||U?"T"+hY({H:A$(G),M:A$(B),S:A$(F,U)+V}):"")})($,Y)}function l5($,Z,J,W){let Y=D0($),j=W>1||W===0&&Y!==w;return W===1?Y===w?Z(J):b6(J):j?b6(J)+n5(Y,W===2):Z(J)}function hY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function m7($,Z){return b6($)+"T"+s5($,Z)}function b6($){return i5($)+"-"+o0($.isoDay)}function i5($){let{isoYear:Z}=$;return(Z<0||Z>9999?o5(Z)+x6(6,Math.abs(Z)):x6(4,Z))+"-"+o0($.isoMonth)}function FF($){return o0($.isoMonth)+"-"+o0($.isoDay)}function s5($,Z){let J=[o0($.isoHour),o0($.isoMinute)];return Z!==-1&&J.push(o0($.isoSecond)+((W,Y,j,z)=>p7(W*F1+Y*m$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function k$($,Z=0){if(Z===1)return"";let[J,W]=S1(Math.abs($),D4),[Y,j]=S1(W,U4),[z,X]=S1(j,a0);return o5($)+o0(J)+":"+o0(Y)+(z||X?":"+o0(z)+p7(X):"")}function h7($,Z){if(Z!==1){let J=D0($);if(Z>1||Z===0&&J!==w)return n5(J,Z===2)}return""}function n5($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function p7($,Z){let J=x6(9,$);return J=Z===void 0?J.replace(NV,""):J.slice(0,Z),J?"."+J:""}function o5($){return $<0?"-":"+"}function A$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function VF($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=Y$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function a5($,Z){let J=S0(Z,$);return{calendar:Z.calendar,...h0(YX,J),offset:k$(J.offsetNanoseconds),timeZone:Z.timeZone}}function w$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return M7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,B,F,K)=>{let V=x0(B);K&&(F=E6(F));for(let U of G){let D=l0(u0(U,V));if(K&&(D=E6(D)),D===F)return U}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(hF)}return z?x0(Z):m0($,Z,Y,X)}function m0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(pF);if(W.length)return W[J===3?1:0];let Y=x0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(HZ(Q,-c));return d7(X.getOffsetNanosecondsFor(HZ(Q,c))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(Y$(Y,z)))[J===2?0:W.length-1]}function c7($){if(Math.abs($)>=c)throw RangeError(gF);return $}function d7($){if($>c)throw RangeError(mF);return $}function u7($,Z,J){return U0(i0(LZ(Z.epochNanoseconds,((W)=>{if(Jj(W))throw RangeError(uF);return F0(W,5)})($?E0(J):J))))}function l7($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...a7(z,X,W,J?E0(Y):Y,j)}}function i7($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return j0(r7($(j),J,Z?E0(W):W,Y),j)}function s7($,Z,J,W,Y){let{calendar:j}=J;return z0(r6($(j),J,Z?E0(W):W,Y),j)}function n7($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=F3(z,J);Z&&(W=Z4(W)),W.sign<0&&(X=z.dateAdd(X,{...O0,months:1}),X=q$(X,-1));let Q=z.dateAdd(X,W,Y);return S$(F3(z,Q),j)}function o7($,Z,J){return Z1(r5(Z,$?E0(J):J)[0])}function a7($,Z,J,W,Y){let j=F0(W,5),z=J.epochNanoseconds;if(Jj(W)){let X=S0(J,$);z=LZ(m0($,{...r6(Z,X,{...W,...v2},Y),...h0(W1,X)}),j)}else z=LZ(z,j),v(Y);return{epochNanoseconds:i0(z)}}function r7($,Z,J,W){let[Y,j]=r5(Z,J);return R1({...r6($,Z,{...J,...v2,days:J.days+j},W),...Y})}function r6($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);v(W);let Y=J.days+F0(J,5)[0];return Y?e1(q$(Z,Y)):Z}function F3($,Z,J=1){return q$(Z,J-$.day(Z))}function r5($,Z){let[J,W]=F0(Z,5),[Y,j]=h6(J$($)+W);return[Y,J+j]}function q$($,Z){return Z?{...$,...p6(A0($)+Z*v0)}:$}function t6($,Z,J){let W=$(J.calendar);return $4(J)?[J,W,Z(J.timeZone)]:[{...J,...r0},W]}function t7($){return $?f5:x0}function e6($){return $?k(a7,$):r7}function e7($){return $?k(DF,$):OF}function $4($){return $&&$.epochNanoseconds}function V3($,Z){return $<=6-($4(Z)?1:0)}function $2($,Z,J,W,Y,j,z){let X=$($1(z).relativeTo),Q=Math.max(E$(Y),E$(j));if(V3(Q,X))return a(CZ(((D,O,L,T)=>{let P=LZ(F0(D),F0(O),T?-1:1);if(!Number.isFinite(P[0]))throw RangeError(F4);return{...O0,...AZ(P,L)}})(Y,j,Q,W)));if(!X)throw RangeError(V4);W&&(j=E0(j));let[G,B,F]=t6(Z,J,X),K=e6(F),V=e7(F),U=K(B,G,Y);return a(V(B,G,K(B,U,j),Q))}function t5($,Z,J,W,Y){let j=E$(W),[z,X,Q,G,B]=((E,S,f)=>{E=A7(E,k6);let M=c2(E),I=f(E[zX]),y=x7(E),H$=b3(E,7),T0=E3(E);if(M===void 0&&T0===void 0)throw RangeError(lF);return T0==null&&(T0=0),M==null&&(M=Math.max(T0,S)),S5(M,T0),y=C7(y,T0,1),[M,T0,y,H$,I]})(Y,j,$),F=Math.max(j,z);if(!$4(B)&&F<=6)return a(CZ(((E,S,f,M,I)=>{let y=n6(F0(E),f,M,I);return{...O0,...AZ(y,S)}})(W,z,X,Q,G)));if(!B)throw RangeError(V4);let[K,V,U]=t6(Z,J,B),D=t7(U),O=e6(U),L=e7(U),T=O(V,K,W),P=L(V,K,T,z),_=W.sign,A=j$(P);if(_&&A&&_!==A)throw RangeError(C3);return A&&(P=s6(P,D(T),z,X,Q,G,V,K,D,O)),a(P)}function e5($){return $.sign===-1?Z4($):$}function Z4($){return a(E0($))}function E0($){let Z={};for(let J of m)Z[J]=-1*$[J]||0;return Z}function $j($){return!$.sign}function j$($,Z=m){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(dF);J=Y}}return J}function CZ($){for(let Z of eF)n0(Z,$[Z],-sY,sY,1);return Zj(l0(F0($),a0)),$}function Zj($){if(!Number.isSafeInteger($))throw RangeError(cF)}function F0($,Z=6){return J5($,Z,m)}function AZ($,Z=6){let[J,W]=$,Y=y6(W,Z,m);if(Y[m[Z]]+=J*(c/B1[Z]),!Number.isFinite(Y[m[Z]]))throw RangeError(F4);return Y}function J4($,Z=5){return y6($,Z,m)}function Jj($){return Boolean(j$($,JX))}function E$($){let Z=9;for(;Z>0&&!$[m[Z]];Z--);return Z}function UF($,Z){return[$,Z]}function pY($){let Z=Math.floor($/I6)*I6;return[Z,Z+I6]}function Wj($){let Z=z$($=C6($));if(!Z)throw RangeError(y0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(y0($));J=SZ(Z.offset)}return Z.timeZone&&Y2(Z.timeZone,1),U0(M7(c6(Z),J))}function Yj($){let Z=z$(e($));if(!Z)throw RangeError(y0($));if(Z.timeZone)return Vj(Z,Z.offset?SZ(Z.offset):void 0);if(Z.m)throw RangeError(y0($));return Dj(Z)}function jj($,Z){let J=z$(e($));if(!J||!J.timeZone)throw RangeError(y0($));let{offset:W}=J,Y=W?SZ(W):void 0,[,j,z]=P3(Z);return Vj(J,Y,j,z)}function SZ($){let Z=Y2($);if(Z===void 0)throw RangeError(y0($));return Z}function zj($){let Z=z$(e($));if(!Z||Z.m)throw RangeError(y0($));return j0(Uj(Z))}function W4($){let Z=z$(e($));if(!Z||Z.m)throw RangeError(y0($));return z0(Z.p?Uj(Z):Dj(Z))}function Xj($,Z){let J=J2(e(Z));if(J)return Z2(J),S$(H7(R$(J)));let W=W4(Z);return S$(F3($(W.calendar),W))}function Z2($){if($.calendar!==w)throw RangeError(E1($.calendar))}function Qj($,Z){let J=W2(e(Z));if(J)return Z2(J),S6(R$(J));let W=W4(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,B]=j.I(z,X),[F,K]=j.N(G,B,Q);return S6(e1(j.P(F,K,Q)),Y)}function Gj($){let Z,J=((W)=>{let Y=AV.exec(W);return Y?(Y4(Y[10]),Hj(Y)):void 0})(e($));if(!J){if(J=z$($),!J)throw RangeError(y0($));if(!J.p)throw RangeError(y0($));if(J.m)throw RangeError(E1("Z"));Z2(J)}if((Z=J2($))&&gY(Z))throw RangeError(y0($));if((Z=W2($))&&gY(Z))throw RangeError(y0($));return Z1(d6(J,1))}function Kj($){let Z=((J)=>{let W=bV.exec(J);return W?((Y)=>{function j(B,F,K){let V=0,U=0;if(K&&([V,Q]=S1(Q,B1[K])),B!==void 0){if(X)throw RangeError(E1(B));U=((D)=>{let O=parseInt(D);if(!Number.isFinite(O))throw RangeError(E1(D));return O})(B),z=1,F&&(Q=j2(F)*(B1[K]/a0),X=1)}return V+U}let z=0,X=0,Q=0,G={...NZ(m,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...y6(Q,2,m)};if(!z)throw RangeError(qz(m));return z2(Y[1])<0&&(G=E0(G)),G})(W):void 0})(e($));if(!Z)throw RangeError(y0($));return a(CZ(Z))}function Bj($){let Z=z$($)||J2($)||W2($);return Z?Z.calendar:$}function Fj($){let Z=z$($);return Z&&(Z.timeZone||Z.m&&c$||Z.offset)||$}function Vj($,Z,J=0,W=0){let Y=j4($.timeZone),j=N4(Y);return L0(w$(j,c6($),Z,J,W,!j.v,$.m),Y,N3($.calendar))}function Uj($){return Oj(R1(c6($)))}function Dj($){return Oj(e1(R$($)))}function Oj($){return{...$,calendar:N3($.calendar)}}function z$($){let Z=CV.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:Lj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...Hj(J.slice(5)),...Y4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function J2($){let Z=_V.exec($);return Z?((J)=>({isoYear:Lj(J),isoMonth:parseInt(J[4]),isoDay:1,...Y4(J[5])}))(Z):void 0}function W2($){let Z=xV.exec($);return Z?((J)=>({isoYear:TZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...Y4(J[3])}))(Z):void 0}function Y2($,Z){let J=SV.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(E1(j));return c7((OZ(W[2])*D4+OZ(W[3])*U4+OZ(W[4])*a0+j2(W[5]||""))*z2(W[1]))})(J,Z):void 0}function Lj($){let Z=z2($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(E1(-0));return Z*J}function Hj($){let Z=OZ($[3]);return{...h6(j2($[4]||""))[0],isoHour:OZ($[1]),isoMinute:OZ($[2]),isoSecond:Z===60?59:Z}}function Y4($){let Z,J,W=[];if($.replace(EV,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(E1(Y))}else{if(J)throw RangeError(E1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(E1($));return{timeZone:J,calendar:W[0]||w}}function j2($){return parseInt($.padEnd(9,"0"))}function EZ($){return new RegExp(`^${$}$`,"i")}function z2($){return $&&$!=="+"?-1:1}function OZ($){return $===void 0?0:parseInt($)}function Mj($){return j4(e($))}function j4($){let Z=X2($);return typeof Z=="number"?k$(Z):Z?((J)=>{if(fV.test(J))throw RangeError(vF);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?yY(j).replace(/island|noronha|murdo|rivadavia|urville/,yY):j)).join("/")})($):c$}function cY($){let Z=X2($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:c$}function X2($){let Z=Y2($=$.toUpperCase(),1);return Z!==void 0?Z:$!==c$?RV($):void 0}function Q2($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function G2($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function Pj($,Z,J,W,Y,j){let z=$($1(j).relativeTo),X=Math.max(E$(W),E$(Y));if($5(m,W,Y))return 0;if(V3(X,z))return C0(F0(W),F0(Y));if(!z)throw RangeError(V4);let[Q,G,B]=t6(Z,J,z),F=t7(B),K=e6(B);return C0(F(K(G,Q,W)),F(K(G,Q,Y)))}function K2($,Z){return y$($,Z)||z4($,Z)}function y$($,Z){return t1(A0($),A0(Z))}function z4($,Z){return t1(J$($),J$(Z))}function Tj($,Z){return!Q2($,Z)}function Nj($,Z){return!G2($,Z)&&!!X4($.timeZone,Z.timeZone)&&xZ($.calendar,Z.calendar)}function Ij($,Z){return!K2($,Z)&&xZ($.calendar,Z.calendar)}function _j($,Z){return!y$($,Z)&&xZ($.calendar,Z.calendar)}function xj($,Z){return!y$($,Z)&&xZ($.calendar,Z.calendar)}function Cj($,Z){return!y$($,Z)&&xZ($.calendar,Z.calendar)}function Aj($,Z){return!z4($,Z)}function X4($,Z){if($===Z)return 1;let J=D0($),W=D0(Z);if(J===W)return 1;try{return cY(J)===cY(W)}catch(Y){}}function B2($,Z,J,W){let Y=_Z($,Y0(W),3,5),j=Q4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return a($?E0(j):j)}function F2($,Z,J,W,Y,j){let z=K4(W.calendar,Y.calendar),X=Y0(j),[Q,G,B,F]=_Z(J,X,5),K=W.epochNanoseconds,V=Y.epochNanoseconds,U=C0(V,K),D;if(U)if(Q<6)D=Q4(K,V,Q,G,B,F);else{let O=Z(((T,P)=>{if(!X4(T,P))throw RangeError(pz);return T})(W.timeZone,Y.timeZone)),L=$(z);D=Ej(L,O,W,Y,U,Q,X),D=s6(D,V,Q,G,B,F,L,W,f5,k(a7,O))}else D=O0;return a(J?E0(D):D)}function V2($,Z,J,W,Y){let j=K4(J.calendar,W.calendar),z=Y0(Y),[X,Q,G,B]=_Z(Z,z,6),F=x0(J),K=x0(W),V=C0(K,F),U;if(V)if(X<=6)U=Q4(F,K,X,Q,G,B);else{let D=$(j);U=bj(D,J,W,V,X,z),U=s6(U,K,X,Q,G,B,D,J,x0,r7)}else U=O0;return a(Z?E0(U):U)}function U2($,Z,J,W,Y){let j=K4(J.calendar,W.calendar),z=Y0(Y);return Sj(Z,()=>$(j),J,W,..._Z(Z,z,6,9,6),z)}function D2($,Z,J,W,Y){let j=K4(J.calendar,W.calendar),z=Y0(Y),X=_Z(Z,z,9,9,8),Q=$(j);return Sj(Z,()=>Q,F3(Q,J),F3(Q,W),...X,z)}function Sj($,Z,J,W,Y,j,z,X,Q){let G=x0(J),B=x0(W),F;if(C0(B,G))if(Y===6)F=Q4(G,B,Y,j,z,X);else{let K=Z();F=K.dateUntil(J,W,Y,Q),j===6&&z===1||(F=s6(F,B,Y,j,z,X,K,J,x0,r6))}else F=O0;return a($?E0(F):F)}function O2($,Z,J,W){let Y=Y0(W),[j,z,X,Q]=_Z($,Y,5,5),G=W$(L2(Z,J),T3(z,X),Q),B={...O0,...J4(G,j)};return a($?E0(B):B)}function DF($,Z,J,W,Y,j){let z=C0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Rj(J.epochNanoseconds,W.epochNanoseconds,Y):Ej(Z,$,J,W,z,Y,j):O0}function OF($,Z,J,W,Y){let j=x0(Z),z=x0(J),X=C0(z,j);return X?W<=6?Rj(j,z,W):bj($,Z,J,X,W,Y):O0}function Ej($,Z,J,W,Y,j,z){let[X,Q,G]=((K,V,U,D)=>{function O(){return S={...q$(P,A++*-D),...T},f=m0(K,S),C0(_,f)===-D}let L=S0(V,K),T=h0(W1,L),P=S0(U,K),_=U.epochNanoseconds,A=0,E=L2(L,P),S,f;if(Math.sign(E)===-D&&A++,O()&&(D===-1||O()))throw RangeError(C3);let M=l0(u0(f,_));return[L,S,M]})(Z,J,W,Y);var B,F;return{...j===6?(B=X,F=Q,{...O0,days:fj(B,F)}):$.dateUntil(X,Q,j,z),...J4(G)}}function bj($,Z,J,W,Y,j){let[z,X,Q]=((G,B,F)=>{let K=B,V=L2(G,B);return Math.sign(V)===-F&&(K=q$(B,-F),V+=c*F),[G,K,V]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...J4(Q)}}function Q4($,Z,J,W,Y,j){return{...O0,...AZ(n6(u0($,Z),W,Y,j),J)}}function Rj($,Z,J){return{...O0,...AZ(u0($,Z),J)}}function fj($,Z){return G4(A0($),A0(Z))}function G4($,Z){return Math.trunc((Z-$)/v0)}function L2($,Z){return J$(Z)-J$($)}function K4($,Z){if(!xZ($,Z))throw RangeError(f2);return $}function LF($){function Z(Y){return((j,z)=>({...kj(j,z),F:j.month,day:parseInt(j.day)}))(L7(J,Y),W)}let J=s2($),W=R6($);return{id:$,O:HF(Z),B:MF(Z)}}function HF($){return g0((Z)=>{let J=A0(Z);return $(J)},WeakMap)}function MF($){let Z=$(0).year-jV;return g0((J)=>{let W,Y=IZ(J-Z),j=[],z=[];do Y+=400*v0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*v0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=v0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:uz(z.reverse())}})}function kj($,Z){let J,W,Y=wj($);if($.era){let j=ez[Z];j!==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=Y,Y=mj(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function wj($){return parseInt($.relatedYear||$.year)}function Z7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function U3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*v0}function P6($){let Z=uY(this,$),J=uY(this,$-1),W=Z.length;if(W>J.length){let Y=hj(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function T6($){return G4(U3.call(this,$),U3.call(this,$+1))}function dY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),G4(J[Z-1],Y[W-1])}function N6($){return this.B($).k.length}function uY($,Z){return Object.keys($.B(Z).C)}function qj($){return N3(e($))}function N3($){if(($=$.toLowerCase())!==w&&$!==L4&&R6($)!==R6(s2($).resolvedOptions().calendar))throw RangeError(yF($));return $}function R6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function yj($){return this.R($)[0]}function vj($){return this.R($)[1]}function H2($){let[Z]=this.h($);return G4(this.q(Z),A0($))+1}function gj($){let Z=wV.exec($);if(!Z)throw RangeError(wF($));return[parseInt(Z[1]),Boolean(Z[2])]}function f6($,Z,J){return $+(Z||J&&$>=J?1:0)}function J7($,Z){return $-(Z&&$>=Z?1:0)}function mj($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function W7($){return ez[pj($)]}function hj($){return aF[pj($)]}function pj($){return R6($.id||w)}function cj($,Z,J,W){let Y=X$(J,W,J1,[],oz);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=v$(Y),X=$(Y.timeZone);return{epochNanoseconds:w$(Z(X),{...j,...z},Y.offset!==void 0?SZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...r0}}function dj($,Z,J,W,Y,j){let z=X$(J,Y,J1,sz,oz),X=$(z.timeZone),[Q,G,B]=P3(j),F=J.dateFromFields(z,l6(j,Q)),K=v$(z,Q);return L0(w$(Z(X),{...F,...K},z.offset!==void 0?SZ(z.offset):void 0,G,B),X,W)}function uj($,Z,J){let W=X$($,Z,J1,[],w1),Y=v(J);return j0(R1({...$.dateFromFields(W,l6(J,Y)),...v$(W,Y)}))}function M2($,Z,J,W=[]){let Y=X$($,Z,J1,W);return $.dateFromFields(Y,J)}function P2($,Z,J,W){let Y=X$($,Z,q2,W);return $.yearMonthFromFields(Y,J)}function T2($,Z,J,W,Y=[]){let j=X$($,J,J1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=TZ),$.monthDayFromFields(j,W)}function lj($,Z){let J=v(Z);return Z1(v$(K1($,j7,[],1),J))}function ij($){let Z=K1($,y2);return a(CZ({...O0,...Z}))}function X$($,Z,J,W=[],Y=[]){return K1(Z,[...$.fields(J),...Y].sort(),W)}function K1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(SF(X));if(X==="constructor"||X==="__proto__")throw RangeError(b2(X));let Q=$[X];if(Q!==void 0)z=1,nY[X]&&(Q=nY[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(E2(X));Y[X]=tz[X]}j=X}if(W&&!z)throw TypeError(qz(Z));return Y}function v$($,Z){return d6(gV({...tz,...$}),Z)}function sj($,Z,J,W,Y,j){let z=Y0(j),{calendar:X,timeZone:Q}=J;return L0(((G,B,F,K,V)=>{let U=I3(G,F,K,J1,nz,iz),[D,O,L]=P3(V,2);return w$(B,{...G.dateFromFields(U,l6(V,D)),...v$(U,D)},SZ(U.offset),O,L)})($(X),Z(Q),W,Y,z),Q,X)}function nj($,Z,J,W,Y){let j=Y0(Y);return j0(((z,X,Q,G)=>{let B=I3(z,X,Q,J1,w1),F=v(G);return R1({...z.dateFromFields(B,l6(G,F)),...v$(B,F)})})($(Z.calendar),J,W,j))}function oj($,Z,J,W,Y){let j=Y0(Y);return((z,X,Q,G)=>{let B=I3(z,X,Q,J1);return z.dateFromFields(B,G)})($(Z.calendar),J,W,j)}function aj($,Z,J,W,Y){let j=Y0(Y);return S$(((z,X,Q,G)=>{let B=I3(z,X,Q,q2);return z.yearMonthFromFields(B,G)})($(Z.calendar),J,W,j))}function rj($,Z,J,W,Y){let j=Y0(Y);return((z,X,Q,G)=>{let B=I3(z,X,Q,J1);return z.monthDayFromFields(B,G)})($(Z.calendar),J,W,j)}function tj($,Z,J){return Z1(((W,Y,j)=>{let z=v(j);return v$({...h0(j7,W),...K1(Y,j7)},z)})($,Z,J))}function ej($,Z){return a((J=$,W=Z,CZ({...J,...K1(W,y2)})));var J,W}function I3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=K1(Z,z,j),Q=K1(J,z);return X=$.mergeFields(X,Q),K1(X,z,[])}function N2($,Z){let J=X$($,Z,rz);return $.monthDayFromFields(J)}function I2($,Z,J){let W=X$($,Z,az);return $.yearMonthFromFields(W,J)}function $z($,Z,J,W,Y){Z=h0(J=$.fields(J),Z),W=K1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=K1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function a8($,Z){let{era:J,eraYear:W,year:Y}=Z,j=W7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(bF);if(!j)throw RangeError(EF);let z=j[J];if(z===void 0)throw RangeError(fF(J));let X=mj(W,z);if(Y!==void 0&&Y!==X)throw RangeError(RF);Y=X}else if(Y===void 0)throw TypeError(kF(j));return Y}function r8($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,B)=>{let F=X.U(G),[K,V]=gj(Q),U=f6(K,V,F);if(V){let D=hj(X);if(D===void 0)throw RangeError(G3);if(D>0){if(U>D)throw RangeError(G3);if(F===void 0){if(B===1)throw RangeError(G3);U--}}else{if(U!==-D)throw RangeError(G3);if(F===void 0&&B===1)throw RangeError(G3)}}return U})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(mz);Y=z,W=1}else if(Y===void 0)throw TypeError(qF);return n0("month",Y,1,$.L(J),W)}function lY($,Z,J,W,Y){return q0(Z,"day",1,$.j(W,J),Y)}function t8($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Zz($){return U0(i0(m6(g6($))))}function Jz($,Z,J,W,Y=w){return L0(i0(m6(g6(J))),Z(W),$(Y))}function Wz($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,B=w){return j0(R1(c6(t0(_0,NZ(H4,[Z,J,W,Y,j,z,X,Q,G])))),$(B))}function Yz($,Z,J,W,Y=w){return z0(e1(R$(t0(_0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function jz($,Z,J,W=w,Y=1){let j=_0(Z),z=_0(J),X=$(W);return S$(H7(R$({isoYear:j,isoMonth:z,isoDay:_0(Y)})),X)}function zz($,Z,J,W=w,Y=TZ){let j=_0(Z),z=_0(J),X=$(W);return S6(e1(R$({isoYear:_0(Y),isoMonth:j,isoDay:z})),X)}function Xz($=0,Z=0,J=0,W=0,Y=0,j=0){return Z1(d6(t0(_0,NZ(W1,[$,Z,J,W,Y,j])),1))}function Qz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return a(CZ(t0(F5,NZ(m,[$,Z,J,W,Y,j,z,X,Q,G]))))}function _2($,Z,J=w){return L0($.epochNanoseconds,Z,J)}function Gz($){return U0($.epochNanoseconds)}function x2($,Z){return j0(S0(Z,$))}function C2($,Z){return z0(S0(Z,$))}function Kz($,Z,J){return I2($(Z.calendar),J)}function Bz($,Z,J){return N2($(Z.calendar),J)}function A2($,Z){return Z1(S0(Z,$))}function Fz($,Z,J,W){let Y=((j,z,X,Q)=>{let G=N7(Q);return m0(j(z),X,G)})($,J,Z,W);return L0(i0(Y),J,Z.calendar)}function Vz($,Z,J){let W=$(Z.calendar);return S$({...Z,...I2(W,J)})}function Uz($,Z,J){return N2($(Z.calendar),J)}function Dz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):r0;return L0(m0(J(j),{...W,...X}),j,W.calendar)}function Oz($,Z=r0){return j0(R1({...$,...Z}))}function Lz($,Z,J){return I2($(Z.calendar),J)}function Hz($,Z,J){return N2($(Z.calendar),J)}function Mz($,Z,J,W){return((Y,j,z)=>$z(Y,j,az,b1(z),S3))($(Z.calendar),J,W)}function Pz($,Z,J,W){return((Y,j,z)=>$z(Y,j,rz,b1(z),O4))($(Z.calendar),J,W)}function Tz($,Z,J,W,Y){let j=b1(Y),z=Z(j.plainDate),X=$(j.timeZone);return L0(m0(J(X),{...z,...W}),X,z.calendar)}function Nz($,Z){return j0(R1({...$,...Z}))}function Iz($){return U0(i0(MZ($,a0)))}function _z($){return U0(i0(MZ($,F1)))}function xz($){return U0(i0(m6(g6($),m$)))}function Cz($){return U0(i0(m6(g6($))))}function Az($,Z,J=r0){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J};return L0(w$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function Sz($,Z,J){let W=Z.timeZone,Y=$(W),j={...S0(Z,Y),...J},z=fz(Z.calendar,J.calendar);return L0(w$(Y,j,j.offsetNanoseconds,2),W,z)}function Ez($,Z=r0){return j0({...$,...Z})}function bz($,Z){return j0({...$,...Z},fz($.calendar,Z.calendar))}function B4($,Z){return{...$,calendar:Z}}function Rz($,Z){return{...$,timeZone:Z}}function fz($,Z){if($===Z)return $;let J=D0($),W=D0(Z);if(J===W||J===w)return Z;if(W===w)return $;throw RangeError(f2)}function PF($,Z){return(J)=>J===w?$:J===L4||J===PZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),kV(J))}function g$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=G7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=c$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function f1($,Z=S2){let[J,,,W]=$;return(Y,j=$U,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...TF($,Q,z)]}}function S2($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(sF);J.timeZone=$}return new Q$(Z,J)}function TF($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==w)&&z!==X)throw RangeError(f2)})(D0(j.calendar),Z.calendar,Y),W(j,Z)))}function bZ($){let Z=_3();return Y$(Z,$.getOffsetNanosecondsFor(Z))}function _3(){return MZ(Date.now(),F1)}function k1(){return aY||(aY=new Q$().resolvedOptions().timeZone)}var NF=($,Z)=>`Non-integer ${$}: ${Z}`,IF=($,Z)=>`Non-positive ${$}: ${Z}`,_F=($,Z)=>`Non-finite ${$}: ${Z}`,xF=($)=>`Cannot convert bigint to ${$}`,CF=($)=>`Invalid bigint: ${$}`,AF="Cannot convert Symbol to string",kz="Invalid object",wz=($,Z,J,W,Y)=>Y?wz($,Y[Z],Y[J],Y[W]):x3($,Z)+`; must be between ${J}-${W}`,x3=($,Z)=>`Invalid ${$}: ${Z}`,E2=($)=>`Missing ${$}`,b2=($)=>`Invalid field ${$}`,SF=($)=>`Duplicate field ${$}`,qz=($)=>"No valid fields: "+$.join(),yz="Invalid bag",vz=($,Z,J)=>x3($,Z)+"; must be "+Object.keys(J).join(),gz="Cannot use valueOf",R2="Invalid calling context",EF="Forbidden era/eraYear",bF="Mismatching era/eraYear",RF="Mismatching year/eraYear",fF=($)=>`Invalid era: ${$}`,kF=($)=>"Missing year"+($?"/era/eraYear":""),wF=($)=>`Invalid monthCode: ${$}`,mz="Mismatching month/monthCode",qF="Missing month/monthCode",iY="Cannot guess year",G3="Invalid leap month",hz="Invalid protocol",C3="Invalid protocol results",f2="Mismatching Calendars",yF=($)=>`Invalid Calendar: ${$}`,pz="Mismatching TimeZones",vF="Forbidden ICU TimeZone",gF="Out-of-bounds offset",mF="Out-of-bounds TimeZone gap",hF="Invalid TimeZone offset",pF="Ambiguous offset",F4="Out-of-bounds date",cF="Out-of-bounds duration",dF="Cannot mix duration signs",V4="Missing relativeTo",uF="Cannot use large units",lF="Required smallestUnit or largestUnit",iF="smallestUnit > largestUnit",y0=($)=>`Cannot parse: ${$}`,E1=($)=>`Invalid substring: ${$}`,cz=($)=>`Cannot format ${$}`,dz="Mismatching types for formatting",sF="Cannot specify TimeZone",uz=k(L3,($,Z)=>Z),RZ=k(L3,($,Z,J)=>J),o0=k(x6,2),Y7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},A3=Object.keys(Y7),v0=86400000,lz=1000,m$=1000,F1=1e6,a0=1e9,U4=60000000000,D4=3600000000000,c=86400000000000,B1=[1,m$,F1,a0,U4,D4,c],w1=A3.slice(0,6),j7=H3(w1),iz=["offset"],sz=["timeZone"],nz=w1.concat(iz),oz=nz.concat(sz),z7=["era","eraYear"],nF=z7.concat(["year"]),O4=["year"],k2=["monthCode"],w2=["month"].concat(k2),S3=["day"],q2=w2.concat(O4),az=k2.concat(O4),J1=S3.concat(q2),oF=S3.concat(w2),rz=S3.concat(k2),tz=RZ(w1,0),w="iso8601",L4="gregory",PZ="japanese",ez={[L4]:{bce:-1,ce:0},[PZ]:{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}},aF={chinese:13,dangi:13,hebrew:-6},e=k(v6,"string"),$X=k(v6,"boolean"),rF=k(v6,"number"),ZX=k(v6,"function"),m=A3.map(($)=>$+"s"),y2=H3(m),tF=m.slice(0,6),JX=m.slice(6),eF=JX.slice(1),$V=uz(m),O0=RZ(m,0),v2=RZ(tF,0),g2=k(Z5,m),W1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],m2=["isoDay","isoMonth","isoYear"],H4=W1.concat(m2),h2=H3(m2),WX=H3(W1),YX=H3(H4),r0=RZ(WX,0),ZV=k(Z5,H4),Q$=Intl.DateTimeFormat,jX="en-GB",p2=1e8,JV=p2*v0,WV=[p2,0],YV=[-p2,0],D3=275760,O3=-271821,jV=1970,TZ=1972,A1=12,zV=IZ(1868,9,8),XV=g0(XF,WeakMap),k6="smallestUnit",X7="unit",B3="roundingIncrement",e8="fractionalSecondDigits",zX="relativeTo",XX={constrain:0,reject:1},QV=Object.keys(XX),GV={compatible:0,reject:1,earlier:2,later:3},KV={reject:0,use:1,prefer:2,ignore:3},BV={auto:0,never:1,critical:2,always:3},FV={auto:0,never:1,critical:2},VV={auto:0,never:1},UV={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},E3=k(S7,k6),c2=k(S7,"largestUnit"),DV=k(S7,X7),QX=k(f$,"overflow",XX),GX=k(f$,"disambiguation",GV),OV=k(f$,"offset",KV),d2=k(f$,"calendarName",BV),LV=k(f$,"timeZoneName",FV),HV=k(f$,"offset",VV),b3=k(f$,"roundingMode",UV),fZ="PlainYearMonth",kZ="PlainMonthDay",h$="PlainDate",p$="PlainDateTime",M4="PlainTime",q1="ZonedDateTime",P4="Instant",T4="Duration",MV=[Math.floor,($)=>M6($)?Math.floor($):Math.round($),Math.ceil,($)=>M6($)?Math.ceil($):Math.round($),Math.trunc,($)=>M6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>M6($)?($=Math.trunc($)||0)+$%2:Math.round($)],c$="UTC",I6=5184000,PV=A6(1847),TV=A6(new Date().getUTCFullYear()+10),NV=/0+$/,S0=g0(VF,WeakMap),sY=4294967295,N4=g0(($)=>{let Z=X2($);return typeof Z=="object"?new BX(Z):new KX(Z||0)});class KX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[M7($,this.v)]}l(){}}class BX{constructor($){this.$=((Z)=>{function J(Q){let G=$7(Q,z,X),[B,F]=pY(G),K=Y(B),V=Y(F);return K===V?K:W(j(B,F),K,V,Q)}function W(Q,G,B,F){let K,V;for(;(F===void 0||(K=F<Q[0]?G:F>=Q[1]?B:void 0)===void 0)&&(V=Q[1]-Q[0]);){let U=Q[0]+Math.floor(V/2);Z(U)===B?Q[1]=U:Q[0]=U+1}return K}let Y=g0(Z),j=g0(UF),z=PV,X=TV;return{G(Q){let G=J(Q-86400),B=J(Q+86400),F=Q-G,K=Q-B;if(G===B)return[F];let V=J(F);return V===J(K)?[Q-V]:G>B?[F,K]:[]},V:J,l(Q,G){let B=$7(Q,z,X),[F,K]=pY(B),V=I6*G,U=G<0?()=>K>z||(z=B,0):()=>F<X||(X=B,0);for(;U();){let D=Y(F),O=Y(K);if(D!==O){let L=j(F,K);W(L,D,O);let T=L[0];if((t1(T,Q)||1)===G)return T}F+=V,K+=V}}}})(((Z)=>(J)=>{let W=L7(Z,J*lz);return A6(wj(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(D5($))*a0}getPossibleInstantsFor($){let[Z,J]=[A6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*F1+W.isoMicrosecond*m$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>i0(HZ(MZ(Y,a0),J)))}l($,Z){let[J,W]=O5($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return MZ(Y,a0)}}var u2="([+\u2212-])",_6="(?:[.,](\\d{1,9}))?",FX=`(?:(?:${u2}(\\d{6}))|(\\d{4}))-?(\\d{2})`,l2="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+_6+")?)?",i2=u2+l2,IV=FX+"-?(\\d{2})(?:[T ]"+l2+"(Z|"+i2+")?)?",VX="\\[(!?)([^\\]]*)\\]",I4=`((?:${VX}){0,9})`,_V=EZ(FX+I4),xV=EZ("(?:--)?(\\d{2})-?(\\d{2})"+I4),CV=EZ(IV+I4),AV=EZ("T?"+l2+"(?:"+i2+")?"+I4),SV=EZ(i2),EV=new RegExp(VX,"g"),bV=EZ(`${u2}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${_6}H)?(?:(\\d+)${_6}M)?(?:(\\d+)${_6}S)?)?`),RV=g0(($)=>new Q$(jX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),fV=/^(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$/,kV=g0(LF),s2=g0(($)=>new Q$(jX,{calendar:$,timeZone:c$,era:"short",year:"numeric",month:"short",day:"numeric"})),wV=/^M(\d{2})(L?)$/,qV={era:C6,eraYear:_0,year:_0,month:vY,monthCode:C6,day:vY},yV=RZ(w1,_0),vV=RZ(m,F5),nY=Object.assign({},qV,yV,vV,{offset:C6}),gV=k(zF,w1,W1),oY={dateAdd($,Z,J){let W=v(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=F0(Z,5)[0],j||z)Y=((G,B,F,K,V)=>{let[U,D,O]=G.h(B);if(F){let[L,T]=G.I(U,D);U+=F,D=f6(L,T,G.U(U)),D=n0("month",D,1,G.L(U),V)}return K&&([U,D]=G._(U,D,K)),O=n0("day",O,1,G.j(U,D),V),G.q(U,D,O)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=A0($)}return Y+=(7*X+Q)*v0,e1(p6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=fj({...$,...r0},{...Z,...r0});return J===7&&([Q,G]=Z$(G,7)),{...O0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,B,F,K,V,U)=>{let D=K-G,O=V-B,L=U-F;if(D||O){let T=Math.sign(D||O),P=Q.j(K,V),_=0;if(Math.sign(L)===-T){let A=P;[K,V]=Q._(K,V,-T),D=K-G,O=V-B,P=Q.j(K,V),_=T<0?-A:P}if(L=U-Math.min(F,P)+_,D){let[A,E]=Q.I(G,B),[S,f]=Q.I(K,V);if(O=S-A||Number(f)-Number(E),Math.sign(O)===-T){let M=T<0&&-Q.L(K);D=(K-=T)-G,O=V-f6(A,E,Q.U(K))+(M||Q.L(K))}}}return[D,O,L]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...O0,years:j,months:z,days:X}},dateFromFields($,Z){let J=v(Z),W=a8(this,$),Y=r8(this,$,W,J),j=lY(this,$,Y,W,J);return z0(e1(this.P(W,Y,j)),this.id||w)},yearMonthFromFields($,Z){let J=v(Z),W=a8(this,$),Y=r8(this,$,W,J);return S$(H7(this.P(W,Y,1)),this.id||w)},monthDayFromFields($,Z){let J=v(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,B,F;if(Y!==void 0){[X,Q]=gj(Y),F=rY($,"day");let K=this.N(X,Q,F);if(!K)throw RangeError(iY);if([G,B]=K,z!==void 0&&z!==B)throw RangeError(mz);W&&(B=n0("month",B,1,A1,1),F=n0("day",F,1,P7(j!==void 0?j:G,B),J))}else{G=j===void 0&&W?TZ:a8(this,$),B=r8(this,$,G,J),F=lY(this,$,B,G,J);let K=this.U(G);Q=B===K,X=J7(B,K);let V=this.N(X,Q,F);if(!V)throw RangeError(iY);[G,B]=V}return S6(e1(this.P(G,B,F)),this.id||w)},fields($){return W7(this)&&$.includes("year")?[...$,...z7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return t8(J,Z,w2),W7(this)&&(t8(J,Z,nF),this.id===PZ&&t8(J,Z,oF,z7)),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:H2,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+o0(j)+(z?"L":""))(W,Y)},dayOfWeek:T5,daysInWeek(){return 7}},mV={dayOfYear:H2,h:H5,q:IZ},hV=Object.assign({},mV,{weekOfYear:yj,yearOfWeek:vj,R($){function Z(V){return(7-V<W?7:0)-V}function J(V){let U=P5(K+V),D=V||1,O=Z(K3(Q+U*D,7));return B=(U+(O-G)*D)/7}let W=this.id?1:4,Y=T5($),j=this.dayOfYear($),z=K3(Y-1,7),X=j-1,Q=K3(z-X,7),G=Z(Q),B,F=Math.floor((X-G)/7)+1,K=$.isoYear;return F?F>J(0)&&(F=1,K++):(F=J(-1),K--),[F,K,B]}}),pV={dayOfYear:H2,h:Z7,q:U3,weekOfYear:yj,yearOfWeek:vj,R(){return[]}},wZ=PF(Object.assign({},oY,hV,{h:H5,ee($){return this.id===L4?N5($):this.id===PZ?XV($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[TZ,$]},K:T7,U(){},L:M5,J:($)=>$*A1,j:P7,X:P5,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:IZ,_:($,Z,J)=>($+=q6(J,A1),(Z+=B7(J,A1))<1?($--,Z+=A1):Z>A1&&($++,Z-=A1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},oY,pV,{h:Z7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=P6.call(this,$);return[J7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=Z7.call(this,{isoYear:TZ,isoMonth:A1,isoDay:31}),z=P6.call(this,W),X=Y===z;(t1($,J7(Y,z))||t1(Number(Z),Number(X))||t1(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,B=P6.call(this,G),F=f6($,Z,B);if(Z===(F===B)&&J<=dY.call(this,G,F))return[G,F]}},K($){let Z=T6.call(this,$);return Z>T6.call(this,$-1)&&Z>T6.call(this,$+1)},U:P6,L:N6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=N6.call(this,z+Y);return j},j:dY,X:T6,P($,Z,J){return p6(U3.call(this,$,Z,J))},q:U3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(F4);if(J<0)for(;Z<1;)Z+=N6.call(this,--$);else{let W;for(;Z>(W=N6.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}})),$$="numeric",qZ=["timeZoneName"],UX={month:$$,day:$$},n2={year:$$,month:$$},o2=Object.assign({},n2,{day:$$}),a2={hour:$$,minute:$$,second:$$},r2=Object.assign({},o2,a2),cV=Object.assign({},r2,{timeZoneName:"short"}),dV=Object.keys(n2),uV=Object.keys(UX),lV=Object.keys(o2),iV=Object.keys(a2),t2=["dateStyle"],sV=dV.concat(t2),nV=uV.concat(t2),e2=lV.concat(t2,["weekday"]),R3=iV.concat(["dayPeriod","timeStyle"]),$9=e2.concat(R3),oV=$9.concat(qZ),aV=qZ.concat(R3),rV=qZ.concat(e2),tV=qZ.concat(["day","weekday"],R3),eV=qZ.concat(["year","weekday"],R3),$U={},Z9=[g$($9,r2),i6],DX=[g$(oV,cV),i6,0,($,Z)=>{let J=D0($.timeZone);if(Z&&D0(Z.timeZone)!==J)throw RangeError(pz);return J}],J9=[g$($9,r2,qZ),A0],W9=[g$(e2,o2,aV),A0],Y9=[g$(R3,a2,rV),($)=>J$($)/F1],j9=[g$(sV,n2,tV),A0,1],z9=[g$(nV,UX,eV),A0,1],aY;function D1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(R2);MX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...B){return Q.call(this,X(this),...B)},Q7(G))}function X(Q){let G=P0(Q);if(!G||G.branding!==$)throw TypeError(R2);return G}return Object.defineProperties(j.prototype,{...tY(t0(z,J)),...b$(t0(z,W)),...w6("Temporal."+$)}),Object.defineProperties(j,{...b$(Y),...Q7($)}),[j,(Q)=>{let G=Object.create(j.prototype);return MX(G,Q),G},X]}function NX($){return $=$.concat("id").sort(),(Z)=>{if(!eY(Z,$))throw TypeError(hz);return Z}}function mZ($){if(P0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(yz);return $}function _4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=P0(j)||{},{branding:X}=z,Q=X===h$||Z.includes(X)?z:R0(j);return Y[W](Q)};return J}function G9($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?wZ(j):(z=j,Object.assign(Object.create(OU),{i:z})))[J](W);var j,z};return Z}function V$(){throw TypeError(gz)}function k3({calendar:$}){return typeof $=="string"?new H9($):$}function OX($,Z){if(Z=Y0(Z),V0($)){let W=P0($);if(W&&W.branding===kZ)return v(Z),W;let Y=xX($);return T2(R4(Y||w),!Y,$,Z)}let J=Qj(wZ,$);return v(Z),J}function IX($,Z,J){return W=Z.call($,b0(U0(J))),c7(M3(W));var W}function x4($,Z=EX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=k(Z[Y],$,ZX($[Y]));return W}function u($,Z){return typeof $=="string"?N4($):x4($,Z)}function Q0($){return u($,Q9)}function V1($){if(V0($)){let Z=P0($);if(Z)switch(Z.branding){case P4:return Z;case q1:return U0(Z.epochNanoseconds)}}return Wj($)}function LX($,Z,J){let W=Z.l(V1(J).epochNanoseconds,$);return W?b0(U0(W)):null}function n($){return V0($)?(P0($)||{}).timeZone||NU($):((Z)=>j4(Fj(e(Z))))($)}function G$($,Z){if(V0($)){let J=P0($)||{};switch(J.branding){case M4:return v(Z),J;case p$:return v(Z),Z1(J);case q1:return v(Z),A2(Q0,J)}return lj($,Z)}return v(Z),Gj($)}function K9($){return $===void 0?void 0:G$($)}function yZ($,Z){if(Z=Y0(Z),V0($)){let W=P0($);return W&&W.branding===fZ?(v(Z),W):P2(E4(w3($)),$,Z)}let J=Xj(wZ,$);return v(Z),J}function K$($,Z){if(Z=Y0(Z),V0($)){let W=P0($)||{};switch(W.branding){case p$:return v(Z),W;case h$:return v(Z),j0({...W,...r0});case q1:return v(Z),x2(Q0,W)}return uj(b4(w3($)),$,Z)}let J=zj($);return v(Z),J}function R0($,Z){if(Z=Y0(Z),V0($)){let W=P0($)||{};switch(W.branding){case h$:return v(Z),W;case p$:return v(Z),z0(W);case q1:return v(Z),C2(Q0,W)}return M2(b4(w3($)),$,Z)}let J=W4($);return v(Z),J}function _X($,Z,J){return e0(Z.call($,Z0(z0(J,$))))}function O1($){return(Z)=>typeof Z=="string"?wZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=k(W[z],J,J[z]);return j})(Z,$)}function $0($){if(V0($)){let Z=P0($);return Z&&Z.branding===T4?Z:ij($)}return Kj($)}function f3($){if($!==void 0){if(V0($)){let Z=P0($)||{};switch(Z.branding){case q1:case h$:return Z;case p$:return z0(Z)}let J=w3($);return{...cj(n,u,b4(J),$),calendar:J}}return Yj($)}}function w3($){return xX($)||w}function xX($){let{calendar:Z}=$;if(Z!==void 0)return M0(Z)}function M0($){return V0($)?(P0($)||{}).calendar||vU($):((Z)=>N3(Bj(e(Z))))($)}function vZ($,Z){if(Z=Y0(Z),V0($)){let J=P0($);if(J&&J.branding===q1)return P3(Z),J;let W=w3($);return dj(n,u,b4(W),W,$,Z)}return jj($,Z)}function HX($){return t0((Z)=>(J)=>Z(X9(J)),$)}function X9($){return S0($,Q0)}function ZU(){let $=Q$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(Q$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);M9.set(this,((z,X={})=>{let Q=new Q$(z,X),G=Q.resolvedOptions(),B=G.locale,F=h0(Object.keys(X),G),K=g0(YU),V=(...U)=>{let D,O=U.map((L,T)=>{let P=P0(L),_=(P||{}).branding;if(T&&D&&D!==_)throw TypeError(dz);return D=_,P});return D?K(D)(B,F,...O):[Q,...U]};return V.u=Q,V})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&JU(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||WU(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function JU($){return function(...Z){let J=M9.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function WU($){return function(...Z){return M9.get(this).u[$](...Z)}}function YU($){let Z=jU[$];if(!Z)throw TypeError(cz($));return f1(Z,g0(S2))}var jU={Instant:Z9,PlainDateTime:J9,PlainDate:W9,PlainTime:Y9,PlainYearMonth:j9,PlainMonthDay:z9},zU=f1(Z9),XU=f1(DX),QU=f1(J9),GU=f1(W9),KU=f1(Y9),BU=f1(j9),FU=f1(z9),B9={era:z5,eraYear:F7,year:M3,month:e0,daysInMonth:e0,daysInYear:e0,inLeapYear:$X,monthsInYear:e0},A4={monthCode:e},F9={day:e0},CX={dayOfWeek:e0,dayOfYear:e0,weekOfYear:X5,yearOfWeek:F7,daysInWeek:e0},AX=Object.assign({},B9,A4,F9,CX),C4=new WeakMap,P0=C4.get.bind(C4),MX=C4.set.bind(C4),VU={..._4(B9,[fZ]),..._4(CX,[]),..._4(A4,[fZ,kZ]),..._4(F9,[kZ])},V9=G9(AX),UU=G9({...B9,...A4}),DU=G9({...A4,...F9}),q3={calendarId:($)=>D0($.calendar)},OU=t0(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Z0(z0(J,W))))},AX),LU=L3(($)=>(Z)=>Z[$],m.concat("sign")),U9=L3(($,Z)=>(J)=>J[W1[Z]],w1),SX={epochSeconds:E5,epochMilliseconds:i6,epochMicroseconds:b5,epochNanoseconds:R5},y3=k(G7,new Set(["branding"])),[HU,gZ,MU]=D1(kZ,k(zz,M0),{...q3,...DU},{getISOFields:y3,getCalendar:k3,with($,Z,J){return gZ(rj(wU,$,this,mZ(Z),J))},equals:($,Z)=>Cj($,OX(Z)),toPlainDate($,Z){return Z0(Pz(v3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=FU(Z,J,$);return W.format(Y)},toString:v7,toJSON:($)=>v7($),valueOf:V$},{from:($,Z)=>gZ(OX($,Z))}),EX={getOffsetNanosecondsFor:IX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,H0(j0(J,w)))].map((j)=>TU(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(C0),d7(l0(u0(W[0],W[Y-1])))),W}},Q9={getOffsetNanosecondsFor:IX},[PU,b0,TU]=D1(P4,Zz,SX,{add:($,Z)=>b0(u7(0,$,$0(Z))),subtract:($,Z)=>b0(u7(1,$,$0(Z))),until:($,Z,J)=>l(B2(0,$,V1(Z),J)),since:($,Z,J)=>l(B2(1,$,V1(Z),J)),round:($,Z)=>b0(w5($,Z)),equals:($,Z)=>Tj($,V1(Z)),toZonedDateTime($,Z){let J=b1(Z);return X0(_2($,n(J.timeZone),M0(J.calendar)))},toZonedDateTimeISO:($,Z)=>X0(_2($,n(Z))),toLocaleString($,Z,J){let[W,Y]=zU(Z,J,$);return W.format(Y)},toString:($,Z)=>f7(n,Q0,$,Z),toJSON:($)=>f7(n,Q0,$),valueOf:V$},{from:($)=>b0(V1($)),fromEpochSeconds:($)=>b0(Iz($)),fromEpochMilliseconds:($)=>b0(_z($)),fromEpochMicroseconds:($)=>b0(xz($)),fromEpochNanoseconds:($)=>b0(Cz($)),compare:($,Z)=>Q2(V1($),V1(Z))}),[S4,uP]=D1("TimeZone",($)=>{let Z=Mj($);return{branding:"TimeZone",id:Z,o:N4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(K$(Z)).map((J)=>b0(U0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(V1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=V1(Z).epochNanoseconds,W=x4(this,Q9).getOffsetNanosecondsFor(J);return k$(W)},getPlainDateTimeFor($,Z,J=w){let W=V1(Z).epochNanoseconds,Y=x4(this,Q9).getOffsetNanosecondsFor(W);return H0(j0(Y$(W,Y),M0(J)))},getInstantFor($,Z,J){let W=K$(Z),Y=N7(J),j=x4(this);return b0(U0(m0(j,W,Y)))},getNextTransition:({o:$},Z)=>LX(1,$,Z),getPreviousTransition:({o:$},Z)=>LX(-1,$,Z),equals($,Z){return!!X4(this,n(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=n($);return typeof Z=="string"?new S4(Z):Z}}),NU=NX(Object.keys(EX)),[IU,B$]=D1(M4,Xz,U9,{getISOFields:y3,with($,Z,J){return B$(tj(this,mZ(Z),J))},add:($,Z)=>B$(o7(0,$,$0(Z))),subtract:($,Z)=>B$(o7(1,$,$0(Z))),until:($,Z,J)=>l(O2(0,$,G$(Z),J)),since:($,Z,J)=>l(O2(1,$,G$(Z),J)),round:($,Z)=>B$(v5($,Z)),equals:($,Z)=>Aj($,G$(Z)),toZonedDateTime:($,Z)=>X0(Tz(n,R0,u,$,Z)),toPlainDateTime:($,Z)=>H0(Nz($,R0(Z))),toLocaleString($,Z,J){let[W,Y]=KU(Z,J,$);return W.format(Y)},toString:g7,toJSON:($)=>g7($),valueOf:V$},{from:($,Z)=>B$(G$($,Z)),compare:($,Z)=>z4(G$($),G$(Z))}),[_U,F$,xU]=D1(fZ,k(jz,M0),{...q3,...UU},{getISOFields:y3,getCalendar:k3,with($,Z,J){return F$(aj(kU,$,this,mZ(Z),J))},add:($,Z,J)=>F$(n7(PX,0,$,$0(Z),J)),subtract:($,Z,J)=>F$(n7(PX,1,$,$0(Z),J)),until:($,Z,J)=>l(D2(TX,0,$,yZ(Z),J)),since:($,Z,J)=>l(D2(TX,1,$,yZ(Z),J)),equals:($,Z)=>xj($,yZ(Z)),toPlainDate($,Z){return Z0(Mz(v3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=BU(Z,J,$);return W.format(Y)},toString:y7,toJSON:($)=>y7($),valueOf:V$},{from:($,Z)=>F$(yZ($,Z)),compare:($,Z)=>y$(yZ($),yZ(Z))}),[CU,H0]=D1(p$,k(Wz,M0),{...q3,...V9,...U9},{getISOFields:y3,getCalendar:k3,with($,Z,J){return H0(nj(v3,$,this,mZ(Z),J))},withCalendar:($,Z)=>H0(B4($,M0(Z))),withPlainDate:($,Z)=>H0(bz($,R0(Z))),withPlainTime:($,Z)=>H0(Ez($,K9(Z))),add:($,Z,J)=>H0(i7(d$,0,$,$0(Z),J)),subtract:($,Z,J)=>H0(i7(d$,1,$,$0(Z),J)),until:($,Z,J)=>l(V2(U1,0,$,K$(Z),J)),since:($,Z,J)=>l(V2(U1,1,$,K$(Z),J)),round:($,Z)=>H0(y5($,Z)),equals:($,Z)=>Ij($,K$(Z)),toZonedDateTime:($,Z,J)=>X0(Fz(u,$,n(Z),J)),toPlainDate:($)=>Z0(z0($)),toPlainTime:($)=>B$(Z1($)),toPlainYearMonth($){return F$(Vz(E4,$,this))},toPlainMonthDay($){return gZ(Uz(R4,$,this))},toLocaleString($,Z,J){let[W,Y]=QU(Z,J,$);return W.format(Y)},toString:w7,toJSON:($)=>w7($),valueOf:V$},{from:($,Z)=>H0(K$($,Z)),compare:($,Z)=>K2(K$($),K$(Z))}),[AU,Z0,bX]=D1(h$,k(Yz,M0),{...q3,...V9},{getISOFields:y3,getCalendar:k3,with($,Z,J){return Z0(oj(v3,$,this,mZ(Z),J))},withCalendar:($,Z)=>Z0(B4($,M0(Z))),add:($,Z,J)=>Z0(s7(d$,0,$,$0(Z),J)),subtract:($,Z,J)=>Z0(s7(d$,1,$,$0(Z),J)),until:($,Z,J)=>l(U2(U1,0,$,R0(Z),J)),since:($,Z,J)=>l(U2(U1,1,$,R0(Z),J)),equals:($,Z)=>_j($,R0(Z)),toZonedDateTime($,Z){let J=!V0(Z)||Z instanceof S4?{timeZone:Z}:Z;return X0(Dz(n,G$,u,$,J))},toPlainDateTime:($,Z)=>H0(Oz($,K9(Z))),toPlainYearMonth($){return F$(Lz(E4,$,this))},toPlainMonthDay($){return gZ(Hz(R4,$,this))},toLocaleString($,Z,J){let[W,Y]=GU(Z,J,$);return W.format(Y)},toString:q7,toJSON:($)=>q7($),valueOf:V$},{from:($,Z)=>Z0(R0($,Z)),compare:($,Z)=>y$(R0($),R0(Z))}),D9={fields($,Z,J){return[...Z.call($,J)]}},RX=Object.assign({dateFromFields($,Z,J,W){return bX(Z.call($,Object.assign(Object.create(null),J),W))}},D9),fX=Object.assign({yearMonthFromFields($,Z,J,W){return xU(Z.call($,Object.assign(Object.create(null),J),W))}},D9),kX=Object.assign({monthDayFromFields($,Z,J,W){return MU(Z.call($,Object.assign(Object.create(null),J),W))}},D9),O9={mergeFields($,Z,J,W){return b1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},SU=Object.assign({},RX,O9),EU=Object.assign({},fX,O9),bU=Object.assign({},kX,O9),L9={dateAdd($,Z,J,W,Y){return bX(Z.call($,Z0(z0(J,$)),l(a(W)),Y))}},wX=Object.assign({},L9,{dateUntil($,Z,J,W,Y,j){return yU(Z.call($,Z0(z0(J,$)),Z0(z0(W,$)),Object.assign(Object.create(null),j,{largestUnit:A3[Y]})))}}),RU=Object.assign({},L9,{day:_X}),fU=Object.assign({},wX,{day:_X}),E4=O1(fX),b4=O1(RX),R4=O1(kX),kU=O1(EU),v3=O1(SU),wU=O1(bU),d$=O1(L9),U1=O1(wX),PX=O1(RU),TX=O1(fU),[qU,l,yU]=D1(T4,Qz,{...LU,blank:$j},{with:($,Z)=>l(ej($,Z)),negated:($)=>l(Z4($)),abs:($)=>l(e5($)),add:($,Z,J)=>l($2(f3,U1,u,0,$,$0(Z),J)),subtract:($,Z,J)=>l($2(f3,U1,u,1,$,$0(Z),J)),round:($,Z)=>l(t5(f3,U1,u,$,Z)),total:($,Z)=>k5(f3,U1,u,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):a6($)},toString:a6,toJSON:($)=>a6($),valueOf:V$},{from:($)=>l($0($)),compare:($,Z,J)=>Pj(f3,d$,u,$0($),$0(Z),J)}),qX={toString:($)=>$.id,toJSON:($)=>$.id,...VU,dateAdd:({id:$,o:Z},J,W,Y)=>Z0(z0(Z.dateAdd(R0(J),$0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>l(a($.dateUntil(R0(Z),R0(J),_5(W)))),dateFromFields:({id:$,o:Z},J,W)=>Z0(M2(Z,J,W,j5($))),yearMonthFromFields:({id:$,o:Z},J,W)=>F$(P2(Z,J,W,W5($))),monthDayFromFields:({id:$,o:Z},J,W)=>gZ(T2(Z,0,J,W,Y5($))),fields({o:$},Z){let J=new Set(J1),W=[];for(let Y of Z){if(e(Y),!J.has(Y))throw RangeError(b2(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(K7(V7(Z)),K7(V7(J)))},[H9]=D1("Calendar",($)=>{let Z=qj($);return{branding:"Calendar",id:Z,o:wZ(Z)}},{id:($)=>$.id},qX,{from($){let Z=M0($);return typeof Z=="string"?new H9(Z):Z}}),vU=NX(Object.keys(qX).slice(4)),[gU,X0]=D1(q1,k(Jz,M0,n),{...SX,...q3,...HX(V9),...HX(U9),offset:($)=>k$(X9($).offsetNanoseconds),offsetNanoseconds:($)=>X9($).offsetNanoseconds,timeZoneId:($)=>D0($.timeZone),hoursInDay:($)=>g5(u,$)},{getISOFields:($)=>a5(Q0,$),getCalendar:k3,getTimeZone:({timeZone:$})=>typeof $=="string"?new S4($):$,with($,Z,J){return X0(sj(v3,u,$,this,mZ(Z),J))},withCalendar:($,Z)=>X0(B4($,M0(Z))),withTimeZone:($,Z)=>X0(Rz($,n(Z))),withPlainDate:($,Z)=>X0(Sz(u,$,R0(Z))),withPlainTime:($,Z)=>X0(Az(u,$,K9(Z))),add:($,Z,J)=>X0(l7(d$,u,0,$,$0(Z),J)),subtract:($,Z,J)=>X0(l7(d$,u,1,$,$0(Z),J)),until:($,Z,J)=>l(a(F2(U1,u,0,$,vZ(Z),J))),since:($,Z,J)=>l(a(F2(U1,u,1,$,vZ(Z),J))),round:($,Z)=>X0(q5(u,$,Z)),startOfDay:($)=>X0(m5(u,$)),equals:($,Z)=>Nj($,vZ(Z)),toInstant:($)=>b0(Gz($)),toPlainDateTime:($)=>H0(x2(Q0,$)),toPlainDate:($)=>Z0(C2(Q0,$)),toPlainTime:($)=>B$(A2(Q0,$)),toPlainYearMonth($){return F$(Kz(E4,$,this))},toPlainMonthDay($){return gZ(Bz(R4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=XU(Z,J,$);return W.format(Y)},toString:($,Z)=>k7(Q0,$,Z),toJSON:($)=>k7(Q0,$),valueOf:V$},{from:($,Z)=>X0(vZ($,Z)),compare:($,Z)=>G2(vZ($),vZ(Z))}),mU=Object.defineProperties({},{...w6("Temporal.Now"),...b$({timeZoneId:()=>k1(),instant:()=>b0(U0(_3())),zonedDateTime:($,Z=k1())=>X0(L0(_3(),n(Z),M0($))),zonedDateTimeISO:($=k1())=>X0(L0(_3(),n($),w)),plainDateTime:($,Z=k1())=>H0(j0(bZ(Q0(n(Z))),M0($))),plainDateTimeISO:($=k1())=>H0(j0(bZ(Q0(n($))),w)),plainDate:($,Z=k1())=>Z0(z0(bZ(Q0(n(Z))),M0($))),plainDateISO:($=k1())=>Z0(z0(bZ(Q0(n($))),w)),plainTimeISO:($=k1())=>B$(Z1(bZ(Q0(n($)))))})}),hZ=Object.defineProperties({},{...w6("Temporal"),...b$({PlainYearMonth:_U,PlainMonthDay:HU,PlainDate:AU,PlainTime:IU,PlainDateTime:CU,ZonedDateTime:gU,Instant:PU,Calendar:H9,TimeZone:S4,Duration:qU,Now:mU})}),hU=ZU(),M9=new WeakMap,pU=Object.defineProperties(Object.create(Intl),b$({DateTimeFormat:hU}));var f4="x-gemi-socket";var aP="gemi.v1",yX="/__gemi/socket",rP=/^[A-Za-z0-9_-]{1,32}$/,tP={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function JT($){return $}function vX(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:yX,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 cU,randomBytes as dU}from"crypto";function uU($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(cU("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var lU="__control",P9=250,iU=1e4,sU=15000;class T9{config;prefix;controlChannel;instanceId=dU(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??uU(),this.controlChannel=this.prefix+lU,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=g3((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 $})(),sU,"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 (${gX(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(iU,P9*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(P9,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;g3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${gX(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??nU(Math.min(Z,P9));await g3(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 Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await g3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await g3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}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 g3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function nU($){return new Promise((Z)=>setTimeout(Z,$))}function gX($){return $ instanceof Error?$.message:String($)}import{createHmac as oU,hkdfSync as aU,randomBytes as mX}from"crypto";function hX($){return oU("sha256",rU()).update($).digest("base64url").slice(0,22)}var k4=null;function rU(){let $=process.env.SECRET||void 0;if(k4&&k4.secret===$)return k4.key;let Z=$?Buffer.from(aU("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):mX(32);return k4={secret:$,key:Z},Z}function XT(){return mX(16).toString("base64url")}var tU=/^[A-Za-z0-9_-]{8,64}$/;function N9($){return typeof $==="string"&&tU.test($)}function pX($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class dX 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 p0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=L1(vX(),$),this.driver=ZD(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 m3(this,w4($,Z[0]),null)}toUser($){return new m3(this,{topic:XZ($),pattern:K0},null)}toOthers($){return new uX(this,$D($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(w4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){VW(Z);let Y;try{Y=pX($.topic,Z,J,W?hX(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){pZ(()=>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=eU($);pZ(()=>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 dX(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 m3{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 uX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new m3(this.manager,w4($,Z[0]),this.except)}toUser($){return new m3(this.manager,{topic:XZ($),pattern:K0},this.except)}}function w4($,Z){if(FW($))return{topic:L8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:Y3($,Z??{}),pattern:$};if($===K0)throw new p('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:L8($)}}function eU($){if($&&typeof $==="object"&&"user"in $)return{user:XZ($.user).slice(K0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:w4($.channel,$.params).topic};throw new p("Broadcast.revoke takes { user } or { channel }.")}function $D($){if($===null||$===void 0)return null;if(typeof $==="string")return N9($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(f4);return N9(J)?J:null}function ZD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new cX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new T9({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.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 I9 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class JD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as _9,createHmac as WD,randomBytes as lX,timingSafeEqual as nX}from"crypto";var p3=600,q4="gemi_oauth",YD=`__Host-${q4}`;function cZ($,Z=q4){if(Z===q4)return $?YD:q4;return $?`__Host-${Z}`:Z}function h3($){return $.toString("base64url")}function oX($){return WD("sha256",FZ()).update(`gemi-oauth-state:${$}`).digest()}function iX($,Z){let J=_9("sha256").update($).digest(),W=_9("sha256").update(Z).digest();return nX(J,W)&&$.length===Z.length}function y4($,Z=Date.now(),J={}){let W=h3(lX(32)),Y=h3(lX(32)),j=jD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+p3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:zD(z)}}function jD($){return h3(_9("sha256").update($).digest())}function zD($){let Z=h3(Buffer.from(JSON.stringify($)));return`${Z}.${h3(oX(Z))}`}function XD($){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"),Y=oX(J);if(W.length!==Y.length||!nX(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string")return null;return j}catch{return null}}var U$=new Map,sX=1e4;function QD($,Z,J){if(U$.size>=sX){for(let[W,Y]of U$)if(Y<=J)U$.delete(W);while(U$.size>=sX){let W=U$.keys().next().value;if(W===void 0)break;U$.delete(W)}}U$.set($,Z)}function v4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=XD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=iX(J.state,$.returnedState),Y=iX(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(U$.has(J.state))return{ok:!1,reason:"invalid_state"};return QD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var x9=new WeakMap;function KD($){let Z=x9.get($);if(!Z)Z=$(GD(32).toString("hex")),x9.set($,Z),Z.catch(()=>x9.delete($));return Z}async function C9($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await KD($.hashPassword))}catch{}return!1}async function u$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class S9 extends Error{}function A9($){return typeof $==="string"&&$!==""?$:null}function aX($){return X3($)}var BD=256;function rX($){return typeof $==="string"&&$!==""&&$.length<=BD?$:null}function tX($){let{password:Z,code:J,...W}=$;return W}var g4="intended_url";function $Q($){if($.cookies.get(g4))$.ctx().setCookie(g4,"",{maxAge:-1})}function eX($){let Z=$.cookies.get(g4);if(!Z)return null;$Q($);try{return X1(decodeURIComponent(Z),"")||null}catch{return null}}class E9 extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class ZQ extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class JQ extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function y1($){if(H(b).config[$]===!1)throw new J0("Not found",{status:404})}class r extends z3{async me(){let $=await w0.user();if(!$)throw new q8;return $}async verifyEmail($=new C){y1("password");let Z=await $.input(),{userProvider:J}=H(b),W=A9(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=H(b),{userProvider:J}=Z,W=A9($.search.get("token")),Y=null;try{Y=X3(decodeURIComponent($.search.get("email")??""))}catch{}if(await UZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,H(b).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await u$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){y1("magicLink");let Z=H(b),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=X3(W),z=rX(Y);if(await UZ("verify",j,$,Z.config.emailCode.verifyLimit),!j||!z)throw new h({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(X.status!=="ok")throw new h({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=H(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,H(b).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await u$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=H(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,H(b).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await u$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new E9){y1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await C9(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,H(b).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await u$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signIn($=new E9){y1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await C9(j.config,W,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,H(b).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await u$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signUp(){y1("password");let $=H(b),{userProvider:Z,config:J}=$,W=new J.signUpRequest,Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G={method:"password",input:tX(Y.toJSON())},B=aX(j);if(!B)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new h({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(B,!1))throw new h({email:["Email address already exists"]});let K=await J.hashPassword(z),V=H(d).detectLocale(W),U;if(Q)U=await Z.findInvitation(Q,B);let D,O="";if(U)D=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let L=await Z.createUser({email:B,name:X,password:K,emailVerifiedAt:new Date,locale:V});return await Z.createAccount({organizationId:U.organizationId,userId:L.id,organizationRole:U.role}),await J.onUserCreated(L,G),L});else O=await J.generateEmailVerificationToken(B),D=await Z.transaction(async()=>{let L=await Z.createUser({email:B,name:X,password:K,verificationToken:O,locale:V});return await J.onUserCreated(L,G),L});return await J.onSignUp(D,O,W.search.toJSON()),D}async signOut($=new C){let Z=T$($),J=H(b),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(b).accessTokenCookieOptions($,new Date(0))),H(b).cookieDomain($))$.ctx().setCookie("access_token","",{...H(b).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)FD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user);return{}}async forgotPassword($=new ZQ){y1("password");let Z=await $.input(),J=aX(Z.get("email"));if(!J)return{};let{userProvider:W,config:Y}=H(b),j=await W.findUserByEmailAddress(J,Y.verifyEmail);if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z),{}}async resetPassword($=new JQ){y1("password");let{userProvider:Z,config:J}=H(b),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=A9(j),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new h({token:["Invalid token"]});if(hZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(hZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new h({email:["User not found"]});let B=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:B}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new C){y1("password");let{userProvider:Z,config:J}=H(b),W=await w0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof j==="string"&&await C9(J,j,X?.password)))throw new h({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=H(b).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await DZ(J,Z);if(!Y){if(W)throw new J0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=QZ($.rawRequest),z=X1($.search.get(z1),"");if(z)$.ctx().setCookie(g4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else $Q($);let{state:X,codeChallenge:Q,cookieValue:G}=y4(Z);return $.ctx().setCookie(cZ(j),G,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:p3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=H(b),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await DZ(Y.oauthProviders,Z);if(j&&!z)throw new J0("Not found",{status:404});let X=QZ($.rawRequest),Q=cZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let B=$.search.get("error");if(B)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");let F=v4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in F)return console.error(`Authentication error: OAuth callback refused (${F.reason})`),this.oauthFailure($,F.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let K;try{K=await z.onCallback($,{state:F.payload.state,codeVerifier:F.payload.codeVerifier})}catch(M){if(M instanceof I9)return this.oauthFailure($,M.code);return console.error("Authentication error: OAuth provider callback failed",M),this.oauthFailure($,"provider_error")}let{name:V,username:U,providerId:D,emailVerified:O}=K??{},L=typeof K?.email==="string"?K.email:void 0,T=L?O6(L):null,P=D?await W.findUserBySocialAccount(Z,D):null,_="signin",A=!P&&!T&&!L&&!!D&&z.createUsersWithoutEmail===!0;if(!P&&A){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{P=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:V,username:U,locale:H(d).detectLocale($)}),_="signup"}catch(M){let I=await W.findUserBySocialAccount(Z,D);if(!I)throw M;P=I}}if(!P){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,L?"invalid_email":D?"missing_email":"no_identity");if(O===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let M=H(d).detectLocale($);try{let I=await this.linkOAuthAccount({provider:Z,providerId:D,email:T,rawEmail:L,name:V,username:U,locale:M,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(I==="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(I==="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(I)P=I.user,_=I.action}catch(I){let y=D?await W.findUserBySocialAccount(Z,D):null;if(!y)throw I;P=y}if(!P)return this.oauthFailure($,"account_conflict")}let E=await J.createOrUpdateSessionV2({email:P.email,id:P.id});if($.ctx().setCookie("access_token",E.token,H(b).accessTokenCookieOptions($,E.expiresAt)),_==="signup")await Y.onSignUp(P,"",$.search.toJSON());else await Y.onSignIn(P,$.search.toJSON());await u$(J.config,{session:E,user:P,isNewUser:_==="signup",method:"oauth",req:$});let S=eX($)??Y.redirectPath,f=Y.oauthCompleteProfilePath?X1(Y.oauthCompleteProfilePath,""):"";if(f&&!P.email){let M=new URL(f,"http://gemi.invalid");M.searchParams.set(z1,S),S=`${M.pathname}${M.search}${M.hash}`}return{session:E,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=H(b);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,{method:"oauth",input:{}}),W})}oauthFailure($,Z){let J=eX($),W=H(b).config.oauthFailurePath;if(W){let Y=X1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(z1,J);N1.external(`${j.pathname}${j.search}${j.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:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=H(b),B=(U)=>({provider:Z,userId:U,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),F=await Q.findUserByEmailAddress(W,!1),K=Y?.trim();if(!F&&K&&K!==W)F=await Q.findUserByEmailAddress(K,!1);if(F){if($.linkExisting===!1)return"account_exists";if(!J)return{user:F,action:"signin"};let U=await Q.findSocialAccounts(F.id,Z);if(U.some((O)=>O.providerId===J))return{user:F,action:"signin"};if(U.some((O)=>O.providerId))return console.error(`Authentication error: user ${F.id} is already linked to a different ${Z} account`),null;let D=U[0];if(D){if(!await Q.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(B(F.id));return{user:F,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let U=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(B(U.id));return await G.onUserCreated(U,{method:"oauth",input:{}}),U}),action:"signup"}}async createMagicLinkToken($=new C){y1("magicLink");let Z=await $.input(),J=X3(Z.get("email")),W=H(b),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await UZ("request",J,$,j),!J)return{email:null};let{user:z,pin:X,token:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=H(b),J=Z.config.emailCode;if(!J.enabled)throw new J0("Not found",{status:404});let W=await $.input(),Y=O6(W.get("email"));if(await UZ("request",Y,$,J.requestLimit),!Y)throw new h({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=H(b),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new J0("Not found",{status:404});let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=O6(j),G=rX(z);if(await UZ("verify",Q,$,W.emailCode.verifyLimit),!Q||!G)throw new h({code:["invalid_code"]});let B=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(B.status==="too_many_attempts")throw new h({code:["too_many_attempts"]});if(B.status!=="ok")throw new h({code:["invalid_code"]});let F=B.row,K=await J.findUserByEmailAddress(Q,!1),V=!1;if(K){if(!await Z.claimOneTimeCode(Q,F.id))throw new h({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let D=H(d).detectLocale($);try{K=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(Q,F.id))throw new S9;let O=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await W.onUserCreated(O,{method:"email-code",input:tX(Y.toJSON())}),O}),V=!0}catch(O){if(O instanceof S9)throw new h({code:["invalid_code"]});throw O}}else throw await Z.claimOneTimeCode(Q,F.id),new h({code:["invalid_code"]});let U=await Z.createOrUpdateSessionV2({email:Q,id:K.id});return $.ctx().setCookie("access_token",U.token,H(b).accessTokenCookieOptions($,U.expiresAt)),await W.onSignIn(U,$.search.toJSON()),await u$(Z.config,{session:U,isNewUser:V,method:"email-code",req:$}),{session:U,isNewUser:V}}}function FD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=H();if(typeof J?.bound!=="function"||!J.bound(p0))return;J.make(p0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var WQ="gemi_oauth_connection";class m4 extends z3{async connect($=new C){let Z=String($.params.provider??""),W=H(c3).providers[Z],Y=await w0.user(),j=X1($.search.get(z1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=QZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=y4(YQ(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(cZ(z,WQ),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:p3}),N1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:jQ($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=H(c3),W=await w0.user(),Y=QZ($.rawRequest),j=cZ(Y,WQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=v4({provider:YQ(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let B=$.search.get("error");if(B)return this.finish(Q,Z,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let F=$.search.get("code");if(!F)return this.finish(Q,Z,"missing_code");try{let K=await G.exchangeCode({code:F,codeVerifier:X.payload.codeVerifier,redirectUri:jQ($,Z,G.config.redirectUri)}),V=await J.save(W,Z,K);await H(b).config.onConnected({user:W,provider:Z,connection:V,profile:K.profile??null,req:$})}catch(K){if(K instanceof zQ)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(Q,Z,K.providerError??K.code);throw K}return this.finish(Q,Z)}finish($,Z,J){let W=$||X1(H(b).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw N1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function YQ($){return`connection:${$}`}function jQ($,Z,J){if(J)return J;return`${l$()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function XQ($){return $.magicLink!==!1||$.emailCode?.enabled===!0}function QQ($){return Object.keys($.oauthProviders??{}).length>0}function GQ($={}){let Z=[];if(XQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:$.emailCode?.enabled===!0&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(QQ($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class KQ extends I1{middlewares=["cache:private"];routes={"/:provider":this.redirect([m4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([m4,"callback"]).middleware([X6,"auth"])}}function BQ($={}){let Z=XQ($),J=QQ($);class W extends I1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[r,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[r,"oauthCallback"])}}return class extends I1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[r,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":KQ}}}class b9 extends I0{middlewares=["cache:private"];routes={"/sign-in":this.post(r,"signIn"),"/sign-in-v2":this.post(r,"signInV2"),"/sign-up":this.post(r,"signUp"),"/sign-out":this.post(r,"signOut"),"/forgot-password":this.post(r,"forgotPassword"),"/reset-password":this.post(r,"resetPassword"),"/change-password":this.post(r,"changePassword"),"/verify-email":this.post(r,"verifyEmail"),"/me":this.get(r,"me").middleware(["auth"]),"/magic-link":this.post(r,"createMagicLinkToken"),"/sign-in-with-pin":this.post(r,"signInWithPin"),"/sign-in-with-pin-v2":this.post(r,"signInWithPinV2"),"/email-code":this.post(r,"requestEmailCode"),"/email-code/verify":this.post(r,"verifyEmailCode")}}class R9 extends I0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await H(d).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=H(d),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class f9{}class k9 extends f9{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await h4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function LN($){return $}function FQ(){return{driver:new k9,allowedHosts:[],maxSize:10485760,timeout:1e4}}class G0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var VD=new Set([301,302,303,307,308]),UD="/api/__gemi__/services/image/";async function UQ($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=VQ($,Y);try{for(let z=0;;z++){let X=await DD(j,Z,W),Q=X.headers.get("location");if(VD.has(X.status)&&Q){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new G0(502,"The image redirects too many times");j=VQ(Q,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new G0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new G0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw LD(z,W)}}function VQ($,Z){let J;try{J=new URL($,Z)}catch{throw new G0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new G0(400,"Only http(s) images can be resized");return J}async function DD($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(UD))throw new G0(403,"This image source is not allowed");if(OD($.pathname))throw new G0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return _1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new G0(403,"This image source is not allowed");return _1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function OD($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function LD($,Z){if($ instanceof G0)return $;if(Z.aborted)return new G0(504,"The image took too long to load",{cause:$});if($ instanceof G6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new G0(403,"This image source is not allowed",{cause:$});case"too-large":return new G0(413,"The image is too large",{cause:$});case"timeout":return new G0(504,"The image took too long to load",{cause:$})}return new G0(502,"The image could not be loaded",{cause:$})}class w9 extends I0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return DQ(400,"url query parameter is required");let X=H(OQ),Q=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],G=l$();if(G&&URL.canParse(G))Q.push(new URL(G).origin);let B;try{B=await UQ(J,{ownOrigins:Q,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(V){if(V instanceof G0)return DQ(V.status,V.message);throw V}let F=await X.resize(B.bytes,{height:Y,width:W,fit:j,quality:z}),K=new Headers({"Content-Type":"image/webp","Content-Length":`${F.byteLength}`});if(B.cacheControl)K.set("Cache-Control",B.cacheControl);return new Response(new Uint8Array(F),{headers:K})})}}function DQ($,Z){return Response.json({error:Z},{status:$})}class OQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=FQ();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class q9 extends I0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(LQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function fN($){return $}function HQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function MQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function HD($){return"run"in $}function MD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function PD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function TD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function ND($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function PQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function ID($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function y9($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let B=j==="/"?"":j,F=Z==="/"?"":Z,K=ID((`${F}${B}`===""?"/":`${F}${B}`).replaceAll("//","/"));if(!W[K])W[K]={};W[K][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[K].OPTIONS={exec:()=>{let U=new C().ctx().headers;return new Response(null,{headers:U,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(ND(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(HD(z)){let X=z,Q=X.method,G=X.middlewares,B=X.run.bind(X);if(Y(j,Q,B,G,X.source),PQ(z))Y(j,"HEAD",B,G,X.source)}if(MD(z))for(let[X,Q]of Object.entries(z)){let G=Q,B=G.middlewares,F=G.run.bind(G);if(Y(j,X,F,B,G.source),X==="get"&&PQ(G))Y(j,"HEAD",F,B,G.source)}if(TD(z)){let X=new z,Q=y9(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[G,B]of Object.entries(Q)){let F=G.replaceAll("//","/");W[F]={...W[F],...B}}}if(PD(z)){let{first:X,second:Q}=z;for(let[G,B]of Object.entries(X)){let F=B.middlewares,K=B.run.bind(B),[V,...U]=j.split("/").reverse();if(!V.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(U.reverse().join("/"),G,K,F,B.source)}for(let[G,B]of Object.entries(Q)){let F=B.middlewares,K=B.run.bind(B);Y(j,G,K,F,B.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function p4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function v9($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function g9($){let Z=p4($);return Z.length>1?Z.replace(/\/$/,""):Z}function TQ($,Z){return Z.map((J)=>({...J,path:g9(v9($,J.path))}))}function c4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=c4(j.routes);for(let[X,{exec:Q,middleware:G,segments:B,features:F,static:K}]of Object.entries(z)){let V=v9(J,X),U=(D)=>Y.run.call(Y,D,J);Z[p4(V)]={exec:[U,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...F],viewPath:Y.viewPath,segments:[{path:g9(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...TQ(J,B)],...K?{static:K}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[p4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:g9(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=c4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:B,features:F,static:K}]of Object.entries(j)){let V=v9(J,z);Z[p4(V)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...F],viewPath:G,segments:TQ(J,B),...K?{static:K}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var m9="theme";function NQ($){return $==="light"||$==="dark"||$==="system"}function IQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
14
14
  for(i=0;i<k.length;i++){j=k[i].indexOf('=');if(j>0&&k[i].slice(0,j).trim()===o.cookie){v=decodeURIComponent(k[i].slice(j+1).trim());break}}
15
15
  if(v!=='light'&&v!=='dark'&&v!=='system'){try{v=localStorage.getItem('theme')}catch(x){}}
16
16
  if(v==='light'||v==='dark'||v==='system')e=v;else e=o.default;
17
17
  if(!e)return;
18
18
  if(e==='system')e=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
19
- c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}var _D=Object.defineProperty,x=($,Z)=>_D($,"name",{value:Z,configurable:!0}),lZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};x(lZ,"Part");var xD=/[$_\p{ID_Start}]/u,CD=/[$_\u200C\u200D\p{ID_Continue}]/u,p9=".*";function _Q($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}x(_Q,"isASCII");function u9($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=x(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let Q=$.substr(X,1);if(X===W+1&&xD.test(Q)||X!==W+1&&CD.test(Q)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",Q=W+1,G=!1;if($[Q]==="?"){j(`Pattern cannot start with "?" at ${Q}`);continue}for(;Q<$.length;){if(!_Q($[Q],!1)){j(`Invalid character '${$[Q]}' at ${Q}.`),G=!0;break}if($[Q]==="\\"){X+=$[Q++]+$[Q++];continue}if($[Q]===")"){if(z--,z===0){Q++;break}}else if($[Q]==="("&&(z++,$[Q+1]!=="?")){j(`Capturing groups are not allowed at ${Q}`),G=!0;break}X+=$[Q++]}if(G)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=Q;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}x(u9,"lexer");function l9($,Z={}){let J=u9($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${c0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",Q=new Set,G=x((P)=>{if(z<J.length&&J[z].type===P)return J[z++].value},"tryConsume"),K=x(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),F=x((P)=>{let _=G(P);if(_!==void 0)return _;let{type:A,index:E}=J[z];throw TypeError(`Unexpected ${A} at ${E}, expected ${P}`)},"mustConsume"),B=x(()=>{let P="",_;for(;_=G("CHAR")??G("ESCAPED_CHAR");)P+=_;return P},"consumeText"),U=x((P)=>P,"DefaultEncodePart"),V=Z.encodePart||U,D="",O=x((P)=>{D+=P},"appendToPendingFixedValue"),L=x(()=>{D.length&&(Y.push(new lZ(3,"","",V(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),T=x((P,_,A,E,S)=>{let f=3;switch(S){case"?":f=1;break;case"*":f=0;break;case"+":f=2;break}if(!_&&!A&&f===3){O(P);return}if(L(),!_&&!A){if(!P)return;Y.push(new lZ(3,"","",V(P),"",f));return}let M;A?A==="*"?M=p9:M=A:M=W;let I=2;M===W?(I=1,M=""):M===p9&&(I=0,M="");let y;if(_?y=_:A&&(y=j++),Q.has(y))throw TypeError(`Duplicate name '${y}'.`);Q.add(y),Y.push(new lZ(I,y,V(P),M,V(E),f))},"addPart");for(;z<J.length;){let P=G("CHAR"),_=G("NAME"),A=G("REGEX");if(!_&&!A&&(A=G("ASTERISK")),_||A){let S=P??"";Z.prefixes.indexOf(S)===-1&&(O(S),S=""),L();let f=K();T(S,_,A,"",f);continue}let E=P??G("ESCAPED_CHAR");if(E){O(E);continue}if(G("OPEN")){let S=B(),f=G("NAME"),M=G("REGEX");!f&&!M&&(M=G("ASTERISK"));let I=B();F("CLOSE");let y=K();T(S,f,M,I,y);continue}L(),F("END")}return Y}x(l9,"parse");function c0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(c0,"escapeString");function c9($){return $&&$.ignoreCase?"ui":"u"}x(c9,"flags");function xQ($,Z,J){return i9(l9($,J),Z,J)}x(xQ,"stringToRegexp");function i$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}x(i$,"modifierToString");function i9($,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+=c0(X.value):W+=`(?:${c0(X.value)})${i$(X.modifier)}`;continue}Z&&Z.push(X.name);let Q=`[^${c0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=Q:X.type===0&&(G=p9),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${G})${i$(X.modifier)}`:W+=`((?:${G})${i$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${c0(X.prefix)}(${G})${c0(X.suffix)})`,W+=i$(X.modifier);continue}W+=`(?:${c0(X.prefix)}`,W+=`((?:${G})(?:`,W+=c0(X.suffix),W+=c0(X.prefix),W+=`(?:${G}))*)${c0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${c0(J.endsWith)}]|$`,j=`[${c0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,c9(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,c9(J))}x(i9,"partsToRegexp");var O$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},AD={delimiter:".",prefixes:"",sensitive:!0,strict:!0},SD={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function CQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}x(CQ,"isAbsolutePathname");function s9($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}x(s9,"maybeStripPrefix");function AQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}x(AQ,"maybeStripSuffix");function n9($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}x(n9,"treatAsIPv6Hostname");var SQ=["ftp","file","http","https","ws","wss"];function o9($){if(!$)return!0;for(let Z of SQ)if($.test(Z))return!0;return!1}x(o9,"isSpecialScheme");function EQ($,Z){if($=s9($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}x(EQ,"canonicalizeHash");function bQ($,Z){if($=s9($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}x(bQ,"canonicalizeSearch");function RQ($,Z){return Z||$===""?$:n9($)?t9($):r9($)}x(RQ,"canonicalizeHostname");function fQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}x(fQ,"canonicalizePassword");function kQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}x(kQ,"canonicalizeUsername");function wQ($,Z,J){if(J||$==="")return $;if(Z&&!SQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}x(wQ,"canonicalizePathname");function qQ($,Z,J){return a9(Z)===$&&($=""),J||$===""?$:e9($)}x(qQ,"canonicalizePort");function yQ($,Z){return $=AQ($,":"),Z||$===""?$:d4($)}x(yQ,"canonicalizeProtocol");function a9($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}x(a9,"defaultPortForProtocol");function d4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}x(d4,"protocolEncodeCallback");function vQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}x(vQ,"usernameEncodeCallback");function gQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}x(gQ,"passwordEncodeCallback");function r9($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}x(r9,"hostnameEncodeCallback");function t9($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}x(t9,"ipv6HostnameEncodeCallback");function e9($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}x(e9,"portEncodeCallback");function mQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}x(mQ,"standardURLPathnameEncodeCallback");function hQ($){return $===""?$:new URL(`data:${$}`).pathname}x(hQ,"pathURLPathnameEncodeCallback");function pQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}x(pQ,"searchEncodeCallback");function cQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}x(cQ,"hashEncodeCallback");var dQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#G=0;#X=0;#V=0;#U=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=u9(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#M(),this.#K()?this.#J(9,1):this.#B()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#F(5);continue}this.#J(10,0);break}if(this.#V>0)if(this.#C())this.#V-=1;else continue;if(this.#x()){this.#V+=1;continue}switch(this.#X){case 0:this.#P()&&this.#F(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#N()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#L()?this.#F(3):(this.#H()||this.#B()||this.#K())&&this.#F(5);break;case 3:this.#I()?this.#J(4,1):this.#L()&&this.#J(5,1);break;case 4:this.#L()&&this.#J(5,1);break;case 5:this.#A()?this.#U+=1:this.#S()&&(this.#U-=1),this.#_()&&!this.#U?this.#J(6,1):this.#H()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#B()?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.#Q();break;case 2:break;case 3:this.#Z.username=this.#Q();break;case 4:this.#Z.password=this.#Q();break;case 5:this.#Z.hostname=this.#Q();break;case 6:this.#Z.port=this.#Q();break;case 7:this.#Z.pathname=this.#Q();break;case 8:this.#Z.search=this.#Q();break;case 9:this.#Z.hash=this.#Q();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.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#T($,Z)}#T($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#M(){this.#$=this.#G,this.#Y=0}#F($){this.#M(),this.#X=$}#O($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#O($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#N(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#L(){return this.#z(this.#$,"@")}#I(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#B(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#O(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#Q(){let $=this.#W[this.#$],Z=this.#O(this.#G).index;return this.#j.substring(Z,$.index)}#E(){let $={};Object.assign($,O$),$.encodePart=d4;let Z=xQ(this.#Q(),void 0,$);this.#D=o9(Z)}};x(dQ,"Parser");var h9=["protocol","username","password","hostname","port","pathname","search","hash"],D$="*";function d9($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}x(d9,"extractValues");function H1($,Z){return Z?uZ($):$}x(H1,"processBaseURLString");function dZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=H1(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=H1(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=H1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=H1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=H1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=H1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=H1(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=H1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=yQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=kQ(Z.username,J)),typeof Z.password=="string"&&($.password=fQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=RQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=qQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!CQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=H1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=wQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=bQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=EQ(Z.hash,J)),$}x(dZ,"applyInit");function uZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}x(uZ,"escapePatternString");function uQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(uQ,"escapeRegexpString");function lQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${uQ(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=uZ(X.value);continue}j+=`{${uZ(X.value)}}${i$(X.modifier)}`;continue}let Q=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),K=z>0?$[z-1]:null,F=z<$.length-1?$[z+1]:null;if(!G&&Q&&X.type===1&&X.modifier===3&&F&&!F.prefix.length&&!F.suffix.length)if(F.type===3){let B=F.value.length>0?F.value[0]:"";G=Y.test(B)}else G=!F.hasCustomName();if(!G&&!X.prefix.length&&K&&K.type===3){let B=K.value[K.value.length-1];G=Z.prefixes.includes(B)}G&&(j+="{"),j+=uZ(X.prefix),Q&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?Q||(j+=`(${W})`):X.type===0&&(!Q&&(!K||K.type===3||K.modifier!==3||G||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&Q&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=uZ(X.suffix),G&&(j+="}"),X.modifier!==3&&(j+=i$(X.modifier))}return j}x(lQ,"partsToPattern");var $J=class{#j;#W={};#Z={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new dQ($);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 Y={ignoreCase:J.ignoreCase===!0},j={pathname:D$,protocol:D$,username:D$,password:D$,hostname:D$,port:D$,search:D$,hash:D$};this.#j=dZ(j,$,!0),a9(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of h9){if(!(z in this.#j))continue;let X={},Q=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,O$),X.encodePart=d4;break;case"username":Object.assign(X,O$),X.encodePart=vQ;break;case"password":Object.assign(X,O$),X.encodePart=gQ;break;case"hostname":Object.assign(X,AD),n9(Q)?X.encodePart=t9:X.encodePart=r9;break;case"port":Object.assign(X,O$),X.encodePart=e9;break;case"pathname":o9(this.#W.protocol)?(Object.assign(X,SD,Y),X.encodePart=mQ):(Object.assign(X,O$,Y),X.encodePart=hQ);break;case"search":Object.assign(X,O$,Y),X.encodePart=pQ;break;case"hash":Object.assign(X,O$,Y),X.encodePart=cQ;break}try{this.#Y[z]=l9(Q,X),this.#W[z]=i9(this.#Y[z],this.#Z[z],X),this.#$[z]=lQ(this.#Y[z],X),this.#G=this.#G||this.#Y[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[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=dZ(J,$,!1):J=dZ(J,d9($,Z),!1)}catch{return!1}let W;for(W of h9)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=dZ(J,$,!1):J=dZ(J,d9($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of h9){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,Q]of this.#Z[Y].entries())if(typeof Q=="string"||typeof Q=="number"){let G=j[X+1];z[Q]=G}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=x((X,Q)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<Q[G])return-1;if(X[G]===Q[G])continue;return 1}return 0},"comparePart"),Y=new lZ(3,"","","","",3),j=new lZ(0,"","","","",3),z=x((X,Q)=>{let G=0;for(;G<Math.min(X.length,Q.length);++G){let K=W(X[G],Q[G]);if(K)return K}return X.length===Q.length?0:W(X[G]??Y,Q[G]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};x($J,"URLPattern");function d3($,Z){for(let[J,W]of Object.entries($)){let Y=new $J({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var s$={startIndex:0,carriedViews:[]};function iQ($,Z){let J=B0($.path,Z);return J.includes("*")?null:J}function ED($,Z){if(!$)return s$;if($.search!==Z.search)return s$;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=iQ(Y,$.params),X=iQ(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return s$;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function bD($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function sQ($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return s$;let z;try{z=new URL(W,Y)}catch{return s$}if(z.origin!==Y)return s$;let X=d3(Z,bD(z.pathname,J));if(!X)return s$;return ED({segments:X.route.segments,params:X.params,search:z.search},j)}var ZJ="x-gemi-from";import{createElement as g1,Fragment as VG}from"react";function RD($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function u4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=u4(j.routes);for(let[X,Q]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,K=X==="/"&&J!=="/"?J:G;Z[K]=[Y,...Q]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=u4(Y.routes);for(let[z,X]of Object.entries(j)){let Q=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:Q;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[RD(J),W]))}function l4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)l4(Y[1],j)}function i4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=i4(j.routes);l4(Z,[Y,z])}else l4(Z,[Y,[]])}else{let Y=new W,j=i4(Y.routes);for(let z of j)l4(Z,z)}return Z}function JJ($){let Z=[];for(let[J,W]of $)Z.push(J,...JJ(W).flat());return Array.from(new Set(Z))}function nQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class L$ extends g{static getFacadeAccessor(){return o}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??L$.locale(),$.timeZone??L$.timeZone())}static setLocale($=L$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=N.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class WJ{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function oQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var fD=50;class iZ{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 Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} 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??{},Y=new URLSearchParams(oQ(Z.search??{}));Y.delete("json"),Y.sort();let j=B0($,W),z=Y.toString(),X=this.keyFor(j,z),Q=this.entries.get(X);if(Q)return Q;let G;if(J==="render"&&this.renderStartedAt!==null){let U=Math.round(performance.now()-this.renderStartedAt);if(U>fD)G=U}let K,F=new Promise((U)=>{K=U}),B={path:j,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:F,source:J,startedAt:this.elapsed()};return this.entries.set(X,B),this.fetcher($,W,Y).then((U)=>{B.status="resolved",B.data=U},(U)=>{B.status="rejected",B.error=U}).then(()=>{if(B.settledAt=this.elapsed(),this.maybeLogLateDiscovery(B),B.status==="rejected"&&this.failListener)this.failListener(B);if(this.settleListener)this.settleListener(B);else this.settledBacklog.push(B);K()}),B}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 v1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){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=Y;this.name="QueryError"}}function sZ(){let $=JSON.stringify({error:o1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function YJ(){return{status:403,error:{message:"Forbidden"}}}function u3($){let Z=nZ.getStore();return(J,W,Y)=>{let j=new URL($.url).origin,z=[B0(J,W),Y.toString()].filter((K)=>K.length>0).join("?"),X=new Request(`${j}/${z}`,{headers:$.headers,signal:$.signal}),Q=aQ($);if(Q)oZ(X,Q);let G=new C(X,W);return nZ.run(Z,()=>N.run(G,async()=>{try{let K=H(Y1).dispatchers(Q).api,F=await K.runRouteMiddleware(J,G)??await K.getRouteData(J);if(u1(F)){if(!F.ok)throw new v1(B0(J,W),Y.toString(),F.status,F.body);return F.body}if(F instanceof Response){let B=await F.json().catch(()=>null);if(!F.ok)throw new v1(B0(J,W),Y.toString(),F.status,B);return B}return F}catch(K){if(K instanceof v1)throw K;let F=new v1(B0(J,W),Y.toString(),500,{message:K instanceof Error?K.message:String(K)});throw F.cause=K,F}}))}}var kD=new Set(["script","style","template","title"]),wD=/\shidden([\s=/]|$)/i,qD=/"[^"]*"|'[^']*'/g;function yD($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let F=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=F;else Z+=F}if(j===-1)break;if($.startsWith("<!--",j)){let F=$.indexOf("-->",j+4);Y=F===-1?$.length:F+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let Q=$.slice(j+1,X);Y=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(Q)?.[1]?.toLowerCase();if(!G)continue;let K=Q.startsWith("/");if(!K&&kD.has(G)&&!Q.endsWith("/")){let F=$.indexOf(`</${G}`,Y);Y=F===-1?$.length:F;continue}if(G!=="div")continue;if(K){if(W>0)W-=1}else if(W>0)W+=1;else if(wD.test(Q.replace(qD,'""')))W=1}return{shellChars:Z,deferredChars:J}}var vD=1000,gD=64;function mD($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function hD($,Z){if(Z.deferredChars<vD)return null;if(Z.shellChars>=gD)return null;return`[gemi] GET ${$} streams ${mD(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 rQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=hD(J,W);if(!Y)return;Z.add(J),$(Y)}}}function tQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),yD(Z)}}}function eQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,Q=(K)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}W?.({aborted:K})};j=Q,z.enqueue(Y.encode(`${JSON.stringify($)}
20
- `)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
21
- `))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as _I,createContext as pD,createElement as xI,lazy as CI,use as AI,useContext as SI}from"react";function $G($){return{islands:[],render:$,instances:new WeakMap,count:0}}var l3="gemi-slot",ZG="data-slot",JG="data-gemi-slot";var cD=Symbol.for("gemi.staticRender"),WG=globalThis[cD]??=pD(null);import{createHash as QG}from"crypto";var jJ='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';import{createHash as dD}from"crypto";import{existsSync as jG,readFileSync as uD}from"fs";import{join as GJ}from"path";var zG=".script",lD=[".ts",".js"],iD="document-scripts.json",XG="data-gemi-script",sD=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function nD($){if(typeof $!=="string"||!sD.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function oD($,Z){for(let J of lD){let W=GJ($,"views",`${Z}${zG}${J}`);if(jG(W))return W}return null}async function YG($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
19
+ c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}var _D=Object.defineProperty,x=($,Z)=>_D($,"name",{value:Z,configurable:!0}),lZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};x(lZ,"Part");var xD=/[$_\p{ID_Start}]/u,CD=/[$_\u200C\u200D\p{ID_Continue}]/u,p9=".*";function _Q($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}x(_Q,"isASCII");function u9($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=x(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let Q=$.substr(X,1);if(X===W+1&&xD.test(Q)||X!==W+1&&CD.test(Q)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",Q=W+1,G=!1;if($[Q]==="?"){j(`Pattern cannot start with "?" at ${Q}`);continue}for(;Q<$.length;){if(!_Q($[Q],!1)){j(`Invalid character '${$[Q]}' at ${Q}.`),G=!0;break}if($[Q]==="\\"){X+=$[Q++]+$[Q++];continue}if($[Q]===")"){if(z--,z===0){Q++;break}}else if($[Q]==="("&&(z++,$[Q+1]!=="?")){j(`Capturing groups are not allowed at ${Q}`),G=!0;break}X+=$[Q++]}if(G)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=Q;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}x(u9,"lexer");function l9($,Z={}){let J=u9($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${c0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",Q=new Set,G=x((P)=>{if(z<J.length&&J[z].type===P)return J[z++].value},"tryConsume"),B=x(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),F=x((P)=>{let _=G(P);if(_!==void 0)return _;let{type:A,index:E}=J[z];throw TypeError(`Unexpected ${A} at ${E}, expected ${P}`)},"mustConsume"),K=x(()=>{let P="",_;for(;_=G("CHAR")??G("ESCAPED_CHAR");)P+=_;return P},"consumeText"),V=x((P)=>P,"DefaultEncodePart"),U=Z.encodePart||V,D="",O=x((P)=>{D+=P},"appendToPendingFixedValue"),L=x(()=>{D.length&&(Y.push(new lZ(3,"","",U(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),T=x((P,_,A,E,S)=>{let f=3;switch(S){case"?":f=1;break;case"*":f=0;break;case"+":f=2;break}if(!_&&!A&&f===3){O(P);return}if(L(),!_&&!A){if(!P)return;Y.push(new lZ(3,"","",U(P),"",f));return}let M;A?A==="*"?M=p9:M=A:M=W;let I=2;M===W?(I=1,M=""):M===p9&&(I=0,M="");let y;if(_?y=_:A&&(y=j++),Q.has(y))throw TypeError(`Duplicate name '${y}'.`);Q.add(y),Y.push(new lZ(I,y,U(P),M,U(E),f))},"addPart");for(;z<J.length;){let P=G("CHAR"),_=G("NAME"),A=G("REGEX");if(!_&&!A&&(A=G("ASTERISK")),_||A){let S=P??"";Z.prefixes.indexOf(S)===-1&&(O(S),S=""),L();let f=B();T(S,_,A,"",f);continue}let E=P??G("ESCAPED_CHAR");if(E){O(E);continue}if(G("OPEN")){let S=K(),f=G("NAME"),M=G("REGEX");!f&&!M&&(M=G("ASTERISK"));let I=K();F("CLOSE");let y=B();T(S,f,M,I,y);continue}L(),F("END")}return Y}x(l9,"parse");function c0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(c0,"escapeString");function c9($){return $&&$.ignoreCase?"ui":"u"}x(c9,"flags");function xQ($,Z,J){return i9(l9($,J),Z,J)}x(xQ,"stringToRegexp");function i$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}x(i$,"modifierToString");function i9($,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+=c0(X.value):W+=`(?:${c0(X.value)})${i$(X.modifier)}`;continue}Z&&Z.push(X.name);let Q=`[^${c0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=Q:X.type===0&&(G=p9),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${G})${i$(X.modifier)}`:W+=`((?:${G})${i$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${c0(X.prefix)}(${G})${c0(X.suffix)})`,W+=i$(X.modifier);continue}W+=`(?:${c0(X.prefix)}`,W+=`((?:${G})(?:`,W+=c0(X.suffix),W+=c0(X.prefix),W+=`(?:${G}))*)${c0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${c0(J.endsWith)}]|$`,j=`[${c0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,c9(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,c9(J))}x(i9,"partsToRegexp");var O$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},AD={delimiter:".",prefixes:"",sensitive:!0,strict:!0},SD={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function CQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}x(CQ,"isAbsolutePathname");function s9($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}x(s9,"maybeStripPrefix");function AQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}x(AQ,"maybeStripSuffix");function n9($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}x(n9,"treatAsIPv6Hostname");var SQ=["ftp","file","http","https","ws","wss"];function o9($){if(!$)return!0;for(let Z of SQ)if($.test(Z))return!0;return!1}x(o9,"isSpecialScheme");function EQ($,Z){if($=s9($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}x(EQ,"canonicalizeHash");function bQ($,Z){if($=s9($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}x(bQ,"canonicalizeSearch");function RQ($,Z){return Z||$===""?$:n9($)?t9($):r9($)}x(RQ,"canonicalizeHostname");function fQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}x(fQ,"canonicalizePassword");function kQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}x(kQ,"canonicalizeUsername");function wQ($,Z,J){if(J||$==="")return $;if(Z&&!SQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}x(wQ,"canonicalizePathname");function qQ($,Z,J){return a9(Z)===$&&($=""),J||$===""?$:e9($)}x(qQ,"canonicalizePort");function yQ($,Z){return $=AQ($,":"),Z||$===""?$:d4($)}x(yQ,"canonicalizeProtocol");function a9($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}x(a9,"defaultPortForProtocol");function d4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}x(d4,"protocolEncodeCallback");function vQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}x(vQ,"usernameEncodeCallback");function gQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}x(gQ,"passwordEncodeCallback");function r9($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}x(r9,"hostnameEncodeCallback");function t9($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}x(t9,"ipv6HostnameEncodeCallback");function e9($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}x(e9,"portEncodeCallback");function mQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}x(mQ,"standardURLPathnameEncodeCallback");function hQ($){return $===""?$:new URL(`data:${$}`).pathname}x(hQ,"pathURLPathnameEncodeCallback");function pQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}x(pQ,"searchEncodeCallback");function cQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}x(cQ,"hashEncodeCallback");var dQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#G=0;#X=0;#V=0;#U=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=u9(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#M(),this.#K()?this.#J(9,1):this.#B()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#F(5);continue}this.#J(10,0);break}if(this.#V>0)if(this.#C())this.#V-=1;else continue;if(this.#x()){this.#V+=1;continue}switch(this.#X){case 0:this.#P()&&this.#F(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#N()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#L()?this.#F(3):(this.#H()||this.#B()||this.#K())&&this.#F(5);break;case 3:this.#I()?this.#J(4,1):this.#L()&&this.#J(5,1);break;case 4:this.#L()&&this.#J(5,1);break;case 5:this.#A()?this.#U+=1:this.#S()&&(this.#U-=1),this.#_()&&!this.#U?this.#J(6,1):this.#H()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#B()?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.#Q();break;case 2:break;case 3:this.#Z.username=this.#Q();break;case 4:this.#Z.password=this.#Q();break;case 5:this.#Z.hostname=this.#Q();break;case 6:this.#Z.port=this.#Q();break;case 7:this.#Z.pathname=this.#Q();break;case 8:this.#Z.search=this.#Q();break;case 9:this.#Z.hash=this.#Q();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.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#T($,Z)}#T($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#M(){this.#$=this.#G,this.#Y=0}#F($){this.#M(),this.#X=$}#O($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#O($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#N(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#L(){return this.#z(this.#$,"@")}#I(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#B(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#O(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#Q(){let $=this.#W[this.#$],Z=this.#O(this.#G).index;return this.#j.substring(Z,$.index)}#E(){let $={};Object.assign($,O$),$.encodePart=d4;let Z=xQ(this.#Q(),void 0,$);this.#D=o9(Z)}};x(dQ,"Parser");var h9=["protocol","username","password","hostname","port","pathname","search","hash"],D$="*";function d9($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}x(d9,"extractValues");function H1($,Z){return Z?uZ($):$}x(H1,"processBaseURLString");function dZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=H1(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=H1(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=H1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=H1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=H1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=H1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=H1(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=H1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=yQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=kQ(Z.username,J)),typeof Z.password=="string"&&($.password=fQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=RQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=qQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!CQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=H1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=wQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=bQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=EQ(Z.hash,J)),$}x(dZ,"applyInit");function uZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}x(uZ,"escapePatternString");function uQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(uQ,"escapeRegexpString");function lQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${uQ(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=uZ(X.value);continue}j+=`{${uZ(X.value)}}${i$(X.modifier)}`;continue}let Q=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),B=z>0?$[z-1]:null,F=z<$.length-1?$[z+1]:null;if(!G&&Q&&X.type===1&&X.modifier===3&&F&&!F.prefix.length&&!F.suffix.length)if(F.type===3){let K=F.value.length>0?F.value[0]:"";G=Y.test(K)}else G=!F.hasCustomName();if(!G&&!X.prefix.length&&B&&B.type===3){let K=B.value[B.value.length-1];G=Z.prefixes.includes(K)}G&&(j+="{"),j+=uZ(X.prefix),Q&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?Q||(j+=`(${W})`):X.type===0&&(!Q&&(!B||B.type===3||B.modifier!==3||G||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&Q&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=uZ(X.suffix),G&&(j+="}"),X.modifier!==3&&(j+=i$(X.modifier))}return j}x(lQ,"partsToPattern");var $J=class{#j;#W={};#Z={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new dQ($);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 Y={ignoreCase:J.ignoreCase===!0},j={pathname:D$,protocol:D$,username:D$,password:D$,hostname:D$,port:D$,search:D$,hash:D$};this.#j=dZ(j,$,!0),a9(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of h9){if(!(z in this.#j))continue;let X={},Q=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,O$),X.encodePart=d4;break;case"username":Object.assign(X,O$),X.encodePart=vQ;break;case"password":Object.assign(X,O$),X.encodePart=gQ;break;case"hostname":Object.assign(X,AD),n9(Q)?X.encodePart=t9:X.encodePart=r9;break;case"port":Object.assign(X,O$),X.encodePart=e9;break;case"pathname":o9(this.#W.protocol)?(Object.assign(X,SD,Y),X.encodePart=mQ):(Object.assign(X,O$,Y),X.encodePart=hQ);break;case"search":Object.assign(X,O$,Y),X.encodePart=pQ;break;case"hash":Object.assign(X,O$,Y),X.encodePart=cQ;break}try{this.#Y[z]=l9(Q,X),this.#W[z]=i9(this.#Y[z],this.#Z[z],X),this.#$[z]=lQ(this.#Y[z],X),this.#G=this.#G||this.#Y[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[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=dZ(J,$,!1):J=dZ(J,d9($,Z),!1)}catch{return!1}let W;for(W of h9)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=dZ(J,$,!1):J=dZ(J,d9($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of h9){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,Q]of this.#Z[Y].entries())if(typeof Q=="string"||typeof Q=="number"){let G=j[X+1];z[Q]=G}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=x((X,Q)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<Q[G])return-1;if(X[G]===Q[G])continue;return 1}return 0},"comparePart"),Y=new lZ(3,"","","","",3),j=new lZ(0,"","","","",3),z=x((X,Q)=>{let G=0;for(;G<Math.min(X.length,Q.length);++G){let B=W(X[G],Q[G]);if(B)return B}return X.length===Q.length?0:W(X[G]??Y,Q[G]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};x($J,"URLPattern");function d3($,Z){for(let[J,W]of Object.entries($)){let Y=new $J({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var s$={startIndex:0,carriedViews:[]};function iQ($,Z){let J=B0($.path,Z);return J.includes("*")?null:J}function ED($,Z){if(!$)return s$;if($.search!==Z.search)return s$;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=iQ(Y,$.params),X=iQ(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return s$;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function bD($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function sQ($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return s$;let z;try{z=new URL(W,Y)}catch{return s$}if(z.origin!==Y)return s$;let X=d3(Z,bD(z.pathname,J));if(!X)return s$;return ED({segments:X.route.segments,params:X.params,search:z.search},j)}var ZJ="x-gemi-from";import{createElement as g1,Fragment as VG}from"react";function RD($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function u4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=u4(j.routes);for(let[X,Q]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,B=X==="/"&&J!=="/"?J:G;Z[B]=[Y,...Q]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=u4(Y.routes);for(let[z,X]of Object.entries(j)){let Q=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:Q;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[RD(J),W]))}function l4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)l4(Y[1],j)}function i4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=i4(j.routes);l4(Z,[Y,z])}else l4(Z,[Y,[]])}else{let Y=new W,j=i4(Y.routes);for(let z of j)l4(Z,z)}return Z}function JJ($){let Z=[];for(let[J,W]of $)Z.push(J,...JJ(W).flat());return Array.from(new Set(Z))}function nQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class L$ extends g{static getFacadeAccessor(){return d}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??L$.locale(),$.timeZone??L$.timeZone())}static setLocale($=L$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=N.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class WJ{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function oQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var fD=50;class iZ{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 Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} 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??{},Y=new URLSearchParams(oQ(Z.search??{}));Y.delete("json"),Y.sort();let j=B0($,W),z=Y.toString(),X=this.keyFor(j,z),Q=this.entries.get(X);if(Q)return Q;let G;if(J==="render"&&this.renderStartedAt!==null){let V=Math.round(performance.now()-this.renderStartedAt);if(V>fD)G=V}let B,F=new Promise((V)=>{B=V}),K={path:j,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:F,source:J,startedAt:this.elapsed()};return this.entries.set(X,K),this.fetcher($,W,Y).then((V)=>{K.status="resolved",K.data=V},(V)=>{K.status="rejected",K.error=V}).then(()=>{if(K.settledAt=this.elapsed(),this.maybeLogLateDiscovery(K),K.status==="rejected"&&this.failListener)this.failListener(K);if(this.settleListener)this.settleListener(K);else this.settledBacklog.push(K);B()}),K}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 v1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){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=Y;this.name="QueryError"}}function sZ(){let $=JSON.stringify({error:o1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function YJ(){return{status:403,error:{message:"Forbidden"}}}function u3($){let Z=nZ.getStore(),J=N.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[B0(W,Y),j.toString()].filter((F)=>F.length>0).join("?"),Q=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),G=aQ($);if(G)oZ(Q,G);let B=new C(Q,Y);return nZ.run(Z,()=>N.run(B,async()=>{let F=J?.locale;if(F&&H(d).isLocaleAware)N.getStore().setLocale(F);try{let K=H(Y1).dispatchers(G).api,V=await K.runRouteMiddleware(W,B)??await K.getRouteData(W);if(u1(V)){if(!V.ok)throw new v1(B0(W,Y),j.toString(),V.status,V.body);return V.body}if(V instanceof Response){let U=await V.json().catch(()=>null);if(!V.ok)throw new v1(B0(W,Y),j.toString(),V.status,U);return U}return V}catch(K){if(K instanceof v1)throw K;let V=new v1(B0(W,Y),j.toString(),500,{message:K instanceof Error?K.message:String(K)});throw V.cause=K,V}}))}}var kD=new Set(["script","style","template","title"]),wD=/\shidden([\s=/]|$)/i,qD=/"[^"]*"|'[^']*'/g;function yD($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let F=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=F;else Z+=F}if(j===-1)break;if($.startsWith("<!--",j)){let F=$.indexOf("-->",j+4);Y=F===-1?$.length:F+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let Q=$.slice(j+1,X);Y=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(Q)?.[1]?.toLowerCase();if(!G)continue;let B=Q.startsWith("/");if(!B&&kD.has(G)&&!Q.endsWith("/")){let F=$.indexOf(`</${G}`,Y);Y=F===-1?$.length:F;continue}if(G!=="div")continue;if(B){if(W>0)W-=1}else if(W>0)W+=1;else if(wD.test(Q.replace(qD,'""')))W=1}return{shellChars:Z,deferredChars:J}}var vD=1000,gD=64;function mD($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function hD($,Z){if(Z.deferredChars<vD)return null;if(Z.shellChars>=gD)return null;return`[gemi] GET ${$} streams ${mD(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 rQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=hD(J,W);if(!Y)return;Z.add(J),$(Y)}}}function tQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),yD(Z)}}}function eQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,Q=(B)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}W?.({aborted:B})};j=Q,z.enqueue(Y.encode(`${JSON.stringify($)}
20
+ `)),Z.onSettle((B)=>{if(X||B.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([B.path,B.variantKey,B.data])}
21
+ `))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as xI,createContext as pD,createElement as CI,lazy as AI,use as SI,useContext as EI}from"react";function $G($){return{islands:[],render:$,instances:new WeakMap,count:0}}var l3="gemi-slot",ZG="data-slot",JG="data-gemi-slot";var cD=Symbol.for("gemi.staticRender"),WG=globalThis[cD]??=pD(null);import{createHash as QG}from"crypto";var jJ='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';import{createHash as dD}from"crypto";import{existsSync as jG,readFileSync as uD}from"fs";import{join as GJ}from"path";var zG=".script",lD=[".ts",".js"],iD="document-scripts.json",XG="data-gemi-script",sD=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function nD($){if(typeof $!=="string"||!sD.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function oD($,Z){for(let J of lD){let W=GJ($,"views",`${Z}${zG}${J}`);if(jG(W))return W}return null}async function YG($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
22
22
  `);throw Error(`The document script ${$} does not bundle.
23
- ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function aD($){return`'sha256-${dD("sha256").update($).digest("base64")}'`}var zJ,XJ=new Map;function rD(){if(zJ===void 0){let $=GJ(QJ(),"dist","server",iD);zJ=jG($)?JSON.parse(uD($,"utf8")):null}return zJ??null}async function KJ($){nD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=rD()?.[$];if(j!==void 0)return j;let z=XJ.get($);if(z)return z}let J=GJ(QJ(),"app"),W=oD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${zG}.ts (or .js).`);if(!Z)return YG(W);let Y=YG(W);return XJ.set($,Y),Y.catch(()=>XJ.delete($)),Y}async function qI($){return aD(await KJ($))}var tD="gemi-islands",dI=`'sha256-${QG("sha256").update(VJ).digest("base64")}'`;function BJ($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var FJ=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),uI=`'sha256-${QG("sha256").update(jJ).digest("base64")}'`,eD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',$O="gemi-static";function GG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let D=V.module?J(V.module):void 0;if(!D)return console.error(`[gemi] island ${V.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(V.load==="eager"){for(let O of D.preload)z.add(O);if(V.preloadDynamic)for(let O of D.dynamicPreload??[])z.add(O)}return{s:D.src,e:V.export,l:V.load}});let Q=X.some((V)=>V!==null),G=j?`<script type="module" ${XG}="${FJ(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return BJ($,"</head>",G,!1);let F=(Y?`<meta name="${$O}" content="${FJ(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${FJ(V)}"/>`).join("")+G,B=Y?jJ:VJ,U=(Q?`<script type="application/json" id="${tD}">${G1({i:X})}</script>`:"")+`<script type="module">${W?eD+B:B}</script>`;return BJ(BJ($,"</head>",F,!1),"</body>",U,!0)}function ZO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function KG($){let Z=`<template ${JG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=ZO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${l3} ${ZG}="${j}" style="display:contents"></${l3}>`;$=$.split(Q).join(`<${l3} style="display:contents">${X}</${l3}>`)}return $}function BG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function FG($,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 JO=async()=>(await import("./chunk-3xj1e3ns.js")).default,UJ,i3=async(...$)=>{return UJ??=import("react-dom/server.browser").catch((Z)=>{throw UJ=void 0,Z}),(await UJ).renderToReadableStream(...$)},UG=1e4,DG="no-locale",WO="no-theme";async function YO($,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 LJ="/assets";function jO($){return $===LJ||$.startsWith(`${LJ}/`)}function zO($){let Z=$.filter(jO);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 "${LJ}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function XO($){let Z=H(Y1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function DJ($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function QO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class s3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=rQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;defaultMeta;constructor($,Z={}){let J=MQ();this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":BQ(Z)};this.requiredViews=Object.fromEntries(GQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=c4(W),zO(Object.keys(this.flatViewRoutes)),this.routeManifest=u4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=i4(W),this.flatComponentTree=JJ(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}this.root=$.root}async passesFeatureGates($){let Z=H(r1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)s4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{n$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let K of J?.[G]??[])Q.add(K);return[...Q].map((G)=>g1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let K=OJ(),F=new AbortController,B=setTimeout(()=>F.abort(),UG),U=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},V=$G(async(D,O)=>{let L=await i3(D,{signal:F.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await L.allReady.catch(()=>{}),await new Response(L).text()});try{let D,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)D={name:O,source:await KJ(O)};let L;if(W.navigation){let _=W.navigation===!0?{}:W.navigation,A=_.version?String(await J(()=>_.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",D?.name??"",A].join("|"),prefetch:_.prefetch==="none"?"none":"intent"}}let T=await i3(g1(WG.Provider,{value:V,children:g1(VG,{children:[...G,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:Q,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let P=KG(await new Response(T).text());return new Response(GG(P,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,D),{status:200,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:K,noStream:F,noTheme:B,url:U,user:V,viewData:D,breadcrumbs:O,urlLocaleSegment:L,meta:T,isOgRequest:P,appId:_,features:A,staticView:E}=$,S=this.theme===!1||B||E?null:{cookie:this.theme.cookie??m9,default:this.theme.default??null,value:GO(Z,this.theme.cookie??m9)},f=L?nQ(Q,[L]).pathname:Q,M={kind:"view",data:{meta:T,pageData:{[f]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:V},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?XO(Z):null},appId:_,features:A,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},I=this.root,y=this.routeManifest[Y];return async(H$)=>{let{bootstrapModules:T0=[],loaders:h1,getStyles:l,viewImportMap:q,cssManifest:N0,ogMap:t$,viewModules:o3,clientEntry:M$,modulePreloadManifest:p1,assetBase:c1,resolveIsland:e$,buildId:n}=H$,eZ=M$?[]:T0,a3=(k0)=>[k0,`window.loaders=${h1}`,...M$?[`import(${JSON.stringify(M$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let k0=null,JZ=null;for(let WZ of y??[])if(typeof t$[WZ]==="function")JZ=WZ,k0=t$[WZ];if(!k0)return new Response("Not found",{status:404});let PK=Object.values(M.data.pageData)[0];try{await i3(g1(k0,PK[JZ]),{onError:()=>{}})}catch(WZ){let{fonts:TK,...NK}=WZ.satoriOptions,IK=await Promise.all(TK.map((r3)=>{return YO(r3.name,r3.weight,r3.style).then((SK)=>({...r3,data:SK}))})),nJ=new Headers(j);nJ.set("Content-Type","image/png");let[_K,xK]=await Promise.all([JO(),h4("Rendering an OG image")]),CK=await _K(WZ.jsx,{...NK,fonts:IK}),AK=await xK(Buffer.from(CK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(AK),{headers:nJ})}return new Response("data")}if(E&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:E,currentViews:y,data:M.data,serverQueries:G,headers:j,getStyles:l,viewImportMap:q,viewModules:o3,resolveIsland:e$,buildId:n});if(M.data.cssManifest=N0,M.data.modulePreloadManifest=p1??{},c1&&c1!=="/")M.data.assetBase=c1;if(n&&n!=="dev")M.data.buildId=n;let $Z=this.modulePreloadLinks({clientEntry:M$,modulePreloadManifest:p1,views:y??["404"],routeKey:Y??"404"}),$3=await l(y??["404"]);M.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let d1=new AbortController,P$=setTimeout(()=>d1.abort(),UG),R=H6(K)||F,f0=Bun.env.NODE_ENV!=="production"&&!R&&Y&&this.shellReporter.shouldObserve(Y)?tQ():null,ZZ=OJ();try{let k0=await i3(g1(VG,{children:[...$Z,...$3,...S?[g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:IQ(G1({cookie:S.cookie,default:S.default}))}})]:[],g1(I,{data:M.data,viewImportMap:q,viewModules:o3,serverQueries:G,dictionarySink:ZZ,key:"root"})]}),{bootstrapScriptContent:a3(`window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:eZ,signal:d1.signal,...R?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(JZ){if(Bun.env.NODE_ENV!=="production")console.error(JZ)}});if(k0.allReady.catch(()=>{}).finally(()=>clearTimeout(P$)),R)await k0.allReady.catch(()=>{});return new Response(u8(k0,G,{onShell:R?void 0:()=>G.markShell(),onChunk:f0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(d1.signal.aborted)),f0)this.shellReporter.report(Y,f0.measure())})},ZZ),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(k0){if(clearTimeout(P$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted))),k0;let JZ=await i3(g1("div"),{bootstrapScriptContent:a3(`window.error= ${G1(k0.message)}; window.stack_trace=${G1(k0.stack)};window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...eZ]:eZ});return new Response(u8(JZ,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(N$(Z))return 404;if(Z?.kind===s1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(n1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,K=null,F=H(o),B=d3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(DG);if(U&&F.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,K=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let M=J.pathname.replace(/\/+$/,""),I=U&&F.supportedLocales.includes(M.slice(1));if(M&&!I)return new Response("",{status:301,headers:{Location:`${M}${J.search}`}})}if(U&&!Y&&K===null&&!(K===null&&B!==null)){let M=OG(z,F.supportedLocales,F.defaultLocale);if(M){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:`/${M}${I}${W?".json":""}${J.search}`}})}}if(U&&!Y){let M=H(o).detectLocale(new C($,{},"view",Q));if(K===null&&M!==F.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:`/${M}${I}${J.search}`}})}}Q=Q.replace("//","/");let D=[],O=[],L=null,T={},P=null,_=!1,A=!1,E=[],S;try{let M=d3(this.flatViewRoutes,Q);if(K&&M?.route.middleware.includes(DG))M=null;if(M){if(L=M.routePath,T=M.params,D=M.route.exec,O=M.route.middleware,E=M.route.features,_=O.includes("no-stream"),A=O.includes(WO),S=M.route.static,W&&this.partialRendering){let I=$.headers.get(ZJ),y=sQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(o).supportedLocales,from:I,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),P={from:I,carriedViews:y.carriedViews}}}}catch(M){throw M}if(S&&W)return new Response("Not found",{status:404});let f=new C($,T,"view",L);return this.hooks.onRequestStart(f),await N.run(f,async()=>{let M=null,I=N.getStore(),y=nZ.getStore(),H$=(q)=>nZ.run(y,()=>N.runWith(I,q));I.serverQueries=new iZ(u3($));let T0=new Set;I.serverQueries.onQueryFail((q)=>{T0.add(q.error);try{H$(()=>Promise.resolve(this.hooks.onRequestFail(l,q.error)).catch(()=>{}))}catch{}});let h1=BG(S);if(K){let q=K.replaceAll("/","");L$.setLocale(q,{cookie:h1.locale})}else if(F.isLocaleAware&&!U)I.setLocale(F.defaultLocale);else L$.setLocale(void 0,{cookie:h1.locale});let l=I.req;if(h1.session)s4();try{let q=null;try{await H(i1).runMiddleware(O)}catch(R){if(q=this.viewRefusalStatus(l,R,T0),q===null)throw R}if(q!==null||E.length>0&&!await this.passesFeatureGates(E))L=null,D=[],l.routePath="";let N0=H(o),t$=N0.isEnabled,o3=N0.isLocaleAware,M$=new C($,l.params),p1={defaultLocale:N0.defaultLocale,timeZone:N0.detectTimeZone(M$)};if(o3){let R=null;if(K)R=K.replaceAll("/",""),I.setLocale(R);else if(!U)R=I.locale??N0.defaultLocale;else R=N0.detectLocale(M$),I.setLocale(R);let f0=t$?N0.getPageTranslations(R,l.routePath):{};p1={...p1,supportedLocales:N0.supportedLocales,currentLocale:R,dictionary:{[R]:f0},defaultLocale:N0.defaultLocale,...U?{}:{localeRouting:"off"}}}await LG(p1.currentLocale??"");let c1;try{c1=await Promise.all(D.map((R)=>R(l)))}catch(R){if(q=this.viewRefusalStatus(l,R,T0),q===null)throw R;L=null,D=[],l.routePath="",c1=[]}if(L===null)await this.hooks.onNotFound(l,{status:q??404});if(this.defaultMeta&&!I.metadata.hasAllDefaultFields)I.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(l):this.defaultMeta);let{cookies:e$,headers:n}=I;if(q!==null)n.set("Cache-Control","no-store");M={data:c1,cookies:e$,headers:n,user:I.user,prefetchedData:I.serverQueries.snapshotResolved(),currentPathName:L,params:l.params,urlLocaleSegment:G,meta:I.renderMeta(),appId:H(WJ).id,features:await H(r1).forClient()};let{params:eZ,user:a3}=M,$Z={},$3={};for(let R of c1??[]){let[f0,ZZ]=Object.entries(R)?.[0]??[];if(!f0||!ZZ)continue;$3[`${f0}:${L}`]=ZZ.breadcrumb,$Z[f0]=ZZ}let d1=$Z.FILE;if(d1){for(let R of e$)n.append("Set-Cookie",R.toString());try{await this.onRequestEnd(l)}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await T8(d1,n)}if(W){n.set("Content-Type","application/x-ndjson; charset=utf-8"),n.append("Vary",ZJ),e$.forEach((f0)=>n.append("Set-Cookie",f0.toString())),await this.hooks.onRequestEnd(l);let R={meta:P&&!I.metadata.touched?null:M.meta,data:{[Q]:$Z},breadcrumbs:$3,prefetchedData:I.serverQueries.snapshotResolved(),i18n:p1,features:M.features,is404:!L,appId:M.appId,partial:P};return new Response(eQ(R,I.serverQueries,void 0,({aborted:f0})=>H$(()=>this.completeStream(l,I.serverQueries.summarize(f0)))),{headers:n})}if(n.set("Content-Type","text/html; charset=utf-8"),!_&&!(S&&L))n.append("Vary","User-Agent");let P$=Boolean(S&&L);if(!P$||h1.session)s4();for(let R of e$)n.append("Set-Cookie",R.toString());if(!P$||h1.csrf){let R=Bun.CSRF.generate(process.env.SECRET);n.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(l,{mintSession:!P$||h1.session})}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(P$)FG(n,S);return await this.render({req:l,runInRequestScope:H$,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:n,i18n:p1,params:eZ,pathname:J.pathname,serverQueries:I.serverQueries,userAgent:$.headers.get("user-agent"),noStream:_,noTheme:A,url:J,user:a3,viewData:$Z,breadcrumbs:$3,urlLocaleSegment:G,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:L?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===s1){let N0=W?QO(q.payload.viewData??q.payload.api):DJ(q.payload.view);for(let t$ of I.cookies)N0.headers.append("Set-Cookie",t$.toString());return N0}if(!T0.has(q))this.hooks.onRequestFail(l,q);if(n1(q))return console.error(q),W?sZ():DJ(YJ());if(q instanceof v1&&q.status===403)return W?sZ():DJ(YJ());throw q}},Z)}}function GO($,Z){let J=$.cookies?.get(Z);return NQ(J)?J:null}function HJ(){let $=JSON.stringify({error:o1("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 NG extends I0{routes={"/api-routes":this.get(()=>{let $=H(o4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(s3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var KO=new Set([l1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),BO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,FO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function VO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(KO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===l1)throw Error(`dispatchAs: credentials may not set the "${l1}" cookie. The access token stays the initiator's.`);if(!BO.test(Y)||!FO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function UO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function HG($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function MG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function DO(){return Bun.env.NODE_ENV==="development"}class o4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=HQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=y9({"/":$.rootRouter,"/auth":b9,"/__gemi__/services/i18n":R9,"/__gemi__/services/image":w9,...DO()?{"/__gemi__/services/logs":q9,"/__gemi__/debug":NG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=TG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(i1).runMiddleware(W)}catch(Y){if(Y.kind===s1)return HG(Y.payload.api);else{if(N$(Y))return HJ();if(this.onRequestFail(Z,Y),console.error(Y),n1(Y))return sZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===s1)return HG(j.payload.api);if(N$(j))return HJ();if(this.onRequestFail(J.req,j),console.error(j),n1(j))return sZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){n$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:o1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=H(o);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(i1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let D=MG(K,z.headers,z.cookies);return await Q(),D}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let D=MG(F,B,U);if(this.isOpenEndedBody($,D)){let O=UO(D,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),D}let V=(u1(F)?F:j1.json(F)).toResponse(B,U);return await Q(),V}catch(G){if(!X)try{await Q()}catch(K){console.error(K)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,K=[],F=Q?null:$.cookies.get(l1);if(F)K.push(`${l1}=${F}`);if(Y?.credentials)VO(G,K,Y.credentials,Q!==void 0);if(K.length>0)G.set("Cookie",K.join("; "));let B=Q?null:$.headers.get(l1);if(B)G.set(l1,B);let U=$.headers.get("User-Agent");if(U)G.set("User-Agent",U);let V;if(W instanceof FormData)V=W;else if(W!==void 0)G.set("Content-Type","application/json"),V=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:V,...Y?.signal?{signal:Y.signal}:{}});if(PG(D,GZ($),Q?.grant,Y?.progress),$.domain)oZ(D,$.domain);let O=Q?{user:Q.user}:void 0;return N.exit(()=>Y6.exit(()=>this.handleApiRequest(D,O)))}}import{timingSafeEqual as OO}from"crypto";var t4="",TJ="*",LO=60000,HO=1e4,PJ=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,a4=16,MJ=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r4="x-forwarded-host";function IG($){return $.startsWith(":")}function aZ($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&OO(J,W)}function MO($){if(!$)return null;if($===!0)return{header:r4,clientIpHeader:null,secret:null};return{header:($.hostHeader??r4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function PO($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!MJ.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!==void 0){if(typeof J!=="string"||!MJ.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!MJ.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<a4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${a4} characters. A guessable one lets any client name its own host.`)}function M1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function TO($){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 NO($){let Z=M1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>PJ.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<a4)throw Error(`\`route.domains.ask.secret\` must be at least ${a4} characters. A guessable one is worse than leaving \`ask\` out.`);PO($.trustProxy);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),IG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>PJ.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class NJ{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){NO($),this.root=M1($.root),this.hostTrust=MO($.trustProxy);for(let Z of $.groups??[])if(IG(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??LO,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:_$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return M1(this.forwardedHost($))??M1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&M1(Y)?TO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:TJ,params:{},custom:!0};return null}async allows($,Z){let J=M1($);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:t4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&PJ.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=HO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=M1($);if(Z)this.cache.delete(Z)}}}var IO={kind:"none"};function Vx($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return IO;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function Ux($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:_$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _G=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xG=16;function Dx($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!_G.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_G.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<xG)throw Error(`GEMI_PROXY_SECRET must be at least ${xG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function CG($,Z){if(!aZ($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:_$(J)}var _O="/__gemi__/domains/ask";class Y1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;constructor($,Z){this.groups.set(t4,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new NJ(J);let W=(Y)=>({api:Y.api?new o4({...Z.api,...Y.api}):$.api,view:Y.view?new s3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(TJ,W(J.custom.fallback))}applyClientIp($){let Z=this.clientIpTrust;if(Z)IJ($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?CG($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)IJ($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return oZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==_O)return null;if(!aZ(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??t4)}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 rZ($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var AG=600000;function SG($,Z){return[U6($,Z),U6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new o8){LY($.oauthProviders),this.config={...L1(HY($),$),emailCode:d8($.emailCode)},this.provider=Z}async oauthProvider($){return await DZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await fY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Y1)?H(Y1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Y1).resolver?.root:M1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??M1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!v8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=rZ(J.expiresAt),j=rZ(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/AG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=U6($,j),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of SG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(v8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/AG),W=SG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=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())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new I$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=jY(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:FY(Z),Q=D6("link",$,j),G=D6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let K=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>rZ(U.createdAt)+K>Date.now()&&U.pin!==G&&U.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return VZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>rZ(G.createdAt)+W*60000>Date.now());if(z.length===0)return VZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await DY(G.id,rZ(G.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let Q=null;for(let G of z)if(VZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return VZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(VZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(rZ(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class w0 extends g{static getFacadeAccessor(){return b}static async user(){let $=await w0.userOrNull();if($)return $;throw new I$({redirectTo:z6(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await Z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return X1(Z?.search.get(z1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new KZ}static async guardSafe($){let Z=await w0.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 e4{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 iZ(u3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=e4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){e4.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 iZ(u3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function xO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function _J($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?xO(z):encodeURIComponent(String(z))}`});return`${$8}${J==="/"?"":J}`||$8}var EG=new Map;function bG($,Z){let J=EG.get($);if(!J)J=new URLPattern({pathname:`${$8}${$==="/"?"":$}`}),EG.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function RG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=CO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function CO($){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 fG{static origin($){return xJ($)}static absolute($,...Z){return`${l$()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Y1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):l$();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return RG({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}static api($,...Z){return _J(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${xJ()}${_J(String($),Z[0]??{})}`}static matchApi($,Z){return bG(String($),Z)}}class kG{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 robots($){N.getStore().metadata.robots($)}static fonts($){N.getStore().metadata.fonts($)}}var AO={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 m1 extends g{static getFacadeAccessor(){return o$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function FC($){return $}function wG(){return{store:"memory",ttl:null}}class CJ{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var SO="500";class AJ{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${EO(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",SO]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(o$)?$.make(o$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function EO($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var bO="k:",qG="tag:",RO="t:";class SJ{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class EJ extends SJ{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=L1(wG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)a$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new vG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return bO+gG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=qG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=yG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(qG+Z,yG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:a$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new CJ(this.config.memory);if($==="redis"){let Z=this.options.application;return new AJ({...this.config.redis,client:Z?{send:(J,W)=>Z.make(o$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class vG extends SJ{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${RO}${Z.join(",")}:${$}`}}function gG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function yG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class mG extends g{static getFacadeAccessor(){return EJ}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class hG extends g{static getFacadeAccessor(){return Q1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class cG extends g{static getFacadeAccessor(){return pG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class uG extends g{static getFacadeAccessor(){return dG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class lG extends g{static getFacadeAccessor(){return c3}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 hC($){return $}function iG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function Z8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function bJ($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:fO}=globalThis.Bun;function kO(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var wO=async($)=>{let Z=new fO($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},qO=async($)=>{let Z;try{Z=(await import("./chunk-tms2g9at.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},sG=($)=>kO()?wO($):qO($);var yO=/^[A-Za-z_][A-Za-z0-9_]*$/;class RJ{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!yO.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??sG}async createTable(){for(let $ of vO(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return nG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
23
+ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function aD($){return`'sha256-${dD("sha256").update($).digest("base64")}'`}var zJ,XJ=new Map;function rD(){if(zJ===void 0){let $=GJ(QJ(),"dist","server",iD);zJ=jG($)?JSON.parse(uD($,"utf8")):null}return zJ??null}async function KJ($){nD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=rD()?.[$];if(j!==void 0)return j;let z=XJ.get($);if(z)return z}let J=GJ(QJ(),"app"),W=oD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${zG}.ts (or .js).`);if(!Z)return YG(W);let Y=YG(W);return XJ.set($,Y),Y.catch(()=>XJ.delete($)),Y}async function yI($){return aD(await KJ($))}var tD="gemi-islands",uI=`'sha256-${QG("sha256").update(VJ).digest("base64")}'`;function BJ($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var FJ=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),lI=`'sha256-${QG("sha256").update(jJ).digest("base64")}'`,eD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',$O="gemi-static";function GG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let D=U.module?J(U.module):void 0;if(!D)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let O of D.preload)z.add(O);if(U.preloadDynamic)for(let O of D.dynamicPreload??[])z.add(O)}return{s:D.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${XG}="${FJ(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return BJ($,"</head>",G,!1);let F=(Y?`<meta name="${$O}" content="${FJ(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${FJ(U)}"/>`).join("")+G,K=Y?jJ:VJ,V=(Q?`<script type="application/json" id="${tD}">${G1({i:X})}</script>`:"")+`<script type="module">${W?eD+K:K}</script>`;return BJ(BJ($,"</head>",F,!1),"</body>",V,!0)}function ZO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function KG($){let Z=`<template ${JG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=ZO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${l3} ${ZG}="${j}" style="display:contents"></${l3}>`;$=$.split(Q).join(`<${l3} style="display:contents">${X}</${l3}>`)}return $}function BG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function FG($,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 JO=async()=>(await import("./chunk-44y62yav.js")).default,UJ,i3=async(...$)=>{return UJ??=import("react-dom/server.browser").catch((Z)=>{throw UJ=void 0,Z}),(await UJ).renderToReadableStream(...$)},UG=1e4,DG="no-locale",WO="no-theme";async function YO($,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 LJ="/assets";function jO($){return $===LJ||$.startsWith(`${LJ}/`)}function zO($){let Z=$.filter(jO);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 "${LJ}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function XO($){let Z=H(Y1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function DJ($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function QO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class s3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=rQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;defaultMeta;constructor($,Z={}){let J=MQ();this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":BQ(Z)};this.requiredViews=Object.fromEntries(GQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=c4(W),zO(Object.keys(this.flatViewRoutes)),this.routeManifest=u4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=i4(W),this.flatComponentTree=JJ(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}this.root=$.root}async passesFeatureGates($){let Z=H(r1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)s4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{n$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>g1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=OJ(),F=new AbortController,K=setTimeout(()=>F.abort(),UG),V=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},U=$G(async(D,O)=>{let L=await i3(D,{signal:F.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:V});return await L.allReady.catch(()=>{}),await new Response(L).text()});try{let D,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)D={name:O,source:await KJ(O)};let L;if(W.navigation){let _=W.navigation===!0?{}:W.navigation,A=_.version?String(await J(()=>_.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",D?.name??"",A].join("|"),prefetch:_.prefetch==="none"?"none":"intent"}}let T=await i3(g1(WG.Provider,{value:U,children:g1(VG,{children:[...G,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:V});await T.allReady.catch(()=>{});let P=KG(await new Response(T).text());return new Response(GG(P,U,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,D),{status:200,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:F,noTheme:K,url:V,user:U,viewData:D,breadcrumbs:O,urlLocaleSegment:L,meta:T,isOgRequest:P,appId:_,features:A,staticView:E}=$,S=this.theme===!1||K||E?null:{cookie:this.theme.cookie??m9,default:this.theme.default??null,value:GO(Z,this.theme.cookie??m9)},f=L?nQ(Q,[L]).pathname:Q,M={kind:"view",data:{meta:T,pageData:{[f]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:U},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:V.search,is404:!Y?!0:!1,domain:Z.domain?XO(Z):null},appId:_,features:A,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},I=this.root,y=this.routeManifest[Y];return async(H$)=>{let{bootstrapModules:T0=[],loaders:h1,getStyles:i,viewImportMap:q,cssManifest:N0,ogMap:t$,viewModules:o3,clientEntry:M$,modulePreloadManifest:p1,assetBase:c1,resolveIsland:e$,buildId:o}=H$,eZ=M$?[]:T0,a3=(k0)=>[k0,`window.loaders=${h1}`,...M$?[`import(${JSON.stringify(M$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let k0=null,JZ=null;for(let WZ of y??[])if(typeof t$[WZ]==="function")JZ=WZ,k0=t$[WZ];if(!k0)return new Response("Not found",{status:404});let PK=Object.values(M.data.pageData)[0];try{await i3(g1(k0,PK[JZ]),{onError:()=>{}})}catch(WZ){let{fonts:TK,...NK}=WZ.satoriOptions,IK=await Promise.all(TK.map((r3)=>{return YO(r3.name,r3.weight,r3.style).then((SK)=>({...r3,data:SK}))})),nJ=new Headers(j);nJ.set("Content-Type","image/png");let[_K,xK]=await Promise.all([JO(),h4("Rendering an OG image")]),CK=await _K(WZ.jsx,{...NK,fonts:IK}),AK=await xK(Buffer.from(CK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(AK),{headers:nJ})}return new Response("data")}if(E&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:E,currentViews:y,data:M.data,serverQueries:G,headers:j,getStyles:i,viewImportMap:q,viewModules:o3,resolveIsland:e$,buildId:o});if(M.data.cssManifest=N0,M.data.modulePreloadManifest=p1??{},c1&&c1!=="/")M.data.assetBase=c1;if(o&&o!=="dev")M.data.buildId=o;let $Z=this.modulePreloadLinks({clientEntry:M$,modulePreloadManifest:p1,views:y??["404"],routeKey:Y??"404"}),$3=await i(y??["404"]);M.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let d1=new AbortController,P$=setTimeout(()=>d1.abort(),UG),R=H6(B)||F,f0=Bun.env.NODE_ENV!=="production"&&!R&&Y&&this.shellReporter.shouldObserve(Y)?tQ():null,ZZ=OJ();try{let k0=await i3(g1(VG,{children:[...$Z,...$3,...S?[g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:IQ(G1({cookie:S.cookie,default:S.default}))}})]:[],g1(I,{data:M.data,viewImportMap:q,viewModules:o3,serverQueries:G,dictionarySink:ZZ,key:"root"})]}),{bootstrapScriptContent:a3(`window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:eZ,signal:d1.signal,...R?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(JZ){if(Bun.env.NODE_ENV!=="production")console.error(JZ)}});if(k0.allReady.catch(()=>{}).finally(()=>clearTimeout(P$)),R)await k0.allReady.catch(()=>{});return new Response(u8(k0,G,{onShell:R?void 0:()=>G.markShell(),onChunk:f0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(d1.signal.aborted)),f0)this.shellReporter.report(Y,f0.measure())})},ZZ),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(k0){if(clearTimeout(P$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted))),k0;let JZ=await i3(g1("div"),{bootstrapScriptContent:a3(`window.error= ${G1(k0.message)}; window.stack_trace=${G1(k0.stack)};window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...eZ]:eZ});return new Response(u8(JZ,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(N$(Z))return 404;if(Z?.kind===s1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(n1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,B=null,F=H(d),K=d3(this.flatViewRoutes,j),V=F.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(DG);if(V&&F.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let M=J.pathname.replace(/\/+$/,""),I=V&&F.supportedLocales.includes(M.slice(1));if(M&&!I)return new Response("",{status:301,headers:{Location:`${M}${J.search}`}})}if(V&&!Y&&B===null&&!(B===null&&K!==null)){let M=OG(z,F.supportedLocales,F.defaultLocale);if(M){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:`/${M}${I}${W?".json":""}${J.search}`}})}}if(V&&!Y){let M=H(d).detectLocale(new C($,{},"view",Q));if(B===null&&M!==F.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:`/${M}${I}${J.search}`}})}}Q=Q.replace("//","/");let D=[],O=[],L=null,T={},P=null,_=!1,A=!1,E=[],S;try{let M=d3(this.flatViewRoutes,Q);if(B&&M?.route.middleware.includes(DG))M=null;if(M){if(L=M.routePath,T=M.params,D=M.route.exec,O=M.route.middleware,E=M.route.features,_=O.includes("no-stream"),A=O.includes(WO),S=M.route.static,W&&this.partialRendering){let I=$.headers.get(ZJ),y=sQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(d).supportedLocales,from:I,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),P={from:I,carriedViews:y.carriedViews}}}}catch(M){throw M}if(S&&W)return new Response("Not found",{status:404});let f=new C($,T,"view",L);return this.hooks.onRequestStart(f),await N.run(f,async()=>{let M=null,I=N.getStore(),y=nZ.getStore(),H$=(q)=>nZ.run(y,()=>N.runWith(I,q));I.serverQueries=new iZ(u3($));let T0=new Set;I.serverQueries.onQueryFail((q)=>{T0.add(q.error);try{H$(()=>Promise.resolve(this.hooks.onRequestFail(i,q.error)).catch(()=>{}))}catch{}});let h1=BG(S);if(B){let q=B.replaceAll("/","");L$.setLocale(q,{cookie:h1.locale})}else if(F.isLocaleAware&&!V)I.setLocale(F.defaultLocale);else L$.setLocale(void 0,{cookie:h1.locale});let i=I.req;if(h1.session)s4();try{let q=null;try{await H(i1).runMiddleware(O)}catch(R){if(q=this.viewRefusalStatus(i,R,T0),q===null)throw R}if(q!==null||E.length>0&&!await this.passesFeatureGates(E))L=null,D=[],i.routePath="";let N0=H(d),t$=N0.isEnabled,o3=N0.isLocaleAware,M$=new C($,i.params),p1={defaultLocale:N0.defaultLocale,timeZone:N0.detectTimeZone(M$)};if(o3){let R=null;if(B)R=B.replaceAll("/",""),I.setLocale(R);else if(!V)R=I.locale??N0.defaultLocale;else R=N0.detectLocale(M$),I.setLocale(R);let f0=t$?N0.getPageTranslations(R,i.routePath):{};p1={...p1,supportedLocales:N0.supportedLocales,currentLocale:R,dictionary:{[R]:f0},defaultLocale:N0.defaultLocale,...V?{}:{localeRouting:"off"}}}await LG(p1.currentLocale??"");let c1;try{c1=await Promise.all(D.map((R)=>R(i)))}catch(R){if(q=this.viewRefusalStatus(i,R,T0),q===null)throw R;L=null,D=[],i.routePath="",c1=[]}if(L===null)await this.hooks.onNotFound(i,{status:q??404});if(this.defaultMeta&&!I.metadata.hasAllDefaultFields)I.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);let{cookies:e$,headers:o}=I;if(q!==null)o.set("Cache-Control","no-store");M={data:c1,cookies:e$,headers:o,user:I.user,prefetchedData:I.serverQueries.snapshotResolved(),currentPathName:L,params:i.params,urlLocaleSegment:G,meta:I.renderMeta(),appId:H(WJ).id,features:await H(r1).forClient()};let{params:eZ,user:a3}=M,$Z={},$3={};for(let R of c1??[]){let[f0,ZZ]=Object.entries(R)?.[0]??[];if(!f0||!ZZ)continue;$3[`${f0}:${L}`]=ZZ.breadcrumb,$Z[f0]=ZZ}let d1=$Z.FILE;if(d1){for(let R of e$)o.append("Set-Cookie",R.toString());try{await this.onRequestEnd(i)}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await T8(d1,o)}if(W){o.set("Content-Type","application/x-ndjson; charset=utf-8"),o.append("Vary",ZJ),e$.forEach((f0)=>o.append("Set-Cookie",f0.toString())),await this.hooks.onRequestEnd(i);let R={meta:P&&!I.metadata.touched?null:M.meta,data:{[Q]:$Z},breadcrumbs:$3,prefetchedData:I.serverQueries.snapshotResolved(),i18n:p1,features:M.features,is404:!L,appId:M.appId,partial:P};return new Response(eQ(R,I.serverQueries,void 0,({aborted:f0})=>H$(()=>this.completeStream(i,I.serverQueries.summarize(f0)))),{headers:o})}if(o.set("Content-Type","text/html; charset=utf-8"),!_&&!(S&&L))o.append("Vary","User-Agent");let P$=Boolean(S&&L);if(!P$||h1.session)s4();for(let R of e$)o.append("Set-Cookie",R.toString());if(!P$||h1.csrf){let R=Bun.CSRF.generate(process.env.SECRET);o.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!P$||h1.session})}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(P$)FG(o,S);return await this.render({req:i,runInRequestScope:H$,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:o,i18n:p1,params:eZ,pathname:J.pathname,serverQueries:I.serverQueries,userAgent:$.headers.get("user-agent"),noStream:_,noTheme:A,url:J,user:a3,viewData:$Z,breadcrumbs:$3,urlLocaleSegment:G,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:L?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===s1){let N0=W?QO(q.payload.viewData??q.payload.api):DJ(q.payload.view);for(let t$ of I.cookies)N0.headers.append("Set-Cookie",t$.toString());return N0}if(!T0.has(q))this.hooks.onRequestFail(i,q);if(n1(q))return console.error(q),W?sZ():DJ(YJ());if(q instanceof v1&&q.status===403)return W?sZ():DJ(YJ());throw q}},Z)}}function GO($,Z){let J=$.cookies?.get(Z);return NQ(J)?J:null}function HJ(){let $=JSON.stringify({error:o1("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 NG extends I0{routes={"/api-routes":this.get(()=>{let $=H(o4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(s3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var KO=new Set([l1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),BO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,FO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function VO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(KO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===l1)throw Error(`dispatchAs: credentials may not set the "${l1}" cookie. The access token stays the initiator's.`);if(!BO.test(Y)||!FO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function UO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function HG($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function MG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function DO(){return Bun.env.NODE_ENV==="development"}class o4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=HQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=y9({"/":$.rootRouter,"/auth":b9,"/__gemi__/services/i18n":R9,"/__gemi__/services/image":w9,...DO()?{"/__gemi__/services/logs":q9,"/__gemi__/debug":NG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=TG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(i1).runMiddleware(W)}catch(Y){if(Y.kind===s1)return HG(Y.payload.api);else{if(N$(Y))return HJ();if(this.onRequestFail(Z,Y),console.error(Y),n1(Y))return sZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===s1)return HG(j.payload.api);if(N$(j))return HJ();if(this.onRequestFail(J.req,j),console.error(j),n1(j))return sZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){n$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:o1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=H(d);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(i1).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let D=MG(B,z.headers,z.cookies);return await Q(),D}let F=await this.getRouteData(W),K=z.headers,V=z.cookies;if(F instanceof Response){let D=MG(F,K,V);if(this.isOpenEndedBody($,D)){let O=UO(D,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),D}let U=(u1(F)?F:j1.json(F)).toResponse(K,V);return await Q(),U}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],F=Q?null:$.cookies.get(l1);if(F)B.push(`${l1}=${F}`);if(Y?.credentials)VO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(l1);if(K)G.set(l1,K);let V=$.headers.get("User-Agent");if(V)G.set("User-Agent",V);let U;if(W instanceof FormData)U=W;else if(W!==void 0)G.set("Content-Type","application/json"),U=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:U,...Y?.signal?{signal:Y.signal}:{}});if(PG(D,GZ($),Q?.grant,Y?.progress),$.domain)oZ(D,$.domain);let O=Q?{user:Q.user}:void 0;return N.exit(()=>Y6.exit(()=>this.handleApiRequest(D,O)))}}import{timingSafeEqual as OO}from"crypto";var t4="",TJ="*",LO=60000,HO=1e4,PJ=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,a4=16,MJ=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r4="x-forwarded-host";function IG($){return $.startsWith(":")}function aZ($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&OO(J,W)}function MO($){if(!$)return null;if($===!0)return{header:r4,clientIpHeader:null,secret:null};return{header:($.hostHeader??r4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function PO($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!MJ.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!==void 0){if(typeof J!=="string"||!MJ.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!MJ.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<a4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${a4} characters. A guessable one lets any client name its own host.`)}function M1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function TO($){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 NO($){let Z=M1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>PJ.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<a4)throw Error(`\`route.domains.ask.secret\` must be at least ${a4} characters. A guessable one is worse than leaving \`ask\` out.`);PO($.trustProxy);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),IG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>PJ.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class NJ{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){NO($),this.root=M1($.root),this.hostTrust=MO($.trustProxy);for(let Z of $.groups??[])if(IG(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??LO,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:_$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return M1(this.forwardedHost($))??M1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&M1(Y)?TO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:TJ,params:{},custom:!0};return null}async allows($,Z){let J=M1($);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:t4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&PJ.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=HO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=M1($);if(Z)this.cache.delete(Z)}}}var IO={kind:"none"};function Ux($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return IO;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function Dx($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:_$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _G=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xG=16;function Ox($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!_G.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_G.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<xG)throw Error(`GEMI_PROXY_SECRET must be at least ${xG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function CG($,Z){if(!aZ($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:_$(J)}var _O="/__gemi__/domains/ask";class Y1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;constructor($,Z){this.groups.set(t4,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new NJ(J);let W=(Y)=>({api:Y.api?new o4({...Z.api,...Y.api}):$.api,view:Y.view?new s3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(TJ,W(J.custom.fallback))}applyClientIp($){let Z=this.clientIpTrust;if(Z)IJ($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?CG($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)IJ($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return oZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==_O)return null;if(!aZ(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??t4)}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 rZ($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var AG=600000;function SG($,Z){return[U6($,Z),U6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new o8){LY($.oauthProviders),this.config={...L1(HY($),$),emailCode:d8($.emailCode)},this.provider=Z}async oauthProvider($){return await DZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await fY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Y1)?H(Y1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Y1).resolver?.root:M1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??M1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!v8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=rZ(J.expiresAt),j=rZ(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/AG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=U6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of SG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(v8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/AG),W=SG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=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())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new I$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=jY(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:FY(Z),Q=D6("link",$,j),G=D6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((V)=>rZ(V.createdAt)+B>Date.now()&&V.pin!==G&&V.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((V)=>V.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return VZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>rZ(G.createdAt)+W*60000>Date.now());if(z.length===0)return VZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await DY(G.id,rZ(G.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let Q=null;for(let G of z)if(VZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return VZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(VZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(rZ(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class w0 extends g{static getFacadeAccessor(){return b}static async user(){let $=await w0.userOrNull();if($)return $;throw new I$({redirectTo:z6(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await Z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return X1(Z?.search.get(z1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new KZ}static async guardSafe($){let Z=await w0.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 e4{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 iZ(u3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=e4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){e4.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 iZ(u3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function xO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function _J($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?xO(z):encodeURIComponent(String(z))}`});return`${$8}${J==="/"?"":J}`||$8}var EG=new Map;function bG($,Z){let J=EG.get($);if(!J)J=new URLPattern({pathname:`${$8}${$==="/"?"":$}`}),EG.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function RG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=CO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function CO($){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 fG{static origin($){return xJ($)}static absolute($,...Z){return`${l$()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Y1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):l$();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return RG({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}static api($,...Z){return _J(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${xJ()}${_J(String($),Z[0]??{})}`}static matchApi($,Z){return bG(String($),Z)}}class kG{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 robots($){N.getStore().metadata.robots($)}static fonts($){N.getStore().metadata.fonts($)}}var AO={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 m1 extends g{static getFacadeAccessor(){return o$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function VC($){return $}function wG(){return{store:"memory",ttl:null}}class CJ{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var SO="500";class AJ{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${EO(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",SO]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(o$)?$.make(o$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function EO($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var bO="k:",qG="tag:",RO="t:";class SJ{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class EJ extends SJ{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=L1(wG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)a$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new vG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return bO+gG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=qG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=yG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(qG+Z,yG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:a$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new CJ(this.config.memory);if($==="redis"){let Z=this.options.application;return new AJ({...this.config.redis,client:Z?{send:(J,W)=>Z.make(o$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class vG extends SJ{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${RO}${Z.join(",")}:${$}`}}function gG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function yG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class mG extends g{static getFacadeAccessor(){return EJ}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class hG extends g{static getFacadeAccessor(){return Q1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class cG extends g{static getFacadeAccessor(){return pG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class uG extends g{static getFacadeAccessor(){return dG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class lG extends g{static getFacadeAccessor(){return c3}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 pC($){return $}function iG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function Z8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function bJ($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:fO}=globalThis.Bun;function kO(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var wO=async($)=>{let Z=new fO($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},qO=async($)=>{let Z;try{Z=(await import("./chunk-777v6242.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},sG=($)=>kO()?wO($):qO($);var yO=/^[A-Za-z_][A-Za-z0-9_]*$/;class RJ{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!yO.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??sG}async createTable(){for(let $ of vO(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return nG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
24
24
  INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
25
25
  ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
26
26
  RETURNING seq
@@ -49,7 +49,7 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
49
49
  )`]}class fJ{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($),Y=W?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!W||Z===Y)return{entries:[],head:Y,gap:!1};let j=W.entries[0]?.seq??Y+1;if(j>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-j;return{entries:W.entries.slice(z,z+J),head:Y,gap:!1}}}var eG=new TextEncoder;function oG($,Z){return eG.encode(`id: ${$}
50
50
  data: ${JSON.stringify(Z)}
51
51
 
52
- `)}function $K($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(B){if(!(B instanceof J8))throw B;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,Q=!1,G=!1,K=(B)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{B.close()}catch{}},F=new ReadableStream({start(B){X=setInterval(()=>{if(tG())return K(B);try{B.enqueue(eG.encode(aG))}catch{K(B)}},$.config.keepaliveInterval)},async pull(B){try{if(!Q){if(await z.ready(),Q=!0,!G)B.enqueue(oG(z.cursor,{type:"ready"}));return}let U=await z.next();if(U.done||G)return K(B);B.enqueue(oG(z.cursor,U.value))}catch(U){if(!G)console.error("[gemi] A change feed stream failed.",U);K(B)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(F,{headers:rG()})}var ZK=255,JK=500,gO=30000;class J8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class tZ{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=JK;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=L1(iG(),$),this.driver=hO(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){wJ($);let J=Z===void 0?null:Z;if(d0()!==void 0&&!this.driver.joinsTransaction?.())return pZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return pZ(()=>this.wake($,W)),W}async head($){return wJ($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=kJ($);return Z8(await this.driver.heads(Z))}subscribe($,Z={}){let J=kJ($);if(this.all.size>=this.config.maxSubscriptions)throw new J8(this.config.maxSubscriptions);let W=new WK(this,J,mO(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return $K(this,$,kJ(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,Y]of J)this.wake(W,Y)}}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=JK,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,gO)}}}class WK{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,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return Z8(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:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});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 wJ($){if(typeof $!=="string"||$===""||$.length>ZK)throw Error(`A change feed channel is a string of 1 to ${ZK} characters; got ${JSON.stringify($)}.`)}function kJ($){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)wJ(J);return Z}function mO($){if($===void 0||$===null)return new Map;if(typeof $==="string")return bJ($);let Z=$ instanceof Map?[...$]:Object.entries($);return bJ(Z8(new Map(Z)))}function hO($,Z){if($==="memory")return new fJ;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 RJ(Z.make(C1));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 YK extends g{static getFacadeAccessor(){return tZ}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 n3 extends p0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(p0)?$.make(p0):void 0;if(Z instanceof n3)return Z;let J=new n3($,Z);return $.instance(p0,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(p0,this.previous);return}this.application.forget(p0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${qJ($,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 ${qJ($,Z,J)} not to have been broadcast, but it was broadcast ${yJ(W.length)}: ${vJ(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${qJ($,J,W)} to have been broadcast ${yJ(Z)}, but it was broadcast ${yJ(Y.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"}: ${vJ(this.sent)}.`)}matching($,Z,J){return zZ($),this.sent.filter((W)=>(W.pattern===$||UW($,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: ${vJ(this.sent)}.`}}function qJ($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function yJ($){return`${$} ${$===1?"time":"times"}`}function vJ($){return $.map((Z)=>`${Z.topic} ${Z.event}(${pO(Z.data)})`).join(", ")}function pO($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class jK extends g{static getFacadeAccessor(){return p0}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 n3.install(H())}}function MA($){return $}function zK(){return{store:"memory",sweepLimit:500}}var gJ=["completed","failed","cancelled","timed_out"],P1=["pending","running"];function T1($){return gJ.includes($)}class mJ{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,hJ($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(T1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(P1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function hJ($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class dJ{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of cO(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
52
+ `)}function $K($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(K){if(!(K instanceof J8))throw K;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,Q=!1,G=!1,B=(K)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{K.close()}catch{}},F=new ReadableStream({start(K){X=setInterval(()=>{if(tG())return B(K);try{K.enqueue(eG.encode(aG))}catch{B(K)}},$.config.keepaliveInterval)},async pull(K){try{if(!Q){if(await z.ready(),Q=!0,!G)K.enqueue(oG(z.cursor,{type:"ready"}));return}let V=await z.next();if(V.done||G)return B(K);K.enqueue(oG(z.cursor,V.value))}catch(V){if(!G)console.error("[gemi] A change feed stream failed.",V);B(K)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(F,{headers:rG()})}var ZK=255,JK=500,gO=30000;class J8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class tZ{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=JK;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=L1(iG(),$),this.driver=hO(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){wJ($);let J=Z===void 0?null:Z;if(d0()!==void 0&&!this.driver.joinsTransaction?.())return pZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return pZ(()=>this.wake($,W)),W}async head($){return wJ($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=kJ($);return Z8(await this.driver.heads(Z))}subscribe($,Z={}){let J=kJ($);if(this.all.size>=this.config.maxSubscriptions)throw new J8(this.config.maxSubscriptions);let W=new WK(this,J,mO(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return $K(this,$,kJ(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,Y]of J)this.wake(W,Y)}}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=JK,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,gO)}}}class WK{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,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return Z8(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:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});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 wJ($){if(typeof $!=="string"||$===""||$.length>ZK)throw Error(`A change feed channel is a string of 1 to ${ZK} characters; got ${JSON.stringify($)}.`)}function kJ($){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)wJ(J);return Z}function mO($){if($===void 0||$===null)return new Map;if(typeof $==="string")return bJ($);let Z=$ instanceof Map?[...$]:Object.entries($);return bJ(Z8(new Map(Z)))}function hO($,Z){if($==="memory")return new fJ;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 RJ(Z.make(C1));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 YK extends g{static getFacadeAccessor(){return tZ}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 n3 extends p0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(p0)?$.make(p0):void 0;if(Z instanceof n3)return Z;let J=new n3($,Z);return $.instance(p0,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(p0,this.previous);return}this.application.forget(p0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${qJ($,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 ${qJ($,Z,J)} not to have been broadcast, but it was broadcast ${yJ(W.length)}: ${vJ(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${qJ($,J,W)} to have been broadcast ${yJ(Z)}, but it was broadcast ${yJ(Y.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"}: ${vJ(this.sent)}.`)}matching($,Z,J){return zZ($),this.sent.filter((W)=>(W.pattern===$||UW($,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: ${vJ(this.sent)}.`}}function qJ($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function yJ($){return`${$} ${$===1?"time":"times"}`}function vJ($){return $.map((Z)=>`${Z.topic} ${Z.event}(${pO(Z.data)})`).join(", ")}function pO($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class jK extends g{static getFacadeAccessor(){return p0}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 n3.install(H())}}function PA($){return $}function zK(){return{store:"memory",sweepLimit:500}}var gJ=["completed","failed","cancelled","timed_out"],P1=["pending","running"];function T1($){return gJ.includes($)}class mJ{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,hJ($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(T1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(P1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function hJ($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class dJ{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of cO(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
53
53
  INSERT INTO ${this.name(Z)}
54
54
  (id, kind, subject, owner, status, meta, version,
55
55
  created_at, started_at, updated_at, deadline_at)
@@ -112,6 +112,6 @@ data: ${JSON.stringify(Z)}
112
112
  "updated_at" BIGINT NOT NULL,
113
113
  "finished_at" BIGINT,
114
114
  "deadline_at" BIGINT${W}
115
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GK=191,KK=30000;class z8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class X8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class uJ{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=L1(zK(),$),this.store=lO(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(tZ);return this.ownFeed??=new tZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){VK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;VK("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:a$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return uO(Z),this.change($,P1,{status:"running",progress:Z})}complete($,Z){return this.change($,P1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,P1,{status:"failed",error:FK(Z)})}cancel($,Z){return this.change($,P1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new z8($);if(T1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof X8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,P1,{status:"failed",error:Q instanceof X8?FK(Q):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+a$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new z8($);let z=null;for(;;){if(T1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BK(z,Math.min(Q,X??1/0,KK),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new z8($);if(yield W,T1(W.status))return;for await(let Y of J){let j=dO(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,T1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=a$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||T1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,P1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(T1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BK(j,Math.min(z??1/0,KK))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function dO($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function FK($){if(typeof $==="string")return{message:$};if($ instanceof X8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function VK($,Z){if(typeof Z!=="string"||Z===""||Z.length>GK)throw TypeError(`A run's ${$} is a string of 1 to ${GK} characters; got ${JSON.stringify(Z)}.`)}function uO($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function lO($,Z){if($==="memory")return new mJ;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(C1).connection();return new dJ(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UK extends g{static getFacadeAccessor(){return uJ}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class DK extends g{static getFacadeAccessor(){return r1}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 sJ{value;constructor($){this.value=$}}var iO=/^[A-Za-z_][A-Za-z0-9_$]*$/;function sO($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!iO.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class Q8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}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 iJ(J.sql,(W)=>lJ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=sO(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(d0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await iJ(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await lJ(j,()=>W(X));throw new sJ(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof sJ)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-xed7yf6h.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=HK($,LK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=d0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return OK($),H(C1).connection($)}}var r$=new Q8;class MK extends g{static getFacadeAccessor(){return C1}static connection($){return new Q8($)}static get sql(){return r$.sql}static get dialect(){return r$.dialect}static query($){return r$.query($)}static execute($){return r$.execute($)}static transaction($){return r$.transaction($)}static readOnly($,Z){return r$.readOnly($,Z)}static schema(){return r$.schema()}static close(){return this.getFacadeRoot().close()}}export{j1 as he,bK as ie,s0 as je,Z3 as ke,F8 as le,jZ as me,W3 as ne,I0 as oe,Z6 as pe,y8 as qe,v8 as re,jY as se,a1 as te,Q1 as ue,_$ as ve,t as we,vW as xe,GZ as ye,zY as ze,XY as Ae,m8 as Be,h8 as Ce,D6 as De,VZ as Ee,dB as Fe,FP as Ge,HY as He,xY as Ie,l8 as Je,CY as Ke,AY as Le,rB as Me,SY as Ne,i8 as Oe,$F as Pe,ZF as Qe,s8 as Re,EY as Se,bY as Te,r1 as Ue,RY as Ve,jF as We,o8 as Xe,I8 as Ye,X6 as Ze,N1 as _e,T8 as $e,I1 as af,L$ as bf,e4 as cf,fG as df,kG as ef,AO as ff,m1 as gf,FC as hf,wG as if,CJ as jf,AJ as kf,EJ as lf,vG as mf,mG as nf,hG as of,cG as pf,uG as qf,lG as rf,hC as sf,iG as tf,Z8 as uf,bJ as vf,RJ as wf,fJ as xf,J8 as yf,tZ as zf,WK as Af,YK as Bf,p as Cf,Y3 as Df,f4 as Ef,aP as Ff,rP as Gf,tP as Hf,JT as If,vX as Jf,T9 as Kf,hX as Lf,XT as Mf,dX as Nf,p0 as Of,m3 as Pf,uX as Qf,jK as Rf,MA as Sf,gJ as Tf,P1 as Uf,T1 as Vf,mJ as Wf,dJ as Xf,cO as Yf,z8 as Zf,X8 as _f,uJ as $f,UK as ag,DK as bg,Q8 as cg,MK as dg,I9 as eg,JD as fg,f9 as gg,k9 as hg,LN as ig,FQ as jg,OQ as kg,J6 as lg,i1 as mg,fN as ng,HQ as og,MQ as pg,WJ as qg,sZ as rg,YJ as sg,qI as tg,dI as ug,uI as vg,LJ as wg,jO as xg,DJ as yg,QO as zg,s3 as Ag,HJ as Bg,HG as Cg,MG as Dg,o4 as Eg,Vx as Fg,Ux as Gg,Dx as Hg,Y1 as Ig,b as Jg,w0 as Kg,W6 as Lg,MW as Mg,uK as Ng,OW as Og,TW as Pg,H8 as Qg,j6 as Rg,M8 as Sg,NW as Tg,rK as Ug,tK as Vg,SW as Wg,bW as Xg,fW as Yg,mW as Zg,hW as _g,pW as $g,A8 as ah,YB as bh,W0 as ch,tW as dh,BZ as eh,WY as fh};
115
+ )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GK=191,KK=30000;class z8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class X8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class uJ{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=L1(zK(),$),this.store=lO(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(tZ);return this.ownFeed??=new tZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){VK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;VK("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:a$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return uO(Z),this.change($,P1,{status:"running",progress:Z})}complete($,Z){return this.change($,P1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,P1,{status:"failed",error:FK(Z)})}cancel($,Z){return this.change($,P1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new z8($);if(T1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof X8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,P1,{status:"failed",error:Q instanceof X8?FK(Q):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+a$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new z8($);let z=null;for(;;){if(T1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BK(z,Math.min(Q,X??1/0,KK),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new z8($);if(yield W,T1(W.status))return;for await(let Y of J){let j=dO(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,T1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=a$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||T1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,P1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(T1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BK(j,Math.min(z??1/0,KK))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function dO($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function FK($){if(typeof $==="string")return{message:$};if($ instanceof X8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function VK($,Z){if(typeof Z!=="string"||Z===""||Z.length>GK)throw TypeError(`A run's ${$} is a string of 1 to ${GK} characters; got ${JSON.stringify(Z)}.`)}function uO($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function lO($,Z){if($==="memory")return new mJ;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(C1).connection();return new dJ(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UK extends g{static getFacadeAccessor(){return uJ}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class DK extends g{static getFacadeAccessor(){return r1}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 sJ{value;constructor($){this.value=$}}var iO=/^[A-Za-z_][A-Za-z0-9_$]*$/;function sO($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!iO.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class Q8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}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 iJ(J.sql,(W)=>lJ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=sO(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(d0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await iJ(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await lJ(j,()=>W(X));throw new sJ(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof sJ)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-hgpvfhtp.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=HK($,LK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=d0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return OK($),H(C1).connection($)}}var r$=new Q8;class MK extends g{static getFacadeAccessor(){return C1}static connection($){return new Q8($)}static get sql(){return r$.sql}static get dialect(){return r$.dialect}static query($){return r$.query($)}static execute($){return r$.execute($)}static transaction($){return r$.transaction($)}static readOnly($,Z){return r$.readOnly($,Z)}static schema(){return r$.schema()}static close(){return this.getFacadeRoot().close()}}export{j1 as ie,bK as je,s0 as ke,Z3 as le,F8 as me,jZ as ne,W3 as oe,I0 as pe,Z6 as qe,y8 as re,v8 as se,jY as te,a1 as ue,Q1 as ve,_$ as we,t as xe,vW as ye,GZ as ze,zY as Ae,XY as Be,m8 as Ce,h8 as De,D6 as Ee,VZ as Fe,dB as Ge,FP as He,HY as Ie,xY as Je,l8 as Ke,CY as Le,AY as Me,rB as Ne,SY as Oe,i8 as Pe,$F as Qe,ZF as Re,s8 as Se,EY as Te,bY as Ue,r1 as Ve,RY as We,jF as Xe,o8 as Ye,I8 as Ze,X6 as _e,N1 as $e,T8 as af,I1 as bf,L$ as cf,e4 as df,fG as ef,kG as ff,AO as gf,m1 as hf,VC as if,wG as jf,CJ as kf,AJ as lf,EJ as mf,vG as nf,mG as of,hG as pf,cG as qf,uG as rf,lG as sf,pC as tf,iG as uf,Z8 as vf,bJ as wf,RJ as xf,fJ as yf,J8 as zf,tZ as Af,WK as Bf,YK as Cf,p as Df,Y3 as Ef,f4 as Ff,aP as Gf,rP as Hf,tP as If,JT as Jf,vX as Kf,T9 as Lf,hX as Mf,XT as Nf,dX as Of,p0 as Pf,m3 as Qf,uX as Rf,jK as Sf,PA as Tf,gJ as Uf,P1 as Vf,T1 as Wf,mJ as Xf,dJ as Yf,cO as Zf,z8 as _f,X8 as $f,uJ as ag,UK as bg,DK as cg,Q8 as dg,MK as eg,I9 as fg,JD as gg,f9 as hg,k9 as ig,LN as jg,FQ as kg,OQ as lg,J6 as mg,i1 as ng,fN as og,HQ as pg,MQ as qg,WJ as rg,sZ as sg,YJ as tg,yI as ug,uI as vg,lI as wg,LJ as xg,jO as yg,DJ as zg,QO as Ag,s3 as Bg,HJ as Cg,HG as Dg,MG as Eg,o4 as Fg,Ux as Gg,Dx as Hg,Ox as Ig,Y1 as Jg,b as Kg,w0 as Lg,W6 as Mg,MW as Ng,uK as Og,OW as Pg,TW as Qg,H8 as Rg,j6 as Sg,M8 as Tg,NW as Ug,rK as Vg,tK as Wg,SW as Xg,bW as Yg,fW as Zg,mW as _g,hW as $g,pW as ah,A8 as bh,YB as ch,W0 as dh,tW as eh,BZ as fh,WY as gh};
116
116
 
117
- //# debugId=E0510070900DC23264756E2164756E21
117
+ //# debugId=46D81230158C9F7964756E2164756E21