gemi 0.167.0 → 0.168.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +3 -5
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +16 -2
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/Prompt.d.ts +15 -1
- package/dist/ai/Prompt.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +32 -32
- package/dist/ai/index.js.map +4 -4
- package/dist/app/index.js +1 -1
- package/dist/bin/gemi.js +405 -376
- package/dist/bin/gemi.js.map +5 -4
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-eyv6hss6.js → chunk-0q65jzhv.js} +2 -2
- package/dist/{chunk-eyv6hss6.js.map → chunk-0q65jzhv.js.map} +1 -1
- package/dist/{chunk-p3qbym3v.js → chunk-0wet87jm.js} +2 -2
- package/dist/{chunk-p3qbym3v.js.map → chunk-0wet87jm.js.map} +1 -1
- package/dist/{chunk-4fzevafk.js → chunk-0wk992a5.js} +2 -2
- package/dist/{chunk-4fzevafk.js.map → chunk-0wk992a5.js.map} +1 -1
- package/dist/{chunk-q4vtjdea.js → chunk-17272ccy.js} +3 -3
- package/dist/{chunk-q4vtjdea.js.map → chunk-17272ccy.js.map} +1 -1
- package/dist/{chunk-w4at2d5d.js → chunk-1h6g1hkg.js} +2 -2
- package/dist/{chunk-w4at2d5d.js.map → chunk-1h6g1hkg.js.map} +1 -1
- package/dist/{chunk-hdt8cwsv.js → chunk-21hppqtb.js} +2 -2
- package/dist/{chunk-hdt8cwsv.js.map → chunk-21hppqtb.js.map} +1 -1
- package/dist/{chunk-qec3g4w3.js → chunk-2v7wq01w.js} +2 -2
- package/dist/{chunk-qec3g4w3.js.map → chunk-2v7wq01w.js.map} +1 -1
- package/dist/{chunk-z316fasf.js → chunk-2xtkh8bh.js} +19 -19
- package/dist/{chunk-z316fasf.js.map → chunk-2xtkh8bh.js.map} +3 -3
- package/dist/{chunk-0hfvwzd1.js → chunk-31np60bx.js} +2 -2
- package/dist/{chunk-0hfvwzd1.js.map → chunk-31np60bx.js.map} +1 -1
- package/dist/{chunk-mbkje42z.js → chunk-3682hkq0.js} +2 -2
- package/dist/{chunk-mbkje42z.js.map → chunk-3682hkq0.js.map} +1 -1
- package/dist/{chunk-fnj2hc5v.js → chunk-3rp908gn.js} +1 -1
- package/dist/{chunk-3xj1e3ns.js → chunk-44y62yav.js} +3 -3
- package/dist/{chunk-3xj1e3ns.js.map → chunk-44y62yav.js.map} +1 -1
- package/dist/{chunk-c3cdj9y7.js → chunk-4mtqbcc5.js} +2 -2
- package/dist/{chunk-c3cdj9y7.js.map → chunk-4mtqbcc5.js.map} +1 -1
- package/dist/{chunk-80703vks.js → chunk-4qpyz627.js} +2 -2
- package/dist/{chunk-80703vks.js.map → chunk-4qpyz627.js.map} +1 -1
- package/dist/{chunk-4rnpvajg.js → chunk-4tt14jnx.js} +2 -2
- package/dist/{chunk-4rnpvajg.js.map → chunk-4tt14jnx.js.map} +1 -1
- package/dist/{chunk-efjk5aq7.js → chunk-5n21z4n8.js} +2 -2
- package/dist/{chunk-efjk5aq7.js.map → chunk-5n21z4n8.js.map} +1 -1
- package/dist/{chunk-pk4drzc9.js → chunk-5nz46dyw.js} +2 -2
- package/dist/{chunk-pk4drzc9.js.map → chunk-5nz46dyw.js.map} +1 -1
- package/dist/{chunk-6tbs7yc1.js → chunk-6t1t7h05.js} +2 -2
- package/dist/{chunk-6tbs7yc1.js.map → chunk-6t1t7h05.js.map} +1 -1
- package/dist/{chunk-tms2g9at.js → chunk-777v6242.js} +1 -1
- package/dist/{chunk-kcgnjzqr.js → chunk-8b9ks729.js} +3 -3
- package/dist/{chunk-kcgnjzqr.js.map → chunk-8b9ks729.js.map} +1 -1
- package/dist/{chunk-8f4jkpv7.js → chunk-8hfyscnn.js} +1 -1
- package/dist/{chunk-4587ab6m.js → chunk-978pc27j.js} +2 -2
- package/dist/{chunk-4587ab6m.js.map → chunk-978pc27j.js.map} +1 -1
- package/dist/{chunk-y1ks8ahw.js → chunk-9aj6eavs.js} +2 -2
- package/dist/{chunk-y1ks8ahw.js.map → chunk-9aj6eavs.js.map} +1 -1
- package/dist/{chunk-xw5d66ec.js → chunk-9akefv1y.js} +2 -2
- package/dist/{chunk-xw5d66ec.js.map → chunk-9akefv1y.js.map} +1 -1
- package/dist/{chunk-y6x52vkb.js → chunk-9ft0ayhf.js} +2 -2
- package/dist/{chunk-y6x52vkb.js.map → chunk-9ft0ayhf.js.map} +1 -1
- package/dist/{chunk-m5hd632w.js → chunk-9wcv7e1a.js} +2 -2
- package/dist/{chunk-h5whhrds.js.map → chunk-9wcv7e1a.js.map} +1 -1
- package/dist/{chunk-matvbghh.js → chunk-a053eza0.js} +2 -2
- package/dist/{chunk-matvbghh.js.map → chunk-a053eza0.js.map} +1 -1
- package/dist/{chunk-c0dvdfm0.js → chunk-a9frf7ym.js} +2 -2
- package/dist/{chunk-c0dvdfm0.js.map → chunk-a9frf7ym.js.map} +1 -1
- package/dist/{chunk-2jk0f4sj.js → chunk-aj1jrwwh.js} +2 -2
- package/dist/{chunk-2jk0f4sj.js.map → chunk-aj1jrwwh.js.map} +1 -1
- package/dist/{chunk-tqgpahmn.js → chunk-bb3fdgwt.js} +4 -4
- package/dist/{chunk-tqgpahmn.js.map → chunk-bb3fdgwt.js.map} +1 -1
- package/dist/{chunk-36yp8364.js → chunk-c46vhvk4.js} +2 -2
- package/dist/{chunk-36yp8364.js.map → chunk-c46vhvk4.js.map} +1 -1
- package/dist/{chunk-5x9b1ema.js → chunk-df2zeevj.js} +2 -2
- package/dist/{chunk-5x9b1ema.js.map → chunk-df2zeevj.js.map} +1 -1
- package/dist/{chunk-ndyafsv6.js → chunk-drwjwtmj.js} +2 -2
- package/dist/{chunk-ndyafsv6.js.map → chunk-drwjwtmj.js.map} +1 -1
- package/dist/{chunk-wypncj52.js → chunk-ecdjbd2w.js} +3 -3
- package/dist/{chunk-wypncj52.js.map → chunk-ecdjbd2w.js.map} +1 -1
- package/dist/{chunk-6cw6tn57.js → chunk-embwksec.js} +2 -2
- package/dist/{chunk-6cw6tn57.js.map → chunk-embwksec.js.map} +1 -1
- package/dist/{chunk-mcavkjh4.js → chunk-esjt9q54.js} +2 -2
- package/dist/{chunk-mcavkjh4.js.map → chunk-esjt9q54.js.map} +1 -1
- package/dist/chunk-f4nanvkm.js +5 -0
- package/dist/{chunk-8v6y52et.js.map → chunk-f4nanvkm.js.map} +1 -1
- package/dist/{chunk-b8qfypzq.js → chunk-fb77hwk0.js} +3 -3
- package/dist/{chunk-b8qfypzq.js.map → chunk-fb77hwk0.js.map} +1 -1
- package/dist/{chunk-fva651jp.js → chunk-fcbgshf5.js} +2 -2
- package/dist/{chunk-fva651jp.js.map → chunk-fcbgshf5.js.map} +1 -1
- package/dist/{chunk-f6mwnw81.js → chunk-g1jfc50d.js} +3 -3
- package/dist/{chunk-f6mwnw81.js.map → chunk-g1jfc50d.js.map} +1 -1
- package/dist/{chunk-0psf0chk.js → chunk-g548q257.js} +2 -2
- package/dist/{chunk-0psf0chk.js.map → chunk-g548q257.js.map} +1 -1
- package/dist/{chunk-wjff0d08.js → chunk-gjwf07hy.js} +3 -3
- package/dist/{chunk-wjff0d08.js.map → chunk-gjwf07hy.js.map} +1 -1
- package/dist/{chunk-2ewe42dq.js → chunk-gwphn604.js} +3 -3
- package/dist/{chunk-2ewe42dq.js.map → chunk-gwphn604.js.map} +1 -1
- package/dist/{chunk-xed7yf6h.js → chunk-hgpvfhtp.js} +1 -1
- package/dist/{chunk-h5whhrds.js → chunk-hwpp9b7f.js} +2 -2
- package/dist/{chunk-m5hd632w.js.map → chunk-hwpp9b7f.js.map} +1 -1
- package/dist/{chunk-vqf4s99d.js → chunk-jd079awh.js} +2 -2
- package/dist/{chunk-vqf4s99d.js.map → chunk-jd079awh.js.map} +1 -1
- package/dist/{chunk-1ap3vcrr.js → chunk-jxx9mctk.js} +2 -2
- package/dist/{chunk-1ap3vcrr.js.map → chunk-jxx9mctk.js.map} +1 -1
- package/dist/{chunk-mj429x94.js → chunk-k87tqe29.js} +2 -2
- package/dist/{chunk-mj429x94.js.map → chunk-k87tqe29.js.map} +1 -1
- package/dist/{chunk-1k4rvfza.js → chunk-kbw6y0ag.js} +2 -2
- package/dist/{chunk-1k4rvfza.js.map → chunk-kbw6y0ag.js.map} +1 -1
- package/dist/{chunk-pr2enaz5.js → chunk-krdq5s4y.js} +2 -2
- package/dist/{chunk-pr2enaz5.js.map → chunk-krdq5s4y.js.map} +1 -1
- package/dist/{chunk-7ysw97gp.js → chunk-m6sj1q1q.js} +2 -2
- package/dist/{chunk-7ysw97gp.js.map → chunk-m6sj1q1q.js.map} +1 -1
- package/dist/{chunk-hgvt5084.js → chunk-m950vw4c.js} +2 -2
- package/dist/{chunk-hgvt5084.js.map → chunk-m950vw4c.js.map} +1 -1
- package/dist/{chunk-873k84dt.js → chunk-mm45shzv.js} +2 -2
- package/dist/{chunk-873k84dt.js.map → chunk-mm45shzv.js.map} +1 -1
- package/dist/{chunk-6q15sx3h.js → chunk-p56zntmt.js} +3 -3
- package/dist/{chunk-6q15sx3h.js.map → chunk-p56zntmt.js.map} +1 -1
- package/dist/{chunk-ndj94vde.js → chunk-q01p8ta3.js} +2 -2
- package/dist/{chunk-ndj94vde.js.map → chunk-q01p8ta3.js.map} +1 -1
- package/dist/{chunk-p97w2388.js → chunk-q3511sb5.js} +2 -2
- package/dist/{chunk-p97w2388.js.map → chunk-q3511sb5.js.map} +1 -1
- package/dist/{chunk-kfdy4vv1.js → chunk-q788x8pm.js} +2 -2
- package/dist/{chunk-kfdy4vv1.js.map → chunk-q788x8pm.js.map} +1 -1
- package/dist/{chunk-23670kw5.js → chunk-rpdekb8t.js} +2 -2
- package/dist/{chunk-23670kw5.js.map → chunk-rpdekb8t.js.map} +1 -1
- package/dist/{chunk-j7k0nzqz.js → chunk-s4fb4njt.js} +2 -2
- package/dist/{chunk-j7k0nzqz.js.map → chunk-s4fb4njt.js.map} +1 -1
- package/dist/{chunk-7yh908jj.js → chunk-s71e6k9m.js} +3 -3
- package/dist/{chunk-7yh908jj.js.map → chunk-s71e6k9m.js.map} +1 -1
- package/dist/{chunk-6eb6jgdv.js → chunk-sdn3dmpp.js} +4 -4
- package/dist/{chunk-6eb6jgdv.js.map → chunk-sdn3dmpp.js.map} +1 -1
- package/dist/{chunk-fxd7pqk3.js → chunk-sp77zwpn.js} +2 -2
- package/dist/{chunk-fxd7pqk3.js.map → chunk-sp77zwpn.js.map} +1 -1
- package/dist/{chunk-82jhqxx7.js → chunk-sv86v56c.js} +3 -3
- package/dist/{chunk-82jhqxx7.js.map → chunk-sv86v56c.js.map} +1 -1
- package/dist/{chunk-bym06a64.js → chunk-sxf94q13.js} +2 -2
- package/dist/{chunk-bym06a64.js.map → chunk-sxf94q13.js.map} +1 -1
- package/dist/{chunk-pd3qbf8r.js → chunk-ta2wsjz6.js} +2 -2
- package/dist/{chunk-pd3qbf8r.js.map → chunk-ta2wsjz6.js.map} +1 -1
- package/dist/{chunk-58k1zstz.js → chunk-thbs63gy.js} +1 -1
- package/dist/{chunk-71prz4rp.js → chunk-vfvjfw5k.js} +2 -2
- package/dist/{chunk-71prz4rp.js.map → chunk-vfvjfw5k.js.map} +1 -1
- package/dist/{chunk-sca3tpce.js → chunk-vnk4vaer.js} +3 -3
- package/dist/{chunk-sca3tpce.js.map → chunk-vnk4vaer.js.map} +1 -1
- package/dist/{chunk-qnv9w5g5.js → chunk-wc2sg9ny.js} +2 -2
- package/dist/{chunk-qnv9w5g5.js.map → chunk-wc2sg9ny.js.map} +1 -1
- package/dist/{chunk-rzqxkm9r.js → chunk-wp9hw3we.js} +2 -2
- package/dist/{chunk-rzqxkm9r.js.map → chunk-wp9hw3we.js.map} +1 -1
- package/dist/{chunk-4w9gbe11.js → chunk-wt1yzzbw.js} +1 -1
- package/dist/{chunk-d29dcs3e.js → chunk-xkas0yp8.js} +3 -3
- package/dist/{chunk-d29dcs3e.js.map → chunk-xkas0yp8.js.map} +1 -1
- package/dist/{chunk-j1yhtwsk.js → chunk-y3s05q6b.js} +2 -2
- package/dist/{chunk-j1yhtwsk.js.map → chunk-y3s05q6b.js.map} +1 -1
- package/dist/{chunk-ndawdgtt.js → chunk-ys8nk9ga.js} +3 -3
- package/dist/{chunk-ndawdgtt.js.map → chunk-ys8nk9ga.js.map} +1 -1
- package/dist/{chunk-0gzqhjyg.js → chunk-z4dhd5pk.js} +2 -2
- package/dist/{chunk-0gzqhjyg.js.map → chunk-z4dhd5pk.js.map} +1 -1
- package/dist/{chunk-xxbkp90v.js → chunk-z5g56ds0.js} +3 -3
- package/dist/{chunk-xxbkp90v.js.map → chunk-z5g56ds0.js.map} +1 -1
- package/dist/{chunk-bzrhc7q3.js → chunk-zqptpk90.js} +2 -2
- package/dist/{chunk-bzrhc7q3.js.map → chunk-zqptpk90.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/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/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +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/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-8v6y52et.js +0 -5
- /package/dist/{chunk-fnj2hc5v.js.map → chunk-3rp908gn.js.map} +0 -0
- /package/dist/{chunk-tms2g9at.js.map → chunk-777v6242.js.map} +0 -0
- /package/dist/{chunk-8f4jkpv7.js.map → chunk-8hfyscnn.js.map} +0 -0
- /package/dist/{chunk-xed7yf6h.js.map → chunk-hgpvfhtp.js.map} +0 -0
- /package/dist/{chunk-58k1zstz.js.map → chunk-thbs63gy.js.map} +0 -0
- /package/dist/{chunk-4w9gbe11.js.map → chunk-wt1yzzbw.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{kh as HK}from"./chunk-sca3tpce.js";import{Eh as LK}from"./chunk-d29dcs3e.js";import{Di as _1,Fh as z3,Hi as LQ,Ii as n$,Jh as PG,Ji as o$,Kh as qW,Ki as aG,Lh as yW,Mh as D8,Mi as rG,Nh as G8,Qh as K8,Rh as B8,Sh as oZ,Th as aQ,Uh as IJ,Vh as jW,Wh as h,ai as C,bi as q8,ci as KZ,di as O8,ei as Q6,gi as I$,hi as g,ii as h4,qi as G6,wi as K6}from"./chunk-ndawdgtt.js";import{Pi as s1,Qi as J0,Ri as o1,Si as gW}from"./chunk-efjk5aq7.js";import{Ti as l$,Ui as xJ,Yi as NY,Zi as s4,_i as N}from"./chunk-w4at2d5d.js";import{bj as zQ,ej as c3}from"./chunk-7yh908jj.js";import{ij as wY,lj as dG}from"./chunk-b8qfypzq.js";import{Dj as N$,Ij as n1}from"./chunk-1ap3vcrr.js";import{Wj as cX}from"./chunk-j7k0nzqz.js";import{Xj as a$,_j as pG}from"./chunk-6tbs7yc1.js";import{$j as L1}from"./chunk-c0dvdfm0.js";import{ak as Y6,bk as d0,ck as x1,dk as lJ,ek as OK,gk as pZ,hk as nG,qk as iJ}from"./chunk-2ewe42dq.js";import{Fk as C1}from"./chunk-hgvt5084.js";import{Kk as LG,Pk as OJ}from"./chunk-4587ab6m.js";import{$k as d,Wk as OG}from"./chunk-71prz4rp.js";import{al as nZ,dl as H}from"./chunk-kcgnjzqr.js";import{ll as VJ}from"./chunk-fxd7pqk3.js";import{ml as tG}from"./chunk-xw5d66ec.js";import{wl as QJ}from"./chunk-23670kw5.js";import{xl as $8,zl as TG}from"./chunk-vqf4s99d.js";import{El as n4}from"./chunk-m5hd632w.js";function t3($){return typeof $==="function"&&$.prototype!==void 0}var aJ=Symbol.for("gemi.HttpResponse"),EK=new Set([301,302,303,307,308]);class j1{kind;body;status;headers;[aJ]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return oJ(J,"json"),new j1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return j1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!EK.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new j1("empty",void 0,J,Y)}static noContent($={}){return new j1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return oJ(J,"text"),new j1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function oJ($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function u1($){return typeof $==="object"&&$!==null&&$[aJ]===!0}function bK($,Z,J={}){return j1.error($,Z,J)}function s0($){return typeof $==="string"?[$]:$}function e3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function RK($){return"total"in $&&"partial"in $&&"body"in $}function rJ(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":B8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function fK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RK($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function F8($,Z){if($ instanceof Response)return $;if(!$)return rJ();let J=await fK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return rJ()}let{range:Q}=Z;if(Q){if(z<=0)return Z3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=G8(Q,z);if(!K)return Z3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),G)F.set("Content-Range",K8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",e3(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[K,V]of Object.entries(J.extraHeaders))F.set(K,V);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:F})}return new Response(W,{status:B,headers:F})}class jZ extends J0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var tJ={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function W3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in tJ)))return Math.floor(Number(J[1])*(tJ[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var J3=new WeakMap;function $W($){return J3.has($)}function ZW($){return J3.get($)?.limit??null}function JW($){let Z=J3.get($);return Z?Z.read>Z.limit:!1}function kK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function U8($,Z){let J=kK($);if(J!==null&&J>Z)throw new jZ(Z)}function $6($,Z,J={}){let W=J3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};J3.set($,Y),qK($,Y)}if(J.checkDeclared!==!1)U8($,Z)}function wK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function V8($,Z){if(Z.stream!==void 0)return Z.stream;let J=wK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new jZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function YZ($,Z){if(U8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=V8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function eJ($){return $.headers.get("Content-Type")??""}function qK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>V8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>YZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await YZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await YZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await YZ($,Z)))}),J("blob",{value:async()=>new Blob([await YZ($,Z)],{type:eJ($)})}),J("formData",{value:async()=>new Response(await YZ($,Z),{headers:{"Content-Type":eJ($)}}).formData()}),J("clone",{value:()=>{U8($,Z.limit);let W=V8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function WW($){return t3($)}class s{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!WW(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(WW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=s0($),this}}class zW{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=s0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of jW($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(JW($.rawRequest))throw new jZ(ZW($.rawRequest));throw J}}}class XW{constructor(...$){return new s(...$)}}class QW extends s{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=D8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(u1(Y))return Y;return await F8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof O8)return Z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class GW{constructor(...$){return new QW(...$)}}class KW{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new s("GET",$,"list"),post:new s("POST",$,"store")},this.second={get:new s("GET",$,"show"),put:new s("PUT",$,"update"),delete:new s("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class I0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new s("GET",$,Z)}post($,Z){return new s("POST",$,Z)}put($,Z){return new s("PUT",$,Z)}patch($,Z){return new s("PATCH",$,Z)}delete($,Z){return new s("DELETE",$,Z)}resource($){return new KW($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${YW($)}.`);return yK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${YW($)}.`);return vK($)}file($,Z){return new XW("GET",$,Z)}stream($,Z){return new GW("GET",$,Z)}proxy($,Z={}){return new zW($,Z)}}function YW($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function yK($){let Z={stream:new s("POST",$,"stream"),attach:new s("POST",$,"attach"),stop:new s("POST",$,"stop"),upload:new s("POST",$,"upload")};return class extends I0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function vK($){let Z={start:new s("POST",$,"voiceStart"),update:new s("PATCH",$,"voiceUpdate"),end:new s("DELETE",$,"voiceEnd")};return class extends I0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var l1="access_token";function T$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Z6($,Z){let J=T$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var gK=/^[A-Za-z0-9_-]+$/,mK=/^:[A-Za-z_][A-Za-z0-9_]*$/,BW=/^[A-Za-z0-9_-]{1,128}$/,hK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function FW($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function zZ($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(mK.test(W)){let Y=W.slice(1);if(J.has(Y))throw new p(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new p(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!gK.test(W))throw new p(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function Y3($,Z={}){let J=zZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!BW.test(Q))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function L8($){if(zZ($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function VW($){if(typeof $!=="string"||$.length===0||$.length>64||!hK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function UW($,Z){if($===Z)return!0;if($===K0)return Z.startsWith(`${K0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&BW.test(W[j]))}var K0="user";function XZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return Y3(`${K0}.:id`,{id:Z})}class t{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class J6 extends t{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return $6(this.req.rawRequest,W3(Z)),{}}}function pK($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var cK={"body-limit":J6};class i1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:W3($.bodyLimit)}get aliases(){return{...cK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!$W($))$6($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of pK($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:DW(z)})}}else if(t3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:DW(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await dK(W.slice(j+1)),z}return Y})()}}function DW($){return $?.runsOnRefusal===!0}async function dK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class W6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...s0($)],this}events(...$){return this}}class MW{static __brand="ChannelRouter";channels={};public(){return new W6("public")}private($){return new W6("private",$)}async authorize($,Z,J={},W={}){try{sK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!PW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===K0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=Y3(Z,J??{})}catch(Q){if(Q instanceof p)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return N.exit(()=>Y6.exit(()=>N.run(X,async()=>{let Q=N.getStore();try{if(Y.middlewares.length>0)await H(i1).runMiddleware(Y.middlewares);if(Z===K0){let G=await OW(X);if(!G)return{ok:!1,code:"denied"};if(j=XZ(G),Y.visibility==="private"&&Y.authorizer){if(await LW(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await LW(Y.authorizer,X,z):await OW(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(iK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function uK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;TW(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function PW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function OW($){if(!N.getStore().user&&T$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function LW($,Z,J){if(lK($))return new $().authorize(Z,J);return $(Z,J)}function lK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function iK($){return $?.kind===s1||n1($)||N$($)}var HW=new WeakSet;function sK($){if(HW.has($))return;TW($),HW.add($)}function TW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!PW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=zZ(W);if(j[0].startsWith(":"))throw new p(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==K0&&j.length===2&&j[0]===K0)throw new p(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==K0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===K0?[K0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(nK(J[W].segments,J[Y].segments))throw new p(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function nK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class H8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class j6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class M8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function oK($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function aK($,Z){let J=oK($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class NW{static __brand="McpRouter";routes={};scopes;param($){return new H8($.as,$.input,$.bind)}fromTool($,Z={}){return new M8($,Z)}fromApiRoute($,Z,J){return new j6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let F={},K=new Map;for(let V of B){let{name:U,casing:D,description:O,params:L,files:T,...P}=Y[V],_=U??(D?aK(W,D):W);if(K.has(_))throw Error(`${G}: the audiences "${K.get(_)}" and "${V}" are both named "${_}". Give one its own name or casing.`);K.set(_,V);let A=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof A!=="string")throw Error(`${G}: the audience "${V}" has no description, and there is no shared one.`);let E={...Q,...P,description:A};if(z||L)E.params={...z,...L};if(X||T)E.files={...X,...T};F[_]=new j6($,Z,E)}return F}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class P8 extends J0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class N1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new P8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new P8($,Z)}}class IW{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return N1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function T8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",e3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class _W{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function xW($,Z){if(u1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class CW{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=xW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=s0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class AW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends I1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends I1{routes=J??{}}}else this.children=class extends I1{routes=Z},this.handler=()=>({})}async run($,Z){let J=xW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class I1{middlewares=[];featureGates=[];routes={};view($,Z){return new CW($,Z)}file($){return new _W($)}redirect($){return new IW($)}layout($,Z,J){return new AW($,Z,J)}}function rK($){return $}function tK(){return{aliases:{},global:[],bodyLimit:null}}var z1="redirect";function X1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function QZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function eK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(d).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function $B($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function z6($,Z){let J=Z||H(b).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=eK($,!W);if(W||!$B(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(z1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class SW extends t{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await Z6(H(b),J);if(!W)throw new I$({redirectTo:z6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",N8="private, no-cache, no-store, max-age=0, must-revalidate";class X6 extends t{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(I8))return{};if(T$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new EW(`${W.pathname}${W.search}`)}}class EW extends J0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=ZB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":N8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":N8}},viewData:{status:200,data:{},headers:{"Cache-Control":N8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function ZB($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class bW extends t{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var RW={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class fW extends t{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...RW,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...RW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var JB="Rate limit exceeded";class a1 extends J0{result;retryAfter;constructor($,Z=JB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?_8($):{}};this.payload={api:{status:429,data:{error:{...o1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function _8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class Q1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(kW("window",W),kW("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new a1(W,typeof J==="function"?J(W):J);return W}}function kW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as x8}from"net";function _$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return x8(j)===6?j:null}if(x8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&x8(J[1])===4?J[1]:null}class vW extends t{async run($,Z){let J=WB();if(!J)return{};let W=await J.consume(this.key(),{limit:wW($)??this.config.limit,window:wW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(_8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new a1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=qW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${GZ(this.req)}:${this.req.routePath??"*"}`}}function WB(){try{let $=H();return $.bound(Q1)?$.make(Q1):null}catch{return null}}function GZ($){let Z=yW($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return _$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function wW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class mW extends t{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new C8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new C8;return{}}}class C8 extends J0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:gW("csrf","Invalid CSRF token",403)}},view:{}}}class hW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class pW{all($,Z){return!0}}class A8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new KZ:new Q6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends t{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof KZ:$ instanceof Q6}}function YB($){return new A8($)}async function B6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await LB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return OB(z,Z,J,$.url)}async function OB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new K6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function LB($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function F6($){return new TextDecoder("utf-8").decode($)}var HB={"&":"&","<":"<",">":">",'"':""","'":"'"};function x$($){return $.replace(/[&<>"']/g,(Z)=>HB[Z])}var MB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function S8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return MB[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function E8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function cW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(S8($.slice(W)));return}if(Y>W)Z.text(S8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(E8($.slice(Y+2,j).trim())),W=j+1}else{let j=PB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=E8(z.slice(0,Q));if(G){if(Z.open(G,TB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function PB($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function TB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[E8(W[1])]=S8(W[2]??W[3]??"");return Z}class W0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var sW="http://www.sitemaps.org/schemas/sitemap/0.9",NB="http://www.w3.org/1999/xhtml",f8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
import{lh as HK}from"./chunk-vnk4vaer.js";import{Fh as LK}from"./chunk-xkas0yp8.js";import{Ei as _1,Gh as z3,Ii as LQ,Ji as n$,Kh as PG,Ki as o$,Lh as qW,Li as aG,Mh as yW,Nh as D8,Ni as rG,Oh as G8,Rh as K8,Sh as B8,Th as oZ,Uh as aQ,Vh as IJ,Wh as jW,Xh as h,bi as C,ci as q8,di as KZ,ei as O8,fi as Q6,hi as I$,ii as g,ji as h4,ri as G6,xi as K6}from"./chunk-ys8nk9ga.js";import{Qi as s1,Ri as J0,Si as o1,Ti as gW}from"./chunk-5n21z4n8.js";import{$i as N,Ui as l$,Vi as xJ,Zi as NY,_i as s4}from"./chunk-1h6g1hkg.js";import{cj as zQ,fj as c3}from"./chunk-s71e6k9m.js";import{jj as wY,mj as dG}from"./chunk-fb77hwk0.js";import{Ej as N$,Jj as n1}from"./chunk-jxx9mctk.js";import{Xj as cX}from"./chunk-s4fb4njt.js";import{$j as pG,Yj as a$}from"./chunk-6t1t7h05.js";import{ak as L1}from"./chunk-a9frf7ym.js";import{bk as Y6,ck as d0,dk as x1,ek as lJ,fk as OK,hk as pZ,ik as nG,rk as iJ}from"./chunk-gwphn604.js";import{Gk as C1}from"./chunk-m950vw4c.js";import{Lk as LG,Qk as OJ}from"./chunk-978pc27j.js";import{Xk as OG,al as d}from"./chunk-vfvjfw5k.js";import{bl as nZ,el as H}from"./chunk-8b9ks729.js";import{ml as VJ}from"./chunk-sp77zwpn.js";import{nl as tG}from"./chunk-9akefv1y.js";import{xl as QJ}from"./chunk-rpdekb8t.js";import{Al as TG,yl as $8}from"./chunk-jd079awh.js";import{Fl as n4}from"./chunk-9wcv7e1a.js";function t3($){return typeof $==="function"&&$.prototype!==void 0}var aJ=Symbol.for("gemi.HttpResponse"),EK=new Set([301,302,303,307,308]);class j1{kind;body;status;headers;[aJ]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return oJ(J,"json"),new j1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return j1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!EK.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new j1("empty",void 0,J,Y)}static noContent($={}){return new j1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return oJ(J,"text"),new j1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function oJ($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function u1($){return typeof $==="object"&&$!==null&&$[aJ]===!0}function bK($,Z,J={}){return j1.error($,Z,J)}function s0($){return typeof $==="string"?[$]:$}function e3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function RK($){return"total"in $&&"partial"in $&&"body"in $}function rJ(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":B8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function fK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RK($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function F8($,Z){if($ instanceof Response)return $;if(!$)return rJ();let J=await fK($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return rJ()}let{range:Q}=Z;if(Q){if(z<=0)return Z3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=G8(Q,z);if(!K)return Z3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),G)F.set("Content-Range",K8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",e3(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[K,V]of Object.entries(J.extraHeaders))F.set(K,V);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:F})}return new Response(W,{status:B,headers:F})}class jZ extends J0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var tJ={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function W3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in tJ)))return Math.floor(Number(J[1])*(tJ[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var J3=new WeakMap;function $W($){return J3.has($)}function ZW($){return J3.get($)?.limit??null}function JW($){let Z=J3.get($);return Z?Z.read>Z.limit:!1}function kK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function U8($,Z){let J=kK($);if(J!==null&&J>Z)throw new jZ(Z)}function $6($,Z,J={}){let W=J3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};J3.set($,Y),qK($,Y)}if(J.checkDeclared!==!1)U8($,Z)}function wK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function V8($,Z){if(Z.stream!==void 0)return Z.stream;let J=wK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new jZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function YZ($,Z){if(U8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=V8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function eJ($){return $.headers.get("Content-Type")??""}function qK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>V8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>YZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await YZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await YZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await YZ($,Z)))}),J("blob",{value:async()=>new Blob([await YZ($,Z)],{type:eJ($)})}),J("formData",{value:async()=>new Response(await YZ($,Z),{headers:{"Content-Type":eJ($)}}).formData()}),J("clone",{value:()=>{U8($,Z.limit);let W=V8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function WW($){return t3($)}class s{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!WW(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(WW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=s0($),this}}class zW{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=s0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of jW($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(JW($.rawRequest))throw new jZ(ZW($.rawRequest));throw J}}}class XW{constructor(...$){return new s(...$)}}class QW extends s{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=D8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(u1(Y))return Y;return await F8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof O8)return Z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class GW{constructor(...$){return new QW(...$)}}class KW{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new s("GET",$,"list"),post:new s("POST",$,"store")},this.second={get:new s("GET",$,"show"),put:new s("PUT",$,"update"),delete:new s("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class I0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new s("GET",$,Z)}post($,Z){return new s("POST",$,Z)}put($,Z){return new s("PUT",$,Z)}patch($,Z){return new s("PATCH",$,Z)}delete($,Z){return new s("DELETE",$,Z)}resource($){return new KW($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${YW($)}.`);return yK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${YW($)}.`);return vK($)}file($,Z){return new XW("GET",$,Z)}stream($,Z){return new GW("GET",$,Z)}proxy($,Z={}){return new zW($,Z)}}function YW($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function yK($){let Z={stream:new s("POST",$,"stream"),attach:new s("POST",$,"attach"),stop:new s("POST",$,"stop"),upload:new s("POST",$,"upload")};return class extends I0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function vK($){let Z={start:new s("POST",$,"voiceStart"),update:new s("PATCH",$,"voiceUpdate"),end:new s("DELETE",$,"voiceEnd")};return class extends I0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var l1="access_token";function T$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Z6($,Z){let J=T$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var gK=/^[A-Za-z0-9_-]+$/,mK=/^:[A-Za-z_][A-Za-z0-9_]*$/,BW=/^[A-Za-z0-9_-]{1,128}$/,hK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function FW($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function zZ($){if(typeof $!=="string"||$.length===0)throw new p("A channel pattern must be a non-empty string.");if($.length>255)throw new p(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(mK.test(W)){let Y=W.slice(1);if(J.has(Y))throw new p(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new p(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!gK.test(W))throw new p(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function Y3($,Z={}){let J=zZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new p(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!BW.test(Q))throw new p(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new p(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new p(`The topic built from "${$}" is longer than 255 characters.`);return Y}function L8($){if(zZ($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function VW($){if(typeof $!=="string"||$.length===0||$.length>64||!hK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function UW($,Z){if($===Z)return!0;if($===K0)return Z.startsWith(`${K0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&BW.test(W[j]))}var K0="user";function XZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return Y3(`${K0}.:id`,{id:Z})}class t{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class J6 extends t{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return $6(this.req.rawRequest,W3(Z)),{}}}function pK($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var cK={"body-limit":J6};class i1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:W3($.bodyLimit)}get aliases(){return{...cK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!$W($))$6($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of pK($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:DW(z)})}}else if(t3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:DW(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await dK(W.slice(j+1)),z}return Y})()}}function DW($){return $?.runsOnRefusal===!0}async function dK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class W6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...s0($)],this}events(...$){return this}}class MW{static __brand="ChannelRouter";channels={};public(){return new W6("public")}private($){return new W6("private",$)}async authorize($,Z,J={},W={}){try{sK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!PW(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===K0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=Y3(Z,J??{})}catch(Q){if(Q instanceof p)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return N.exit(()=>Y6.exit(()=>N.run(X,async()=>{let Q=N.getStore();try{if(Y.middlewares.length>0)await H(i1).runMiddleware(Y.middlewares);if(Z===K0){let G=await OW(X);if(!G)return{ok:!1,code:"denied"};if(j=XZ(G),Y.visibility==="private"&&Y.authorizer){if(await LW(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await LW(Y.authorizer,X,z):await OW(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(iK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function uK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;TW(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function PW($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function OW($){if(!N.getStore().user&&T$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function LW($,Z,J){if(lK($))return new $().authorize(Z,J);return $(Z,J)}function lK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function iK($){return $?.kind===s1||n1($)||N$($)}var HW=new WeakSet;function sK($){if(HW.has($))return;TW($),HW.add($)}function TW($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!PW(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=zZ(W);if(j[0].startsWith(":"))throw new p(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==K0&&j.length===2&&j[0]===K0)throw new p(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==K0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new p(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===K0?[K0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(nK(J[W].segments,J[Y].segments))throw new p(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function nK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class H8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class j6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class M8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function oK($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function aK($,Z){let J=oK($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class NW{static __brand="McpRouter";routes={};scopes;param($){return new H8($.as,$.input,$.bind)}fromTool($,Z={}){return new M8($,Z)}fromApiRoute($,Z,J){return new j6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let F={},K=new Map;for(let V of B){let{name:U,casing:D,description:O,params:L,files:T,...P}=Y[V],_=U??(D?aK(W,D):W);if(K.has(_))throw Error(`${G}: the audiences "${K.get(_)}" and "${V}" are both named "${_}". Give one its own name or casing.`);K.set(_,V);let A=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof A!=="string")throw Error(`${G}: the audience "${V}" has no description, and there is no shared one.`);let E={...Q,...P,description:A};if(z||L)E.params={...z,...L};if(X||T)E.files={...X,...T};F[_]=new j6($,Z,E)}return F}}function B0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class P8 extends J0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class N1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new P8([B0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new P8($,Z)}}class IW{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return N1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function T8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",e3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class _W{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function xW($,Z){if(u1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class CW{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=xW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=s0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class AW{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends I1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends I1{routes=J??{}}}else this.children=class extends I1{routes=Z},this.handler=()=>({})}async run($,Z){let J=xW(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=s0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class I1{middlewares=[];featureGates=[];routes={};view($,Z){return new CW($,Z)}file($){return new _W($)}redirect($){return new IW($)}layout($,Z,J){return new AW($,Z,J)}}function rK($){return $}function tK(){return{aliases:{},global:[],bodyLimit:null}}var z1="redirect";function X1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function QZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function eK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(d).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function $B($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function z6($,Z){let J=Z||H(b).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=eK($,!W);if(W||!$B(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(z1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class SW extends t{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await Z6(H(b),J);if(!W)throw new I$({redirectTo:z6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",N8="private, no-cache, no-store, max-age=0, must-revalidate";class X6 extends t{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(I8))return{};if(T$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new EW(`${W.pathname}${W.search}`)}}class EW extends J0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=ZB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":N8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":N8}},viewData:{status:200,data:{},headers:{"Cache-Control":N8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function ZB($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class bW extends t{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var RW={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class fW extends t{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...RW,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...RW,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var JB="Rate limit exceeded";class a1 extends J0{result;retryAfter;constructor($,Z=JB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?_8($):{}};this.payload={api:{status:429,data:{error:{...o1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function _8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class Q1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(kW("window",W),kW("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new a1(W,typeof J==="function"?J(W):J);return W}}function kW($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as x8}from"net";function _$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return x8(j)===6?j:null}if(x8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&x8(J[1])===4?J[1]:null}class vW extends t{async run($,Z){let J=WB();if(!J)return{};let W=await J.consume(this.key(),{limit:wW($)??this.config.limit,window:wW(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(_8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new a1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=qW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${GZ(this.req)}:${this.req.routePath??"*"}`}}function WB(){try{let $=H();return $.bound(Q1)?$.make(Q1):null}catch{return null}}function GZ($){let Z=yW($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return _$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function wW($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class mW extends t{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new C8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new C8;return{}}}class C8 extends J0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:gW("csrf","Invalid CSRF token",403)}},view:{}}}class hW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class pW{all($,Z){return!0}}class A8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new KZ:new Q6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends t{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof KZ:$ instanceof Q6}}function YB($){return new A8($)}async function B6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await LB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return OB(z,Z,J,$.url)}async function OB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new K6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function LB($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function F6($){return new TextDecoder("utf-8").decode($)}var HB={"&":"&","<":"<",">":">",'"':""","'":"'"};function x$($){return $.replace(/[&<>"']/g,(Z)=>HB[Z])}var MB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function S8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return MB[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function E8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function cW($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(S8($.slice(W)));return}if(Y>W)Z.text(S8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(E8($.slice(Y+2,j).trim())),W=j+1}else{let j=PB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=E8(z.slice(0,Q));if(G){if(Z.open(G,TB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function PB($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function TB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[E8(W[1])]=S8(W[2]??W[3]??"");return Z}class W0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var sW="http://www.sitemaps.org/schemas/sitemap/0.9",NB="http://www.w3.org/1999/xhtml",f8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`,dW=`<urlset xmlns="${sW}" xmlns:xhtml="${NB}">
|
|
4
4
|
`,uW=`</urlset>
|
|
5
5
|
`,C$=50000,j3=52428800,lW=2048,IB=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),_B=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,xB="application/xml; charset=utf-8",iW=new TextEncoder;function k8($,Z){let J;try{J=new URL($)}catch{throw new W0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new W0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>lW)throw new W0(`Sitemap: ${Z} is over ${lW} characters: "${W.slice(0,80)}\u2026".`);return W}function nW($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new W0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!_B.test($))throw new W0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function CB($){let Z=k8($.loc,"loc"),J=`<url><loc>${x$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${x$(nW($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!IB.has($.changefreq))throw new W0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new W0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new W0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=k8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${x$(Y)}" href="${x$(j)}"/>`}return`${J}</url>
|
|
@@ -20,7 +20,7 @@ c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}($
|
|
|
20
20
|
`)),Z.onSettle((B)=>{if(X||B.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([B.path,B.variantKey,B.data])}
|
|
21
21
|
`))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as xI,createContext as pD,createElement as CI,lazy as AI,use as SI,useContext as EI}from"react";function $G($){return{islands:[],render:$,instances:new WeakMap,count:0}}var l3="gemi-slot",ZG="data-slot",JG="data-gemi-slot";var cD=Symbol.for("gemi.staticRender"),WG=globalThis[cD]??=pD(null);import{createHash as QG}from"crypto";var jJ='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';import{createHash as dD}from"crypto";import{existsSync as jG,readFileSync as uD}from"fs";import{join as GJ}from"path";var zG=".script",lD=[".ts",".js"],iD="document-scripts.json",XG="data-gemi-script",sD=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function nD($){if(typeof $!=="string"||!sD.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function oD($,Z){for(let J of lD){let W=GJ($,"views",`${Z}${zG}${J}`);if(jG(W))return W}return null}async function YG($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
|
|
22
22
|
`);throw Error(`The document script ${$} does not bundle.
|
|
23
|
-
${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function aD($){return`'sha256-${dD("sha256").update($).digest("base64")}'`}var zJ,XJ=new Map;function rD(){if(zJ===void 0){let $=GJ(QJ(),"dist","server",iD);zJ=jG($)?JSON.parse(uD($,"utf8")):null}return zJ??null}async function KJ($){nD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=rD()?.[$];if(j!==void 0)return j;let z=XJ.get($);if(z)return z}let J=GJ(QJ(),"app"),W=oD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${zG}.ts (or .js).`);if(!Z)return YG(W);let Y=YG(W);return XJ.set($,Y),Y.catch(()=>XJ.delete($)),Y}async function yI($){return aD(await KJ($))}var tD="gemi-islands",uI=`'sha256-${QG("sha256").update(VJ).digest("base64")}'`;function BJ($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var FJ=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),lI=`'sha256-${QG("sha256").update(jJ).digest("base64")}'`,eD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',$O="gemi-static";function GG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let D=U.module?J(U.module):void 0;if(!D)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let O of D.preload)z.add(O);if(U.preloadDynamic)for(let O of D.dynamicPreload??[])z.add(O)}return{s:D.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${XG}="${FJ(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return BJ($,"</head>",G,!1);let F=(Y?`<meta name="${$O}" content="${FJ(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${FJ(U)}"/>`).join("")+G,K=Y?jJ:VJ,V=(Q?`<script type="application/json" id="${tD}">${G1({i:X})}</script>`:"")+`<script type="module">${W?eD+K:K}</script>`;return BJ(BJ($,"</head>",F,!1),"</body>",V,!0)}function ZO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function KG($){let Z=`<template ${JG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=ZO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${l3} ${ZG}="${j}" style="display:contents"></${l3}>`;$=$.split(Q).join(`<${l3} style="display:contents">${X}</${l3}>`)}return $}function BG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function FG($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}var JO=async()=>(await import("./chunk-3xj1e3ns.js")).default,UJ,i3=async(...$)=>{return UJ??=import("react-dom/server.browser").catch((Z)=>{throw UJ=void 0,Z}),(await UJ).renderToReadableStream(...$)},UG=1e4,DG="no-locale",WO="no-theme";async function YO($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var LJ="/assets";function jO($){return $===LJ||$.startsWith(`${LJ}/`)}function zO($){let Z=$.filter(jO);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${LJ}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function XO($){let Z=H(Y1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function DJ($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function QO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class s3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=rQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;defaultMeta;constructor($,Z={}){let J=MQ();this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":BQ(Z)};this.requiredViews=Object.fromEntries(GQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=c4(W),zO(Object.keys(this.flatViewRoutes)),this.routeManifest=u4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=i4(W),this.flatComponentTree=JJ(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}this.root=$.root}async passesFeatureGates($){let Z=H(r1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)s4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{n$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>g1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=OJ(),F=new AbortController,K=setTimeout(()=>F.abort(),UG),V=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},U=$G(async(D,O)=>{let L=await i3(D,{signal:F.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:V});return await L.allReady.catch(()=>{}),await new Response(L).text()});try{let D,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)D={name:O,source:await KJ(O)};let L;if(W.navigation){let _=W.navigation===!0?{}:W.navigation,A=_.version?String(await J(()=>_.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",D?.name??"",A].join("|"),prefetch:_.prefetch==="none"?"none":"intent"}}let T=await i3(g1(WG.Provider,{value:U,children:g1(VG,{children:[...G,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:V});await T.allReady.catch(()=>{});let P=KG(await new Response(T).text());return new Response(GG(P,U,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,D),{status:200,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:F,noTheme:K,url:V,user:U,viewData:D,breadcrumbs:O,urlLocaleSegment:L,meta:T,isOgRequest:P,appId:_,features:A,staticView:E}=$,S=this.theme===!1||K||E?null:{cookie:this.theme.cookie??m9,default:this.theme.default??null,value:GO(Z,this.theme.cookie??m9)},f=L?nQ(Q,[L]).pathname:Q,M={kind:"view",data:{meta:T,pageData:{[f]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:U},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:V.search,is404:!Y?!0:!1,domain:Z.domain?XO(Z):null},appId:_,features:A,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},I=this.root,y=this.routeManifest[Y];return async(H$)=>{let{bootstrapModules:T0=[],loaders:h1,getStyles:i,viewImportMap:q,cssManifest:N0,ogMap:t$,viewModules:o3,clientEntry:M$,modulePreloadManifest:p1,assetBase:c1,resolveIsland:e$,buildId:o}=H$,eZ=M$?[]:T0,a3=(k0)=>[k0,`window.loaders=${h1}`,...M$?[`import(${JSON.stringify(M$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let k0=null,JZ=null;for(let WZ of y??[])if(typeof t$[WZ]==="function")JZ=WZ,k0=t$[WZ];if(!k0)return new Response("Not found",{status:404});let PK=Object.values(M.data.pageData)[0];try{await i3(g1(k0,PK[JZ]),{onError:()=>{}})}catch(WZ){let{fonts:TK,...NK}=WZ.satoriOptions,IK=await Promise.all(TK.map((r3)=>{return YO(r3.name,r3.weight,r3.style).then((SK)=>({...r3,data:SK}))})),nJ=new Headers(j);nJ.set("Content-Type","image/png");let[_K,xK]=await Promise.all([JO(),h4("Rendering an OG image")]),CK=await _K(WZ.jsx,{...NK,fonts:IK}),AK=await xK(Buffer.from(CK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(AK),{headers:nJ})}return new Response("data")}if(E&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:E,currentViews:y,data:M.data,serverQueries:G,headers:j,getStyles:i,viewImportMap:q,viewModules:o3,resolveIsland:e$,buildId:o});if(M.data.cssManifest=N0,M.data.modulePreloadManifest=p1??{},c1&&c1!=="/")M.data.assetBase=c1;if(o&&o!=="dev")M.data.buildId=o;let $Z=this.modulePreloadLinks({clientEntry:M$,modulePreloadManifest:p1,views:y??["404"],routeKey:Y??"404"}),$3=await i(y??["404"]);M.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let d1=new AbortController,P$=setTimeout(()=>d1.abort(),UG),R=H6(B)||F,f0=Bun.env.NODE_ENV!=="production"&&!R&&Y&&this.shellReporter.shouldObserve(Y)?tQ():null,ZZ=OJ();try{let k0=await i3(g1(VG,{children:[...$Z,...$3,...S?[g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:IQ(G1({cookie:S.cookie,default:S.default}))}})]:[],g1(I,{data:M.data,viewImportMap:q,viewModules:o3,serverQueries:G,dictionarySink:ZZ,key:"root"})]}),{bootstrapScriptContent:a3(`window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:eZ,signal:d1.signal,...R?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(JZ){if(Bun.env.NODE_ENV!=="production")console.error(JZ)}});if(k0.allReady.catch(()=>{}).finally(()=>clearTimeout(P$)),R)await k0.allReady.catch(()=>{});return new Response(u8(k0,G,{onShell:R?void 0:()=>G.markShell(),onChunk:f0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(d1.signal.aborted)),f0)this.shellReporter.report(Y,f0.measure())})},ZZ),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(k0){if(clearTimeout(P$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted))),k0;let JZ=await i3(g1("div"),{bootstrapScriptContent:a3(`window.error= ${G1(k0.message)}; window.stack_trace=${G1(k0.stack)};window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...eZ]:eZ});return new Response(u8(JZ,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(N$(Z))return 404;if(Z?.kind===s1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(n1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,B=null,F=H(d),K=d3(this.flatViewRoutes,j),V=F.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(DG);if(V&&F.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let M=J.pathname.replace(/\/+$/,""),I=V&&F.supportedLocales.includes(M.slice(1));if(M&&!I)return new Response("",{status:301,headers:{Location:`${M}${J.search}`}})}if(V&&!Y&&B===null&&!(B===null&&K!==null)){let M=OG(z,F.supportedLocales,F.defaultLocale);if(M){let I=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${I}${W?".json":""}${J.search}`}})}}if(V&&!Y){let M=H(d).detectLocale(new C($,{},"view",Q));if(B===null&&M!==F.defaultLocale){let I=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${I}${J.search}`}})}}Q=Q.replace("//","/");let D=[],O=[],L=null,T={},P=null,_=!1,A=!1,E=[],S;try{let M=d3(this.flatViewRoutes,Q);if(B&&M?.route.middleware.includes(DG))M=null;if(M){if(L=M.routePath,T=M.params,D=M.route.exec,O=M.route.middleware,E=M.route.features,_=O.includes("no-stream"),A=O.includes(WO),S=M.route.static,W&&this.partialRendering){let I=$.headers.get(ZJ),y=sQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(d).supportedLocales,from:I,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),P={from:I,carriedViews:y.carriedViews}}}}catch(M){throw M}if(S&&W)return new Response("Not found",{status:404});let f=new C($,T,"view",L);return this.hooks.onRequestStart(f),await N.run(f,async()=>{let M=null,I=N.getStore(),y=nZ.getStore(),H$=(q)=>nZ.run(y,()=>N.runWith(I,q));I.serverQueries=new iZ(u3($));let T0=new Set;I.serverQueries.onQueryFail((q)=>{T0.add(q.error);try{H$(()=>Promise.resolve(this.hooks.onRequestFail(i,q.error)).catch(()=>{}))}catch{}});let h1=BG(S);if(B){let q=B.replaceAll("/","");L$.setLocale(q,{cookie:h1.locale})}else if(F.isLocaleAware&&!V)I.setLocale(F.defaultLocale);else L$.setLocale(void 0,{cookie:h1.locale});let i=I.req;if(h1.session)s4();try{let q=null;try{await H(i1).runMiddleware(O)}catch(R){if(q=this.viewRefusalStatus(i,R,T0),q===null)throw R}if(q!==null||E.length>0&&!await this.passesFeatureGates(E))L=null,D=[],i.routePath="";let N0=H(d),t$=N0.isEnabled,o3=N0.isLocaleAware,M$=new C($,i.params),p1={defaultLocale:N0.defaultLocale,timeZone:N0.detectTimeZone(M$)};if(o3){let R=null;if(B)R=B.replaceAll("/",""),I.setLocale(R);else if(!V)R=I.locale??N0.defaultLocale;else R=N0.detectLocale(M$),I.setLocale(R);let f0=t$?N0.getPageTranslations(R,i.routePath):{};p1={...p1,supportedLocales:N0.supportedLocales,currentLocale:R,dictionary:{[R]:f0},defaultLocale:N0.defaultLocale,...V?{}:{localeRouting:"off"}}}await LG(p1.currentLocale??"");let c1;try{c1=await Promise.all(D.map((R)=>R(i)))}catch(R){if(q=this.viewRefusalStatus(i,R,T0),q===null)throw R;L=null,D=[],i.routePath="",c1=[]}if(L===null)await this.hooks.onNotFound(i,{status:q??404});if(this.defaultMeta&&!I.metadata.hasAllDefaultFields)I.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);let{cookies:e$,headers:o}=I;if(q!==null)o.set("Cache-Control","no-store");M={data:c1,cookies:e$,headers:o,user:I.user,prefetchedData:I.serverQueries.snapshotResolved(),currentPathName:L,params:i.params,urlLocaleSegment:G,meta:I.renderMeta(),appId:H(WJ).id,features:await H(r1).forClient()};let{params:eZ,user:a3}=M,$Z={},$3={};for(let R of c1??[]){let[f0,ZZ]=Object.entries(R)?.[0]??[];if(!f0||!ZZ)continue;$3[`${f0}:${L}`]=ZZ.breadcrumb,$Z[f0]=ZZ}let d1=$Z.FILE;if(d1){for(let R of e$)o.append("Set-Cookie",R.toString());try{await this.onRequestEnd(i)}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await T8(d1,o)}if(W){o.set("Content-Type","application/x-ndjson; charset=utf-8"),o.append("Vary",ZJ),e$.forEach((f0)=>o.append("Set-Cookie",f0.toString())),await this.hooks.onRequestEnd(i);let R={meta:P&&!I.metadata.touched?null:M.meta,data:{[Q]:$Z},breadcrumbs:$3,prefetchedData:I.serverQueries.snapshotResolved(),i18n:p1,features:M.features,is404:!L,appId:M.appId,partial:P};return new Response(eQ(R,I.serverQueries,void 0,({aborted:f0})=>H$(()=>this.completeStream(i,I.serverQueries.summarize(f0)))),{headers:o})}if(o.set("Content-Type","text/html; charset=utf-8"),!_&&!(S&&L))o.append("Vary","User-Agent");let P$=Boolean(S&&L);if(!P$||h1.session)s4();for(let R of e$)o.append("Set-Cookie",R.toString());if(!P$||h1.csrf){let R=Bun.CSRF.generate(process.env.SECRET);o.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!P$||h1.session})}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(P$)FG(o,S);return await this.render({req:i,runInRequestScope:H$,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:o,i18n:p1,params:eZ,pathname:J.pathname,serverQueries:I.serverQueries,userAgent:$.headers.get("user-agent"),noStream:_,noTheme:A,url:J,user:a3,viewData:$Z,breadcrumbs:$3,urlLocaleSegment:G,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:L?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===s1){let N0=W?QO(q.payload.viewData??q.payload.api):DJ(q.payload.view);for(let t$ of I.cookies)N0.headers.append("Set-Cookie",t$.toString());return N0}if(!T0.has(q))this.hooks.onRequestFail(i,q);if(n1(q))return console.error(q),W?sZ():DJ(YJ());if(q instanceof v1&&q.status===403)return W?sZ():DJ(YJ());throw q}},Z)}}function GO($,Z){let J=$.cookies?.get(Z);return NQ(J)?J:null}function HJ(){let $=JSON.stringify({error:o1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class NG extends I0{routes={"/api-routes":this.get(()=>{let $=H(o4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(s3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var KO=new Set([l1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),BO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,FO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function VO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(KO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===l1)throw Error(`dispatchAs: credentials may not set the "${l1}" cookie. The access token stays the initiator's.`);if(!BO.test(Y)||!FO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function UO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function HG($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function MG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function DO(){return Bun.env.NODE_ENV==="development"}class o4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=HQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=y9({"/":$.rootRouter,"/auth":b9,"/__gemi__/services/i18n":R9,"/__gemi__/services/image":w9,...DO()?{"/__gemi__/services/logs":q9,"/__gemi__/debug":NG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=TG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(i1).runMiddleware(W)}catch(Y){if(Y.kind===s1)return HG(Y.payload.api);else{if(N$(Y))return HJ();if(this.onRequestFail(Z,Y),console.error(Y),n1(Y))return sZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===s1)return HG(j.payload.api);if(N$(j))return HJ();if(this.onRequestFail(J.req,j),console.error(j),n1(j))return sZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){n$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:o1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=H(d);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(i1).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let D=MG(B,z.headers,z.cookies);return await Q(),D}let F=await this.getRouteData(W),K=z.headers,V=z.cookies;if(F instanceof Response){let D=MG(F,K,V);if(this.isOpenEndedBody($,D)){let O=UO(D,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),D}let U=(u1(F)?F:j1.json(F)).toResponse(K,V);return await Q(),U}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],F=Q?null:$.cookies.get(l1);if(F)B.push(`${l1}=${F}`);if(Y?.credentials)VO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(l1);if(K)G.set(l1,K);let V=$.headers.get("User-Agent");if(V)G.set("User-Agent",V);let U;if(W instanceof FormData)U=W;else if(W!==void 0)G.set("Content-Type","application/json"),U=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:U,...Y?.signal?{signal:Y.signal}:{}});if(PG(D,GZ($),Q?.grant,Y?.progress),$.domain)oZ(D,$.domain);let O=Q?{user:Q.user}:void 0;return N.exit(()=>Y6.exit(()=>this.handleApiRequest(D,O)))}}import{timingSafeEqual as OO}from"crypto";var t4="",TJ="*",LO=60000,HO=1e4,PJ=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,a4=16,MJ=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r4="x-forwarded-host";function IG($){return $.startsWith(":")}function aZ($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&OO(J,W)}function MO($){if(!$)return null;if($===!0)return{header:r4,clientIpHeader:null,secret:null};return{header:($.hostHeader??r4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function PO($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!MJ.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(J!==void 0){if(typeof J!=="string"||!MJ.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!MJ.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<a4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${a4} characters. A guessable one lets any client name its own host.`)}function M1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function TO($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function NO($){let Z=M1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>PJ.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<a4)throw Error(`\`route.domains.ask.secret\` must be at least ${a4} characters. A guessable one is worse than leaving \`ask\` out.`);PO($.trustProxy);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),IG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>PJ.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class NJ{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){NO($),this.root=M1($.root),this.hostTrust=MO($.trustProxy);for(let Z of $.groups??[])if(IG(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??LO,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:_$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return M1(this.forwardedHost($))??M1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&M1(Y)?TO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:TJ,params:{},custom:!0};return null}async allows($,Z){let J=M1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:t4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&PJ.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=HO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=M1($);if(Z)this.cache.delete(Z)}}}var IO={kind:"none"};function Ux($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return IO;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function Dx($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:_$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _G=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xG=16;function Ox($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!_G.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_G.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<xG)throw Error(`GEMI_PROXY_SECRET must be at least ${xG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function CG($,Z){if(!aZ($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:_$(J)}var _O="/__gemi__/domains/ask";class Y1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;constructor($,Z){this.groups.set(t4,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new NJ(J);let W=(Y)=>({api:Y.api?new o4({...Z.api,...Y.api}):$.api,view:Y.view?new s3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(TJ,W(J.custom.fallback))}applyClientIp($){let Z=this.clientIpTrust;if(Z)IJ($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?CG($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)IJ($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return oZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==_O)return null;if(!aZ(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??t4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function rZ($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var AG=600000;function SG($,Z){return[U6($,Z),U6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new o8){LY($.oauthProviders),this.config={...L1(HY($),$),emailCode:d8($.emailCode)},this.provider=Z}async oauthProvider($){return await DZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await fY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Y1)?H(Y1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Y1).resolver?.root:M1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??M1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!v8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=rZ(J.expiresAt),j=rZ(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/AG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=U6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of SG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(v8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/AG),W=SG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new I$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=jY(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:FY(Z),Q=D6("link",$,j),G=D6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((V)=>rZ(V.createdAt)+B>Date.now()&&V.pin!==G&&V.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((V)=>V.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return VZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>rZ(G.createdAt)+W*60000>Date.now());if(z.length===0)return VZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await DY(G.id,rZ(G.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let Q=null;for(let G of z)if(VZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return VZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(VZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(rZ(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class w0 extends g{static getFacadeAccessor(){return b}static async user(){let $=await w0.userOrNull();if($)return $;throw new I$({redirectTo:z6(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await Z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return X1(Z?.search.get(z1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new KZ}static async guardSafe($){let Z=await w0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class e4{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new iZ(u3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=e4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){e4.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new iZ(u3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function xO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function _J($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?xO(z):encodeURIComponent(String(z))}`});return`${$8}${J==="/"?"":J}`||$8}var EG=new Map;function bG($,Z){let J=EG.get($);if(!J)J=new URLPattern({pathname:`${$8}${$==="/"?"":$}`}),EG.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function RG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=CO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function CO($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class fG{static origin($){return xJ($)}static absolute($,...Z){return`${l$()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Y1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):l$();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return RG({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}static api($,...Z){return _J(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${xJ()}${_J(String($),Z[0]??{})}`}static matchApi($,Z){return bG(String($),Z)}}class kG{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static robots($){N.getStore().metadata.robots($)}static fonts($){N.getStore().metadata.fonts($)}}var AO={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class m1 extends g{static getFacadeAccessor(){return o$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function VC($){return $}function wG(){return{store:"memory",ttl:null}}class CJ{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var SO="500";class AJ{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${EO(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",SO]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(o$)?$.make(o$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function EO($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var bO="k:",qG="tag:",RO="t:";class SJ{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class EJ extends SJ{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=L1(wG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)a$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new vG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return bO+gG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=qG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=yG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(qG+Z,yG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:a$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new CJ(this.config.memory);if($==="redis"){let Z=this.options.application;return new AJ({...this.config.redis,client:Z?{send:(J,W)=>Z.make(o$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class vG extends SJ{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${RO}${Z.join(",")}:${$}`}}function gG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function yG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class mG extends g{static getFacadeAccessor(){return EJ}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class hG extends g{static getFacadeAccessor(){return Q1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class cG extends g{static getFacadeAccessor(){return pG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class uG extends g{static getFacadeAccessor(){return dG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class lG extends g{static getFacadeAccessor(){return c3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function pC($){return $}function iG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function Z8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function bJ($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:fO}=globalThis.Bun;function kO(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var wO=async($)=>{let Z=new fO($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},qO=async($)=>{let Z;try{Z=(await import("./chunk-tms2g9at.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},sG=($)=>kO()?wO($):qO($);var yO=/^[A-Za-z_][A-Za-z0-9_]*$/;class RJ{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!yO.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??sG}async createTable(){for(let $ of vO(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return nG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
23
|
+
${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function aD($){return`'sha256-${dD("sha256").update($).digest("base64")}'`}var zJ,XJ=new Map;function rD(){if(zJ===void 0){let $=GJ(QJ(),"dist","server",iD);zJ=jG($)?JSON.parse(uD($,"utf8")):null}return zJ??null}async function KJ($){nD($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=rD()?.[$];if(j!==void 0)return j;let z=XJ.get($);if(z)return z}let J=GJ(QJ(),"app"),W=oD(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${zG}.ts (or .js).`);if(!Z)return YG(W);let Y=YG(W);return XJ.set($,Y),Y.catch(()=>XJ.delete($)),Y}async function yI($){return aD(await KJ($))}var tD="gemi-islands",uI=`'sha256-${QG("sha256").update(VJ).digest("base64")}'`;function BJ($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var FJ=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),lI=`'sha256-${QG("sha256").update(jJ).digest("base64")}'`,eD='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',$O="gemi-static";function GG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let D=U.module?J(U.module):void 0;if(!D)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let O of D.preload)z.add(O);if(U.preloadDynamic)for(let O of D.dynamicPreload??[])z.add(O)}return{s:D.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${XG}="${FJ(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return BJ($,"</head>",G,!1);let F=(Y?`<meta name="${$O}" content="${FJ(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${FJ(U)}"/>`).join("")+G,K=Y?jJ:VJ,V=(Q?`<script type="application/json" id="${tD}">${G1({i:X})}</script>`:"")+`<script type="module">${W?eD+K:K}</script>`;return BJ(BJ($,"</head>",F,!1),"</body>",V,!0)}function ZO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function KG($){let Z=`<template ${JG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=ZO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${l3} ${ZG}="${j}" style="display:contents"></${l3}>`;$=$.split(Q).join(`<${l3} style="display:contents">${X}</${l3}>`)}return $}function BG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function FG($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}var JO=async()=>(await import("./chunk-44y62yav.js")).default,UJ,i3=async(...$)=>{return UJ??=import("react-dom/server.browser").catch((Z)=>{throw UJ=void 0,Z}),(await UJ).renderToReadableStream(...$)},UG=1e4,DG="no-locale",WO="no-theme";async function YO($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var LJ="/assets";function jO($){return $===LJ||$.startsWith(`${LJ}/`)}function zO($){let Z=$.filter(jO);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${LJ}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function XO($){let Z=H(Y1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function DJ($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function QO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class s3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=rQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;defaultMeta;constructor($,Z={}){let J=MQ();this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":BQ(Z)};this.requiredViews=Object.fromEntries(GQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=c4(W),zO(Object.keys(this.flatViewRoutes)),this.routeManifest=u4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=i4(W),this.flatComponentTree=JJ(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}this.root=$.root}async passesFeatureGates($){let Z=H(r1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)s4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{n$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>g1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=OJ(),F=new AbortController,K=setTimeout(()=>F.abort(),UG),V=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},U=$G(async(D,O)=>{let L=await i3(D,{signal:F.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:V});return await L.allReady.catch(()=>{}),await new Response(L).text()});try{let D,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)D={name:O,source:await KJ(O)};let L;if(W.navigation){let _=W.navigation===!0?{}:W.navigation,A=_.version?String(await J(()=>_.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",D?.name??"",A].join("|"),prefetch:_.prefetch==="none"?"none":"intent"}}let T=await i3(g1(WG.Provider,{value:U,children:g1(VG,{children:[...G,g1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:V});await T.allReady.catch(()=>{});let P=KG(await new Response(T).text());return new Response(GG(P,U,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,D),{status:200,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:F,noTheme:K,url:V,user:U,viewData:D,breadcrumbs:O,urlLocaleSegment:L,meta:T,isOgRequest:P,appId:_,features:A,staticView:E}=$,S=this.theme===!1||K||E?null:{cookie:this.theme.cookie??m9,default:this.theme.default??null,value:GO(Z,this.theme.cookie??m9)},f=L?nQ(Q,[L]).pathname:Q,M={kind:"view",data:{meta:T,pageData:{[f]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:U},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:V.search,is404:!Y?!0:!1,domain:Z.domain?XO(Z):null},appId:_,features:A,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},I=this.root,y=this.routeManifest[Y];return async(H$)=>{let{bootstrapModules:T0=[],loaders:h1,getStyles:i,viewImportMap:q,cssManifest:N0,ogMap:t$,viewModules:o3,clientEntry:M$,modulePreloadManifest:p1,assetBase:c1,resolveIsland:e$,buildId:o}=H$,eZ=M$?[]:T0,a3=(k0)=>[k0,`window.loaders=${h1}`,...M$?[`import(${JSON.stringify(M$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let k0=null,JZ=null;for(let WZ of y??[])if(typeof t$[WZ]==="function")JZ=WZ,k0=t$[WZ];if(!k0)return new Response("Not found",{status:404});let PK=Object.values(M.data.pageData)[0];try{await i3(g1(k0,PK[JZ]),{onError:()=>{}})}catch(WZ){let{fonts:TK,...NK}=WZ.satoriOptions,IK=await Promise.all(TK.map((r3)=>{return YO(r3.name,r3.weight,r3.style).then((SK)=>({...r3,data:SK}))})),nJ=new Headers(j);nJ.set("Content-Type","image/png");let[_K,xK]=await Promise.all([JO(),h4("Rendering an OG image")]),CK=await _K(WZ.jsx,{...NK,fonts:IK}),AK=await xK(Buffer.from(CK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(AK),{headers:nJ})}return new Response("data")}if(E&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:E,currentViews:y,data:M.data,serverQueries:G,headers:j,getStyles:i,viewImportMap:q,viewModules:o3,resolveIsland:e$,buildId:o});if(M.data.cssManifest=N0,M.data.modulePreloadManifest=p1??{},c1&&c1!=="/")M.data.assetBase=c1;if(o&&o!=="dev")M.data.buildId=o;let $Z=this.modulePreloadLinks({clientEntry:M$,modulePreloadManifest:p1,views:y??["404"],routeKey:Y??"404"}),$3=await i(y??["404"]);M.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let d1=new AbortController,P$=setTimeout(()=>d1.abort(),UG),R=H6(B)||F,f0=Bun.env.NODE_ENV!=="production"&&!R&&Y&&this.shellReporter.shouldObserve(Y)?tQ():null,ZZ=OJ();try{let k0=await i3(g1(VG,{children:[...$Z,...$3,...S?[g1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:IQ(G1({cookie:S.cookie,default:S.default}))}})]:[],g1(I,{data:M.data,viewImportMap:q,viewModules:o3,serverQueries:G,dictionarySink:ZZ,key:"root"})]}),{bootstrapScriptContent:a3(`window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:eZ,signal:d1.signal,...R?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(JZ){if(Bun.env.NODE_ENV!=="production")console.error(JZ)}});if(k0.allReady.catch(()=>{}).finally(()=>clearTimeout(P$)),R)await k0.allReady.catch(()=>{});return new Response(u8(k0,G,{onShell:R?void 0:()=>G.markShell(),onChunk:f0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(d1.signal.aborted)),f0)this.shellReporter.report(Y,f0.measure())})},ZZ),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(k0){if(clearTimeout(P$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted))),k0;let JZ=await i3(g1("div"),{bootstrapScriptContent:a3(`window.error= ${G1(k0.message)}; window.stack_trace=${G1(k0.stack)};window.__GEMI_DATA__ = ${G1(M.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...eZ]:eZ});return new Response(u8(JZ,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(d1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(N$(Z))return 404;if(Z?.kind===s1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(n1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof v1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,B=null,F=H(d),K=d3(this.flatViewRoutes,j),V=F.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(DG);if(V&&F.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let M=J.pathname.replace(/\/+$/,""),I=V&&F.supportedLocales.includes(M.slice(1));if(M&&!I)return new Response("",{status:301,headers:{Location:`${M}${J.search}`}})}if(V&&!Y&&B===null&&!(B===null&&K!==null)){let M=OG(z,F.supportedLocales,F.defaultLocale);if(M){let I=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${I}${W?".json":""}${J.search}`}})}}if(V&&!Y){let M=H(d).detectLocale(new C($,{},"view",Q));if(B===null&&M!==F.defaultLocale){let I=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${M}${I}${J.search}`}})}}Q=Q.replace("//","/");let D=[],O=[],L=null,T={},P=null,_=!1,A=!1,E=[],S;try{let M=d3(this.flatViewRoutes,Q);if(B&&M?.route.middleware.includes(DG))M=null;if(M){if(L=M.routePath,T=M.params,D=M.route.exec,O=M.route.middleware,E=M.route.features,_=O.includes("no-stream"),A=O.includes(WO),S=M.route.static,W&&this.partialRendering){let I=$.headers.get(ZJ),y=sQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(d).supportedLocales,from:I,origin:J.origin,to:{segments:M.route.segments,params:T,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),P={from:I,carriedViews:y.carriedViews}}}}catch(M){throw M}if(S&&W)return new Response("Not found",{status:404});let f=new C($,T,"view",L);return this.hooks.onRequestStart(f),await N.run(f,async()=>{let M=null,I=N.getStore(),y=nZ.getStore(),H$=(q)=>nZ.run(y,()=>N.runWith(I,q));I.serverQueries=new iZ(u3($));let T0=new Set;I.serverQueries.onQueryFail((q)=>{T0.add(q.error);try{H$(()=>Promise.resolve(this.hooks.onRequestFail(i,q.error)).catch(()=>{}))}catch{}});let h1=BG(S);if(B){let q=B.replaceAll("/","");L$.setLocale(q,{cookie:h1.locale})}else if(F.isLocaleAware&&!V)I.setLocale(F.defaultLocale);else L$.setLocale(void 0,{cookie:h1.locale});let i=I.req;if(h1.session)s4();try{let q=null;try{await H(i1).runMiddleware(O)}catch(R){if(q=this.viewRefusalStatus(i,R,T0),q===null)throw R}if(q!==null||E.length>0&&!await this.passesFeatureGates(E))L=null,D=[],i.routePath="";let N0=H(d),t$=N0.isEnabled,o3=N0.isLocaleAware,M$=new C($,i.params),p1={defaultLocale:N0.defaultLocale,timeZone:N0.detectTimeZone(M$)};if(o3){let R=null;if(B)R=B.replaceAll("/",""),I.setLocale(R);else if(!V)R=I.locale??N0.defaultLocale;else R=N0.detectLocale(M$),I.setLocale(R);let f0=t$?N0.getPageTranslations(R,i.routePath):{};p1={...p1,supportedLocales:N0.supportedLocales,currentLocale:R,dictionary:{[R]:f0},defaultLocale:N0.defaultLocale,...V?{}:{localeRouting:"off"}}}await LG(p1.currentLocale??"");let c1;try{c1=await Promise.all(D.map((R)=>R(i)))}catch(R){if(q=this.viewRefusalStatus(i,R,T0),q===null)throw R;L=null,D=[],i.routePath="",c1=[]}if(L===null)await this.hooks.onNotFound(i,{status:q??404});if(this.defaultMeta&&!I.metadata.hasAllDefaultFields)I.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);let{cookies:e$,headers:o}=I;if(q!==null)o.set("Cache-Control","no-store");M={data:c1,cookies:e$,headers:o,user:I.user,prefetchedData:I.serverQueries.snapshotResolved(),currentPathName:L,params:i.params,urlLocaleSegment:G,meta:I.renderMeta(),appId:H(WJ).id,features:await H(r1).forClient()};let{params:eZ,user:a3}=M,$Z={},$3={};for(let R of c1??[]){let[f0,ZZ]=Object.entries(R)?.[0]??[];if(!f0||!ZZ)continue;$3[`${f0}:${L}`]=ZZ.breadcrumb,$Z[f0]=ZZ}let d1=$Z.FILE;if(d1){for(let R of e$)o.append("Set-Cookie",R.toString());try{await this.onRequestEnd(i)}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await T8(d1,o)}if(W){o.set("Content-Type","application/x-ndjson; charset=utf-8"),o.append("Vary",ZJ),e$.forEach((f0)=>o.append("Set-Cookie",f0.toString())),await this.hooks.onRequestEnd(i);let R={meta:P&&!I.metadata.touched?null:M.meta,data:{[Q]:$Z},breadcrumbs:$3,prefetchedData:I.serverQueries.snapshotResolved(),i18n:p1,features:M.features,is404:!L,appId:M.appId,partial:P};return new Response(eQ(R,I.serverQueries,void 0,({aborted:f0})=>H$(()=>this.completeStream(i,I.serverQueries.summarize(f0)))),{headers:o})}if(o.set("Content-Type","text/html; charset=utf-8"),!_&&!(S&&L))o.append("Vary","User-Agent");let P$=Boolean(S&&L);if(!P$||h1.session)s4();for(let R of e$)o.append("Set-Cookie",R.toString());if(!P$||h1.csrf){let R=Bun.CSRF.generate(process.env.SECRET);o.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!P$||h1.session})}catch(R){n$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(P$)FG(o,S);return await this.render({req:i,runInRequestScope:H$,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:o,i18n:p1,params:eZ,pathname:J.pathname,serverQueries:I.serverQueries,userAgent:$.headers.get("user-agent"),noStream:_,noTheme:A,url:J,user:a3,viewData:$Z,breadcrumbs:$3,urlLocaleSegment:G,meta:M.meta,appId:M.appId,features:M.features,isOgRequest:Y,staticView:L?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===s1){let N0=W?QO(q.payload.viewData??q.payload.api):DJ(q.payload.view);for(let t$ of I.cookies)N0.headers.append("Set-Cookie",t$.toString());return N0}if(!T0.has(q))this.hooks.onRequestFail(i,q);if(n1(q))return console.error(q),W?sZ():DJ(YJ());if(q instanceof v1&&q.status===403)return W?sZ():DJ(YJ());throw q}},Z)}}function GO($,Z){let J=$.cookies?.get(Z);return NQ(J)?J:null}function HJ(){let $=JSON.stringify({error:o1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class NG extends I0{routes={"/api-routes":this.get(()=>{let $=H(o4).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(s3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var KO=new Set([l1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),BO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,FO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function VO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(KO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===l1)throw Error(`dispatchAs: credentials may not set the "${l1}" cookie. The access token stays the initiator's.`);if(!BO.test(Y)||!FO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function UO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function HG($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function MG($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function DO(){return Bun.env.NODE_ENV==="development"}class o4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=HQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=y9({"/":$.rootRouter,"/auth":b9,"/__gemi__/services/i18n":R9,"/__gemi__/services/image":w9,...DO()?{"/__gemi__/services/logs":q9,"/__gemi__/debug":NG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=TG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(i1).runMiddleware(W)}catch(Y){if(Y.kind===s1)return HG(Y.payload.api);else{if(N$(Y))return HJ();if(this.onRequestFail(Z,Y),console.error(Y),n1(Y))return sZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===s1)return HG(j.payload.api);if(N$(j))return HJ();if(this.onRequestFail(J.req,j),console.error(j),n1(j))return sZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){n$.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:o1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=H(d);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(i1).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let D=MG(B,z.headers,z.cookies);return await Q(),D}let F=await this.getRouteData(W),K=z.headers,V=z.cookies;if(F instanceof Response){let D=MG(F,K,V);if(this.isOpenEndedBody($,D)){let O=UO(D,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),D}let U=(u1(F)?F:j1.json(F)).toResponse(K,V);return await Q(),U}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],F=Q?null:$.cookies.get(l1);if(F)B.push(`${l1}=${F}`);if(Y?.credentials)VO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(l1);if(K)G.set(l1,K);let V=$.headers.get("User-Agent");if(V)G.set("User-Agent",V);let U;if(W instanceof FormData)U=W;else if(W!==void 0)G.set("Content-Type","application/json"),U=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:U,...Y?.signal?{signal:Y.signal}:{}});if(PG(D,GZ($),Q?.grant,Y?.progress),$.domain)oZ(D,$.domain);let O=Q?{user:Q.user}:void 0;return N.exit(()=>Y6.exit(()=>this.handleApiRequest(D,O)))}}import{timingSafeEqual as OO}from"crypto";var t4="",TJ="*",LO=60000,HO=1e4,PJ=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,a4=16,MJ=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r4="x-forwarded-host";function IG($){return $.startsWith(":")}function aZ($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&OO(J,W)}function MO($){if(!$)return null;if($===!0)return{header:r4,clientIpHeader:null,secret:null};return{header:($.hostHeader??r4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function PO($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!MJ.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(J!==void 0){if(typeof J!=="string"||!MJ.test(J))throw Error(`\`route.domains.trustProxy.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(J)}.`);if(!W)throw Error("`route.domains.trustProxy.clientIpHeader` needs `secret`: without proof the proxy sent it, any client that reaches the app directly picks its own address.");if(J.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `hostHeader`.");if(typeof W.header==="string"&&J.toLowerCase()===W.header.toLowerCase())throw Error("`route.domains.trustProxy.clientIpHeader` names the same header as `secret.header`.")}if(!W)return;if(typeof W.header!=="string"||!MJ.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??r4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof W.value!=="string"||W.value.length<a4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${a4} characters. A guessable one lets any client name its own host.`)}function M1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function TO($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function NO($){let Z=M1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>PJ.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<a4)throw Error(`\`route.domains.ask.secret\` must be at least ${a4} characters. A guessable one is worse than leaving \`ask\` out.`);PO($.trustProxy);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),IG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>PJ.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class NJ{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){NO($),this.root=M1($.root),this.hostTrust=MO($.trustProxy);for(let Z of $.groups??[])if(IG(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??LO,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.hostTrust;if(!Z?.clientIpHeader||!Z.secret)return null;if(!aZ($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:_$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return M1(this.forwardedHost($))??M1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&M1(Y)?TO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:TJ,params:{},custom:!0};return null}async allows($,Z){let J=M1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:t4,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&PJ.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=HO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=M1($);if(Z)this.cache.delete(Z)}}}var IO={kind:"none"};function Ux($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return IO;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function Dx($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:_$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _G=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xG=16;function Ox($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!_G.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_G.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<xG)throw Error(`GEMI_PROXY_SECRET must be at least ${xG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function CG($,Z){if(!aZ($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:_$(J)}var _O="/__gemi__/domains/ask";class Y1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;constructor($,Z){this.groups.set(t4,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new NJ(J);let W=(Y)=>({api:Y.api?new o4({...Z.api,...Y.api}):$.api,view:Y.view?new s3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(TJ,W(J.custom.fallback))}applyClientIp($){let Z=this.clientIpTrust;if(Z)IJ($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?CG($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)IJ($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return oZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==_O)return null;if(!aZ(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??t4)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function rZ($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var AG=600000;function SG($,Z){return[U6($,Z),U6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new o8){LY($.oauthProviders),this.config={...L1(HY($),$),emailCode:d8($.emailCode)},this.provider=Z}async oauthProvider($){return await DZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await fY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Y1)?H(Y1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Y1).resolver?.root:M1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??M1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!v8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=rZ(J.expiresAt),j=rZ(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/AG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=U6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of SG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(v8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/AG),W=SG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new I$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=jY(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:FY(Z),Q=D6("link",$,j),G=D6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((V)=>rZ(V.createdAt)+B>Date.now()&&V.pin!==G&&V.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((V)=>V.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return VZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>rZ(G.createdAt)+W*60000>Date.now());if(z.length===0)return VZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await DY(G.id,rZ(G.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let Q=null;for(let G of z)if(VZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return VZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(VZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(rZ(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class w0 extends g{static getFacadeAccessor(){return b}static async user(){let $=await w0.userOrNull();if($)return $;throw new I$({redirectTo:z6(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await Z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return X1(Z?.search.get(z1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new KZ}static async guardSafe($){let Z=await w0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class e4{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new iZ(u3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=e4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){e4.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new iZ(u3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function xO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function _J($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?xO(z):encodeURIComponent(String(z))}`});return`${$8}${J==="/"?"":J}`||$8}var EG=new Map;function bG($,Z){let J=EG.get($);if(!J)J=new URLPattern({pathname:`${$8}${$==="/"?"":$}`}),EG.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function RG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=CO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function CO($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class fG{static origin($){return xJ($)}static absolute($,...Z){return`${l$()}${B0(String($),Z[0]??{})}`}static relative($,...Z){return B0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Y1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):l$();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return RG({root:W.root,origin:j},$,B0(String(Z),J[0]??{}))}static api($,...Z){return _J(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${xJ()}${_J(String($),Z[0]??{})}`}static matchApi($,Z){return bG(String($),Z)}}class kG{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static robots($){N.getStore().metadata.robots($)}static fonts($){N.getStore().metadata.fonts($)}}var AO={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class m1 extends g{static getFacadeAccessor(){return o$}static get client(){return this.getFacadeRoot().client}static get($){return m1.client.get($)}static set($,Z){return m1.client.set($,Z)}static del(...$){return m1.client.del(...$)}static exists($){return m1.client.exists($)}static incr($){return m1.client.incr($)}static expire($,Z){return m1.client.expire($,Z)}static ttl($){return m1.client.ttl($)}}function VC($){return $}function wG(){return{store:"memory",ttl:null}}class CJ{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var SO="500";class AJ{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${EO(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",SO]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(o$)?$.make(o$).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function EO($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var bO="k:",qG="tag:",RO="t:";class SJ{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class EJ extends SJ{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=L1(wG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)a$(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new vG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return bO+gG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=qG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=yG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(qG+Z,yG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:a$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new CJ(this.config.memory);if($==="redis"){let Z=this.options.application;return new AJ({...this.config.redis,client:Z?{send:(J,W)=>Z.make(o$).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class vG extends SJ{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${RO}${Z.join(",")}:${$}`}}function gG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function yG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class mG extends g{static getFacadeAccessor(){return EJ}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class hG extends g{static getFacadeAccessor(){return Q1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class cG extends g{static getFacadeAccessor(){return pG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class uG extends g{static getFacadeAccessor(){return dG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class lG extends g{static getFacadeAccessor(){return c3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function pC($){return $}function iG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function Z8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function bJ($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:fO}=globalThis.Bun;function kO(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var wO=async($)=>{let Z=new fO($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},qO=async($)=>{let Z;try{Z=(await import("./chunk-777v6242.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},sG=($)=>kO()?wO($):qO($);var yO=/^[A-Za-z_][A-Za-z0-9_]*$/;class RJ{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!yO.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??sG}async createTable(){for(let $ of vO(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return nG(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
24
24
|
INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
|
|
25
25
|
ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
|
|
26
26
|
RETURNING seq
|
|
@@ -112,6 +112,6 @@ data: ${JSON.stringify(Z)}
|
|
|
112
112
|
"updated_at" BIGINT NOT NULL,
|
|
113
113
|
"finished_at" BIGINT,
|
|
114
114
|
"deadline_at" BIGINT${W}
|
|
115
|
-
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GK=191,KK=30000;class z8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class X8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class uJ{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=L1(zK(),$),this.store=lO(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(tZ);return this.ownFeed??=new tZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){VK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;VK("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:a$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return uO(Z),this.change($,P1,{status:"running",progress:Z})}complete($,Z){return this.change($,P1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,P1,{status:"failed",error:FK(Z)})}cancel($,Z){return this.change($,P1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new z8($);if(T1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof X8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,P1,{status:"failed",error:Q instanceof X8?FK(Q):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+a$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new z8($);let z=null;for(;;){if(T1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BK(z,Math.min(Q,X??1/0,KK),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new z8($);if(yield W,T1(W.status))return;for await(let Y of J){let j=dO(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,T1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=a$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||T1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,P1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(T1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BK(j,Math.min(z??1/0,KK))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function dO($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function FK($){if(typeof $==="string")return{message:$};if($ instanceof X8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function VK($,Z){if(typeof Z!=="string"||Z===""||Z.length>GK)throw TypeError(`A run's ${$} is a string of 1 to ${GK} characters; got ${JSON.stringify(Z)}.`)}function uO($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function lO($,Z){if($==="memory")return new mJ;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(C1).connection();return new dJ(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UK extends g{static getFacadeAccessor(){return uJ}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class DK extends g{static getFacadeAccessor(){return r1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class sJ{value;constructor($){this.value=$}}var iO=/^[A-Za-z_][A-Za-z0-9_$]*$/;function sO($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!iO.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class Q8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return iJ(J.sql,(W)=>lJ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=sO(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(d0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await iJ(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await lJ(j,()=>W(X));throw new sJ(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof sJ)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-xed7yf6h.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=HK($,LK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=d0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return OK($),H(C1).connection($)}}var r$=new Q8;class MK extends g{static getFacadeAccessor(){return C1}static connection($){return new Q8($)}static get sql(){return r$.sql}static get dialect(){return r$.dialect}static query($){return r$.query($)}static execute($){return r$.execute($)}static transaction($){return r$.transaction($)}static readOnly($,Z){return r$.readOnly($,Z)}static schema(){return r$.schema()}static close(){return this.getFacadeRoot().close()}}export{j1 as he,bK as ie,s0 as je,Z3 as ke,F8 as le,jZ as me,W3 as ne,I0 as oe,Z6 as pe,y8 as qe,v8 as re,jY as se,a1 as te,Q1 as ue,_$ as ve,t as we,vW as xe,GZ as ye,zY as ze,XY as Ae,m8 as Be,h8 as Ce,D6 as De,VZ as Ee,dB as Fe,FP as Ge,HY as He,xY as Ie,l8 as Je,CY as Ke,AY as Le,rB as Me,SY as Ne,i8 as Oe,$F as Pe,ZF as Qe,s8 as Re,EY as Se,bY as Te,r1 as Ue,RY as Ve,jF as We,o8 as Xe,I8 as Ye,X6 as Ze,N1 as _e,T8 as $e,I1 as af,L$ as bf,e4 as cf,fG as df,kG as ef,AO as ff,m1 as gf,VC as hf,wG as if,CJ as jf,AJ as kf,EJ as lf,vG as mf,mG as nf,hG as of,cG as pf,uG as qf,lG as rf,pC as sf,iG as tf,Z8 as uf,bJ as vf,RJ as wf,fJ as xf,J8 as yf,tZ as zf,WK as Af,YK as Bf,p as Cf,Y3 as Df,f4 as Ef,aP as Ff,rP as Gf,tP as Hf,JT as If,vX as Jf,T9 as Kf,hX as Lf,XT as Mf,dX as Nf,p0 as Of,m3 as Pf,uX as Qf,jK as Rf,PA as Sf,gJ as Tf,P1 as Uf,T1 as Vf,mJ as Wf,dJ as Xf,cO as Yf,z8 as Zf,X8 as _f,uJ as $f,UK as ag,DK as bg,Q8 as cg,MK as dg,I9 as eg,JD as fg,f9 as gg,k9 as hg,LN as ig,FQ as jg,OQ as kg,J6 as lg,i1 as mg,fN as ng,HQ as og,MQ as pg,WJ as qg,sZ as rg,YJ as sg,yI as tg,uI as ug,lI as vg,LJ as wg,jO as xg,DJ as yg,QO as zg,s3 as Ag,HJ as Bg,HG as Cg,MG as Dg,o4 as Eg,Ux as Fg,Dx as Gg,Ox as Hg,Y1 as Ig,b as Jg,w0 as Kg,W6 as Lg,MW as Mg,uK as Ng,OW as Og,TW as Pg,H8 as Qg,j6 as Rg,M8 as Sg,NW as Tg,rK as Ug,tK as Vg,SW as Wg,bW as Xg,fW as Yg,mW as Zg,hW as _g,pW as $g,A8 as ah,YB as bh,W0 as ch,tW as dh,BZ as eh,WY as fh};
|
|
115
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GK=191,KK=30000;class z8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class X8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class uJ{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=L1(zK(),$),this.store=lO(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(tZ);return this.ownFeed??=new tZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){VK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;VK("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:a$($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return uO(Z),this.change($,P1,{status:"running",progress:Z})}complete($,Z){return this.change($,P1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,P1,{status:"failed",error:FK(Z)})}cancel($,Z){return this.change($,P1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new z8($);if(T1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof X8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,P1,{status:"failed",error:Q instanceof X8?FK(Q):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+a$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new z8($);let z=null;for(;;){if(T1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BK(z,Math.min(Q,X??1/0,KK),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new z8($);if(yield W,T1(W.status))return;for await(let Y of J){let j=dO(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,T1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=a$($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||T1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,P1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(T1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BK(j,Math.min(z??1/0,KK))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function dO($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function FK($){if(typeof $==="string")return{message:$};if($ instanceof X8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function VK($,Z){if(typeof Z!=="string"||Z===""||Z.length>GK)throw TypeError(`A run's ${$} is a string of 1 to ${GK} characters; got ${JSON.stringify(Z)}.`)}function uO($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function lO($,Z){if($==="memory")return new mJ;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(C1).connection();return new dJ(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UK extends g{static getFacadeAccessor(){return uJ}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class DK extends g{static getFacadeAccessor(){return r1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class sJ{value;constructor($){this.value=$}}var iO=/^[A-Za-z_][A-Za-z0-9_$]*$/;function sO($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!iO.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class Q8{bound;constructor($){this.bound=$}get name(){return this.bound??x1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return iJ(J.sql,(W)=>lJ(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=sO(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(d0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await iJ(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await lJ(j,()=>W(X));throw new sJ(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof sJ)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-hgpvfhtp.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=HK($,LK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=d0();if($===void 0)return;return x1()===this.name?$:void 0}connection($=this.name){return OK($),H(C1).connection($)}}var r$=new Q8;class MK extends g{static getFacadeAccessor(){return C1}static connection($){return new Q8($)}static get sql(){return r$.sql}static get dialect(){return r$.dialect}static query($){return r$.query($)}static execute($){return r$.execute($)}static transaction($){return r$.transaction($)}static readOnly($,Z){return r$.readOnly($,Z)}static schema(){return r$.schema()}static close(){return this.getFacadeRoot().close()}}export{j1 as ie,bK as je,s0 as ke,Z3 as le,F8 as me,jZ as ne,W3 as oe,I0 as pe,Z6 as qe,y8 as re,v8 as se,jY as te,a1 as ue,Q1 as ve,_$ as we,t as xe,vW as ye,GZ as ze,zY as Ae,XY as Be,m8 as Ce,h8 as De,D6 as Ee,VZ as Fe,dB as Ge,FP as He,HY as Ie,xY as Je,l8 as Ke,CY as Le,AY as Me,rB as Ne,SY as Oe,i8 as Pe,$F as Qe,ZF as Re,s8 as Se,EY as Te,bY as Ue,r1 as Ve,RY as We,jF as Xe,o8 as Ye,I8 as Ze,X6 as _e,N1 as $e,T8 as af,I1 as bf,L$ as cf,e4 as df,fG as ef,kG as ff,AO as gf,m1 as hf,VC as if,wG as jf,CJ as kf,AJ as lf,EJ as mf,vG as nf,mG as of,hG as pf,cG as qf,uG as rf,lG as sf,pC as tf,iG as uf,Z8 as vf,bJ as wf,RJ as xf,fJ as yf,J8 as zf,tZ as Af,WK as Bf,YK as Cf,p as Df,Y3 as Ef,f4 as Ff,aP as Gf,rP as Hf,tP as If,JT as Jf,vX as Kf,T9 as Lf,hX as Mf,XT as Nf,dX as Of,p0 as Pf,m3 as Qf,uX as Rf,jK as Sf,PA as Tf,gJ as Uf,P1 as Vf,T1 as Wf,mJ as Xf,dJ as Yf,cO as Zf,z8 as _f,X8 as $f,uJ as ag,UK as bg,DK as cg,Q8 as dg,MK as eg,I9 as fg,JD as gg,f9 as hg,k9 as ig,LN as jg,FQ as kg,OQ as lg,J6 as mg,i1 as ng,fN as og,HQ as pg,MQ as qg,WJ as rg,sZ as sg,YJ as tg,yI as ug,uI as vg,lI as wg,LJ as xg,jO as yg,DJ as zg,QO as Ag,s3 as Bg,HJ as Cg,HG as Dg,MG as Eg,o4 as Fg,Ux as Gg,Dx as Hg,Ox as Ig,Y1 as Jg,b as Kg,w0 as Lg,W6 as Mg,MW as Ng,uK as Og,OW as Pg,TW as Qg,H8 as Rg,j6 as Sg,M8 as Tg,NW as Ug,rK as Vg,tK as Wg,SW as Xg,bW as Yg,fW as Zg,mW as _g,hW as $g,pW as ah,A8 as bh,YB as ch,W0 as dh,tW as eh,BZ as fh,WY as gh};
|
|
116
116
|
|
|
117
|
-
//# debugId=
|
|
117
|
+
//# debugId=46D81230158C9F7964756E2164756E21
|