gemi 0.114.0 → 0.116.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/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-75wk4jxd.js → chunk-15c2vgaf.js} +2 -2
- package/dist/{chunk-75wk4jxd.js.map → chunk-15c2vgaf.js.map} +1 -1
- package/dist/{chunk-56fgk5rq.js → chunk-1hr4xht1.js} +2 -2
- package/dist/{chunk-56fgk5rq.js.map → chunk-1hr4xht1.js.map} +1 -1
- package/dist/{chunk-8c2fs0n0.js → chunk-1myhm0g3.js} +3 -3
- package/dist/{chunk-8c2fs0n0.js.map → chunk-1myhm0g3.js.map} +1 -1
- package/dist/chunk-1q9kd20m.js +5 -0
- package/dist/{chunk-fakvf9wb.js.map → chunk-1q9kd20m.js.map} +1 -1
- package/dist/{chunk-37qk5dh8.js → chunk-1vzks22y.js} +2 -2
- package/dist/{chunk-37qk5dh8.js.map → chunk-1vzks22y.js.map} +1 -1
- package/dist/{chunk-8h7dh2h2.js → chunk-2tzm58j3.js} +2 -2
- package/dist/{chunk-8h7dh2h2.js.map → chunk-2tzm58j3.js.map} +1 -1
- package/dist/{chunk-x157wrgy.js → chunk-3hrj5rwm.js} +2 -2
- package/dist/{chunk-x157wrgy.js.map → chunk-3hrj5rwm.js.map} +1 -1
- package/dist/{chunk-wysm6qte.js → chunk-4088szy9.js} +2 -2
- package/dist/{chunk-wysm6qte.js.map → chunk-4088szy9.js.map} +1 -1
- package/dist/{chunk-m17ktssc.js → chunk-41da9628.js} +1 -1
- package/dist/chunk-49nyyjfe.js +5 -0
- package/dist/{chunk-jzp0fs6h.js.map → chunk-49nyyjfe.js.map} +3 -3
- package/dist/{chunk-cna105t6.js → chunk-56jky6vf.js} +2 -2
- package/dist/{chunk-cna105t6.js.map → chunk-56jky6vf.js.map} +1 -1
- package/dist/{chunk-h4pazcgg.js → chunk-6cx8ncd4.js} +2 -2
- package/dist/{chunk-h4pazcgg.js.map → chunk-6cx8ncd4.js.map} +1 -1
- package/dist/{chunk-7fwp7vwh.js → chunk-6d8rvr1v.js} +2 -2
- package/dist/{chunk-7fwp7vwh.js.map → chunk-6d8rvr1v.js.map} +1 -1
- package/dist/{chunk-h2r2rdhj.js → chunk-785b41h1.js} +2 -2
- package/dist/{chunk-h2r2rdhj.js.map → chunk-785b41h1.js.map} +1 -1
- package/dist/{chunk-7v8sgqen.js → chunk-79xg42e7.js} +2 -2
- package/dist/{chunk-7v8sgqen.js.map → chunk-79xg42e7.js.map} +1 -1
- package/dist/{chunk-8rt4wx8z.js → chunk-7vb4eey2.js} +2 -2
- package/dist/{chunk-8rt4wx8z.js.map → chunk-7vb4eey2.js.map} +1 -1
- package/dist/{chunk-ap5gek56.js → chunk-8rv62v14.js} +2 -2
- package/dist/{chunk-ap5gek56.js.map → chunk-8rv62v14.js.map} +1 -1
- package/dist/{chunk-1f9sqht5.js → chunk-98m15b9x.js} +2 -2
- package/dist/{chunk-1f9sqht5.js.map → chunk-98m15b9x.js.map} +1 -1
- package/dist/{chunk-d4m4amy4.js → chunk-9n1hx3mq.js} +2 -2
- package/dist/{chunk-d4m4amy4.js.map → chunk-9n1hx3mq.js.map} +1 -1
- package/dist/{chunk-erxv1jz7.js → chunk-aazmrxj9.js} +2 -2
- package/dist/{chunk-erxv1jz7.js.map → chunk-aazmrxj9.js.map} +1 -1
- package/dist/{chunk-pmywkp1w.js → chunk-aeh67ynz.js} +3 -3
- package/dist/{chunk-pmywkp1w.js.map → chunk-aeh67ynz.js.map} +1 -1
- package/dist/{chunk-hz6yzzbz.js → chunk-agyfv3f8.js} +1 -1
- package/dist/{chunk-tp3mzj4v.js → chunk-bra1a1fq.js} +2 -2
- package/dist/{chunk-tp3mzj4v.js.map → chunk-bra1a1fq.js.map} +1 -1
- package/dist/{chunk-583vxa2v.js → chunk-cbqazg9k.js} +2 -2
- package/dist/{chunk-583vxa2v.js.map → chunk-cbqazg9k.js.map} +1 -1
- package/dist/{chunk-m2yfvwrn.js → chunk-d2gfcf85.js} +2 -2
- package/dist/{chunk-m2yfvwrn.js.map → chunk-d2gfcf85.js.map} +1 -1
- package/dist/{chunk-4szjp84e.js → chunk-d9mar37g.js} +2 -2
- package/dist/{chunk-4szjp84e.js.map → chunk-d9mar37g.js.map} +1 -1
- package/dist/{chunk-a5sbgffr.js → chunk-e573yxpq.js} +1 -1
- package/dist/{chunk-gdmsn3f5.js → chunk-eqse2m6n.js} +2 -2
- package/dist/{chunk-gdmsn3f5.js.map → chunk-eqse2m6n.js.map} +1 -1
- package/dist/{chunk-jyrsd1dn.js → chunk-er3wf6ng.js} +2 -2
- package/dist/{chunk-jyrsd1dn.js.map → chunk-er3wf6ng.js.map} +1 -1
- package/dist/{chunk-2rphhsr7.js → chunk-fre6f4nk.js} +2 -2
- package/dist/{chunk-2rphhsr7.js.map → chunk-fre6f4nk.js.map} +1 -1
- package/dist/{chunk-1p0dazvk.js → chunk-fxgxf16k.js} +2 -2
- package/dist/{chunk-1p0dazvk.js.map → chunk-fxgxf16k.js.map} +1 -1
- package/dist/{chunk-ty4aj41k.js → chunk-gts5p6mw.js} +3 -3
- package/dist/{chunk-ty4aj41k.js.map → chunk-gts5p6mw.js.map} +1 -1
- package/dist/{chunk-rrqr1dwq.js → chunk-hdps9n52.js} +2 -2
- package/dist/{chunk-rrqr1dwq.js.map → chunk-hdps9n52.js.map} +1 -1
- package/dist/{chunk-jk97wv0q.js → chunk-jdhdrr2k.js} +2 -2
- package/dist/{chunk-jk97wv0q.js.map → chunk-jdhdrr2k.js.map} +1 -1
- package/dist/chunk-jmg2zsaf.js +5 -0
- package/dist/{chunk-fv9mr1t4.js.map → chunk-jmg2zsaf.js.map} +4 -4
- package/dist/{chunk-w2fpr99k.js → chunk-jmpw6bqz.js} +2 -2
- package/dist/{chunk-w2fpr99k.js.map → chunk-jmpw6bqz.js.map} +1 -1
- package/dist/{chunk-6h9j3f1x.js → chunk-kejwjerj.js} +2 -2
- package/dist/{chunk-6h9j3f1x.js.map → chunk-kejwjerj.js.map} +1 -1
- package/dist/{chunk-mqcy5vja.js → chunk-kqxdsv22.js} +2 -2
- package/dist/{chunk-mqcy5vja.js.map → chunk-kqxdsv22.js.map} +1 -1
- package/dist/{chunk-7rmjr8p7.js → chunk-ktr3k768.js} +2 -2
- package/dist/{chunk-7rmjr8p7.js.map → chunk-ktr3k768.js.map} +1 -1
- package/dist/{chunk-kcx468qv.js → chunk-m54s6jpr.js} +2 -2
- package/dist/{chunk-e6fp6dxx.js.map → chunk-m54s6jpr.js.map} +1 -1
- package/dist/{chunk-nek1gzz2.js → chunk-mazznq15.js} +3 -3
- package/dist/{chunk-nek1gzz2.js.map → chunk-mazznq15.js.map} +1 -1
- package/dist/{chunk-r4namj39.js → chunk-mqfzdfnz.js} +2 -2
- package/dist/{chunk-r4namj39.js.map → chunk-mqfzdfnz.js.map} +1 -1
- package/dist/chunk-ms9k0rx6.js +46 -0
- package/dist/{chunk-v9na3dny.js.map → chunk-ms9k0rx6.js.map} +5 -5
- package/dist/{chunk-hrvzchxd.js → chunk-mschc94q.js} +2 -2
- package/dist/{chunk-hrvzchxd.js.map → chunk-mschc94q.js.map} +1 -1
- package/dist/{chunk-329ggbcw.js → chunk-p91b8zcn.js} +2 -2
- package/dist/{chunk-329ggbcw.js.map → chunk-p91b8zcn.js.map} +1 -1
- package/dist/chunk-pn8v6fj2.js +14 -0
- package/dist/{chunk-0n9vs1ad.js.map → chunk-pn8v6fj2.js.map} +5 -5
- package/dist/{chunk-awp3n119.js → chunk-pyk3gzvc.js} +2 -2
- package/dist/{chunk-awp3n119.js.map → chunk-pyk3gzvc.js.map} +1 -1
- package/dist/{chunk-zns7xcz9.js → chunk-qjhw8nje.js} +1 -1
- package/dist/{chunk-5j76r5q8.js → chunk-qsrcdzan.js} +3 -3
- package/dist/{chunk-5j76r5q8.js.map → chunk-qsrcdzan.js.map} +1 -1
- package/dist/{chunk-xrh6k13s.js → chunk-sr942vb1.js} +2 -2
- package/dist/{chunk-xrh6k13s.js.map → chunk-sr942vb1.js.map} +1 -1
- package/dist/{chunk-yp5979we.js → chunk-t04f3akb.js} +2 -2
- package/dist/{chunk-yp5979we.js.map → chunk-t04f3akb.js.map} +1 -1
- package/dist/{chunk-j3nr4cg0.js → chunk-t4yh4nf9.js} +3 -3
- package/dist/{chunk-j3nr4cg0.js.map → chunk-t4yh4nf9.js.map} +1 -1
- package/dist/{chunk-8k8534kg.js → chunk-tn2bryy2.js} +2 -2
- package/dist/{chunk-8k8534kg.js.map → chunk-tn2bryy2.js.map} +1 -1
- package/dist/{chunk-q95k1ymq.js → chunk-tw5kwbx4.js} +2 -2
- package/dist/{chunk-q95k1ymq.js.map → chunk-tw5kwbx4.js.map} +1 -1
- package/dist/{chunk-kg1nbxvm.js → chunk-tzm3c7n6.js} +4 -4
- package/dist/{chunk-kg1nbxvm.js.map → chunk-tzm3c7n6.js.map} +1 -1
- package/dist/{chunk-zgn0p8qr.js → chunk-v1tfdgy1.js} +2 -2
- package/dist/{chunk-zgn0p8qr.js.map → chunk-v1tfdgy1.js.map} +1 -1
- package/dist/{chunk-e7axa0d5.js → chunk-vbdty91k.js} +3 -3
- package/dist/{chunk-e7axa0d5.js.map → chunk-vbdty91k.js.map} +1 -1
- package/dist/{chunk-e6fp6dxx.js → chunk-vw8849ys.js} +2 -2
- package/dist/{chunk-kcx468qv.js.map → chunk-vw8849ys.js.map} +1 -1
- package/dist/{chunk-y0wx6w80.js → chunk-vxm6yevm.js} +2 -2
- package/dist/{chunk-y0wx6w80.js.map → chunk-vxm6yevm.js.map} +1 -1
- package/dist/{chunk-kqb4s1r0.js → chunk-whtzggn6.js} +2 -2
- package/dist/{chunk-kqb4s1r0.js.map → chunk-whtzggn6.js.map} +1 -1
- package/dist/{chunk-3ma9m432.js → chunk-wyw6p3fg.js} +2 -2
- package/dist/{chunk-3ma9m432.js.map → chunk-wyw6p3fg.js.map} +1 -1
- package/dist/{chunk-gv91vjeb.js → chunk-x7cpth2f.js} +1 -1
- package/dist/{chunk-z32xfe8c.js → chunk-xt9tv99x.js} +2 -2
- package/dist/{chunk-z32xfe8c.js.map → chunk-xt9tv99x.js.map} +1 -1
- package/dist/{chunk-60nyk1w8.js → chunk-yf1njzd5.js} +2 -2
- package/dist/{chunk-60nyk1w8.js.map → chunk-yf1njzd5.js.map} +1 -1
- package/dist/{chunk-jv4g8grc.js → chunk-yhrye9cm.js} +2 -2
- package/dist/{chunk-jv4g8grc.js.map → chunk-yhrye9cm.js.map} +1 -1
- package/dist/{chunk-wwmdqhzy.js → chunk-zyt2w03d.js} +2 -2
- package/dist/{chunk-wwmdqhzy.js.map → chunk-zyt2w03d.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-BgLyzzOL.js → ThemeProvider-BLI4zpLu.js} +8 -3
- package/dist/chunks/ThemeProvider-BLI4zpLu.js.map +1 -0
- package/dist/client/ClientRouter.d.ts +3 -5
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/Head.d.ts +1 -1
- package/dist/client/Head.d.ts.map +1 -1
- package/dist/client/ServerDataProvider.d.ts +2 -0
- package/dist/client/ServerDataProvider.d.ts.map +1 -1
- package/dist/client/createRoot.d.ts +2 -4
- package/dist/client/createRoot.d.ts.map +1 -1
- package/dist/client/htmlAttributes.d.ts +18 -0
- package/dist/client/htmlAttributes.d.ts.map +1 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +79 -6
- package/dist/client/index.js.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/Meta.d.ts +11 -1
- package/dist/facades/Meta.d.ts.map +1 -1
- package/dist/facades/Storage.d.ts +25 -1
- package/dist/facades/Storage.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/HttpRequest.d.ts +3 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/Metadata.d.ts +23 -0
- 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/http/requestContext.d.ts +3 -0
- package/dist/http/requestContext.d.ts.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.d.ts +1 -0
- package/dist/i18n/index.d.ts.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.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/file-storage/drivers/AzureBlobDriver.d.ts +12 -1
- package/dist/services/file-storage/drivers/AzureBlobDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/FileStorageDriver.d.ts +32 -1
- package/dist/services/file-storage/drivers/FileStorageDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +22 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/S3Driver.d.ts +14 -1
- package/dist/services/file-storage/drivers/S3Driver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/types.d.ts +26 -0
- package/dist/services/file-storage/drivers/types.d.ts.map +1 -1
- package/dist/services/index.d.ts +3 -3
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +4 -4
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +19 -0
- package/dist/services/router/config.d.ts.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/testing/index.js +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-0n9vs1ad.js +0 -14
- package/dist/chunk-fakvf9wb.js +0 -5
- package/dist/chunk-fv9mr1t4.js +0 -5
- package/dist/chunk-jzp0fs6h.js +0 -5
- package/dist/chunk-v9na3dny.js +0 -46
- package/dist/chunks/ThemeProvider-BgLyzzOL.js.map +0 -1
- /package/dist/{chunk-m17ktssc.js.map → chunk-41da9628.js.map} +0 -0
- /package/dist/{chunk-hz6yzzbz.js.map → chunk-agyfv3f8.js.map} +0 -0
- /package/dist/{chunk-a5sbgffr.js.map → chunk-e573yxpq.js.map} +0 -0
- /package/dist/{chunk-zns7xcz9.js.map → chunk-qjhw8nje.js.map} +0 -0
- /package/dist/{chunk-gv91vjeb.js.map → chunk-x7cpth2f.js.map} +0 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ye as EY,df as gX}from"./chunk-whtzggn6.js";import{Wf as yX,kf as S3,pf as bZ}from"./chunk-hytt9qyj.js";import{$f as YX,Ig as o7,Jg as E$,Kg as TX,Lg as _X,Ng as HX,Xf as p8,ag as ZY,bg as JY,cg as E8,dg as _8,gg as H8,hg as x8,ig as EZ,jg as g5,kg as KX,lg as qj,mg as h,rg as f,sg as h8,tg as h$,ug as R8,vg as y3,xg as W$,yg as X0,zg as J8}from"./chunk-pn8v6fj2.js";import{Qg as RZ,Rg as y0,Sg as v1,Tg as WY}from"./chunk-15c2vgaf.js";import{Ug as A5,Vg as Q8,Wg as A}from"./chunk-49nyyjfe.js";import{Zg as MX}from"./chunk-tn2bryy2.js";import{_g as V8}from"./chunk-cbqazg9k.js";import{$g as WX,ah as F1,bh as X$,ch as kX,dh as wX,fh as Hj,gh as PX,ph as qX}from"./chunk-1myhm0g3.js";import{Eh as O$}from"./chunk-kejwjerj.js";import{Jh as ZX,Oh as Bj}from"./chunk-aazmrxj9.js";import{Vh as $X,Zh as o}from"./chunk-jmg2zsaf.js";import{_h as fZ,bi as N}from"./chunk-t4yh4nf9.js";import{ei as xX}from"./chunk-zyt2w03d.js";import{pi as zX}from"./chunk-d9mar37g.js";import{ui as U8}from"./chunk-vw8849ys.js";function R3($){return typeof $==="function"&&$.prototype!==void 0}function Q1($){return typeof $==="string"?[$]:$}function b3($,Z){let J=Z?"attachment":"inline",j=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${j}"; filename*=UTF-8''${encodeURIComponent($)}`}function oX($){return"total"in $&&"partial"in $&&"body"in $}function fj(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function wZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":x8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function aX($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(oX($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,j=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??j-1,total:j,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function S8($,Z){if($ instanceof Response)return $;if(!$)return fj();let J=await aX($),{body:j,start:Y,end:W,total:z,partial:X}=J;if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return fj()}let{range:O}=Z;if(O){if(z<=0)return wZ(Math.max(z,0));if(!X){if(j instanceof Blob){let U=_8(O,z);if(!U)return wZ(z);j=j.slice(U.start,U.end+1),Y=U.start,W=U.end,X=!0}}}let G=Boolean(O)&&X,K=G?206:J.status,Q=new Headers;if(Q.set("Accept-Ranges","bytes"),Q.set("Content-Type",J.type||"application/octet-stream"),Q.set("X-Content-Type-Options","nosniff"),G)Q.set("Content-Range",H8(Y,W,z)),Q.set("Content-Length",String(W-Y+1));else if(z>=0)Q.set("Content-Length",String(z));if(J.name)Q.set("Content-Disposition",b3(J.name,J.download));if(J.etag)Q.set("ETag",J.etag);if(J.lastModified)Q.set("Last-Modified",J.lastModified.toUTCString());for(let[U,B]of Object.entries(J.extraHeaders))Q.set(U,B);if((Z.method??"GET").toUpperCase()==="HEAD"){if(j&&"cancel"in j&&typeof j.cancel==="function")await j.cancel();return new Response(null,{status:K,headers:Q})}return new Response(j,{status:K,headers:Q})}class q$ extends y0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var Ej={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function yZ($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in Ej)))return Math.floor(Number(J[1])*(Ej[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var qZ=new WeakMap;function bj($){return qZ.has($)}function vj($){return qZ.get($)?.limit??null}function kj($){let Z=qZ.get($);return Z?Z.read>Z.limit:!1}function rX($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function f8($,Z){let J=rX($);if(J!==null&&J>Z)throw new q$(Z)}function v3($,Z,J={}){let j=qZ.get($);if(j)j.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};qZ.set($,Y),eX($,Y)}if(J.checkDeclared!==!1)f8($,Z)}function tX($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function A8($,Z){if(Z.stream!==void 0)return Z.stream;let J=tX($);if(!J)return Z.stream=null;let j;return Z.stream=new ReadableStream({async pull(Y){j??=J.getReader();let{done:W,value:z}=await j.read();if(W){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new q$(Z.limit);Y.error(X),j.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return j?j.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function w$($,Z){if(f8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=A8($,Z);if(!J)return new Uint8Array(0);let j=J.getReader(),Y=[],W=0;for(;;){let{done:O,value:G}=await j.read();if(O)break;Y.push(G),W+=G.byteLength}let z=new Uint8Array(W),X=0;for(let O of Y)z.set(O,X),X+=O.byteLength;return z}function Rj($){return $.headers.get("Content-Type")??""}function eX($,Z){let J=(j,Y)=>Object.defineProperty($,j,{configurable:!0,...Y});J("body",{get:()=>A8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>w$($,Z)}),J("arrayBuffer",{value:async()=>{let j=await w$($,Z);return j.buffer.slice(j.byteOffset,j.byteOffset+j.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await w$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await w$($,Z)))}),J("blob",{value:async()=>new Blob([await w$($,Z)],{type:Rj($)})}),J("formData",{value:async()=>new Response(await w$($,Z),{headers:{"Content-Type":Rj($)}}).formData()}),J("clone",{value:()=>{f8($,Z.limit);let j=A8($,Z),Y=null;if(j){let[W,z]=j.tee();Z.stream=W,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function wj($){return R3($)}class Z0{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!wj(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(wj(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=Q1($),this}}class yj{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=Q1($),this}async run(){let $=new f,Z=$.headers.toJSON();for(let J of qj($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(kj($.rawRequest))throw new q$(vj($.rawRequest));throw J}}}class gj{constructor(...$){return new Z0(...$)}}class mj extends Z0{__internal_brand="StreamHandler";async run($){let Z=A.getStore(),J=Z?.req?.rawRequest,j=E8(J?.headers.get("Range"));if(Z)Z.rangeRequest=j;try{let Y=await super.run($);return await S8(Y,{range:j,method:J?.method})}catch(Y){if(Y instanceof R8)return wZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class pj{constructor(...$){return new mj(...$)}}class hj{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new Z0("GET",$,"list"),post:new Z0("POST",$,"store")},this.second={get:new Z0("GET",$,"show"),put:new Z0("PUT",$,"update"),delete:new Z0("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 A0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new Z0("GET",$,Z)}post($,Z){return new Z0("POST",$,Z)}put($,Z){return new Z0("PUT",$,Z)}patch($,Z){return new Z0("PATCH",$,Z)}delete($,Z){return new Z0("DELETE",$,Z)}resource($){return new hj($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${$O($)}.`);return ZO($,this)}file($,Z){return new gj("GET",$,Z)}stream($,Z){return new pj("GET",$,Z)}proxy($,Z={}){return new yj($,Z)}}function $O($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function ZO($,Z){let J={stream:new Z0("POST",$,"stream"),attach:new Z0("POST",$,"attach"),stop:new Z0("POST",$,"stop"),upload:new Z0("POST",$,"upload")};return class extends A0{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(Y){if(Y.stream)J.stream.middleware(Y.stream);if(Y.attach)J.attach.middleware(Y.attach);if(Y.stop)J.stop.middleware(Y.stop);if(Y.upload)J.upload.middleware(Y.upload);return this}}}class b8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class v8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class cj{static __brand="McpRouter";routes={};scopes;param($){return new b8($.as,$.input,$.bind)}fromApiRoute($,Z,J){return new v8($,Z,J)}}function O0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,j)=>{let Y=j.endsWith("?")||j.endsWith("*"),W=Y?j.slice(0,-1):j,z=Z[W];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${W}`);console.error(`Missing parameter: ${W} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class k8 extends y0{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 y${static to($,...Z){let[J={}]=Z,{search:j={},params:Y={},permanent:W,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(j).toString();throw new k8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(W?301:307))}static external($,Z=307){throw new k8($,Z)}}var uj=Symbol.for("gemi.HttpResponse");class j${kind;body;status;headers;[uj]=!0;constructor($,Z,J,j){this.kind=$;this.body=Z;this.status=J;this.headers=j}static json($,Z={}){let J=Z.status??200;return JO(J),new j$("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return j$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,j=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,W)=>{if(W.toLowerCase()!=="set-cookie")J.set(W,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(j,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function JO($){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 g$($){return typeof $==="object"&&$!==null&&$[uj]===!0}function jO($,Z,J={}){return j$.error($,Z,J)}class dj{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(j)=>{return new Z()[J](j)}}}async run($,Z){let{destination:J,permanent:j=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return y$.to(J,{permanent:j,status:Y}),{}}middleware($){return this.middlewares=Q1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function w8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,j=J?$:$.file,Y=J?$.name:$.name??$.file?.name,W=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[O,G]of Object.entries($.headers??{}))Z.set(O,G);if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",W||"application/octet-stream"),j instanceof Blob)Z.set("Content-Length",String(j.size));if(Y)Z.set("Content-Disposition",b3(Y,z));return new Response(j instanceof Blob?j.stream():j,{status:X,headers:Z})}class lj{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(j)=>{return new Z()[J](j)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=Q1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function ij($,Z){if(g$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class sj{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,j]=Z;this.handler=(Y)=>{return new J()[j](Y)}}}async run($,Z){let J=ij(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=Q1($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class nj{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends R1{routes=J??{}};else if(Array.isArray(Z)){let[j,Y]=Z;this.handler=(W)=>{return new j()[Y](W)},this.children=class extends R1{routes=J??{}}}else this.children=class extends R1{routes=Z},this.handler=()=>({})}async run($,Z){let J=ij(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=Q1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class R1{middlewares=[];featureGates=[];routes={};view($,Z){return new sj($,Z)}file($){return new lj($)}redirect($){return new dj($)}layout($,Z,J){return new nj($,Z,J)}}class G0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}function YO($){return $}function WO(){return{aliases:{},global:[],bodyLimit:null}}var Y$="redirect";function m$($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let j=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${j}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function q8($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function zO($,Z=!0){let J=new URL($.rawRequest.url),j=J.pathname.replace(/\.(json|og)$/,""),[,Y,...W]=j.split("/");if(N(o).supportedLocales.includes(Y))j=`/${W.join("/")}`;return Z?`${j}${J.search}`:j}function XO($,Z){let J=(j)=>j.replace(/\/+$/,"")||"/";return J($)===J(Z)}function k3($,Z){let J=Z||N(E).config.signInPath,j=/^[a-z][a-z\d+.-]*:/i.test(J);if(j?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let W=zO($,!j);if(j||!XO(new URL(W,Y).pathname,Y.pathname))Y.searchParams.set(Y$,W)}return j?Y.href:`${Y.pathname}${Y.search}`}var b1="access_token";function y8($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function w3($,Z){let J=y8(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}class oj extends G0{async run($){let Z=A.getStore(),J=Z.req;if(Z.user)return{};let j=await w3(N(E),J);if(!j)throw new W$({redirectTo:k3(J,$)});return Z.setUser(j),{}}}class aj extends G0{async run(...$){let[Z="public",J="864000",...j]=$,Y=`${Z}, max-age=${J}${j.length>0?", ":""}${j.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var rj={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class tj extends G0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...rj,...this.config.origins[Z]};for(let[j,Y]of Object.entries(J))$.ctx().setHeaders(j,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...rj,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[j,Y]of Object.entries(J))$.ctx().setHeaders(j,Y)}return{}}}class $1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,j=Z.window??this.config.window,Y=Z.cost??1;if(ej("window",j),ej("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:j*1000,cost:Y})}}function ej($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class gZ extends y0{constructor($){super("Rate limit exceeded");let Z={"Content-Type":"application/json",...$?YY($):{}};this.payload={api:{status:429,data:{error:v1("rate_limit","Rate limit exceeded",429)},headers:Z},view:{error:{message:"Rate limit exceeded"},status:429,headers:Z}}}}class jY extends G0{async run($,Z){let J=OO();if(!J)return{};let j=await J.consume(this.key(),{limit:$Y($)??this.config.limit,window:$Y(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[W,z]of Object.entries(YY(j)))Y.setHeaders(W,z)}if(!j.allowed)throw new gZ(j);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=ZY(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${p$(this.req)}:${this.req.routePath??"*"}`}}function OO(){try{let $=N();return $.bound($1)?$.make($1):null}catch{return null}}function p$($){let Z=JY($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[j]=J.split(",");if(j?.trim())return j.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function YY($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}function $Y($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class zY extends G0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new g8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new g8;return{}}}class g8 extends y0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:WY("csrf","Invalid CSRF token",403)}},view:{}}}class q3 extends G0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return v3(this.req.rawRequest,yZ(Z)),{}}}class XY{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class OY{all($,Z){return!0}}class m8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new h$:new y3}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let j=J.get(Z);if(!j)j=this.decide($,Z),J.set(Z,j);return j}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new f,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 G0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:j})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(j!==void 0){let W=await $.body(j,Z);if(await this.authorize(Z,W),J!==void 0&&String(Y)!==String(W))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof h$:$ instanceof y3}}function GO($){return new m8($)}import{lookup as IO}from"dns/promises";import*as NO from"http";import*as LO from"https";import*as n$ from"zlib";function KO($){if($==="")return null;let Z=$.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let J=[];for(let W of Z){let z=QO(W);if(z===null)return null;J.push(z)}let j=J.pop();for(let W of J)if(W>255)return null;if(j>=256**(4-J.length))return null;let Y=j;return J.forEach((W,z)=>{Y+=W*256**(3-z)}),new Uint8Array([Math.floor(Y/16777216)&255,Math.floor(Y/65536)&255,Math.floor(Y/256)&255,Y&255])}function QO($){if($==="")return null;let Z=$,J=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),J=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),J=8;if(!(J===16?/^[0-9a-f]+$/i:J===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let Y=parseInt(Z,J);return Number.isSafeInteger(Y)?Y:null}function GY($){let Z=$;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let J=Z.indexOf("%");if(J!==-1)Z=Z.slice(0,J);if(!Z.includes(":"))return null;let j=Z.split("::");if(j.length>2)return null;let Y=(G,K)=>{if(G==="")return[];let Q=[],U=G.split(":");for(let B=0;B<U.length;B++){let F=U[B];if(K&&B===U.length-1&&F.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(F))return null;let D=F.split(".").map(Number);if(D.some((T)=>T>255))return null;Q.push(D[0]<<8|D[1],D[2]<<8|D[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(F))return null;Q.push(parseInt(F,16))}return Q},W=Y(j[0],j.length===1),z=j.length===2?Y(j[1],!0):[];if(!W||!z)return null;let X;if(j.length===2){let G=8-W.length-z.length;if(G<1)return null;X=[...W,...Array.from({length:G},()=>0),...z]}else X=W;if(X.length!==8)return null;let O=new Uint8Array(16);return X.forEach((G,K)=>{O[K*2]=G>>8,O[K*2+1]=G&255}),O}function mZ($){let Z=GY($);if(Z)return{family:6,bytes:Z};let J=KO($);if(J)return{family:4,bytes:J};return null}function z$($){if($.family===6&&UO($.bytes))return{family:4,bytes:$.bytes.slice(12)};return $}function UO($){for(let Z=0;Z<10;Z++)if($[Z]!==0)return!1;return $[10]===255&&$[11]===255}function pZ($){if($.family===4)return Array.from($.bytes).join(".");let Z=[];for(let J=0;J<16;J+=2)Z.push(($.bytes[J]<<8|$.bytes[J+1]).toString(16));return Z.join(":")}function u$($){let Z=$.lastIndexOf("/"),J=Z===-1?$:$.slice(0,Z),j=/^[0-9.]+$/.test(J)?BO(J):GY(J);if(!j)return null;let Y=z$(j.length===4?{family:4,bytes:j}:{family:6,bytes:j}),W=Y.family===4?32:128,z=W;if(Z!==-1){let X=$.slice(Z+1);if(!/^\d{1,3}$/.test(X))return null;if(z=Number(X),j.length===16&&Y.family===4)z-=96;if(z<0||z>W)return null}return{family:Y.family,bytes:Y.bytes,prefix:z}}function BO($){return/^\d{1,3}(\.\d{1,3}){3}$/.test($)&&$.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array($.split(".").map(Number)):null}function U1($,Z){let J=z$($);if(J.family!==Z.family)return!1;let j=Z.prefix;for(let Y=0;j>0;Y++){let W=Math.min(8,j),z=255<<8-W&255;if((J.bytes[Y]&z)!==(Z.bytes[Y]&z))return!1;j-=W}return!0}var k=($,Z)=>({cidr:u$($),kind:Z,text:$}),FO=[k("0.0.0.0/8","unspecified"),k("10.0.0.0/8","private"),k("100.64.0.0/10","shared"),k("127.0.0.0/8","loopback"),k("169.254.169.254/32","metadata"),k("169.254.0.0/16","link-local"),k("168.63.129.16/32","metadata"),k("172.16.0.0/12","private"),k("192.0.0.0/24","reserved"),k("192.0.2.0/24","documentation"),k("192.88.99.0/24","reserved"),k("192.168.0.0/16","private"),k("198.18.0.0/15","benchmarking"),k("198.51.100.0/24","documentation"),k("203.0.113.0/24","documentation"),k("224.0.0.0/4","multicast"),k("255.255.255.255/32","broadcast"),k("240.0.0.0/4","reserved")],DO=[k("::/128","unspecified"),k("::1/128","loopback"),k("64:ff9b:1::/48","private"),k("::/8","reserved"),k("100::/64","reserved"),k("2001:db8::/32","documentation"),k("2001::/23","reserved"),k("3fff::/20","documentation"),k("fd00:ec2::254/128","metadata"),k("fc00::/7","unique-local"),k("fe80::/10","link-local"),k("fec0::/10","private"),k("ff00::/8","multicast")],TO=u$("64:ff9b::/96"),VO=u$("2002::/16"),MO=u$("2000::/3");function c$($){let Z=typeof $==="string"?mZ($):$;if(!Z)return{kind:"reserved",range:"not an IP address"};let J=z$(Z);if(J.family===4){let Y=FO.find((W)=>U1(J,W.cidr));return Y?{kind:Y.kind,range:Y.text}:null}if(U1(J,TO))return c$({family:4,bytes:J.bytes.slice(12)});if(U1(J,VO))return c$({family:4,bytes:J.bytes.slice(2,6)});let j=DO.find((Y)=>U1(J,Y.cidr));if(j)return{kind:j.kind,range:j.text};return U1(J,MO)?null:{kind:"reserved",range:"outside 2000::/3"}}function KY($,Z){let J=z$($),j=z$(Z);return J.family===j.family&&J.bytes.every((Y,W)=>Y===j.bytes[W])}class B0 extends Error{code="safe-fetch";url;constructor($,Z,J){super($,J);this.name=new.target.name,this.url=Z}}class B1 extends B0{reason;code="invalid-url";constructor($,Z,J){super(J,$);this.reason=Z}}class d$ extends B0{host;reason;code="blocked-host";constructor($,Z,J){super(J==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,$);this.host=Z;this.reason=J}}class k1 extends B0{host;address;range;code="blocked-address";constructor($,Z,J,j){super(Z===J?`${J} is not a public address (${j}).`:`${Z} resolves to ${J}, which is not a public address (${j}).`,$);this.host=Z;this.address=J;this.range=j}}class l$ extends B0{host;code="dns";constructor($,Z,J){super(`Couldn't resolve ${Z}.`,$,{cause:J});this.host=Z}}class i$ extends B0{phase;ms;code="timeout";constructor($,Z,J){super(Z==="connect"?`Couldn't connect within ${J} ms.`:`The request didn't finish within ${J} ms.`,$);this.phase=Z;this.ms=J}}class s$ extends B0{limit;code="too-large";constructor($,Z){super(`The response is larger than ${Z} bytes.`,$);this.limit=Z}}class hZ extends B0{contentType;allowed;code="content-type";constructor($,Z,J){super(`The response is ${Z??"of no content type"}, not ${J.join(" or ")}.`,$);this.contentType=Z;this.allowed=J}}class cZ extends B0{limit;code="too-many-redirects";constructor($,Z){super(`More than ${Z} redirects.`,$);this.limit=Z}}class w1 extends B0{code="network";constructor($,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,$,{cause:Z})}}class dZ extends Response{#Y;#Z;address;constructor($,Z,J){super($,Z);this.#Y=J.url,this.#Z=J.redirected,this.address=J.address}get url(){return this.#Y}get redirected(){return this.#Z}}var uZ={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},PO=new Set([301,302,303,307,308]),CO=new Set([101,103,204,205,304]),_O=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],HO=["authorization","cookie","proxy-authorization"];async function BY($,Z={}){let J=xO(Z),j=Z.signal;j?.throwIfAborted();let Y=new AbortController,W=Y.signal,z=String($),X=(Q)=>{if(!W.aborted)Y.abort(Q)},O=setTimeout(()=>X(new i$(z,"total",J.timeout)),J.timeout),G=()=>X(j.reason);j?.addEventListener("abort",G,{once:!0});let K=()=>{clearTimeout(O),j?.removeEventListener("abort",G)};try{let Q=UY(z,J),U=(Z.method??"GET").toUpperCase(),B=new Headers(Z.headers);for(let D of _O)B.delete(D);if(!B.has("accept"))B.set("accept","*/*");if(!B.has("user-agent"))B.set("user-agent","gemi");if(!B.has("accept-encoding"))B.set("accept-encoding","gzip, deflate, br");let F=await EO(U,Z.body,B);for(let D=0;;D++){z=Q.href;let{request:T,response:V,address:P}=await RO(Q,U,B,F,J,W),M=V.statusCode??0,H=V.headers.location;if(PO.has(M)&&H&&Z.redirect!=="manual"){if(T.destroy(),D>=J.maxRedirects)throw new cZ(Q.href,J.maxRedirects);let S;try{S=new URL(H,Q)}catch{throw new B1(H,"malformed",`The redirect to "${H}" is not a URL.`)}if(M===303?U!=="HEAD":(M===301||M===302)&&U==="POST"){U="GET",F=null;let _=[];B.forEach((L,I)=>{if(I.startsWith("content-"))_.push(I)});for(let L of _)B.delete(L)}if(S.origin!==Q.origin)for(let _ of HO)B.delete(_);Q=UY(S.href,J);continue}return bO({url:Q,hop:D,method:U,request:T,response:V,address:P,policy:J,signal:W,release:K})}}catch(Q){throw K(),W.aborted?W.reason:Q}}function xO($){let Z=(j,Y)=>{let W={hosts:[],ranges:[]};for(let z of j){let X=z.includes("/")||z.includes(":")||/^[\d.]+$/.test(z),O=X?u$(z):null;if(O)W.ranges.push(O);else if(!X&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(z))W.hosts.push(FY(z));else throw TypeError(`safeFetch: "${z}" in ${Y} is not a host name or an IP range.`)}return W},J=$.allowPrivate;return{timeout:$.timeout??uZ.timeout,connectTimeout:$.connectTimeout??uZ.connectTimeout,maxSize:$.maxSize??uZ.maxSize,maxRedirects:$.maxRedirects??uZ.maxRedirects,ports:$.ports??uZ.ports,allow:$.allow&&$.allow.length>0?Z($.allow,"allow"):null,deny:Z($.deny??[],"deny"),allowPrivate:J===!0?!0:Z(J||[],"allowPrivate").ranges,contentTypes:$.contentTypes?.length?$.contentTypes:null,resolve:$.resolve??SO}}async function SO($){return(await IO($,{all:!0,verbatim:!0})).map((J)=>J.address)}function FY($){return $.toLowerCase().replace(/\.$/,"")}function QY($,Z){return Z.some((J)=>J.startsWith("*.")?$.endsWith(J.slice(1)):$===J)}function UY($,Z){let J;try{J=new URL($)}catch{throw new B1($,"malformed",`"${$}" is not a URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new B1(J.href,"scheme",`Only http and https URLs can be fetched, not ${J.protocol.slice(0,-1)}.`);if(J.username||J.password)throw new B1(J.href,"credentials","The URL has a username or password in it.");let j=DY(J);if(Z.ports!=="any"&&!Z.ports.includes(j))throw new B1(J.href,"port",`Port ${j} is not allowed.`);return J}function DY($){return $.port?Number($.port):$.protocol==="https:"?443:80}async function AO($,Z,J){let j=FY($.hostname.replace(/^\[(.*)\]$/,"$1")),Y=mZ(j),W=Y!==null&&(j.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(j));if(!W&&QY(j,Z.deny.hosts))throw new d$($.href,j,"denied");let z=!W&&Z.allow!==null&&QY(j,Z.allow.hosts);if(Z.allow&&!z&&Z.allow.ranges.length===0)throw new d$($.href,j,"not-allowed");let X;if(W)X=[Y];else{let O;try{O=await fO(Z.resolve(j),J)}catch(G){if(J.aborted)throw J.reason;throw new l$($.href,j,G)}if(X=O.map((G)=>mZ(G)).filter((G)=>G!==null),X.length===0)throw new l$($.href,j)}for(let O of X){let G=pZ(O);if(Z.deny.ranges.some((Q)=>U1(O,Q)))throw new k1($.href,j,G,"denied");if(Z.allow&&!z&&!Z.allow.ranges.some((Q)=>U1(O,Q)))throw new k1($.href,j,G,"not-allowed");let K=c$(O);if(K&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((Q)=>U1(O,Q)))throw new k1($.href,j,G,K.kind)}return{host:j,addresses:X,isLiteral:W}}function fO($,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise((J,j)=>{let Y=()=>j(Z.reason);Z.addEventListener("abort",Y,{once:!0}),$.then((W)=>{Z.removeEventListener("abort",Y),J(W)},(W)=>{Z.removeEventListener("abort",Y),j(W)})})}async function EO($,Z,J){if(Z===void 0||Z===null)return null;if($==="GET"||$==="HEAD")throw TypeError(`safeFetch: a ${$} request can't have a body.`);let j=new Request("http://body.invalid/",{method:"POST",body:Z}),Y=j.headers.get("content-type");if(Y&&!J.has("content-type"))J.set("content-type",Y);return new Uint8Array(await j.arrayBuffer())}async function RO($,Z,J,j,Y,W){let z=new AbortController,X=setTimeout(()=>z.abort(new i$($.href,"connect",Y.connectTimeout)),Y.connectTimeout),O=AbortSignal.any([W,z.signal]);try{let{host:G,addresses:K,isLiteral:Q}=await AO($,Y,O),U=$.protocol==="https:",B={};if(J.forEach((F,D)=>{B[D]=F}),j)B["content-length"]=String(j.byteLength);return await new Promise((F,D)=>{let T={method:Z,host:G,port:DY($),path:`${$.pathname}${$.search}`,headers:B,agent:!1,lookup:(_,L,I)=>{let C=L?.family,b=K.filter((m)=>!C||m.family===C);if(b.length===0)I(Object.assign(Error(`No IPv${C} address for ${G}`),{code:"ENOTFOUND"}));else if(L?.all)I(null,b.map((m)=>({address:pZ(m),family:m.family})));else I(null,pZ(b[0]),b[0].family)}};if(U&&!Q)T.servername=G;let V=(U?LO:NO).request(T),P=null,M=(_)=>{O.removeEventListener("abort",H),V.destroy(),D(_)},H=()=>M(O.aborted?O.reason:W.reason);O.addEventListener("abort",H,{once:!0});let S=(_)=>{let L=_?.remoteAddress;if(!L||P!==null)return!0;let I=mZ(L);if(!I||!K.some((C)=>KY(C,I)))return M(new k1($.href,G,L,"not-allowed")),!1;return P=pZ(z$(I)),!0};V.once("socket",(_)=>{let L=()=>{if(S(_)&&!U)clearTimeout(X)};if(_.connecting)_.once("connect",L);else L();if(U)_.once("secureConnect",()=>clearTimeout(X))}),V.once("response",(_)=>{if(clearTimeout(X),_.on("error",()=>{}),!S(_.socket))return;O.removeEventListener("abort",H),F({request:V,response:_,address:P})}),V.on("error",(_)=>{if(O.aborted)return M(O.reason);M(_ instanceof B0?_:new w1($.href,_))}),V.end(j??void 0)})}finally{clearTimeout(X)}}function bO({url:$,hop:Z,method:J,request:j,response:Y,address:W,policy:z,signal:X,release:O}){let G=Y.statusCode??0;if(G<200||G>599)throw j.destroy(),new w1($.href,Error(`Unexpected status ${G}`));let K=new Headers,Q=Y.rawHeaders;for(let L=0;L<Q.length;L+=2)K.append(Q[L],Q[L+1]);if(z.contentTypes){let L=K.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!L||!z.contentTypes.some((I)=>vO(L,I)))throw j.destroy(),new hZ($.href,L,z.contentTypes)}let U={url:$.href,redirected:Z>0,address:W},B={status:G,statusText:Y.statusMessage??"",headers:K};if(J==="HEAD"||CO.has(G))return j.destroy(),O(),new dZ(null,B,U);let F=K.get("content-encoding")?.trim().toLowerCase(),D=F==="gzip"||F==="x-gzip"?n$.createGunzip():F==="deflate"?n$.createInflate():F==="br"?n$.createBrotliDecompress():null,T=Number(K.get("content-length"));if(!D&&Number.isFinite(T)&&T>z.maxSize)throw j.destroy(),new s$($.href,z.maxSize);if(D)K.delete("content-encoding"),K.delete("content-length");let V=D?Y.pipe(D):Y,P=0,M=!1,H=()=>{},S=()=>{M=!0,X.removeEventListener("abort",H),O()},_=new ReadableStream({start(L){let I=(b)=>{if(M)return;if(S(),b===void 0)L.close();else j.destroy(),D?.destroy(),L.error(b)};if(H=()=>I(X.reason),X.addEventListener("abort",H,{once:!0}),X.aborted)return H();V.on("data",(b)=>{if(M)return;if(P+=b.byteLength,P>z.maxSize)return I(new s$($.href,z.maxSize));if(L.enqueue(new Uint8Array(b)),(L.desiredSize??1)<=0)V.pause()}),V.once("end",()=>I());let C=(b)=>I(b instanceof B0?b:new w1($.href,b));if(V.on("error",C),D)Y.on("error",C);Y.once("aborted",()=>I(new w1($.href,Error("The response was cut off."))))},pull(){V.resume()},cancel(){if(M)return;S(),j.destroy(),D?.destroy()}});return new dZ(_,B,U)}function vO($,Z){let J=Z.toLowerCase();return J.endsWith("/*")?$.startsWith(J.slice(0,-1)):$===J}import{createHmac as TY,randomBytes as kO}from"crypto";var c8="v2.";function u8($){return $.startsWith(c8)}function o$(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function VY($){let Z=kO(16).toString("hex"),J=TY("sha256",o$()).update(`${$}:${Z}`).digest("hex");return`${c8}${J}`}function g3($,Z){let J=TY("sha256",o$()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${c8}${J}`}import{createHash as yO,createHmac as gO,randomInt as mO,timingSafeEqual as NY}from"crypto";function MY($,Z){return Math.floor($/Z)*Z}function wO($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function d8($,Z,J,j){return Z*wO(J,j)+$}function qO($){let{current:Z,previous:J,elapsed:j,window:Y,limit:W,cost:z}=$,X=W-z;if(X<0)return Y;let O=Math.max(0,Y-j);if(J>0){let K=Y*(1-(X-Z)/J);if(K<=Y)return Math.max(0,Math.ceil(K-j))}if(Z<=X)return O;if(Z<=0)return O;let G=Y*(1-X/Z);return O+Math.max(0,Math.ceil(G))}function IY($){let{allowed:Z,current:J,previous:j,now:Y,elapsed:W,window:z,limit:X,cost:O}=$;if(Z){let K=d8(J,j,W,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-K)),resetAt:Y-W+z,retryAfter:0}}let G=qO({current:J,previous:j,elapsed:W,window:z,limit:X,cost:O});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class l8{}class i8 extends l8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:j}=$,Y=$.cost??1,W=Date.now(),z=MY(W,j),X=W-z,O=this.roll(Z,j,z);O.limit=J;let K=d8(O.current,O.previous,X,j)+Y<=J;if(K)O.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,O),this.buckets.size>this.maxKeys)this.evict(W);return IY({allowed:K,current:O.current,previous:O.previous,now:W,elapsed:X,window:j,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let j=this.buckets.get($);if(!j||j.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(j.windowStart===J)return j;if(j.windowStart+Z===J)return j.previous=j.current,j.current=0,j.windowStart=J,j;return j.previous=0,j.current=0,j.windowStart=J,j}evict($){for(let[j,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(j);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([j,Y],W)=>({key:j,order:W,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((j,Y)=>j.spent-Y.spent||j.order-Y.order);for(let{key:j}of J){if(this.buckets.size<=Z)break;this.buckets.delete(j)}}}var CY="h1.";function m3($,Z,J){let j=gO("sha256",o$()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${CY}${j}`}function lZ($,Z,J,j){let Y=typeof j==="string"?j:"",W=typeof J==="string"?J:"",z=W.startsWith(CY),X=m3($,Z,Y),O=Buffer.from(z?X:Y),G=Buffer.from(W);if(O.length!==G.length||Y===""||W==="")return NY(O,O),!1;return NY(O,G)}function _Y($){let Z="";for(let J=0;J<$;J++)Z+=String(mO(0,10));return Z}var HY=320;function iZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>HY)return null;return Z.toLowerCase()}function p3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>HY)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var LY=null;function xY(){try{let $=N();if(typeof $?.bound==="function"&&$.bound($1))return $.make($1)}catch{}return LY??=new $1({driver:new i8,limit:1000,window:60}),LY}function PY($){return $.length<=64?$:`sha256:${yO("sha256").update($).digest("hex")}`}async function a$($,Z,J,j){let Y=xY(),W=[[`auth:code-${$}:ip:${PY(p$(J))}`,j.perIp]];if(Z!==null)W.push([`auth:code-${$}:email:${PY(Z)}`,j.perEmail]);for(let[z,X]of W){if(!X)continue;let[O,G]=X,K=await Y.consume(z,{limit:O,window:G});if(!K.allowed)throw new gZ(K)}}async function SY($,Z,J,j=10){let Y=Math.max(86400,Math.ceil(j*60*(J+1)));return(await xY().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as n8}from"crypto";class s8 extends f{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 h3($,Z,J,j=1/0){if(!Number.isInteger(Z)||Z<J||Z>j){let Y=j===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${j}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function o8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,j=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5;return h3("length",Z,4,12),h3("expiresInMinutes",J,1),h3("linkExpiresInMinutes",j,1),h3("maxAttempts",Y,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:j,maxAttempts:Y,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:W,code:z})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${W}: ${z} (set auth.emailCode.send to deliver it)`)})}}async function pO($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function ED($){return $}function AY($={}){return{basePath:"/auth",verifyEmail:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:s8,oauthProviders:{},oauthFailurePath:null,verifyPassword:pO,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>n8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return n8(32).toString("hex")},generateMagicLinkToken:()=>n8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:o8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}function a8($){if($&&typeof $==="object")delete $.password;return $}function hO(){return new Proxy({},{get:($,Z)=>EY(Z)})}var fY=new WeakMap;function RY($){if($&&typeof $==="object"){for(let Z of Object.values($))RY(Z);Object.freeze($)}return $}var cO={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},uO=RY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:cO});class r8{models;constructor($=hO()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return uO}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??X$(),j=N(O$).connection(J),Y=()=>this.transaction(async()=>{if(j.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await F1()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(j.dialect!=="sqlite"||F1())return Y();let z=(fY.get(j)??Promise.resolve()).then(Y,Y);return fY.set(j,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return a8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return a8(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?a8(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as vQ}from"crypto";function f0($,Z,J,j,Y){return h0(Z,sY($,Z),J,j,Y)}function h0($,Z,J,j,Y,W){let z=J2(Z,J,j);if(Y&&Z!==z)throw RangeError(Ez($,Z,J,j,W));return z}function sY($,Z){let J=$[Z];if(J===void 0)throw TypeError(RJ(Z));return J}function Q0($){return $!==null&&/object|function/.test(typeof $)}function b0($,Z=Map){let J=new Z;return(j,...Y)=>{if(J.has(j))return J.get(j);let W=$(j,...Y);return J.set(j,W),W}}function K2($){return U$({name:$},1)}function U$($,Z){return l0((J)=>({value:J,configurable:1,writable:!Z}),$)}function nY($){return l0((Z)=>({get:Z,configurable:1}),$)}function j6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function jZ($,Z){let J={},j=$.length;for(let Y of Z)J[$[--j]]=Y;return J}function l0($,Z,J){let j={};for(let Y in Z)j[Y]=$(Z[Y],Y,J);return j}function Z3($,Z,J){let j={};for(let Y=0;Y<Z.length;Y++){let W=Z[Y];j[W]=$(W,Y,J)}return j}function dO($,Z,J){let j={};for(let Y=0;Y<$.length;Y++)j[Z[Y]]=J[$[Y]];return j}function k0($,Z){let J={};for(let j of $)J[j]=Z[j];return J}function Q2($,Z){let J={};for(let j in Z)$.has(j)||(J[j]=Z[j]);return J}function U2($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function oY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function aY($,Z,J){for(let j of $)if(Z[j]!==J[j])return 0;return 1}function rY($,Z,J){let j={...J};for(let Y=0;Y<Z;Y++)j[$[Y]]=0;return j}function v($,...Z){return(...J)=>$(...Z,...J)}function bY($){return $[0].toUpperCase()+$.substring(1)}function J3($){return $.slice().sort()}function n3($,Z){return String(Z).padStart($,"0")}function q1($,Z){return Math.sign($-Z)}function J2($,Z,J){return Math.min(Math.max($,Z),J)}function T1($,Z){return[Math.floor($/Z),nZ($,Z)]}function nZ($,Z){return($%Z+Z)%Z}function m1($,Z){return[Y6($,Z),B2($,Z)]}function Y6($,Z){return Math.trunc($/Z)||0}function B2($,Z){return $%Z||0}function c3($){return Math.abs($%1)===0.5}function tY($,Z,J){let j=0,Y=0;for(let X=0;X<=Z;X++){let O=$[J[X]],G=J1[X],K=c/G,[Q,U]=m1(O,K);j+=U*G,Y+=Q}let[W,z]=m1(j,c);return[Y+W,z]}function W6($,Z,J){let j={};for(let Y=Z;Y>=0;Y--){let W=J1[Y];j[J[Y]]=Y6($,W),$=B2($,W)}return j}function eY($){return $===w?m6:[]}function $W($){return $===w?U3:[]}function ZW($){return $===w?["year","day"]:[]}function JW($){if($!==void 0)return a($)}function jW($){if($!==void 0)return i0($)}function F2($){if($!==void 0)return j3($)}function i0($){return zW(j3($))}function j3($){return WW(wG($))}function D2($){if($==null)throw TypeError("Cannot be null or undefined");return $}function YW($,Z){if(Z==null)throw RangeError(RJ($));return Z}function M1($){if(!Q0($))throw TypeError(fz);return $}function z6($,Z,J=$){if(typeof Z!==$)throw TypeError(G3(J,Z));return Z}function WW($,Z="number"){if(!Number.isInteger($))throw RangeError(zG(Z,$));return $||0}function zW($,Z="number"){if($<=0)throw RangeError(XG(Z,$));return $}function T2($){if(typeof $=="symbol")throw TypeError(QG);return String($)}function o3($,Z){return Q0($)?String($):a($,Z)}function X6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(KG($));return $}function XW($,Z="number"){if(typeof $=="bigint")throw TypeError(GG(Z));if($=Number($),!Number.isFinite($))throw RangeError(OG(Z,$));return $}function N0($,Z){return Math.trunc(XW($,Z))||0}function OW($,Z){return WW(XW($,Z),Z)}function vY($,Z){return zW(N0($,Z),Z)}function V2($,Z){let[J,j]=m1(Z,c),Y=$+J,W=Math.sign(Y);return W&&W===-Math.sign(j)&&(Y-=W,j+=W*c),[Y,j]}function t$($,Z,J=1){return V2($[0]+Z[0]*J,$[1]+Z[1]*J)}function e$($,Z){return V2($[0],$[1]+Z)}function g0($,Z){return t$(Z,$,-1)}function P0($,Z){return q1($[0],Z[0])||q1($[1],Z[1])}function GW($,Z,J){return P0($,Z)===-1||P0($,J)===1}function O6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function $Z($,Z=1){let J=c/Z,[j,Y]=m1($,J);return[j,Y*Z]}function KW($,Z=1){let[J,j]=$,Y=Math.floor(j/Z),W=c/Z;return BigInt(J)*BigInt(W)+BigInt(Y)}function m0($,Z=1,J){let[j,Y]=$,[W,z]=m1(Y,Z);return j*(c/Z)+(W+(J?z/Z:0))}function M2($,Z,J=T1){let[j,Y]=$,[W,z]=J(Y,Z);return[j*(c/Z)+W,z]}function I2($,Z){let J=$.formatToParts(Z),j={};for(let Y of J)j[Y.type]=Y.value;return j}function N2($){return f0($,"isoYear",$3,eZ,1),$.isoYear===$3?f0($,"isoMonth",4,12,1):$.isoYear===eZ&&f0($,"isoMonth",1,9,1),$}function y1($){return I1({...$,...d0,isoHour:12}),$}function I1($){let Z=f0($,"isoYear",$3,eZ,1),J=Z===$3?1:Z===eZ?-1:0;return J&&p0(L0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function p0($){if(!$||GW($,cG,hG))throw RangeError(w6);return $}function p1($){return tY($,5,a0)[1]}function G6($){let[Z,J]=T1($,c);return[W6(J,5,a0),Z]}function QW($){return UW($)[0]}function UW($){return M2($,u0)}function C0($){return YZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function L0($){let Z=C0($);if(Z!==void 0){let[J,j]=m1(Z,R0);return[J,j*j1+($.isoMicrosecond||0)*L$+($.isoNanosecond||0)]}}function L2($,Z){let[J,j]=G6(p1($)-Z);return p0(L0({...$,isoDay:$.isoDay+j,...J}))}function a3(...$){return YZ(...$)/hz}function YZ(...$){let[Z,J]=BW(...$),j=Z.valueOf();if(!isNaN(j))return j-J*R0}function BW($,Z=1,J=1,j=0,Y=0,W=0,z=0){let X=$===$3?1:$===eZ?-1:0,O=new Date;return O.setUTCHours(j,Y,W,z),O.setUTCFullYear($,Z-1,J+X),[O,X]}function c1($,Z){let[J,j]=e$($,Z);j<0&&(j+=c,J-=1);let[Y,W]=T1(j,j1),[z,X]=T1(W,L$);return K6(J*R0+Y,z,X)}function K6($,Z=0,J=0){let j=Math.ceil(Math.max(0,Math.abs($)-pG)/R0)*Math.sign($),Y=new Date($-j*R0);return jZ(h6,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+j,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function FW($){return[$.isoYear,$.isoMonth,$.isoDay]}function DW(){return D1}function P2($,Z){switch(Z){case 2:return C2($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function TW($){return C2($)?366:365}function C2($){return $%4==0&&($%100!=0||$%400==0)}function VW($){let[Z,J]=BW($.isoYear,$.isoMonth,$.isoDay);return nZ(Z.getUTCDay()-J,7)||7}function MW({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function lO($){let Z=C0($);if(Z<dG)return MW($);let J=I2(oJ(ZZ),Z),{era:j,eraYear:Y}=f9(J,ZZ);return[j,Y]}function Q6($){return B$($),U6($,1),$}function B$($){return IW($,1),$}function kY($){return aY(hJ,$,IW($))}function IW($,Z){let{isoYear:J}=$,j=f0($,"isoMonth",1,DW(),Z);return{isoYear:J,isoMonth:j,isoDay:f0($,"isoDay",1,P2(J,j),Z)}}function U6($,Z){return jZ(a0,[f0($,"isoHour",0,23,Z),f0($,"isoMinute",0,59,Z),f0($,"isoSecond",0,59,Z),f0($,"isoMillisecond",0,999,Z),f0($,"isoMicrosecond",0,999,Z),f0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:Y7(M1($))}function Y3($,Z=0){$=s0($);let J=W7($),j=$K($,Z);return[Y7($),j,J]}function _2($){return W7(s0($))}function NW($){return $=s0($),dJ($,9,6,1)}function WZ($,Z,J,j=9,Y=0,W=4){Z=s0(Z);let z=dJ(Z,j,Y),X=S2(Z),O=F3(Z,W),G=B3(Z,j,Y,1);return z==null?z=Math.max(J,G):_W(z,G),X=A2(X,G,1),$&&(O=((K)=>K<4?(K+2)%4:K)(O)),[z,G,X,O]}function B6($,Z=6,J){let j=S2($=f2($,J6)),Y=F3($,7),W=B3($,Z);return W=YW(J6,W),j=A2(j,W,void 0,J),[W,j,Y]}function H2($){return lJ(s0($))}function LW($,Z){return x2(s0($),Z)}function x2($,Z=4){let J=CW($);return[F3($,4),...PW(B3($,Z),J)]}function PW($,Z){return $!=null?[J1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function S2($){let Z=$[oZ];return Z===void 0?1:N0(Z,oZ)}function A2($,Z,J,j){let Y=j?c:J1[Z+1];if(Y){let W=J1[Z];if(Y%(($=h0(oZ,$,1,Y/W-(j?0:1),1))*W))throw RangeError(G3(oZ,$))}else $=h0(oZ,$,1,J?1e9:1,1);return $}function CW($){let Z=$[Z2];if(Z!==void 0){if(typeof Z!="number"){if(T2(Z)==="auto")return;throw RangeError(G3(Z2,Z))}Z=h0(Z2,Math.floor(Z),0,9,1)}return Z}function s0($){return $===void 0?{}:M1($)}function f2($,Z){return typeof $=="string"?{[Z]:$}:M1($)}function J0($){if($!==void 0){if(Q0($))return Object.assign(Object.create(null),$);throw TypeError(fz)}}function F6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:iG[Z]})}function E2($,Z,J=9,j=0,Y){let W=Z[$];if(W===void 0)return Y?j:void 0;if(W=T2(W),W==="auto")return Y?j:null;let z=z2[W];if(z===void 0&&(z=gG[W]),z===void 0)throw RangeError(vz($,W,z2));return h0($,z,j,J,1,Q3),z}function F$($,Z,J,j=0){let Y=J[$];if(Y===void 0)return j;let W=T2(Y),z=Z[W];if(z===void 0)throw RangeError(vz($,W,Z));return z}function _W($,Z){if(Z>$)throw RangeError(EG)}function U0($){return{branding:u6,epochNanoseconds:$}}function T0($,Z,J){return{branding:C1,calendar:J,timeZone:Z,epochNanoseconds:$}}function j0($,Z=$.calendar){return{branding:C$,calendar:Z,...k0($7,$)}}function Y0($,Z=$.calendar){return{branding:P$,calendar:Z,...k0(cJ,$)}}function K$($,Z=$.calendar){return{branding:BZ,calendar:Z,...k0(cJ,$)}}function r3($,Z=$.calendar){return{branding:FZ,calendar:Z,...k0(cJ,$)}}function n0($){return{branding:c6,...k0(ez,$)}}function i($){return{branding:d6,sign:u1($),...k0(gJ,$)}}function HW($){return QW($.epochNanoseconds)}function D6($){return M2($.epochNanoseconds,j1)[0]}function xW($){return KW($.epochNanoseconds,L$)}function SW($){return KW($.epochNanoseconds)}function AW($){return $.epochNanoseconds}function F0($){return typeof $=="string"?$:a($.id)}function zZ($,Z){return $===Z||F0($)===F0(Z)}function fW($,Z,J,j,Y){let W=Q$(j),[z,X]=((T,V)=>{let P=V((T=f2(T,G2))[J7]),M=eG(T);return M=YW(G2,M),[M,P]})(Y,$);if(rZ(Math.max(z,W),X))return wY(j,z);if(!X)throw RangeError(q6);let[O,G,K]=L6(Z,J,X),Q=$J(K),U=P6(K),B=ZJ(K),F=U(G,O,j),D=B(G,O,F,z);return rZ(z,X)?wY(D,z):((T,V,P,M,H,S,_)=>{let L=u1(T),[I,C]=R2(M,pJ(P,T),P,L,H,S,_),b=b2(V,I,C);return T[g[P]]+b*L})(D,Q(F),z,G,O,Q,U)}function wY($,Z){return m0(K0($),J1[Z],1)}function R2($,Z,J,j,Y,W,z){let X=g[J],O={...Z,[X]:Z[X]+j},G=z($,Y,Z),K=z($,Y,O);return[W(G),W(K)]}function b2($,Z,J){let j=m0(g0(Z,J));if(!j)throw RangeError(K3);return m0(g0(Z,$))/j}function EW($,Z){let[J,j,Y]=B6(Z,5,1);return U0(V6($.epochNanoseconds,J,j,Y,1))}function RW($,Z,J){let{epochNanoseconds:j,timeZone:Y,calendar:W}=Z,[z,X,O]=B6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)j=((K,Q,U,B)=>{let F=_0(U,Q),[D,T]=K(F),V=U.epochNanoseconds,P=v0(Q,D),M=v0(Q,T);if(GW(V,P,M))throw RangeError(K3);return pW(b2(V,P,M),B)?M:P})(gW,G,Z,O);else{let K=G.getOffsetNanosecondsFor(j);j=T$(G,qW(c1(j,K),z,X,O),K,2,0,1)}return T0(j,Y,W)}function bW($,Z){return j0(qW($,...B6(Z)),$.calendar)}function vW($,Z){let[J,j,Y]=B6(Z,5);var W;return n0((W=Y,v2($,W3(J,j),W)[0]))}function kW($,Z){let J=$(Z.timeZone),j=_0(Z,J),[Y,W]=gW(j),z=m0(g0(v0(J,Y),v0(J,W)),g6,1);if(z<=0)throw RangeError(K3);return z}function wW($,Z){let{timeZone:J,calendar:j}=Z,Y=((W,z,X)=>v0(z,W(_0(X,z))))(mW,$(J),Z);return T0(Y,J,j)}function qW($,Z,J,j){return yW($,W3(Z,J),j)}function yW($,Z,J){let[j,Y]=v2($,Z,J);return I1({...V$($,Y),...j})}function v2($,Z,J){return G6(h1(p1($),Z,J))}function t3($){return h1($,y6,7)}function W3($,Z){return J1[$]*Z}function gW($){let Z=mW($);return[Z,V$(Z,1)]}function mW($){return mG(6,$)}function iO($,Z,J){let j=Math.min(Q$($),6);return OZ(M6(K0($,j),Z,J),j)}function T6($,Z,J,j,Y,W,z,X,O,G){if(j===0&&Y===1)return $;let K=rZ(j,X)?C6(X)&&j<6&&J>=6?nO:sO:oO,[Q,U,B]=K($,Z,J,j,Y,W,z,X,O,G);return B&&j!==7&&(Q=((F,D,T,V,P,M,H,S)=>{let _=u1(F);for(let L=V+1;L<=T;L++){if(L===7&&T!==7)continue;let I=pJ(L,F);I[g[L]]+=_;let C=m0(g0(H(S(P,M,I)),D));if(C&&Math.sign(C)!==_)break;F=I}return F})(Q,U,J,Math.max(6,j),z,X,O,G)),Q}function V6($,Z,J,j,Y){if(Z===6){let W=((z)=>z[0]+z[1]/c)($);return[h1(W,J,j),0]}return M6($,W3(Z,J),j,Y)}function M6($,Z,J,j){let[Y,W]=$;j&&W<0&&(W+=c,Y-=1);let[z,X]=T1(h1(W,Z,J),c);return V2(Y+z,X)}function h1($,Z,J){return pW($/Z,J)*Z}function pW($,Z){return jK[Z]($)}function sO($,Z,J,j,Y,W){let z=u1($),X=K0($),O=V6(X,j,Y,W),G=g0(X,O),K=Math.sign(O[0]-X[0])===z,Q=OZ(O,Math.min(J,6));return[{...$,...Q},t$(Z,G),K]}function nO($,Z,J,j,Y,W,z,X,O,G){let K=u1($),Q=m0(K0($,5)),U=W3(j,Y),B=h1(Q,U,W),[F,D]=R2(z,{...$,...mJ},6,K,X,O,G),T=B-m0(g0(F,D)),V=0;T&&Math.sign(T)!==K?Z=e$(F,B):(V+=K,B=h1(T,U,W),Z=e$(D,B));let P=H6(B);return[{...$,...P,days:$.days+V},Z,Boolean(V)]}function oO($,Z,J,j,Y,W,z,X,O,G){let K=u1($),Q=g[j],U=pJ(j,$);j===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let B=Y6($[Q],Y)*Y;U[Q]=B;let[F,D]=R2(z,U,j,Y*K,X,O,G),T=B+b2(Z,F,D)*K*Y,V=h1(T,Y,W),P=Math.sign(V-T)===K;return U[Q]=V,[U,P?D:F,P]}function k2($,Z,J,j){let[Y,W,z,X]=((G)=>{let K=x2(G=s0(G));return[G.timeZone,...K]})(j),O=Y!==void 0;return((G,K,Q,U,B,F)=>{Q=M6(Q,B,U,1);let D=K.getOffsetNanosecondsFor(Q);return h2(c1(Q,D),F)+(G?D$(t3(D)):"Z")})(O,Z(O?$(Y):_$),J.epochNanoseconds,W,z,X)}function w2($,Z,J){let[j,Y,W,z,X,O]=((G)=>{G=s0(G);let K=lJ(G),Q=CW(G),U=JK(G),B=F3(G,4),F=B3(G,4);return[K,ZK(G),U,B,...PW(F,Q)]})(J);return((G,K,Q,U,B,F,D,T,V,P)=>{U=M6(U,V,T,1);let M=G(Q).getOffsetNanosecondsFor(U);return h2(c1(U,M),P)+D$(t3(M),D)+((H,S)=>S!==1?"["+(S===2?"!":"")+F0(H)+"]":"")(Q,F)+c2(K,B)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,j,Y,W,z,X,O)}function q2($,Z){let[J,j,Y,W]=((G)=>(G=s0(G),[lJ(G),...x2(G)]))(Z);return z=$.calendar,X=J,O=W,h2(yW($,Y,j),O)+c2(z,X);var z,X,O}function y2($,Z){return J=$.calendar,j=$,Y=H2(Z),e3(j)+c2(J,Y);var J,j,Y}function g2($,Z){return hW($.calendar,cW,$,H2(Z))}function m2($,Z){return hW($.calendar,aO,$,H2(Z))}function p2($,Z){let[J,j,Y]=LW(Z);return W=Y,uW(v2($,j,J)[0],W);var W}function I6($,Z){let[J,j,Y]=LW(Z,3);return j>1&&($={...$,...iO($,j,J)}),((W,z)=>{let{sign:X}=W,O=X===-1?H0(W):W,{hours:G,minutes:K}=O,[Q,U]=M2(K0(O,3),u0,m1);rW(Q);let B=u2(U,z),F=z>=0||!X||B;return(X<0?"-":"")+"P"+qY({Y:G$(O.years),M:G$(O.months),W:G$(O.weeks),D:G$(O.days)})+(G||K||Q||F?"T"+qY({H:G$(G),M:G$(K),S:G$(Q,F)+B}):"")})($,Y)}function hW($,Z,J,j){let Y=F0($),W=j>1||j===0&&Y!==w;return j===1?Y===w?Z(J):e3(J):W?e3(J)+dW(Y,j===2):Z(J)}function qY($){let Z=[];for(let J in $){let j=$[J];j&&Z.push(j,J)}return Z.join("")}function h2($,Z){return e3($)+"T"+uW($,Z)}function e3($){return cW($)+"-"+c0($.isoDay)}function cW($){let{isoYear:Z}=$;return(Z<0||Z>9999?lW(Z)+n3(6,Math.abs(Z)):n3(4,Z))+"-"+c0($.isoMonth)}function aO($){return c0($.isoMonth)+"-"+c0($.isoDay)}function uW($,Z){let J=[c0($.isoHour),c0($.isoMinute)];return Z!==-1&&J.push(c0($.isoSecond)+((j,Y,W,z)=>u2(j*j1+Y*L$+W,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function D$($,Z=0){if(Z===1)return"";let[J,j]=T1(Math.abs($),g6),[Y,W]=T1(j,y6),[z,X]=T1(W,u0);return lW($)+c0(J)+":"+c0(Y)+(z||X?":"+c0(z)+u2(X):"")}function c2($,Z){if(Z!==1){let J=F0($);if(Z>1||Z===0&&J!==w)return dW(J,Z===2)}return""}function dW($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function u2($,Z){let J=n3(9,$);return J=Z===void 0?J.replace(zK,""):J.slice(0,Z),J?"."+J:""}function lW($){return $<0?"-":"+"}function G$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function rO($,Z){let{epochNanoseconds:J}=$,j=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=c1(J,j);return{calendar:$.calendar,...Y,offsetNanoseconds:j}}function iW($,Z){let J=_0(Z,$);return{calendar:Z.calendar,...k0($7,J),offset:D$(J.offsetNanoseconds),timeZone:Z.timeZone}}function T$($,Z,J,j=0,Y=0,W,z){if(J!==void 0&&j===1&&(j===1||z))return L2(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&j!==3){let O=((G,K,Q,U)=>{let B=L0(K);U&&(Q=t3(Q));for(let F of G){let D=m0(g0(F,B));if(U&&(D=t3(D)),D===Q)return F}})(X,Z,J,W);if(O!==void 0)return O;if(j===0)throw RangeError(_G)}return z?L0(Z):v0($,Z,Y,X)}function v0($,Z,J=0,j=$.getPossibleInstantsFor(Z)){if(j.length===1)return j[0];if(J===1)throw RangeError(HG);if(j.length)return j[J===3?1:0];let Y=L0(Z),W=((X,O)=>{let G=X.getOffsetNanosecondsFor(e$(O,-c));return l2(X.getOffsetNanosecondsFor(e$(O,c))-G)})($,Y),z=W*(J===2?-1:1);return(j=$.getPossibleInstantsFor(c1(Y,z)))[J===2?0:j.length-1]}function d2($){if(Math.abs($)>=c)throw RangeError(PG);return $}function l2($){if($>c)throw RangeError(CG);return $}function i2($,Z,J){return U0(p0(t$(Z.epochNanoseconds,((j)=>{if(tW(j))throw RangeError(AG);return K0(j,5)})($?H0(J):J))))}function s2($,Z,J,j,Y,W=Object.create(null)){let z=Z(j.timeZone),X=$(j.calendar);return{...j,...t2(z,X,j,J?H0(Y):Y,W)}}function n2($,Z,J,j,Y=Object.create(null)){let{calendar:W}=J;return j0(e2($(W),J,Z?H0(j):j,Y),W)}function o2($,Z,J,j,Y){let{calendar:W}=J;return Y0(N6($(W),J,Z?H0(j):j,Y),W)}function a2($,Z,J,j,Y=Object.create(null)){let W=J.calendar,z=$(W),X=aZ(z,J);Z&&(j=_6(j)),j.sign<0&&(X=z.dateAdd(X,{...D0,months:1}),X=V$(X,-1));let O=z.dateAdd(X,j,Y);return K$(aZ(z,O),W)}function r2($,Z,J){return n0(sW(Z,$?H0(J):J)[0])}function t2($,Z,J,j,Y){let W=K0(j,5),z=J.epochNanoseconds;if(tW(j)){let X=_0(J,$);z=t$(v0($,{...N6(Z,X,{...j,...mJ},Y),...k0(a0,X)}),W)}else z=t$(z,W),y(Y);return{epochNanoseconds:p0(z)}}function e2($,Z,J,j){let[Y,W]=sW(Z,J);return I1({...N6($,Z,{...J,...mJ,days:J.days+W},j),...Y})}function N6($,Z,J,j){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,j);y(j);let Y=J.days+K0(J,5)[0];return Y?y1(V$(Z,Y)):Z}function aZ($,Z,J=1){return V$(Z,J-$.day(Z))}function sW($,Z){let[J,j]=K0(Z,5),[Y,W]=G6(p1($)+j);return[Y,J+W]}function V$($,Z){return Z?{...$,...K6(C0($)+Z*R0)}:$}function L6($,Z,J){let j=$(J.calendar);return C6(J)?[J,j,Z(J.timeZone)]:[{...J,...d0},j]}function $J($){return $?AW:L0}function P6($){return $?v(t2,$):e2}function ZJ($){return $?v(eO,$):$G}function C6($){return $&&$.epochNanoseconds}function rZ($,Z){return $<=6-(C6(Z)?1:0)}function JJ($,Z,J,j,Y,W,z){let X=$(s0(z).relativeTo),O=Math.max(Q$(Y),Q$(W));if(rZ(O,X))return i(XZ(((D,T,V,P)=>{let M=t$(K0(D),K0(T),P?-1:1);if(!Number.isFinite(M[0]))throw RangeError(w6);return{...D0,...OZ(M,V)}})(Y,W,O,j)));if(!X)throw RangeError(q6);j&&(W=H0(W));let[G,K,Q]=L6(Z,J,X),U=P6(Q),B=ZJ(Q),F=U(K,G,Y);return i(B(K,G,U(K,F,W),O))}function nW($,Z,J,j,Y){let W=Q$(j),[z,X,O,G,K]=((_,L,I)=>{_=f2(_,J6);let C=dJ(_),b=I(_[J7]),m=S2(_),A1=F3(_,7),e=B3(_);if(C===void 0&&e===void 0)throw RangeError(fG);return e==null&&(e=0),C==null&&(C=Math.max(e,L)),_W(C,e),m=A2(m,e,1),[C,e,m,A1,b]})(Y,W,$),Q=Math.max(W,z);if(!C6(K)&&Q<=6)return i(XZ(((_,L,I,C,b)=>{let m=V6(K0(_),I,C,b);return{...D0,...OZ(m,L)}})(j,z,X,O,G)));if(!K)throw RangeError(q6);let[U,B,F]=L6(Z,J,K),D=$J(F),T=P6(F),V=ZJ(F),P=T(B,U,j),M=V(B,U,P,z),H=j.sign,S=u1(M);if(H&&S&&H!==S)throw RangeError(K3);return S&&(M=T6(M,D(P),z,X,O,G,B,U,D,T)),i(M)}function oW($){return $.sign===-1?_6($):$}function _6($){return i(H0($))}function H0($){let Z={};for(let J of g)Z[J]=-1*$[J]||0;return Z}function aW($){return!$.sign}function u1($,Z=g){let J=0;for(let j of Z){let Y=Math.sign($[j]);if(Y){if(J&&J!==Y)throw RangeError(SG);J=Y}}return J}function XZ($){for(let Z of yG)h0(Z,$[Z],-uY,uY,1);return rW(m0(K0($),u0)),$}function rW($){if(!Number.isSafeInteger($))throw RangeError(xG)}function K0($,Z=6){return tY($,Z,g)}function OZ($,Z=6){let[J,j]=$,Y=W6(j,Z,g);if(Y[g[Z]]+=J*(c/J1[Z]),!Number.isFinite(Y[g[Z]]))throw RangeError(w6);return Y}function H6($,Z=5){return W6($,Z,g)}function tW($){return Boolean(u1($,tz))}function Q$($){let Z=9;for(;Z>0&&!$[g[Z]];Z--);return Z}function tO($,Z){return[$,Z]}function yY($){let Z=Math.floor($/i3)*i3;return[Z,Z+i3]}function eW($){let Z=d1($=o3($));if(!Z)throw RangeError(E0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(E0($));J=GZ(Z.offset)}return Z.timeZone&&zJ(Z.timeZone,1),U0(L2(Q6(Z),J))}function $9($){let Z=d1(a($));if(!Z)throw RangeError(E0($));if(Z.timeZone)return G9(Z,Z.offset?GZ(Z.offset):void 0);if(Z.m)throw RangeError(E0($));return Q9(Z)}function Z9($,Z){let J=d1(a($));if(!J||!J.timeZone)throw RangeError(E0($));let{offset:j}=J,Y=j?GZ(j):void 0,[,W,z]=Y3(Z);return G9(J,Y,W,z)}function GZ($){let Z=zJ($);if(Z===void 0)throw RangeError(E0($));return Z}function J9($){let Z=d1(a($));if(!Z||Z.m)throw RangeError(E0($));return j0(K9(Z))}function x6($){let Z=d1(a($));if(!Z||Z.m)throw RangeError(E0($));return Y0(Z.p?K9(Z):Q9(Z))}function j9($,Z){let J=YJ(a(Z));if(J)return jJ(J),K$(N2(B$(J)));let j=x6(Z);return K$(aZ($(j.calendar),j))}function jJ($){if($.calendar!==w)throw RangeError(V1($.calendar))}function Y9($,Z){let J=WJ(a(Z));if(J)return jJ(J),r3(B$(J));let j=x6(Z),{calendar:Y}=j,W=$(Y),[z,X,O]=W.h(j),[G,K]=W.I(z,X),[Q,U]=W.N(G,K,O);return r3(y1(W.P(Q,U,O)),Y)}function W9($){let Z,J=((j)=>{let Y=QK.exec(j);return Y?(S6(Y[10]),F9(Y)):void 0})(a($));if(!J){if(J=d1($),!J)throw RangeError(E0($));if(!J.p)throw RangeError(E0($));if(J.m)throw RangeError(V1("Z"));jJ(J)}if((Z=YJ($))&&kY(Z))throw RangeError(E0($));if((Z=WJ($))&&kY(Z))throw RangeError(E0($));return n0(U6(J,1))}function z9($){let Z=((J)=>{let j=FK.exec(J);return j?((Y)=>{function W(K,Q,U){let B=0,F=0;if(U&&([B,O]=T1(O,J1[U])),K!==void 0){if(X)throw RangeError(V1(K));F=((D)=>{let T=parseInt(D);if(!Number.isFinite(T))throw RangeError(V1(D));return T})(K),z=1,Q&&(O=XJ(Q)*(J1[U]/u0),X=1)}return B+F}let z=0,X=0,O=0,G={...jZ(g,[W(Y[2]),W(Y[3]),W(Y[4]),W(Y[5]),W(Y[6],Y[7],5),W(Y[8],Y[9],4),W(Y[10],Y[11],3)]),...W6(O,2,g)};if(!z)throw RangeError(Rz(g));return OJ(Y[1])<0&&(G=H0(G)),G})(j):void 0})(a($));if(!Z)throw RangeError(E0($));return i(XZ(Z))}function X9($){let Z=d1($)||YJ($)||WJ($);return Z?Z.calendar:$}function O9($){let Z=d1($);return Z&&(Z.timeZone||Z.m&&_$||Z.offset)||$}function G9($,Z,J=0,j=0){let Y=A6($.timeZone),W=l6(Y);return T0(T$(W,Q6($),Z,J,j,!W.v,$.m),Y,z3($.calendar))}function K9($){return U9(I1(Q6($)))}function Q9($){return U9(y1(B$($)))}function U9($){return{...$,calendar:z3($.calendar)}}function d1($){let Z=KK.exec($);return Z?((J)=>{let j=J[10],Y=(j||"").toUpperCase()==="Z";return{isoYear:B9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...F9(J.slice(5)),...S6(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:j}})(Z):void 0}function YJ($){let Z=OK.exec($);return Z?((J)=>({isoYear:B9(J),isoMonth:parseInt(J[4]),isoDay:1,...S6(J[5])}))(Z):void 0}function WJ($){let Z=GK.exec($);return Z?((J)=>({isoYear:JZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...S6(J[3])}))(Z):void 0}function zJ($,Z){let J=UK.exec($);return J?((j,Y)=>{let W=j[4]||j[5];if(Y&&W)throw RangeError(V1(W));return d2((r$(j[2])*g6+r$(j[3])*y6+r$(j[4])*u0+XJ(j[5]||""))*OJ(j[1]))})(J,Z):void 0}function B9($){let Z=OJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(V1(-0));return Z*J}function F9($){let Z=r$($[3]);return{...G6(XJ($[4]||""))[0],isoHour:r$($[1]),isoMinute:r$($[2]),isoSecond:Z===60?59:Z}}function S6($){let Z,J,j=[];if($.replace(BK,(Y,W,z)=>{let X=Boolean(W),[O,G]=z.split("=").reverse();if(G){if(G==="u-ca")j.push(O),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(V1(Y))}else{if(J)throw RangeError(V1(Y));J=O}return""}),j.length>1&&Z)throw RangeError(V1($));return{timeZone:J,calendar:j[0]||w}}function XJ($){return parseInt($.padEnd(9,"0"))}function KZ($){return new RegExp(`^${$}$`,"i")}function OJ($){return $&&$!=="+"?-1:1}function r$($){return $===void 0?0:parseInt($)}function D9($){return A6(a($))}function A6($){let Z=GJ($);return typeof Z=="number"?D$(Z):Z?((J)=>{if(TK.test(J))throw RangeError(LG);return J.toLowerCase().split("/").map((j,Y)=>(j.length<=3||/\d/.test(j))&&!/etc|yap/.test(j)?j.toUpperCase():j.replace(/baja|dumont|[a-z]+/g,(W,z)=>W.length<=2&&!Y||W==="in"||W==="chat"?W.toUpperCase():W.length>2||!z?bY(W).replace(/island|noronha|murdo|rivadavia|urville/,bY):W)).join("/")})($):_$}function gY($){let Z=GJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:_$}function GJ($){let Z=zJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==_$?DK($):void 0}function KJ($,Z){return P0($.epochNanoseconds,Z.epochNanoseconds)}function QJ($,Z){return P0($.epochNanoseconds,Z.epochNanoseconds)}function T9($,Z,J,j,Y,W){let z=$(s0(W).relativeTo),X=Math.max(Q$(j),Q$(Y));if(aY(g,j,Y))return 0;if(rZ(X,z))return P0(K0(j),K0(Y));if(!z)throw RangeError(q6);let[O,G,K]=L6(Z,J,z),Q=$J(K),U=P6(K);return P0(Q(U(G,O,j)),Q(U(G,O,Y)))}function UJ($,Z){return M$($,Z)||f6($,Z)}function M$($,Z){return q1(C0($),C0(Z))}function f6($,Z){return q1(p1($),p1(Z))}function V9($,Z){return!KJ($,Z)}function M9($,Z){return!QJ($,Z)&&!!E6($.timeZone,Z.timeZone)&&zZ($.calendar,Z.calendar)}function I9($,Z){return!UJ($,Z)&&zZ($.calendar,Z.calendar)}function N9($,Z){return!M$($,Z)&&zZ($.calendar,Z.calendar)}function L9($,Z){return!M$($,Z)&&zZ($.calendar,Z.calendar)}function P9($,Z){return!M$($,Z)&&zZ($.calendar,Z.calendar)}function C9($,Z){return!f6($,Z)}function E6($,Z){if($===Z)return 1;let J=F0($),j=F0(Z);if(J===j)return 1;try{return gY(J)===gY(j)}catch(Y){}}function BJ($,Z,J,j){let Y=WZ($,J0(j),3,5),W=R6(Z.epochNanoseconds,J.epochNanoseconds,...Y);return i($?H0(W):W)}function FJ($,Z,J,j,Y,W){let z=v6(j.calendar,Y.calendar),X=J0(W),[O,G,K,Q]=WZ(J,X,5),U=j.epochNanoseconds,B=Y.epochNanoseconds,F=P0(B,U),D;if(F)if(O<6)D=R6(U,B,O,G,K,Q);else{let T=Z(((P,M)=>{if(!E6(P,M))throw RangeError(yz);return P})(j.timeZone,Y.timeZone)),V=$(z);D=H9(V,T,j,Y,F,O,X),D=T6(D,B,O,G,K,Q,V,j,AW,v(t2,T))}else D=D0;return i(J?H0(D):D)}function DJ($,Z,J,j,Y){let W=v6(J.calendar,j.calendar),z=J0(Y),[X,O,G,K]=WZ(Z,z,6),Q=L0(J),U=L0(j),B=P0(U,Q),F;if(B)if(X<=6)F=R6(Q,U,X,O,G,K);else{let D=$(W);F=x9(D,J,j,B,X,z),F=T6(F,U,X,O,G,K,D,J,L0,e2)}else F=D0;return i(Z?H0(F):F)}function TJ($,Z,J,j,Y){let W=v6(J.calendar,j.calendar),z=J0(Y);return _9(Z,()=>$(W),J,j,...WZ(Z,z,6,9,6),z)}function VJ($,Z,J,j,Y){let W=v6(J.calendar,j.calendar),z=J0(Y),X=WZ(Z,z,9,9,8),O=$(W);return _9(Z,()=>O,aZ(O,J),aZ(O,j),...X,z)}function _9($,Z,J,j,Y,W,z,X,O){let G=L0(J),K=L0(j),Q;if(P0(K,G))if(Y===6)Q=R6(G,K,Y,W,z,X);else{let U=Z();Q=U.dateUntil(J,j,Y,O),W===6&&z===1||(Q=T6(Q,K,Y,W,z,X,U,J,L0,N6))}else Q=D0;return i($?H0(Q):Q)}function MJ($,Z,J,j){let Y=J0(j),[W,z,X,O]=WZ($,Y,5,5),G=h1(IJ(Z,J),W3(z,X),O),K={...D0,...H6(G,W)};return i($?H0(K):K)}function eO($,Z,J,j,Y,W){let z=P0(j.epochNanoseconds,J.epochNanoseconds);return z?Y<6?S9(J.epochNanoseconds,j.epochNanoseconds,Y):H9(Z,$,J,j,z,Y,W):D0}function $G($,Z,J,j,Y){let W=L0(Z),z=L0(J),X=P0(z,W);return X?j<=6?S9(W,z,j):x9($,Z,J,X,j,Y):D0}function H9($,Z,J,j,Y,W,z){let[X,O,G]=((U,B,F,D)=>{function T(){return L={...V$(M,S++*-D),...P},I=v0(U,L),P0(H,I)===-D}let V=_0(B,U),P=k0(a0,V),M=_0(F,U),H=F.epochNanoseconds,S=0,_=IJ(V,M),L,I;if(Math.sign(_)===-D&&S++,T()&&(D===-1||T()))throw RangeError(K3);let C=m0(g0(I,H));return[V,L,C]})(Z,J,j,Y);var K,Q;return{...W===6?(K=X,Q=O,{...D0,days:A9(K,Q)}):$.dateUntil(X,O,W,z),...H6(G)}}function x9($,Z,J,j,Y,W){let[z,X,O]=((G,K,Q)=>{let U=K,B=IJ(G,K);return Math.sign(B)===-Q&&(U=V$(K,-Q),B+=c*Q),[G,U,B]})(Z,J,j);return{...$.dateUntil(z,X,Y,W),...H6(O)}}function R6($,Z,J,j,Y,W){return{...D0,...OZ(V6(g0($,Z),j,Y,W),J)}}function S9($,Z,J){return{...D0,...OZ(g0($,Z),J)}}function A9($,Z){return b6(C0($),C0(Z))}function b6($,Z){return Math.trunc((Z-$)/R0)}function IJ($,Z){return p1(Z)-p1($)}function v6($,Z){if(!zZ($,Z))throw RangeError(kJ);return $}function ZG($){function Z(Y){return((W,z)=>({...f9(W,z),F:W.month,day:parseInt(W.day)}))(I2(J,Y),j)}let J=oJ($),j=$6($);return{id:$,O:JG(Z),B:jG(Z)}}function JG($){return b0((Z)=>{let J=C0(Z);return $(J)},WeakMap)}function jG($){let Z=$(0).year-uG;return b0((J)=>{let j,Y=YZ(J-Z),W=[],z=[];do Y+=400*R0;while((j=$(Y)).year<=J);do Y+=(1-j.day)*R0,j.year===J&&(W.push(Y),z.push(j.F)),Y-=R0;while((j=$(Y)).year>=J);return{k:W.reverse(),C:pz(z.reverse())}})}function f9($,Z){let J,j,Y=E9($);if($.era){let W=oz[Z];W!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),j=Y,Y=w9(j,W[J]||0))}return{era:J,eraYear:j,year:Y}}function E9($){return parseInt($.relatedYear||$.year)}function j2($){let{year:Z,F:J,day:j}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,j]}function tZ($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*R0}function u3($){let Z=pY(this,$),J=pY(this,$-1),j=Z.length;if(j>J.length){let Y=q9(this);if(Y<0)return-Y;for(let W=0;W<j;W++)if(Z[W]!==J[W])return W+1}}function d3($){return b6(tZ.call(this,$),tZ.call(this,$+1))}function mY($,Z){let{k:J}=this.B($),j=Z+1,Y=J;return j>J.length&&(j=1,Y=this.B($+1).k),b6(J[Z-1],Y[j-1])}function l3($){return this.B($).k.length}function pY($,Z){return Object.keys($.B(Z).C)}function R9($){return z3(a($))}function z3($){if(($=$.toLowerCase())!==w&&$!==p6&&$6($)!==$6(oJ($).resolvedOptions().calendar))throw RangeError(NG($));return $}function $6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function b9($){return this.R($)[0]}function v9($){return this.R($)[1]}function NJ($){let[Z]=this.h($);return b6(this.q(Z),C0($))+1}function k9($){let Z=MK.exec($);if(!Z)throw RangeError(MG($));return[parseInt(Z[1]),Boolean(Z[2])]}function Z6($,Z,J){return $+(Z||J&&$>=J?1:0)}function Y2($,Z){return $-(Z&&$>=Z?1:0)}function w9($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function W2($){return oz[y9($)]}function q9($){return kG[y9($)]}function y9($){return $6($.id||w)}function g9($,Z,J,j){let Y=l1(J,j,o0,[],lz);if(Y.timeZone!==void 0){let W=J.dateFromFields(Y),z=I$(Y),X=$(Y.timeZone);return{epochNanoseconds:T$(Z(X),{...W,...z},Y.offset!==void 0?GZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...d0}}function m9($,Z,J,j,Y,W){let z=l1(J,Y,o0,uz,lz),X=$(z.timeZone),[O,G,K]=Y3(W),Q=J.dateFromFields(z,F6(W,O)),U=I$(z,O);return T0(T$(Z(X),{...Q,...U},z.offset!==void 0?GZ(z.offset):void 0,G,K),X,j)}function p9($,Z,J){let j=l1($,Z,o0,[],P1),Y=y(J);return j0(I1({...$.dateFromFields(j,F6(J,Y)),...I$(j,Y)}))}function LJ($,Z,J,j=[]){let Y=l1($,Z,o0,j);return $.dateFromFields(Y,J)}function PJ($,Z,J,j){let Y=l1($,Z,yJ,j);return $.yearMonthFromFields(Y,J)}function CJ($,Z,J,j,Y=[]){let W=l1($,J,o0,Y);return Z&&W.month!==void 0&&W.monthCode===void 0&&W.year===void 0&&(W.year=JZ),$.monthDayFromFields(W,j)}function h9($,Z){let J=y(Z);return n0(I$(Z1($,X2,[],1),J))}function c9($){let Z=Z1($,gJ);return i(XZ({...D0,...Z}))}function l1($,Z,J,j=[],Y=[]){return Z1(Z,[...$.fields(J),...Y].sort(),j)}function Z1($,Z,J,j=!J){let Y={},W,z=0;for(let X of Z){if(X===W)throw RangeError(UG(X));if(X==="constructor"||X==="__proto__")throw RangeError(bJ(X));let O=$[X];if(O!==void 0)z=1,dY[X]&&(O=dY[X](O,X)),Y[X]=O;else if(J){if(J.includes(X))throw TypeError(RJ(X));Y[X]=nz[X]}W=X}if(j&&!z)throw TypeError(Rz(Z));return Y}function I$($,Z){return U6(PK({...nz,...$}),Z)}function u9($,Z,J,j,Y,W){let z=J0(W),{calendar:X,timeZone:O}=J;return T0(((G,K,Q,U,B)=>{let F=X3(G,Q,U,o0,dz,cz),[D,T,V]=Y3(B,2);return T$(K,{...G.dateFromFields(F,F6(B,D)),...I$(F,D)},GZ(F.offset),T,V)})($(X),Z(O),j,Y,z),O,X)}function d9($,Z,J,j,Y){let W=J0(Y);return j0(((z,X,O,G)=>{let K=X3(z,X,O,o0,P1),Q=y(G);return I1({...z.dateFromFields(K,F6(G,Q)),...I$(K,Q)})})($(Z.calendar),J,j,W))}function l9($,Z,J,j,Y){let W=J0(Y);return((z,X,O,G)=>{let K=X3(z,X,O,o0);return z.dateFromFields(K,G)})($(Z.calendar),J,j,W)}function i9($,Z,J,j,Y){let W=J0(Y);return K$(((z,X,O,G)=>{let K=X3(z,X,O,yJ);return z.yearMonthFromFields(K,G)})($(Z.calendar),J,j,W))}function s9($,Z,J,j,Y){let W=J0(Y);return((z,X,O,G)=>{let K=X3(z,X,O,o0);return z.monthDayFromFields(K,G)})($(Z.calendar),J,j,W)}function n9($,Z,J){return n0(((j,Y,W)=>{let z=y(W);return I$({...k0(X2,j),...Z1(Y,X2)},z)})($,Z,J))}function o9($,Z){return i((J=$,j=Z,XZ({...J,...Z1(j,gJ)})));var J,j}function X3($,Z,J,j,Y=[],W=[]){let z=[...$.fields(j),...Y].sort(),X=Z1(Z,z,W),O=Z1(J,z);return X=$.mergeFields(X,O),Z1(X,z,[])}function _J($,Z){let J=l1($,Z,sz);return $.monthDayFromFields(J)}function HJ($,Z,J){let j=l1($,Z,iz);return $.yearMonthFromFields(j,J)}function a9($,Z,J,j,Y){Z=k0(J=$.fields(J),Z),j=Z1(j,Y=$.fields(Y),[]);let W=$.mergeFields(Z,j);return W=Z1(W,[...J,...Y].sort(),[]),$.dateFromFields(W)}function t8($,Z){let{era:J,eraYear:j,year:Y}=Z,W=W2($);if(J!==void 0||j!==void 0){if(J===void 0||j===void 0)throw TypeError(FG);if(!W)throw RangeError(BG);let z=W[J];if(z===void 0)throw RangeError(TG(J));let X=w9(j,z);if(Y!==void 0&&Y!==X)throw RangeError(DG);Y=X}else if(Y===void 0)throw TypeError(VG(W));return Y}function e8($,Z,J,j){let{month:Y,monthCode:W}=Z;if(W!==void 0){let z=((X,O,G,K)=>{let Q=X.U(G),[U,B]=k9(O),F=Z6(U,B,Q);if(B){let D=q9(X);if(D===void 0)throw RangeError(sZ);if(D>0){if(F>D)throw RangeError(sZ);if(Q===void 0){if(K===1)throw RangeError(sZ);F--}}else{if(F!==-D)throw RangeError(sZ);if(Q===void 0&&K===1)throw RangeError(sZ)}}return F})($,W,J,j);if(Y!==void 0&&Y!==z)throw RangeError(wz);Y=z,j=1}else if(Y===void 0)throw TypeError(IG);return h0("month",Y,1,$.L(J),j)}function hY($,Z,J,j,Y){return f0(Z,"day",1,$.j(j,J),Y)}function $2($,Z,J,j){let Y=0,W=[];for(let z of J)Z[z]!==void 0?Y=1:W.push(z);if(Object.assign($,Z),Y)for(let z of j||W)delete $[z]}function r9($){return U0(p0(O6(X6($))))}function t9($,Z,J,j,Y=w){return T0(p0(O6(X6(J))),Z(j),$(Y))}function e9($,Z,J,j,Y=0,W=0,z=0,X=0,O=0,G=0,K=w){return j0(I1(Q6(l0(N0,jZ(h6,[Z,J,j,Y,W,z,X,O,G])))),$(K))}function $z($,Z,J,j,Y=w){return Y0(y1(B$(l0(N0,{isoYear:Z,isoMonth:J,isoDay:j}))),$(Y))}function Zz($,Z,J,j=w,Y=1){let W=N0(Z),z=N0(J),X=$(j);return K$(N2(B$({isoYear:W,isoMonth:z,isoDay:N0(Y)})),X)}function Jz($,Z,J,j=w,Y=JZ){let W=N0(Z),z=N0(J),X=$(j);return r3(y1(B$({isoYear:N0(Y),isoMonth:W,isoDay:z})),X)}function jz($=0,Z=0,J=0,j=0,Y=0,W=0){return n0(U6(l0(N0,jZ(a0,[$,Z,J,j,Y,W])),1))}function Yz($=0,Z=0,J=0,j=0,Y=0,W=0,z=0,X=0,O=0,G=0){return i(XZ(l0(OW,jZ(g,[$,Z,J,j,Y,W,z,X,O,G]))))}function xJ($,Z,J=w){return T0($.epochNanoseconds,Z,J)}function Wz($){return U0($.epochNanoseconds)}function SJ($,Z){return j0(_0(Z,$))}function AJ($,Z){return Y0(_0(Z,$))}function zz($,Z,J){return HJ($(Z.calendar),J)}function Xz($,Z,J){return _J($(Z.calendar),J)}function fJ($,Z){return n0(_0(Z,$))}function Oz($,Z,J,j){let Y=((W,z,X,O)=>{let G=_2(O);return v0(W(z),X,G)})($,J,Z,j);return T0(p0(Y),J,Z.calendar)}function Gz($,Z,J){let j=$(Z.calendar);return K$({...Z,...HJ(j,J)})}function Kz($,Z,J){return _J($(Z.calendar),J)}function Qz($,Z,J,j,Y){let W=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):d0;return T0(v0(J(W),{...j,...X}),W,j.calendar)}function Uz($,Z=d0){return j0(I1({...$,...Z}))}function Bz($,Z,J){return HJ($(Z.calendar),J)}function Fz($,Z,J){return _J($(Z.calendar),J)}function Dz($,Z,J,j){return((Y,W,z)=>a9(Y,W,iz,M1(z),U3))($(Z.calendar),J,j)}function Tz($,Z,J,j){return((Y,W,z)=>a9(Y,W,sz,M1(z),m6))($(Z.calendar),J,j)}function Vz($,Z,J,j,Y){let W=M1(Y),z=Z(W.plainDate),X=$(W.timeZone);return T0(v0(J(X),{...z,...j}),X,z.calendar)}function Mz($,Z){return j0(I1({...$,...Z}))}function Iz($){return U0(p0($Z($,u0)))}function Nz($){return U0(p0($Z($,j1)))}function Lz($){return U0(p0(O6(X6($),L$)))}function Pz($){return U0(p0(O6(X6($))))}function Cz($,Z,J=d0){let j=Z.timeZone,Y=$(j),W={..._0(Z,Y),...J};return T0(T$(Y,W,W.offsetNanoseconds,2),j,Z.calendar)}function _z($,Z,J){let j=Z.timeZone,Y=$(j),W={..._0(Z,Y),...J},z=Az(Z.calendar,J.calendar);return T0(T$(Y,W,W.offsetNanoseconds,2),j,z)}function Hz($,Z=d0){return j0({...$,...Z})}function xz($,Z){return j0({...$,...Z},Az($.calendar,Z.calendar))}function k6($,Z){return{...$,calendar:Z}}function Sz($,Z){return{...$,timeZone:Z}}function Az($,Z){if($===Z)return $;let J=F0($),j=F0(Z);if(J===j||J===w)return Z;if(j===w)return $;throw RangeError(kJ)}function YG($,Z){return(J)=>J===w?$:J===p6||J===ZZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),VK(J))}function N$($,Z,J){let j=new Set(J);return(Y)=>(((W,z)=>{for(let X of z)if(X in W)return 1;return 0})(Y=Q2(j,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=_$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function N1($,Z=EJ){let[J,,,j]=$;return(Y,W=gK,...z)=>{let X=Z(j&&j(...z),Y,W,J),O=X.resolvedOptions();return[X,...WG($,O,z)]}}function EJ($,Z,J,j){if(J=j(J),$){if(J.timeZone!==void 0)throw TypeError(RG);J.timeZone=$}return new i1(Z,J)}function WG($,Z,J){let[,j,Y]=$;return J.map((W)=>(W.calendar&&((z,X,O)=>{if((O||z!==w)&&z!==X)throw RangeError(kJ)})(F0(W.calendar),Z.calendar,Y),j(W,Z)))}function QZ($){let Z=O3();return c1(Z,$.getOffsetNanosecondsFor(Z))}function O3(){return $Z(Date.now(),j1)}function L1(){return iY||(iY=new i1().resolvedOptions().timeZone)}var zG=($,Z)=>`Non-integer ${$}: ${Z}`,XG=($,Z)=>`Non-positive ${$}: ${Z}`,OG=($,Z)=>`Non-finite ${$}: ${Z}`,GG=($)=>`Cannot convert bigint to ${$}`,KG=($)=>`Invalid bigint: ${$}`,QG="Cannot convert Symbol to string",fz="Invalid object",Ez=($,Z,J,j,Y)=>Y?Ez($,Y[Z],Y[J],Y[j]):G3($,Z)+`; must be between ${J}-${j}`,G3=($,Z)=>`Invalid ${$}: ${Z}`,RJ=($)=>`Missing ${$}`,bJ=($)=>`Invalid field ${$}`,UG=($)=>`Duplicate field ${$}`,Rz=($)=>"No valid fields: "+$.join(),bz="Invalid bag",vz=($,Z,J)=>G3($,Z)+"; must be "+Object.keys(J).join(),kz="Cannot use valueOf",vJ="Invalid calling context",BG="Forbidden era/eraYear",FG="Mismatching era/eraYear",DG="Mismatching year/eraYear",TG=($)=>`Invalid era: ${$}`,VG=($)=>"Missing year"+($?"/era/eraYear":""),MG=($)=>`Invalid monthCode: ${$}`,wz="Mismatching month/monthCode",IG="Missing month/monthCode",cY="Cannot guess year",sZ="Invalid leap month",qz="Invalid protocol",K3="Invalid protocol results",kJ="Mismatching Calendars",NG=($)=>`Invalid Calendar: ${$}`,yz="Mismatching TimeZones",LG="Forbidden ICU TimeZone",PG="Out-of-bounds offset",CG="Out-of-bounds TimeZone gap",_G="Invalid TimeZone offset",HG="Ambiguous offset",w6="Out-of-bounds date",xG="Out-of-bounds duration",SG="Cannot mix duration signs",q6="Missing relativeTo",AG="Cannot use large units",fG="Required smallestUnit or largestUnit",EG="smallestUnit > largestUnit",E0=($)=>`Cannot parse: ${$}`,V1=($)=>`Invalid substring: ${$}`,gz=($)=>`Cannot format ${$}`,mz="Mismatching types for formatting",RG="Cannot specify TimeZone",pz=v(Z3,($,Z)=>Z),UZ=v(Z3,($,Z,J)=>J),c0=v(n3,2),z2={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},Q3=Object.keys(z2),R0=86400000,hz=1000,L$=1000,j1=1e6,u0=1e9,y6=60000000000,g6=3600000000000,c=86400000000000,J1=[1,L$,j1,u0,y6,g6,c],P1=Q3.slice(0,6),X2=J3(P1),cz=["offset"],uz=["timeZone"],dz=P1.concat(cz),lz=dz.concat(uz),O2=["era","eraYear"],bG=O2.concat(["year"]),m6=["year"],wJ=["monthCode"],qJ=["month"].concat(wJ),U3=["day"],yJ=qJ.concat(m6),iz=wJ.concat(m6),o0=U3.concat(yJ),vG=U3.concat(qJ),sz=U3.concat(wJ),nz=UZ(P1,0),w="iso8601",p6="gregory",ZZ="japanese",oz={[p6]:{bce:-1,ce:0},[ZZ]:{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}},kG={chinese:13,dangi:13,hebrew:-6},a=v(z6,"string"),az=v(z6,"boolean"),wG=v(z6,"number"),rz=v(z6,"function"),g=Q3.map(($)=>$+"s"),gJ=J3(g),qG=g.slice(0,6),tz=g.slice(6),yG=tz.slice(1),gG=pz(g),D0=UZ(g,0),mJ=UZ(qG,0),pJ=v(rY,g),a0=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],hJ=["isoDay","isoMonth","isoYear"],h6=a0.concat(hJ),cJ=J3(hJ),ez=J3(a0),$7=J3(h6),d0=UZ(ez,0),mG=v(rY,h6),i1=Intl.DateTimeFormat,Z7="en-GB",uJ=1e8,pG=uJ*R0,hG=[uJ,0],cG=[-uJ,0],eZ=275760,$3=-271821,uG=1970,JZ=1972,D1=12,dG=YZ(1868,9,8),lG=b0(lO,WeakMap),J6="smallestUnit",G2="unit",oZ="roundingIncrement",Z2="fractionalSecondDigits",J7="relativeTo",j7={constrain:0,reject:1},iG=Object.keys(j7),sG={compatible:0,reject:1,earlier:2,later:3},nG={reject:0,use:1,prefer:2,ignore:3},oG={auto:0,never:1,critical:2,always:3},aG={auto:0,never:1,critical:2},rG={auto:0,never:1},tG={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},B3=v(E2,J6),dJ=v(E2,"largestUnit"),eG=v(E2,G2),Y7=v(F$,"overflow",j7),W7=v(F$,"disambiguation",sG),$K=v(F$,"offset",nG),lJ=v(F$,"calendarName",oG),ZK=v(F$,"timeZoneName",aG),JK=v(F$,"offset",rG),F3=v(F$,"roundingMode",tG),BZ="PlainYearMonth",FZ="PlainMonthDay",P$="PlainDate",C$="PlainDateTime",c6="PlainTime",C1="ZonedDateTime",u6="Instant",d6="Duration",jK=[Math.floor,($)=>c3($)?Math.floor($):Math.round($),Math.ceil,($)=>c3($)?Math.ceil($):Math.round($),Math.trunc,($)=>c3($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>c3($)?($=Math.trunc($)||0)+$%2:Math.round($)],_$="UTC",i3=5184000,YK=a3(1847),WK=a3(new Date().getUTCFullYear()+10),zK=/0+$/,_0=b0(rO,WeakMap),uY=4294967295,l6=b0(($)=>{let Z=GJ($);return typeof Z=="object"?new X7(Z):new z7(Z||0)});class z7{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[L2($,this.v)]}l(){}}class X7{constructor($){this.$=((Z)=>{function J(O){let G=J2(O,z,X),[K,Q]=yY(G),U=Y(K),B=Y(Q);return U===B?U:j(W(K,Q),U,B,O)}function j(O,G,K,Q){let U,B;for(;(Q===void 0||(U=Q<O[0]?G:Q>=O[1]?K:void 0)===void 0)&&(B=O[1]-O[0]);){let F=O[0]+Math.floor(B/2);Z(F)===K?O[1]=F:O[0]=F+1}return U}let Y=b0(Z),W=b0(tO),z=YK,X=WK;return{G(O){let G=J(O-86400),K=J(O+86400),Q=O-G,U=O-K;if(G===K)return[Q];let B=J(Q);return B===J(U)?[O-B]:G>K?[Q,U]:[]},V:J,l(O,G){let K=J2(O,z,X),[Q,U]=yY(K),B=i3*G,F=G<0?()=>U>z||(z=K,0):()=>Q<X||(X=K,0);for(;F();){let D=Y(Q),T=Y(U);if(D!==T){let V=W(Q,U);j(V,D,T);let P=V[0];if((q1(P,O)||1)===G)return P}Q+=B,U+=B}}}})(((Z)=>(J)=>{let j=I2(Z,J*hz);return a3(E9(j),parseInt(j.month),parseInt(j.day),parseInt(j.hour),parseInt(j.minute),parseInt(j.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(QW($))*u0}getPossibleInstantsFor($){let[Z,J]=[a3((j=$).isoYear,j.isoMonth,j.isoDay,j.isoHour,j.isoMinute,j.isoSecond),j.isoMillisecond*j1+j.isoMicrosecond*L$+j.isoNanosecond];var j;return this.$.G(Z).map((Y)=>p0(e$($Z(Y,u0),J)))}l($,Z){let[J,j]=UW($),Y=this.$.l(J+(Z>0||j?1:0),Z);if(Y!==void 0)return $Z(Y,u0)}}var iJ="([+\u2212-])",s3="(?:[.,](\\d{1,9}))?",O7=`(?:(?:${iJ}(\\d{6}))|(\\d{4}))-?(\\d{2})`,sJ="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+s3+")?)?",nJ=iJ+sJ,XK=O7+"-?(\\d{2})(?:[T ]"+sJ+"(Z|"+nJ+")?)?",G7="\\[(!?)([^\\]]*)\\]",i6=`((?:${G7}){0,9})`,OK=KZ(O7+i6),GK=KZ("(?:--)?(\\d{2})-?(\\d{2})"+i6),KK=KZ(XK+i6),QK=KZ("T?"+sJ+"(?:"+nJ+")?"+i6),UK=KZ(nJ),BK=new RegExp(G7,"g"),FK=KZ(`${iJ}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${s3}H)?(?:(\\d+)${s3}M)?(?:(\\d+)${s3}S)?)?`),DK=b0(($)=>new i1(Z7,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),TK=/^(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$/,VK=b0(ZG),oJ=b0(($)=>new i1(Z7,{calendar:$,timeZone:_$,era:"short",year:"numeric",month:"short",day:"numeric"})),MK=/^M(\d{2})(L?)$/,IK={era:o3,eraYear:N0,year:N0,month:vY,monthCode:o3,day:vY},NK=UZ(P1,N0),LK=UZ(g,OW),dY=Object.assign({},IK,NK,LK,{offset:o3}),PK=v(dO,P1,a0),lY={dateAdd($,Z,J){let j=y(J),Y,{years:W,months:z,weeks:X,days:O}=Z;if(O+=K0(Z,5)[0],W||z)Y=((G,K,Q,U,B)=>{let[F,D,T]=G.h(K);if(Q){let[V,P]=G.I(F,D);F+=Q,D=Z6(V,P,G.U(F)),D=h0("month",D,1,G.L(F),B)}return U&&([F,D]=G._(F,D,U)),T=h0("day",T,1,G.j(F,D),B),G.q(F,D,T)})(this,$,W,z,j);else{if(!X&&!O)return $;Y=C0($)}return Y+=(7*X+O)*R0,y1(K6(Y))},dateUntil($,Z,J){if(J<=7){let O=0,G=A9({...$,...d0},{...Z,...d0});return J===7&&([O,G]=m1(G,7)),{...D0,weeks:O,days:G}}let j=this.h($),Y=this.h(Z),[W,z,X]=((O,G,K,Q,U,B,F)=>{let D=U-G,T=B-K,V=F-Q;if(D||T){let P=Math.sign(D||T),M=O.j(U,B),H=0;if(Math.sign(V)===-P){let S=M;[U,B]=O._(U,B,-P),D=U-G,T=B-K,M=O.j(U,B),H=P<0?-S:M}if(V=F-Math.min(Q,M)+H,D){let[S,_]=O.I(G,K),[L,I]=O.I(U,B);if(T=L-S||Number(I)-Number(_),Math.sign(T)===-P){let C=P<0&&-O.L(U);D=(U-=P)-G,T=B-Z6(S,_,O.U(U))+(C||O.L(U))}}}return[D,T,V]})(this,...j,...Y);return J===8&&(z+=this.J(W,j[0]),W=0),{...D0,years:W,months:z,days:X}},dateFromFields($,Z){let J=y(Z),j=t8(this,$),Y=e8(this,$,j,J),W=hY(this,$,Y,j,J);return Y0(y1(this.P(j,Y,W)),this.id||w)},yearMonthFromFields($,Z){let J=y(Z),j=t8(this,$),Y=e8(this,$,j,J);return K$(N2(this.P(j,Y,1)),this.id||w)},monthDayFromFields($,Z){let J=y(Z),j=!this.id,{monthCode:Y,year:W,month:z}=$,X,O,G,K,Q;if(Y!==void 0){[X,O]=k9(Y),Q=sY($,"day");let U=this.N(X,O,Q);if(!U)throw RangeError(cY);if([G,K]=U,z!==void 0&&z!==K)throw RangeError(wz);j&&(K=h0("month",K,1,D1,1),Q=h0("day",Q,1,P2(W!==void 0?W:G,K),J))}else{G=W===void 0&&j?JZ:t8(this,$),K=e8(this,$,G,J),Q=hY(this,$,K,G,J);let U=this.U(G);O=K===U,X=Y2(K,U);let B=this.N(X,O,Q);if(!B)throw RangeError(cY);[G,K]=B}return r3(y1(this.P(G,K,Q)),this.id||w)},fields($){return W2(this)&&$.includes("year")?[...$,...O2]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return $2(J,Z,qJ),W2(this)&&($2(J,Z,bG),this.id===ZZ&&$2(J,Z,vG,O2)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:NJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[j,Y]=this.I(Z,J);return((W,z)=>"M"+c0(W)+(z?"L":""))(j,Y)},dayOfWeek:VW,daysInWeek(){return 7}},CK={dayOfYear:NJ,h:FW,q:YZ},_K=Object.assign({},CK,{weekOfYear:b9,yearOfWeek:v9,R($){function Z(B){return(7-B<j?7:0)-B}function J(B){let F=TW(U+B),D=B||1,T=Z(nZ(O+F*D,7));return K=(F+(T-G)*D)/7}let j=this.id?1:4,Y=VW($),W=this.dayOfYear($),z=nZ(Y-1,7),X=W-1,O=nZ(z-X,7),G=Z(O),K,Q=Math.floor((X-G)/7)+1,U=$.isoYear;return Q?Q>J(0)&&(Q=1,U++):(Q=J(-1),U--),[Q,U,K]}}),HK={dayOfYear:NJ,h:j2,q:tZ,weekOfYear:b9,yearOfWeek:v9,R(){return[]}},DZ=YG(Object.assign({},lY,_K,{h:FW,ee($){return this.id===p6?MW($):this.id===ZZ?lG($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[JZ,$]},K:C2,U(){},L:DW,J:($)=>$*D1,j:P2,X:TW,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:YZ,_:($,Z,J)=>($+=Y6(J,D1),(Z+=B2(J,D1))<1?($--,Z+=D1):Z>D1&&($++,Z-=D1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},lY,HK,{h:j2,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=u3.call(this,$);return[Y2(Z,J),J===Z]},N($,Z,J){let[j,Y,W]=j2.call(this,{isoYear:JZ,isoMonth:D1,isoDay:31}),z=u3.call(this,j),X=Y===z;(q1($,Y2(Y,z))||q1(Number(Z),Number(X))||q1(J,W))===1&&j--;for(let O=0;O<100;O++){let G=j-O,K=u3.call(this,G),Q=Z6($,Z,K);if(Z===(Q===K)&&J<=mY.call(this,G,Q))return[G,Q]}},K($){let Z=d3.call(this,$);return Z>d3.call(this,$-1)&&Z>d3.call(this,$+1)},U:u3,L:l3,J($,Z){let J=Z+$,j=Math.sign($),Y=j<0?-1:0,W=0;for(let z=Z;z!==J;z+=j)W+=l3.call(this,z+Y);return W},j:mY,X:d3,P($,Z,J){return K6(tZ.call(this,$,Z,J))},q:tZ,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(w6);if(J<0)for(;Z<1;)Z+=l3.call(this,--$);else{let j;for(;Z>(j=l3.call(this,$));)Z-=j,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:j}=this.B(Z);return j[J]+1},day($){return this.O($).day}})),g1="numeric",TZ=["timeZoneName"],K7={month:g1,day:g1},aJ={year:g1,month:g1},rJ=Object.assign({},aJ,{day:g1}),tJ={hour:g1,minute:g1,second:g1},eJ=Object.assign({},rJ,tJ),xK=Object.assign({},eJ,{timeZoneName:"short"}),SK=Object.keys(aJ),AK=Object.keys(K7),fK=Object.keys(rJ),EK=Object.keys(tJ),$4=["dateStyle"],RK=SK.concat($4),bK=AK.concat($4),Z4=fK.concat($4,["weekday"]),D3=EK.concat(["dayPeriod","timeStyle"]),J4=Z4.concat(D3),vK=J4.concat(TZ),kK=TZ.concat(D3),wK=TZ.concat(Z4),qK=TZ.concat(["day","weekday"],D3),yK=TZ.concat(["year","weekday"],D3),gK={},j4=[N$(J4,eJ),D6],Q7=[N$(vK,xK),D6,0,($,Z)=>{let J=F0($.timeZone);if(Z&&F0(Z.timeZone)!==J)throw RangeError(yz);return J}],Y4=[N$(J4,eJ,TZ),C0],W4=[N$(Z4,rJ,kK),C0],z4=[N$(D3,tJ,wK),($)=>p1($)/j1],X4=[N$(RK,aJ,qK),C0,1],O4=[N$(bK,K7,yK),C0,1],iY;function z1($,Z,J,j,Y){function W(...O){if(!(this instanceof W))throw TypeError(vJ);D7(this,Z(...O))}function z(O,G){return Object.defineProperties(function(...K){return O.call(this,X(this),...K)},K2(G))}function X(O){let G=I0(O);if(!G||G.branding!==$)throw TypeError(vJ);return G}return Object.defineProperties(W.prototype,{...nY(l0(z,J)),...U$(l0(z,j)),...j6("Temporal."+$)}),Object.defineProperties(W,{...U$(Y),...K2($)}),[W,(O)=>{let G=Object.create(W.prototype);return D7(G,O),G},X]}function M7($){return $=$.concat("id").sort(),(Z)=>{if(!oY(Z,$))throw TypeError(qz);return Z}}function NZ($){if(I0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(bz);return $}function s6($,Z){let J={};for(let j in $)J[j]=({o:Y},W)=>{let z=I0(W)||{},{branding:X}=z,O=X===P$||Z.includes(X)?z:S0(W);return Y[j](O)};return J}function Q4($){let Z={};for(let J in $)Z[J]=(j)=>{let{calendar:Y}=j;return(W=Y,typeof W=="string"?DZ(W):(z=W,Object.assign(Object.create($Q),{i:z})))[J](j);var W,z};return Z}function r1(){throw TypeError(kz)}function V3({calendar:$}){return typeof $=="string"?new N4($):$}function U7($,Z){if(Z=J0(Z),Q0($)){let j=I0($);if(j&&j.branding===FZ)return y(Z),j;let Y=L7($);return CJ($8(Y||w),!Y,$,Z)}let J=Y9(DZ,$);return y(Z),J}function I7($,Z,J){return j=Z.call($,x0(U0(J))),d2(j3(j));var j}function n6($,Z=H7){let J=Object.keys(Z).sort(),j={};for(let Y of J)j[Y]=v(Z[Y],$,rz($[Y]));return j}function u($,Z){return typeof $=="string"?l6($):n6($,Z)}function z0($){return u($,K4)}function Y1($){if(Q0($)){let Z=I0($);if(Z)switch(Z.branding){case u6:return Z;case C1:return U0(Z.epochNanoseconds)}}return eW($)}function B7($,Z,J){let j=Z.l(Y1(J).epochNanoseconds,$);return j?x0(U0(j)):null}function l($){return Q0($)?(I0($)||{}).timeZone||zQ($):((Z)=>A6(O9(a(Z))))($)}function s1($,Z){if(Q0($)){let J=I0($)||{};switch(J.branding){case c6:return y(Z),J;case C$:return y(Z),n0(J);case C1:return y(Z),fJ(z0,J)}return h9($,Z)}return y(Z),W9($)}function U4($){return $===void 0?void 0:s1($)}function VZ($,Z){if(Z=J0(Z),Q0($)){let j=I0($);return j&&j.branding===BZ?(y(Z),j):PJ(t6(M3($)),$,Z)}let J=j9(DZ,$);return y(Z),J}function n1($,Z){if(Z=J0(Z),Q0($)){let j=I0($)||{};switch(j.branding){case C$:return y(Z),j;case P$:return y(Z),j0({...j,...d0});case C1:return y(Z),SJ(z0,j)}return p9(e6(M3($)),$,Z)}let J=J9($);return y(Z),J}function S0($,Z){if(Z=J0(Z),Q0($)){let j=I0($)||{};switch(j.branding){case P$:return y(Z),j;case C$:return y(Z),Y0(j);case C1:return y(Z),AJ(z0,j)}return LJ(e6(M3($)),$,Z)}let J=x6($);return y(Z),J}function N7($,Z,J){return i0(Z.call($,t(Y0(J,$))))}function X1($){return(Z)=>typeof Z=="string"?DZ(Z):((J,j)=>{let Y=Object.keys(j).sort(),W={};for(let z of Y)W[z]=v(j[z],J,J[z]);return W})(Z,$)}function r($){if(Q0($)){let Z=I0($);return Z&&Z.branding===d6?Z:c9($)}return z9($)}function T3($){if($!==void 0){if(Q0($)){let Z=I0($)||{};switch(Z.branding){case C1:case P$:return Z;case C$:return Y0(Z)}let J=M3($);return{...g9(l,u,e6(J),$),calendar:J}}return $9($)}}function M3($){return L7($)||w}function L7($){let{calendar:Z}=$;if(Z!==void 0)return M0(Z)}function M0($){return Q0($)?(I0($)||{}).calendar||LQ($):((Z)=>z3(X9(a(Z))))($)}function MZ($,Z){if(Z=J0(Z),Q0($)){let J=I0($);if(J&&J.branding===C1)return Y3(Z),J;let j=M3($);return m9(l,u,e6(j),j,$,Z)}return Z9($,Z)}function F7($){return l0((Z)=>(J)=>Z(G4(J)),$)}function G4($){return _0($,z0)}function mK(){let $=i1.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(i1),j=function(Y,W={}){if(!(this instanceof j))return new j(Y,W);L4.set(this,((z,X={})=>{let O=new i1(z,X),G=O.resolvedOptions(),K=G.locale,Q=k0(Object.keys(X),G),U=b0(cK),B=(...F)=>{let D,T=F.map((V,P)=>{let M=I0(V),H=(M||{}).branding;if(P&&D&&D!==H)throw TypeError(mz);return D=H,M});return D?U(D)(K,Q,...T):[O,...F]};return B.u=O,B})(Y,W))};for(let Y in Z){let W=Z[Y],z=Y.startsWith("format")&&pK(Y);typeof W.value=="function"?W.value=Y==="constructor"?j:z||hK(Y):z&&(W.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(j,J),j}function pK($){return function(...Z){let J=L4.get(this),[j,...Y]=J(...Z);return j[$](...Y)}}function hK($){return function(...Z){return L4.get(this).u[$](...Z)}}function cK($){let Z=uK[$];if(!Z)throw TypeError(gz($));return N1(Z,b0(EJ))}var uK={Instant:j4,PlainDateTime:Y4,PlainDate:W4,PlainTime:z4,PlainYearMonth:X4,PlainMonthDay:O4},dK=N1(j4),lK=N1(Q7),iK=N1(Y4),sK=N1(W4),nK=N1(z4),oK=N1(X4),aK=N1(O4),B4={era:JW,eraYear:F2,year:j3,month:i0,daysInMonth:i0,daysInYear:i0,inLeapYear:az,monthsInYear:i0},a6={monthCode:a},F4={day:i0},P7={dayOfWeek:i0,dayOfYear:i0,weekOfYear:jW,yearOfWeek:F2,daysInWeek:i0},C7=Object.assign({},B4,a6,F4,P7),o6=new WeakMap,I0=o6.get.bind(o6),D7=o6.set.bind(o6),rK={...s6(B4,[BZ]),...s6(P7,[]),...s6(a6,[BZ,FZ]),...s6(F4,[FZ])},D4=Q4(C7),tK=Q4({...B4,...a6}),eK=Q4({...a6,...F4}),I3={calendarId:($)=>F0($.calendar)},$Q=l0(($,Z)=>function(J){let{i:j}=this;return $(j[Z](t(Y0(J,j))))},C7),ZQ=Z3(($)=>(Z)=>Z[$],g.concat("sign")),T4=Z3(($,Z)=>(J)=>J[a0[Z]],P1),_7={epochSeconds:HW,epochMilliseconds:D6,epochMicroseconds:xW,epochNanoseconds:SW},N3=v(Q2,new Set(["branding"])),[JQ,IZ,jQ]=z1(FZ,v(Jz,M0),{...I3,...eK},{getISOFields:N3,getCalendar:V3,with($,Z,J){return IZ(s9(MQ,$,this,NZ(Z),J))},equals:($,Z)=>P9($,U7(Z)),toPlainDate($,Z){return t(Tz(L3,$,this,Z))},toLocaleString($,Z,J){let[j,Y]=aK(Z,J,$);return j.format(Y)},toString:m2,toJSON:($)=>m2($),valueOf:r1},{from:($,Z)=>IZ(U7($,Z))}),H7={getOffsetNanosecondsFor:I7,getPossibleInstantsFor($,Z,J){let j=[...Z.call($,V0(j0(J,w)))].map((W)=>WQ(W).epochNanoseconds),Y=j.length;return Y>1&&(j.sort(P0),l2(m0(g0(j[0],j[Y-1])))),j}},K4={getOffsetNanosecondsFor:I7},[YQ,x0,WQ]=z1(u6,r9,_7,{add:($,Z)=>x0(i2(0,$,r(Z))),subtract:($,Z)=>x0(i2(1,$,r(Z))),until:($,Z,J)=>d(BJ(0,$,Y1(Z),J)),since:($,Z,J)=>d(BJ(1,$,Y1(Z),J)),round:($,Z)=>x0(EW($,Z)),equals:($,Z)=>V9($,Y1(Z)),toZonedDateTime($,Z){let J=M1(Z);return W0(xJ($,l(J.timeZone),M0(J.calendar)))},toZonedDateTimeISO:($,Z)=>W0(xJ($,l(Z))),toLocaleString($,Z,J){let[j,Y]=dK(Z,J,$);return j.format(Y)},toString:($,Z)=>k2(l,z0,$,Z),toJSON:($)=>k2(l,z0,$),valueOf:r1},{from:($)=>x0(Y1($)),fromEpochSeconds:($)=>x0(Iz($)),fromEpochMilliseconds:($)=>x0(Nz($)),fromEpochMicroseconds:($)=>x0(Lz($)),fromEpochNanoseconds:($)=>x0(Pz($)),compare:($,Z)=>KJ(Y1($),Y1(Z))}),[r6,mD]=z1("TimeZone",($)=>{let Z=D9($);return{branding:"TimeZone",id:Z,o:l6(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(n1(Z)).map((J)=>x0(U0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(Y1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=Y1(Z).epochNanoseconds,j=n6(this,K4).getOffsetNanosecondsFor(J);return D$(j)},getPlainDateTimeFor($,Z,J=w){let j=Y1(Z).epochNanoseconds,Y=n6(this,K4).getOffsetNanosecondsFor(j);return V0(j0(c1(j,Y),M0(J)))},getInstantFor($,Z,J){let j=n1(Z),Y=_2(J),W=n6(this);return x0(U0(v0(W,j,Y)))},getNextTransition:({o:$},Z)=>B7(1,$,Z),getPreviousTransition:({o:$},Z)=>B7(-1,$,Z),equals($,Z){return!!E6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new r6(Z):Z}}),zQ=M7(Object.keys(H7)),[XQ,o1]=z1(c6,jz,T4,{getISOFields:N3,with($,Z,J){return o1(n9(this,NZ(Z),J))},add:($,Z)=>o1(r2(0,$,r(Z))),subtract:($,Z)=>o1(r2(1,$,r(Z))),until:($,Z,J)=>d(MJ(0,$,s1(Z),J)),since:($,Z,J)=>d(MJ(1,$,s1(Z),J)),round:($,Z)=>o1(vW($,Z)),equals:($,Z)=>C9($,s1(Z)),toZonedDateTime:($,Z)=>W0(Vz(l,S0,u,$,Z)),toPlainDateTime:($,Z)=>V0(Mz($,S0(Z))),toLocaleString($,Z,J){let[j,Y]=nK(Z,J,$);return j.format(Y)},toString:p2,toJSON:($)=>p2($),valueOf:r1},{from:($,Z)=>o1(s1($,Z)),compare:($,Z)=>f6(s1($),s1(Z))}),[OQ,a1,GQ]=z1(BZ,v(Zz,M0),{...I3,...tK},{getISOFields:N3,getCalendar:V3,with($,Z,J){return a1(i9(VQ,$,this,NZ(Z),J))},add:($,Z,J)=>a1(a2(T7,0,$,r(Z),J)),subtract:($,Z,J)=>a1(a2(T7,1,$,r(Z),J)),until:($,Z,J)=>d(VJ(V7,0,$,VZ(Z),J)),since:($,Z,J)=>d(VJ(V7,1,$,VZ(Z),J)),equals:($,Z)=>L9($,VZ(Z)),toPlainDate($,Z){return t(Dz(L3,$,this,Z))},toLocaleString($,Z,J){let[j,Y]=oK(Z,J,$);return j.format(Y)},toString:g2,toJSON:($)=>g2($),valueOf:r1},{from:($,Z)=>a1(VZ($,Z)),compare:($,Z)=>M$(VZ($),VZ(Z))}),[KQ,V0]=z1(C$,v(e9,M0),{...I3,...D4,...T4},{getISOFields:N3,getCalendar:V3,with($,Z,J){return V0(d9(L3,$,this,NZ(Z),J))},withCalendar:($,Z)=>V0(k6($,M0(Z))),withPlainDate:($,Z)=>V0(xz($,S0(Z))),withPlainTime:($,Z)=>V0(Hz($,U4(Z))),add:($,Z,J)=>V0(n2(H$,0,$,r(Z),J)),subtract:($,Z,J)=>V0(n2(H$,1,$,r(Z),J)),until:($,Z,J)=>d(DJ(W1,0,$,n1(Z),J)),since:($,Z,J)=>d(DJ(W1,1,$,n1(Z),J)),round:($,Z)=>V0(bW($,Z)),equals:($,Z)=>I9($,n1(Z)),toZonedDateTime:($,Z,J)=>W0(Oz(u,$,l(Z),J)),toPlainDate:($)=>t(Y0($)),toPlainTime:($)=>o1(n0($)),toPlainYearMonth($){return a1(Gz(t6,$,this))},toPlainMonthDay($){return IZ(Kz($8,$,this))},toLocaleString($,Z,J){let[j,Y]=iK(Z,J,$);return j.format(Y)},toString:q2,toJSON:($)=>q2($),valueOf:r1},{from:($,Z)=>V0(n1($,Z)),compare:($,Z)=>UJ(n1($),n1(Z))}),[QQ,t,x7]=z1(P$,v($z,M0),{...I3,...D4},{getISOFields:N3,getCalendar:V3,with($,Z,J){return t(l9(L3,$,this,NZ(Z),J))},withCalendar:($,Z)=>t(k6($,M0(Z))),add:($,Z,J)=>t(o2(H$,0,$,r(Z),J)),subtract:($,Z,J)=>t(o2(H$,1,$,r(Z),J)),until:($,Z,J)=>d(TJ(W1,0,$,S0(Z),J)),since:($,Z,J)=>d(TJ(W1,1,$,S0(Z),J)),equals:($,Z)=>N9($,S0(Z)),toZonedDateTime($,Z){let J=!Q0(Z)||Z instanceof r6?{timeZone:Z}:Z;return W0(Qz(l,s1,u,$,J))},toPlainDateTime:($,Z)=>V0(Uz($,U4(Z))),toPlainYearMonth($){return a1(Bz(t6,$,this))},toPlainMonthDay($){return IZ(Fz($8,$,this))},toLocaleString($,Z,J){let[j,Y]=sK(Z,J,$);return j.format(Y)},toString:y2,toJSON:($)=>y2($),valueOf:r1},{from:($,Z)=>t(S0($,Z)),compare:($,Z)=>M$(S0($),S0(Z))}),V4={fields($,Z,J){return[...Z.call($,J)]}},S7=Object.assign({dateFromFields($,Z,J,j){return x7(Z.call($,Object.assign(Object.create(null),J),j))}},V4),A7=Object.assign({yearMonthFromFields($,Z,J,j){return GQ(Z.call($,Object.assign(Object.create(null),J),j))}},V4),f7=Object.assign({monthDayFromFields($,Z,J,j){return jQ(Z.call($,Object.assign(Object.create(null),J),j))}},V4),M4={mergeFields($,Z,J,j){return M1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),j)))}},UQ=Object.assign({},S7,M4),BQ=Object.assign({},A7,M4),FQ=Object.assign({},f7,M4),I4={dateAdd($,Z,J,j,Y){return x7(Z.call($,t(Y0(J,$)),d(i(j)),Y))}},E7=Object.assign({},I4,{dateUntil($,Z,J,j,Y,W){return NQ(Z.call($,t(Y0(J,$)),t(Y0(j,$)),Object.assign(Object.create(null),W,{largestUnit:Q3[Y]})))}}),DQ=Object.assign({},I4,{day:N7}),TQ=Object.assign({},E7,{day:N7}),t6=X1(A7),e6=X1(S7),$8=X1(f7),VQ=X1(BQ),L3=X1(UQ),MQ=X1(FQ),H$=X1(I4),W1=X1(E7),T7=X1(DQ),V7=X1(TQ),[IQ,d,NQ]=z1(d6,Yz,{...ZQ,blank:aW},{with:($,Z)=>d(o9($,Z)),negated:($)=>d(_6($)),abs:($)=>d(oW($)),add:($,Z,J)=>d(JJ(T3,W1,u,0,$,r(Z),J)),subtract:($,Z,J)=>d(JJ(T3,W1,u,1,$,r(Z),J)),round:($,Z)=>d(nW(T3,W1,u,$,Z)),total:($,Z)=>fW(T3,W1,u,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):I6($)},toString:I6,toJSON:($)=>I6($),valueOf:r1},{from:($)=>d(r($)),compare:($,Z,J)=>T9(T3,H$,u,r($),r(Z),J)}),R7={toString:($)=>$.id,toJSON:($)=>$.id,...rK,dateAdd:({id:$,o:Z},J,j,Y)=>t(Y0(Z.dateAdd(S0(J),r(j),Y),$)),dateUntil:({o:$},Z,J,j)=>d(i($.dateUntil(S0(Z),S0(J),NW(j)))),dateFromFields:({id:$,o:Z},J,j)=>t(LJ(Z,J,j,ZW($))),yearMonthFromFields:({id:$,o:Z},J,j)=>a1(PJ(Z,J,j,eY($))),monthDayFromFields:({id:$,o:Z},J,j)=>IZ(CJ(Z,0,J,j,$W($))),fields({o:$},Z){let J=new Set(o0),j=[];for(let Y of Z){if(a(Y),!J.has(Y))throw RangeError(bJ(Y));J.delete(Y),j.push(Y)}return $.fields(j)},mergeFields:({o:$},Z,J)=>$.mergeFields(U2(D2(Z)),U2(D2(J)))},[N4]=z1("Calendar",($)=>{let Z=R9($);return{branding:"Calendar",id:Z,o:DZ(Z)}},{id:($)=>$.id},R7,{from($){let Z=M0($);return typeof Z=="string"?new N4(Z):Z}}),LQ=M7(Object.keys(R7).slice(4)),[PQ,W0]=z1(C1,v(t9,M0,l),{..._7,...I3,...F7(D4),...F7(T4),offset:($)=>D$(G4($).offsetNanoseconds),offsetNanoseconds:($)=>G4($).offsetNanoseconds,timeZoneId:($)=>F0($.timeZone),hoursInDay:($)=>kW(u,$)},{getISOFields:($)=>iW(z0,$),getCalendar:V3,getTimeZone:({timeZone:$})=>typeof $=="string"?new r6($):$,with($,Z,J){return W0(u9(L3,u,$,this,NZ(Z),J))},withCalendar:($,Z)=>W0(k6($,M0(Z))),withTimeZone:($,Z)=>W0(Sz($,l(Z))),withPlainDate:($,Z)=>W0(_z(u,$,S0(Z))),withPlainTime:($,Z)=>W0(Cz(u,$,U4(Z))),add:($,Z,J)=>W0(s2(H$,u,0,$,r(Z),J)),subtract:($,Z,J)=>W0(s2(H$,u,1,$,r(Z),J)),until:($,Z,J)=>d(i(FJ(W1,u,0,$,MZ(Z),J))),since:($,Z,J)=>d(i(FJ(W1,u,1,$,MZ(Z),J))),round:($,Z)=>W0(RW(u,$,Z)),startOfDay:($)=>W0(wW(u,$)),equals:($,Z)=>M9($,MZ(Z)),toInstant:($)=>x0(Wz($)),toPlainDateTime:($)=>V0(SJ(z0,$)),toPlainDate:($)=>t(AJ(z0,$)),toPlainTime:($)=>o1(fJ(z0,$)),toPlainYearMonth($){return a1(zz(t6,$,this))},toPlainMonthDay($){return IZ(Xz($8,$,this))},toLocaleString($,Z,J={}){let[j,Y]=lK(Z,J,$);return j.format(Y)},toString:($,Z)=>w2(z0,$,Z),toJSON:($)=>w2(z0,$),valueOf:r1},{from:($,Z)=>W0(MZ($,Z)),compare:($,Z)=>QJ(MZ($),MZ(Z))}),CQ=Object.defineProperties({},{...j6("Temporal.Now"),...U$({timeZoneId:()=>L1(),instant:()=>x0(U0(O3())),zonedDateTime:($,Z=L1())=>W0(T0(O3(),l(Z),M0($))),zonedDateTimeISO:($=L1())=>W0(T0(O3(),l($),w)),plainDateTime:($,Z=L1())=>V0(j0(QZ(z0(l(Z))),M0($))),plainDateTimeISO:($=L1())=>V0(j0(QZ(z0(l($))),w)),plainDate:($,Z=L1())=>t(Y0(QZ(z0(l(Z))),M0($))),plainDateISO:($=L1())=>t(Y0(QZ(z0(l($))),w)),plainTimeISO:($=L1())=>o1(n0(QZ(z0(l($)))))})}),LZ=Object.defineProperties({},{...j6("Temporal"),...U$({PlainYearMonth:OQ,PlainMonthDay:JQ,PlainDate:QQ,PlainTime:XQ,PlainDateTime:KQ,ZonedDateTime:PQ,Instant:YQ,Calendar:N4,TimeZone:r6,Duration:IQ,Now:CQ})}),_Q=mK(),L4=new WeakMap,HQ=Object.defineProperties(Object.create(Intl),U$({DateTimeFormat:_Q}));class P4 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class xQ{}import{createHash as C4,createHmac as SQ,randomBytes as b7,timingSafeEqual as w7}from"crypto";var _4=600,q7="gemi_oauth",AQ=`__Host-${q7}`;function H4($){return $?AQ:q7}function P3($){return $.toString("base64url")}function y7($){return SQ("sha256",o$()).update(`gemi-oauth-state:${$}`).digest()}function v7($,Z){let J=C4("sha256").update($).digest(),j=C4("sha256").update(Z).digest();return w7(J,j)&&$.length===Z.length}function g7($,Z=Date.now()){let J=P3(b7(32)),j=P3(b7(32)),Y=fQ(j),W={provider:$,state:J,codeVerifier:j,expiresAt:Z+_4*1000};return{state:J,codeVerifier:j,codeChallenge:Y,cookieValue:EQ(W)}}function fQ($){return P3(C4("sha256").update($).digest())}function EQ($){let Z=P3(Buffer.from(JSON.stringify($)));return`${Z}.${P3(y7(Z))}`}function RQ($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),j=Buffer.from($.slice(Z+1),"base64url"),Y=y7(J);if(j.length!==Y.length||!w7(j,Y))return null;try{let W=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof W?.provider!=="string"||typeof W?.state!=="string"||typeof W?.codeVerifier!=="string"||typeof W?.expiresAt!=="number")return null;return W}catch{return null}}var t1=new Map,k7=1e4;function bQ($,Z,J){if(t1.size>=k7){for(let[j,Y]of t1)if(Y<=J)t1.delete(j);while(t1.size>=k7){let j=t1.keys().next().value;if(j===void 0)break;t1.delete(j)}}t1.set($,Z)}function m7($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=RQ($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let j=v7(J.state,$.returnedState),Y=v7(J.provider,$.provider);if(!j||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(t1.has(J.state))return{ok:!1,reason:"invalid_state"};return bQ(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var x4=new WeakMap;function kQ($){let Z=x4.get($);if(!Z)Z=$(vQ(32).toString("hex")),x4.set($,Z),Z.catch(()=>x4.delete($));return Z}async function S4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await kQ($.hashPassword))}catch{}return!1}async function x$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:j,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class f4 extends Error{}function A4($){return typeof $==="string"&&$!==""?$:null}function p7($){return iZ($)}var wQ=256;function h7($){return typeof $==="string"&&$!==""&&$.length<=wQ?$:null}var Z8="intended_url";function u7($){if($.cookies.get(Z8))$.ctx().setCookie(Z8,"",{maxAge:-1})}function c7($){let Z=$.cookies.get(Z8);if(!Z)return null;u7($);try{return m$(decodeURIComponent(Z),"")||null}catch{return null}}class E4 extends f{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class d7 extends f{schema={email:{required:"Email is required",email:"Invalid email"}}}class l7 extends f{schema={password:{required:"Password is required",password:"Invalid password"}}}class s extends p8{async me(){let $=await S$.user();if(!$)throw new h8;return $}async verifyEmail($=new f){let Z=await $.input(),{userProvider:J}=N(E),j=A4(Z.get("token"));if(!j)return{email:null};let Y=await J.findUserByVerificationToken(j);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new f){let Z=N(E),{userProvider:J}=Z,j=A4($.search.get("token")),Y=null;try{Y=iZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await a$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!Y||!j||!await Z.verifyMagicLinkToken(Y,j))return{error:"Invalid token"};await J.verifyUser(Y);let W=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",W.token,N(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await x$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async verifyPinRequest($){let Z=N(E),J=await $.input(),{email:j,pin:Y}=J.toJSON(),W=iZ(j),z=h7(Y);if(await a$("verify",W,$,Z.config.emailCode.verifyLimit),!W||!z)throw new h({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(W,z);if(X.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(X.status!=="ok")throw new h({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(W),W}async signInWithPinV2($=new f){let Z=N(E),J=await this.verifyPinRequest($),j=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",j.token,N(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await x$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),j}async signInWithPin($=new f){let Z=N(E),J=await this.verifyPinRequest($),j=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",j.token,N(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await x$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async signInV2($=new E4){let Z=await $.input(),{email:J,password:j}=Z.toJSON(),Y=J.toLowerCase().trim(),W=N(E),z=await W.userProvider.findUserByEmailAddress(Y,W.config.verifyEmail),X=typeof j==="string"&&await S4(W.config,j,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let O=await W.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",O.token,N(E).accessTokenCookieOptions($,O.expiresAt)),await W.config.onSignIn(z,$.search.toJSON()),await x$(W.config,{session:O,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signIn($=new E4){let Z=await $.input(),{email:J,password:j}=Z.toJSON(),Y=J.toLowerCase().trim(),W=N(E),z=await W.userProvider.findUserByEmailAddress(Y,W.config.verifyEmail),X=typeof j==="string"&&await S4(W.config,j,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let O=await W.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",O.token,N(E).accessTokenCookieOptions($,O.expiresAt)),await W.config.onSignIn(z,$.search.toJSON()),await x$(W.config,{session:O,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signUp(){let $=N(E),{userProvider:Z,config:J}=$,j=new J.signUpRequest,Y=await j.input(),{email:W,password:z,name:X,invitationId:O}=Y.toJSON(),G=p7(W);if(!G)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(O!=null&&typeof O!=="string")throw new h({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(G,!1))throw new h({email:["Email address already exists"]});let Q=await J.hashPassword(z),U=N(o).detectLocale(j),B;if(O)B=await Z.findInvitation(O,G);let F,D="";if(B)F=await Z.transaction(async()=>{await Z.deleteInvitationById(O);let T=await Z.createUser({email:G,name:X,password:Q,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:B.organizationId,userId:T.id,organizationRole:B.role}),await J.onUserCreated(T),T});else D=await J.generateEmailVerificationToken(G),F=await Z.transaction(async()=>{let T=await Z.createUser({email:G,name:X,password:Q,verificationToken:D,locale:U});return await J.onUserCreated(T),T});return await J.onSignUp(F,D,j.search.toJSON()),F}async signOut($=new f){let Z=y8($),J=N(E),{config:j}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",N(E).accessTokenCookieOptions($,new Date(0))),N(E).cookieDomain($))$.ctx().setCookie("access_token","",{...N(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)Y.user.extension=await j.extendSession(Y.user),await j.onSignOut(Y.user);return{}}async forgotPassword($=new d7){let Z=await $.input(),J=p7(Z.get("email"));if(!J)return{};let{userProvider:j,config:Y}=N(E),W=await j.findUserByEmailAddress(J,Y.verifyEmail);if(!W)return{};let z=await Y.generateForgotPasswordToken(W);return await j.createPasswordResetToken({user:W,token:z}),await Y.onForgotPassword(W,z),{}}async resetPassword($=new l7){let{userProvider:Z,config:J}=N(E),j=await $.input(),{password:Y,token:W}=j.toJSON(),z=A4(W),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new h({token:["Invalid token"]});if(LZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(LZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new h({email:["User not found"]});let K=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:K}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new f){let{userProvider:Z,config:J}=N(E),j=await S$.user(),Y=await $.input(),{oldPassword:W,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(j.email,J.verifyEmail);if(!(typeof W==="string"&&await S4(J,W,X?.password)))throw new h({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:j.id,password:G}),await Z.deleteAllUserSessions(j.id),{}}async oauthRedirect($=new f){let{provider:Z}=$.params,J=N(E).config.oauthProviders[Z];if(!J)throw Error(`Invalid provider: ${Z}`);let j=q8($.rawRequest),Y=m$($.search.get(Y$),"");if(Y)$.ctx().setCookie(Z8,encodeURIComponent(Y),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else u7($);let{state:W,codeChallenge:z,cookieValue:X}=g7(Z);return $.ctx().setCookie(H4(j),X,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:_4}),{destination:await J.getRedirectUrl($,{state:W,codeChallenge:z,codeChallengeMethod:"S256"})}}async oauthCallback($=new f){let{provider:Z}=$.params,J=N(E),{userProvider:j,config:Y}=J,W=Y.oauthProviders[Z],z=q8($.rawRequest),X=H4(z),O=$.cookies.get(X);if(O!==void 0&&O!==null)$.ctx().setCookie(X,"",{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:-1});if(!W)return this.oauthFailure($,"unknown_provider");let G=$.search.get("error");if(G)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(G)?G:"provider_error");let K=m7({provider:Z,cookieValue:O,returnedState:$.search.get("state")});if("reason"in K)return console.error(`Authentication error: OAuth callback refused (${K.reason})`),this.oauthFailure($,K.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let Q;try{Q=await W.onCallback($,{state:K.payload.state,codeVerifier:K.payload.codeVerifier})}catch(_){if(_ instanceof P4)return this.oauthFailure($,_.code);return console.error("Authentication error: OAuth provider callback failed",_),this.oauthFailure($,"provider_error")}let{name:U,username:B,providerId:F,emailVerified:D}=Q??{},T=typeof Q?.email==="string"?Q.email:void 0,V=T?p3(T):null,P=F?await j.findUserBySocialAccount(Z,F):null,M="signin";if(!P){if(!V)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,T?"invalid_email":F?"missing_email":"no_identity");if(D===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let _=N(o).detectLocale($);try{let L=await this.linkOAuthAccount({provider:Z,providerId:F,email:V,rawEmail:T,name:U,username:B,locale:_});if(L)P=L.user,M=L.action}catch(L){let I=F?await j.findUserBySocialAccount(Z,F):null;if(!I)throw L;P=I}if(!P)return this.oauthFailure($,"account_conflict")}let H=await J.createOrUpdateSessionV2({email:P.email,id:P.id});if($.ctx().setCookie("access_token",H.token,N(E).accessTokenCookieOptions($,H.expiresAt)),M==="signup")await Y.onSignUp(P,"",$.search.toJSON());else await Y.onSignIn(P,$.search.toJSON());await x$(J.config,{session:H,user:P,isNewUser:M==="signup",method:"oauth",req:$});let S=c7($)??Y.redirectPath;return{session:H,redirectTo:S}}oauthFailure($,Z){let J=c7($),j=N(E).config.oauthFailurePath;if(j){let Y=m$(j,"");if(Y){let W=new URL(Y,"http://gemi.invalid");if(W.searchParams.set("error",Z),J)W.searchParams.set(Y$,J);y$.external(`${W.pathname}${W.search}${W.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(j)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:j,rawEmail:Y,name:W,username:z,locale:X}=$,{userProvider:O,config:G}=N(E),K=(F)=>({provider:Z,userId:F,email:j,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),Q=await O.findUserByEmailAddress(j,!1),U=Y?.trim();if(!Q&&U&&U!==j)Q=await O.findUserByEmailAddress(U,!1);if(Q){if(!J)return{user:Q,action:"signin"};let F=await O.findSocialAccounts(Q.id,Z);if(F.some((T)=>T.providerId===J))return{user:Q,action:"signin"};if(F.some((T)=>T.providerId))return console.error(`Authentication error: user ${Q.id} is already linked to a different ${Z} account`),null;let D=F[0];if(D){if(!await O.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await O.createSocialAccount(K(Q.id));return{user:Q,action:"signin"}}return{user:await O.transaction(async()=>{let F=await O.createUser({email:j,name:W,locale:X,emailVerifiedAt:new Date});if(J)await O.createSocialAccount(K(F.id));return await G.onUserCreated(F),F}),action:"signup"}}async createMagicLinkToken($=new f){let Z=await $.input(),J=iZ(Z.get("email")),j=N(E),{uniformMagicLinkResponse:Y,requestLimit:W}=j.config.emailCode;if(await a$("request",J,$,W),!J)return{email:null};let{user:z,pin:X,token:O}=await j.createMagicLinkToken(J);if(z)return await j.config.onMagicLinkCreated(z,{email:J,pin:X,token:O}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new f){let Z=N(E),J=Z.config.emailCode;if(!J.enabled)throw new y0("Not found",{status:404});let j=await $.input(),Y=p3(j.get("email"));if(await a$("request",Y,$,J.requestLimit),!Y)throw new h({email:["Invalid email"]});let W=await Z.userProvider.findUserByEmailAddress(Y,!1);if(W||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!W,req:$})}return{ok:!0}}async verifyEmailCode($=new f){let Z=N(E),{userProvider:J,config:j}=Z;if(!j.emailCode.enabled)throw new y0("Not found",{status:404});let Y=await $.input(),{email:W,code:z,name:X}=Y.toJSON(),O=p3(W),G=h7(z);if(await a$("verify",O,$,j.emailCode.verifyLimit),!O||!G)throw new h({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(O,G,{claim:!1});if(K.status==="too_many_attempts")throw new h({code:["too_many_attempts"]});if(K.status!=="ok")throw new h({code:["invalid_code"]});let Q=K.row,U=await J.findUserByEmailAddress(O,!1),B=!1;if(U){if(!await J.claimMagicLinkToken(Q.id))throw new h({code:["invalid_code"]});await J.verifyUser(O)}else if(j.emailCode.createUser){let D=N(o).detectLocale($);try{U=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(Q.id))throw new f4;let T=await J.createUser({email:O,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await j.onUserCreated(T),T}),B=!0}catch(T){if(T instanceof f4)throw new h({code:["invalid_code"]});throw T}}else throw await J.claimMagicLinkToken(Q.id),new h({code:["invalid_code"]});let F=await Z.createOrUpdateSessionV2({email:O,id:U.id});return $.ctx().setCookie("access_token",F.token,N(E).accessTokenCookieOptions($,F.expiresAt)),await j.onSignIn(F,$.search.toJSON()),await x$(Z.config,{session:F,isNewUser:B,method:"email-code",req:$}),{session:F,isNewUser:B}}}class i7 extends R1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[s,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[s,"oauthCallback"])}}class R4 extends R1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[s,"signInWithMagicLink"]),"/oauth":i7}}class b4 extends A0{middlewares=["cache:private"];routes={"/sign-in":this.post(s,"signIn"),"/sign-in-v2":this.post(s,"signInV2"),"/sign-up":this.post(s,"signUp"),"/sign-out":this.post(s,"signOut"),"/forgot-password":this.post(s,"forgotPassword"),"/reset-password":this.post(s,"resetPassword"),"/change-password":this.post(s,"changePassword"),"/verify-email":this.post(s,"verifyEmail"),"/me":this.get(s,"me").middleware(["auth"]),"/magic-link":this.post(s,"createMagicLinkToken"),"/sign-in-with-pin":this.post(s,"signInWithPin"),"/sign-in-with-pin-v2":this.post(s,"signInWithPinV2"),"/email-code":this.post(s,"requestEmailCode"),"/email-code/verify":this.post(s,"verifyEmailCode")}}class v4 extends A0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new f().params.locale;return await N(o).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new f,Z=`/${$.params.scope??""}`,J=$.params.locale,j=N(o),Y=J??j.detectLocale($),W=j.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:W}})}}class k4{}class w4 extends k4{async resize($,Z){let{height:J,width:j,quality:Y,fit:W}=Z;return await(await J8("The Sharp image optimization driver"))($).resize(j>0?j:void 0,J>0?J:void 0,{fit:W}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function HT($){return $}function s7(){return{driver:new w4}}class q4 extends A0{routes={"/resize":this.file(async()=>{let $=new f,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),j=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),W=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let O=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,G=await fetch(O);if(!G.ok)return new Response(JSON.stringify({error:"Image not found",info:O}),{headers:{"Content-Type":"application/json"},status:404});let K=Buffer.from(await G.arrayBuffer()),Q=await N(n7).resize(K,{height:Y,width:j,fit:W,quality:z});G.headers.delete("Content-Type"),G.headers.delete("Content-Length");let U=new Headers(G.headers);return U.set("Content-Type","image/webp"),U.set("Content-Length",`${Q.byteLength}`),new Response(new Uint8Array(Q),{headers:U})})}}class n7{static token="image";driver;constructor($={}){this.driver=$.driver??s7().driver}resize($,Z){return this.driver.resize($,Z)}}class y4 extends A0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(N(o7).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function qQ($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[j,Y=""]=J.split(":");if(j.startsWith("-")){if(Z.has(j.replace("-","")))Z.delete(j.replace("-",""))}else Z.set(j,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var yQ={"body-limit":q3};class PZ{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:yZ($.bodyLimit)}get aliases(){return{...yQ,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!bj($))v3($,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 f,J=this.aliases,j=[];for(let[Y,W]of qQ($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);j.push({run:()=>X.run.call(X,...W),runsOnRefusal:a7(z)})}}else if(R3(Y)){let z=new Y(Z);j.push({run:z.run.bind(z),runsOnRefusal:a7(Y)})}else j.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let W=0;W<j.length;W++)try{Y={...Y,...await j[W].run()}}catch(z){throw await gQ(j.slice(W+1)),z}return Y})()}}function a7($){return $?.runsOnRefusal===!0}async function gQ($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}function hT($){return $}function r7(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function t7(){return{partialRendering:!0,localeRouting:"prefix",onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function mQ($){return"run"in $}function pQ($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function hQ($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function cQ($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function uQ($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function e7($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function g4($,Z="",J=[]){let j={};function Y(W,z,X,O,G){let K=W==="/"?"":W,Q=Z==="/"?"":Z,U=(`${Q}${K}`===""?"/":`${Q}${K}`).replaceAll("//","/");if(!j[U])j[U]={};j[U][z.toUpperCase()]={exec:X,middleware:[...J,...O],...G?{source:G}:{}},j[U].OPTIONS={exec:()=>{let F=new f().ctx().headers;return new Response(null,{headers:F,status:204})},middleware:[]}}for(let[W,z]of Object.entries($)){if(uQ(z)){let X=z;for(let O of["GET","POST","PUT","DELETE"])Y(W,O,X.run.bind(X),X.middlewares);continue}if(mQ(z)){let X=z,O=X.method,G=X.middlewares,K=X.run.bind(X);if(Y(W,O,K,G,X.source),e7(z))Y(W,"HEAD",K,G,X.source)}if(pQ(z))for(let[X,O]of Object.entries(z)){let G=O,K=G.middlewares,Q=G.run.bind(G);if(Y(W,X,Q,K,G.source),X==="get"&&e7(G))Y(W,"HEAD",Q,K,G.source)}if(cQ(z)){let X=new z,O=g4(X.routes,`${Z}${W}`,X.middlewares);for(let[G,K]of Object.entries(O))j[G.replaceAll("//","/")]=K}if(hQ(z)){let{first:X,second:O}=z;for(let[G,K]of Object.entries(X)){let Q=K.middlewares,U=K.run.bind(K),[B,...F]=W.split("/").reverse();if(!B.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(F.reverse().join("/"),G,U,Q,K.source)}for(let[G,K]of Object.entries(O)){let Q=K.middlewares,U=K.run.bind(K);Y(W,G,U,Q,K.source)}}}return Object.fromEntries(Object.entries(j).sort(([W],[z])=>{let X=W.split("/").length+W.split(":").length,O=z.split("/").length+z.split(":").length;return X-O}))}function j8($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function m4($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function p4($){let Z=j8($);return Z.length>1?Z.replace(/\/$/,""):Z}function $5($,Z){return Z.map((J)=>({...J,path:p4(m4($,J.path))}))}function Y8($){let Z={};for(let[J,j]of Object.entries($))if("run"in j){let Y=j;if("children"in Y){let W=new Y.children,z=Y8(W.routes);for(let[X,{exec:O,middleware:G,segments:K,features:Q,static:U}]of Object.entries(z)){let B=m4(J,X),F=(D)=>Y.run.call(Y,D,J);Z[j8(B)]={exec:[F,...O],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...Q],viewPath:Y.viewPath,segments:[{path:p4(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...$5(J,K)],...U?{static:U}:{}}}}else{let W=(z)=>Y.run.call(Y,z,J);Z[j8(J)]={exec:[W],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:p4(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new j,W=Y8(Y.routes);for(let[z,{exec:X,middleware:O,viewPath:G,segments:K,features:Q,static:U}]of Object.entries(W)){let B=m4(J,z);Z[j8(B)]={exec:X,middleware:[...Y.middlewares,...O],features:[...Y.featureGates,...Q],viewPath:G,segments:$5(J,K),...U?{static:U}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[j])=>{let Y=J.split("/").length+J.split(":").length,W=j.split("/").length+j.split(":").length;return Y-W}))}var dQ=Object.defineProperty,x=($,Z)=>dQ($,"name",{value:Z,configurable:!0}),HZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,j,Y,W){this.type=$,this.name=Z,this.prefix=J,this.value=j,this.suffix=Y,this.modifier=W}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};x(HZ,"Part");var lQ=/[$_\p{ID_Start}]/u,iQ=/[$_\u200C\u200D\p{ID_Continue}]/u,c4=".*";function Z5($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}x(Z5,"isASCII");function l4($,Z=!1){let J=[],j=0;for(;j<$.length;){let Y=$[j],W=x(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:j,value:$[j++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:j,value:$[j++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:j,value:$[j++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:j++,value:$[j++]});continue}if(Y==="{"){J.push({type:"OPEN",index:j,value:$[j++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:j,value:$[j++]});continue}if(Y===":"){let z="",X=j+1;for(;X<$.length;){let O=$.substr(X,1);if(X===j+1&&lQ.test(O)||X!==j+1&&iQ.test(O)){z+=$[X++];continue}break}if(!z){W(`Missing parameter name at ${j}`);continue}J.push({type:"NAME",index:j,value:z}),j=X;continue}if(Y==="("){let z=1,X="",O=j+1,G=!1;if($[O]==="?"){W(`Pattern cannot start with "?" at ${O}`);continue}for(;O<$.length;){if(!Z5($[O],!1)){W(`Invalid character '${$[O]}' at ${O}.`),G=!0;break}if($[O]==="\\"){X+=$[O++]+$[O++];continue}if($[O]===")"){if(z--,z===0){O++;break}}else if($[O]==="("&&(z++,$[O+1]!=="?")){W(`Capturing groups are not allowed at ${O}`),G=!0;break}X+=$[O++]}if(G)continue;if(z){W(`Unbalanced pattern at ${j}`);continue}if(!X){W(`Missing pattern at ${j}`);continue}J.push({type:"REGEX",index:j,value:X}),j=O;continue}J.push({type:"CHAR",index:j,value:$[j++]})}return J.push({type:"END",index:j,value:""}),J}x(l4,"lexer");function i4($,Z={}){let J=l4($);Z.delimiter??="/#?",Z.prefixes??="./";let j=`[^${w0(Z.delimiter)}]+?`,Y=[],W=0,z=0,X="",O=new Set,G=x((M)=>{if(z<J.length&&J[z].type===M)return J[z++].value},"tryConsume"),K=x(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),Q=x((M)=>{let H=G(M);if(H!==void 0)return H;let{type:S,index:_}=J[z];throw TypeError(`Unexpected ${S} at ${_}, expected ${M}`)},"mustConsume"),U=x(()=>{let M="",H;for(;H=G("CHAR")??G("ESCAPED_CHAR");)M+=H;return M},"consumeText"),B=x((M)=>M,"DefaultEncodePart"),F=Z.encodePart||B,D="",T=x((M)=>{D+=M},"appendToPendingFixedValue"),V=x(()=>{D.length&&(Y.push(new HZ(3,"","",F(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),P=x((M,H,S,_,L)=>{let I=3;switch(L){case"?":I=1;break;case"*":I=0;break;case"+":I=2;break}if(!H&&!S&&I===3){T(M);return}if(V(),!H&&!S){if(!M)return;Y.push(new HZ(3,"","",F(M),"",I));return}let C;S?S==="*"?C=c4:C=S:C=j;let b=2;C===j?(b=1,C=""):C===c4&&(b=0,C="");let m;if(H?m=H:S&&(m=W++),O.has(m))throw TypeError(`Duplicate name '${m}'.`);O.add(m),Y.push(new HZ(b,m,F(M),C,F(_),I))},"addPart");for(;z<J.length;){let M=G("CHAR"),H=G("NAME"),S=G("REGEX");if(!H&&!S&&(S=G("ASTERISK")),H||S){let L=M??"";Z.prefixes.indexOf(L)===-1&&(T(L),L=""),V();let I=K();P(L,H,S,"",I);continue}let _=M??G("ESCAPED_CHAR");if(_){T(_);continue}if(G("OPEN")){let L=U(),I=G("NAME"),C=G("REGEX");!I&&!C&&(C=G("ASTERISK"));let b=U();Q("CLOSE");let m=K();P(L,I,C,b,m);continue}V(),Q("END")}return Y}x(i4,"parse");function w0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(w0,"escapeString");function u4($){return $&&$.ignoreCase?"ui":"u"}x(u4,"flags");function J5($,Z,J){return s4(i4($,J),Z,J)}x(J5,"stringToRegexp");function A$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}x(A$,"modifierToString");function s4($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let j=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?j+=w0(X.value):j+=`(?:${w0(X.value)})${A$(X.modifier)}`;continue}Z&&Z.push(X.name);let O=`[^${w0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=O:X.type===0&&(G=c4),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?j+=`(${G})${A$(X.modifier)}`:j+=`((?:${G})${A$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){j+=`(?:${w0(X.prefix)}(${G})${w0(X.suffix)})`,j+=A$(X.modifier);continue}j+=`(?:${w0(X.prefix)}`,j+=`((?:${G})(?:`,j+=w0(X.suffix),j+=w0(X.prefix),j+=`(?:${G}))*)${w0(X.suffix)})`,X.modifier===0&&(j+="?")}let Y=`[${w0(J.endsWith)}]|$`,W=`[${w0(J.delimiter)}]`;if(J.end)return J.strict||(j+=`${W}?`),J.endsWith.length?j+=`(?=${Y})`:j+="$",new RegExp(j,u4(J));J.strict||(j+=`(?:${W}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(j+=`(?=${W}|${Y})`),new RegExp(j,u4(J))}x(s4,"partsToRegexp");var $$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},sQ={delimiter:".",prefixes:"",sensitive:!0,strict:!0},nQ={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function j5($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}x(j5,"isAbsolutePathname");function n4($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}x(n4,"maybeStripPrefix");function Y5($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}x(Y5,"maybeStripSuffix");function o4($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}x(o4,"treatAsIPv6Hostname");var W5=["ftp","file","http","https","ws","wss"];function a4($){if(!$)return!0;for(let Z of W5)if($.test(Z))return!0;return!1}x(a4,"isSpecialScheme");function z5($,Z){if($=n4($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}x(z5,"canonicalizeHash");function X5($,Z){if($=n4($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}x(X5,"canonicalizeSearch");function O5($,Z){return Z||$===""?$:o4($)?e4($):t4($)}x(O5,"canonicalizeHostname");function G5($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}x(G5,"canonicalizePassword");function K5($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}x(K5,"canonicalizeUsername");function Q5($,Z,J){if(J||$==="")return $;if(Z&&!W5.includes(Z))return new URL(`${Z}:${$}`).pathname;let j=$[0]=="/";return $=new URL(j?$:"/-"+$,"https://example.com").pathname,j||($=$.substring(2,$.length)),$}x(Q5,"canonicalizePathname");function U5($,Z,J){return r4(Z)===$&&($=""),J||$===""?$:$j($)}x(U5,"canonicalizePort");function B5($,Z){return $=Y5($,":"),Z||$===""?$:W8($)}x(B5,"canonicalizeProtocol");function r4($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}x(r4,"defaultPortForProtocol");function W8($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}x(W8,"protocolEncodeCallback");function F5($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}x(F5,"usernameEncodeCallback");function D5($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}x(D5,"passwordEncodeCallback");function t4($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}x(t4,"hostnameEncodeCallback");function e4($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}x(e4,"ipv6HostnameEncodeCallback");function $j($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}x($j,"portEncodeCallback");function T5($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}x(T5,"standardURLPathnameEncodeCallback");function V5($){return $===""?$:new URL(`data:${$}`).pathname}x(V5,"pathURLPathnameEncodeCallback");function M5($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}x(M5,"searchEncodeCallback");function I5($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}x(I5,"hashEncodeCallback");var N5=class{#Y;#Z=[];#J={};#$=0;#W=1;#G=0;#X=0;#B=0;#F=0;#D=!1;constructor($){this.#Y=$}get result(){return this.#J}parse(){for(this.#Z=l4(this.#Y,!0);this.#$<this.#Z.length;this.#$+=this.#W){if(this.#W=1,this.#Z[this.#$].type==="END"){if(this.#X===0){this.#I(),this.#K()?this.#j(9,1):this.#Q()?this.#j(8,1):this.#j(7,0);continue}else if(this.#X===2){this.#U(5);continue}this.#j(10,0);break}if(this.#B>0)if(this.#x())this.#B-=1;else continue;if(this.#H()){this.#B+=1;continue}switch(this.#X){case 0:this.#N()&&this.#U(1);break;case 1:if(this.#N()){this.#f();let $=7,Z=1;this.#P()?($=2,Z=3):this.#D&&($=2),this.#j($,Z)}break;case 2:this.#V()?this.#U(3):(this.#M()||this.#Q()||this.#K())&&this.#U(5);break;case 3:this.#C()?this.#j(4,1):this.#V()&&this.#j(5,1);break;case 4:this.#V()&&this.#j(5,1);break;case 5:this.#S()?this.#F+=1:this.#A()&&(this.#F-=1),this.#_()&&!this.#F?this.#j(6,1):this.#M()?this.#j(7,0):this.#Q()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 6:this.#M()?this.#j(7,0):this.#Q()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 7:this.#Q()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 8:this.#K()&&this.#j(9,1);break;case 9:break;case 10:break}}this.#J.hostname!==void 0&&this.#J.port===void 0&&(this.#J.port="")}#j($,Z){switch(this.#X){case 0:break;case 1:this.#J.protocol=this.#O();break;case 2:break;case 3:this.#J.username=this.#O();break;case 4:this.#J.password=this.#O();break;case 5:this.#J.hostname=this.#O();break;case 6:this.#J.port=this.#O();break;case 7:this.#J.pathname=this.#O();break;case 8:this.#J.search=this.#O();break;case 9:this.#J.hash=this.#O();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#J.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#J.pathname??=this.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#J.search??="")),this.#L($,Z)}#L($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#W=0}#I(){this.#$=this.#G,this.#W=0}#U($){this.#I(),this.#X=$}#T($){return $<0&&($=this.#Z.length-$),$<this.#Z.length?this.#Z[$]:this.#Z[this.#Z.length-1]}#z($,Z){let J=this.#T($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#N(){return this.#z(this.#$,":")}#P(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#V(){return this.#z(this.#$,"@")}#C(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#Q(){if(this.#z(this.#$,"?"))return!0;if(this.#Z[this.#$].value!=="?")return!1;let $=this.#T(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#H(){return this.#Z[this.#$].type=="OPEN"}#x(){return this.#Z[this.#$].type=="CLOSE"}#S(){return this.#z(this.#$,"[")}#A(){return this.#z(this.#$,"]")}#O(){let $=this.#Z[this.#$],Z=this.#T(this.#G).index;return this.#Y.substring(Z,$.index)}#f(){let $={};Object.assign($,$$),$.encodePart=W8;let Z=J5(this.#O(),void 0,$);this.#D=a4(Z)}};x(N5,"Parser");var h4=["protocol","username","password","hostname","port","pathname","search","hash"],e1="*";function d4($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}x(d4,"extractValues");function O1($,Z){return Z?_Z($):$}x(O1,"processBaseURLString");function CZ($,Z,J){let j;if(typeof Z.baseURL=="string")try{j=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=O1(j.protocol.substring(0,j.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=O1(j.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=O1(j.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=O1(j.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=O1(j.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=O1(j.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=O1(j.search.substring(1,j.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=O1(j.hash.substring(1,j.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=B5(Z.protocol,J)),typeof Z.username=="string"&&($.username=K5(Z.username,J)),typeof Z.password=="string"&&($.password=G5(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=O5(Z.hostname,J)),typeof Z.port=="string"&&($.port=U5(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,j&&!j5($.pathname,J)){let Y=j.pathname.lastIndexOf("/");Y>=0&&($.pathname=O1(j.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=Q5($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=X5(Z.search,J)),typeof Z.hash=="string"&&($.hash=z5(Z.hash,J)),$}x(CZ,"applyInit");function _Z($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}x(_Z,"escapePatternString");function L5($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(L5,"escapeRegexpString");function P5($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",j=`[^${L5(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,W="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){W+=_Z(X.value);continue}W+=`{${_Z(X.value)}}${A$(X.modifier)}`;continue}let O=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),K=z>0?$[z-1]:null,Q=z<$.length-1?$[z+1]:null;if(!G&&O&&X.type===1&&X.modifier===3&&Q&&!Q.prefix.length&&!Q.suffix.length)if(Q.type===3){let U=Q.value.length>0?Q.value[0]:"";G=Y.test(U)}else G=!Q.hasCustomName();if(!G&&!X.prefix.length&&K&&K.type===3){let U=K.value[K.value.length-1];G=Z.prefixes.includes(U)}G&&(W+="{"),W+=_Z(X.prefix),O&&(W+=`:${X.name}`),X.type===2?W+=`(${X.value})`:X.type===1?O||(W+=`(${j})`):X.type===0&&(!O&&(!K||K.type===3||K.modifier!==3||G||X.prefix!=="")?W+="*":W+=`(${J})`),X.type===1&&O&&X.suffix.length&&Y.test(X.suffix[0])&&(W+="\\"),W+=_Z(X.suffix),G&&(W+="}"),X.modifier!==3&&(W+=A$(X.modifier))}return W}x(P5,"partsToPattern");var Zj=class{#Y;#Z={};#J={};#$={};#W={};#G=!1;constructor($={},Z,J){try{let j;if(typeof Z=="string"?j=Z:J=Z,typeof $=="string"){let X=new N5($);if(X.parse(),$=X.result,j===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=j}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(j)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},W={pathname:e1,protocol:e1,username:e1,password:e1,hostname:e1,port:e1,search:e1,hash:e1};this.#Y=CZ(W,$,!0),r4(this.#Y.protocol)===this.#Y.port&&(this.#Y.port="");let z;for(z of h4){if(!(z in this.#Y))continue;let X={},O=this.#Y[z];switch(this.#J[z]=[],z){case"protocol":Object.assign(X,$$),X.encodePart=W8;break;case"username":Object.assign(X,$$),X.encodePart=F5;break;case"password":Object.assign(X,$$),X.encodePart=D5;break;case"hostname":Object.assign(X,sQ),o4(O)?X.encodePart=e4:X.encodePart=t4;break;case"port":Object.assign(X,$$),X.encodePart=$j;break;case"pathname":a4(this.#Z.protocol)?(Object.assign(X,nQ,Y),X.encodePart=T5):(Object.assign(X,$$,Y),X.encodePart=V5);break;case"search":Object.assign(X,$$,Y),X.encodePart=M5;break;case"hash":Object.assign(X,$$,Y),X.encodePart=I5;break}try{this.#W[z]=i4(O,X),this.#Z[z]=s4(this.#W[z],this.#J[z],X),this.#$[z]=P5(this.#W[z],X),this.#G=this.#G||this.#W[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#Y[z]}'.`)}}}catch(j){throw TypeError(`Failed to construct 'URLPattern': ${j.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=CZ(J,$,!1):J=CZ(J,d4($,Z),!1)}catch{return!1}let j;for(j of h4)if(!this.#Z[j].exec(J[j]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=CZ(J,$,!1):J=CZ(J,d4($,Z),!1)}catch{return null}let j={};Z?j.inputs=[$,Z]:j.inputs=[$];let Y;for(Y of h4){let W=this.#Z[Y].exec(J[Y]);if(!W)return null;let z={};for(let[X,O]of this.#J[Y].entries())if(typeof O=="string"||typeof O=="number"){let G=W[X+1];z[O]=G}j[Y]={input:J[Y]??"",groups:z}}return j}static compareComponent($,Z,J){let j=x((X,O)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<O[G])return-1;if(X[G]===O[G])continue;return 1}return 0},"comparePart"),Y=new HZ(3,"","","","",3),W=new HZ(0,"","","","",3),z=x((X,O)=>{let G=0;for(;G<Math.min(X.length,O.length);++G){let K=j(X[G],O[G]);if(K)return K}return X.length===O.length?0:j(X[G]??Y,O[G]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#W[$],[W]):!Z.#$[$]&&J.#$[$]?z([W],J.#W[$]):z(Z.#W[$],J.#W[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};x(Zj,"URLPattern");function C3($,Z){for(let[J,j]of Object.entries($)){let Y=new Zj({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:j}}return null}var f$={startIndex:0,carriedViews:[]};function C5($,Z){let J=O0($.path,Z);return J.includes("*")?null:J}function oQ($,Z){if(!$)return f$;if($.search!==Z.search)return f$;let J=Math.min($.segments.length,Z.segments.length-1),j=0;while(j<J){let Y=$.segments[j],W=Z.segments[j];if(W.alwaysRun)break;if(Y.viewPath!==W.viewPath)break;let z=C5(Y,$.params),X=C5(W,Z.params);if(z===null||X===null||z!==X)break;j++}if(j===0)return f$;return{startIndex:j,carriedViews:Z.segments.slice(0,j).map(({viewPath:Y})=>Y)}}function aQ($,Z){let[,J,...j]=$.split("/");if(!Z.includes(J))return $;let Y=`/${j.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function _5($){let{flatViewRoutes:Z,supportedLocales:J,from:j,origin:Y,to:W}=$;if(!j)return f$;let z;try{z=new URL(j,Y)}catch{return f$}if(z.origin!==Y)return f$;let X=C3(Z,aQ(z.pathname,J));if(!X)return f$;return oQ({segments:X.route.segments,params:X.params,search:z.search},W)}var Jj="x-gemi-from";import{createElement as x1,Fragment as r5}from"react";function rQ($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function z8($){let Z={};for(let[J,j]of Object.entries($))if("run"in j){let Y=j.viewPath;if("children"in j){Z[J]=[Y];let W=new j.children,z=z8(W.routes);for(let[X,O]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,K=X==="/"&&J!=="/"?J:G;Z[K]=[Y,...O]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new j,W=z8(Y.routes);for(let[z,X]of Object.entries(W)){let O=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:O;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,j])=>[rQ(J),j]))}function X8($,Z){let[J,j]=Z,Y=$.find(([W])=>W===J);if(!Y){$.push([J,[...j]]);return}for(let W of j)X8(Y[1],W)}function O8($){let Z=[];for(let[J,j]of Object.entries($))if("run"in j){let Y=j.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in j){let W=new j.children,z=O8(W.routes);X8(Z,[Y,z])}else X8(Z,[Y,[]])}else{let Y=new j,W=O8(Y.routes);for(let z of W)X8(Z,z)}return Z}function jj($){let Z=[];for(let[J,j]of $)Z.push(J,...jj(j).flat());return Array.from(new Set(Z))}class Z$ extends X0{static getFacadeAccessor(){return o}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=A.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(A.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??Z$.locale(),$.timeZone??Z$.timeZone())}static setLocale($=Z$.locale(),Z={}){let J=this.getFacadeRoot(),j=$;if(!J.supportedLocales.includes($))j=J.defaultLocale;let Y=A.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",j,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(j),j}}class Yj{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}var tQ=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),eQ=new Set(["svg","math"]);function H5($){return $===32||$===9||$===10||$===12||$===13}function x5($){return $>=65&&$<=90||$>=97&&$<=122}function G8($){return $>=65&&$<=90?$+32:$}function S5(){let $="data",Z="",J=!1,j="",Y=0,W=0,z=!1,X=0,O=0,G=()=>$==="data"&&X===0&&O===0,K=()=>{if(!J&&tQ.has(Z)){$="rawText",j=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(eQ.has(Z)){if(J)O=Math.max(0,O-1);else if(!z)O+=1}Z=""},Q=(U)=>{switch($){case"data":if(U===60)$="tagOpen";return;case"tagOpen":if(U===33)$="bang",W=0;else if(U===47)$="endTagOpen";else if(x5(U))$="tagName",J=!1,z=!1,Z=String.fromCharCode(G8(U));else if(U===63)$="bogus";else if(U===60)$="tagOpen";else $="data";return;case"endTagOpen":if(x5(U))$="tagName",J=!0,z=!1,Z=String.fromCharCode(G8(U));else if(U===62)$="data";else $="bogus";return;case"tagName":if(H5(U)||U===47)$="inTag",z=U===47;else if(U===62)K();else Z+=String.fromCharCode(G8(U));return;case"inTag":if(U===62){K();return}if(z=U===47,U===34)$="attrDouble";else if(U===39)$="attrSingle";return;case"attrDouble":if(U===34)$="inTag";z=!1;return;case"attrSingle":if(U===39)$="inTag";z=!1;return;case"bang":if(U===45){if(W+=1,W===2)$="comment",W=0}else if(U===62)$="data";else $="bogus";return;case"bogus":if(U===62)$="data";return;case"comment":if(U===45)W=W<2?W+1:2;else if(U===62&&W>=2)$="data",W=0;else W=0;return;case"rawText":{if(Y<j.length){if(G8(U)===j.charCodeAt(Y))Y+=1;else Y=U===60?1:0;return}if(U===62)$="data",Z="";else if(H5(U)||U===47)$="inTag",Z="";else Y=U===60?1:0;return}}};return{scanToInsertionPoint(U){for(let B=0;B<U.length;B++){if(G())return B;Q(U[B])}return U.length},write(U){for(let B=0;B<U.length;B++)Q(U[B])},isSafe:G}}function _1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function $U($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${_1([$.path,$.variantKey,$.data])})</script>`}function ZU($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${_1([$.id,$.locale,$.strings])})</script>`}function Wj($,Z,J={},j){let Y=new TextEncoder,W=[],z=!1,X=!1,O=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((F)=>{if(F.status!=="resolved")return;W.push($U(F))}),j?.onUse((F)=>{W.push(ZU(F))});let G=$.getReader(),K=S5(),Q=(F,D)=>{F.enqueue(D),J.onChunk?.(D)},U=(F)=>{while(W.length>0){let D=Y.encode(W.shift());K.write(D),Q(F,D)}},B=(F,D)=>{if(W.length===0){K.write(D),Q(F,D);return}let T=K.scanToInsertionPoint(D);if(T>0)Q(F,D.subarray(0,T));if(K.isSafe())U(F);let V=D.subarray(T);if(V.length>0)K.write(V),Q(F,V)};return new ReadableStream({async pull(F){let D;try{D=await G.read()}catch(P){throw O(),P}let{done:T,value:V}=D;if(T){U(F),F.close(),O();return}if(!z){if(z=!0,K.write(V),Q(F,V),J.onShell?.(),K.isSafe())U(F);return}B(F,V)},cancel(F){return O(),G.cancel(F)}})}var JU=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function K8($){if(!$)return!1;return JU.test($)}async function f5($,Z=()=>{}){let J=A.getStore(),j=J?.req??null,Y=null;if(j?.rawRequest?.url)try{Y=new URL(j.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await jU($,Z),request:{path:Y,routePath:j?.routePath??null,locale:J?.locale??null},anonymousId:A5(),isBot:K8(j?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function E5($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function jU($,Z){if(!$.context)return{};try{let J=A.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function R5($,Z){return`${$}:${Z}`}function zj($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function b5($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function v5($,Z,J,j){if(j.unavailable)return{value:!1,reason:"unavailable"};if(j.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let W;try{W=Z.when(J)}catch(z){return j.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof W==="boolean")return{value:W,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=WU($,Z,J,j.buckets);return b5(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function YU($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function WU($,Z,J,j){let Y=R5(Z.salt??$,YU(J));if(!j)return zj(Y);let W=j.get(Y);if(W!==void 0)return W;let z=zj(Y);return j.set(Y,z),z}class k5 extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class Xj{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,j=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=j}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new k5(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let j of $??[]){let Y=typeof j?.key==="string"?j.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,j.active===!0);let W=zU(j);if(W)J.set(Y,W)}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 zU($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let j=$.updatedAt;if(j instanceof Date||typeof j==="string"||typeof j==="number"){let Y=j instanceof Date?j:new Date(j);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class XU{}class OU extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class Oj extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class w5 extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class q5{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class xZ{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new Xj($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([j,Y])=>({key:j,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(j),...Z.get(j)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{A.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new w5(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let j=GU(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new Oj(Y.constructor?.name||"an anonymous source");let{actorRecorded:W}=await Y.write($,Z,{actor:j});if(j!==null&&!W&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new q5(this,E5($))}async evaluateIn($,Z,J){let j=this.memoFor(Z),Y=j?.get($);if(Y)return Y;let W=this.declared[$];if(!W)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),O=v5($,W,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return j?.set($,O),this.notify($,O,Z),O}async evaluateAllIn($,Z,J){let j={};for(let[Y,W]of Object.entries(this.declared)){if(J.clientOnly&&W.serverOnly)continue;j[Y]=(await this.evaluateIn(Y,$,Z)).value}return j}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=A.getStore();if($?.featureContext)return $.featureContext;let Z=await f5(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=A.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=A.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(j){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${j instanceof Error?j.message:String(j)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function GU($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}function y5($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var KU=50;class SZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,j=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${j})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let j=Z.params??{},Y=new URLSearchParams(y5(Z.search??{}));Y.delete("json"),Y.sort();let W=O0($,j),z=Y.toString(),X=this.keyFor(W,z),O=this.entries.get(X);if(O)return O;let G;if(J==="render"&&this.renderStartedAt!==null){let B=Math.round(performance.now()-this.renderStartedAt);if(B>KU)G=B}let K,Q=new Promise((B)=>{K=B}),U={path:W,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:Q,source:J,startedAt:this.elapsed()};return this.entries.set(X,U),this.fetcher($,j,Y).then((B)=>{U.status="resolved",U.data=B},(B)=>{U.status="rejected",U.error=B}).then(()=>{if(U.settledAt=this.elapsed(),this.maybeLogLateDiscovery(U),U.status==="rejected"&&this.failListener)this.failListener(U);if(this.settleListener)this.settleListener(U);else this.settledBacklog.push(U);K()}),U}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class H1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,j,Y){super(typeof j?.message==="string"?j.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=j;this.retryAfter=Y;this.name="QueryError"}}function AZ(){let $=JSON.stringify({error:v1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function Gj(){return{status:403,error:{message:"Forbidden"}}}function _3($){let Z=fZ.getStore();return(J,j,Y)=>{let W=new URL($.url).origin,z=[O0(J,j),Y.toString()].filter((K)=>K.length>0).join("?"),X=new Request(`${W}/${z}`,{headers:$.headers,signal:$.signal}),O=g5($);if(O)EZ(X,O);let G=new f(X,j);return fZ.run(Z,()=>A.run(G,async()=>{try{let K=await N(r0).dispatchers(O).api.getRouteData(J);if(g$(K)){if(!K.ok)throw new H1(O0(J,j),Y.toString(),K.status,K.body);return K.body}if(K instanceof Response){let Q=await K.json().catch(()=>null);if(!K.ok)throw new H1(O0(J,j),Y.toString(),K.status,Q);return Q}return K}catch(K){if(K instanceof H1)throw K;let Q=new H1(O0(J,j),Y.toString(),500,{message:K instanceof Error?K.message:String(K)});throw Q.cause=K,Q}}))}}var QU=new Set(["script","style","template","title"]),UU=/\shidden([\s=/]|$)/i,BU=/"[^"]*"|'[^']*'/g;function FU($){let Z=0,J=0,j=0,Y=0;while(Y<$.length){let W=$.indexOf("<",Y),z=W===-1?$.length:W;if(z>Y){let Q=$.slice(Y,z).replace(/\s+/g,"").length;if(j>0)J+=Q;else Z+=Q}if(W===-1)break;if($.startsWith("<!--",W)){let Q=$.indexOf("-->",W+4);Y=Q===-1?$.length:Q+3;continue}let X=$.indexOf(">",W);if(X===-1)break;let O=$.slice(W+1,X);Y=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(O)?.[1]?.toLowerCase();if(!G)continue;let K=O.startsWith("/");if(!K&&QU.has(G)&&!O.endsWith("/")){let Q=$.indexOf(`</${G}`,Y);Y=Q===-1?$.length:Q;continue}if(G!=="div")continue;if(K){if(j>0)j-=1}else if(j>0)j+=1;else if(UU.test(O.replace(BU,'""')))j=1}return{shellChars:Z,deferredChars:J}}var DU=1000,TU=64;function VU($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function MU($,Z){if(Z.deferredChars<DU)return null;if(Z.shellChars>=TU)return null;return`[gemi] GET ${$} streams ${VU(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function m5($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,j){if(Z.has(J))return;let Y=MU(J,j);if(!Y)return;Z.add(J),$(Y)}}}function p5(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),FU(Z)}}}function h5($,Z,J=1e4,j){let Y=new TextEncoder,W=()=>{};return new ReadableStream({start(z){let X=!1,O=(K)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}j?.({aborted:K})};W=O,z.enqueue(Y.encode(`${JSON.stringify($)}
|
|
3
|
+
`)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
|
|
4
|
+
`))});let G=setTimeout(()=>O(!0),J);Z.allSettled().then(()=>O(!1),()=>O(!1))},cancel(){W(!1)}})}import{Fragment as nV,createContext as IU,createElement as oV,lazy as aV,use as rV,useContext as tV}from"react";function c5($){return{islands:[],render:$,instances:new WeakMap,count:0}}var H3="gemi-slot",u5="data-slot",d5="data-gemi-slot";var NU=Symbol.for("gemi.staticRender"),l5=globalThis[NU]??=IU(null);import{createHash as LU}from"crypto";var PU="gemi-islands",Kj='const d=document,c=JSON.parse(d.getElementById("gemi-islands").textContent),w=f=>(window.requestIdleCallback||setTimeout)(f),m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};for(const e of d.querySelectorAll("gemi-island")){const o=c.i[e.dataset.island];if(!o)continue;if(o.l=="eager")m(e,o);else if(o.l=="idle"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}',jM=`'sha256-${LU("sha256").update(Kj).digest("base64")}'`,CU='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});'+Kj;function i5($,Z,J,j){if(!J)return $;let Y=j?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var _U=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<");function s5($,Z,J,j){if(Z.islands.length===0||!J)return $;let Y=new Set,W=Z.islands.map((O)=>{let G=O.module?J(O.module):void 0;if(!G)return console.error(`[gemi] island ${O.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(O.load==="eager")for(let K of G.preload)Y.add(K);return{s:G.src,e:O.export,l:O.load}});if(W.every((O)=>O===null))return $;let z=[...Y].map((O)=>`<link rel="modulepreload" href="${_U(O)}"/>`).join(""),X=`<script type="application/json" id="${PU}">${_1({i:W})}</script><script type="module">${j?CU:Kj}</script>`;return i5(i5($,"</head>",z,!1),"</body>",X,!0)}function HU($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let j=0;for(let Y=J.exec($);Y;Y=J.exec($))if(j+=Y[1]?-1:1,j===0)return J.lastIndex;return-1}function n5($){let Z=`<template ${d5}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let j=HU($,J);if(j===-1)break;let Y=J+Z.length,W=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,j-11);$=$.slice(0,J)+$.slice(j);let O=`<${H3} ${u5}="${W}" style="display:contents"></${H3}>`;$=$.split(O).join(`<${H3} style="display:contents">${X}</${H3}>`)}return $}function o5($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function a5($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}var xU=async()=>(await import("./chunk-vbdty91k.js")).default,Qj,x3=async(...$)=>{return Qj??=import("react-dom/server.browser").catch((Z)=>{throw Qj=void 0,Z}),(await Qj).renderToReadableStream(...$)},t5=1e4,e5="no-locale",SU=`
|
|
5
|
+
!function(){try{var d=document.documentElement,c=d.classList;
|
|
6
|
+
c.remove('light','dark');
|
|
7
|
+
var e=localStorage.getItem('theme');
|
|
8
|
+
if('system'===e||(!e&&'system'===defaultTheme)){
|
|
9
|
+
var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
|
|
10
|
+
if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
|
|
11
|
+
else{d.style.colorScheme='light';c.add('light')}
|
|
12
|
+
}else if(e){
|
|
13
|
+
c.add(e||'')
|
|
14
|
+
}}catch(e){}}()
|
|
15
|
+
`;async function AU($,Z,J){let j=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${j}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var Fj="/assets";function fU($){return $===Fj||$.startsWith(`${Fj}/`)}function EU($){let Z=$.filter(fU);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((j)=>`"${j}"`).join(", ")} use${J?"":"s"} the reserved "${Fj}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function RU($){let Z=N(r0).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function Uj($){let{status:Z=400,error:J}=$;return new Response(J?.message,{...$,status:Z})}function bU($){let{status:Z=400,data:J,directive:j,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:j}),{headers:Y,status:Z})}class A3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=m5();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;constructor($){let Z=t7();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":R4};this.flatViewRoutes=Y8(J),EU(Object.keys(this.flatViewRoutes)),this.routeManifest=z8(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,j])=>j.at(-1)!=="FILE")),this.componentTree=O8(J),this.flatComponentTree=jj(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,j])=>j.static).map(([j])=>j);for(let j of this.staticRoutes){let Y=this.flatViewRoutes[j].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=N(xZ);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)Q8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(j)=>{E$.error(j?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(j)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(j){J(j)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:j,routeKey:Y}=$,W=()=>{let O=new Set(Z?.preload??[]);for(let G of j)for(let K of J?.[G]??[])O.add(K);return[...O].map((G)=>x1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return W();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=W(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:j,currentViews:Y,data:W,serverQueries:z,headers:X}=$,O;if(j.layout){if(O=$.viewImportMap[j.layout],!O)throw Error(`The static layout "${j.layout}" was not found. It is a view path: a file at app/views/${j.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:j.layout});z.markRenderStart();let K=Bj(),Q=new AbortController,U=setTimeout(()=>Q.abort(),t5),B=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},F=c5(async(D,T)=>{let V=await x3(D,{signal:Q.signal,identifierPrefix:T,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});return await V.allReady.catch(()=>{}),await new Response(V).text()});try{let D=await x3(x1(l5.Provider,{value:F,children:x1(r5,{children:[...G,x1(this.root,{data:W,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:O,key:"root"})]})}),{signal:Q.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});await D.allReady.catch(()=>{});let T=n5(await new Response(D).text());return new Response(s5(T,F,$.resolveIsland,Bun.env.NODE_ENV!=="production"),{status:200,headers:X})}finally{clearTimeout(U),J(()=>this.completeStream(Z,z.summarize(Q.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:j,currentPathName:Y,headers:W,i18n:z,params:X,pathname:O,serverQueries:G,userAgent:K,noStream:Q,url:U,user:B,viewData:F,breadcrumbs:D,urlLocaleSegment:T,meta:V,isOgRequest:P,appId:M,features:H,staticView:S}=$,_=O.replace(`/${T}`,""),L={kind:"view",data:{meta:V,pageData:{[_]:F},__csrf:j.toString("base64"),prefetchedData:{},i18n:z,auth:{user:B},routeManifest:this.clientRouteManifest,breadcrumbs:D,router:{urlLocaleSegment:T,pathname:Y,params:X,currentPath:O,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?RU(Z):null},appId:M,features:H,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},I=this.root,C=this.routeManifest[Y];return async(b)=>{let{bootstrapModules:m=[],loaders:A1,getStyles:e,viewImportMap:n,cssManifest:q,ogMap:q0,viewModules:f3,clientEntry:R$,modulePreloadManifest:kZ,assetBase:K1,resolveIsland:b$}=b,f1=R$?[]:m,$0=(p)=>[p,`window.loaders=${A1}`,...R$?[`import(${JSON.stringify(R$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let p=null,e0=null;for(let k$ of C??[])if(typeof q0[k$]==="function")e0=k$,p=q0[k$];if(!p)return new Response("Not found",{status:404});let pX=Object.values(L.data.pageData)[0];try{await x3(x1(p,pX[e0]),{onError:()=>{}})}catch(k$){let{fonts:hX,...cX}=k$.satoriOptions,uX=await Promise.all(hX.map((E3)=>{return AU(E3.name,E3.weight,E3.style).then((nX)=>({...E3,data:nX}))})),Aj=new Headers(W);Aj.set("Content-Type","image/png");let[dX,lX]=await Promise.all([xU(),J8("Rendering an OG image")]),iX=await dX(k$.jsx,{...cX,fonts:uX}),sX=await lX(Buffer.from(iX)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(sX),{headers:Aj})}return new Response("data")}if(S&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:C,data:L.data,serverQueries:G,headers:W,getStyles:e,viewImportMap:n,viewModules:f3,resolveIsland:b$});if(L.data.cssManifest=q,L.data.modulePreloadManifest=kZ??{},K1&&K1!=="/")L.data.assetBase=K1;let P8=this.modulePreloadLinks({clientEntry:R$,modulePreloadManifest:kZ,views:C??["404"],routeKey:Y??"404"}),C8=await e(C);L.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let t0=new AbortController,v$=setTimeout(()=>t0.abort(),t5),J$=K8(K)||Q,E1=Bun.env.NODE_ENV!=="production"&&!J$&&Y&&this.shellReporter.shouldObserve(Y)?p5():null,R=Bj();try{let p=await x3(x1(r5,{children:[...P8,...C8,x1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:SU}}),x1(I,{data:L.data,viewImportMap:n,viewModules:f3,serverQueries:G,dictionarySink:R,key:"root"})]}),{bootstrapScriptContent:$0(`window.__GEMI_DATA__ = ${_1(L.data)}`),bootstrapModules:f1,signal:t0.signal,...J$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(e0){if(Bun.env.NODE_ENV!=="production")console.error(e0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(v$)),J$)await p.allReady.catch(()=>{});return new Response(Wj(p,G,{onShell:J$?void 0:()=>G.markShell(),onChunk:E1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(t0.signal.aborted)),E1)this.shellReporter.report(Y,E1.measure())})},R),{status:!Y?$.refusedStatus??404:200,headers:W})}catch(p){if(clearTimeout(v$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(t0.signal.aborted))),p;let e0=await x3(x1("div"),{bootstrapScriptContent:$0(`window.error= ${_1(p.message)}; window.stack_trace=${_1(p.stack)};window.__GEMI_DATA__ = ${_1(L.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...f1]:f1});return new Response(Wj(e0,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(t0.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:W})}}}viewRefusalStatus($,Z,J){if(S3(Z))return 404;if(Z?.kind===RZ){let j=Z.payload?.view?.status;return j===403||j===404?j:null}if(bZ(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof H1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),j=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),W=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=W.split("/"),O=W,G=null,K=null,Q=N(o),U=C3(this.flatViewRoutes,W),B=Q.isLocaleAware&&this.localeRouting==="prefix"&&!U?.route.middleware.includes(e5);if(B&&Q.supportedLocales.includes(z))O=`/${X.join("/")}`,G=z,K=z;if(B&&!Y&&K===null&&!(K===null&&U!==null)){let I=$X(z,Q.supportedLocales,Q.defaultLocale);if(I){let C=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${C}${j?".json":""}${J.search}`}})}}if(B&&!Y){let I=N(o).detectLocale(new f($,{},"view",O));if(K===null&&I!==Q.defaultLocale){let C=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${C}${J.search}`}})}}O=O.replace("//","/");let D=[],T=[],V=null,P={},M=null,H=!1,S=[],_;try{let I=C3(this.flatViewRoutes,O);if(K&&I?.route.middleware.includes(e5))I=null;if(I){if(V=I.routePath,P=I.params,D=I.route.exec,T=I.route.middleware,S=I.route.features,H=T.includes("no-stream"),_=I.route.static,j&&this.partialRendering){let C=$.headers.get(Jj),b=_5({flatViewRoutes:this.flatViewRoutes,supportedLocales:N(o).supportedLocales,from:C,origin:J.origin,to:{segments:I.route.segments,params:P,search:J.search}});if(b.startIndex>0)D=D.slice(b.startIndex),M={from:C,carriedViews:b.carriedViews}}}}catch(I){throw I}if(_&&j)return new Response("Not found",{status:404});let L=new f($,P,"view",V);return this.hooks.onRequestStart(L),await A.run(L,async()=>{let I=null,C=A.getStore(),b=fZ.getStore(),m=(q)=>fZ.run(b,()=>A.runWith(C,q));C.serverQueries=new SZ(_3($));let A1=new Set;C.serverQueries.onQueryFail((q)=>{A1.add(q.error);try{m(()=>Promise.resolve(this.hooks.onRequestFail(n,q.error)).catch(()=>{}))}catch{}});let e=o5(_);if(K){let q=K.replaceAll("/","");Z$.setLocale(q,{cookie:e.locale})}else if(Q.isLocaleAware&&!B)C.setLocale(Q.defaultLocale);else Z$.setLocale(void 0,{cookie:e.locale});let n=C.req;if(e.session)Q8();try{let q=null;try{await N(PZ).runMiddleware(T)}catch(R){if(q=this.viewRefusalStatus(n,R,A1),q===null)throw R}if(q!==null||S.length>0&&!await this.passesFeatureGates(S))V=null,D=[],n.routePath="";let q0=N(o),f3=q0.isEnabled,R$=q0.isLocaleAware,kZ=new f($,n.params),K1={defaultLocale:q0.defaultLocale,timeZone:q0.detectTimeZone(kZ)};if(R$){let R=null;if(K)R=K.replaceAll("/",""),C.setLocale(R);else if(!B)R=C.locale??q0.defaultLocale;else R=q0.detectLocale(kZ),C.setLocale(R);let p=f3?q0.getPageTranslations(R,n.routePath):{};K1={...K1,supportedLocales:q0.supportedLocales,currentLocale:R,dictionary:{[R]:p},defaultLocale:q0.defaultLocale,...B?{}:{localeRouting:"off"}}}await ZX(K1.currentLocale??"");let b$;try{b$=await Promise.all(D.map((R)=>R(n)))}catch(R){if(q=this.viewRefusalStatus(n,R,A1),q===null)throw R;V=null,D=[],n.routePath="",b$=[]}let{cookies:f1,headers:$0}=C;if(q!==null)$0.set("Cache-Control","no-store");I={data:b$,cookies:f1,headers:$0,user:C.user,prefetchedData:C.serverQueries.snapshotResolved(),currentPathName:V,params:n.params,urlLocaleSegment:G,meta:C.renderMeta(),appId:N(Yj).id,features:await N(xZ).forClient()};let{params:P8,user:C8}=I,t0={},v$={};for(let R of b$??[]){let[p,e0]=Object.entries(R)?.[0]??[];if(!p||!e0)continue;v$[`${p}:${V}`]=e0.breadcrumb,t0[p]=e0}let J$=t0.FILE;if(J$){for(let R of f1)$0.append("Set-Cookie",R.toString());try{await this.onRequestEnd(n)}catch(R){E$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await w8(J$,$0)}if(j){$0.set("Content-Type","application/x-ndjson; charset=utf-8"),$0.append("Vary",Jj),f1.forEach((p)=>$0.append("Set-Cookie",p.toString())),await this.hooks.onRequestEnd(n);let R={meta:M&&!C.metadata.touched?null:I.meta,data:{[O]:t0},breadcrumbs:v$,prefetchedData:C.serverQueries.snapshotResolved(),i18n:K1,features:I.features,is404:!V,appId:I.appId,partial:M};return new Response(h5(R,C.serverQueries,void 0,({aborted:p})=>m(()=>this.completeStream(n,C.serverQueries.summarize(p)))),{headers:$0})}if($0.set("Content-Type","text/html; charset=utf-8"),!H&&!(_&&V))$0.append("Vary","User-Agent");let E1=Boolean(_&&V);if(!E1||e.session)Q8();for(let R of f1)$0.append("Set-Cookie",R.toString());if(!E1||e.csrf){let R=Bun.CSRF.generate(process.env.SECRET);$0.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(n,{mintSession:!E1||e.session})}catch(R){E$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(E1)a5($0,_);return await this.render({req:n,runInRequestScope:m,csrfTokenHMAC:Buffer.from(""),currentPathName:V,headers:$0,i18n:K1,params:P8,pathname:J.pathname,serverQueries:C.serverQueries,userAgent:$.headers.get("user-agent"),noStream:H,url:J,user:C8,viewData:t0,breadcrumbs:v$,urlLocaleSegment:G,meta:I.meta,appId:I.appId,features:I.features,isOgRequest:Y,staticView:V?_:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===RZ)if(j)return bU(q.payload.viewData??q.payload.api);else return Uj(q.payload.view);if(!A1.has(q))this.hooks.onRequestFail(n,q);if(bZ(q))return console.error(q),j?AZ():Uj(Gj());if(q instanceof H1&&q.status===403)return j?AZ():Uj(Gj());throw q}},Z)}}function Dj(){let $=JSON.stringify({error:v1("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 XX extends A0{routes={"/api-routes":this.get(()=>{let $=N(B8).flatRoutes,Z=[];for(let[J,j]of Object.entries($))for(let[Y,W]of Object.entries(j)){let{exec:z,middleware:X}=W;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=N(A3).flatViewRoutes,Z=[];for(let[J,{middleware:j,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:j});return Z})}}var vU=new Set([b1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),kU=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,wU=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function qU($,Z,J,j){for(let[Y,W]of Object.entries(J.headers??{})){if(W===void 0||W===null)continue;let z=Y.toLowerCase();if(vU.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(j&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,W)}for(let[Y,W]of Object.entries(J.cookies??{})){if(W===void 0||W===null)continue;if(Y===b1)throw Error(`dispatchAs: credentials may not set the "${b1}" cookie. The access token stays the initiator's.`);if(!kU.test(Y)||!wU.test(W))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${W}`)}}function yU($,Z){let J=$.body.getReader(),j=!1,Y=()=>{if(j)return;j=!0;try{Z()}catch(z){console.error(z)}},W=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(O){Y(),z.error(O);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(W,{status:$.status,statusText:$.statusText,headers:$.headers})}function JX($){let{status:Z=400,data:J,headers:j}=$,Y=new Headers({"Content-Type":"application/json",...j});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function jX($,Z,J){let j=[];Z?.forEach((z,X)=>j.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(j.length===0&&Y.length===0)return $;let W=(z)=>{for(let[X,O]of j){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,O)}for(let X of Y)z.append("Set-Cookie",X)};try{return W($.headers),$}catch{let z=new Headers($.headers);return W(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class B8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=r7();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=g4({"/":$.rootRouter,"/auth":b4,"/__gemi__/services/i18n":v4,"/__gemi__/services/logs":y4,"/__gemi__/services/image":q4,"/__gemi__/debug":XX})}getRouteHandlerAndParams($){let Z=new URL($.url),J=zX(Z.pathname),j={},Y;for(let[W]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:W});if(z.test({pathname:J})){Y=W,j=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:j,path:Y}}async runRouteMiddleware($,Z){let j=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await N(PZ).runMiddleware(j)}catch(Y){if(Y.kind===RZ)return JX(Y.payload.api);else{if(S3(Y))return Dj();if(this.onRequestFail(Z,Y),console.error(Y),bZ(Y))return AZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=A.getStore(),j=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await j()}catch(W){if(W.kind===RZ)return JX(W.payload.api);if(S3(W))return Dj();if(this.onRequestFail(J.req,W),console.error(W),bZ(W))return AZ();throw W}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let j=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){E$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await j();return}$.whenIdle().then(j).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:j}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[j];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:v1("not_found","Not found",404)}),{status:404});let W=new f($,J,"api",j);if(!this.isFrameworkRoute(j))this.onRequestStart(W);return await A.run(W,async()=>{let z=A.getStore(),X=!1,O=async()=>{X=!0,await this.endRequest(z,W,j)};try{let G=N(o);if(G.isEnabled){let D=G.detectLocale(W);z.setLocale(D)}z.setRequest(W),N(PZ).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(j,W);if(K instanceof Response){let D=jX(K,z.headers,z.cookies);return await O(),D}let Q=await this.getRouteData(j),U=z.headers,B=z.cookies;if(Q instanceof Response){let D=jX(Q,U,B);if(this.isOpenEndedBody($,D)){let T=yU(D,()=>this.endRequest(z,W,j));return X=!0,T}return await O(),D}let F=(g$(Q)?Q:j$.json(Q)).toResponse(U,B);return await O(),F}catch(G){if(!X)try{await O()}catch(K){console.error(K)}throw G}},Z)}async dispatchAs($,Z,J,j,Y){let W=new URL($.rawRequest.url).origin,z=new URL(`${W}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==W||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let O=Y?.identity;if(O!==void 0&&(typeof O!=="object"||!O?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,K=[],Q=O?null:$.cookies.get(b1);if(Q)K.push(`${b1}=${Q}`);if(Y?.credentials)qU(G,K,Y.credentials,O!==void 0);if(K.length>0)G.set("Cookie",K.join("; "));let U=O?null:$.headers.get(b1);if(U)G.set(b1,U);let B=$.headers.get("User-Agent");if(B)G.set("User-Agent",B);let F;if(j instanceof FormData)F=j;else if(j!==void 0)G.set("Content-Type","application/json"),F=JSON.stringify(j);let D=new Request(z,{method:Z,headers:G,body:F,...Y?.signal?{signal:Y.signal}:{}});if(YX(D,p$($),O?.grant,Y?.progress),$.domain)EZ(D,$.domain);let T=O?{user:O.user}:void 0;return A.exit(()=>WX.exit(()=>this.handleApiRequest(D,T)))}}import{timingSafeEqual as gU}from"crypto";var D8="",Mj="*",mU=60000,pU=1e4,Tj=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,F8=16,OX=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Vj="x-forwarded-host";function GX($){return $.startsWith(":")}function Ij($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),j=Buffer.from(Z,"utf8");return J.length===j.length&&gU(J,j)}function hU($){if(!$)return null;if($===!0)return{header:Vj,secret:null};return{header:($.hostHeader??Vj).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function cU($){if(!$||$===!0)return;let{hostHeader:Z,secret:J}=$;if(Z!==void 0&&(typeof Z!=="string"||!OX.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"||!OX.test(J.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${J.header}".`);if(J.header.toLowerCase()===(Z??Vj).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof J.value!=="string"||J.value.length<F8)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${F8} characters. A guessable one lets any client name its own host.`)}function G1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function uU($){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 dU($){let Z=G1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((W)=>Tj.test(W)))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<F8)throw Error(`\`route.domains.ask.secret\` must be at least ${F8} characters. A guessable one is worse than leaving \`ask\` out.`);cU($.trustProxy);let j=new Set,Y=null;for(let W of $.groups??[]){let{subdomain:z}=W;if(j.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(j.add(z),GX(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=W;continue}if(W.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>Tj.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!j.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class Nj{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){dU($),this.root=G1($.root),this.hostTrust=hU($.trustProxy);for(let Z of $.groups??[])if(GX(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??mU,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!Ij($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return G1(this.forwardedHost($))??G1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),j=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),W=Y&&G1(Y)?uU(Y):null;return`${j}://${W??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:Mj,params:{},custom:!0};return null}async allows($,Z){let J=G1($);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:D8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let j=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(j);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&Tj.test(j)){let W={[this.param.name]:j};if(this.param.exists&&!await this.param.exists(W,Z))return null;return{host:$,group:this.param.subdomain,params:W,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let j=this.inFlight.get($);if(j)return j;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let W;try{W=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=pU)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:W,expiresAt:Date.now()+this.cacheTtlMs})}return W}forget($){if($===void 0)this.cache.clear();else{let Z=G1($);if(Z)this.cache.delete(Z)}}}var lU="/__gemi__/domains/ask";class r0{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(D8,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new Nj(J);let j=(Y)=>({api:Y.api?new B8({...Z.api,...Y.api}):$.api,view:Y.view?new A3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,j(Y));if(J.custom?.fallback)this.groups.set(Mj,j(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)KX($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return EZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==lU)return null;if(!Ij(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),j=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:j?200:404})}dispatchers($){return this.groups.get($?.group??D8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,j]of this.groups){if($.has(j.view))continue;$.add(j.view),Z.push({group:J,view:j.view})}return Z}}function T8($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var QX=600000;function UX($,Z){return[g3($,Z),g3($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new r8){this.config={...V8(AY($),$),emailCode:o8($.emailCode)},this.provider=Z}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=N().bound(r0)?N(r0).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?N(r0).resolver?.root:G1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let j=$.domain?.host??G1(new URL($.rawRequest.url).host);return j===J||j?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!u8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let j=Date.now(),Y=T8(J.expiresAt),W=T8(J.absoluteExpiresAt);if(Y<=j||W<=j)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,j);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let j=A.getStore()?.req;if(!j)return null;let Y=Date.now(),W=Math.floor(Y/QX),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:j,userAgent:Z}))return null;let G=g3($,W),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of UX($,W))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let O=await this.getSession(z,Z);if(O)j.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(j,new Date(O.expiresAt)));return O}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(u8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/QX),j=UX($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let W of j){if(Y?.user)break;Y=await this.userProvider.findSession({token:W,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let W of j)await this.userProvider.deleteSession({token:W});return Y})}requestCarryingCookie($){let Z=A.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let j=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:j}),W=this.requestCarryingCookie($.token);if(W)W.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(W,j));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??j}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),j=new f;if(j.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(j,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new f,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new W$;let j=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=VY(J),W=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:j,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:j??""});return z?.user?z:W}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:j}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:j}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),j=await this.config.generateCode($),Y=typeof j==="string"&&j!==""?j:_Y(Z);return await this.userProvider.createMagicLinkToken({email:$,token:m3("link",$,J),pin:m3("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:j,maxAttempts:Y}=this.config.emailCode,W=await this.userProvider.findMagicLinkTokenByEmail($);if(!W)return lZ("pin",$,null,Z),{status:"invalid"};let z=T8(W.createdAt);if(z+j*60000<=Date.now())return lZ("pin",$,null,Z),{status:"expired"};if(!await SY(W.id,z,Y,j))return await this.userProvider.claimMagicLinkToken(W.id),{status:"too_many_attempts"};if(!lZ("pin",$,W.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(W.id))return{status:"invalid"};return{status:"ok",row:W}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),j=lZ("link",$,J?.token,Z);if(!J||!j)return!1;if(T8(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class S$ extends X0{static getFacadeAccessor(){return E}static async user(){let $=A.getStore(),Z=$?.user;if(!Z){if(Z=await w3(this.getFacadeRoot(),$?.req),Z)$?.setUser(Z)}if(Z)return Z;throw new W$({redirectTo:k3($?.req,this.getFacadeRoot().config.signInPath)})}static intendedUrl($){let Z=A.getStore()?.req;return m$(Z?.search.get(Y$),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await S$.user();if(!await $(Z))throw new h$}static async guardSafe($){let Z=await S$.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class M8{static ensure($,Z={}){let J=A.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new SZ(_3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=M8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){M8.ensure($,Z[0])}static noPrefetch(){let $=A.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new SZ(_3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function BX($,Z,J="/"){let j=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,W=new URL(J.startsWith("/")?J:`/${J}`,j),z=iU(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(W.hostname=z.hostname,z.port)W.port=z.port;return W.toString()}function iU($){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 FX{static absolute($,...Z){return`${process.env.HOST_NAME}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let j=N(r0).resolver;if(!j)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=A.getStore()?.req?.rawRequest,W=Y?j.publicOrigin(Y):process.env.HOST_NAME;if(!W)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` for the protocol.");return BX({root:j.root,origin:W},$,O0(String(Z),J[0]??{}))}}class DX{name="Meta";static description($){A.getStore().metadata.description($)}static title($){A.getStore().metadata.title($)}static openGraph($){A.getStore().metadata.openGraph($)}static htmlAttributes($){A.getStore().metadata.htmlAttributes($)}static canonical($){A.getStore().metadata.canonical($)}static alternates($){A.getStore().metadata.alternates($)}}var sU={set($,Z,J){A.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(A.getStore().req.cookies.has($))return!1;return A.getStore().setCookie($,Z,J),!0},delete($,Z){A.getStore().deleteCookie($,Z)}};class S1 extends X0{static getFacadeAccessor(){return TX}static get client(){return this.getFacadeRoot().client}static get($){return S1.client.get($)}static set($,Z){return S1.client.set($,Z)}static del(...$){return S1.client.del(...$)}static exists($){return S1.client.exists($)}static incr($){return S1.client.incr($)}static expire($,Z){return S1.client.expire($,Z)}static ttl($){return S1.client.ttl($)}}class VX extends X0{static getFacadeAccessor(){return $1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}}class IX extends X0{static getFacadeAccessor(){return MX}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}function DN($){return $}function NX(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function I8($){let Z=new URLSearchParams;for(let[J,j]of $)Z.append(J,String(j));return Z.toString()}function Lj($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[j,Y]of J){let W=Number(Y);if(Y!==""&&Number.isSafeInteger(W)&&W>=0)Z.set(j,W)}return Z}var{SQL:nU}=globalThis.Bun;function oU(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var aU=async($)=>{let Z=new nU($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,j,Y)=>Z.listen(J,j,Y),close:()=>Z.close({timeout:1})}},rU=async($)=>{let Z;try{Z=(await import("./chunk-qjhw8nje.js")).default}catch(j){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:j})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(j,Y,W)=>J.listen(j,Y,W),close:()=>J.end({timeout:1}).catch(()=>{})}},LX=($)=>oU()?aU($):rU($);var tU=/^[A-Za-z_][A-Za-z0-9_]*$/;class Pj{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",j=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,j,Y])if(!tU.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let W=Z.retain??1000;if(!Number.isInteger(W)||W<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${W}.`);this.headsTable=J,this.entriesTable=j,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=W,this.listener=Z.listener??LX}async createTable(){for(let $ of eU(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let W=this.sqliteTurn.then(Y);return this.sqliteTurn=W.catch(()=>{}),W}let j=this.append(J,$,Z);return PX(j),j}async append($,Z,J){let j=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[W]=await $`
|
|
16
|
+
INSERT INTO ${j} (channel, seq) VALUES (${Z}, 1)
|
|
17
|
+
ON CONFLICT (channel) DO UPDATE SET seq = ${j}.seq + 1
|
|
18
|
+
RETURNING seq
|
|
19
|
+
`,z=Number(W.seq);if(await $`
|
|
20
|
+
INSERT INTO ${Y} (channel, seq, data, created_at)
|
|
21
|
+
VALUES (${Z}, ${z}, ${JSON.stringify(J??null)}, ${Date.now()})
|
|
22
|
+
`,z>this.retain)await $`DELETE FROM ${Y} 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((Y)=>[Y,0]));if($.length===0)return Z;let J=this.sql,j=await J`
|
|
23
|
+
SELECT channel, seq FROM ${J.unsafe(`"${this.headsTable}"`)}
|
|
24
|
+
WHERE channel IN ${J([...$])}
|
|
25
|
+
`;for(let Y of j)Z.set(Y.channel,Number(Y.seq));return Z}async read($,Z,J){let j=this.sql,[Y]=await j`
|
|
26
|
+
SELECT seq FROM ${j.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
|
|
27
|
+
`,W=Y?Number(Y.seq):0;if(Z>W)return{entries:[],head:W,gap:!0};if(Z===W)return{entries:[],head:W,gap:!1};let z=await j`
|
|
28
|
+
SELECT seq, data FROM ${j.unsafe(`"${this.entriesTable}"`)}
|
|
29
|
+
WHERE channel = ${$} AND seq > ${Z}
|
|
30
|
+
ORDER BY seq
|
|
31
|
+
LIMIT ${J}
|
|
32
|
+
`;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:W,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:W,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(j)=>{let Y=j.indexOf(" "),W=Number(j.slice(0,Y));if(Y>0&&Number.isInteger(W))$(j.slice(Y+1),W)},Z)}catch(j){throw await J.close(),j}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=F1();if($===void 0||X$()!==this.connection)return;return $}}function eU($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
33
|
+
"channel" TEXT NOT NULL PRIMARY KEY,
|
|
34
|
+
"seq" BIGINT NOT NULL
|
|
35
|
+
)`,`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
36
|
+
"channel" TEXT NOT NULL,
|
|
37
|
+
"seq" BIGINT NOT NULL,
|
|
38
|
+
"data" TEXT NOT NULL,
|
|
39
|
+
"created_at" BIGINT NOT NULL,
|
|
40
|
+
PRIMARY KEY ("channel", "seq")
|
|
41
|
+
)`]}class Cj{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let j=++J.head;if(J.entries.push({seq:j,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return j}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let j=this.logs.get($),Y=j?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!j||Z===Y)return{entries:[],head:Y,gap:!1};let W=j.entries[0]?.seq??Y+1;if(W>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-W;return{entries:j.entries.slice(z,z+J),head:Y,gap:!1}}}var SX=new TextEncoder;function CX($,Z){return SX.encode(`id: ${$}
|
|
42
|
+
data: ${JSON.stringify(Z)}
|
|
43
|
+
|
|
44
|
+
`)}function AX($,Z,J,j){let Y=Z instanceof Request?Z:Z.rawRequest,W=j.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:W,signal:Y.signal})}catch(U){if(!(U instanceof N8))throw U;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(j.retryAfter??5)}})}let X=null,O=!1,G=!1,K=(U)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{U.close()}catch{}},Q=new ReadableStream({start(U){X=setInterval(()=>{if(xX())return K(U);try{U.enqueue(SX.encode(_X))}catch{K(U)}},$.config.keepaliveInterval)},async pull(U){try{if(!O){if(await z.ready(),O=!0,!G)U.enqueue(CX(z.cursor,{type:"ready"}));return}let B=await z.next();if(B.done||G)return K(U);U.enqueue(CX(z.cursor,B.value))}catch(B){if(!G)console.error("[gemi] A change feed stream failed.",B);K(U)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(Q,{headers:HX()})}var fX=255,EX=500,$B=30000;class N8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class Sj{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=EX;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=V8(NX(),$),this.driver=JB(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){xj($);let J=Z===void 0?null:Z;if(F1()!==void 0&&!this.driver.joinsTransaction?.())return Hj(async()=>{this.wake($,await this.driver.publish($,J))}),null;let j=await this.driver.publish($,J);return Hj(()=>this.wake($,j)),j}async head($){return xj($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=_j($);return I8(await this.driver.heads(Z))}subscribe($,Z={}){let J=_j($);if(this.all.size>=this.config.maxSubscriptions)throw new N8(this.config.maxSubscriptions);let j=new RX(this,J,ZB(Z.cursor),this.config,Z.signal);this.all.add(j);for(let Y of J){let W=this.followers.get(Y);if(!W)this.followers.set(Y,W=new Set);W.add(j)}return this.startListening(),this.startPolling(),j}stream($,Z,J={}){return AX(this,$,_j(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[j,Y]of J)this.wake(j,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=EX,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,$B)}}}class RX{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,j,Y){this.manager=$;this.config=j;this.signal=Y;this.channels=Z;for(let W of Z){let z=J.get(W);if(z!==void 0)this.positions.set(W,z),this.readTo.set(W,z),this.dirty.add(W)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return I8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let j=Z.get(J)??0;this.positions.set(J,j),this.readTo.set(J,j)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:j,head:Y,gap:W}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(W){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of j)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(j.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function xj($){if(typeof $!=="string"||$===""||$.length>fX)throw Error(`A change feed channel is a string of 1 to ${fX} characters; got ${JSON.stringify($)}.`)}function _j($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)xj(J);return Z}function ZB($){if($===void 0||$===null)return new Map;if(typeof $==="string")return Lj($);let Z=$ instanceof Map?[...$]:Object.entries($);return Lj(I8(new Map(Z)))}function JB($,Z){if($==="memory")return new Cj;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 Pj(Z.make(O$));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 bX extends X0{static getFacadeAccessor(){return Sj}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class vX extends X0{static getFacadeAccessor(){return xZ}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class L8{bound;constructor($){this.bound=$}get name(){return this.bound??X$()}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 qX(J.sql,(j)=>kX(Z,()=>$(j)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-agyfv3f8.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:j,values:Y}=gX($,yX(J.dialect),Z);return(this.handle()??J.sql).unsafe(j,Y)}handle(){let $=F1();if($===void 0)return;return X$()===this.name?$:void 0}connection($=this.name){return wX($),N(O$).connection($)}}var vZ=new L8;class mX extends X0{static getFacadeAccessor(){return O$}static connection($){return new L8($)}static get sql(){return vZ.sql}static get dialect(){return vZ.dialect}static query($){return vZ.query($)}static execute($){return vZ.execute($)}static transaction($){return vZ.transaction($)}static schema(){return vZ.schema()}static close(){return this.getFacadeRoot().close()}}export{Q1 as Mc,wZ as Nc,S8 as Oc,q$ as Pc,yZ as Qc,A0 as Rc,b8 as Sc,v8 as Tc,cj as Uc,y$ as Vc,j$ as Wc,jO as Xc,w8 as Yc,R1 as Zc,G0 as _c,YO as $c,WO as ad,c8 as bd,u8 as cd,VY as dd,$1 as ed,gZ as fd,jY as gd,p$ as hd,MY as id,IY as jd,l8 as kd,i8 as ld,m3 as md,lZ as nd,ED as od,AY as pd,uO as qd,r8 as rd,w3 as sd,S$ as td,Z$ as ud,M8 as vd,FX as wd,DX as xd,sU as yd,S1 as zd,VX as Ad,IX as Bd,DN as Cd,NX as Dd,I8 as Ed,Lj as Fd,Pj as Gd,Cj as Hd,N8 as Id,Sj as Jd,RX as Kd,bX as Ld,R5 as Md,zj as Nd,b5 as Od,v5 as Pd,YU as Qd,k5 as Rd,Xj as Sd,XU as Td,OU as Ud,Oj as Vd,w5 as Wd,q5 as Xd,xZ as Yd,vX as Zd,L8 as _d,mX as $d,P4 as ae,xQ as be,k4 as ce,w4 as de,HT as ee,s7 as fe,n7 as ge,q3 as he,PZ as ie,hT as je,r7 as ke,t7 as le,Yj as me,AZ as ne,Gj as oe,jM as pe,Fj as qe,fU as re,Uj as se,bU as te,A3 as ue,Dj as ve,JX as we,jX as xe,B8 as ye,r0 as ze,E as Ae,oj as Be,aj as Ce,tj as De,zY as Ee,XY as Fe,OY as Ge,m8 as He,GO as Ie,c$ as Je,B0 as Ke,B1 as Le,d$ as Me,k1 as Ne,l$ as Oe,i$ as Pe,s$ as Qe,hZ as Re,cZ as Se,w1 as Te,dZ as Ue,BY as Ve};
|
|
45
|
+
|
|
46
|
+
//# debugId=23D19F7D3D7A0DA864756E2164756E21
|