gemi 0.125.0 → 0.126.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/connections/ConnectionsController.d.ts.map +1 -1
- package/dist/auth/oauth/GoogleOAuthProvider.d.ts +1 -1
- package/dist/auth/oauth/GoogleOAuthProvider.d.ts.map +1 -1
- package/dist/auth/oauth/InstagramOAuthProvider.d.ts +1 -1
- package/dist/auth/oauth/InstagramOAuthProvider.d.ts.map +1 -1
- package/dist/auth/oauth/XOAuthProvider.d.ts.map +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-hff9w6rt.js → chunk-094m8mj3.js} +2 -2
- package/dist/{chunk-hff9w6rt.js.map → chunk-094m8mj3.js.map} +1 -1
- package/dist/chunk-0arss2xy.js +5 -0
- package/dist/{chunk-rany5zgk.js.map → chunk-0arss2xy.js.map} +5 -4
- package/dist/{chunk-mmqnq1qh.js → chunk-0f0xxqhy.js} +3 -3
- package/dist/{chunk-mmqnq1qh.js.map → chunk-0f0xxqhy.js.map} +1 -1
- package/dist/chunk-15bmfr7f.js +5 -0
- package/dist/{chunk-tabsxzg9.js.map → chunk-15bmfr7f.js.map} +5 -4
- package/dist/{chunk-910p6ne6.js → chunk-1dzs05dc.js} +2 -2
- package/dist/{chunk-910p6ne6.js.map → chunk-1dzs05dc.js.map} +1 -1
- package/dist/{chunk-rmgkc3a2.js → chunk-1eb4p352.js} +2 -2
- package/dist/{chunk-rmgkc3a2.js.map → chunk-1eb4p352.js.map} +1 -1
- package/dist/{chunk-cwt8e782.js → chunk-1gd1ykgj.js} +3 -3
- package/dist/{chunk-cwt8e782.js.map → chunk-1gd1ykgj.js.map} +1 -1
- package/dist/{chunk-stn0a56e.js → chunk-1v368y9a.js} +2 -2
- package/dist/{chunk-stn0a56e.js.map → chunk-1v368y9a.js.map} +1 -1
- package/dist/{chunk-x2j84d06.js → chunk-28bby5pp.js} +2 -2
- package/dist/{chunk-x2j84d06.js.map → chunk-28bby5pp.js.map} +1 -1
- package/dist/{chunk-gp00enrk.js → chunk-3fyhd641.js} +1 -1
- package/dist/{chunk-ex41d03h.js → chunk-43faxwf5.js} +2 -2
- package/dist/{chunk-ex41d03h.js.map → chunk-43faxwf5.js.map} +1 -1
- package/dist/{chunk-ey1xrbaz.js → chunk-56ryda9y.js} +2 -2
- package/dist/{chunk-ey1xrbaz.js.map → chunk-56ryda9y.js.map} +1 -1
- package/dist/{chunk-t2t63wa0.js → chunk-5vvfcdpk.js} +2 -2
- package/dist/{chunk-t2t63wa0.js.map → chunk-5vvfcdpk.js.map} +1 -1
- package/dist/{chunk-p5df4pn7.js → chunk-62zn06wb.js} +2 -2
- package/dist/{chunk-p5df4pn7.js.map → chunk-62zn06wb.js.map} +1 -1
- package/dist/{chunk-3br5zr7a.js → chunk-7dzprr9b.js} +3 -3
- package/dist/{chunk-3br5zr7a.js.map → chunk-7dzprr9b.js.map} +1 -1
- package/dist/{chunk-erzfs4t2.js → chunk-7eerqsg2.js} +2 -2
- package/dist/{chunk-erzfs4t2.js.map → chunk-7eerqsg2.js.map} +1 -1
- package/dist/{chunk-z5nfve1k.js → chunk-7nfprr9v.js} +2 -2
- package/dist/{chunk-z5nfve1k.js.map → chunk-7nfprr9v.js.map} +1 -1
- package/dist/{chunk-1jcngq6w.js → chunk-7x2n788t.js} +3 -3
- package/dist/{chunk-1jcngq6w.js.map → chunk-7x2n788t.js.map} +1 -1
- package/dist/{chunk-rwmja4zs.js → chunk-84rbdyhe.js} +2 -2
- package/dist/{chunk-rwmja4zs.js.map → chunk-84rbdyhe.js.map} +1 -1
- package/dist/chunk-87bmhng2.js +5 -0
- package/dist/{chunk-1xmh61fg.js.map → chunk-87bmhng2.js.map} +1 -1
- package/dist/{chunk-c0qpv8x7.js → chunk-87jj7n9q.js} +2 -2
- package/dist/{chunk-c0qpv8x7.js.map → chunk-87jj7n9q.js.map} +1 -1
- package/dist/{chunk-hxn0s3zh.js → chunk-89swy5aq.js} +2 -2
- package/dist/{chunk-hxn0s3zh.js.map → chunk-89swy5aq.js.map} +1 -1
- package/dist/{chunk-y9f2see3.js → chunk-8df7fn7f.js} +3 -3
- package/dist/{chunk-y9f2see3.js.map → chunk-8df7fn7f.js.map} +1 -1
- package/dist/{chunk-bny9s44t.js → chunk-99z9d0sa.js} +2 -2
- package/dist/{chunk-bny9s44t.js.map → chunk-99z9d0sa.js.map} +1 -1
- package/dist/{chunk-by5gwr8x.js → chunk-9hhxy88x.js} +2 -2
- package/dist/{chunk-by5gwr8x.js.map → chunk-9hhxy88x.js.map} +1 -1
- package/dist/{chunk-yhht1j7f.js → chunk-9x0pgkns.js} +2 -2
- package/dist/{chunk-yhht1j7f.js.map → chunk-9x0pgkns.js.map} +1 -1
- package/dist/{chunk-dy58aztm.js → chunk-avfntxm1.js} +2 -2
- package/dist/{chunk-dy58aztm.js.map → chunk-avfntxm1.js.map} +1 -1
- package/dist/{chunk-h8w9mzjj.js → chunk-b2pdqxj3.js} +11 -11
- package/dist/{chunk-h8w9mzjj.js.map → chunk-b2pdqxj3.js.map} +3 -4
- package/dist/{chunk-j12hpdxk.js → chunk-bghxdjqv.js} +1 -1
- package/dist/{chunk-6vz75swk.js → chunk-bhbxhk9e.js} +2 -2
- package/dist/{chunk-6vz75swk.js.map → chunk-bhbxhk9e.js.map} +1 -1
- package/dist/{chunk-6q6bhkyf.js → chunk-c48gag78.js} +1 -1
- package/dist/{chunk-5fh4pvyt.js → chunk-c65rh4k8.js} +2 -2
- package/dist/{chunk-5fh4pvyt.js.map → chunk-c65rh4k8.js.map} +1 -1
- package/dist/chunk-cwpezdpw.js +57 -0
- package/dist/{chunk-eyptwf54.js.map → chunk-cwpezdpw.js.map} +10 -5
- package/dist/{chunk-6wgh7nk6.js → chunk-dm7mada7.js} +3 -3
- package/dist/{chunk-6wgh7nk6.js.map → chunk-dm7mada7.js.map} +1 -1
- package/dist/{chunk-1mxb44n9.js → chunk-ebdkmzm9.js} +2 -2
- package/dist/{chunk-1mxb44n9.js.map → chunk-ebdkmzm9.js.map} +1 -1
- package/dist/{chunk-xfvegbxn.js → chunk-ecb8qggy.js} +2 -2
- package/dist/{chunk-xfvegbxn.js.map → chunk-ecb8qggy.js.map} +1 -1
- package/dist/{chunk-p6jbmcrg.js → chunk-etf6h5m1.js} +2 -2
- package/dist/{chunk-p6jbmcrg.js.map → chunk-etf6h5m1.js.map} +1 -1
- package/dist/{chunk-zq5375wd.js → chunk-ewv1m1sv.js} +3 -3
- package/dist/{chunk-zq5375wd.js.map → chunk-ewv1m1sv.js.map} +1 -1
- package/dist/{chunk-dxyxd7b3.js → chunk-gv59djt3.js} +2 -2
- package/dist/{chunk-dxyxd7b3.js.map → chunk-gv59djt3.js.map} +1 -1
- package/dist/{chunk-8tvfmy1a.js → chunk-gxp48t81.js} +4 -4
- package/dist/{chunk-8tvfmy1a.js.map → chunk-gxp48t81.js.map} +1 -1
- package/dist/{chunk-r923001x.js → chunk-h4755p9h.js} +2 -2
- package/dist/{chunk-r923001x.js.map → chunk-h4755p9h.js.map} +1 -1
- package/dist/{chunk-q6ah4yjg.js → chunk-hye22tpt.js} +2 -2
- package/dist/{chunk-q6ah4yjg.js.map → chunk-hye22tpt.js.map} +1 -1
- package/dist/{chunk-eq5svwca.js → chunk-jg3kg55f.js} +2 -2
- package/dist/{chunk-eq5svwca.js.map → chunk-jg3kg55f.js.map} +1 -1
- package/dist/{chunk-s4semb89.js → chunk-k6gvbvyw.js} +1 -1
- package/dist/{chunk-vhvvjaj3.js → chunk-kzk5r6v4.js} +3 -3
- package/dist/{chunk-vhvvjaj3.js.map → chunk-kzk5r6v4.js.map} +1 -1
- package/dist/{chunk-ghcvztxn.js → chunk-m63v6aze.js} +2 -2
- package/dist/{chunk-ghcvztxn.js.map → chunk-m63v6aze.js.map} +1 -1
- package/dist/{chunk-khdkrfxp.js → chunk-mj4n5mar.js} +2 -2
- package/dist/{chunk-khdkrfxp.js.map → chunk-mj4n5mar.js.map} +1 -1
- package/dist/{chunk-kcsa57km.js → chunk-mj7h1dgh.js} +2 -2
- package/dist/{chunk-kcsa57km.js.map → chunk-mj7h1dgh.js.map} +1 -1
- package/dist/{chunk-cpem1j1x.js → chunk-mpt5jg4e.js} +2 -2
- package/dist/{chunk-cpem1j1x.js.map → chunk-mpt5jg4e.js.map} +1 -1
- package/dist/{chunk-3kxe9geg.js → chunk-n8mxsfc2.js} +3 -3
- package/dist/{chunk-3kxe9geg.js.map → chunk-n8mxsfc2.js.map} +1 -1
- package/dist/{chunk-n3z83qhq.js → chunk-nrf23yan.js} +2 -2
- package/dist/{chunk-n3z83qhq.js.map → chunk-nrf23yan.js.map} +1 -1
- package/dist/{chunk-sv125fqq.js → chunk-nv2t87c3.js} +2 -2
- package/dist/{chunk-sv125fqq.js.map → chunk-nv2t87c3.js.map} +1 -1
- package/dist/{chunk-j10a0m7q.js → chunk-p0ccxfkq.js} +1 -1
- package/dist/{chunk-crnfxn9n.js → chunk-p7abyc0b.js} +2 -2
- package/dist/{chunk-crnfxn9n.js.map → chunk-p7abyc0b.js.map} +1 -1
- package/dist/{chunk-hzen9gh4.js → chunk-psdyfaf1.js} +2 -2
- package/dist/{chunk-hzen9gh4.js.map → chunk-psdyfaf1.js.map} +1 -1
- package/dist/{chunk-knq4ack4.js → chunk-q9mxjh10.js} +2 -2
- package/dist/{chunk-knq4ack4.js.map → chunk-q9mxjh10.js.map} +1 -1
- package/dist/{chunk-7zj6bk9a.js → chunk-qmcjh6de.js} +2 -2
- package/dist/{chunk-7zj6bk9a.js.map → chunk-qmcjh6de.js.map} +1 -1
- package/dist/{chunk-k1ebt28j.js → chunk-qy3s6pwz.js} +2 -2
- package/dist/{chunk-k1ebt28j.js.map → chunk-qy3s6pwz.js.map} +1 -1
- package/dist/{chunk-j5rwv09s.js → chunk-ravssmdy.js} +2 -2
- package/dist/{chunk-j5rwv09s.js.map → chunk-ravssmdy.js.map} +1 -1
- package/dist/{chunk-rvspb96n.js → chunk-rtb64x14.js} +3 -3
- package/dist/{chunk-rvspb96n.js.map → chunk-rtb64x14.js.map} +1 -1
- package/dist/{chunk-ayfjjgv2.js → chunk-rvdsaqdv.js} +1 -1
- package/dist/{chunk-7vrrgxwm.js → chunk-s0kns9q1.js} +3 -3
- package/dist/{chunk-7vrrgxwm.js.map → chunk-s0kns9q1.js.map} +1 -1
- package/dist/{chunk-entpqjyn.js → chunk-s2krqtwj.js} +2 -2
- package/dist/{chunk-entpqjyn.js.map → chunk-s2krqtwj.js.map} +1 -1
- package/dist/{chunk-xe2pm36q.js → chunk-s2y2b8tz.js} +2 -2
- package/dist/{chunk-xe2pm36q.js.map → chunk-s2y2b8tz.js.map} +1 -1
- package/dist/{chunk-t6qpm2j7.js → chunk-t8kzaxaa.js} +2 -2
- package/dist/{chunk-t6qpm2j7.js.map → chunk-t8kzaxaa.js.map} +1 -1
- package/dist/{chunk-0x1s02r1.js → chunk-v1eeh7a7.js} +3 -3
- package/dist/{chunk-0x1s02r1.js.map → chunk-v1eeh7a7.js.map} +1 -1
- package/dist/{chunk-npbf06c1.js → chunk-v7nw1g2n.js} +2 -2
- package/dist/{chunk-npbf06c1.js.map → chunk-v7nw1g2n.js.map} +1 -1
- package/dist/{chunk-b7a22evs.js → chunk-v80890xx.js} +3 -3
- package/dist/{chunk-b7a22evs.js.map → chunk-v80890xx.js.map} +1 -1
- package/dist/{chunk-p7mvp5nf.js → chunk-w4111j5d.js} +2 -2
- package/dist/{chunk-p7mvp5nf.js.map → chunk-w4111j5d.js.map} +1 -1
- package/dist/{chunk-m7pghdcy.js → chunk-wat33wxh.js} +2 -2
- package/dist/{chunk-m7pghdcy.js.map → chunk-wat33wxh.js.map} +1 -1
- package/dist/{chunk-1n40bdxf.js → chunk-x5vpjzpp.js} +2 -2
- package/dist/{chunk-1n40bdxf.js.map → chunk-x5vpjzpp.js.map} +1 -1
- package/dist/{chunk-g52fcwca.js → chunk-xe2cfmyb.js} +2 -2
- package/dist/{chunk-g52fcwca.js.map → chunk-xe2cfmyb.js.map} +1 -1
- package/dist/{chunk-jykkqwcy.js → chunk-ych1dv5q.js} +3 -3
- package/dist/{chunk-jykkqwcy.js.map → chunk-ych1dv5q.js.map} +1 -1
- package/dist/{chunk-ap3g6rbw.js → chunk-yffm8nxa.js} +2 -2
- package/dist/{chunk-ap3g6rbw.js.map → chunk-yffm8nxa.js.map} +1 -1
- package/dist/{chunk-6gwxvmjv.js → chunk-yg8se4vs.js} +3 -3
- package/dist/{chunk-6gwxvmjv.js.map → chunk-yg8se4vs.js.map} +1 -1
- package/dist/chunk-zbvdkh6q.js +10 -0
- package/dist/{chunk-b4x1dt3s.js.map → chunk-zbvdkh6q.js.map} +4 -3
- package/dist/{chunk-s4xg69r9.js → chunk-zy5gxk1g.js} +2 -2
- package/dist/{chunk-s4xg69r9.js.map → chunk-zy5gxk1g.js.map} +1 -1
- package/dist/client/index.js +46 -21
- package/dist/client/index.js.map +1 -1
- package/dist/client/useQuery.d.ts +9 -0
- package/dist/client/useQuery.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Cache.d.ts +36 -0
- package/dist/facades/Cache.d.ts.map +1 -0
- package/dist/facades/Url.d.ts +12 -1
- package/dist/facades/Url.d.ts.map +1 -1
- package/dist/facades/index.d.ts +1 -0
- package/dist/facades/index.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/Metadata.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +3 -3
- package/dist/kernel/providers.d.ts +2 -2
- package/dist/kernel/providers.d.ts.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/cache/CacheManager.d.ts +115 -0
- package/dist/services/cache/CacheManager.d.ts.map +1 -0
- package/dist/services/cache/CacheServiceProvider.d.ts +5 -0
- package/dist/services/cache/CacheServiceProvider.d.ts.map +1 -0
- package/dist/services/cache/CacheStore.d.ts +26 -0
- package/dist/services/cache/CacheStore.d.ts.map +1 -0
- package/dist/services/cache/MemoryCacheStore.d.ts +36 -0
- package/dist/services/cache/MemoryCacheStore.d.ts.map +1 -0
- package/dist/services/cache/RedisCacheStore.d.ts +54 -0
- package/dist/services/cache/RedisCacheStore.d.ts.map +1 -0
- package/dist/services/cache/config.d.ts +35 -0
- package/dist/services/cache/config.d.ts.map +1 -0
- package/dist/services/index.d.ts +6 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +5 -5
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/utils/appOrigin.d.ts +19 -0
- package/dist/utils/appOrigin.d.ts.map +1 -0
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-1xmh61fg.js +0 -5
- package/dist/chunk-b4x1dt3s.js +0 -10
- package/dist/chunk-eyptwf54.js +0 -57
- package/dist/chunk-rany5zgk.js +0 -5
- package/dist/chunk-tabsxzg9.js +0 -5
- /package/dist/{chunk-gp00enrk.js.map → chunk-3fyhd641.js.map} +0 -0
- /package/dist/{chunk-j12hpdxk.js.map → chunk-bghxdjqv.js.map} +0 -0
- /package/dist/{chunk-6q6bhkyf.js.map → chunk-c48gag78.js.map} +0 -0
- /package/dist/{chunk-s4semb89.js.map → chunk-k6gvbvyw.js.map} +0 -0
- /package/dist/{chunk-j10a0m7q.js.map → chunk-p0ccxfkq.js.map} +0 -0
- /package/dist/{chunk-ayfjjgv2.js.map → chunk-rvdsaqdv.js.map} +0 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ag as OQ}from"./chunk-n8mxsfc2.js";import{Ug as DQ}from"./chunk-1gd1ykgj.js";import{$g as e7,$h as $Q,Lh as a3,Sh as ZZ,Vg as nZ,Wh as CX,Xh as g$,Yh as m$,Zg as xG,Zh as eG,_g as t7,ah as a4,bh as u4,eh as l4,fh as i4,gh as mZ,hh as WG,ih as EG,jh as P7,kh as p,ph as x,qh as VJ,rh as $Z,sh as r4,th as o3,vh as D$,wh as g,xh as S4}from"./chunk-dm7mada7.js";import{ci as g1,di as W0,ei as p1,fi as Z9}from"./chunk-7eerqsg2.js";import{gi as b3,hi as kG,li as m9,mi as w4,ni as N}from"./chunk-15bmfr7f.js";import{qi as MX,ti as E3}from"./chunk-rtb64x14.js";import{Ai as iG,xi as r9}from"./chunk-8df7fn7f.js";import{Si as K$,Xi as m1}from"./chunk-yffm8nxa.js";import{jj as YX}from"./chunk-s2krqtwj.js";import{kj as Z7,nj as uG}from"./chunk-0arss2xy.js";import{oj as Y$}from"./chunk-nv2t87c3.js";import{Fj as BQ,pj as i3,qj as P1,rj as V$,sj as FQ,tj as KQ,vj as bZ,wj as rG}from"./chunk-kzk5r6v4.js";import{Uj as T$}from"./chunk-v7nw1g2n.js";import{Zj as MG,ck as l5}from"./chunk-43faxwf5.js";import{jk as PG,ok as i}from"./chunk-mj7h1dgh.js";import{pk as gZ,sk as T}from"./chunk-yg8se4vs.js";import{Ak as c5}from"./chunk-s2y2b8tz.js";import{Bk as ZQ}from"./chunk-7nfprr9v.js";import{Nk as SG}from"./chunk-ecb8qggy.js";import{Sk as k4}from"./chunk-89swy5aq.js";function p3($){return typeof $==="function"&&$.prototype!==void 0}function l0($){return typeof $==="string"?[$]:$}function h3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function xQ($){return"total"in $&&"partial"in $&&"body"in $}function O7(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function dZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":i4($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function SQ($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(xQ($))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 s4($,Z){if($ instanceof Response)return $;if(!$)return O7();let J=await SQ($),{body:W,start:j,end:Y,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return O7()}let{range:G}=Z;if(G){if(z<=0)return dZ(Math.max(z,0));if(!X){if(W instanceof Blob){let K=u4(G,z);if(!K)return dZ(z);W=W.slice(K.start,K.end+1),j=K.start,Y=K.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),Q)B.set("Content-Range",l4(j,Y,z)),B.set("Content-Length",String(Y-j+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",h3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[K,O]of Object.entries(J.extraHeaders))B.set(K,O);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:B})}return new Response(W,{status:F,headers:B})}class n$ extends W0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var U7={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function lZ($){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 U7)))return Math.floor(Number(J[1])*(U7[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var uZ=new WeakMap;function T7($){return uZ.has($)}function H7($){return uZ.get($)?.limit??null}function I7($){let Z=uZ.get($);return Z?Z.read>Z.limit:!1}function CQ($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function o4($,Z){let J=CQ($);if(J!==null&&J>Z)throw new n$(Z)}function c3($,Z,J={}){let W=uZ.get($);if(W)W.limit=Z;else{let j={limit:Z,read:0,stream:void 0,used:!1};uZ.set($,j),fQ($,j)}if(J.checkDeclared!==!1)o4($,Z)}function AQ($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function n4($,Z){if(Z.stream!==void 0)return Z.stream;let J=AQ($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(j){W??=J.getReader();let{done:Y,value:z}=await W.read();if(Y){j.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new n$(Z.limit);j.error(X),W.cancel(X).catch(()=>{});return}j.enqueue(z)},cancel(j){return W?W.cancel(j):J.cancel(j)}},{highWaterMark:0}),Z.stream}async function s$($,Z){if(o4($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=n4($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),j=[],Y=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;j.push(Q),Y+=Q.byteLength}let z=new Uint8Array(Y),X=0;for(let G of j)z.set(G,X),X+=G.byteLength;return z}function V7($){return $.headers.get("Content-Type")??""}function fQ($,Z){let J=(W,j)=>Object.defineProperty($,W,{configurable:!0,...j});J("body",{get:()=>n4($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>s$($,Z)}),J("arrayBuffer",{value:async()=>{let W=await s$($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await s$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await s$($,Z)))}),J("blob",{value:async()=>new Blob([await s$($,Z)],{type:V7($)})}),J("formData",{value:async()=>new Response(await s$($,Z),{headers:{"Content-Type":V7($)}}).formData()}),J("clone",{value:()=>{o4($,Z.limit);let W=n4($,Z),j=null;if(W){let[Y,z]=W.tee();Z.stream=Y,j=z}return new Request($.url,{method:$.method,headers:$.headers,body:j,signal:$.signal,duplex:"half"})}})}function L7($){return p3($)}class j0{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!L7(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(L7(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class M7{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=l0($),this}async run(){let $=new x,Z=$.headers.toJSON();for(let J of P7($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(I7($.rawRequest))throw new n$(H7($.rawRequest));throw J}}}class N7{constructor(...$){return new j0(...$)}}class _7 extends j0{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=a4(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let j=await super.run($);return await s4(j,{range:W,method:J?.method})}catch(j){if(j instanceof r4)return dZ(j.total);throw j}finally{if(Z)Z.rangeRequest=null}}}class x7{constructor(...$){return new _7(...$)}}class S7{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new j0("GET",$,"list"),post:new j0("POST",$,"store")},this.second={get:new j0("GET",$,"show"),put:new j0("PUT",$,"update"),delete:new j0("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class b0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new j0("GET",$,Z)}post($,Z){return new j0("POST",$,Z)}put($,Z){return new j0("PUT",$,Z)}patch($,Z){return new j0("PATCH",$,Z)}delete($,Z){return new j0("DELETE",$,Z)}resource($){return new S7($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${EQ($)}.`);return bQ($,this)}file($,Z){return new N7("GET",$,Z)}stream($,Z){return new x7("GET",$,Z)}proxy($,Z={}){return new M7($,Z)}}function EQ($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function bQ($,Z){let J={stream:new j0("POST",$,"stream"),attach:new j0("POST",$,"attach"),stop:new j0("POST",$,"stop"),upload:new j0("POST",$,"upload")};return class extends b0{static __internal_brand="AgentRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.stream,"/attach":J.attach,"/stop":J.stop,"/files":J.upload};static middleware(j){if(j.stream)J.stream.middleware(j.stream);if(j.attach)J.attach.middleware(j.attach);if(j.stop)J.stop.middleware(j.stop);if(j.upload)J.upload.middleware(j.upload);return this}}}var v1="access_token";function F$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function d3($,Z){let J=F$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var RQ=/^[A-Za-z0-9_-]+$/,wQ=/^:[A-Za-z_][A-Za-z0-9_]*$/,C7=/^[A-Za-z0-9_-]{1,128}$/,kQ=/^[A-Za-z0-9_.:-]+$/;class h extends Error{constructor($){super($);this.name="InvalidChannelError"}}function A7($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function o$($){if(typeof $!=="string"||$.length===0)throw new h("A channel pattern must be a non-empty string.");if($.length>255)throw new h(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(wQ.test(W)){let j=W.slice(1);if(J.has(j))throw new h(`The channel pattern "${$}" names the param "${j}" twice.`);J.add(j);continue}if(W.startsWith("__"))throw new h(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!RQ.test(W))throw new h(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function iZ($,Z={}){let J=o$($),W=new Set,j=J.map((Y)=>{if(!Y.startsWith(":"))return Y;let z=Y.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new h(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!C7.test(G))throw new h(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let Y of Object.keys(Z))if(!W.has(Y))throw new h(`The channel "${$}" has no param "${Y}".`);if(j.length>255)throw new h(`The topic built from "${$}" is longer than 255 characters.`);return j}function t4($){if(o$($).some((J)=>J.startsWith(":")))throw new h(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function f7($){if(typeof $!=="string"||$.length===0||$.length>64||!kQ.test($))throw new h(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function E7($,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((j,Y)=>j===W[Y]||j.startsWith(":")&&C7.test(W[Y]))}var K0="user";function a$($){let Z=typeof $==="object"&&$!==null?$.id:$;return iZ(`${K0}.:id`,{id:Z})}class r{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class u3 extends r{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return c3(this.req.rawRequest,lZ(Z)),{}}}function qQ($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,j=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,j.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var vQ={"body-limit":u3};class y1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:lZ($.bodyLimit)}get aliases(){return{...vQ,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!T7($))c3($,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 x,J=this.aliases,W=[];for(let[j,Y]of qQ($).entries())if(typeof j==="string"){let z=J[j];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...Y),runsOnRefusal:b7(z)})}}else if(p3(j)){let z=new j(Z);W.push({run:z.run.bind(z),runsOnRefusal:b7(j)})}else W.push({run:j,runsOnRefusal:!1});return(async()=>{let j={};for(let Y=0;Y<W.length;Y++)try{j={...j,...await W[Y].run()}}catch(z){throw await yQ(W.slice(Y+1)),z}return j})()}}function b7($){return $?.runsOnRefusal===!0}async function yQ($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class l3{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class q7{static __brand="ChannelRouter";channels={};public(){return new l3("public")}private($){return new l3("private",$)}async authorize($,Z,J={},W={}){try{hQ(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let j=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!v7(j))return{ok:!1,code:"unknown_channel"};let Y=null;try{if(Z===K0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else Y=iZ(Z,J??{})}catch(G){if(G instanceof h)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new x($,z,"api",Z);return N.exit(()=>i3.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(j.middlewares.length>0)await T(y1).runMiddleware(j.middlewares);if(Z===K0){let Q=await R7(X);if(!Q)return{ok:!1,code:"denied"};if(Y=a$(Q),j.visibility==="private"&&j.authorizer){if(await w7(j.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}if(j.visibility==="private"){if((j.authorizer?await w7(j.authorizer,X,z):await R7(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:Y,pattern:Z}}catch(Q){if(pQ(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function gQ($,Z,J={},W={}){let j=typeof $==="function"?new $:$;y7(j);let Y=W.as,z,X=null;if(Y instanceof Request)z=Y;else if(Y&&typeof Y==="object"&&Y.rawRequest instanceof Request)z=Y.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=Y?{user:Y}:null;return(await j.authorize(z,Z,J,{carried:X})).ok}function v7($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function R7($){if(!N.getStore().user&&F$($)===null)return null;try{return await R0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function w7($,Z,J){if(mQ($))return new $().authorize(Z,J);return $(Z,J)}function mQ($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function pQ($){return $?.kind===g1||m1($)||K$($)}var k7=new WeakSet;function hQ($){if(k7.has($))return;y7($),k7.add($)}function y7($){let Z=Object.entries($.channels),J=[];for(let[W,j]of Z){if(!v7(j))throw new h(`The channel "${W}" is not declared with this.public() or this.private().`);let Y=o$(W);if(Y[0].startsWith(":"))throw new h(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==K0&&Y.length===2&&Y[0]===K0)throw new h(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==K0&&j.visibility==="private"&&!j.authorizer&&Y.some((z)=>z.startsWith(":")))throw new h(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===K0?[K0,":id"]:Y})}for(let W=0;W<J.length;W++)for(let j=W+1;j<J.length;j++)if(cQ(J[W].segments,J[j].segments))throw new h(`The channel patterns "${J[W].pattern}" and "${J[j].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function cQ($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class e4{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class $J{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class ZJ{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class g7{static __brand="McpRouter";routes={};scopes;param($){return new e4($.as,$.input,$.bind)}fromTool($,Z={}){return new ZJ($,Z)}fromApiRoute($,Z,J){return new $J($,Z,J)}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let j=W.endsWith("?")||W.endsWith("*"),Y=j?W.slice(0,-1):W,z=Z[Y];if(z===void 0){if(j)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${Y}`);console.error(`Missing parameter: ${Y} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class JJ extends W0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class H1{static to($,...Z){let[J={}]=Z,{search:W={},params:j={},permanent:Y,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new JJ([B0($,j)||"/",X.toString()].filter(Boolean).join("?"),z??(Y?301:307))}static external($,Z=307){throw new JJ($,Z)}}var m7=Symbol.for("gemi.HttpResponse");class B${kind;body;status;headers;[m7]=!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 dQ(J),new B$("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 B$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let j of Z)J.append("Set-Cookie",j);this.headers.forEach((j,Y)=>{if(Y.toLowerCase()!=="set-cookie")J.set(Y,j)});for(let j of this.headers.getSetCookie())J.append("Set-Cookie",j);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function dQ($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function r$($){return typeof $==="object"&&$!==null&&$[m7]===!0}function uQ($,Z,J={}){return B$.error($,Z,J)}class p7{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:j=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return H1.to(J,{permanent:W,status:j}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function WJ($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,j=J?$.name:$.name??$.file?.name,Y=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",Y||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(j)Z.set("Content-Disposition",h3(j,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class h7{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function c7($,Z){if(r$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class d7{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(j)=>{return new J()[W](j)}}}async run($,Z){let J=c7(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=l0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class u7{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,j]=Z;this.handler=(Y)=>{return new W()[j](Y)},this.children=class extends I1{routes=J??{}}}else this.children=class extends I1{routes=Z},this.handler=()=>({})}async run($,Z){let J=c7(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class I1{middlewares=[];featureGates=[];routes={};view($,Z){return new d7($,Z)}file($){return new h7($)}redirect($){return new p7($)}layout($,Z,J){return new u7($,Z,J)}}function lQ($){return $}function iQ(){return{aliases:{},global:[],bodyLimit:null}}var W1="redirect";function j1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),j=`${J.pathname}${W}`.replaceAll(":","%3A");return j.startsWith("//")?Z:j}catch{return Z}}function t$($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function sQ($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,j,...Y]=W.split("/");if(T(i).supportedLocales.includes(j))W=`/${Y.join("/")}`;return Z?`${W}${J.search}`:W}function nQ($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function s3($,Z){let J=Z||T(A).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let j=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let Y=sQ($,!W);if(W||!nQ(new URL(Y,j).pathname,j.pathname))j.searchParams.set(W1,Y)}return W?j.href:`${j.pathname}${j.search}`}class l7 extends r{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await d3(T(A),J);if(!W)throw new D$({redirectTo:s3(J,$)});return Z.setUser(W),{}}}var YJ="gemi_same_site",jJ="private, no-cache, no-store, max-age=0, must-revalidate";class n3 extends r{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(YJ))return{};if(F$(Z))return{};let j=J.headers.get("Sec-Fetch-Site");if(j&&j!=="cross-site")return{};throw W.searchParams.set(YJ,"1"),new i7(`${W.pathname}${W.search}`)}}class i7 extends W0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=oQ($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":jJ,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":jJ}},viewData:{status:200,data:{},headers:{"Cache-Control":jJ},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function oQ($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class s7 extends r{async run(...$){let[Z="public",J="864000",...W]=$,j=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)j="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")j="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")j="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",j);return{}}}var n7={"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 o7 extends r{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...n7,...this.config.origins[Z]};for(let[W,j]of Object.entries(J))$.ctx().setHeaders(W,j)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...n7,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,j]of Object.entries(J))$.ctx().setHeaders(W,j)}return{}}}var aQ="Rate limit exceeded";class h1 extends W0{result;retryAfter;constructor($,Z=aQ){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?zJ($):{}};this.payload={api:{status:429,data:{error:{...p1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function zJ($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class Y1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,j=Z.cost??1;if(a7("window",W),a7("limit",J),!Number.isFinite(j)||j<0)throw Error(`Rate limiter cost must be zero or greater, got ${j}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:j})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new h1(W,typeof J==="function"?J(W):J);return W}}function a7($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class $9 extends r{async run($,Z){let J=rQ();if(!J)return{};let W=await J.consume(this.key(),{limit:r7($)??this.config.limit,window:r7(Z)??this.config.window});if(this.config.headers!==!1){let j=this.req.ctx?.();if(j)for(let[Y,z]of Object.entries(zJ(W)))j.setHeaders(Y,z)}if(!W.allowed)throw new h1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=t7(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${e$(this.req)}:${this.req.routePath??"*"}`}}function rQ(){try{let $=T();return $.bound(Y1)?$.make(Y1):null}catch{return null}}function e$($){let Z=e7($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function r7($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class J9 extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new XJ;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new XJ;return{}}}class XJ extends W0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:Z9("csrf","Invalid CSRF token",403)}},view:{}}}class W9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class j9{all($,Z){return!0}}class GJ{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new $Z:new o3}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 x,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends r{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let j;if(J!==void 0){if(j=$.thread?await $.thread(J,Z):null,j===null||j===void 0)throw this.refusal()}if(W!==void 0){let Y=await $.body(W,Z);if(await this.authorize(Z,Y),J!==void 0&&String(j)!==String(Y))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,j)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof $Z:$ instanceof o3}}function tQ($){return new GJ($)}async function r3($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,j]=await BF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?j.pipeThrough(new DecompressionStream("gzip")):j;return KF(z,Z,J,$.url)}async function KF($,Z,J,W){let j=$.getReader(),Y=[],z=0;try{for(;;){let{done:Q,value:F}=await j.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new a3(W,Z);Y.push(F.subarray(0,Z-z)),z=Z;break}Y.push(F),z+=F.byteLength}}finally{j.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of Y)X.set(Q,G),G+=Q.byteLength;return X}async function BF($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,j=new ReadableStream({start(Y){if(J.done)Y.close();else Y.enqueue(W)},async pull(Y){let z=await Z.read();if(z.done)Y.close();else Y.enqueue(z.value)},cancel(Y){return Z.cancel(Y)}});return[W,j]}function t3($){return new TextDecoder("utf-8").decode($)}var DF={"&":"&","<":"<",">":">",'"':""","'":"'"};function O$($){return $.replace(/[&<>"']/g,(Z)=>DF[Z])}var OF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function QJ($){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 OF[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 FJ($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function Y9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let j=$.indexOf("<",W);if(j===-1){Z.text(QJ($.slice(W)));return}if(j>W)Z.text(QJ($.slice(W,j)));if($.startsWith("<!--",j)){let Y=$.indexOf("-->",j+4);if(Y===-1)return;W=Y+3}else if($.startsWith("<![CDATA[",j)){let Y=$.indexOf("]]>",j+9);if(Y===-1)return;Z.text($.slice(j+9,Y)),W=Y+3}else if($.startsWith("<?",j)){let Y=$.indexOf("?>",j+2);if(Y===-1)return;W=Y+2}else if($.startsWith("<!",j)){let Y=$.indexOf(">",j+2);if(Y===-1)return;let z=$.indexOf("[",j+2);if(z!==-1&&z<Y){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=Y+1}else if($[j+1]==="/"){let Y=$.indexOf(">",j+2);if(Y===-1)return;Z.close(FJ($.slice(j+2,Y).trim())),W=Y+1}else{let Y=UF($,j+1);if(Y===-1)return;let z=$.slice(j+1,Y),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=FJ(z.slice(0,G));if(Q){if(Z.open(Q,VF(z.slice(G)),X),X)Z.close(Q)}W=Y+1}}}function UF($,Z){let J=null;for(let W=Z;W<$.length;W++){let j=$[W];if(J){if(j===J)J=null}else if(j==='"'||j==="'")J=j;else if(j===">")return W}return-1}function VF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[FJ(W[1])]=QJ(W[2]??W[3]??"");return Z}class Y0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var F9="http://www.sitemaps.org/schemas/sitemap/0.9",TF="http://www.w3.org/1999/xhtml",DJ=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
+
`,z9=`<urlset xmlns="${F9}" xmlns:xhtml="${TF}">
|
|
4
|
+
`,X9=`</urlset>
|
|
5
|
+
`,U$=50000,sZ=52428800,G9=2048,HF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),IF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,LF="application/xml; charset=utf-8",Q9=new TextEncoder;function OJ($,Z){let J;try{J=new URL($)}catch{throw new Y0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new Y0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>G9)throw new Y0(`Sitemap: ${Z} is over ${G9} characters: "${W.slice(0,80)}\u2026".`);return W}function K9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new Y0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!IF.test($))throw new Y0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function PF($){let Z=OJ($.loc,"loc"),J=`<url><loc>${O$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${O$(K9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!HF.has($.changefreq))throw new Y0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new Y0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let j=W.hrefLang?.trim();if(!j)throw new Y0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let Y=OJ(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${O$(j)}" href="${O$(Y)}"/>`}return`${J}</url>
|
|
6
|
+
`}function MF($){let Z=$.maxUrls??U$,J=$.maxBytes??sZ;if(!Number.isInteger(Z)||Z<1||Z>U$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${U$}.`);if(!Number.isInteger(J)||J<1||J>sZ)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${sZ}.`);return{maxUrls:Z,maxBytes:J}}function B9($,Z={}){let{maxUrls:J,maxBytes:W}=MF(Z),j=Q9.encode(DJ+z9+X9).byteLength,Y=[],z=[],X=j,G=()=>{Y.push(DJ+z9+z.join("")+X9),z=[],X=j};for(let Q of $){let F=PF(Q),B=Q9.encode(F).byteLength;if(j+B>W)throw new Y0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+B>W)G();z.push(F),X+=B}if(z.length>0||Y.length===0)G();return Y}function D9($){let Z="",J=0;for(let W of $){if(++J>U$)throw new Y0(`Sitemap: an index can list at most ${U$} sitemaps.`);let j=OJ(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${O$(j)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${O$(K9(W.lastmod,j))}</lastmod>`;Z+=`</sitemap>
|
|
7
|
+
`}return`${DJ}<sitemapindex xmlns="${F9}">
|
|
8
|
+
${Z}</sitemapindex>
|
|
9
|
+
`}function KJ($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",LF);return new Response($,{status:Z,headers:W})}function NF($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function _F($,Z={}){let J=B9($,Z),W=NF(Z.page);if(W!==null){let Y=J[W-1];return Y?KJ(Y,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return KJ(J[0],200,Z.headers);let j=Z.pageUrl;if(!j)throw new Y0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return KJ(D9(J.map((Y,z)=>({loc:j(z+1)}))),200,Z.headers)}function BJ($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function O9($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let K=[];for(let O of W.split(/\r?\n/)){if(K.length>=J)break;let D=O.trim()?BJ(O):null;if(D)K.push({loc:D})}if(K.length===0&&W.length>0)throw new Y0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:K}}let j=null,Y=[],z=[],X=[],G=null,Q=null,F="",B=()=>j==="index"?z.length:Y.length;if(Y9(W,{stopped:()=>B()>=J,open(K,O){let D=X[X.length-1];if(X.push(K),j===null){if(K==="urlset")j="urlset";else if(K==="sitemapindex")j="index";return}if(j==="urlset"&&K==="url"&&D==="urlset"||j==="index"&&K==="sitemap"&&D==="sitemapindex")G={};else if(G&&(D==="url"||D==="sitemap")&&(K==="loc"||K==="lastmod"||K==="changefreq"||K==="priority"))Q=K,F="";else if(G&&j==="urlset"&&D==="url"&&K==="link"){let U=O.href?BJ(O.href):null;if(O.rel?.toLowerCase()==="alternate"&&O.hreflang&&U)(G.alternates??=[]).push({hrefLang:O.hreflang,href:U})}},close(K){let O=X.lastIndexOf(K);if(O===-1)return;if(X.length=O,Q&&K===Q&&G)G[Q]=F.trim(),Q=null;else if(G&&(K==="url"||K==="sitemap")){let D=G;G=null,Q=null;let U=D.loc?BJ(D.loc):null;if(!U)return;if(j==="index"){z.push(D.lastmod?{loc:U,lastmod:D.lastmod}:{loc:U});return}let V={loc:U};if(D.lastmod)V.lastmod=D.lastmod;if(D.changefreq)V.changefreq=D.changefreq;let H=D.priority?Number(D.priority):NaN;if(Number.isFinite(H))V.priority=H;if(D.alternates)V.alternates=D.alternates;Y.push(V)}},text(K){if(Q)F+=K}}),j===null)throw new Y0("Sitemap: the document has no <urlset> or <sitemapindex>.");return j==="index"?{kind:j,sitemaps:z}:{kind:j,urls:Y}}async function*xF($,Z={}){let{maxUrls:J=U$,maxSitemaps:W=50,maxDepth:j=3,maxSize:Y=sZ,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,F=0,B=0;while(G.length>0&&B<J&&F<W){let K=G.shift(),O=K.url.replace(/#.*$/,"");if(Q.has(O))continue;Q.add(O),F++;let D;try{let U=await ZZ(K.url,{...X,maxSize:Y});if(!U.ok)throw U.body?.cancel().catch(()=>{}),new Y0(`Sitemap: ${K.url} answered ${U.status}.`,K.url,U.status);let V=t3(await r3(U,Y));D=O9(V,{maxUrls:Math.max(J-B,W-F)})}catch(U){if(K.depth===0||!z||X.signal?.aborted)throw U;z(U,K.url);continue}if(D.kind==="index"){if(K.depth>=j)continue;G=D.sitemaps.slice(0,W-F).map((V)=>({url:V.loc,depth:K.depth+1})).concat(G);continue}for(let U of D.urls)if(yield{...U,sitemap:K.url},++B>=J)return}}var U9={response:_F,chunk:B9,index:D9,parse:O9,read:xF,MAX_URLS:U$,MAX_BYTES:sZ};var SF=512000,CF=new TextEncoder;function V9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function T9($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let j=$.codePointAt(J);if(j>65535)J++;for(let Y of CF.encode(String.fromCodePoint(j)))Z+=`%${Y.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function AF($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,j=0,Y=0,z=-1,X=0;while(Y<Z.length)if(j<W.length&&W[j]!=="*"&&W[j]===Z[Y])j++,Y++;else if(j<W.length&&W[j]==="*")z=j++,X=Y;else if(j===W.length&&!J)return!0;else if(z!==-1)j=z+1,Y=++X;else return!1;while(j<W.length&&W[j]==="*")j++;return j===W.length}class JZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=V9($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let j=new URL(String($));J=j.pathname+j.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=T9(J);let W=null;for(let j of this.groupsFor(Z))for(let Y of j.rules){if(!AF(Y.path,J))continue;let z=Y.path.length,X=Y.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var fF={"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 H9($,Z={}){let J=[],W=[],j=null,Y=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),G=(X===-1?z:z.slice(0,X)).trim(),Q=G.indexOf(":");if(Q===-1)continue;let F=fF[G.slice(0,Q).trim().toLowerCase()],B=G.slice(Q+1).trim();if(!F)continue;if(F==="sitemap"){if(!B||/\s/.test(B))continue;try{let K=Z.url?new URL(B,Z.url):new URL(B);if(K.protocol==="http:"||K.protocol==="https:")W.push(K.href)}catch{}continue}if(F==="user-agent"){if(!Y||!j)j={userAgents:[],rules:[]},J.push(j),Y=!0;let K=V9(B);if(K)j.userAgents.push(K);continue}if(!j)continue;if(Y=!1,F==="crawl-delay"){let K=Number(B);if(Number.isFinite(K)&&K>=0)j.crawlDelay=K;continue}if(!B)continue;j.rules.push({type:F,path:T9(B)})}return new JZ(J,W)}async function EF($,Z={}){let{maxSize:J=SF,...W}=Z,j=new URL("/robots.txt",$),Y=await ZZ(j,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=Y.status;if(z===429||z>=500)return Y.body?.cancel().catch(()=>{}),new JZ([],[],"unreachable");if(z>=400)return Y.body?.cancel().catch(()=>{}),new JZ([],[],"unavailable");let X=await r3(Y,J,!0),G=t3(X);if(X.byteLength>=J)G=G.slice(0,Math.max(0,G.lastIndexOf(`
|
|
10
|
+
`)));return H9(G,{url:Y.url})}function UJ($){return $===void 0?[]:typeof $==="string"?[$]:$}function e3($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
|
|
11
|
+
`}function I9($){let Z=[];for(let W of $.rules??[]){let j=UJ(W.userAgent);if(j.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let Y=j.map((X)=>e3("User-agent",X)).join(""),z=[...UJ(W.allow).map((X)=>["Allow",X]),...UJ(W.disallow).map((X)=>["Disallow",X])];for(let[X,G]of z){if(!G.startsWith("/")&&!G.startsWith("*"))throw TypeError(`Robots: ${X} "${G}" must start with "/" or "*".`);Y+=e3(X,G)}if(z.length===0)Y+=`Disallow:
|
|
12
|
+
`;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);Y+=e3("Crawl-delay",String(W.crawlDelay))}Z.push(Y)}let J=($.sitemaps??[]).map((W)=>{let j;try{j=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return e3("Sitemap",j.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
|
|
13
|
+
`)}function bF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(I9($),{status:200,headers:J})}var L9={response:bF,text:I9,parse:H9,fetch:EF};import{createHmac as P9,randomBytes as RF}from"crypto";var TJ="v2.";function HJ($){return $.startsWith(TJ)}function WZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function M9($){let Z=RF(16).toString("hex"),J=P9("sha256",WZ()).update(`${$}:${Z}`).digest("hex");return`${TJ}${J}`}function $6($,Z){let J=P9("sha256",WZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${TJ}${J}`}import{createHash as qF,createHmac as vF,randomInt as yF,timingSafeEqual as x9}from"crypto";function N9($,Z){return Math.floor($/Z)*Z}function wF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function IJ($,Z,J,W){return Z*wF(J,W)+$}function kF($){let{current:Z,previous:J,elapsed:W,window:j,limit:Y,cost:z}=$,X=Y-z;if(X<0)return j;let G=Math.max(0,j-W);if(J>0){let F=j*(1-(X-Z)/J);if(F<=j)return Math.max(0,Math.ceil(F-W))}if(Z<=X)return G;if(Z<=0)return G;let Q=j*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function _9($){let{allowed:Z,current:J,previous:W,now:j,elapsed:Y,window:z,limit:X,cost:G}=$;if(Z){let F=IJ(J,W,Y,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-F)),resetAt:j-Y+z,retryAfter:0}}let Q=kF({current:J,previous:W,elapsed:Y,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:j+Q,retryAfter:Q}}class LJ{}class PJ extends LJ{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,j=$.cost??1,Y=Date.now(),z=N9(Y,W),X=Y-z,G=this.roll(Z,W,z);G.limit=J;let F=IJ(G.current,G.previous,X,W)+j<=J;if(F)G.current+=j;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(Y);return _9({allowed:F,current:G.current,previous:G.previous,now:Y,elapsed:X,window:W,limit:J,cost:j})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,j]of this.buckets)if($-j.windowStart>=j.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,j],Y)=>({key:W,order:Y,spent:j.limit>0?(j.current+j.previous)/j.limit:0}));J.sort((W,j)=>W.spent-j.spent||W.order-j.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var A9="h1.";function Z6($,Z,J){let W=vF("sha256",WZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${A9}${W}`}function oZ($,Z,J,W){let j=typeof W==="string"?W:"",Y=typeof J==="string"?J:"",z=Y.startsWith(A9),X=Z6($,Z,j),G=Buffer.from(z?X:j),Q=Buffer.from(Y);if(G.length!==Q.length||j===""||Y==="")return x9(G,G),!1;return x9(G,Q)}function f9($){let Z="";for(let J=0;J<$;J++)Z+=String(yF(0,10));return Z}var E9=320;function aZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>E9)return null;return Z.toLowerCase()}function J6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>E9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var S9=null;function b9(){try{let $=T();if(typeof $?.bound==="function"&&$.bound(Y1))return $.make(Y1)}catch{}return S9??=new Y1({driver:new PJ,limit:1000,window:60}),S9}function C9($){return $.length<=64?$:`sha256:${qF("sha256").update($).digest("hex")}`}async function jZ($,Z,J,W){let j=b9(),Y=[[`auth:code-${$}:ip:${C9(e$(J))}`,W.perIp]];if(Z!==null)Y.push([`auth:code-${$}:email:${C9(Z)}`,W.perEmail]);for(let[z,X]of Y){if(!X)continue;let[G,Q]=X,F=await j.consume(z,{limit:G,window:Q});if(!F.allowed)throw new h1(F)}}async function R9($,Z,J,W=10){let j=Math.max(86400,Math.ceil(W*60*(J+1)));return(await b9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:j})).allowed}import{randomBytes as NJ}from"crypto";class MJ extends x{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 W6($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let j=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${j}, got ${Z}`)}}function gF($={}){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 _J($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,j=$.maxAttempts??5;return W6("length",Z,4,12),W6("expiresInMinutes",J,1),W6("linkExpiresInMinutes",W,1),W6("maxAttempts",j,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:Y,code:z})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${Y}: ${z} (set auth.emailCode.send to deliver it)`)})}}async function mF($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function w9($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function k9($){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 RH($){return $}function q9($={}){return gF($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:MJ,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:mF,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>NJ(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return NJ(32).toString("hex")},generateMagicLinkToken:()=>NJ(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:_J($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var pF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),hF=new Set(["svg","math"]);function v9($){return $===32||$===9||$===10||$===12||$===13}function y9($){return $>=65&&$<=90||$>=97&&$<=122}function j6($){return $>=65&&$<=90?$+32:$}function g9(){let $="data",Z="",J=!1,W="",j=0,Y=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,F=()=>{if(!J&&pF.has(Z)){$="rawText",W=`</${Z}`,j=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(hF.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},B=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",Y=0;else if(K===47)$="endTagOpen";else if(y9(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(j6(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(y9(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(j6(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(v9(K)||K===47)$="inTag",z=K===47;else if(K===62)F();else Z+=String.fromCharCode(j6(K));return;case"inTag":if(K===62){F();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(Y+=1,Y===2)$="comment",Y=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)Y=Y<2?Y+1:2;else if(K===62&&Y>=2)$="data",Y=0;else Y=0;return;case"rawText":{if(j<W.length){if(j6(K)===W.charCodeAt(j))j+=1;else j=K===60?1:0;return}if(K===62)$="data",Z="";else if(v9(K)||K===47)$="inTag",Z="";else j=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let O=0;O<K.length;O++){if(Q())return O;B(K[O])}return K.length},write(K){for(let O=0;O<K.length;O++)B(K[O])},isSafe:Q}}function L1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function cF($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${L1([$.path,$.variantKey,$.data])})</script>`}function dF($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${L1([$.id,$.locale,$.strings])})</script>`}function xJ($,Z,J={},W){let j=new TextEncoder,Y=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;Y.push(cF(D))}),W?.onUse((D)=>{Y.push(dF(D))});let Q=$.getReader(),F=g9(),B=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},K=(D)=>{while(Y.length>0){let U=j.encode(Y.shift());F.write(U),B(D,U)}},O=(D,U)=>{if(Y.length===0){F.write(U),B(D,U);return}let V=F.scanToInsertionPoint(U);if(V>0)B(D,U.subarray(0,V));if(F.isSafe())K(D);let H=U.subarray(V);if(H.length>0)F.write(H),B(D,H)};return new ReadableStream({async pull(D){let U;try{U=await Q.read()}catch(P){throw G(),P}let{done:V,value:H}=U;if(V){K(D),D.close(),G();return}if(!z){if(z=!0,F.write(H),B(D,H),J.onShell?.(),F.isSafe())K(D);return}O(D,H)},cancel(D){return G(),Q.cancel(D)}})}var uF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function Y6($){if(!$)return!1;return uF.test($)}async function p9($,Z=()=>{}){let J=N.getStore(),W=J?.req??null,j=null;if(W?.rawRequest?.url)try{j=new URL(W.rawRequest.url).pathname}catch{j=null}return{user:J?.user??null,attributes:await lF($,Z),request:{path:j,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:m9(),isBot:Y6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function h9($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function lF($,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 c9($,Z){return`${$}:${Z}`}function SJ($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function d9($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function u9($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let Y;try{Y=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof Y==="boolean")return{value:Y,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let j=sF($,Z,J,W.buckets);return d9(j,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function iF($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function sF($,Z,J,W){let j=c9(Z.salt??$,iF(J));if(!W)return SJ(j);let Y=W.get(j);if(Y!==void 0)return Y;let z=SJ(j);return W.set(j,z),z}class l9 extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class CJ{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new l9(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let j=typeof W?.key==="string"?W.key:null;if(!j){this.warn("Ignoring a feature row with no `key`.");continue}if(!(j in this.declared)){this.warn(`Feature row "${j}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(j,W.active===!0);let Y=nF(W);if(Y)J.set(j,Y)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function nF($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let j=W instanceof Date?W:new Date(W);if(!Number.isNaN(j.getTime()))Z.updatedAt=j}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class oF{}class aF 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 AJ 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 i9 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 s9{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class c1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new CJ($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,j])=>({key:W,describe:j.describe,rollout:j.rollout,targeted:j.when!==void 0,serverOnly:j.serverOnly,salt:j.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new i9(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=rF(J.actor),j=this.config.source;if(typeof j.write!=="function")throw new AJ(j.constructor?.name||"an anonymous source");let{actorRecorded:Y}=await j.write($,Z,{actor:W});if(W!==null&&!Y&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new s9(this,h9($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),j=W?.get($);if(j)return j;let Y=this.declared[$];if(!Y)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=u9($,Y,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,J){let W={};for(let[j,Y]of Object.entries(this.declared)){if(J.clientOnly&&Y.serverOnly)continue;W[j]=(await this.evaluateIn(j,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await p9(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 rF($){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 n9($){if($===void 0)return!0;return await T(c1).enabled($)}async function YZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=w9($[Z]);if(!J||!await n9(J.feature))return null;return J.provider}async function o9($){let Z=[];for(let J of Object.keys($))if(await YZ($,J))Z.push(J);return Z}function fJ($){if($&&typeof $==="object")delete $.password;return $}function tF(){return new Proxy({},{get:($,Z)=>r9(Z)})}var a9=new WeakMap;function t9($){if($&&typeof $==="object"){for(let Z of Object.values($))t9(Z);Object.freeze($)}return $}var eF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},$K=t9({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:eF});class EJ{models;constructor($=tF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return $K}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??V$(),W=T(T$).connection(J),j=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await P1()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||P1())return j();let z=(a9.get(W)??Promise.resolve()).then(j,j);return a9.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return fJ(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return fJ(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?fJ(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 jO}from"crypto";function w0($,Z,J,W,j){return i0(Z,OW($,Z),J,W,j)}function i0($,Z,J,W,j,Y){let z=qJ(Z,J,W);if(j&&Z!==z)throw RangeError(rY($,Z,J,W,Y));return z}function OW($,Z){let J=$[Z];if(J===void 0)throw TypeError(F8(Z));return J}function O0($){return $!==null&&/object|function/.test(typeof $)}function v0($,Z=Map){let J=new Z;return(W,...j)=>{if(J.has(W))return J.get(W);let Y=$(W,...j);return J.set(W,Y),Y}}function dJ($){return P$({name:$},1)}function P$($,Z){return a0((J)=>({value:J,configurable:1,writable:!Z}),$)}function UW($){return a0((Z)=>({get:Z,configurable:1}),$)}function P6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function BZ($,Z){let J={},W=$.length;for(let j of Z)J[$[--W]]=j;return J}function a0($,Z,J){let W={};for(let j in Z)W[j]=$(Z[j],j,J);return W}function Y3($,Z,J){let W={};for(let j=0;j<Z.length;j++){let Y=Z[j];W[Y]=$(Y,j,J)}return W}function ZK($,Z,J){let W={};for(let j=0;j<$.length;j++)W[Z[j]]=J[$[j]];return W}function g0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function uJ($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function lJ($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function VW($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function TW($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function HW($,Z,J){let W={...J};for(let j=0;j<Z;j++)W[$[j]]=0;return W}function R($,...Z){return(...J)=>$(...Z,...J)}function e9($){return $[0].toUpperCase()+$.substring(1)}function z3($){return $.slice().sort()}function B6($,Z){return String(Z).padStart($,"0")}function d1($,Z){return Math.sign($-Z)}function qJ($,Z,J){return Math.min(Math.max($,Z),J)}function N1($,Z){return[Math.floor($/Z),tZ($,Z)]}function tZ($,Z){return($%Z+Z)%Z}function i1($,Z){return[M6($,Z),iJ($,Z)]}function M6($,Z){return Math.trunc($/Z)||0}function iJ($,Z){return $%Z||0}function z6($){return Math.abs($%1)===0.5}function IW($,Z,J){let W=0,j=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=X1[X],F=c/Q,[B,K]=i1(G,F);W+=K*Q,j+=B}let[Y,z]=i1(W,c);return[j+Y,z]}function N6($,Z,J){let W={};for(let j=Z;j>=0;j--){let Y=X1[j];W[J[j]]=M6($,Y),$=iJ($,Y)}return W}function LW($){return $===w?W4:[]}function PW($){return $===w?V3:[]}function MW($){return $===w?["year","day"]:[]}function NW($){if($!==void 0)return t($)}function _W($){if($!==void 0)return r0($)}function sJ($){if($!==void 0)return X3($)}function r0($){return CW(X3($))}function X3($){return SW(iK($))}function nJ($){if($==null)throw TypeError("Cannot be null or undefined");return $}function xW($,Z){if(Z==null)throw RangeError(F8($));return Z}function x1($){if(!O0($))throw TypeError(aY);return $}function _6($,Z,J=$){if(typeof Z!==$)throw TypeError(D3(J,Z));return Z}function SW($,Z="number"){if(!Number.isInteger($))throw RangeError(TK(Z,$));return $||0}function CW($,Z="number"){if($<=0)throw RangeError(HK(Z,$));return $}function oJ($){if(typeof $=="symbol")throw TypeError(MK);return String($)}function D6($,Z){return O0($)?String($):t($,Z)}function x6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(PK($));return $}function AW($,Z="number"){if(typeof $=="bigint")throw TypeError(LK(Z));if($=Number($),!Number.isFinite($))throw RangeError(IK(Z,$));return $}function N0($,Z){return Math.trunc(AW($,Z))||0}function fW($,Z){return SW(AW($,Z),Z)}function $W($,Z){return CW(N0($,Z),Z)}function aJ($,Z){let[J,W]=i1(Z,c),j=$+J,Y=Math.sign(j);return Y&&Y===-Math.sign(W)&&(j-=Y,W+=Y*c),[j,W]}function XZ($,Z,J=1){return aJ($[0]+Z[0]*J,$[1]+Z[1]*J)}function GZ($,Z){return aJ($[0],$[1]+Z)}function c0($,Z){return XZ(Z,$,-1)}function x0($,Z){return d1($[0],Z[0])||d1($[1],Z[1])}function EW($,Z,J){return x0($,Z)===-1||x0($,J)===1}function S6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function QZ($,Z=1){let J=c/Z,[W,j]=i1($,J);return[W,j*Z]}function bW($,Z=1){let[J,W]=$,j=Math.floor(W/Z),Y=c/Z;return BigInt(J)*BigInt(Y)+BigInt(j)}function d0($,Z=1,J){let[W,j]=$,[Y,z]=i1(j,Z);return W*(c/Z)+(Y+(J?z/Z:0))}function rJ($,Z,J=N1){let[W,j]=$,[Y,z]=J(j,Z);return[W*(c/Z)+Y,z]}function tJ($,Z){let J=$.formatToParts(Z),W={};for(let j of J)W[j.type]=j.value;return W}function eJ($){return w0($,"isoYear",j3,W3,1),$.isoYear===j3?w0($,"isoMonth",4,12,1):$.isoYear===W3&&w0($,"isoMonth",1,9,1),$}function u1($){return S1({...$,...o0,isoHour:12}),$}function S1($){let Z=w0($,"isoYear",j3,W3,1),J=Z===j3?1:Z===W3?-1:0;return J&&u0(_0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function u0($){if(!$||EW($,eK,tK))throw RangeError(e6);return $}function s1($){return IW($,5,Z1)[1]}function C6($){let[Z,J]=N1($,c);return[N6(J,5,Z1),Z]}function RW($){return wW($)[0]}function wW($){return rJ($,n0)}function S0($){return DZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function _0($){let Z=S0($);if(Z!==void 0){let[J,W]=i1(Z,q0);return[J,W*G1+($.isoMicrosecond||0)*E$+($.isoNanosecond||0)]}}function $2($,Z){let[J,W]=C6(s1($)-Z);return u0(_0({...$,isoDay:$.isoDay+W,...J}))}function O6(...$){return DZ(...$)/Gz}function DZ(...$){let[Z,J]=kW(...$),W=Z.valueOf();if(!isNaN(W))return W-J*q0}function kW($,Z=1,J=1,W=0,j=0,Y=0,z=0){let X=$===j3?1:$===W3?-1:0,G=new Date;return G.setUTCHours(W,j,Y,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function o1($,Z){let[J,W]=GZ($,Z);W<0&&(W+=c,J-=1);let[j,Y]=N1(W,G1),[z,X]=N1(Y,E$);return A6(J*q0+j,z,X)}function A6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-rK)/q0)*Math.sign($),j=new Date($-W*q0);return BZ(Y4,[j.getUTCFullYear(),j.getUTCMonth()+1,j.getUTCDate()+W,j.getUTCHours(),j.getUTCMinutes(),j.getUTCSeconds(),j.getUTCMilliseconds(),Z,J])}function qW($){return[$.isoYear,$.isoMonth,$.isoDay]}function vW(){return M1}function Z2($,Z){switch(Z){case 2:return J2($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function yW($){return J2($)?366:365}function J2($){return $%4==0&&($%100!=0||$%400==0)}function gW($){let[Z,J]=kW($.isoYear,$.isoMonth,$.isoDay);return tZ(Z.getUTCDay()-J,7)||7}function mW({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function JK($){let Z=S0($);if(Z<ZB)return mW($);let J=tJ(A8(FZ),Z),{era:W,eraYear:j}=aj(J,FZ);return[W,j]}function f6($){return M$($),E6($,1),$}function M$($){return pW($,1),$}function ZW($){return TW(L8,$,pW($))}function pW($,Z){let{isoYear:J}=$,W=w0($,"isoMonth",1,vW(),Z);return{isoYear:J,isoMonth:W,isoDay:w0($,"isoDay",1,Z2(J,W),Z)}}function E6($,Z){return BZ(Z1,[w0($,"isoHour",0,23,Z),w0($,"isoMinute",0,59,Z),w0($,"isoSecond",0,59,Z),w0($,"isoMillisecond",0,999,Z),w0($,"isoMicrosecond",0,999,Z),w0($,"isoNanosecond",0,999,Z)])}function v($){return $===void 0?0:xz(x1($))}function G3($,Z=0){$=t0($);let J=Sz($),W=KB($,Z);return[xz($),W,J]}function W2($){return Sz(t0($))}function hW($){return $=t0($),N8($,9,6,1)}function OZ($,Z,J,W=9,j=0,Y=4){Z=t0(Z);let z=N8(Z,W,j),X=z2(Z),G=H3(Z,Y),Q=T3(Z,W,j,1);return z==null?z=Math.max(J,Q):lW(z,Q),X=X2(X,Q,1),$&&(G=((F)=>F<4?(F+2)%4:F)(G)),[z,Q,X,G]}function b6($,Z=6,J){let W=z2($=G2($,L6)),j=H3($,7),Y=T3($,Z);return Y=xW(L6,Y),W=X2(W,Y,void 0,J),[Y,W,j]}function j2($){return _8(t0($))}function cW($,Z){return Y2(t0($),Z)}function Y2($,Z=4){let J=uW($);return[H3($,4),...dW(T3($,Z),J)]}function dW($,Z){return $!=null?[X1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function z2($){let Z=$[eZ];return Z===void 0?1:N0(Z,eZ)}function X2($,Z,J,W){let j=W?c:X1[Z+1];if(j){let Y=X1[Z];if(j%(($=i0(eZ,$,1,j/Y-(W?0:1),1))*Y))throw RangeError(D3(eZ,$))}else $=i0(eZ,$,1,J?1e9:1,1);return $}function uW($){let Z=$[kJ];if(Z!==void 0){if(typeof Z!="number"){if(oJ(Z)==="auto")return;throw RangeError(D3(kJ,Z))}Z=i0(kJ,Math.floor(Z),0,9,1)}return Z}function t0($){return $===void 0?{}:x1($)}function G2($,Z){return typeof $=="string"?{[Z]:$}:x1($)}function z0($){if($!==void 0){if(O0($))return Object.assign(Object.create(null),$);throw TypeError(aY)}}function R6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:WB[Z]})}function Q2($,Z,J=9,W=0,j){let Y=Z[$];if(Y===void 0)return j?W:void 0;if(Y=oJ(Y),Y==="auto")return j?W:null;let z=mJ[Y];if(z===void 0&&(z=oK[Y]),z===void 0)throw RangeError($z($,Y,mJ));return i0($,z,W,J,1,U3),z}function N$($,Z,J,W=0){let j=J[$];if(j===void 0)return W;let Y=oJ(j),z=Z[Y];if(z===void 0)throw RangeError($z($,Y,Z));return z}function lW($,Z){if(Z>$)throw RangeError(hK)}function U0($){return{branding:X4,epochNanoseconds:$}}function I0($,Z,J){return{branding:E1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:R$,calendar:Z,...g0(Pz,$)}}function G0($,Z=$.calendar){return{branding:b$,calendar:Z,...g0(P8,$)}}function I$($,Z=$.calendar){return{branding:MZ,calendar:Z,...g0(P8,$)}}function U6($,Z=$.calendar){return{branding:NZ,calendar:Z,...g0(P8,$)}}function e0($){return{branding:z4,...g0(Lz,$)}}function s($){return{branding:G4,sign:a1($),...g0(T8,$)}}function iW($){return RW($.epochNanoseconds)}function w6($){return rJ($.epochNanoseconds,G1)[0]}function sW($){return bW($.epochNanoseconds,E$)}function nW($){return bW($.epochNanoseconds)}function oW($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:t($.id)}function UZ($,Z){return $===Z||T0($)===T0(Z)}function aW($,Z,J,W,j){let Y=L$(W),[z,X]=((V,H)=>{let P=H((V=G2(V,cJ))[Nz]),I=FB(V);return I=xW(cJ,I),[I,P]})(j,$);if(Z3(Math.max(z,Y),X))return JW(W,z);if(!X)throw RangeError($4);let[G,Q,F]=m6(Z,J,X),B=w2(F),K=p6(F),O=k2(F),D=K(Q,G,W),U=O(Q,G,D,z);return Z3(z,X)?JW(U,z):((V,H,P,I,C,f,E)=>{let S=a1(V),[M,L]=F2(I,I8(P,V),P,S,C,f,E),k=K2(H,M,L);return V[y[P]]+k*S})(U,B(D),z,Q,G,B,K)}function JW($,Z){return d0(D0($),X1[Z],1)}function F2($,Z,J,W,j,Y,z){let X=y[J],G={...Z,[X]:Z[X]+W},Q=z($,j,Z),F=z($,j,G);return[Y(Q),Y(F)]}function K2($,Z,J){let W=d0(c0(Z,J));if(!W)throw RangeError(O3);return d0(c0(Z,$))/W}function rW($,Z){let[J,W,j]=b6(Z,5,1);return U0(q6($.epochNanoseconds,J,W,j,1))}function tW($,Z,J){let{epochNanoseconds:W,timeZone:j,calendar:Y}=Z,[z,X,G]=b6(J);if(z===0&&X===1)return Z;let Q=$(j);if(z===6)W=((F,B,K,O)=>{let D=C0(K,B),[U,V]=F(D),H=K.epochNanoseconds,P=y0(B,U),I=y0(B,V);if(EW(H,P,I))throw RangeError(O3);return Xj(K2(H,P,I),O)?I:P})(Yj,Q,Z,G);else{let F=Q.getOffsetNanosecondsFor(W);W=x$(Q,Wj(o1(W,F),z,X,G),F,2,0,1)}return I0(W,j,Y)}function eW($,Z){return X0(Wj($,...b6(Z)),$.calendar)}function $j($,Z){let[J,W,j]=b6(Z,5);var Y;return e0((Y=j,B2($,Q3(J,W),Y)[0]))}function Zj($,Z){let J=$(Z.timeZone),W=C0(Z,J),[j,Y]=Yj(W),z=d0(c0(y0(J,j),y0(J,Y)),J4,1);if(z<=0)throw RangeError(O3);return z}function Jj($,Z){let{timeZone:J,calendar:W}=Z,j=((Y,z,X)=>y0(z,Y(C0(X,z))))(zj,$(J),Z);return I0(j,J,W)}function Wj($,Z,J,W){return jj($,Q3(Z,J),W)}function jj($,Z,J){let[W,j]=B2($,Z,J);return S1({...S$($,j),...W})}function B2($,Z,J){return C6(n1(s1($),Z,J))}function V6($){return n1($,Z4,7)}function Q3($,Z){return X1[$]*Z}function Yj($){let Z=zj($);return[Z,S$(Z,1)]}function zj($){return aK(6,$)}function WK($,Z,J){let W=Math.min(L$($),6);return TZ(v6(D0($,W),Z,J),W)}function k6($,Z,J,W,j,Y,z,X,G,Q){if(W===0&&j===1)return $;let F=Z3(W,X)?h6(X)&&W<6&&J>=6?YK:jK:zK,[B,K,O]=F($,Z,J,W,j,Y,z,X,G,Q);return O&&W!==7&&(B=((D,U,V,H,P,I,C,f)=>{let E=a1(D);for(let S=H+1;S<=V;S++){if(S===7&&V!==7)continue;let M=I8(S,D);M[y[S]]+=E;let L=d0(c0(C(f(P,I,M)),U));if(L&&Math.sign(L)!==E)break;D=M}return D})(B,K,J,Math.max(6,W),z,X,G,Q)),B}function q6($,Z,J,W,j){if(Z===6){let Y=((z)=>z[0]+z[1]/c)($);return[n1(Y,J,W),0]}return v6($,Q3(Z,J),W,j)}function v6($,Z,J,W){let[j,Y]=$;W&&Y<0&&(Y+=c,j-=1);let[z,X]=N1(n1(Y,Z,J),c);return aJ(j+z,X)}function n1($,Z,J){return Xj($/Z,J)*Z}function Xj($,Z){return OB[Z]($)}function jK($,Z,J,W,j,Y){let z=a1($),X=D0($),G=q6(X,W,j,Y),Q=c0(X,G),F=Math.sign(G[0]-X[0])===z,B=TZ(G,Math.min(J,6));return[{...$,...B},XZ(Z,Q),F]}function YK($,Z,J,W,j,Y,z,X,G,Q){let F=a1($),B=d0(D0($,5)),K=Q3(W,j),O=n1(B,K,Y),[D,U]=F2(z,{...$,...H8},6,F,X,G,Q),V=O-d0(c0(D,U)),H=0;V&&Math.sign(V)!==F?Z=GZ(D,O):(H+=F,O=n1(V,K,Y),Z=GZ(U,O));let P=d6(O);return[{...$,...P,days:$.days+H},Z,Boolean(H)]}function zK($,Z,J,W,j,Y,z,X,G,Q){let F=a1($),B=y[W],K=I8(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let O=M6($[B],j)*j;K[B]=O;let[D,U]=F2(z,K,W,j*F,X,G,Q),V=O+K2(Z,D,U)*F*j,H=n1(V,j,Y),P=Math.sign(H-V)===F;return K[B]=H,[K,P?U:D,P]}function D2($,Z,J,W){let[j,Y,z,X]=((Q)=>{let F=Y2(Q=t0(Q));return[Q.timeZone,...F]})(W),G=j!==void 0;return((Q,F,B,K,O,D)=>{B=v6(B,O,K,1);let U=F.getOffsetNanosecondsFor(B);return L2(o1(B,U),D)+(Q?_$(V6(U)):"Z")})(G,Z(G?$(j):w$),J.epochNanoseconds,Y,z,X)}function O2($,Z,J){let[W,j,Y,z,X,G]=((Q)=>{Q=t0(Q);let F=_8(Q),B=uW(Q),K=DB(Q),O=H3(Q,4),D=T3(Q,4);return[F,BB(Q),K,O,...dW(D,B)]})(J);return((Q,F,B,K,O,D,U,V,H,P)=>{K=v6(K,H,V,1);let I=Q(B).getOffsetNanosecondsFor(K);return L2(o1(K,I),P)+_$(V6(I),U)+((C,f)=>f!==1?"["+(f===2?"!":"")+T0(C)+"]":"")(B,D)+P2(F,O)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,j,Y,z,X,G)}function U2($,Z){let[J,W,j,Y]=((Q)=>(Q=t0(Q),[_8(Q),...Y2(Q)]))(Z);return z=$.calendar,X=J,G=Y,L2(jj($,j,W),G)+P2(z,X);var z,X,G}function V2($,Z){return J=$.calendar,W=$,j=j2(Z),T6(W)+P2(J,j);var J,W,j}function T2($,Z){return Gj($.calendar,Qj,$,j2(Z))}function H2($,Z){return Gj($.calendar,XK,$,j2(Z))}function I2($,Z){let[J,W,j]=cW(Z);return Y=j,Fj(B2($,W,J)[0],Y);var Y}function y6($,Z){let[J,W,j]=cW(Z,3);return W>1&&($={...$,...WK($,W,J)}),((Y,z)=>{let{sign:X}=Y,G=X===-1?A0(Y):Y,{hours:Q,minutes:F}=G,[B,K]=rJ(D0(G,3),n0,i1);Hj(B);let O=M2(K,z),D=z>=0||!X||O;return(X<0?"-":"")+"P"+WW({Y:H$(G.years),M:H$(G.months),W:H$(G.weeks),D:H$(G.days)})+(Q||F||B||D?"T"+WW({H:H$(Q),M:H$(F),S:H$(B,D)+O}):"")})($,j)}function Gj($,Z,J,W){let j=T0($),Y=W>1||W===0&&j!==w;return W===1?j===w?Z(J):T6(J):Y?T6(J)+Kj(j,W===2):Z(J)}function WW($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function L2($,Z){return T6($)+"T"+Fj($,Z)}function T6($){return Qj($)+"-"+s0($.isoDay)}function Qj($){let{isoYear:Z}=$;return(Z<0||Z>9999?Bj(Z)+B6(6,Math.abs(Z)):B6(4,Z))+"-"+s0($.isoMonth)}function XK($){return s0($.isoMonth)+"-"+s0($.isoDay)}function Fj($,Z){let J=[s0($.isoHour),s0($.isoMinute)];return Z!==-1&&J.push(s0($.isoSecond)+((W,j,Y,z)=>M2(W*G1+j*E$+Y,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function _$($,Z=0){if(Z===1)return"";let[J,W]=N1(Math.abs($),J4),[j,Y]=N1(W,Z4),[z,X]=N1(Y,n0);return Bj($)+s0(J)+":"+s0(j)+(z||X?":"+s0(z)+M2(X):"")}function P2($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==w)return Kj(J,Z===2)}return""}function Kj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function M2($,Z){let J=B6(9,$);return J=Z===void 0?J.replace(TB,""):J.slice(0,Z),J?"."+J:""}function Bj($){return $<0?"-":"+"}function H$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function GK($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),j=o1(J,W);return{calendar:$.calendar,...j,offsetNanoseconds:W}}function Dj($,Z){let J=C0(Z,$);return{calendar:Z.calendar,...g0(Pz,J),offset:_$(J.offsetNanoseconds),timeZone:Z.timeZone}}function x$($,Z,J,W=0,j=0,Y,z){if(J!==void 0&&W===1&&(W===1||z))return $2(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,F,B,K)=>{let O=_0(F);K&&(B=V6(B));for(let D of Q){let U=d0(c0(D,O));if(K&&(U=V6(U)),U===B)return D}})(X,Z,J,Y);if(G!==void 0)return G;if(W===0)throw RangeError(qK)}return z?_0(Z):y0($,Z,j,X)}function y0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(vK);if(W.length)return W[J===3?1:0];let j=_0(Z),Y=((X,G)=>{let Q=X.getOffsetNanosecondsFor(GZ(G,-c));return _2(X.getOffsetNanosecondsFor(GZ(G,c))-Q)})($,j),z=Y*(J===2?-1:1);return(W=$.getPossibleInstantsFor(o1(j,z)))[J===2?0:W.length-1]}function N2($){if(Math.abs($)>=c)throw RangeError(wK);return $}function _2($){if($>c)throw RangeError(kK);return $}function x2($,Z,J){return U0(u0(XZ(Z.epochNanoseconds,((W)=>{if(Ij(W))throw RangeError(mK);return D0(W,5)})($?A0(J):J))))}function S2($,Z,J,W,j,Y=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...b2(z,X,W,J?A0(j):j,Y)}}function C2($,Z,J,W,j=Object.create(null)){let{calendar:Y}=J;return X0(R2($(Y),J,Z?A0(W):W,j),Y)}function A2($,Z,J,W,j){let{calendar:Y}=J;return G0(g6($(Y),J,Z?A0(W):W,j),Y)}function f2($,Z,J,W,j=Object.create(null)){let Y=J.calendar,z=$(Y),X=$3(z,J);Z&&(W=c6(W)),W.sign<0&&(X=z.dateAdd(X,{...H0,months:1}),X=S$(X,-1));let G=z.dateAdd(X,W,j);return I$($3(z,G),Y)}function E2($,Z,J){return e0(Oj(Z,$?A0(J):J)[0])}function b2($,Z,J,W,j){let Y=D0(W,5),z=J.epochNanoseconds;if(Ij(W)){let X=C0(J,$);z=XZ(y0($,{...g6(Z,X,{...W,...H8},j),...g0(Z1,X)}),Y)}else z=XZ(z,Y),v(j);return{epochNanoseconds:u0(z)}}function R2($,Z,J,W){let[j,Y]=Oj(Z,J);return S1({...g6($,Z,{...J,...H8,days:J.days+Y},W),...j})}function g6($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);v(W);let j=J.days+D0(J,5)[0];return j?u1(S$(Z,j)):Z}function $3($,Z,J=1){return S$(Z,J-$.day(Z))}function Oj($,Z){let[J,W]=D0(Z,5),[j,Y]=C6(s1($)+W);return[j,J+Y]}function S$($,Z){return Z?{...$,...A6(S0($)+Z*q0)}:$}function m6($,Z,J){let W=$(J.calendar);return h6(J)?[J,W,Z(J.timeZone)]:[{...J,...o0},W]}function w2($){return $?oW:_0}function p6($){return $?R(b2,$):R2}function k2($){return $?R(FK,$):KK}function h6($){return $&&$.epochNanoseconds}function Z3($,Z){return $<=6-(h6(Z)?1:0)}function q2($,Z,J,W,j,Y,z){let X=$(t0(z).relativeTo),G=Math.max(L$(j),L$(Y));if(Z3(G,X))return s(VZ(((U,V,H,P)=>{let I=XZ(D0(U),D0(V),P?-1:1);if(!Number.isFinite(I[0]))throw RangeError(e6);return{...H0,...TZ(I,H)}})(j,Y,G,W)));if(!X)throw RangeError($4);W&&(Y=A0(Y));let[Q,F,B]=m6(Z,J,X),K=p6(B),O=k2(B),D=K(F,Q,j);return s(O(F,Q,K(F,D,Y),G))}function Uj($,Z,J,W,j){let Y=L$(W),[z,X,G,Q,F]=((E,S,M)=>{E=G2(E,L6);let L=N8(E),k=M(E[Nz]),m=z2(E),q1=H3(E,7),Z0=T3(E);if(L===void 0&&Z0===void 0)throw RangeError(pK);return Z0==null&&(Z0=0),L==null&&(L=Math.max(Z0,S)),lW(L,Z0),m=X2(m,Z0,1),[L,Z0,m,q1,k]})(j,Y,$),B=Math.max(Y,z);if(!h6(F)&&B<=6)return s(VZ(((E,S,M,L,k)=>{let m=q6(D0(E),M,L,k);return{...H0,...TZ(m,S)}})(W,z,X,G,Q)));if(!F)throw RangeError($4);let[K,O,D]=m6(Z,J,F),U=w2(D),V=p6(D),H=k2(D),P=V(O,K,W),I=H(O,K,P,z),C=W.sign,f=a1(I);if(C&&f&&C!==f)throw RangeError(O3);return f&&(I=k6(I,U(P),z,X,G,Q,O,K,U,V)),s(I)}function Vj($){return $.sign===-1?c6($):$}function c6($){return s(A0($))}function A0($){let Z={};for(let J of y)Z[J]=-1*$[J]||0;return Z}function Tj($){return!$.sign}function a1($,Z=y){let J=0;for(let W of Z){let j=Math.sign($[W]);if(j){if(J&&J!==j)throw RangeError(gK);J=j}}return J}function VZ($){for(let Z of nK)i0(Z,$[Z],-FW,FW,1);return Hj(d0(D0($),n0)),$}function Hj($){if(!Number.isSafeInteger($))throw RangeError(yK)}function D0($,Z=6){return IW($,Z,y)}function TZ($,Z=6){let[J,W]=$,j=N6(W,Z,y);if(j[y[Z]]+=J*(c/X1[Z]),!Number.isFinite(j[y[Z]]))throw RangeError(e6);return j}function d6($,Z=5){return N6($,Z,y)}function Ij($){return Boolean(a1($,Iz))}function L$($){let Z=9;for(;Z>0&&!$[y[Z]];Z--);return Z}function QK($,Z){return[$,Z]}function jW($){let Z=Math.floor($/F6)*F6;return[Z,Z+F6]}function Lj($){let Z=r1($=D6($));if(!Z)throw RangeError(k0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(k0($));J=HZ(Z.offset)}return Z.timeZone&&m2(Z.timeZone,1),U0($2(f6(Z),J))}function Pj($){let Z=r1(t($));if(!Z)throw RangeError(k0($));if(Z.timeZone)return Ej(Z,Z.offset?HZ(Z.offset):void 0);if(Z.m)throw RangeError(k0($));return Rj(Z)}function Mj($,Z){let J=r1(t($));if(!J||!J.timeZone)throw RangeError(k0($));let{offset:W}=J,j=W?HZ(W):void 0,[,Y,z]=G3(Z);return Ej(J,j,Y,z)}function HZ($){let Z=m2($);if(Z===void 0)throw RangeError(k0($));return Z}function Nj($){let Z=r1(t($));if(!Z||Z.m)throw RangeError(k0($));return X0(bj(Z))}function u6($){let Z=r1(t($));if(!Z||Z.m)throw RangeError(k0($));return G0(Z.p?bj(Z):Rj(Z))}function _j($,Z){let J=y2(t(Z));if(J)return v2(J),I$(eJ(M$(J)));let W=u6(Z);return I$($3($(W.calendar),W))}function v2($){if($.calendar!==w)throw RangeError(_1($.calendar))}function xj($,Z){let J=g2(t(Z));if(J)return v2(J),U6(M$(J));let W=u6(Z),{calendar:j}=W,Y=$(j),[z,X,G]=Y.h(W),[Q,F]=Y.I(z,X),[B,K]=Y.N(Q,F,G);return U6(u1(Y.P(B,K,G)),j)}function Sj($){let Z,J=((W)=>{let j=MB.exec(W);return j?(l6(j[10]),qj(j)):void 0})(t($));if(!J){if(J=r1($),!J)throw RangeError(k0($));if(!J.p)throw RangeError(k0($));if(J.m)throw RangeError(_1("Z"));v2(J)}if((Z=y2($))&&ZW(Z))throw RangeError(k0($));if((Z=g2($))&&ZW(Z))throw RangeError(k0($));return e0(E6(J,1))}function Cj($){let Z=((J)=>{let W=xB.exec(J);return W?((j)=>{function Y(F,B,K){let O=0,D=0;if(K&&([O,G]=N1(G,X1[K])),F!==void 0){if(X)throw RangeError(_1(F));D=((U)=>{let V=parseInt(U);if(!Number.isFinite(V))throw RangeError(_1(U));return V})(F),z=1,B&&(G=p2(B)*(X1[K]/n0),X=1)}return O+D}let z=0,X=0,G=0,Q={...BZ(y,[Y(j[2]),Y(j[3]),Y(j[4]),Y(j[5]),Y(j[6],j[7],5),Y(j[8],j[9],4),Y(j[10],j[11],3)]),...N6(G,2,y)};if(!z)throw RangeError(tY(y));return h2(j[1])<0&&(Q=A0(Q)),Q})(W):void 0})(t($));if(!Z)throw RangeError(k0($));return s(VZ(Z))}function Aj($){let Z=r1($)||y2($)||g2($);return Z?Z.calendar:$}function fj($){let Z=r1($);return Z&&(Z.timeZone||Z.m&&w$||Z.offset)||$}function Ej($,Z,J=0,W=0){let j=i6($.timeZone),Y=Q4(j);return I0(x$(Y,f6($),Z,J,W,!Y.v,$.m),j,F3($.calendar))}function bj($){return wj(S1(f6($)))}function Rj($){return wj(u1(M$($)))}function wj($){return{...$,calendar:F3($.calendar)}}function r1($){let Z=PB.exec($);return Z?((J)=>{let W=J[10],j=(W||"").toUpperCase()==="Z";return{isoYear:kj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...qj(J.slice(5)),...l6(J[16]),p:Boolean(J[6]),m:j,offset:j?void 0:W}})(Z):void 0}function y2($){let Z=IB.exec($);return Z?((J)=>({isoYear:kj(J),isoMonth:parseInt(J[4]),isoDay:1,...l6(J[5])}))(Z):void 0}function g2($){let Z=LB.exec($);return Z?((J)=>({isoYear:KZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...l6(J[3])}))(Z):void 0}function m2($,Z){let J=NB.exec($);return J?((W,j)=>{let Y=W[4]||W[5];if(j&&Y)throw RangeError(_1(Y));return N2((zZ(W[2])*J4+zZ(W[3])*Z4+zZ(W[4])*n0+p2(W[5]||""))*h2(W[1]))})(J,Z):void 0}function kj($){let Z=h2($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(_1(-0));return Z*J}function qj($){let Z=zZ($[3]);return{...C6(p2($[4]||""))[0],isoHour:zZ($[1]),isoMinute:zZ($[2]),isoSecond:Z===60?59:Z}}function l6($){let Z,J,W=[];if($.replace(_B,(j,Y,z)=>{let X=Boolean(Y),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")W.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(_1(j))}else{if(J)throw RangeError(_1(j));J=G}return""}),W.length>1&&Z)throw RangeError(_1($));return{timeZone:J,calendar:W[0]||w}}function p2($){return parseInt($.padEnd(9,"0"))}function IZ($){return new RegExp(`^${$}$`,"i")}function h2($){return $&&$!=="+"?-1:1}function zZ($){return $===void 0?0:parseInt($)}function vj($){return i6(t($))}function i6($){let Z=c2($);return typeof Z=="number"?_$(Z):Z?((J)=>{if(CB.test(J))throw RangeError(RK);return J.toLowerCase().split("/").map((W,j)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(Y,z)=>Y.length<=2&&!j||Y==="in"||Y==="chat"?Y.toUpperCase():Y.length>2||!z?e9(Y).replace(/island|noronha|murdo|rivadavia|urville/,e9):Y)).join("/")})($):w$}function YW($){let Z=c2($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:w$}function c2($){let Z=m2($=$.toUpperCase(),1);return Z!==void 0?Z:$!==w$?SB($):void 0}function d2($,Z){return x0($.epochNanoseconds,Z.epochNanoseconds)}function u2($,Z){return x0($.epochNanoseconds,Z.epochNanoseconds)}function yj($,Z,J,W,j,Y){let z=$(t0(Y).relativeTo),X=Math.max(L$(W),L$(j));if(TW(y,W,j))return 0;if(Z3(X,z))return x0(D0(W),D0(j));if(!z)throw RangeError($4);let[G,Q,F]=m6(Z,J,z),B=w2(F),K=p6(F);return x0(B(K(Q,G,W)),B(K(Q,G,j)))}function l2($,Z){return C$($,Z)||s6($,Z)}function C$($,Z){return d1(S0($),S0(Z))}function s6($,Z){return d1(s1($),s1(Z))}function gj($,Z){return!d2($,Z)}function mj($,Z){return!u2($,Z)&&!!n6($.timeZone,Z.timeZone)&&UZ($.calendar,Z.calendar)}function pj($,Z){return!l2($,Z)&&UZ($.calendar,Z.calendar)}function hj($,Z){return!C$($,Z)&&UZ($.calendar,Z.calendar)}function cj($,Z){return!C$($,Z)&&UZ($.calendar,Z.calendar)}function dj($,Z){return!C$($,Z)&&UZ($.calendar,Z.calendar)}function uj($,Z){return!s6($,Z)}function n6($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return YW(J)===YW(W)}catch(j){}}function i2($,Z,J,W){let j=OZ($,z0(W),3,5),Y=o6(Z.epochNanoseconds,J.epochNanoseconds,...j);return s($?A0(Y):Y)}function s2($,Z,J,W,j,Y){let z=r6(W.calendar,j.calendar),X=z0(Y),[G,Q,F,B]=OZ(J,X,5),K=W.epochNanoseconds,O=j.epochNanoseconds,D=x0(O,K),U;if(D)if(G<6)U=o6(K,O,G,Q,F,B);else{let V=Z(((P,I)=>{if(!n6(P,I))throw RangeError(jz);return P})(W.timeZone,j.timeZone)),H=$(z);U=ij(H,V,W,j,D,G,X),U=k6(U,O,G,Q,F,B,H,W,oW,R(b2,V))}else U=H0;return s(J?A0(U):U)}function n2($,Z,J,W,j){let Y=r6(J.calendar,W.calendar),z=z0(j),[X,G,Q,F]=OZ(Z,z,6),B=_0(J),K=_0(W),O=x0(K,B),D;if(O)if(X<=6)D=o6(B,K,X,G,Q,F);else{let U=$(Y);D=sj(U,J,W,O,X,z),D=k6(D,K,X,G,Q,F,U,J,_0,R2)}else D=H0;return s(Z?A0(D):D)}function o2($,Z,J,W,j){let Y=r6(J.calendar,W.calendar),z=z0(j);return lj(Z,()=>$(Y),J,W,...OZ(Z,z,6,9,6),z)}function a2($,Z,J,W,j){let Y=r6(J.calendar,W.calendar),z=z0(j),X=OZ(Z,z,9,9,8),G=$(Y);return lj(Z,()=>G,$3(G,J),$3(G,W),...X,z)}function lj($,Z,J,W,j,Y,z,X,G){let Q=_0(J),F=_0(W),B;if(x0(F,Q))if(j===6)B=o6(Q,F,j,Y,z,X);else{let K=Z();B=K.dateUntil(J,W,j,G),Y===6&&z===1||(B=k6(B,F,j,Y,z,X,K,J,_0,g6))}else B=H0;return s($?A0(B):B)}function r2($,Z,J,W){let j=z0(W),[Y,z,X,G]=OZ($,j,5,5),Q=n1(t2(Z,J),Q3(z,X),G),F={...H0,...d6(Q,Y)};return s($?A0(F):F)}function FK($,Z,J,W,j,Y){let z=x0(W.epochNanoseconds,J.epochNanoseconds);return z?j<6?nj(J.epochNanoseconds,W.epochNanoseconds,j):ij(Z,$,J,W,z,j,Y):H0}function KK($,Z,J,W,j){let Y=_0(Z),z=_0(J),X=x0(z,Y);return X?W<=6?nj(Y,z,W):sj($,Z,J,X,W,j):H0}function ij($,Z,J,W,j,Y,z){let[X,G,Q]=((K,O,D,U)=>{function V(){return S={...S$(I,f++*-U),...P},M=y0(K,S),x0(C,M)===-U}let H=C0(O,K),P=g0(Z1,H),I=C0(D,K),C=D.epochNanoseconds,f=0,E=t2(H,I),S,M;if(Math.sign(E)===-U&&f++,V()&&(U===-1||V()))throw RangeError(O3);let L=d0(c0(M,C));return[H,S,L]})(Z,J,W,j);var F,B;return{...Y===6?(F=X,B=G,{...H0,days:oj(F,B)}):$.dateUntil(X,G,Y,z),...d6(Q)}}function sj($,Z,J,W,j,Y){let[z,X,G]=((Q,F,B)=>{let K=F,O=t2(Q,F);return Math.sign(O)===-B&&(K=S$(F,-B),O+=c*B),[Q,K,O]})(Z,J,W);return{...$.dateUntil(z,X,j,Y),...d6(G)}}function o6($,Z,J,W,j,Y){return{...H0,...TZ(q6(c0($,Z),W,j,Y),J)}}function nj($,Z,J){return{...H0,...TZ(c0($,Z),J)}}function oj($,Z){return a6(S0($),S0(Z))}function a6($,Z){return Math.trunc((Z-$)/q0)}function t2($,Z){return s1(Z)-s1($)}function r6($,Z){if(!UZ($,Z))throw RangeError(D8);return $}function BK($){function Z(j){return((Y,z)=>({...aj(Y,z),F:Y.month,day:parseInt(Y.day)}))(tJ(J,j),W)}let J=A8($),W=H6($);return{id:$,O:DK(Z),B:OK(Z)}}function DK($){return v0((Z)=>{let J=S0(Z);return $(J)},WeakMap)}function OK($){let Z=$(0).year-$B;return v0((J)=>{let W,j=DZ(J-Z),Y=[],z=[];do j+=400*q0;while((W=$(j)).year<=J);do j+=(1-W.day)*q0,W.year===J&&(Y.push(j),z.push(W.F)),j-=q0;while((W=$(j)).year>=J);return{k:Y.reverse(),C:Xz(z.reverse())}})}function aj($,Z){let J,W,j=rj($);if($.era){let Y=Vz[Z];Y!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=j,j=JY(W,Y[J]||0))}return{era:J,eraYear:W,year:j}}function rj($){return parseInt($.relatedYear||$.year)}function vJ($){let{year:Z,F:J,day:W}=this.O($),{C:j}=this.B(Z);return[Z,j[J]+1,W]}function J3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*q0}function X6($){let Z=XW(this,$),J=XW(this,$-1),W=Z.length;if(W>J.length){let j=WY(this);if(j<0)return-j;for(let Y=0;Y<W;Y++)if(Z[Y]!==J[Y])return Y+1}}function G6($){return a6(J3.call(this,$),J3.call(this,$+1))}function zW($,Z){let{k:J}=this.B($),W=Z+1,j=J;return W>J.length&&(W=1,j=this.B($+1).k),a6(J[Z-1],j[W-1])}function Q6($){return this.B($).k.length}function XW($,Z){return Object.keys($.B(Z).C)}function tj($){return F3(t($))}function F3($){if(($=$.toLowerCase())!==w&&$!==j4&&H6($)!==H6(A8($).resolvedOptions().calendar))throw RangeError(bK($));return $}function H6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function ej($){return this.R($)[0]}function $Y($){return this.R($)[1]}function e2($){let[Z]=this.h($);return a6(this.q(Z),S0($))+1}function ZY($){let Z=fB.exec($);if(!Z)throw RangeError(fK($));return[parseInt(Z[1]),Boolean(Z[2])]}function I6($,Z,J){return $+(Z||J&&$>=J?1:0)}function yJ($,Z){return $-(Z&&$>=Z?1:0)}function JY($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function gJ($){return Vz[jY($)]}function WY($){return lK[jY($)]}function jY($){return H6($.id||w)}function YY($,Z,J,W){let j=t1(J,W,$1,[],Bz);if(j.timeZone!==void 0){let Y=J.dateFromFields(j),z=A$(j),X=$(j.timeZone);return{epochNanoseconds:x$(Z(X),{...Y,...z},j.offset!==void 0?HZ(j.offset):void 0),timeZone:X}}return{...J.dateFromFields(j),...o0}}function zY($,Z,J,W,j,Y){let z=t1(J,j,$1,Fz,Bz),X=$(z.timeZone),[G,Q,F]=G3(Y),B=J.dateFromFields(z,R6(Y,G)),K=A$(z,G);return I0(x$(Z(X),{...B,...K},z.offset!==void 0?HZ(z.offset):void 0,Q,F),X,W)}function XY($,Z,J){let W=t1($,Z,$1,[],f1),j=v(J);return X0(S1({...$.dateFromFields(W,R6(J,j)),...A$(W,j)}))}function $8($,Z,J,W=[]){let j=t1($,Z,$1,W);return $.dateFromFields(j,J)}function Z8($,Z,J,W){let j=t1($,Z,V8,W);return $.yearMonthFromFields(j,J)}function J8($,Z,J,W,j=[]){let Y=t1($,J,$1,j);return Z&&Y.month!==void 0&&Y.monthCode===void 0&&Y.year===void 0&&(Y.year=KZ),$.monthDayFromFields(Y,W)}function GY($,Z){let J=v(Z);return e0(A$(z1($,pJ,[],1),J))}function QY($){let Z=z1($,T8);return s(VZ({...H0,...Z}))}function t1($,Z,J,W=[],j=[]){return z1(Z,[...$.fields(J),...j].sort(),W)}function z1($,Z,J,W=!J){let j={},Y,z=0;for(let X of Z){if(X===Y)throw RangeError(NK(X));if(X==="constructor"||X==="__proto__")throw RangeError(K8(X));let G=$[X];if(G!==void 0)z=1,KW[X]&&(G=KW[X](G,X)),j[X]=G;else if(J){if(J.includes(X))throw TypeError(F8(X));j[X]=Uz[X]}Y=X}if(W&&!z)throw TypeError(tY(Z));return j}function A$($,Z){return E6(wB({...Uz,...$}),Z)}function FY($,Z,J,W,j,Y){let z=z0(Y),{calendar:X,timeZone:G}=J;return I0(((Q,F,B,K,O)=>{let D=K3(Q,B,K,$1,Kz,Qz),[U,V,H]=G3(O,2);return x$(F,{...Q.dateFromFields(D,R6(O,U)),...A$(D,U)},HZ(D.offset),V,H)})($(X),Z(G),W,j,z),G,X)}function KY($,Z,J,W,j){let Y=z0(j);return X0(((z,X,G,Q)=>{let F=K3(z,X,G,$1,f1),B=v(Q);return S1({...z.dateFromFields(F,R6(Q,B)),...A$(F,B)})})($(Z.calendar),J,W,Y))}function BY($,Z,J,W,j){let Y=z0(j);return((z,X,G,Q)=>{let F=K3(z,X,G,$1);return z.dateFromFields(F,Q)})($(Z.calendar),J,W,Y)}function DY($,Z,J,W,j){let Y=z0(j);return I$(((z,X,G,Q)=>{let F=K3(z,X,G,V8);return z.yearMonthFromFields(F,Q)})($(Z.calendar),J,W,Y))}function OY($,Z,J,W,j){let Y=z0(j);return((z,X,G,Q)=>{let F=K3(z,X,G,$1);return z.monthDayFromFields(F,Q)})($(Z.calendar),J,W,Y)}function UY($,Z,J){return e0(((W,j,Y)=>{let z=v(Y);return A$({...g0(pJ,W),...z1(j,pJ)},z)})($,Z,J))}function VY($,Z){return s((J=$,W=Z,VZ({...J,...z1(W,T8)})));var J,W}function K3($,Z,J,W,j=[],Y=[]){let z=[...$.fields(W),...j].sort(),X=z1(Z,z,Y),G=z1(J,z);return X=$.mergeFields(X,G),z1(X,z,[])}function W8($,Z){let J=t1($,Z,Oz);return $.monthDayFromFields(J)}function j8($,Z,J){let W=t1($,Z,Dz);return $.yearMonthFromFields(W,J)}function TY($,Z,J,W,j){Z=g0(J=$.fields(J),Z),W=z1(W,j=$.fields(j),[]);let Y=$.mergeFields(Z,W);return Y=z1(Y,[...J,...j].sort(),[]),$.dateFromFields(Y)}function bJ($,Z){let{era:J,eraYear:W,year:j}=Z,Y=gJ($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(xK);if(!Y)throw RangeError(_K);let z=Y[J];if(z===void 0)throw RangeError(CK(J));let X=JY(W,z);if(j!==void 0&&j!==X)throw RangeError(SK);j=X}else if(j===void 0)throw TypeError(AK(Y));return j}function RJ($,Z,J,W){let{month:j,monthCode:Y}=Z;if(Y!==void 0){let z=((X,G,Q,F)=>{let B=X.U(Q),[K,O]=ZY(G),D=I6(K,O,B);if(O){let U=WY(X);if(U===void 0)throw RangeError(rZ);if(U>0){if(D>U)throw RangeError(rZ);if(B===void 0){if(F===1)throw RangeError(rZ);D--}}else{if(D!==-U)throw RangeError(rZ);if(B===void 0&&F===1)throw RangeError(rZ)}}return D})($,Y,J,W);if(j!==void 0&&j!==z)throw RangeError(Jz);j=z,W=1}else if(j===void 0)throw TypeError(EK);return i0("month",j,1,$.L(J),W)}function GW($,Z,J,W,j){return w0(Z,"day",1,$.j(W,J),j)}function wJ($,Z,J,W){let j=0,Y=[];for(let z of J)Z[z]!==void 0?j=1:Y.push(z);if(Object.assign($,Z),j)for(let z of W||Y)delete $[z]}function HY($){return U0(u0(S6(x6($))))}function IY($,Z,J,W,j=w){return I0(u0(S6(x6(J))),Z(W),$(j))}function LY($,Z,J,W,j=0,Y=0,z=0,X=0,G=0,Q=0,F=w){return X0(S1(f6(a0(N0,BZ(Y4,[Z,J,W,j,Y,z,X,G,Q])))),$(F))}function PY($,Z,J,W,j=w){return G0(u1(M$(a0(N0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(j))}function MY($,Z,J,W=w,j=1){let Y=N0(Z),z=N0(J),X=$(W);return I$(eJ(M$({isoYear:Y,isoMonth:z,isoDay:N0(j)})),X)}function NY($,Z,J,W=w,j=KZ){let Y=N0(Z),z=N0(J),X=$(W);return U6(u1(M$({isoYear:N0(j),isoMonth:Y,isoDay:z})),X)}function _Y($=0,Z=0,J=0,W=0,j=0,Y=0){return e0(E6(a0(N0,BZ(Z1,[$,Z,J,W,j,Y])),1))}function xY($=0,Z=0,J=0,W=0,j=0,Y=0,z=0,X=0,G=0,Q=0){return s(VZ(a0(fW,BZ(y,[$,Z,J,W,j,Y,z,X,G,Q]))))}function Y8($,Z,J=w){return I0($.epochNanoseconds,Z,J)}function SY($){return U0($.epochNanoseconds)}function z8($,Z){return X0(C0(Z,$))}function X8($,Z){return G0(C0(Z,$))}function CY($,Z,J){return j8($(Z.calendar),J)}function AY($,Z,J){return W8($(Z.calendar),J)}function G8($,Z){return e0(C0(Z,$))}function fY($,Z,J,W){let j=((Y,z,X,G)=>{let Q=W2(G);return y0(Y(z),X,Q)})($,J,Z,W);return I0(u0(j),J,Z.calendar)}function EY($,Z,J){let W=$(Z.calendar);return I$({...Z,...j8(W,J)})}function bY($,Z,J){return W8($(Z.calendar),J)}function RY($,Z,J,W,j){let Y=$(j.timeZone),z=j.plainTime,X=z!==void 0?Z(z):o0;return I0(y0(J(Y),{...W,...X}),Y,W.calendar)}function wY($,Z=o0){return X0(S1({...$,...Z}))}function kY($,Z,J){return j8($(Z.calendar),J)}function qY($,Z,J){return W8($(Z.calendar),J)}function vY($,Z,J,W){return((j,Y,z)=>TY(j,Y,Dz,x1(z),V3))($(Z.calendar),J,W)}function yY($,Z,J,W){return((j,Y,z)=>TY(j,Y,Oz,x1(z),W4))($(Z.calendar),J,W)}function gY($,Z,J,W,j){let Y=x1(j),z=Z(Y.plainDate),X=$(Y.timeZone);return I0(y0(J(X),{...z,...W}),X,z.calendar)}function mY($,Z){return X0(S1({...$,...Z}))}function pY($){return U0(u0(QZ($,n0)))}function hY($){return U0(u0(QZ($,G1)))}function cY($){return U0(u0(S6(x6($),E$)))}function dY($){return U0(u0(S6(x6($))))}function uY($,Z,J=o0){let W=Z.timeZone,j=$(W),Y={...C0(Z,j),...J};return I0(x$(j,Y,Y.offsetNanoseconds,2),W,Z.calendar)}function lY($,Z,J){let W=Z.timeZone,j=$(W),Y={...C0(Z,j),...J},z=oY(Z.calendar,J.calendar);return I0(x$(j,Y,Y.offsetNanoseconds,2),W,z)}function iY($,Z=o0){return X0({...$,...Z})}function sY($,Z){return X0({...$,...Z},oY($.calendar,Z.calendar))}function t6($,Z){return{...$,calendar:Z}}function nY($,Z){return{...$,timeZone:Z}}function oY($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===w)return Z;if(W===w)return $;throw RangeError(D8)}function UK($,Z){return(J)=>J===w?$:J===j4||J===FZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),AB(J))}function f$($,Z,J){let W=new Set(J);return(j)=>(((Y,z)=>{for(let X of z)if(X in Y)return 1;return 0})(j=uJ(W,j),$)||Object.assign(j,Z),J&&(j.timeZone=w$,["full","long"].includes(j.timeStyle)&&(j.timeStyle="medium")),j)}function C1($,Z=Q8){let[J,,,W]=$;return(j,Y=oB,...z)=>{let X=Z(W&&W(...z),j,Y,J),G=X.resolvedOptions();return[X,...VK($,G,z)]}}function Q8($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(cK);J.timeZone=$}return new e1(Z,J)}function VK($,Z,J){let[,W,j]=$;return J.map((Y)=>(Y.calendar&&((z,X,G)=>{if((G||z!==w)&&z!==X)throw RangeError(D8)})(T0(Y.calendar),Z.calendar,j),W(Y,Z)))}function LZ($){let Z=B3();return o1(Z,$.getOffsetNanosecondsFor(Z))}function B3(){return QZ(Date.now(),G1)}function A1(){return DW||(DW=new e1().resolvedOptions().timeZone)}var TK=($,Z)=>`Non-integer ${$}: ${Z}`,HK=($,Z)=>`Non-positive ${$}: ${Z}`,IK=($,Z)=>`Non-finite ${$}: ${Z}`,LK=($)=>`Cannot convert bigint to ${$}`,PK=($)=>`Invalid bigint: ${$}`,MK="Cannot convert Symbol to string",aY="Invalid object",rY=($,Z,J,W,j)=>j?rY($,j[Z],j[J],j[W]):D3($,Z)+`; must be between ${J}-${W}`,D3=($,Z)=>`Invalid ${$}: ${Z}`,F8=($)=>`Missing ${$}`,K8=($)=>`Invalid field ${$}`,NK=($)=>`Duplicate field ${$}`,tY=($)=>"No valid fields: "+$.join(),eY="Invalid bag",$z=($,Z,J)=>D3($,Z)+"; must be "+Object.keys(J).join(),Zz="Cannot use valueOf",B8="Invalid calling context",_K="Forbidden era/eraYear",xK="Mismatching era/eraYear",SK="Mismatching year/eraYear",CK=($)=>`Invalid era: ${$}`,AK=($)=>"Missing year"+($?"/era/eraYear":""),fK=($)=>`Invalid monthCode: ${$}`,Jz="Mismatching month/monthCode",EK="Missing month/monthCode",QW="Cannot guess year",rZ="Invalid leap month",Wz="Invalid protocol",O3="Invalid protocol results",D8="Mismatching Calendars",bK=($)=>`Invalid Calendar: ${$}`,jz="Mismatching TimeZones",RK="Forbidden ICU TimeZone",wK="Out-of-bounds offset",kK="Out-of-bounds TimeZone gap",qK="Invalid TimeZone offset",vK="Ambiguous offset",e6="Out-of-bounds date",yK="Out-of-bounds duration",gK="Cannot mix duration signs",$4="Missing relativeTo",mK="Cannot use large units",pK="Required smallestUnit or largestUnit",hK="smallestUnit > largestUnit",k0=($)=>`Cannot parse: ${$}`,_1=($)=>`Invalid substring: ${$}`,Yz=($)=>`Cannot format ${$}`,zz="Mismatching types for formatting",cK="Cannot specify TimeZone",Xz=R(Y3,($,Z)=>Z),PZ=R(Y3,($,Z,J)=>J),s0=R(B6,2),mJ={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},U3=Object.keys(mJ),q0=86400000,Gz=1000,E$=1000,G1=1e6,n0=1e9,Z4=60000000000,J4=3600000000000,c=86400000000000,X1=[1,E$,G1,n0,Z4,J4,c],f1=U3.slice(0,6),pJ=z3(f1),Qz=["offset"],Fz=["timeZone"],Kz=f1.concat(Qz),Bz=Kz.concat(Fz),hJ=["era","eraYear"],dK=hJ.concat(["year"]),W4=["year"],O8=["monthCode"],U8=["month"].concat(O8),V3=["day"],V8=U8.concat(W4),Dz=O8.concat(W4),$1=V3.concat(V8),uK=V3.concat(U8),Oz=V3.concat(O8),Uz=PZ(f1,0),w="iso8601",j4="gregory",FZ="japanese",Vz={[j4]:{bce:-1,ce:0},[FZ]:{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}},lK={chinese:13,dangi:13,hebrew:-6},t=R(_6,"string"),Tz=R(_6,"boolean"),iK=R(_6,"number"),Hz=R(_6,"function"),y=U3.map(($)=>$+"s"),T8=z3(y),sK=y.slice(0,6),Iz=y.slice(6),nK=Iz.slice(1),oK=Xz(y),H0=PZ(y,0),H8=PZ(sK,0),I8=R(HW,y),Z1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],L8=["isoDay","isoMonth","isoYear"],Y4=Z1.concat(L8),P8=z3(L8),Lz=z3(Z1),Pz=z3(Y4),o0=PZ(Lz,0),aK=R(HW,Y4),e1=Intl.DateTimeFormat,Mz="en-GB",M8=1e8,rK=M8*q0,tK=[M8,0],eK=[-M8,0],W3=275760,j3=-271821,$B=1970,KZ=1972,M1=12,ZB=DZ(1868,9,8),JB=v0(JK,WeakMap),L6="smallestUnit",cJ="unit",eZ="roundingIncrement",kJ="fractionalSecondDigits",Nz="relativeTo",_z={constrain:0,reject:1},WB=Object.keys(_z),jB={compatible:0,reject:1,earlier:2,later:3},YB={reject:0,use:1,prefer:2,ignore:3},zB={auto:0,never:1,critical:2,always:3},XB={auto:0,never:1,critical:2},GB={auto:0,never:1},QB={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},T3=R(Q2,L6),N8=R(Q2,"largestUnit"),FB=R(Q2,cJ),xz=R(N$,"overflow",_z),Sz=R(N$,"disambiguation",jB),KB=R(N$,"offset",YB),_8=R(N$,"calendarName",zB),BB=R(N$,"timeZoneName",XB),DB=R(N$,"offset",GB),H3=R(N$,"roundingMode",QB),MZ="PlainYearMonth",NZ="PlainMonthDay",b$="PlainDate",R$="PlainDateTime",z4="PlainTime",E1="ZonedDateTime",X4="Instant",G4="Duration",OB=[Math.floor,($)=>z6($)?Math.floor($):Math.round($),Math.ceil,($)=>z6($)?Math.ceil($):Math.round($),Math.trunc,($)=>z6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>z6($)?($=Math.trunc($)||0)+$%2:Math.round($)],w$="UTC",F6=5184000,UB=O6(1847),VB=O6(new Date().getUTCFullYear()+10),TB=/0+$/,C0=v0(GK,WeakMap),FW=4294967295,Q4=v0(($)=>{let Z=c2($);return typeof Z=="object"?new Az(Z):new Cz(Z||0)});class Cz{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[$2($,this.v)]}l(){}}class Az{constructor($){this.$=((Z)=>{function J(G){let Q=qJ(G,z,X),[F,B]=jW(Q),K=j(F),O=j(B);return K===O?K:W(Y(F,B),K,O,G)}function W(G,Q,F,B){let K,O;for(;(B===void 0||(K=B<G[0]?Q:B>=G[1]?F:void 0)===void 0)&&(O=G[1]-G[0]);){let D=G[0]+Math.floor(O/2);Z(D)===F?G[1]=D:G[0]=D+1}return K}let j=v0(Z),Y=v0(QK),z=UB,X=VB;return{G(G){let Q=J(G-86400),F=J(G+86400),B=G-Q,K=G-F;if(Q===F)return[B];let O=J(B);return O===J(K)?[G-O]:Q>F?[B,K]:[]},V:J,l(G,Q){let F=qJ(G,z,X),[B,K]=jW(F),O=F6*Q,D=Q<0?()=>K>z||(z=F,0):()=>B<X||(X=F,0);for(;D();){let U=j(B),V=j(K);if(U!==V){let H=Y(B,K);W(H,U,V);let P=H[0];if((d1(P,G)||1)===Q)return P}B+=O,K+=O}}}})(((Z)=>(J)=>{let W=tJ(Z,J*Gz);return O6(rj(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(RW($))*n0}getPossibleInstantsFor($){let[Z,J]=[O6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*G1+W.isoMicrosecond*E$+W.isoNanosecond];var W;return this.$.G(Z).map((j)=>u0(GZ(QZ(j,n0),J)))}l($,Z){let[J,W]=wW($),j=this.$.l(J+(Z>0||W?1:0),Z);if(j!==void 0)return QZ(j,n0)}}var x8="([+\u2212-])",K6="(?:[.,](\\d{1,9}))?",fz=`(?:(?:${x8}(\\d{6}))|(\\d{4}))-?(\\d{2})`,S8="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+K6+")?)?",C8=x8+S8,HB=fz+"-?(\\d{2})(?:[T ]"+S8+"(Z|"+C8+")?)?",Ez="\\[(!?)([^\\]]*)\\]",F4=`((?:${Ez}){0,9})`,IB=IZ(fz+F4),LB=IZ("(?:--)?(\\d{2})-?(\\d{2})"+F4),PB=IZ(HB+F4),MB=IZ("T?"+S8+"(?:"+C8+")?"+F4),NB=IZ(C8),_B=new RegExp(Ez,"g"),xB=IZ(`${x8}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${K6}H)?(?:(\\d+)${K6}M)?(?:(\\d+)${K6}S)?)?`),SB=v0(($)=>new e1(Mz,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),CB=/^(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$/,AB=v0(BK),A8=v0(($)=>new e1(Mz,{calendar:$,timeZone:w$,era:"short",year:"numeric",month:"short",day:"numeric"})),fB=/^M(\d{2})(L?)$/,EB={era:D6,eraYear:N0,year:N0,month:$W,monthCode:D6,day:$W},bB=PZ(f1,N0),RB=PZ(y,fW),KW=Object.assign({},EB,bB,RB,{offset:D6}),wB=R(ZK,f1,Z1),BW={dateAdd($,Z,J){let W=v(J),j,{years:Y,months:z,weeks:X,days:G}=Z;if(G+=D0(Z,5)[0],Y||z)j=((Q,F,B,K,O)=>{let[D,U,V]=Q.h(F);if(B){let[H,P]=Q.I(D,U);D+=B,U=I6(H,P,Q.U(D)),U=i0("month",U,1,Q.L(D),O)}return K&&([D,U]=Q._(D,U,K)),V=i0("day",V,1,Q.j(D,U),O),Q.q(D,U,V)})(this,$,Y,z,W);else{if(!X&&!G)return $;j=S0($)}return j+=(7*X+G)*q0,u1(A6(j))},dateUntil($,Z,J){if(J<=7){let G=0,Q=oj({...$,...o0},{...Z,...o0});return J===7&&([G,Q]=i1(Q,7)),{...H0,weeks:G,days:Q}}let W=this.h($),j=this.h(Z),[Y,z,X]=((G,Q,F,B,K,O,D)=>{let U=K-Q,V=O-F,H=D-B;if(U||V){let P=Math.sign(U||V),I=G.j(K,O),C=0;if(Math.sign(H)===-P){let f=I;[K,O]=G._(K,O,-P),U=K-Q,V=O-F,I=G.j(K,O),C=P<0?-f:I}if(H=D-Math.min(B,I)+C,U){let[f,E]=G.I(Q,F),[S,M]=G.I(K,O);if(V=S-f||Number(M)-Number(E),Math.sign(V)===-P){let L=P<0&&-G.L(K);U=(K-=P)-Q,V=O-I6(f,E,G.U(K))+(L||G.L(K))}}}return[U,V,H]})(this,...W,...j);return J===8&&(z+=this.J(Y,W[0]),Y=0),{...H0,years:Y,months:z,days:X}},dateFromFields($,Z){let J=v(Z),W=bJ(this,$),j=RJ(this,$,W,J),Y=GW(this,$,j,W,J);return G0(u1(this.P(W,j,Y)),this.id||w)},yearMonthFromFields($,Z){let J=v(Z),W=bJ(this,$),j=RJ(this,$,W,J);return I$(eJ(this.P(W,j,1)),this.id||w)},monthDayFromFields($,Z){let J=v(Z),W=!this.id,{monthCode:j,year:Y,month:z}=$,X,G,Q,F,B;if(j!==void 0){[X,G]=ZY(j),B=OW($,"day");let K=this.N(X,G,B);if(!K)throw RangeError(QW);if([Q,F]=K,z!==void 0&&z!==F)throw RangeError(Jz);W&&(F=i0("month",F,1,M1,1),B=i0("day",B,1,Z2(Y!==void 0?Y:Q,F),J))}else{Q=Y===void 0&&W?KZ:bJ(this,$),F=RJ(this,$,Q,J),B=GW(this,$,F,Q,J);let K=this.U(Q);G=F===K,X=yJ(F,K);let O=this.N(X,G,B);if(!O)throw RangeError(QW);[Q,F]=O}return U6(u1(this.P(Q,F,B)),this.id||w)},fields($){return gJ(this)&&$.includes("year")?[...$,...hJ]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return wJ(J,Z,U8),gJ(this)&&(wJ(J,Z,dK),this.id===FZ&&wJ(J,Z,uK,hJ)),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:e2,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,j]=this.I(Z,J);return((Y,z)=>"M"+s0(Y)+(z?"L":""))(W,j)},dayOfWeek:gW,daysInWeek(){return 7}},kB={dayOfYear:e2,h:qW,q:DZ},qB=Object.assign({},kB,{weekOfYear:ej,yearOfWeek:$Y,R($){function Z(O){return(7-O<W?7:0)-O}function J(O){let D=yW(K+O),U=O||1,V=Z(tZ(G+D*U,7));return F=(D+(V-Q)*U)/7}let W=this.id?1:4,j=gW($),Y=this.dayOfYear($),z=tZ(j-1,7),X=Y-1,G=tZ(z-X,7),Q=Z(G),F,B=Math.floor((X-Q)/7)+1,K=$.isoYear;return B?B>J(0)&&(B=1,K++):(B=J(-1),K--),[B,K,F]}}),vB={dayOfYear:e2,h:vJ,q:J3,weekOfYear:ej,yearOfWeek:$Y,R(){return[]}},_Z=UK(Object.assign({},BW,qB,{h:qW,ee($){return this.id===j4?mW($):this.id===FZ?JB($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[KZ,$]},K:J2,U(){},L:vW,J:($)=>$*M1,j:Z2,X:yW,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:DZ,_:($,Z,J)=>($+=M6(J,M1),(Z+=iJ(J,M1))<1?($--,Z+=M1):Z>M1&&($++,Z-=M1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},BW,vB,{h:vJ,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=X6.call(this,$);return[yJ(Z,J),J===Z]},N($,Z,J){let[W,j,Y]=vJ.call(this,{isoYear:KZ,isoMonth:M1,isoDay:31}),z=X6.call(this,W),X=j===z;(d1($,yJ(j,z))||d1(Number(Z),Number(X))||d1(J,Y))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,F=X6.call(this,Q),B=I6($,Z,F);if(Z===(B===F)&&J<=zW.call(this,Q,B))return[Q,B]}},K($){let Z=G6.call(this,$);return Z>G6.call(this,$-1)&&Z>G6.call(this,$+1)},U:X6,L:Q6,J($,Z){let J=Z+$,W=Math.sign($),j=W<0?-1:0,Y=0;for(let z=Z;z!==J;z+=W)Y+=Q6.call(this,z+j);return Y},j:zW,X:G6,P($,Z,J){return A6(J3.call(this,$,Z,J))},q:J3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(e6);if(J<0)for(;Z<1;)Z+=Q6.call(this,--$);else{let W;for(;Z>(W=Q6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),l1="numeric",xZ=["timeZoneName"],bz={month:l1,day:l1},f8={year:l1,month:l1},E8=Object.assign({},f8,{day:l1}),b8={hour:l1,minute:l1,second:l1},R8=Object.assign({},E8,b8),yB=Object.assign({},R8,{timeZoneName:"short"}),gB=Object.keys(f8),mB=Object.keys(bz),pB=Object.keys(E8),hB=Object.keys(b8),w8=["dateStyle"],cB=gB.concat(w8),dB=mB.concat(w8),k8=pB.concat(w8,["weekday"]),I3=hB.concat(["dayPeriod","timeStyle"]),q8=k8.concat(I3),uB=q8.concat(xZ),lB=xZ.concat(I3),iB=xZ.concat(k8),sB=xZ.concat(["day","weekday"],I3),nB=xZ.concat(["year","weekday"],I3),oB={},v8=[f$(q8,R8),w6],Rz=[f$(uB,yB),w6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(jz);return J}],y8=[f$(q8,R8,xZ),S0],g8=[f$(k8,E8,lB),S0],m8=[f$(I3,b8,iB),($)=>s1($)/G1],p8=[f$(cB,f8,sB),S0,1],h8=[f$(dB,bz,nB),S0,1],DW;function K1($,Z,J,W,j){function Y(...G){if(!(this instanceof Y))throw TypeError(B8);vz(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...F){return G.call(this,X(this),...F)},dJ(Q))}function X(G){let Q=M0(G);if(!Q||Q.branding!==$)throw TypeError(B8);return Q}return Object.defineProperties(Y.prototype,{...UW(a0(z,J)),...P$(a0(z,W)),...P6("Temporal."+$)}),Object.defineProperties(Y,{...P$(j),...dJ($)}),[Y,(G)=>{let Q=Object.create(Y.prototype);return vz(Q,G),Q},X]}function mz($){return $=$.concat("id").sort(),(Z)=>{if(!VW(Z,$))throw TypeError(Wz);return Z}}function fZ($){if(M0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(eY);return $}function K4($,Z){let J={};for(let W in $)J[W]=({o:j},Y)=>{let z=M0(Y)||{},{branding:X}=z,G=X===b$||Z.includes(X)?z:E0(Y);return j[W](G)};return J}function u8($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:j}=W;return(Y=j,typeof Y=="string"?_Z(Y):(z=Y,Object.assign(Object.create(KD),{i:z})))[J](W);var Y,z};return Z}function j$(){throw TypeError(Zz)}function P3({calendar:$}){return typeof $=="string"?new e8($):$}function wz($,Z){if(Z=z0(Z),O0($)){let W=M0($);if(W&&W.branding===NZ)return v(Z),W;let j=cz($);return J8(H4(j||w),!j,$,Z)}let J=xj(_Z,$);return v(Z),J}function pz($,Z,J){return W=Z.call($,f0(U0(J))),N2(X3(W));var W}function B4($,Z=iz){let J=Object.keys(Z).sort(),W={};for(let j of J)W[j]=R(Z[j],$,Hz($[j]));return W}function d($,Z){return typeof $=="string"?Q4($):B4($,Z)}function F0($){return d($,d8)}function Q1($){if(O0($)){let Z=M0($);if(Z)switch(Z.branding){case X4:return Z;case E1:return U0(Z.epochNanoseconds)}}return Lj($)}function kz($,Z,J){let W=Z.l(Q1(J).epochNanoseconds,$);return W?f0(U0(W)):null}function l($){return O0($)?(M0($)||{}).timeZone||TD($):((Z)=>i6(fj(t(Z))))($)}function $$($,Z){if(O0($)){let J=M0($)||{};switch(J.branding){case z4:return v(Z),J;case R$:return v(Z),e0(J);case E1:return v(Z),G8(F0,J)}return GY($,Z)}return v(Z),Sj($)}function l8($){return $===void 0?void 0:$$($)}function SZ($,Z){if(Z=z0(Z),O0($)){let W=M0($);return W&&W.branding===MZ?(v(Z),W):Z8(V4(M3($)),$,Z)}let J=_j(_Z,$);return v(Z),J}function Z$($,Z){if(Z=z0(Z),O0($)){let W=M0($)||{};switch(W.branding){case R$:return v(Z),W;case b$:return v(Z),X0({...W,...o0});case E1:return v(Z),z8(F0,W)}return XY(T4(M3($)),$,Z)}let J=Nj($);return v(Z),J}function E0($,Z){if(Z=z0(Z),O0($)){let W=M0($)||{};switch(W.branding){case b$:return v(Z),W;case R$:return v(Z),G0(W);case E1:return v(Z),X8(F0,W)}return $8(T4(M3($)),$,Z)}let J=u6($);return v(Z),J}function hz($,Z,J){return r0(Z.call($,$0(G0(J,$))))}function B1($){return(Z)=>typeof Z=="string"?_Z(Z):((J,W)=>{let j=Object.keys(W).sort(),Y={};for(let z of j)Y[z]=R(W[z],J,J[z]);return Y})(Z,$)}function e($){if(O0($)){let Z=M0($);return Z&&Z.branding===G4?Z:QY($)}return Cj($)}function L3($){if($!==void 0){if(O0($)){let Z=M0($)||{};switch(Z.branding){case E1:case b$:return Z;case R$:return G0(Z)}let J=M3($);return{...YY(l,d,T4(J),$),calendar:J}}return Pj($)}}function M3($){return cz($)||w}function cz($){let{calendar:Z}=$;if(Z!==void 0)return P0(Z)}function P0($){return O0($)?(M0($)||{}).calendar||RD($):((Z)=>F3(Aj(t(Z))))($)}function CZ($,Z){if(Z=z0(Z),O0($)){let J=M0($);if(J&&J.branding===E1)return G3(Z),J;let W=M3($);return zY(l,d,T4(W),W,$,Z)}return Mj($,Z)}function qz($){return a0((Z)=>(J)=>Z(c8(J)),$)}function c8($){return C0($,F0)}function aB(){let $=e1.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(e1),W=function(j,Y={}){if(!(this instanceof W))return new W(j,Y);$5.set(this,((z,X={})=>{let G=new e1(z,X),Q=G.resolvedOptions(),F=Q.locale,B=g0(Object.keys(X),Q),K=v0(eB),O=(...D)=>{let U,V=D.map((H,P)=>{let I=M0(H),C=(I||{}).branding;if(P&&U&&U!==C)throw TypeError(zz);return U=C,I});return U?K(U)(F,B,...V):[G,...D]};return O.u=G,O})(j,Y))};for(let j in Z){let Y=Z[j],z=j.startsWith("format")&&rB(j);typeof Y.value=="function"?Y.value=j==="constructor"?W:z||tB(j):z&&(Y.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function rB($){return function(...Z){let J=$5.get(this),[W,...j]=J(...Z);return W[$](...j)}}function tB($){return function(...Z){return $5.get(this).u[$](...Z)}}function eB($){let Z=$D[$];if(!Z)throw TypeError(Yz($));return C1(Z,v0(Q8))}var $D={Instant:v8,PlainDateTime:y8,PlainDate:g8,PlainTime:m8,PlainYearMonth:p8,PlainMonthDay:h8},ZD=C1(v8),JD=C1(Rz),WD=C1(y8),jD=C1(g8),YD=C1(m8),zD=C1(p8),XD=C1(h8),i8={era:NW,eraYear:sJ,year:X3,month:r0,daysInMonth:r0,daysInYear:r0,inLeapYear:Tz,monthsInYear:r0},O4={monthCode:t},s8={day:r0},dz={dayOfWeek:r0,dayOfYear:r0,weekOfYear:_W,yearOfWeek:sJ,daysInWeek:r0},uz=Object.assign({},i8,O4,s8,dz),D4=new WeakMap,M0=D4.get.bind(D4),vz=D4.set.bind(D4),GD={...K4(i8,[MZ]),...K4(dz,[]),...K4(O4,[MZ,NZ]),...K4(s8,[NZ])},n8=u8(uz),QD=u8({...i8,...O4}),FD=u8({...O4,...s8}),N3={calendarId:($)=>T0($.calendar)},KD=a0(($,Z)=>function(J){let{i:W}=this;return $(W[Z]($0(G0(J,W))))},uz),BD=Y3(($)=>(Z)=>Z[$],y.concat("sign")),o8=Y3(($,Z)=>(J)=>J[Z1[Z]],f1),lz={epochSeconds:iW,epochMilliseconds:w6,epochMicroseconds:sW,epochNanoseconds:nW},_3=R(uJ,new Set(["branding"])),[DD,AZ,OD]=K1(NZ,R(NY,P0),{...N3,...FD},{getISOFields:_3,getCalendar:P3,with($,Z,J){return AZ(OY(fD,$,this,fZ(Z),J))},equals:($,Z)=>dj($,wz(Z)),toPlainDate($,Z){return $0(yY(x3,$,this,Z))},toLocaleString($,Z,J){let[W,j]=XD(Z,J,$);return W.format(j)},toString:H2,toJSON:($)=>H2($),valueOf:j$},{from:($,Z)=>AZ(wz($,Z))}),iz={getOffsetNanosecondsFor:pz,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,L0(X0(J,w)))].map((Y)=>VD(Y).epochNanoseconds),j=W.length;return j>1&&(W.sort(x0),_2(d0(c0(W[0],W[j-1])))),W}},d8={getOffsetNanosecondsFor:pz},[UD,f0,VD]=K1(X4,HY,lz,{add:($,Z)=>f0(x2(0,$,e(Z))),subtract:($,Z)=>f0(x2(1,$,e(Z))),until:($,Z,J)=>u(i2(0,$,Q1(Z),J)),since:($,Z,J)=>u(i2(1,$,Q1(Z),J)),round:($,Z)=>f0(rW($,Z)),equals:($,Z)=>gj($,Q1(Z)),toZonedDateTime($,Z){let J=x1(Z);return Q0(Y8($,l(J.timeZone),P0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(Y8($,l(Z))),toLocaleString($,Z,J){let[W,j]=ZD(Z,J,$);return W.format(j)},toString:($,Z)=>D2(l,F0,$,Z),toJSON:($)=>D2(l,F0,$),valueOf:j$},{from:($)=>f0(Q1($)),fromEpochSeconds:($)=>f0(pY($)),fromEpochMilliseconds:($)=>f0(hY($)),fromEpochMicroseconds:($)=>f0(cY($)),fromEpochNanoseconds:($)=>f0(dY($)),compare:($,Z)=>d2(Q1($),Q1(Z))}),[U4,FI]=K1("TimeZone",($)=>{let Z=vj($);return{branding:"TimeZone",id:Z,o:Q4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(Z$(Z)).map((J)=>f0(U0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(Q1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=Q1(Z).epochNanoseconds,W=B4(this,d8).getOffsetNanosecondsFor(J);return _$(W)},getPlainDateTimeFor($,Z,J=w){let W=Q1(Z).epochNanoseconds,j=B4(this,d8).getOffsetNanosecondsFor(W);return L0(X0(o1(W,j),P0(J)))},getInstantFor($,Z,J){let W=Z$(Z),j=W2(J),Y=B4(this);return f0(U0(y0(Y,W,j)))},getNextTransition:({o:$},Z)=>kz(1,$,Z),getPreviousTransition:({o:$},Z)=>kz(-1,$,Z),equals($,Z){return!!n6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new U4(Z):Z}}),TD=mz(Object.keys(iz)),[HD,J$]=K1(z4,_Y,o8,{getISOFields:_3,with($,Z,J){return J$(UY(this,fZ(Z),J))},add:($,Z)=>J$(E2(0,$,e(Z))),subtract:($,Z)=>J$(E2(1,$,e(Z))),until:($,Z,J)=>u(r2(0,$,$$(Z),J)),since:($,Z,J)=>u(r2(1,$,$$(Z),J)),round:($,Z)=>J$($j($,Z)),equals:($,Z)=>uj($,$$(Z)),toZonedDateTime:($,Z)=>Q0(gY(l,E0,d,$,Z)),toPlainDateTime:($,Z)=>L0(mY($,E0(Z))),toLocaleString($,Z,J){let[W,j]=YD(Z,J,$);return W.format(j)},toString:I2,toJSON:($)=>I2($),valueOf:j$},{from:($,Z)=>J$($$($,Z)),compare:($,Z)=>s6($$($),$$(Z))}),[ID,W$,LD]=K1(MZ,R(MY,P0),{...N3,...QD},{getISOFields:_3,getCalendar:P3,with($,Z,J){return W$(DY(AD,$,this,fZ(Z),J))},add:($,Z,J)=>W$(f2(yz,0,$,e(Z),J)),subtract:($,Z,J)=>W$(f2(yz,1,$,e(Z),J)),until:($,Z,J)=>u(a2(gz,0,$,SZ(Z),J)),since:($,Z,J)=>u(a2(gz,1,$,SZ(Z),J)),equals:($,Z)=>cj($,SZ(Z)),toPlainDate($,Z){return $0(vY(x3,$,this,Z))},toLocaleString($,Z,J){let[W,j]=zD(Z,J,$);return W.format(j)},toString:T2,toJSON:($)=>T2($),valueOf:j$},{from:($,Z)=>W$(SZ($,Z)),compare:($,Z)=>C$(SZ($),SZ(Z))}),[PD,L0]=K1(R$,R(LY,P0),{...N3,...n8,...o8},{getISOFields:_3,getCalendar:P3,with($,Z,J){return L0(KY(x3,$,this,fZ(Z),J))},withCalendar:($,Z)=>L0(t6($,P0(Z))),withPlainDate:($,Z)=>L0(sY($,E0(Z))),withPlainTime:($,Z)=>L0(iY($,l8(Z))),add:($,Z,J)=>L0(C2(k$,0,$,e(Z),J)),subtract:($,Z,J)=>L0(C2(k$,1,$,e(Z),J)),until:($,Z,J)=>u(n2(F1,0,$,Z$(Z),J)),since:($,Z,J)=>u(n2(F1,1,$,Z$(Z),J)),round:($,Z)=>L0(eW($,Z)),equals:($,Z)=>pj($,Z$(Z)),toZonedDateTime:($,Z,J)=>Q0(fY(d,$,l(Z),J)),toPlainDate:($)=>$0(G0($)),toPlainTime:($)=>J$(e0($)),toPlainYearMonth($){return W$(EY(V4,$,this))},toPlainMonthDay($){return AZ(bY(H4,$,this))},toLocaleString($,Z,J){let[W,j]=WD(Z,J,$);return W.format(j)},toString:U2,toJSON:($)=>U2($),valueOf:j$},{from:($,Z)=>L0(Z$($,Z)),compare:($,Z)=>l2(Z$($),Z$(Z))}),[MD,$0,sz]=K1(b$,R(PY,P0),{...N3,...n8},{getISOFields:_3,getCalendar:P3,with($,Z,J){return $0(BY(x3,$,this,fZ(Z),J))},withCalendar:($,Z)=>$0(t6($,P0(Z))),add:($,Z,J)=>$0(A2(k$,0,$,e(Z),J)),subtract:($,Z,J)=>$0(A2(k$,1,$,e(Z),J)),until:($,Z,J)=>u(o2(F1,0,$,E0(Z),J)),since:($,Z,J)=>u(o2(F1,1,$,E0(Z),J)),equals:($,Z)=>hj($,E0(Z)),toZonedDateTime($,Z){let J=!O0(Z)||Z instanceof U4?{timeZone:Z}:Z;return Q0(RY(l,$$,d,$,J))},toPlainDateTime:($,Z)=>L0(wY($,l8(Z))),toPlainYearMonth($){return W$(kY(V4,$,this))},toPlainMonthDay($){return AZ(qY(H4,$,this))},toLocaleString($,Z,J){let[W,j]=jD(Z,J,$);return W.format(j)},toString:V2,toJSON:($)=>V2($),valueOf:j$},{from:($,Z)=>$0(E0($,Z)),compare:($,Z)=>C$(E0($),E0(Z))}),a8={fields($,Z,J){return[...Z.call($,J)]}},nz=Object.assign({dateFromFields($,Z,J,W){return sz(Z.call($,Object.assign(Object.create(null),J),W))}},a8),oz=Object.assign({yearMonthFromFields($,Z,J,W){return LD(Z.call($,Object.assign(Object.create(null),J),W))}},a8),az=Object.assign({monthDayFromFields($,Z,J,W){return OD(Z.call($,Object.assign(Object.create(null),J),W))}},a8),r8={mergeFields($,Z,J,W){return x1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},ND=Object.assign({},nz,r8),_D=Object.assign({},oz,r8),xD=Object.assign({},az,r8),t8={dateAdd($,Z,J,W,j){return sz(Z.call($,$0(G0(J,$)),u(s(W)),j))}},rz=Object.assign({},t8,{dateUntil($,Z,J,W,j,Y){return bD(Z.call($,$0(G0(J,$)),$0(G0(W,$)),Object.assign(Object.create(null),Y,{largestUnit:U3[j]})))}}),SD=Object.assign({},t8,{day:hz}),CD=Object.assign({},rz,{day:hz}),V4=B1(oz),T4=B1(nz),H4=B1(az),AD=B1(_D),x3=B1(ND),fD=B1(xD),k$=B1(t8),F1=B1(rz),yz=B1(SD),gz=B1(CD),[ED,u,bD]=K1(G4,xY,{...BD,blank:Tj},{with:($,Z)=>u(VY($,Z)),negated:($)=>u(c6($)),abs:($)=>u(Vj($)),add:($,Z,J)=>u(q2(L3,F1,d,0,$,e(Z),J)),subtract:($,Z,J)=>u(q2(L3,F1,d,1,$,e(Z),J)),round:($,Z)=>u(Uj(L3,F1,d,$,Z)),total:($,Z)=>aW(L3,F1,d,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):y6($)},toString:y6,toJSON:($)=>y6($),valueOf:j$},{from:($)=>u(e($)),compare:($,Z,J)=>yj(L3,k$,d,e($),e(Z),J)}),tz={toString:($)=>$.id,toJSON:($)=>$.id,...GD,dateAdd:({id:$,o:Z},J,W,j)=>$0(G0(Z.dateAdd(E0(J),e(W),j),$)),dateUntil:({o:$},Z,J,W)=>u(s($.dateUntil(E0(Z),E0(J),hW(W)))),dateFromFields:({id:$,o:Z},J,W)=>$0($8(Z,J,W,MW($))),yearMonthFromFields:({id:$,o:Z},J,W)=>W$(Z8(Z,J,W,LW($))),monthDayFromFields:({id:$,o:Z},J,W)=>AZ(J8(Z,0,J,W,PW($))),fields({o:$},Z){let J=new Set($1),W=[];for(let j of Z){if(t(j),!J.has(j))throw RangeError(K8(j));J.delete(j),W.push(j)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(lJ(nJ(Z)),lJ(nJ(J)))},[e8]=K1("Calendar",($)=>{let Z=tj($);return{branding:"Calendar",id:Z,o:_Z(Z)}},{id:($)=>$.id},tz,{from($){let Z=P0($);return typeof Z=="string"?new e8(Z):Z}}),RD=mz(Object.keys(tz).slice(4)),[wD,Q0]=K1(E1,R(IY,P0,l),{...lz,...N3,...qz(n8),...qz(o8),offset:($)=>_$(c8($).offsetNanoseconds),offsetNanoseconds:($)=>c8($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Zj(d,$)},{getISOFields:($)=>Dj(F0,$),getCalendar:P3,getTimeZone:({timeZone:$})=>typeof $=="string"?new U4($):$,with($,Z,J){return Q0(FY(x3,d,$,this,fZ(Z),J))},withCalendar:($,Z)=>Q0(t6($,P0(Z))),withTimeZone:($,Z)=>Q0(nY($,l(Z))),withPlainDate:($,Z)=>Q0(lY(d,$,E0(Z))),withPlainTime:($,Z)=>Q0(uY(d,$,l8(Z))),add:($,Z,J)=>Q0(S2(k$,d,0,$,e(Z),J)),subtract:($,Z,J)=>Q0(S2(k$,d,1,$,e(Z),J)),until:($,Z,J)=>u(s(s2(F1,d,0,$,CZ(Z),J))),since:($,Z,J)=>u(s(s2(F1,d,1,$,CZ(Z),J))),round:($,Z)=>Q0(tW(d,$,Z)),startOfDay:($)=>Q0(Jj(d,$)),equals:($,Z)=>mj($,CZ(Z)),toInstant:($)=>f0(SY($)),toPlainDateTime:($)=>L0(z8(F0,$)),toPlainDate:($)=>$0(X8(F0,$)),toPlainTime:($)=>J$(G8(F0,$)),toPlainYearMonth($){return W$(CY(V4,$,this))},toPlainMonthDay($){return AZ(AY(H4,$,this))},toLocaleString($,Z,J={}){let[W,j]=JD(Z,J,$);return W.format(j)},toString:($,Z)=>O2(F0,$,Z),toJSON:($)=>O2(F0,$),valueOf:j$},{from:($,Z)=>Q0(CZ($,Z)),compare:($,Z)=>u2(CZ($),CZ(Z))}),kD=Object.defineProperties({},{...P6("Temporal.Now"),...P$({timeZoneId:()=>A1(),instant:()=>f0(U0(B3())),zonedDateTime:($,Z=A1())=>Q0(I0(B3(),l(Z),P0($))),zonedDateTimeISO:($=A1())=>Q0(I0(B3(),l($),w)),plainDateTime:($,Z=A1())=>L0(X0(LZ(F0(l(Z))),P0($))),plainDateTimeISO:($=A1())=>L0(X0(LZ(F0(l($))),w)),plainDate:($,Z=A1())=>$0(G0(LZ(F0(l(Z))),P0($))),plainDateISO:($=A1())=>$0(G0(LZ(F0(l($))),w)),plainTimeISO:($=A1())=>J$(e0(LZ(F0(l($)))))})}),EZ=Object.defineProperties({},{...P6("Temporal"),...P$({PlainYearMonth:ID,PlainMonthDay:DD,PlainDate:MD,PlainTime:HD,PlainDateTime:PD,ZonedDateTime:wD,Instant:UD,Calendar:e8,TimeZone:U4,Duration:ED,Now:kD})}),qD=aB(),$5=new WeakMap,vD=Object.defineProperties(Object.create(Intl),P$({DateTimeFormat:qD}));var UI="gemi.v1",ez="/__gemi/socket",Z5="x-gemi-socket",VI=/^[A-Za-z0-9_-]{1,32}$/,TI={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function LI($){return $}function $X(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:ez,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 yD,randomBytes as gD}from"crypto";function mD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(yD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var pD="__control",J5=250,hD=1e4,cD=15000;class W5{config;prefix;controlChannel;instanceId=gD(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??mD(),this.controlChannel=this.prefix+pD,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=S3((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 $})(),cD,"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 (${ZX(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(hD,J5*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(J5,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;S3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${ZX(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??dD(Math.min(Z,J5));await S3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let j=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(j,j),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let j=this.subscriber;this.active.delete($);try{await S3(j.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(Y){if(this.subscriber===j)this.drop(j);throw Y}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await S3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(j){if(this.subscriber===W)this.drop(W);throw j}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function S3($,Z,J){let W;return Promise.race([$,new Promise((j,Y)=>{W=setTimeout(()=>Y(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function dD($){return new Promise((Z)=>setTimeout(Z,$))}function ZX($){return $ instanceof Error?$.message:String($)}import{createHmac as uD,hkdfSync as lD,randomBytes as JX}from"crypto";function WX($){return uD("sha256",iD()).update($).digest("base64url").slice(0,22)}var I4=null;function iD(){let $=process.env.SECRET||void 0;if(I4&&I4.secret===$)return I4.key;let Z=$?Buffer.from(lD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):JX(32);return I4={secret:$,key:Z},Z}function xI(){return JX(16).toString("base64url")}var sD=/^[A-Za-z0-9_-]{8,64}$/;function j5($){return typeof $==="string"&&sD.test($)}function jX($,Z,J,W){let j={op:"ev",t:$,ev:Z};if(J!==void 0)j.d=J;if(W)j.x=W;return JSON.stringify(j)}class zX extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class m0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=Y$($X(),$),this.driver=aD(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 C3(this,L4($,Z[0]),null)}toUser($){return new C3(this,{topic:a$($),pattern:K0},null)}toOthers($){return new XX(this,oD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),j=$.broadcastWith(),Y=J.map((z)=>this.prepare(L4(z,void 0),W,j,null));for(let{sent:z,frame:X}of Y)this.hand(z,X)}send($,Z,J,W){let{sent:j,frame:Y}=this.prepare($,Z,J,W);this.hand(j,Y)}prepare($,Z,J,W){f7(Z);let j;try{j=jX($.topic,Z,J,W?WX(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,j),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(j).d,...W?{except:W}:{}},frame:j}}hand($,Z){bZ(()=>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=nD($);bZ(()=>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 zX(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 C3{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 XX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new C3(this.manager,L4($,Z[0]),this.except)}toUser($){return new C3(this.manager,{topic:a$($),pattern:K0},this.except)}}function L4($,Z){if(A7($))return{topic:t4($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:iZ($,Z??{}),pattern:$};if($===K0)throw new h('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:t4($)}}function nD($){if($&&typeof $==="object"&&"user"in $)return{user:a$($.user).slice(K0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:L4($.channel,$.params).topic};throw new h("Broadcast.revoke takes { user } or { channel }.")}function oD($){if($===null||$===void 0)return null;if(typeof $==="string")return j5($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(Z5);return j5(J)?J:null}function aD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new YX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},j=$.redis??{};return new W5({url:j.url??W.url??process.env.REDIS_URL,options:j.options??W.options,prefix:j.prefix,subscribeTimeoutMs:j.subscribeTimeoutMs,healthCheckMs:j.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class Y5 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class rD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as z5,createHmac as tD,randomBytes as GX,timingSafeEqual as KX}from"crypto";var f3=600,P4="gemi_oauth",eD=`__Host-${P4}`;function RZ($,Z=P4){if(Z===P4)return $?eD:P4;return $?`__Host-${Z}`:Z}function A3($){return $.toString("base64url")}function BX($){return tD("sha256",WZ()).update(`gemi-oauth-state:${$}`).digest()}function QX($,Z){let J=z5("sha256").update($).digest(),W=z5("sha256").update(Z).digest();return KX(J,W)&&$.length===Z.length}function M4($,Z=Date.now(),J={}){let W=A3(GX(32)),j=A3(GX(32)),Y=$O(j),z={provider:$,state:W,codeVerifier:j,expiresAt:Z+f3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:j,codeChallenge:Y,cookieValue:ZO(z)}}function $O($){return A3(z5("sha256").update($).digest())}function ZO($){let Z=A3(Buffer.from(JSON.stringify($)));return`${Z}.${A3(BX(Z))}`}function JO($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),j=BX(J);if(W.length!==j.length||!KX(W,j))return null;try{let Y=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof Y?.provider!=="string"||typeof Y?.state!=="string"||typeof Y?.codeVerifier!=="string"||typeof Y?.expiresAt!=="number"||Y.subject!==void 0&&typeof Y.subject!=="string"||Y.returnTo!==void 0&&typeof Y.returnTo!=="string")return null;return Y}catch{return null}}var z$=new Map,FX=1e4;function WO($,Z,J){if(z$.size>=FX){for(let[W,j]of z$)if(j<=J)z$.delete(W);while(z$.size>=FX){let W=z$.keys().next().value;if(W===void 0)break;z$.delete(W)}}z$.set($,Z)}function N4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=JO($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=QX(J.state,$.returnedState),j=QX(J.provider,$.provider);if(!W||!j)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(z$.has(J.state))return{ok:!1,reason:"invalid_state"};return WO(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var X5=new WeakMap;function YO($){let Z=X5.get($);if(!Z)Z=$(jO(32).toString("hex")),X5.set($,Z),Z.catch(()=>X5.delete($));return Z}async function G5($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await YO($.hashPassword))}catch{}return!1}async function q$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...j}=J;await $.onAuthenticated({...Z,user:j})}class F5 extends Error{}function Q5($){return typeof $==="string"&&$!==""?$:null}function DX($){return aZ($)}var zO=256;function OX($){return typeof $==="string"&&$!==""&&$.length<=zO?$:null}var _4="intended_url";function VX($){if($.cookies.get(_4))$.ctx().setCookie(_4,"",{maxAge:-1})}function UX($){let Z=$.cookies.get(_4);if(!Z)return null;VX($);try{return j1(decodeURIComponent(Z),"")||null}catch{return null}}class K5 extends x{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class TX extends x{schema={email:{required:"Email is required",email:"Invalid email"}}}class HX extends x{schema={password:{required:"Password is required",password:"Invalid password"}}}function b1($){if(T(A).config[$]===!1)throw new W0("Not found",{status:404})}class n extends nZ{async me(){let $=await R0.user();if(!$)throw new VJ;return $}async verifyEmail($=new x){b1("password");let Z=await $.input(),{userProvider:J}=T(A),W=Q5(Z.get("token"));if(!W)return{email:null};let j=await J.findUserByVerificationToken(W);if(!j)return{email:null};return await J.verifyUser(j.email),{email:j.email}}async signInWithMagicLink($=new x){let Z=T(A),{userProvider:J}=Z,W=Q5($.search.get("token")),j=null;try{j=aZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await jZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!j||!W||!await Z.verifyMagicLinkToken(j,W))return{error:"Invalid token"};await J.verifyUser(j);let Y=await Z.createOrUpdateSession({email:j});return $.ctx().setCookie("access_token",Y.token,T(A).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON()),await q$(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),{session:Y}}async verifyPinRequest($){b1("magicLink");let Z=T(A),J=await $.input(),{email:W,pin:j}=J.toJSON(),Y=aZ(W),z=OX(j);if(await jZ("verify",Y,$,Z.config.emailCode.verifyLimit),!Y||!z)throw new p({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(Y,z);if(X.status==="too_many_attempts")throw new p({pin:["Too many attempts"]});if(X.status!=="ok")throw new p({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(Y),Y}async signInWithPinV2($=new x){let Z=T(A),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,T(A).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await q$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new x){let Z=T(A),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,T(A).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await q$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new K5){b1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),j=J.toLowerCase().trim(),Y=T(A),z=await Y.userProvider.findUserByEmailAddress(j,Y.config.verifyEmail),X=typeof W==="string"&&await G5(Y.config,W,z?.password);if(!z||!X)throw new p({invalid_credentials:["Invalid credentials"]});let G=await Y.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,T(A).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await q$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signIn($=new K5){b1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),j=J.toLowerCase().trim(),Y=T(A),z=await Y.userProvider.findUserByEmailAddress(j,Y.config.verifyEmail),X=typeof W==="string"&&await G5(Y.config,W,z?.password);if(!z||!X)throw new p({invalid_credentials:["Invalid credentials"]});let G=await Y.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,T(A).accessTokenCookieOptions($,G.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await q$(Y.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signUp(){b1("password");let $=T(A),{userProvider:Z,config:J}=$,W=new J.signUpRequest,j=await W.input(),{email:Y,password:z,name:X,invitationId:G}=j.toJSON(),Q=DX(Y);if(!Q)throw new p({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new p({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new p({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(Q,!1))throw new p({email:["Email address already exists"]});let B=await J.hashPassword(z),K=T(i).detectLocale(W),O;if(G)O=await Z.findInvitation(G,Q);let D,U="";if(O)D=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let V=await Z.createUser({email:Q,name:X,password:B,emailVerifiedAt:new Date,locale:K});return await Z.createAccount({organizationId:O.organizationId,userId:V.id,organizationRole:O.role}),await J.onUserCreated(V),V});else U=await J.generateEmailVerificationToken(Q),D=await Z.transaction(async()=>{let V=await Z.createUser({email:Q,name:X,password:B,verificationToken:U,locale:K});return await J.onUserCreated(V),V});return await J.onSignUp(D,U,W.search.toJSON()),D}async signOut($=new x){let Z=F$($),J=T(A),{config:W}=J,j=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",T(A).accessTokenCookieOptions($,new Date(0))),T(A).cookieDomain($))$.ctx().setCookie("access_token","",{...T(A).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(j?.user)XO(j.user),j.user.extension=await W.extendSession(j.user),await W.onSignOut(j.user);return{}}async forgotPassword($=new TX){b1("password");let Z=await $.input(),J=DX(Z.get("email"));if(!J)return{};let{userProvider:W,config:j}=T(A),Y=await W.findUserByEmailAddress(J,j.verifyEmail);if(!Y)return{};let z=await j.generateForgotPasswordToken(Y);return await W.createPasswordResetToken({user:Y,token:z}),await j.onForgotPassword(Y,z),{}}async resetPassword($=new HX){b1("password");let{userProvider:Z,config:J}=T(A),W=await $.input(),{password:j,token:Y}=W.toJSON(),z=Q5(Y),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new p({token:["Invalid token"]});if(EZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(EZ.Now.instant()).sign>=0)throw new p({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!Q)throw new p({email:["User not found"]});let F=await J.hashPassword(j);return await Z.updateUserPassword({id:Q.id,password:F}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q),{}}async changePassword($=new x){b1("password");let{userProvider:Z,config:J}=T(A),W=await R0.user(),j=await $.input(),{oldPassword:Y,newPassword:z}=j.toJSON();if(typeof z!=="string")throw new p({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof Y==="string"&&await G5(J,Y,X?.password)))throw new p({oldPassword:["Incorrect password"]});let Q=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:Q}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new x){let{provider:Z}=$.params,J=T(A).config.oauthProviders,W=Object.hasOwn(J,Z),j=await YZ(J,Z);if(!j){if(W)throw new W0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let Y=t$($.rawRequest),z=j1($.search.get(W1),"");if(z)$.ctx().setCookie(_4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:600});else VX($);let{state:X,codeChallenge:G,cookieValue:Q}=M4(Z);return $.ctx().setCookie(RZ(Y),Q,{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:f3}),{destination:await j.getRedirectUrl($,{state:X,codeChallenge:G,codeChallengeMethod:"S256"})}}async oauthCallback($=new x){let{provider:Z}=$.params,J=T(A),{userProvider:W,config:j}=J,Y=Object.hasOwn(j.oauthProviders,Z),z=await YZ(j.oauthProviders,Z);if(Y&&!z)throw new W0("Not found",{status:404});let X=t$($.rawRequest),G=RZ(X),Q=$.cookies.get(G);if(Q!==void 0&&Q!==null)$.ctx().setCookie(G,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let F=$.search.get("error");if(F)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");let B=N4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in B)return console.error(`Authentication error: OAuth callback refused (${B.reason})`),this.oauthFailure($,B.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let K;try{K=await z.onCallback($,{state:B.payload.state,codeVerifier:B.payload.codeVerifier})}catch(L){if(L instanceof Y5)return this.oauthFailure($,L.code);return console.error("Authentication error: OAuth provider callback failed",L),this.oauthFailure($,"provider_error")}let{name:O,username:D,providerId:U,emailVerified:V}=K??{},H=typeof K?.email==="string"?K.email:void 0,P=H?J6(H):null,I=U?await W.findUserBySocialAccount(Z,U):null,C="signin",f=!I&&!P&&!H&&!!U&&z.createUsersWithoutEmail===!0;if(!I&&f){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{I=await this.createOAuthUserWithoutEmail({provider:Z,providerId:U,name:O,username:D,locale:T(i).detectLocale($)}),C="signup"}catch(L){let k=await W.findUserBySocialAccount(Z,U);if(!k)throw L;I=k}}if(!I){if(!P)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,H?"invalid_email":U?"missing_email":"no_identity");if(V===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let L=T(i).detectLocale($);try{let k=await this.linkOAuthAccount({provider:Z,providerId:U,email:P,rawEmail:H,name:O,username:D,locale:L,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(k==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(k==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(k)I=k.user,C=k.action}catch(k){let m=U?await W.findUserBySocialAccount(Z,U):null;if(!m)throw k;I=m}if(!I)return this.oauthFailure($,"account_conflict")}let E=await J.createOrUpdateSessionV2({email:I.email,id:I.id});if($.ctx().setCookie("access_token",E.token,T(A).accessTokenCookieOptions($,E.expiresAt)),C==="signup")await j.onSignUp(I,"",$.search.toJSON());else await j.onSignIn(I,$.search.toJSON());await q$(J.config,{session:E,user:I,isNewUser:C==="signup",method:"oauth",req:$});let S=UX($)??j.redirectPath,M=j.oauthCompleteProfilePath?j1(j.oauthCompleteProfilePath,""):"";if(M&&!I.email){let L=new URL(M,"http://gemi.invalid");L.searchParams.set(W1,S),S=`${L.pathname}${L.search}${L.hash}`}return{session:E,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=T(A);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W),W})}oauthFailure($,Z){let J=UX($),W=T(A).config.oauthFailurePath;if(W){let j=j1(W,"");if(j){let Y=new URL(j,"http://gemi.invalid");if(Y.searchParams.set("error",Z),J)Y.searchParams.set(W1,J);H1.external(`${Y.pathname}${Y.search}${Y.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:j,name:Y,username:z,locale:X}=$,{userProvider:G,config:Q}=T(A),F=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),B=await G.findUserByEmailAddress(W,!1),K=j?.trim();if(!B&&K&&K!==W)B=await G.findUserByEmailAddress(K,!1);if(B){if($.linkExisting===!1)return"account_exists";if(!J)return{user:B,action:"signin"};let D=await G.findSocialAccounts(B.id,Z);if(D.some((V)=>V.providerId===J))return{user:B,action:"signin"};if(D.some((V)=>V.providerId))return console.error(`Authentication error: user ${B.id} is already linked to a different ${Z} account`),null;let U=D[0];if(U){if(!await G.claimSocialAccount(U,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(F(B.id));return{user:B,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let D=await G.createUser({email:W,name:Y,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(F(D.id));return await Q.onUserCreated(D),D}),action:"signup"}}async createMagicLinkToken($=new x){b1("magicLink");let Z=await $.input(),J=aZ(Z.get("email")),W=T(A),{uniformMagicLinkResponse:j,requestLimit:Y}=W.config.emailCode;if(await jZ("request",J,$,Y),!J)return{email:null};let{user:z,pin:X,token:G}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:G}),{email:J};return{email:j?J:null}}async requestEmailCode($=new x){let Z=T(A),J=Z.config.emailCode;if(!J.enabled)throw new W0("Not found",{status:404});let W=await $.input(),j=J6(W.get("email"));if(await jZ("request",j,$,J.requestLimit),!j)throw new p({email:["Invalid email"]});let Y=await Z.userProvider.findUserByEmailAddress(j,!1);if(Y||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(j,J.length);await J.send({email:j,code:z,token:X,isNewUser:!Y,req:$})}return{ok:!0}}async verifyEmailCode($=new x){let Z=T(A),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new W0("Not found",{status:404});let j=await $.input(),{email:Y,code:z,name:X}=j.toJSON(),G=J6(Y),Q=OX(z);if(await jZ("verify",G,$,W.emailCode.verifyLimit),!G||!Q)throw new p({code:["invalid_code"]});let F=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(F.status==="too_many_attempts")throw new p({code:["too_many_attempts"]});if(F.status!=="ok")throw new p({code:["invalid_code"]});let B=F.row,K=await J.findUserByEmailAddress(G,!1),O=!1;if(K){if(!await J.claimMagicLinkToken(B.id))throw new p({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let U=T(i).detectLocale($);try{K=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(B.id))throw new F5;let V=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await W.onUserCreated(V),V}),O=!0}catch(V){if(V instanceof F5)throw new p({code:["invalid_code"]});throw V}}else throw await J.claimMagicLinkToken(B.id),new p({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:K.id});return $.ctx().setCookie("access_token",D.token,T(A).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON()),await q$(Z.config,{session:D,isNewUser:O,method:"email-code",req:$}),{session:D,isNewUser:O}}}function XO($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=T();if(typeof J?.bound!=="function"||!J.bound(m0))return;J.make(m0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var IX="gemi_oauth_connection";class x4 extends nZ{async connect($=new x){let Z=String($.params.provider??""),W=T(E3).providers[Z],j=await R0.user(),Y=j1($.search.get(W1),"");if(!W)return this.finish(Y,Z,"unknown_provider");let z=t$($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=M4(LX(Z),Date.now(),{subject:String(j.id),...Y?{returnTo:Y}:{}});return $.ctx().setCookie(RZ(z,IX),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:f3}),H1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:PX($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new x){let Z=String($.params.provider??""),J=T(E3),W=await R0.user(),j=t$($.rawRequest),Y=RZ(j,IX),z=$.cookies.get(Y);if(z!==void 0&&z!==null)$.ctx().setCookie(Y,"",{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:-1});let X=N4({provider:LX(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=J.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let F=$.search.get("error");if(F)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(G,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(G,Z,"user_mismatch");let B=$.search.get("code");if(!B)return this.finish(G,Z,"missing_code");try{let K=await Q.exchangeCode({code:B,codeVerifier:X.payload.codeVerifier,redirectUri:PX($,Z,Q.config.redirectUri)}),O=await J.save(W,Z,K);await T(A).config.onConnected({user:W,provider:Z,connection:O,profile:K.profile??null,req:$})}catch(K){if(K instanceof MX)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(G,Z,K.providerError??K.code);throw K}return this.finish(G,Z)}finish($,Z,J){let W=$||j1(T(A).config.redirectPath,"/"),j=new URL(W,"http://gemi.invalid");if(j.searchParams.set("connection",Z),J)j.searchParams.set("connection_error",J);throw H1.external(`${j.pathname}${j.search}${j.hash}`),Error("unreachable: Redirect.external throws")}}function LX($){return`connection:${$}`}function PX($,Z,J){if(J)return J;return`${b3()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}class NX extends I1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[n,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[n,"oauthCallback"])}}class _X extends I1{middlewares=["cache:private"];routes={"/:provider":this.redirect([x4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([x4,"callback"]).middleware([n3,"auth"])}}class B5 extends I1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[n,"signInWithMagicLink"]),"/oauth":NX,"/connections":_X}}class D5 extends b0{middlewares=["cache:private"];routes={"/sign-in":this.post(n,"signIn"),"/sign-in-v2":this.post(n,"signInV2"),"/sign-up":this.post(n,"signUp"),"/sign-out":this.post(n,"signOut"),"/forgot-password":this.post(n,"forgotPassword"),"/reset-password":this.post(n,"resetPassword"),"/change-password":this.post(n,"changePassword"),"/verify-email":this.post(n,"verifyEmail"),"/me":this.get(n,"me").middleware(["auth"]),"/magic-link":this.post(n,"createMagicLinkToken"),"/sign-in-with-pin":this.post(n,"signInWithPin"),"/sign-in-with-pin-v2":this.post(n,"signInWithPinV2"),"/email-code":this.post(n,"requestEmailCode"),"/email-code/verify":this.post(n,"verifyEmailCode")}}class O5 extends b0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new x().params.locale;return await T(i).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new x,Z=`/${$.params.scope??""}`,J=$.params.locale,W=T(i),j=J??W.detectLocale($),Y=W.getPageTranslations(j,Z);return $.ctx().setCookie("i18n-locale",j,{expires:new Date(Date.now()+31536000000)}),{[j]:Y}})}}class U5{}class V5 extends U5{async resize($,Z){let{height:J,width:W,quality:j,fit:Y}=Z;return await(await S4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:Y}).webp({quality:j>0?j:80,force:!0}).toBuffer()}}function qL($){return $}function xX(){return{driver:new V5}}class T5 extends b0{routes={"/resize":this.file(async()=>{let $=new x,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),j=Number(Z.searchParams.get("h")),Y=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let G=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,Q=await fetch(G);if(!Q.ok)return new Response(JSON.stringify({error:"Image not found",info:G}),{headers:{"Content-Type":"application/json"},status:404});let F=Buffer.from(await Q.arrayBuffer()),B=await T(SX).resize(F,{height:j,width:W,fit:Y,quality:z});Q.headers.delete("Content-Type"),Q.headers.delete("Content-Length");let K=new Headers(Q.headers);return K.set("Content-Type","image/webp"),K.set("Content-Length",`${B.byteLength}`),new Response(new Uint8Array(B),{headers:K})})}}class SX{static token="image";driver;constructor($={}){this.driver=$.driver??xX().driver}resize($,Z){return this.driver.resize($,Z)}}class H5 extends b0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(T(CX).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function lL($){return $}function AX(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function fX(){return{partialRendering:!0,localeRouting:"prefix",onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function GO($){return"run"in $}function QO($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function FO($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function KO($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function BO($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function EX($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function I5($,Z="",J=[]){let W={};function j(Y,z,X,G,Q){let F=Y==="/"?"":Y,B=Z==="/"?"":Z,K=(`${B}${F}`===""?"/":`${B}${F}`).replaceAll("//","/");if(!W[K])W[K]={};W[K][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{}},W[K].OPTIONS={exec:()=>{let D=new x().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[Y,z]of Object.entries($)){if(BO(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])j(Y,G,X.run.bind(X),X.middlewares);continue}if(GO(z)){let X=z,G=X.method,Q=X.middlewares,F=X.run.bind(X);if(j(Y,G,F,Q,X.source),EX(z))j(Y,"HEAD",F,Q,X.source)}if(QO(z))for(let[X,G]of Object.entries(z)){let Q=G,F=Q.middlewares,B=Q.run.bind(Q);if(j(Y,X,B,F,Q.source),X==="get"&&EX(Q))j(Y,"HEAD",B,F,Q.source)}if(KO(z)){let X=new z,G=I5(X.routes,`${Z}${Y}`,X.middlewares);for(let[Q,F]of Object.entries(G))W[Q.replaceAll("//","/")]=F}if(FO(z)){let{first:X,second:G}=z;for(let[Q,F]of Object.entries(X)){let B=F.middlewares,K=F.run.bind(F),[O,...D]=Y.split("/").reverse();if(!O.startsWith(":"))throw Error("Resource route must end with a dynamic segment");j(D.reverse().join("/"),Q,K,B,F.source)}for(let[Q,F]of Object.entries(G)){let B=F.middlewares,K=F.run.bind(F);j(Y,Q,K,B,F.source)}}}return Object.fromEntries(Object.entries(W).sort(([Y],[z])=>{let X=Y.split("/").length+Y.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}function C4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function L5($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function P5($){let Z=C4($);return Z.length>1?Z.replace(/\/$/,""):Z}function bX($,Z){return Z.map((J)=>({...J,path:P5(L5($,J.path))}))}function A4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let j=W;if("children"in j){let Y=new j.children,z=A4(Y.routes);for(let[X,{exec:G,middleware:Q,segments:F,features:B,static:K}]of Object.entries(z)){let O=L5(J,X),D=(U)=>j.run.call(j,U,J);Z[C4(O)]={exec:[D,...G],middleware:[...j.middlewares,...Q],features:[...j.featureGates,...B],viewPath:j.viewPath,segments:[{path:P5(J),viewPath:j.viewPath,...j.alwaysRuns?{alwaysRun:!0}:{}},...bX(J,F)],...K?{static:K}:{}}}}else{let Y=(z)=>j.run.call(j,z,J);Z[C4(J)]={exec:[Y],middleware:j.middlewares,features:j.featureGates,viewPath:j.viewPath,segments:[{path:P5(J),viewPath:j.viewPath}],..."staticOptions"in j&&j.staticOptions?{static:j.staticOptions}:{}}}}else{let j=new W,Y=A4(j.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:F,features:B,static:K}]of Object.entries(Y)){let O=L5(J,z);Z[C4(O)]={exec:X,middleware:[...j.middlewares,...G],features:[...j.featureGates,...B],viewPath:Q,segments:bX(J,F),...K?{static:K}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let j=J.split("/").length+J.split(":").length,Y=W.split("/").length+W.split(":").length;return j-Y}))}var DO=Object.defineProperty,_=($,Z)=>DO($,"name",{value:Z,configurable:!0}),qZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,j,Y){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=j,this.modifier=Y}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};_(qZ,"Part");var OO=/[$_\p{ID_Start}]/u,UO=/[$_\u200C\u200D\p{ID_Continue}]/u,N5=".*";function RX($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}_(RX,"isASCII");function S5($,Z=!1){let J=[],W=0;for(;W<$.length;){let j=$[W],Y=_(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(j==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(j==="+"||j==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(j==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(j==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(j==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(j===":"){let z="",X=W+1;for(;X<$.length;){let G=$.substr(X,1);if(X===W+1&&OO.test(G)||X!==W+1&&UO.test(G)){z+=$[X++];continue}break}if(!z){Y(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(j==="("){let z=1,X="",G=W+1,Q=!1;if($[G]==="?"){Y(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!RX($[G],!1)){Y(`Invalid character '${$[G]}' at ${G}.`),Q=!0;break}if($[G]==="\\"){X+=$[G++]+$[G++];continue}if($[G]===")"){if(z--,z===0){G++;break}}else if($[G]==="("&&(z++,$[G+1]!=="?")){Y(`Capturing groups are not allowed at ${G}`),Q=!0;break}X+=$[G++]}if(Q)continue;if(z){Y(`Unbalanced pattern at ${W}`);continue}if(!X){Y(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=G;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}_(S5,"lexer");function C5($,Z={}){let J=S5($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${p0(Z.delimiter)}]+?`,j=[],Y=0,z=0,X="",G=new Set,Q=_((I)=>{if(z<J.length&&J[z].type===I)return J[z++].value},"tryConsume"),F=_(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),B=_((I)=>{let C=Q(I);if(C!==void 0)return C;let{type:f,index:E}=J[z];throw TypeError(`Unexpected ${f} at ${E}, expected ${I}`)},"mustConsume"),K=_(()=>{let I="",C;for(;C=Q("CHAR")??Q("ESCAPED_CHAR");)I+=C;return I},"consumeText"),O=_((I)=>I,"DefaultEncodePart"),D=Z.encodePart||O,U="",V=_((I)=>{U+=I},"appendToPendingFixedValue"),H=_(()=>{U.length&&(j.push(new qZ(3,"","",D(U),"",3)),U="")},"maybeAddPartFromPendingFixedValue"),P=_((I,C,f,E,S)=>{let M=3;switch(S){case"?":M=1;break;case"*":M=0;break;case"+":M=2;break}if(!C&&!f&&M===3){V(I);return}if(H(),!C&&!f){if(!I)return;j.push(new qZ(3,"","",D(I),"",M));return}let L;f?f==="*"?L=N5:L=f:L=W;let k=2;L===W?(k=1,L=""):L===N5&&(k=0,L="");let m;if(C?m=C:f&&(m=Y++),G.has(m))throw TypeError(`Duplicate name '${m}'.`);G.add(m),j.push(new qZ(k,m,D(I),L,D(E),M))},"addPart");for(;z<J.length;){let I=Q("CHAR"),C=Q("NAME"),f=Q("REGEX");if(!C&&!f&&(f=Q("ASTERISK")),C||f){let S=I??"";Z.prefixes.indexOf(S)===-1&&(V(S),S=""),H();let M=F();P(S,C,f,"",M);continue}let E=I??Q("ESCAPED_CHAR");if(E){V(E);continue}if(Q("OPEN")){let S=K(),M=Q("NAME"),L=Q("REGEX");!M&&!L&&(L=Q("ASTERISK"));let k=K();B("CLOSE");let m=F();P(S,M,L,k,m);continue}H(),B("END")}return j}_(C5,"parse");function p0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(p0,"escapeString");function _5($){return $&&$.ignoreCase?"ui":"u"}_(_5,"flags");function wX($,Z,J){return A5(C5($,J),Z,J)}_(wX,"stringToRegexp");function v$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}_(v$,"modifierToString");function A5($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=p0(X.value):W+=`(?:${p0(X.value)})${v$(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${p0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=N5),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${Q})${v$(X.modifier)}`:W+=`((?:${Q})${v$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${p0(X.prefix)}(${Q})${p0(X.suffix)})`,W+=v$(X.modifier);continue}W+=`(?:${p0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=p0(X.suffix),W+=p0(X.prefix),W+=`(?:${Q}))*)${p0(X.suffix)})`,X.modifier===0&&(W+="?")}let j=`[${p0(J.endsWith)}]|$`,Y=`[${p0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${Y}?`),J.endsWith.length?W+=`(?=${j})`:W+="$",new RegExp(W,_5(J));J.strict||(W+=`(?:${Y}(?=${j}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${Y}|${j})`),new RegExp(W,_5(J))}_(A5,"partsToRegexp");var G$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},VO={delimiter:".",prefixes:"",sensitive:!0,strict:!0},TO={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function kX($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}_(kX,"isAbsolutePathname");function f5($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}_(f5,"maybeStripPrefix");function qX($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}_(qX,"maybeStripSuffix");function E5($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}_(E5,"treatAsIPv6Hostname");var vX=["ftp","file","http","https","ws","wss"];function b5($){if(!$)return!0;for(let Z of vX)if($.test(Z))return!0;return!1}_(b5,"isSpecialScheme");function yX($,Z){if($=f5($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}_(yX,"canonicalizeHash");function gX($,Z){if($=f5($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}_(gX,"canonicalizeSearch");function mX($,Z){return Z||$===""?$:E5($)?k5($):w5($)}_(mX,"canonicalizeHostname");function pX($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}_(pX,"canonicalizePassword");function hX($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}_(hX,"canonicalizeUsername");function cX($,Z,J){if(J||$==="")return $;if(Z&&!vX.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}_(cX,"canonicalizePathname");function dX($,Z,J){return R5(Z)===$&&($=""),J||$===""?$:q5($)}_(dX,"canonicalizePort");function uX($,Z){return $=qX($,":"),Z||$===""?$:f4($)}_(uX,"canonicalizeProtocol");function R5($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}_(R5,"defaultPortForProtocol");function f4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}_(f4,"protocolEncodeCallback");function lX($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}_(lX,"usernameEncodeCallback");function iX($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}_(iX,"passwordEncodeCallback");function w5($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}_(w5,"hostnameEncodeCallback");function k5($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}_(k5,"ipv6HostnameEncodeCallback");function q5($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}_(q5,"portEncodeCallback");function sX($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}_(sX,"standardURLPathnameEncodeCallback");function nX($){return $===""?$:new URL(`data:${$}`).pathname}_(nX,"pathURLPathnameEncodeCallback");function oX($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}_(oX,"searchEncodeCallback");function aX($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}_(aX,"hashEncodeCallback");var rX=class{#Y;#W=[];#Z={};#$=0;#j=1;#Q=0;#X=0;#D=0;#O=0;#U=!1;constructor($){this.#Y=$}get result(){return this.#Z}parse(){for(this.#W=S5(this.#Y,!0);this.#$<this.#W.length;this.#$+=this.#j){if(this.#j=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#I(),this.#F()?this.#J(9,1):this.#K()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#B(5);continue}this.#J(10,0);break}if(this.#D>0)if(this.#S())this.#D-=1;else continue;if(this.#x()){this.#D+=1;continue}switch(this.#X){case 0:this.#L()&&this.#B(1);break;case 1:if(this.#L()){this.#f();let $=7,Z=1;this.#M()?($=2,Z=3):this.#U&&($=2),this.#J($,Z)}break;case 2:this.#T()?this.#B(3):(this.#H()||this.#K()||this.#F())&&this.#B(5);break;case 3:this.#N()?this.#J(4,1):this.#T()&&this.#J(5,1);break;case 4:this.#T()&&this.#J(5,1);break;case 5:this.#C()?this.#O+=1:this.#A()&&(this.#O-=1),this.#_()&&!this.#O?this.#J(6,1):this.#H()?this.#J(7,0):this.#K()?this.#J(8,1):this.#F()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#K()?this.#J(8,1):this.#F()&&this.#J(9,1);break;case 7:this.#K()?this.#J(8,1):this.#F()&&this.#J(9,1);break;case 8:this.#F()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#G();break;case 2:break;case 3:this.#Z.username=this.#G();break;case 4:this.#Z.password=this.#G();break;case 5:this.#Z.hostname=this.#G();break;case 6:this.#Z.port=this.#G();break;case 7:this.#Z.pathname=this.#G();break;case 8:this.#Z.search=this.#G();break;case 9:this.#Z.hash=this.#G();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#U?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#P($,Z)}#P($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#j=0}#I(){this.#$=this.#Q,this.#j=0}#B($){this.#I(),this.#X=$}#V($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#V($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#L(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#T(){return this.#z(this.#$,"@")}#N(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#K(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#V(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#F(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#S(){return this.#W[this.#$].type=="CLOSE"}#C(){return this.#z(this.#$,"[")}#A(){return this.#z(this.#$,"]")}#G(){let $=this.#W[this.#$],Z=this.#V(this.#Q).index;return this.#Y.substring(Z,$.index)}#f(){let $={};Object.assign($,G$),$.encodePart=f4;let Z=wX(this.#G(),void 0,$);this.#U=b5(Z)}};_(rX,"Parser");var M5=["protocol","username","password","hostname","port","pathname","search","hash"],X$="*";function x5($,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}}_(x5,"extractValues");function D1($,Z){return Z?kZ($):$}_(D1,"processBaseURLString");function wZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=D1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=D1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=D1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=D1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=D1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=D1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=D1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=D1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=uX(Z.protocol,J)),typeof Z.username=="string"&&($.username=hX(Z.username,J)),typeof Z.password=="string"&&($.password=pX(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=mX(Z.hostname,J)),typeof Z.port=="string"&&($.port=dX(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!kX($.pathname,J)){let j=W.pathname.lastIndexOf("/");j>=0&&($.pathname=D1(W.pathname.substring(0,j+1),J)+$.pathname)}$.pathname=cX($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=gX(Z.search,J)),typeof Z.hash=="string"&&($.hash=yX(Z.hash,J)),$}_(wZ,"applyInit");function kZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}_(kZ,"escapePatternString");function tX($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}_(tX,"escapeRegexpString");function eX($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${tX(Z.delimiter)}]+?`,j=/[$_\u200C\u200D\p{ID_Continue}]/u,Y="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){Y+=kZ(X.value);continue}Y+=`{${kZ(X.value)}}${v$(X.modifier)}`;continue}let G=X.hasCustomName(),Q=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),F=z>0?$[z-1]:null,B=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&B&&!B.prefix.length&&!B.suffix.length)if(B.type===3){let K=B.value.length>0?B.value[0]:"";Q=j.test(K)}else Q=!B.hasCustomName();if(!Q&&!X.prefix.length&&F&&F.type===3){let K=F.value[F.value.length-1];Q=Z.prefixes.includes(K)}Q&&(Y+="{"),Y+=kZ(X.prefix),G&&(Y+=`:${X.name}`),X.type===2?Y+=`(${X.value})`:X.type===1?G||(Y+=`(${W})`):X.type===0&&(!G&&(!F||F.type===3||F.modifier!==3||Q||X.prefix!=="")?Y+="*":Y+=`(${J})`),X.type===1&&G&&X.suffix.length&&j.test(X.suffix[0])&&(Y+="\\"),Y+=kZ(X.suffix),Q&&(Y+="}"),X.modifier!==3&&(Y+=v$(X.modifier))}return Y}_(eX,"partsToPattern");var v5=class{#Y;#W={};#Z={};#$={};#j={};#Q=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new rX($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let j={ignoreCase:J.ignoreCase===!0},Y={pathname:X$,protocol:X$,username:X$,password:X$,hostname:X$,port:X$,search:X$,hash:X$};this.#Y=wZ(Y,$,!0),R5(this.#Y.protocol)===this.#Y.port&&(this.#Y.port="");let z;for(z of M5){if(!(z in this.#Y))continue;let X={},G=this.#Y[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,G$),X.encodePart=f4;break;case"username":Object.assign(X,G$),X.encodePart=lX;break;case"password":Object.assign(X,G$),X.encodePart=iX;break;case"hostname":Object.assign(X,VO),E5(G)?X.encodePart=k5:X.encodePart=w5;break;case"port":Object.assign(X,G$),X.encodePart=q5;break;case"pathname":b5(this.#W.protocol)?(Object.assign(X,TO,j),X.encodePart=sX):(Object.assign(X,G$,j),X.encodePart=nX);break;case"search":Object.assign(X,G$,j),X.encodePart=oX;break;case"hash":Object.assign(X,G$,j),X.encodePart=aX;break}try{this.#j[z]=C5(G,X),this.#W[z]=A5(this.#j[z],this.#Z[z],X),this.#$[z]=eX(this.#j[z],X),this.#Q=this.#Q||this.#j[z].some((Q)=>Q.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#Y[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=wZ(J,$,!1):J=wZ(J,x5($,Z),!1)}catch{return!1}let W;for(W of M5)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=wZ(J,$,!1):J=wZ(J,x5($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let j;for(j of M5){let Y=this.#W[j].exec(J[j]);if(!Y)return null;let z={};for(let[X,G]of this.#Z[j].entries())if(typeof G=="string"||typeof G=="number"){let Q=Y[X+1];z[G]=Q}W[j]={input:J[j]??"",groups:z}}return W}static compareComponent($,Z,J){let W=_((X,G)=>{for(let Q of["type","modifier","prefix","value","suffix"]){if(X[Q]<G[Q])return-1;if(X[Q]===G[Q])continue;return 1}return 0},"comparePart"),j=new qZ(3,"","","","",3),Y=new qZ(0,"","","","",3),z=_((X,G)=>{let Q=0;for(;Q<Math.min(X.length,G.length);++Q){let F=W(X[Q],G[Q]);if(F)return F}return X.length===G.length?0:W(X[Q]??j,G[Q]??j)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#j[$],[Y]):!Z.#$[$]&&J.#$[$]?z([Y],J.#j[$]):z(Z.#j[$],J.#j[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#Q}};_(v5,"URLPattern");function R3($,Z){for(let[J,W]of Object.entries($)){let j=new v5({pathname:J});if(j.test({pathname:Z}))return{routePath:J,params:j.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var y$={startIndex:0,carriedViews:[]};function $G($,Z){let J=B0($.path,Z);return J.includes("*")?null:J}function HO($,Z){if(!$)return y$;if($.search!==Z.search)return y$;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let j=$.segments[W],Y=Z.segments[W];if(Y.alwaysRun)break;if(j.viewPath!==Y.viewPath)break;let z=$G(j,$.params),X=$G(Y,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return y$;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:j})=>j)}}function IO($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let j=`/${W.join("/")}`;return j==="/"?"/":j.replace(/\/$/,"")}function ZG($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:j,to:Y}=$;if(!W)return y$;let z;try{z=new URL(W,j)}catch{return y$}if(z.origin!==j)return y$;let X=R3(Z,IO(z.pathname,J));if(!X)return y$;return HO({segments:X.route.segments,params:X.params,search:z.search},Y)}var y5="x-gemi-from";import{createElement as w1,Fragment as HG}from"react";function LO($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function E4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let j=W.viewPath;if("children"in W){Z[J]=[j];let Y=new W.children,z=E4(Y.routes);for(let[X,G]of Object.entries(z)){let Q=J==="/"?X:`${J}${X}`,F=X==="/"&&J!=="/"?J:Q;Z[F]=[j,...G]}if(Z[J].length===1)delete Z[J]}else Z[J]=[j]}else{let j=new W,Y=E4(j.routes);for(let[z,X]of Object.entries(Y)){let G=J==="/"?z:`${J}${z}`,Q=z==="/"&&J!=="/"?J:G;Z[Q]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[LO(J),W]))}function b4($,Z){let[J,W]=Z,j=$.find(([Y])=>Y===J);if(!j){$.push([J,[...W]]);return}for(let Y of W)b4(j[1],Y)}function R4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let j=W.viewPath;if(j==="__")continue;if(j==="REDIRECT")continue;if(j==="FILE")continue;if("children"in W){let Y=new W.children,z=R4(Y.routes);b4(Z,[j,z])}else b4(Z,[j,[]])}else{let j=new W,Y=R4(j.routes);for(let z of Y)b4(Z,z)}return Z}function g5($){let Z=[];for(let[J,W]of $)Z.push(J,...g5(W).flat());return Array.from(new Set(Z))}class Q$ extends g{static getFacadeAccessor(){return i}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??Q$.locale(),$.timeZone??Q$.timeZone())}static setLocale($=Q$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let j=N.getStore();if(Z.cookie!==!1)j.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return j.setLocale(W),W}}class m5{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function JG($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var PO=50;class vZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let j=JSON.stringify($.data)?.length??0;Z=j>=1024?`${(j/1024).toFixed(1)} kB`:`${j} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let W=Z.params??{},j=new URLSearchParams(JG(Z.search??{}));j.delete("json"),j.sort();let Y=B0($,W),z=j.toString(),X=this.keyFor(Y,z),G=this.entries.get(X);if(G)return G;let Q;if(J==="render"&&this.renderStartedAt!==null){let O=Math.round(performance.now()-this.renderStartedAt);if(O>PO)Q=O}let F,B=new Promise((O)=>{F=O}),K={path:Y,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:B,source:J,startedAt:this.elapsed()};return this.entries.set(X,K),this.fetcher($,W,j).then((O)=>{K.status="resolved",K.data=O},(O)=>{K.status="rejected",K.error=O}).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);F()}),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 R1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,j){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=j;this.name="QueryError"}}function yZ(){let $=JSON.stringify({error:p1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function p5(){return{status:403,error:{message:"Forbidden"}}}function w3($){let Z=gZ.getStore();return(J,W,j)=>{let Y=new URL($.url).origin,z=[B0(J,W),j.toString()].filter((F)=>F.length>0).join("?"),X=new Request(`${Y}/${z}`,{headers:$.headers,signal:$.signal}),G=WG($);if(G)mZ(X,G);let Q=new x(X,W);return gZ.run(Z,()=>N.run(Q,async()=>{try{let F=await T(J1).dispatchers(G).api.getRouteData(J);if(r$(F)){if(!F.ok)throw new R1(B0(J,W),j.toString(),F.status,F.body);return F.body}if(F instanceof Response){let B=await F.json().catch(()=>null);if(!F.ok)throw new R1(B0(J,W),j.toString(),F.status,B);return B}return F}catch(F){if(F instanceof R1)throw F;let B=new R1(B0(J,W),j.toString(),500,{message:F instanceof Error?F.message:String(F)});throw B.cause=F,B}}))}}var MO=new Set(["script","style","template","title"]),NO=/\shidden([\s=/]|$)/i,_O=/"[^"]*"|'[^']*'/g;function xO($){let Z=0,J=0,W=0,j=0;while(j<$.length){let Y=$.indexOf("<",j),z=Y===-1?$.length:Y;if(z>j){let B=$.slice(j,z).replace(/\s+/g,"").length;if(W>0)J+=B;else Z+=B}if(Y===-1)break;if($.startsWith("<!--",Y)){let B=$.indexOf("-->",Y+4);j=B===-1?$.length:B+3;continue}let X=$.indexOf(">",Y);if(X===-1)break;let G=$.slice(Y+1,X);j=X+1;let Q=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!Q)continue;let F=G.startsWith("/");if(!F&&MO.has(Q)&&!G.endsWith("/")){let B=$.indexOf(`</${Q}`,j);j=B===-1?$.length:B;continue}if(Q!=="div")continue;if(F){if(W>0)W-=1}else if(W>0)W+=1;else if(NO.test(G.replace(_O,'""')))W=1}return{shellChars:Z,deferredChars:J}}var SO=1000,CO=64;function AO($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function fO($,Z){if(Z.deferredChars<SO)return null;if(Z.shellChars>=CO)return null;return`[gemi] GET ${$} streams ${AO(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 jG($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let j=fO(J,W);if(!j)return;Z.add(J),$(j)}}}function YG(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),xO(Z)}}}function zG($,Z,J=1e4,W){let j=new TextEncoder,Y=()=>{};return new ReadableStream({start(z){let X=!1,G=(F)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:F})};Y=G,z.enqueue(j.encode(`${JSON.stringify($)}
|
|
14
|
+
`)),Z.onSettle((F)=>{if(X||F.status!=="resolved")return;z.enqueue(j.encode(`${JSON.stringify([F.path,F.variantKey,F.data])}
|
|
15
|
+
`))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){Y(!1)}})}import{Fragment as qP,createContext as EO,createElement as vP,lazy as yP,use as gP,useContext as mP}from"react";function XG($){return{islands:[],render:$,instances:new WeakMap,count:0}}var k3="gemi-slot",GG="data-slot",QG="data-gemi-slot";var bO=Symbol.for("gemi.staticRender"),FG=globalThis[bO]??=EO(null);import{createHash as DG}from"crypto";var h5='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';var RO="gemi-islands",sP=`'sha256-${DG("sha256").update(c5).digest("base64")}'`;function KG($,Z,J,W){if(!J)return $;let j=W?$.lastIndexOf(Z):$.indexOf(Z);return j===-1?$+J:$.slice(0,j)+J+$.slice(j)}var BG=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),nP=`'sha256-${DG("sha256").update(h5).digest("base64")}'`,wO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',kO="gemi-static";function OG($,Z,J,W,j){let Y=new Set,z=[];if(J)z=Z.islands.map((K)=>{let O=K.module?J(K.module):void 0;if(!O)return console.error(`[gemi] island ${K.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(K.load==="eager")for(let D of O.preload)Y.add(D);return{s:O.src,e:K.export,l:K.load}});let X=z.some((K)=>K!==null);if(!X&&!j)return $;let Q=(j?`<meta name="${kO}" content="${BG(j.identity)}"${j.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...Y].map((K)=>`<link rel="modulepreload" href="${BG(K)}"/>`).join(""),F=j?h5:c5,B=(X?`<script type="application/json" id="${RO}">${L1({i:z})}</script>`:"")+`<script type="module">${W?wO+F:F}</script>`;return KG(KG($,"</head>",Q,!1),"</body>",B,!0)}function qO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let j=J.exec($);j;j=J.exec($))if(W+=j[1]?-1:1,W===0)return J.lastIndex;return-1}function UG($){let Z=`<template ${QG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=qO($,J);if(W===-1)break;let j=J+Z.length,Y=$.slice(j,$.indexOf('"',j)),z=$.indexOf(">",j)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${k3} ${GG}="${Y}" style="display:contents"></${k3}>`;$=$.split(G).join(`<${k3} style="display:contents">${X}</${k3}>`)}return $}function VG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function TG($,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 vO=async()=>(await import("./chunk-7x2n788t.js")).default,d5,q3=async(...$)=>{return d5??=import("react-dom/server.browser").catch((Z)=>{throw d5=void 0,Z}),(await d5).renderToReadableStream(...$)},IG=1e4,LG="no-locale",yO=`
|
|
16
|
+
!function(){try{var d=document.documentElement,c=d.classList;
|
|
17
|
+
c.remove('light','dark');
|
|
18
|
+
var e=localStorage.getItem('theme');
|
|
19
|
+
if('system'===e||(!e&&'system'===defaultTheme)){
|
|
20
|
+
var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
|
|
21
|
+
if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
|
|
22
|
+
else{d.style.colorScheme='light';c.add('light')}
|
|
23
|
+
}else if(e){
|
|
24
|
+
c.add(e||'')
|
|
25
|
+
}}catch(e){}}()
|
|
26
|
+
`;async function gO($,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 i5="/assets";function mO($){return $===i5||$.startsWith(`${i5}/`)}function pO($){let Z=$.filter(mO);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 "${i5}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function hO($){let Z=T(J1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function u5($){let{status:Z=400,error:J,body:W,...j}=$;return new Response(W??J?.message,{...j,status:Z})}function cO($){let{status:Z=400,data:J,directive:W,headers:j}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:j,status:Z})}class v3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=jG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=fX();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":B5};this.flatViewRoutes=A4(J),pO(Object.keys(this.flatViewRoutes)),this.routeManifest=E4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=R4(J),this.flatComponentTree=g5(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let j=this.flatViewRoutes[W].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}this.root=$.root}async passesFeatureGates($){let Z=T(c1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)w4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{g$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:j}=$,Y=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let F of J?.[Q]??[])G.add(F);return[...G].map((Q)=>w1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return Y();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(j);if(!X)X=Y(),z.byRoute.set(j,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:j,data:Y,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(j,{static:!0,layout:W.layout});z.markRenderStart();let F=l5(),B=new AbortController,K=setTimeout(()=>B.abort(),IG),O=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=XG(async(U,V)=>{let H=await q3(U,{signal:B.signal,identifierPrefix:V,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let U;if(W.navigation){let P=W.navigation===!0?{}:W.navigation,I=P.version?String(await J(()=>P.version(Z))):"";U={identity:[W.layout??"",$.buildId??"",I].join("|"),prefetch:P.prefetch==="none"?"none":"intent"}}let V=await q3(w1(FG.Provider,{value:D,children:w1(HG,{children:[...Q,w1(this.root,{data:Y,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:F,rootLayout:G,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});await V.allReady.catch(()=>{});let H=UG(await new Response(V).text());return new Response(OG(H,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",U),{status:200,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:j,headers:Y,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:F,noStream:B,url:K,user:O,viewData:D,breadcrumbs:U,urlLocaleSegment:V,meta:H,isOgRequest:P,appId:I,features:C,staticView:f}=$,E=G.replace(`/${V}`,""),S={kind:"view",data:{meta:H,pageData:{[E]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:V,pathname:j,params:X,currentPath:G,searchParams:K.search,is404:!j?!0:!1,domain:Z.domain?hO(Z):null},appId:I,features:C,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},M=this.root,L=this.routeManifest[j];return async(k)=>{let{bootstrapModules:m=[],loaders:q1,getStyles:Z0,viewImportMap:o,cssManifest:q,ogMap:V0,viewModules:p$,clientEntry:h$,modulePreloadManifest:hZ,assetBase:U1,resolveIsland:c$,buildId:d$}=k,a=h$?[]:m,g3=(J0)=>[J0,`window.loaders=${q1}`,...h$?[`import(${JSON.stringify(h$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let J0=null,l$=null;for(let i$ of L??[])if(typeof V0[i$]==="function")l$=i$,J0=V0[i$];if(!J0)return new Response("Not found",{status:404});let VQ=Object.values(S.data.pageData)[0];try{await q3(w1(J0,VQ[l$]),{onError:()=>{}})}catch(i$){let{fonts:TQ,...HQ}=i$.satoriOptions,IQ=await Promise.all(TQ.map((m3)=>{return gO(m3.name,m3.weight,m3.style).then((_Q)=>({...m3,data:_Q}))})),D7=new Headers(Y);D7.set("Content-Type","image/png");let[LQ,PQ]=await Promise.all([vO(),S4("Rendering an OG image")]),MQ=await LQ(i$.jsx,{...HQ,fonts:IQ}),NQ=await PQ(Buffer.from(MQ)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(NQ),{headers:D7})}return new Response("data")}if(f&&j)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:f,currentViews:L,data:S.data,serverQueries:Q,headers:Y,getStyles:Z0,viewImportMap:o,viewModules:p$,resolveIsland:c$,buildId:d$});if(S.data.cssManifest=q,S.data.modulePreloadManifest=hZ??{},U1&&U1!=="/")S.data.assetBase=U1;let d4=this.modulePreloadLinks({clientEntry:h$,modulePreloadManifest:hZ,views:L??["404"],routeKey:j??"404"}),u$=await Z0(L);S.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let V1=new AbortController,cZ=setTimeout(()=>V1.abort(),IG),T1=Y6(F)||B,b=Bun.env.NODE_ENV!=="production"&&!T1&&j&&this.shellReporter.shouldObserve(j)?YG():null,h0=l5();try{let J0=await q3(w1(HG,{children:[...d4,...u$,w1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:yO}}),w1(M,{data:S.data,viewImportMap:o,viewModules:p$,serverQueries:Q,dictionarySink:h0,key:"root"})]}),{bootstrapScriptContent:g3(`window.__GEMI_DATA__ = ${L1(S.data)}`),bootstrapModules:a,signal:V1.signal,...T1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(l$){if(Bun.env.NODE_ENV!=="production")console.error(l$)}});if(J0.allReady.catch(()=>{}).finally(()=>clearTimeout(cZ)),T1)await J0.allReady.catch(()=>{});return new Response(xJ(J0,Q,{onShell:T1?void 0:()=>Q.markShell(),onChunk:b?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(V1.signal.aborted)),b)this.shellReporter.report(j,b.measure())})},h0),{status:!j?$.refusedStatus??404:200,headers:Y})}catch(J0){if(clearTimeout(cZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(V1.signal.aborted))),J0;let l$=await q3(w1("div"),{bootstrapScriptContent:g3(`window.error= ${L1(J0.message)}; window.stack_trace=${L1(J0.stack)};window.__GEMI_DATA__ = ${L1(S.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...a]:a});return new Response(xJ(l$,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(V1.signal.aborted)))}),{status:!j?$.refusedStatus??404:200,headers:Y})}}}viewRefusalStatus($,Z,J){if(K$(Z))return 404;if(Z?.kind===g1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(m1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof R1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),j=J.pathname.endsWith(".og"),Y=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=Y.split("/"),G=Y,Q=null,F=null,B=T(i),K=R3(this.flatViewRoutes,Y),O=B.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(LG);if(O&&B.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,F=z;if(O&&!j&&F===null&&!(F===null&&K!==null)){let M=PG(z,B.supportedLocales,B.defaultLocale);if(M){let L=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${L}${W?".json":""}${J.search}`}})}}if(O&&!j){let M=T(i).detectLocale(new x($,{},"view",G));if(F===null&&M!==B.defaultLocale){let L=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${L}${J.search}`}})}}G=G.replace("//","/");let U=[],V=[],H=null,P={},I=null,C=!1,f=[],E;try{let M=R3(this.flatViewRoutes,G);if(F&&M?.route.middleware.includes(LG))M=null;if(M){if(H=M.routePath,P=M.params,U=M.route.exec,V=M.route.middleware,f=M.route.features,C=V.includes("no-stream"),E=M.route.static,W&&this.partialRendering){let L=$.headers.get(y5),k=ZG({flatViewRoutes:this.flatViewRoutes,supportedLocales:T(i).supportedLocales,from:L,origin:J.origin,to:{segments:M.route.segments,params:P,search:J.search}});if(k.startIndex>0)U=U.slice(k.startIndex),I={from:L,carriedViews:k.carriedViews}}}}catch(M){throw M}if(E&&W)return new Response("Not found",{status:404});let S=new x($,P,"view",H);return this.hooks.onRequestStart(S),await N.run(S,async()=>{let M=null,L=N.getStore(),k=gZ.getStore(),m=(q)=>gZ.run(k,()=>N.runWith(L,q));L.serverQueries=new vZ(w3($));let q1=new Set;L.serverQueries.onQueryFail((q)=>{q1.add(q.error);try{m(()=>Promise.resolve(this.hooks.onRequestFail(o,q.error)).catch(()=>{}))}catch{}});let Z0=VG(E);if(F){let q=F.replaceAll("/","");Q$.setLocale(q,{cookie:Z0.locale})}else if(B.isLocaleAware&&!O)L.setLocale(B.defaultLocale);else Q$.setLocale(void 0,{cookie:Z0.locale});let o=L.req;if(Z0.session)w4();try{let q=null;try{await T(y1).runMiddleware(V)}catch(b){if(q=this.viewRefusalStatus(o,b,q1),q===null)throw b}if(q!==null||f.length>0&&!await this.passesFeatureGates(f))H=null,U=[],o.routePath="";let V0=T(i),p$=V0.isEnabled,h$=V0.isLocaleAware,hZ=new x($,o.params),U1={defaultLocale:V0.defaultLocale,timeZone:V0.detectTimeZone(hZ)};if(h$){let b=null;if(F)b=F.replaceAll("/",""),L.setLocale(b);else if(!O)b=L.locale??V0.defaultLocale;else b=V0.detectLocale(hZ),L.setLocale(b);let h0=p$?V0.getPageTranslations(b,o.routePath):{};U1={...U1,supportedLocales:V0.supportedLocales,currentLocale:b,dictionary:{[b]:h0},defaultLocale:V0.defaultLocale,...O?{}:{localeRouting:"off"}}}await MG(U1.currentLocale??"");let c$;try{c$=await Promise.all(U.map((b)=>b(o)))}catch(b){if(q=this.viewRefusalStatus(o,b,q1),q===null)throw b;H=null,U=[],o.routePath="",c$=[]}let{cookies:d$,headers:a}=L;if(q!==null)a.set("Cache-Control","no-store");M={data:c$,cookies:d$,headers:a,user:L.user,prefetchedData:L.serverQueries.snapshotResolved(),currentPathName:H,params:o.params,urlLocaleSegment:Q,meta:L.renderMeta(),appId:T(m5).id,features:await T(c1).forClient()};let{params:g3,user:d4}=M,u$={},V1={};for(let b of c$??[]){let[h0,J0]=Object.entries(b)?.[0]??[];if(!h0||!J0)continue;V1[`${h0}:${H}`]=J0.breadcrumb,u$[h0]=J0}let cZ=u$.FILE;if(cZ){for(let b of d$)a.append("Set-Cookie",b.toString());try{await this.onRequestEnd(o)}catch(b){g$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await WJ(cZ,a)}if(W){a.set("Content-Type","application/x-ndjson; charset=utf-8"),a.append("Vary",y5),d$.forEach((h0)=>a.append("Set-Cookie",h0.toString())),await this.hooks.onRequestEnd(o);let b={meta:I&&!L.metadata.touched?null:M.meta,data:{[G]:u$},breadcrumbs:V1,prefetchedData:L.serverQueries.snapshotResolved(),i18n:U1,features:M.features,is404:!H,appId:M.appId,partial:I};return new Response(zG(b,L.serverQueries,void 0,({aborted:h0})=>m(()=>this.completeStream(o,L.serverQueries.summarize(h0)))),{headers:a})}if(a.set("Content-Type","text/html; charset=utf-8"),!C&&!(E&&H))a.append("Vary","User-Agent");let T1=Boolean(E&&H);if(!T1||Z0.session)w4();for(let b of d$)a.append("Set-Cookie",b.toString());if(!T1||Z0.csrf){let b=Bun.CSRF.generate(process.env.SECRET);a.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(o,{mintSession:!T1||Z0.session})}catch(b){g$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(T1)TG(a,E);return await this.render({req:o,runInRequestScope:m,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:a,i18n:U1,params:g3,pathname:J.pathname,serverQueries:L.serverQueries,userAgent:$.headers.get("user-agent"),noStream:C,url:J,user:d4,viewData:u$,breadcrumbs:V1,urlLocaleSegment:Q,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:j,staticView:H?E:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===g1){let V0=W?cO(q.payload.viewData??q.payload.api):u5(q.payload.view);for(let p$ of L.cookies)V0.headers.append("Set-Cookie",p$.toString());return V0}if(!q1.has(q))this.hooks.onRequestFail(o,q);if(m1(q))return console.error(q),W?yZ():u5(p5());if(q instanceof R1&&q.status===403)return W?yZ():u5(p5());throw q}},Z)}}function s5(){let $=JSON.stringify({error:p1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class CG extends b0{routes={"/api-routes":this.get(()=>{let $=T(q4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[j,Y]of Object.entries(W)){let{exec:z,middleware:X}=Y;Z.push({path:J,method:j,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=T(v3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:j}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:j,middleware:W});return Z})}}var dO=new Set([v1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),uO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,lO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function iO($,Z,J,W){for(let[j,Y]of Object.entries(J.headers??{})){if(Y===void 0||Y===null)continue;let z=j.toLowerCase();if(dO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${j}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(j,Y)}for(let[j,Y]of Object.entries(J.cookies??{})){if(Y===void 0||Y===null)continue;if(j===v1)throw Error(`dispatchAs: credentials may not set the "${v1}" cookie. The access token stays the initiator's.`);if(!uO.test(j)||!lO.test(Y))throw Error(`dispatchAs: "${j}" is not a cookie a Cookie header can carry.`);Z.push(`${j}=${Y}`)}}function sO($,Z){let J=$.body.getReader(),W=!1,j=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},Y=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){j(),z.error(G);return}if(X.done){j();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{j()}}},{highWaterMark:0});return new Response(Y,{status:$.status,statusText:$.statusText,headers:$.headers})}function NG($){let{status:Z=400,data:J,headers:W}=$,j=new Headers({"Content-Type":"application/json",...W});if(!j.has("Cache-Control"))j.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:j})}function _G($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let j=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&j.length===0)return $;let Y=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of j)z.append("Set-Cookie",X)};try{return Y($.headers),$}catch{let z=new Headers($.headers);return Y(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class q4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=AX();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=I5({"/":$.rootRouter,"/auth":D5,"/__gemi__/services/i18n":O5,"/__gemi__/services/logs":H5,"/__gemi__/services/image":T5,"/__gemi__/debug":CG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=SG(Z.pathname),W={},j;for(let[Y]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:Y});if(z.test({pathname:J})){j=Y,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:j}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await T(y1).runMiddleware(W)}catch(j){if(j.kind===g1)return NG(j.payload.api);else{if(K$(j))return s5();if(this.onRequestFail(Z,j),console.error(j),m1(j))return yZ();throw j}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),j={};try{j=await W()}catch(Y){if(Y.kind===g1)return NG(Y.payload.api);if(K$(Y))return s5();if(this.onRequestFail(J.req,Y),console.error(Y),m1(Y))return yZ();throw Y}return j}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(j){g$.error(j?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(j)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((j)=>{console.error(j)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),j=this.flatRoutes[W];if(!j||!j[$.method])return new Response(JSON.stringify({error:p1("not_found","Not found",404)}),{status:404});let Y=new x($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(Y);return await N.run(Y,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,Y,W)};try{let Q=T(i);if(Q.isEnabled){let U=Q.detectLocale(Y);z.setLocale(U)}z.setRequest(Y),T(y1).applyDefaultBodyLimit($);let F=await this.runRouteMiddleware(W,Y);if(F instanceof Response){let U=_G(F,z.headers,z.cookies);return await G(),U}let B=await this.getRouteData(W),K=z.headers,O=z.cookies;if(B instanceof Response){let U=_G(B,K,O);if(this.isOpenEndedBody($,U)){let V=sO(U,()=>this.endRequest(z,Y,W));return X=!0,V}return await G(),U}let D=(r$(B)?B:B$.json(B)).toResponse(K,O);return await G(),D}catch(Q){if(!X)try{await G()}catch(F){console.error(F)}throw Q}},Z)}async dispatchAs($,Z,J,W,j){let Y=new URL($.rawRequest.url).origin,z=new URL(`${Y}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==Y||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=j?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,F=[],B=G?null:$.cookies.get(v1);if(B)F.push(`${v1}=${B}`);if(j?.credentials)iO(Q,F,j.credentials,G!==void 0);if(F.length>0)Q.set("Cookie",F.join("; "));let K=G?null:$.headers.get(v1);if(K)Q.set(v1,K);let O=$.headers.get("User-Agent");if(O)Q.set("User-Agent",O);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let U=new Request(z,{method:Z,headers:Q,body:D,...j?.signal?{signal:j.signal}:{}});if(xG(U,e$($),G?.grant,j?.progress),$.domain)mZ(U,$.domain);let V=G?{user:G.user}:void 0;return N.exit(()=>i3.exit(()=>this.handleApiRequest(U,V)))}}import{timingSafeEqual as nO}from"crypto";var y4="",a5="*",oO=60000,aO=1e4,n5=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,v4=16,AG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,o5="x-forwarded-host";function fG($){return $.startsWith(":")}function r5($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&nO(J,W)}function rO($){if(!$)return null;if($===!0)return{header:o5,secret:null};return{header:($.hostHeader??o5).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function tO($){if(!$||$===!0)return;let{hostHeader:Z,secret:J}=$;if(Z!==void 0&&(typeof Z!=="string"||!AG.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(!J)return;if(typeof J.header!=="string"||!AG.test(J.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${J.header}".`);if(J.header.toLowerCase()===(Z??o5).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof J.value!=="string"||J.value.length<v4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${v4} characters. A guessable one lets any client name its own host.`)}function O1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function eO($){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 $U($){let Z=O1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((Y)=>n5.test(Y)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<v4)throw Error(`\`route.domains.ask.secret\` must be at least ${v4} characters. A guessable one is worse than leaving \`ask\` out.`);tO($.trustProxy);let W=new Set,j=null;for(let Y of $.groups??[]){let{subdomain:z}=Y;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),fG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(j)throw Error(`\`route.domains\` declares two param subdomains, "${j.subdomain}" and "${z}"; a host could match either.`);j=Y;continue}if(Y.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>n5.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&j&&!j.exists)throw Error(`\`route.domains.ask\` is set, so "${j.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class t5{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){$U($),this.root=O1($.root),this.hostTrust=rO($.trustProxy);for(let Z of $.groups??[])if(fG(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??oO,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!r5($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return O1(this.forwardedHost($))??O1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),j=this.forwardedHost($),Y=j&&O1(j)?eO(j):null;return`${W}://${Y??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:a5,params:{},custom:!0};return null}async allows($,Z){let J=O1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:y4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),j=this.fixed.get(W);if(j)return{host:$,group:j.subdomain,params:{},custom:!1};if(this.param&&n5.test(W)){let Y={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(Y,Z))return null;return{host:$,group:this.param.subdomain,params:Y,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let j=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,j);let Y;try{Y=await j}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=aO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:Y,expiresAt:Date.now()+this.cacheTtlMs})}return Y}forget($){if($===void 0)this.cache.clear();else{let Z=O1($);if(Z)this.cache.delete(Z)}}}var ZU="/__gemi__/domains/ask";class J1{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(y4,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new t5(J);let W=(j)=>({api:j.api?new q4({...Z.api,...j.api}):$.api,view:j.view?new v3({...Z.view,...j.view}):$.view});for(let j of J.groups??[])this.groups.set(j.subdomain,W(j));if(J.custom?.fallback)this.groups.set(a5,W(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)EG($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return mZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==ZU)return null;if(!r5(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??y4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function g4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var bG=600000;function RG($,Z){return[$6($,Z),$6($,Z-1)]}class A{static token="auth";config;provider;constructor($={},Z=new EJ){k9($.oauthProviders),this.config={...Y$(q9($),$),emailCode:_J($.emailCode)},this.provider=Z}async oauthProvider($){return await YZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await o9(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=T().bound(J1)?T(J1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?T(J1).resolver?.root:O1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??O1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!HJ($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),j=g4(J.expiresAt),Y=g4(J.absoluteExpiresAt);if(j<=W||Y<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let j=Date.now(),Y=Math.floor(j/bG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=$6($,Y),F=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:F,userAgent:Z,...this.freshLifetime(j)}),!0}))z=Q}if(!z){for(let Q of RG($,Y))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(HJ($)||!this.config.migrateLegacySession){let j=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),j}let J=Math.floor(Date.now()/bG),W=RG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let j=await this.userProvider.findSession({token:$,userAgent:Z});for(let Y of W){if(j?.user)break;j=await this.userProvider.findSession({token:Y,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let Y of W)await this.userProvider.deleteSession({token:Y});return j})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),j=await this.userProvider.updateSession({token:$.token,expiresAt:W}),Y=this.requestCarryingCookie($.token);if(Y)Y.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(Y,W));if(!j)return $;return{...$,expiresAt:j.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new x;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 x,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new D$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),j=M9(J),Y=await this.userProvider.createSessionV2({token:j,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:j,userAgent:W??""});return z?.user?z:Y}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),W=await this.config.generateCode($),j=typeof W==="string"&&W!==""?W:f9(Z);return await this.userProvider.createMagicLinkToken({email:$,token:Z6("link",$,J),pin:Z6("pin",$,j)}),{email:$,pin:j,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:j}=this.config.emailCode,Y=await this.userProvider.findMagicLinkTokenByEmail($);if(!Y)return oZ("pin",$,null,Z),{status:"invalid"};let z=g4(Y.createdAt);if(z+W*60000<=Date.now())return oZ("pin",$,null,Z),{status:"expired"};if(!await R9(Y.id,z,j,W))return await this.userProvider.claimMagicLinkToken(Y.id),{status:"too_many_attempts"};if(!oZ("pin",$,Y.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(Y.id))return{status:"invalid"};return{status:"ok",row:Y}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=oZ("link",$,J?.token,Z);if(!J||!W)return!1;if(g4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class R0 extends g{static getFacadeAccessor(){return A}static async user(){let $=await R0.userOrNull();if($)return $;throw new D$({redirectTo:s3(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await d3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return j1(Z?.search.get(W1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await R0.user();if(!await $(Z))throw new $Z}static async guardSafe($){let Z=await R0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class m4{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 vZ(w3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=m4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){m4.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 vZ(w3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function wG($,Z,J="/"){let W=new URL($.origin),j=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,Y=new URL(J.startsWith("/")?J:`/${J}`,W),z=JU(j);if(!z)throw Error(`"${j}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(Y.hostname=z.hostname,z.port)Y.port=z.port;return Y.toString()}function JU($){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 qG{static origin($){return kG($)}static absolute($,...Z){return`${b3()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=T(J1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let j=N.getStore()?.req?.rawRequest,Y=j?W.publicOrigin(j):b3();if(!Y)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return wG({root:W.root,origin:Y},$,B0(String(Z),J[0]??{}))}}class vG{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static fonts($){N.getStore().metadata.fonts($)}}var WU={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class k1 extends g{static getFacadeAccessor(){return m$}static get client(){return this.getFacadeRoot().client}static get($){return k1.client.get($)}static set($,Z){return k1.client.set($,Z)}static del(...$){return k1.client.del(...$)}static exists($){return k1.client.exists($)}static incr($){return k1.client.incr($)}static expire($,Z){return k1.client.expire($,Z)}static ttl($){return k1.client.ttl($)}}function J_($){return $}function yG(){return{store:"memory",ttl:null}}class e5{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 jU="500";class $7{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=`${YU(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",jU]),[j,Y]=Array.isArray(W)?W:["0",[]];if(J=String(j),Array.isArray(Y)&&Y.length>0)await $.send("UNLINK",Y.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=T(),Z=$.bound(m$)?$.make(m$).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 YU($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var zU="k:",gG="tag:",XU="t:";class J7{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,j]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof j!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,j)}}class W7 extends J7{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=Y$(yG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)Z7(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 pG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return zU+hG($)}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 j=JSON.stringify(Z);if(j===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,j,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let j=this.inflight.get($);if(j)return j;let Y=(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($,Y),Y}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=gG+Z,W=await this.store.get(J);if(W!==null)return W;let j=mG();return await this.store.set(J,j,null),j}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(gG+Z,mG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:Z7(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new e5(this.config.memory);if($==="redis"){let Z=this.options.application;return new $7({...this.config.redis,client:Z?{send:(J,W)=>Z.make(m$).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 pG extends J7{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){hG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${XU}${Z.join(",")}:${$}`}}function hG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function mG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class cG extends g{static getFacadeAccessor(){return W7}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 dG extends g{static getFacadeAccessor(){return Y1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class lG extends g{static getFacadeAccessor(){return uG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class sG extends g{static getFacadeAccessor(){return iG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class nG extends g{static getFacadeAccessor(){return E3}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 E_($){return $}function oG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function p4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function j7($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,j]of J){let Y=Number(j);if(j!==""&&Number.isSafeInteger(Y)&&Y>=0)Z.set(W,Y)}return Z}var{SQL:GU}=globalThis.Bun;function QU(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var FU=async($)=>{let Z=new GU($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,j)=>Z.listen(J,W,j),close:()=>Z.close({timeout:1})}},KU=async($)=>{let Z;try{Z=(await import("./chunk-c48gag78.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,j,Y)=>J.listen(W,j,Y),close:()=>J.end({timeout:1}).catch(()=>{})}},aG=($)=>QU()?FU($):KU($);var BU=/^[A-Za-z_][A-Za-z0-9_]*$/;class Y7{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",j=Z.notifyChannel??"gemi_changes";for(let z of[J,W,j])if(!BU.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let Y=Z.retain??1000;if(!Number.isInteger(Y)||Y<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Y}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=j,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=Y,this.listener=Z.listener??aG}async createTable(){for(let $ of DU(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let j=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return j();let Y=this.sqliteTurn.then(j);return this.sqliteTurn=Y.catch(()=>{}),Y}let W=this.append(J,$,Z);return rG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),j=$.unsafe(`"${this.entriesTable}"`),[Y]=await $`
|
|
27
|
+
INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
|
|
28
|
+
ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
|
|
29
|
+
RETURNING seq
|
|
30
|
+
`,z=Number(Y.seq);if(await $`
|
|
31
|
+
INSERT INTO ${j} (channel, seq, data, created_at)
|
|
32
|
+
VALUES (${Z}, ${z}, ${JSON.stringify(J??null)}, ${Date.now()})
|
|
33
|
+
`,z>this.retain)await $`DELETE FROM ${j} WHERE channel = ${Z} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await $`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Z}`})`;return z}async heads($){let Z=new Map($.map((j)=>[j,0]));if($.length===0)return Z;let J=this.sql,W=await J`
|
|
34
|
+
SELECT channel, seq FROM ${J.unsafe(`"${this.headsTable}"`)}
|
|
35
|
+
WHERE channel IN ${J([...$])}
|
|
36
|
+
`;for(let j of W)Z.set(j.channel,Number(j.seq));return Z}async read($,Z,J){let W=this.sql,[j]=await W`
|
|
37
|
+
SELECT seq FROM ${W.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
|
|
38
|
+
`,Y=j?Number(j.seq):0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(Z===Y)return{entries:[],head:Y,gap:!1};let z=await W`
|
|
39
|
+
SELECT seq, data FROM ${W.unsafe(`"${this.entriesTable}"`)}
|
|
40
|
+
WHERE channel = ${$} AND seq > ${Z}
|
|
41
|
+
ORDER BY seq
|
|
42
|
+
LIMIT ${J}
|
|
43
|
+
`;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:Y,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:Y,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let j=W.indexOf(" "),Y=Number(W.slice(0,j));if(j>0&&Number.isInteger(Y))$(W.slice(j+1),Y)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=P1();if($===void 0||V$()!==this.connection)return;return $}}function DU($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
44
|
+
"channel" TEXT NOT NULL PRIMARY KEY,
|
|
45
|
+
"seq" BIGINT NOT NULL
|
|
46
|
+
)`,`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
47
|
+
"channel" TEXT NOT NULL,
|
|
48
|
+
"seq" BIGINT NOT NULL,
|
|
49
|
+
"data" TEXT NOT NULL,
|
|
50
|
+
"created_at" BIGINT NOT NULL,
|
|
51
|
+
PRIMARY KEY ("channel", "seq")
|
|
52
|
+
)`]}class z7{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),j=W?.head??0;if(Z>j)return{entries:[],head:j,gap:!0};if(!W||Z===j)return{entries:[],head:j,gap:!1};let Y=W.entries[0]?.seq??j+1;if(Y>Z+1)return{entries:[],head:j,gap:!0};let z=Z+1-Y;return{entries:W.entries.slice(z,z+J),head:j,gap:!1}}}var JQ=new TextEncoder;function tG($,Z){return JQ.encode(`id: ${$}
|
|
53
|
+
data: ${JSON.stringify(Z)}
|
|
54
|
+
|
|
55
|
+
`)}function WQ($,Z,J,W){let j=Z instanceof Request?Z:Z.rawRequest,Y=W.cursor??j.headers.get("Last-Event-ID")??new URL(j.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:Y,signal:j.signal})}catch(K){if(!(K instanceof h4))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,G=!1,Q=!1,F=(K)=>{if(X)clearInterval(X);if(X=null,z.close(),Q)return;Q=!0;try{K.close()}catch{}},B=new ReadableStream({start(K){X=setInterval(()=>{if(ZQ())return F(K);try{K.enqueue(JQ.encode(eG))}catch{F(K)}},$.config.keepaliveInterval)},async pull(K){try{if(!G){if(await z.ready(),G=!0,!Q)K.enqueue(tG(z.cursor,{type:"ready"}));return}let O=await z.next();if(O.done||Q)return F(K);K.enqueue(tG(z.cursor,O.value))}catch(O){if(!Q)console.error("[gemi] A change feed stream failed.",O);F(K)}},cancel(){if(Q=!0,X)clearInterval(X);X=null,z.close()}});return new Response(B,{headers:$Q()})}var jQ=255,YQ=500,OU=30000;class h4 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class Q7{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=YQ;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=Y$(oG(),$),this.driver=VU(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){G7($);let J=Z===void 0?null:Z;if(P1()!==void 0&&!this.driver.joinsTransaction?.())return bZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return bZ(()=>this.wake($,W)),W}async head($){return G7($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=X7($);return p4(await this.driver.heads(Z))}subscribe($,Z={}){let J=X7($);if(this.all.size>=this.config.maxSubscriptions)throw new h4(this.config.maxSubscriptions);let W=new zQ(this,J,UU(Z.cursor),this.config,Z.signal);this.all.add(W);for(let j of J){let Y=this.followers.get(j);if(!Y)this.followers.set(j,Y=new Set);Y.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return WQ(this,$,X7(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,j]of J)this.wake(W,j)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=YQ,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,OU)}}}class zQ{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,j){this.manager=$;this.config=W;this.signal=j;this.channels=Z;for(let Y of Z){let z=J.get(Y);if(z!==void 0)this.positions.set(Y,z),this.readTo.set(Y,z),this.dirty.add(Y)}if(j?.aborted)this.close();else j?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return p4(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:j,gap:Y}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(Y){this.readTo.set($,j),this.pending.push({type:"reset",channel:$,seq:j});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function G7($){if(typeof $!=="string"||$===""||$.length>jQ)throw Error(`A change feed channel is a string of 1 to ${jQ} characters; got ${JSON.stringify($)}.`)}function X7($){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)G7(J);return Z}function UU($){if($===void 0||$===null)return new Map;if(typeof $==="string")return j7($);let Z=$ instanceof Map?[...$]:Object.entries($);return j7(p4(new Map(Z)))}function VU($,Z){if($==="memory")return new z7;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 Y7(Z.make(T$));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 XQ extends g{static getFacadeAccessor(){return Q7}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class y3 extends m0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(m0)?$.make(m0):void 0;if(Z instanceof y3)return Z;let J=new y3($,Z);return $.instance(m0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(m0,this.previous);return}this.application.forget(m0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${F7($,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 ${F7($,Z,J)} not to have been broadcast, but it was broadcast ${K7(W.length)}: ${B7(W)}.`)}assertSentTimes($,Z,J,W){let j=this.matching($,J,W);if(j.length===Z)return;throw Error(`Expected ${F7($,J,W)} to have been broadcast ${K7(Z)}, but it was broadcast ${K7(j.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${B7(this.sent)}.`)}matching($,Z,J){return o$($),this.sent.filter((W)=>(W.pattern===$||E7($,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: ${B7(this.sent)}.`}}function F7($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function K7($){return`${$} ${$===1?"time":"times"}`}function B7($){return $.map((Z)=>`${Z.topic} ${Z.event}(${TU(Z.data)})`).join(", ")}function TU($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class GQ extends g{static getFacadeAccessor(){return m0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return y3.install(T())}}class QQ extends g{static getFacadeAccessor(){return c1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class c4{bound;constructor($){this.bound=$}get name(){return this.bound??V$()}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 BQ(J.sql,(W)=>FQ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-p0ccxfkq.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:j}=OQ($,DQ(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,j)}handle(){let $=P1();if($===void 0)return;return V$()===this.name?$:void 0}connection($=this.name){return KQ($),T(T$).connection($)}}var pZ=new c4;class UQ extends g{static getFacadeAccessor(){return T$}static connection($){return new c4($)}static get sql(){return pZ.sql}static get dialect(){return pZ.dialect}static query($){return pZ.query($)}static execute($){return pZ.execute($)}static transaction($){return pZ.transaction($)}static schema(){return pZ.schema()}static close(){return this.getFacadeRoot().close()}}export{l0 as Nd,dZ as Od,s4 as Pd,n$ as Qd,lZ as Rd,b0 as Sd,d3 as Td,TJ as Ud,HJ as Vd,M9 as Wd,h1 as Xd,Y1 as Yd,r as Zd,$9 as _d,e$ as $d,N9 as ae,_9 as be,LJ as ce,PJ as de,Z6 as ee,oZ as fe,gF as ge,RH as he,q9 as ie,c9 as je,SJ as ke,d9 as le,u9 as me,iF as ne,l9 as oe,CJ as pe,oF as qe,aF as re,AJ as se,i9 as te,s9 as ue,c1 as ve,n9 as we,$K as xe,EJ as ye,YJ as ze,n3 as Ae,H1 as Be,B$ as Ce,uQ as De,WJ as Ee,I1 as Fe,Q$ as Ge,m4 as He,qG as Ie,vG as Je,WU as Ke,k1 as Le,J_ as Me,yG as Ne,e5 as Oe,$7 as Pe,W7 as Qe,pG as Re,cG as Se,dG as Te,lG as Ue,sG as Ve,nG as We,E_ as Xe,oG as Ye,p4 as Ze,j7 as _e,Y7 as $e,z7 as af,h4 as bf,Q7 as cf,zQ as df,XQ as ef,h as ff,iZ as gf,UI as hf,Z5 as if,VI as jf,TI as kf,LI as lf,$X as mf,W5 as nf,WX as of,xI as pf,zX as qf,m0 as rf,C3 as sf,XX as tf,GQ as uf,QQ as vf,c4 as wf,UQ as xf,Y5 as yf,rD as zf,U5 as Af,V5 as Bf,qL as Cf,xX as Df,SX as Ef,u3 as Ff,y1 as Gf,lL as Hf,AX as If,fX as Jf,m5 as Kf,yZ as Lf,p5 as Mf,sP as Nf,nP as Of,i5 as Pf,mO as Qf,u5 as Rf,cO as Sf,v3 as Tf,s5 as Uf,NG as Vf,_G as Wf,q4 as Xf,J1 as Yf,A as Zf,R0 as _f,l3 as $f,q7 as ag,gQ as bg,R7 as cg,y7 as dg,e4 as eg,$J as fg,ZJ as gg,g7 as hg,lQ as ig,iQ as jg,l7 as kg,s7 as lg,o7 as mg,J9 as ng,W9 as og,j9 as pg,GJ as qg,tQ as rg,Y0 as sg,U9 as tg,JZ as ug,L9 as vg};
|
|
56
|
+
|
|
57
|
+
//# debugId=6748AAC858FFCD4764756E2164756E21
|