gemi 0.155.0 → 0.157.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 +15 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +25 -1
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/ImageModel.d.ts +2 -0
- package/dist/ai/ImageModel.d.ts.map +1 -1
- package/dist/ai/contextCompaction.d.ts +9 -1
- package/dist/ai/contextCompaction.d.ts.map +1 -1
- package/dist/ai/eval/Eval.d.ts +323 -0
- package/dist/ai/eval/Eval.d.ts.map +1 -0
- package/dist/ai/eval/stats.d.ts +70 -0
- package/dist/ai/eval/stats.d.ts.map +1 -0
- package/dist/ai/generate.d.ts.map +1 -1
- package/dist/ai/index.d.ts +5 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +27 -26
- package/dist/ai/index.js.map +7 -5
- package/dist/ai/usageMeter.d.ts +23 -0
- package/dist/ai/usageMeter.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-rb7518zz.js → chunk-00z7s34q.js} +2 -2
- package/dist/{chunk-rb7518zz.js.map → chunk-00z7s34q.js.map} +1 -1
- package/dist/{chunk-2r2j2nvq.js → chunk-0v3bca8k.js} +3 -3
- package/dist/{chunk-2r2j2nvq.js.map → chunk-0v3bca8k.js.map} +1 -1
- package/dist/{chunk-4y74s15p.js → chunk-0vc2akg0.js} +1 -1
- package/dist/{chunk-877yc341.js → chunk-0yjm936b.js} +3 -3
- package/dist/{chunk-877yc341.js.map → chunk-0yjm936b.js.map} +1 -1
- package/dist/{chunk-a8n9ec43.js → chunk-159j20yr.js} +2 -2
- package/dist/{chunk-a8n9ec43.js.map → chunk-159j20yr.js.map} +1 -1
- package/dist/{chunk-3csz8pfk.js → chunk-1de3awrh.js} +3 -3
- package/dist/{chunk-3csz8pfk.js.map → chunk-1de3awrh.js.map} +1 -1
- package/dist/{chunk-3nf0nmpp.js → chunk-38kjpa6q.js} +1 -1
- package/dist/{chunk-afaff2se.js → chunk-3ndc8adc.js} +2 -2
- package/dist/{chunk-afaff2se.js.map → chunk-3ndc8adc.js.map} +1 -1
- package/dist/{chunk-z38m1nh5.js → chunk-3t4nw1n2.js} +2 -2
- package/dist/{chunk-z38m1nh5.js.map → chunk-3t4nw1n2.js.map} +1 -1
- package/dist/{chunk-rnd8s0n5.js → chunk-42646nt7.js} +2 -2
- package/dist/{chunk-rnd8s0n5.js.map → chunk-42646nt7.js.map} +1 -1
- package/dist/{chunk-9xyd5r54.js → chunk-4t2j3zcg.js} +2 -2
- package/dist/{chunk-9xyd5r54.js.map → chunk-4t2j3zcg.js.map} +1 -1
- package/dist/{chunk-hh5bs656.js → chunk-4vnrnbn3.js} +3 -3
- package/dist/{chunk-hh5bs656.js.map → chunk-4vnrnbn3.js.map} +1 -1
- package/dist/{chunk-m5f6ksqe.js → chunk-517fjfme.js} +3 -3
- package/dist/{chunk-m5f6ksqe.js.map → chunk-517fjfme.js.map} +1 -1
- package/dist/{chunk-wckbrbzx.js → chunk-56a3vnrj.js} +2 -2
- package/dist/{chunk-wckbrbzx.js.map → chunk-56a3vnrj.js.map} +1 -1
- package/dist/{chunk-ja1289jh.js → chunk-5zxxd7qp.js} +1 -1
- package/dist/{chunk-4ptz62pz.js → chunk-69c2s43a.js} +2 -2
- package/dist/{chunk-4ptz62pz.js.map → chunk-69c2s43a.js.map} +1 -1
- package/dist/chunk-6np1r9gk.js +5 -0
- package/dist/{chunk-49s8wwp2.js.map → chunk-6np1r9gk.js.map} +1 -1
- package/dist/{chunk-bstn00nx.js → chunk-72f6pbap.js} +2 -2
- package/dist/{chunk-bstn00nx.js.map → chunk-72f6pbap.js.map} +1 -1
- package/dist/{chunk-0mgswwbj.js → chunk-7426gfgw.js} +2 -2
- package/dist/{chunk-0mgswwbj.js.map → chunk-7426gfgw.js.map} +1 -1
- package/dist/{chunk-baj76zja.js → chunk-78wht1ph.js} +2 -2
- package/dist/{chunk-baj76zja.js.map → chunk-78wht1ph.js.map} +1 -1
- package/dist/{chunk-mzkzgp2j.js → chunk-7yww9aq7.js} +2 -2
- package/dist/{chunk-mzkzgp2j.js.map → chunk-7yww9aq7.js.map} +1 -1
- package/dist/{chunk-djyx6eyh.js → chunk-7zy6nq9e.js} +2 -2
- package/dist/{chunk-djyx6eyh.js.map → chunk-7zy6nq9e.js.map} +1 -1
- package/dist/{chunk-w6jff43c.js → chunk-8eyxj78g.js} +3 -3
- package/dist/{chunk-w6jff43c.js.map → chunk-8eyxj78g.js.map} +1 -1
- package/dist/{chunk-twrf6d08.js → chunk-986eh0n3.js} +2 -2
- package/dist/{chunk-twrf6d08.js.map → chunk-986eh0n3.js.map} +1 -1
- package/dist/{chunk-mv1rs9he.js → chunk-9gt9qdge.js} +1 -1
- package/dist/{chunk-v9z4x5j2.js → chunk-9kyfaeey.js} +2 -2
- package/dist/{chunk-v9z4x5j2.js.map → chunk-9kyfaeey.js.map} +1 -1
- package/dist/{chunk-198ywkt2.js → chunk-9md6acv2.js} +1 -1
- package/dist/{chunk-6tkkvaqg.js → chunk-ah2jy1vx.js} +2 -2
- package/dist/{chunk-6tkkvaqg.js.map → chunk-ah2jy1vx.js.map} +1 -1
- package/dist/{chunk-xv58jnpb.js → chunk-aq5zx3vg.js} +2 -2
- package/dist/{chunk-xv58jnpb.js.map → chunk-aq5zx3vg.js.map} +1 -1
- package/dist/{chunk-tdvjrftz.js → chunk-cmt3jw6j.js} +2 -2
- package/dist/{chunk-tdvjrftz.js.map → chunk-cmt3jw6j.js.map} +1 -1
- package/dist/{chunk-0hqg6ema.js → chunk-dce3w52r.js} +2 -2
- package/dist/{chunk-0hqg6ema.js.map → chunk-dce3w52r.js.map} +1 -1
- package/dist/{chunk-403b2rfp.js → chunk-dhq7zv0t.js} +2 -2
- package/dist/{chunk-403b2rfp.js.map → chunk-dhq7zv0t.js.map} +1 -1
- package/dist/{chunk-rq8b8pr5.js → chunk-exb35whf.js} +2 -2
- package/dist/{chunk-rq8b8pr5.js.map → chunk-exb35whf.js.map} +1 -1
- package/dist/{chunk-73rzf7ys.js → chunk-fe12f946.js} +2 -2
- package/dist/{chunk-73rzf7ys.js.map → chunk-fe12f946.js.map} +1 -1
- package/dist/{chunk-nh01ncyy.js → chunk-g5d62d1n.js} +2 -2
- package/dist/{chunk-nh01ncyy.js.map → chunk-g5d62d1n.js.map} +1 -1
- package/dist/{chunk-ydkv9e8w.js → chunk-h3gcxf2k.js} +3 -3
- package/dist/{chunk-ydkv9e8w.js.map → chunk-h3gcxf2k.js.map} +1 -1
- package/dist/{chunk-902qqwdt.js → chunk-jr9qerbr.js} +2 -2
- package/dist/{chunk-902qqwdt.js.map → chunk-jr9qerbr.js.map} +1 -1
- package/dist/{chunk-2t61pc8v.js → chunk-jrv31jp9.js} +2 -2
- package/dist/{chunk-2t61pc8v.js.map → chunk-jrv31jp9.js.map} +1 -1
- package/dist/{chunk-dewn1kmd.js → chunk-k1aw97dm.js} +2 -2
- package/dist/{chunk-dewn1kmd.js.map → chunk-k1aw97dm.js.map} +1 -1
- package/dist/{chunk-313593t3.js → chunk-kbdt84xg.js} +2 -2
- package/dist/{chunk-313593t3.js.map → chunk-kbdt84xg.js.map} +1 -1
- package/dist/{chunk-wjdw128m.js → chunk-ks9t82g0.js} +2 -2
- package/dist/{chunk-wjdw128m.js.map → chunk-ks9t82g0.js.map} +1 -1
- package/dist/{chunk-vfwpbveq.js → chunk-kwc68y45.js} +2 -2
- package/dist/{chunk-vfwpbveq.js.map → chunk-kwc68y45.js.map} +1 -1
- package/dist/{chunk-86zhngpg.js → chunk-n95dppzm.js} +2 -2
- package/dist/{chunk-86zhngpg.js.map → chunk-n95dppzm.js.map} +1 -1
- package/dist/{chunk-apga49vp.js → chunk-nvhbkqmd.js} +2 -2
- package/dist/{chunk-apga49vp.js.map → chunk-nvhbkqmd.js.map} +1 -1
- package/dist/{chunk-0t531zdt.js → chunk-p83cjehh.js} +2 -2
- package/dist/{chunk-0t531zdt.js.map → chunk-p83cjehh.js.map} +1 -1
- package/dist/{chunk-wf4kywta.js → chunk-pgdxqrjv.js} +3 -3
- package/dist/{chunk-wf4kywta.js.map → chunk-pgdxqrjv.js.map} +1 -1
- package/dist/{chunk-f4hx69cr.js → chunk-pw5h5935.js} +2 -2
- package/dist/{chunk-f4hx69cr.js.map → chunk-pw5h5935.js.map} +1 -1
- package/dist/{chunk-4d4td4k9.js → chunk-px3ctjxh.js} +2 -2
- package/dist/{chunk-4d4td4k9.js.map → chunk-px3ctjxh.js.map} +1 -1
- package/dist/{chunk-5gq41j99.js → chunk-q3e1bqrs.js} +3 -3
- package/dist/{chunk-5gq41j99.js.map → chunk-q3e1bqrs.js.map} +1 -1
- package/dist/{chunk-c94a3qsx.js → chunk-q7k2hc45.js} +2 -2
- package/dist/{chunk-c94a3qsx.js.map → chunk-q7k2hc45.js.map} +1 -1
- package/dist/{chunk-41bvpent.js → chunk-qbvm5q1g.js} +1 -1
- package/dist/{chunk-7j8x62yb.js → chunk-qvngsa1c.js} +2 -2
- package/dist/{chunk-7j8x62yb.js.map → chunk-qvngsa1c.js.map} +1 -1
- package/dist/{chunk-g8sh9btf.js → chunk-r5y2khw4.js} +2 -2
- package/dist/{chunk-g8sh9btf.js.map → chunk-r5y2khw4.js.map} +1 -1
- package/dist/{chunk-1a11x8ww.js → chunk-rrz2ry81.js} +2 -2
- package/dist/{chunk-1a11x8ww.js.map → chunk-rrz2ry81.js.map} +1 -1
- package/dist/{chunk-e9z8p2fy.js → chunk-rtv4ax8z.js} +2 -2
- package/dist/{chunk-e9z8p2fy.js.map → chunk-rtv4ax8z.js.map} +1 -1
- package/dist/{chunk-ae5ycktd.js → chunk-set6qmjw.js} +2 -2
- package/dist/{chunk-ae5ycktd.js.map → chunk-set6qmjw.js.map} +1 -1
- package/dist/{chunk-sbzqxtqg.js → chunk-ss3yn4g2.js} +3 -3
- package/dist/{chunk-sbzqxtqg.js.map → chunk-ss3yn4g2.js.map} +1 -1
- package/dist/{chunk-fe9fvtvt.js → chunk-t66ex43f.js} +4 -4
- package/dist/{chunk-fe9fvtvt.js.map → chunk-t66ex43f.js.map} +1 -1
- package/dist/{chunk-rv751mxq.js → chunk-t7yt8egz.js} +2 -2
- package/dist/{chunk-rv751mxq.js.map → chunk-t7yt8egz.js.map} +1 -1
- package/dist/{chunk-rnegd7ya.js → chunk-tr8se94g.js} +3 -3
- package/dist/{chunk-rnegd7ya.js.map → chunk-tr8se94g.js.map} +1 -1
- package/dist/{chunk-1fyn63ka.js → chunk-tzheb6ak.js} +3 -3
- package/dist/{chunk-1fyn63ka.js.map → chunk-tzheb6ak.js.map} +1 -1
- package/dist/{chunk-h0kyymhv.js → chunk-v10xzpqs.js} +2 -2
- package/dist/{chunk-h0kyymhv.js.map → chunk-v10xzpqs.js.map} +1 -1
- package/dist/{chunk-2b3hh9xw.js → chunk-wbv6218d.js} +3 -3
- package/dist/{chunk-2b3hh9xw.js.map → chunk-wbv6218d.js.map} +1 -1
- package/dist/{chunk-mp3ecfnh.js → chunk-wg0ttent.js} +2 -2
- package/dist/{chunk-mp3ecfnh.js.map → chunk-wg0ttent.js.map} +1 -1
- package/dist/{chunk-7jnawtcm.js → chunk-wnjvfmqc.js} +2 -2
- package/dist/{chunk-7jnawtcm.js.map → chunk-wnjvfmqc.js.map} +1 -1
- package/dist/{chunk-nhhnkv0e.js → chunk-x82f3q6a.js} +4 -4
- package/dist/{chunk-nhhnkv0e.js.map → chunk-x82f3q6a.js.map} +1 -1
- package/dist/{chunk-mr3szvr3.js → chunk-xff7tkde.js} +2 -2
- package/dist/{chunk-mr3szvr3.js.map → chunk-xff7tkde.js.map} +1 -1
- package/dist/chunk-xp5axyb5.js +30 -0
- package/dist/chunk-xp5axyb5.js.map +28 -0
- package/dist/{chunk-2x6cv37t.js → chunk-xtqd9vpp.js} +2 -2
- package/dist/{chunk-2x6cv37t.js.map → chunk-xtqd9vpp.js.map} +1 -1
- package/dist/{chunk-cee5gq7t.js → chunk-xyyq577r.js} +2 -2
- package/dist/{chunk-cee5gq7t.js.map → chunk-xyyq577r.js.map} +1 -1
- package/dist/{chunk-eqv7yxk7.js → chunk-ycn7w2e9.js} +2 -2
- package/dist/{chunk-eqv7yxk7.js.map → chunk-ycn7w2e9.js.map} +1 -1
- package/dist/{chunk-0fjn202c.js → chunk-yewj83ez.js} +3 -3
- package/dist/{chunk-0fjn202c.js.map → chunk-yewj83ez.js.map} +1 -1
- package/dist/{chunk-2ery6a75.js → chunk-yzsyg1f7.js} +3 -3
- package/dist/{chunk-2ery6a75.js.map → chunk-yzsyg1f7.js.map} +1 -1
- package/dist/{chunk-jgpbr2k1.js → chunk-z7224rhm.js} +2 -2
- package/dist/{chunk-jgpbr2k1.js.map → chunk-z7224rhm.js.map} +1 -1
- package/dist/{chunk-attr793y.js → chunk-zcg6m7gf.js} +2 -2
- package/dist/{chunk-attr793y.js.map → chunk-zcg6m7gf.js.map} +1 -1
- package/dist/{chunk-yhgt9dxj.js → chunk-zfbqgzwa.js} +2 -2
- package/dist/{chunk-yhgt9dxj.js.map → chunk-zfbqgzwa.js.map} +1 -1
- package/dist/{chunk-x5z6r7z9.js → chunk-zv9d6jkj.js} +2 -2
- package/dist/{chunk-x5z6r7z9.js.map → chunk-zv9d6jkj.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/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-1q5eagpm.js +0 -30
- package/dist/chunk-1q5eagpm.js.map +0 -27
- package/dist/chunk-49s8wwp2.js +0 -5
- /package/dist/{chunk-4y74s15p.js.map → chunk-0vc2akg0.js.map} +0 -0
- /package/dist/{chunk-3nf0nmpp.js.map → chunk-38kjpa6q.js.map} +0 -0
- /package/dist/{chunk-ja1289jh.js.map → chunk-5zxxd7qp.js.map} +0 -0
- /package/dist/{chunk-mv1rs9he.js.map → chunk-9gt9qdge.js.map} +0 -0
- /package/dist/{chunk-198ywkt2.js.map → chunk-9md6acv2.js.map} +0 -0
- /package/dist/{chunk-41bvpent.js.map → chunk-qbvm5q1g.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{dh as KK}from"./chunk-hh5bs656.js";import{xh as GK}from"./chunk-3csz8pfk.js";import{$h as I$,Ai as XQ,Bi as l$,Ch as KG,Ci as i$,Dh as b9,Di as hG,Eh as R9,Fh as B8,Fi as pG,Gh as z8,Jh as X8,Kh as Q8,Lh as lZ,Mh as hQ,Nh as TW,Oh as Z9,Ph as h,Vh as C,Wh as w8,Xh as zZ,Yh as V8,Zh as Y6,ai as g,bi as y4,pi as j6,wi as XZ,yh as J3}from"./chunk-2r2j2nvq.js";import{Ii as l1,Ji as Z0,Ki as s1,Li as k9}from"./chunk-cee5gq7t.js";import{Mi as m3,Ni as _W,Ri as HY,Si as d4,Ti as T}from"./chunk-a8n9ec43.js";import{Wi as JQ,Zi as g3}from"./chunk-w6jff43c.js";import{bj as fY,ej as wG}from"./chunk-sbzqxtqg.js";import{Bj as i1,wj as M$}from"./chunk-xv58jnpb.js";import{Pj as gX}from"./chunk-313593t3.js";import{Qj as s$,Tj as bG}from"./chunk-86zhngpg.js";import{Uj as U1}from"./chunk-attr793y.js";import{$j as vZ,Vj as Z6,Wj as i0,Xj as N1,Yj as zK,Zj as XK,ak as gG,jk as QK}from"./chunk-2ery6a75.js";import{yk as _1}from"./chunk-73rzf7ys.js";import{Dk as XG,Ik as OW}from"./chunk-2x6cv37t.js";import{Pk as zG,Uk as n}from"./chunk-mr3szvr3.js";import{Vk as uZ,Yk as L}from"./chunk-1fyn63ka.js";import{el as BW}from"./chunk-g8sh9btf.js";import{fl as cG}from"./chunk-mzkzgp2j.js";import{pl as XW}from"./chunk-apga49vp.js";import{ql as r4,sl as FG}from"./chunk-6tkkvaqg.js";import{xl as u4}from"./chunk-baj76zja.js";function o3($){return typeof $==="function"&&$.prototype!==void 0}var iW=Symbol.for("gemi.HttpResponse"),IK=new Set([301,302,303,307,308]);class Y1{kind;body;status;headers;[iW]=!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 lW(J,"json"),new Y1("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 Y1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!IK.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 Y1("empty",void 0,J,Y)}static noContent($={}){return new Y1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return lW(J,"text"),new Y1("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 lW($,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 c1($){return typeof $==="object"&&$!==null&&$[iW]===!0}function TK($,Z,J={}){return Y1.error($,Z,J)}function l0($){return typeof $==="string"?[$]:$}function a3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function NK($){return"total"in $&&"partial"in $&&"body"in $}function sW(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function rZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":Q8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function _K($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(NK($))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 G8($,Z){if($ instanceof Response)return $;if(!$)return sW();let J=await _K($),{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 sW()}let{range:Q}=Z;if(Q){if(z<=0)return rZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=z8(Q,z);if(!F)return rZ(z);W=W.slice(F.start,F.end+1),Y=F.start,j=F.end,X=!0}}}let G=Boolean(Q)&&X,K=G?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),G)B.set("Content-Range",X8(Y,j,z)),B.set("Content-Length",String(j-Y+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",a3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[F,O]of Object.entries(J.extraHeaders))B.set(F,O);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:B})}return new Response(W,{status:K,headers:B})}class ZZ extends Z0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var nW={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function eZ($){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 nW)))return Math.floor(Number(J[1])*(nW[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var tZ=new WeakMap;function aW($){return tZ.has($)}function rW($){return tZ.get($)?.limit??null}function tW($){let Z=tZ.get($);return Z?Z.read>Z.limit:!1}function xK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function F8($,Z){let J=xK($);if(J!==null&&J>Z)throw new ZZ(Z)}function r3($,Z,J={}){let W=tZ.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};tZ.set($,Y),SK($,Y)}if(J.checkDeclared!==!1)F8($,Z)}function CK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function K8($,Z){if(Z.stream!==void 0)return Z.stream;let J=CK($);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 ZZ(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 $Z($,Z){if(F8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=K8($,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 oW($){return $.headers.get("Content-Type")??""}function SK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>K8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>$Z($,Z)}),J("arrayBuffer",{value:async()=>{let W=await $Z($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await $Z($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await $Z($,Z)))}),J("blob",{value:async()=>new Blob([await $Z($,Z)],{type:oW($)})}),J("formData",{value:async()=>new Response(await $Z($,Z),{headers:{"Content-Type":oW($)}}).formData()}),J("clone",{value:()=>{F8($,Z.limit);let W=K8($,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 eW($){return o3($)}class l{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(!eW(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(eW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class J9{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=l0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of Z9($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(tW($.rawRequest))throw new ZZ(rW($.rawRequest));throw J}}}class W9{constructor(...$){return new l(...$)}}class Y9 extends l{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=B8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(c1(Y))return Y;return await G8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof V8)return rZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class j9{constructor(...$){return new Y9(...$)}}class z9{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new l("GET",$,"list"),post:new l("POST",$,"store")},this.second={get:new l("GET",$,"show"),put:new l("PUT",$,"update"),delete:new l("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 T0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new l("GET",$,Z)}post($,Z){return new l("POST",$,Z)}put($,Z){return new l("PUT",$,Z)}patch($,Z){return new l("PATCH",$,Z)}delete($,Z){return new l("DELETE",$,Z)}resource($){return new z9($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${$9($)}.`);return AK($,this)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${$9($)}.`);return EK($,this)}file($,Z){return new W9("GET",$,Z)}stream($,Z){return new j9("GET",$,Z)}proxy($,Z={}){return new J9($,Z)}}function $9($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function AK($,Z){let J={stream:new l("POST",$,"stream"),attach:new l("POST",$,"attach"),stop:new l("POST",$,"stop"),upload:new l("POST",$,"upload")};return class extends T0{static __internal_brand="AgentRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.stream,"/attach":J.attach,"/stop":J.stop,"/files":J.upload};static middleware(Y){if(Y.stream)J.stream.middleware(Y.stream);if(Y.attach)J.attach.middleware(Y.attach);if(Y.stop)J.stop.middleware(Y.stop);if(Y.upload)J.upload.middleware(Y.upload);return this}}}function EK($,Z){let J={start:new l("POST",$,"voiceStart"),update:new l("PATCH",$,"voiceUpdate"),end:new l("DELETE",$,"voiceEnd")};return class extends T0{static __internal_brand="VoiceRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.start,"/:sessionId":{patch:J.update,delete:J.end}};static middleware(Y){if(Y.start)J.start.middleware(Y.start);if(Y.update)J.update.middleware(Y.update);if(Y.end)J.end.middleware(Y.end);return this}}}var d1="access_token";function P$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function t3($,Z){let J=P$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var fK=/^[A-Za-z0-9_-]+$/,bK=/^:[A-Za-z_][A-Za-z0-9_]*$/,X9=/^[A-Za-z0-9_-]{1,128}$/,RK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function Q9($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function JZ($){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(bK.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(!fK.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 $3($,Z={}){let J=JZ($),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"||!X9.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 D8($){if(JZ($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function G9($){if(typeof $!=="string"||$.length===0||$.length>64||!RK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function K9($,Z){if($===Z)return!0;if($===G0)return Z.startsWith(`${G0}.`)&&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(":")&&X9.test(W[j]))}var G0="user";function WZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return $3(`${G0}.:id`,{id:Z})}class r{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class e3 extends r{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return r3(this.req.rawRequest,eZ(Z)),{}}}function wK($){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 kK={"body-limit":e3};class u1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:eZ($.bodyLimit)}get aliases(){return{...kK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!aW($))r3($,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 wK($).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:F9(z)})}}else if(o3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:F9(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 qK(W.slice(j+1)),z}return Y})()}}function F9($){return $?.runsOnRefusal===!0}async function qK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class $6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class O9{static __brand="ChannelRouter";channels={};public(){return new $6("public")}private($){return new $6("private",$)}async authorize($,Z,J={},W={}){try{mK(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(!U9(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===G0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=$3(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 T.exit(()=>Z6.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await L(u1).runMiddleware(Y.middlewares);if(Z===G0){let G=await B9(X);if(!G)return{ok:!1,code:"denied"};if(j=WZ(G),Y.visibility==="private"&&Y.authorizer){if(await V9(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 V9(Y.authorizer,X,z):await B9(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(gK(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 yK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;L9(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 U9($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function B9($){if(!T.getStore().user&&P$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function V9($,Z,J){if(vK($))return new $().authorize(Z,J);return $(Z,J)}function vK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function gK($){return $?.kind===l1||i1($)||M$($)}var D9=new WeakSet;function mK($){if(D9.has($))return;L9($),D9.add($)}function L9($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!U9(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=JZ(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!==G0&&j.length===2&&j[0]===G0)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!==G0&&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===G0?[G0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(hK(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 hK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class O8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class U8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class L8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class H9{static __brand="McpRouter";routes={};scopes;param($){return new O8($.as,$.input,$.bind)}fromTool($,Z={}){return new L8($,Z)}fromApiRoute($,Z,J){return new U8($,Z,J)}}function K0($,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 H8 extends Z0{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 I1{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 H8([K0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new H8($,Z)}}class P9{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 I1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function P8($,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",a3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class M9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function I9($,Z){if(c1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class T9{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=I9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=l0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class N9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends T1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends T1{routes=J??{}}}else this.children=class extends T1{routes=Z},this.handler=()=>({})}async run($,Z){let J=I9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class T1{middlewares=[];featureGates=[];routes={};view($,Z){return new T9($,Z)}file($){return new M9($)}redirect($){return new P9($)}layout($,Z,J){return new N9($,Z,J)}}function pK($){return $}function cK(){return{aliases:{},global:[],bodyLimit:null}}var j1="redirect";function z1($,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 YZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function dK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(L(n).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function uK($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function J6($,Z){let J=Z||L(A).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=dK($,!W);if(W||!uK(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(j1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class _9 extends r{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await t3(L(A),J);if(!W)throw new I$({redirectTo:J6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",M8="private, no-cache, no-store, max-age=0, must-revalidate";class W6 extends r{run(){let $=T.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(P$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new x9(`${W.pathname}${W.search}`)}}class x9 extends Z0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=lK($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":M8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":M8}},viewData:{status:200,data:{},headers:{"Cache-Control":M8},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 lK($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class C9 extends r{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 S9={"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 A9 extends r{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...S9,...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={...S9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var iK="Rate limit exceeded";class n1 extends Z0{result;retryAfter;constructor($,Z=iK){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?T8($):{}};this.payload={api:{status:429,data:{error:{...s1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function T8($){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 X1{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(E9("window",W),E9("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 n1(W,typeof J==="function"?J(W):J);return W}}function E9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as N8}from"net";function T$($){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 N8(j)===6?j:null}if(N8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&N8(J[1])===4?J[1]:null}class w9 extends r{async run($,Z){let J=sK();if(!J)return{};let W=await J.consume(this.key(),{limit:f9($)??this.config.limit,window:f9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(T8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new n1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=b9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${jZ(this.req)}:${this.req.routePath??"*"}`}}function sK(){try{let $=L();return $.bound(X1)?$.make(X1):null}catch{return null}}function jZ($){let Z=R9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return T$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function f9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class q9 extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new _8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new _8;return{}}}class _8 extends Z0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:k9("csrf","Invalid CSRF token",403)}},view:{}}}class y9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class v9{all($,Z){return!0}}class x8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new zZ:new Y6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends r{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let 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 zZ:$ instanceof Y6}}function nK($){return new x8($)}async function z6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await QF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return XF(z,Z,J,$.url)}async function XF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:K}=await Y.read();if(G)break;if(z+K.byteLength>Z){if(!J)throw new j6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function QF($){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 X6($){return new TextDecoder("utf-8").decode($)}var GF={"&":"&","<":"<",">":">",'"':""","'":"'"};function N$($){return $.replace(/[&<>"']/g,(Z)=>GF[Z])}var KF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function C8($){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 KF[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 S8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function g9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(C8($.slice(W)));return}if(Y>W)Z.text(C8($.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(S8($.slice(Y+2,j).trim())),W=j+1}else{let j=FF($,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=S8(z.slice(0,Q));if(G){if(Z.open(G,BF(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function FF($,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 BF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[S8(W[1])]=C8(W[2]??W[3]??"");return Z}class J0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var d9="http://www.sitemaps.org/schemas/sitemap/0.9",VF="http://www.w3.org/1999/xhtml",f8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
import{fh as KK}from"./chunk-4vnrnbn3.js";import{zh as GK}from"./chunk-1de3awrh.js";import{$h as Y6,Ah as J3,Ci as XQ,Di as l$,Eh as KG,Ei as i$,Fh as b9,Fi as hG,Gh as R9,Hh as B8,Hi as pG,Ih as z8,Lh as X8,Mh as Q8,Nh as lZ,Oh as hQ,Ph as TW,Qh as Z9,Rh as h,Xh as C,Yh as w8,Zh as zZ,_h as V8,bi as I$,ci as g,di as y4,ri as j6,yi as XZ}from"./chunk-0v3bca8k.js";import{Ki as l1,Li as Z0,Mi as s1,Ni as k9}from"./chunk-xyyq577r.js";import{Oi as m3,Pi as _W,Ti as HY,Ui as d4,Vi as T}from"./chunk-159j20yr.js";import{$i as g3,Yi as JQ}from"./chunk-8eyxj78g.js";import{dj as fY,gj as wG}from"./chunk-ss3yn4g2.js";import{Dj as i1,yj as M$}from"./chunk-aq5zx3vg.js";import{Rj as gX}from"./chunk-kbdt84xg.js";import{Sj as s$,Vj as bG}from"./chunk-n95dppzm.js";import{Wj as U1}from"./chunk-zcg6m7gf.js";import{$j as XK,Xj as Z6,Yj as i0,Zj as N1,_j as zK,bk as vZ,ck as gG,lk as QK}from"./chunk-yzsyg1f7.js";import{Ak as _1}from"./chunk-fe12f946.js";import{Fk as XG,Kk as OW}from"./chunk-xtqd9vpp.js";import{Rk as zG,Wk as n}from"./chunk-xff7tkde.js";import{Xk as uZ,_k as L}from"./chunk-tzheb6ak.js";import{gl as BW}from"./chunk-r5y2khw4.js";import{hl as cG}from"./chunk-7yww9aq7.js";import{rl as XW}from"./chunk-nvhbkqmd.js";import{sl as r4,ul as FG}from"./chunk-ah2jy1vx.js";import{zl as u4}from"./chunk-78wht1ph.js";function o3($){return typeof $==="function"&&$.prototype!==void 0}var iW=Symbol.for("gemi.HttpResponse"),IK=new Set([301,302,303,307,308]);class Y1{kind;body;status;headers;[iW]=!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 lW(J,"json"),new Y1("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 Y1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!IK.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 Y1("empty",void 0,J,Y)}static noContent($={}){return new Y1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return lW(J,"text"),new Y1("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 lW($,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 c1($){return typeof $==="object"&&$!==null&&$[iW]===!0}function TK($,Z,J={}){return Y1.error($,Z,J)}function l0($){return typeof $==="string"?[$]:$}function a3($,Z){let J=Z?"attachment":"inline",W=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${W}"; filename*=UTF-8''${encodeURIComponent($)}`}function NK($){return"total"in $&&"partial"in $&&"body"in $}function sW(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function rZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":Q8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function _K($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(NK($))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 G8($,Z){if($ instanceof Response)return $;if(!$)return sW();let J=await _K($),{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 sW()}let{range:Q}=Z;if(Q){if(z<=0)return rZ(Math.max(z,0));if(!X){if(W instanceof Blob){let F=z8(Q,z);if(!F)return rZ(z);W=W.slice(F.start,F.end+1),Y=F.start,j=F.end,X=!0}}}let G=Boolean(Q)&&X,K=G?206:J.status,B=new Headers;if(B.set("Accept-Ranges","bytes"),B.set("Content-Type",J.type||"application/octet-stream"),B.set("X-Content-Type-Options","nosniff"),G)B.set("Content-Range",X8(Y,j,z)),B.set("Content-Length",String(j-Y+1));else if(z>=0)B.set("Content-Length",String(z));if(J.name)B.set("Content-Disposition",a3(J.name,J.download));if(J.etag)B.set("ETag",J.etag);if(J.lastModified)B.set("Last-Modified",J.lastModified.toUTCString());for(let[F,O]of Object.entries(J.extraHeaders))B.set(F,O);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:K,headers:B})}return new Response(W,{status:K,headers:B})}class ZZ extends Z0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var nW={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function eZ($){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 nW)))return Math.floor(Number(J[1])*(nW[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var tZ=new WeakMap;function aW($){return tZ.has($)}function rW($){return tZ.get($)?.limit??null}function tW($){let Z=tZ.get($);return Z?Z.read>Z.limit:!1}function xK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function F8($,Z){let J=xK($);if(J!==null&&J>Z)throw new ZZ(Z)}function r3($,Z,J={}){let W=tZ.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};tZ.set($,Y),SK($,Y)}if(J.checkDeclared!==!1)F8($,Z)}function CK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function K8($,Z){if(Z.stream!==void 0)return Z.stream;let J=CK($);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 ZZ(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 $Z($,Z){if(F8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=K8($,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 oW($){return $.headers.get("Content-Type")??""}function SK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>K8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>$Z($,Z)}),J("arrayBuffer",{value:async()=>{let W=await $Z($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await $Z($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await $Z($,Z)))}),J("blob",{value:async()=>new Blob([await $Z($,Z)],{type:oW($)})}),J("formData",{value:async()=>new Response(await $Z($,Z),{headers:{"Content-Type":oW($)}}).formData()}),J("clone",{value:()=>{F8($,Z.limit);let W=K8($,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 eW($){return o3($)}class l{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(!eW(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(eW(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=l0($),this}}class J9{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=l0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of Z9($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(tW($.rawRequest))throw new ZZ(rW($.rawRequest));throw J}}}class W9{constructor(...$){return new l(...$)}}class Y9 extends l{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=B8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(c1(Y))return Y;return await G8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof V8)return rZ(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class j9{constructor(...$){return new Y9(...$)}}class z9{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new l("GET",$,"list"),post:new l("POST",$,"store")},this.second={get:new l("GET",$,"show"),put:new l("PUT",$,"update"),delete:new l("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 T0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new l("GET",$,Z)}post($,Z){return new l("POST",$,Z)}put($,Z){return new l("PUT",$,Z)}patch($,Z){return new l("PATCH",$,Z)}delete($,Z){return new l("DELETE",$,Z)}resource($){return new z9($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${$9($)}.`);return AK($,this)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${$9($)}.`);return EK($,this)}file($,Z){return new W9("GET",$,Z)}stream($,Z){return new j9("GET",$,Z)}proxy($,Z={}){return new J9($,Z)}}function $9($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function AK($,Z){let J={stream:new l("POST",$,"stream"),attach:new l("POST",$,"attach"),stop:new l("POST",$,"stop"),upload:new l("POST",$,"upload")};return class extends T0{static __internal_brand="AgentRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.stream,"/attach":J.attach,"/stop":J.stop,"/files":J.upload};static middleware(Y){if(Y.stream)J.stream.middleware(Y.stream);if(Y.attach)J.attach.middleware(Y.attach);if(Y.stop)J.stop.middleware(Y.stop);if(Y.upload)J.upload.middleware(Y.upload);return this}}}function EK($,Z){let J={start:new l("POST",$,"voiceStart"),update:new l("PATCH",$,"voiceUpdate"),end:new l("DELETE",$,"voiceEnd")};return class extends T0{static __internal_brand="VoiceRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.start,"/:sessionId":{patch:J.update,delete:J.end}};static middleware(Y){if(Y.start)J.start.middleware(Y.start);if(Y.update)J.update.middleware(Y.update);if(Y.end)J.end.middleware(Y.end);return this}}}var d1="access_token";function P$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function t3($,Z){let J=P$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var fK=/^[A-Za-z0-9_-]+$/,bK=/^:[A-Za-z_][A-Za-z0-9_]*$/,X9=/^[A-Za-z0-9_-]{1,128}$/,RK=/^[A-Za-z0-9_.:-]+$/;class p extends Error{constructor($){super($);this.name="InvalidChannelError"}}function Q9($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function JZ($){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(bK.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(!fK.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 $3($,Z={}){let J=JZ($),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"||!X9.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 D8($){if(JZ($).some((J)=>J.startsWith(":")))throw new p(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function G9($){if(typeof $!=="string"||$.length===0||$.length>64||!RK.test($))throw new p(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function K9($,Z){if($===Z)return!0;if($===G0)return Z.startsWith(`${G0}.`)&&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(":")&&X9.test(W[j]))}var G0="user";function WZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return $3(`${G0}.:id`,{id:Z})}class r{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class e3 extends r{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return r3(this.req.rawRequest,eZ(Z)),{}}}function wK($){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 kK={"body-limit":e3};class u1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:eZ($.bodyLimit)}get aliases(){return{...kK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!aW($))r3($,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 wK($).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:F9(z)})}}else if(o3(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:F9(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 qK(W.slice(j+1)),z}return Y})()}}function F9($){return $?.runsOnRefusal===!0}async function qK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class $6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...l0($)],this}events(...$){return this}}class O9{static __brand="ChannelRouter";channels={};public(){return new $6("public")}private($){return new $6("private",$)}async authorize($,Z,J={},W={}){try{mK(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(!U9(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===G0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=$3(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 T.exit(()=>Z6.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await L(u1).runMiddleware(Y.middlewares);if(Z===G0){let G=await B9(X);if(!G)return{ok:!1,code:"denied"};if(j=WZ(G),Y.visibility==="private"&&Y.authorizer){if(await V9(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 V9(Y.authorizer,X,z):await B9(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(gK(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 yK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;L9(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 U9($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function B9($){if(!T.getStore().user&&P$($)===null)return null;try{return await w0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function V9($,Z,J){if(vK($))return new $().authorize(Z,J);return $(Z,J)}function vK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function gK($){return $?.kind===l1||i1($)||M$($)}var D9=new WeakSet;function mK($){if(D9.has($))return;L9($),D9.add($)}function L9($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!U9(Y))throw new p(`The channel "${W}" is not declared with this.public() or this.private().`);let j=JZ(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!==G0&&j.length===2&&j[0]===G0)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!==G0&&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===G0?[G0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(hK(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 hK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class O8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class U8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class L8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}class H9{static __brand="McpRouter";routes={};scopes;param($){return new O8($.as,$.input,$.bind)}fromTool($,Z={}){return new L8($,Z)}fromApiRoute($,Z,J){return new U8($,Z,J)}}function K0($,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 H8 extends Z0{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 I1{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 H8([K0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new H8($,Z)}}class P9{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 I1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function P8($,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",a3(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class M9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function I9($,Z){if(c1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class T9{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=I9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=l0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class N9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends T1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends T1{routes=J??{}}}else this.children=class extends T1{routes=Z},this.handler=()=>({})}async run($,Z){let J=I9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=l0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class T1{middlewares=[];featureGates=[];routes={};view($,Z){return new T9($,Z)}file($){return new M9($)}redirect($){return new P9($)}layout($,Z,J){return new N9($,Z,J)}}function pK($){return $}function cK(){return{aliases:{},global:[],bodyLimit:null}}var j1="redirect";function z1($,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 YZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function dK($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(L(n).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function uK($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function J6($,Z){let J=Z||L(A).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=dK($,!W);if(W||!uK(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(j1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class _9 extends r{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await t3(L(A),J);if(!W)throw new I$({redirectTo:J6(J,$)});return Z.setUser(W),{}}}var I8="gemi_same_site",M8="private, no-cache, no-store, max-age=0, must-revalidate";class W6 extends r{run(){let $=T.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(P$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(I8,"1"),new x9(`${W.pathname}${W.search}`)}}class x9 extends Z0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=lK($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":M8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":M8}},viewData:{status:200,data:{},headers:{"Cache-Control":M8},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 lK($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class C9 extends r{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 S9={"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 A9 extends r{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...S9,...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={...S9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var iK="Rate limit exceeded";class n1 extends Z0{result;retryAfter;constructor($,Z=iK){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?T8($):{}};this.payload={api:{status:429,data:{error:{...s1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function T8($){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 X1{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(E9("window",W),E9("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 n1(W,typeof J==="function"?J(W):J);return W}}function E9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as N8}from"net";function T$($){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 N8(j)===6?j:null}if(N8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&N8(J[1])===4?J[1]:null}class w9 extends r{async run($,Z){let J=sK();if(!J)return{};let W=await J.consume(this.key(),{limit:f9($)??this.config.limit,window:f9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(T8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new n1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=b9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${jZ(this.req)}:${this.req.routePath??"*"}`}}function sK(){try{let $=L();return $.bound(X1)?$.make(X1):null}catch{return null}}function jZ($){let Z=R9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return T$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function f9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class q9 extends r{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new _8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new _8;return{}}}class _8 extends Z0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:k9("csrf","Invalid CSRF token",403)}},view:{}}}class y9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class v9{all($,Z){return!0}}class x8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new zZ:new Y6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends r{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let 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 zZ:$ instanceof Y6}}function nK($){return new x8($)}async function z6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await QF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return XF(z,Z,J,$.url)}async function XF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:K}=await Y.read();if(G)break;if(z+K.byteLength>Z){if(!J)throw new j6(W,Z);j.push(K.subarray(0,Z-z)),z=Z;break}j.push(K),z+=K.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function QF($){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 X6($){return new TextDecoder("utf-8").decode($)}var GF={"&":"&","<":"<",">":">",'"':""","'":"'"};function N$($){return $.replace(/[&<>"']/g,(Z)=>GF[Z])}var KF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function C8($){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 KF[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 S8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function g9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(C8($.slice(W)));return}if(Y>W)Z.text(C8($.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(S8($.slice(Y+2,j).trim())),W=j+1}else{let j=FF($,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=S8(z.slice(0,Q));if(G){if(Z.open(G,BF(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function FF($,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 BF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[S8(W[1])]=C8(W[2]??W[3]??"");return Z}class J0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var d9="http://www.sitemaps.org/schemas/sitemap/0.9",VF="http://www.w3.org/1999/xhtml",f8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`,m9=`<urlset xmlns="${d9}" xmlns:xhtml="${VF}">
|
|
4
4
|
`,h9=`</urlset>
|
|
5
5
|
`,_$=50000,Z3=52428800,p9=2048,DF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),OF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,UF="application/xml; charset=utf-8",c9=new TextEncoder;function b8($,Z){let J;try{J=new URL($)}catch{throw new J0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new J0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>p9)throw new J0(`Sitemap: ${Z} is over ${p9} characters: "${W.slice(0,80)}\u2026".`);return W}function u9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new J0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!OF.test($))throw new J0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function LF($){let Z=b8($.loc,"loc"),J=`<url><loc>${N$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${N$(u9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!DF.has($.changefreq))throw new J0(`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 J0(`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 J0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=b8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${N$(Y)}" href="${N$(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((K)=>{if(X||K.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
|
|
21
21
|
`))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as ZN,createContext as CO,createElement as JN,lazy as WN,use as YN,useContext as jN}from"react";function uQ($){return{islands:[],render:$,instances:new WeakMap,count:0}}var c3="gemi-slot",lQ="data-slot",iQ="data-gemi-slot";var SO=Symbol.for("gemi.staticRender"),sQ=globalThis[SO]??=CO(null);import{createHash as tQ}from"crypto";var YW='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 AO}from"crypto";import{existsSync as oQ,readFileSync as EO}from"fs";import{join as QW}from"path";var aQ=".script",fO=[".ts",".js"],bO="document-scripts.json",rQ="data-gemi-script",RO=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function wO($){if(typeof $!=="string"||!RO.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 kO($,Z){for(let J of fO){let W=QW($,"views",`${Z}${aQ}${J}`);if(oQ(W))return W}return null}async function nQ($){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 qO($){return`'sha256-${AO("sha256").update($).digest("base64")}'`}var jW,zW=new Map;function yO(){if(jW===void 0){let $=QW(XW(),"dist","server",bO);jW=oQ($)?JSON.parse(EO($,"utf8")):null}return jW??null}async function GW($){wO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=yO()?.[$];if(j!==void 0)return j;let z=zW.get($);if(z)return z}let J=QW(XW(),"app"),W=kO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${aQ}.ts (or .js).`);if(!Z)return nQ(W);let Y=nQ(W);return zW.set($,Y),Y.catch(()=>zW.delete($)),Y}async function BN($){return qO(await GW($))}var vO="gemi-islands",MN=`'sha256-${tQ("sha256").update(BW).digest("base64")}'`;function KW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var FW=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),IN=`'sha256-${tQ("sha256").update(YW).digest("base64")}'`,gO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',mO="gemi-static";function eQ($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let D=V.module?J(V.module):void 0;if(!D)return console.error(`[gemi] island ${V.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(V.load==="eager"){for(let U of D.preload)z.add(U);if(V.preloadDynamic)for(let U of D.dynamicPreload??[])z.add(U)}return{s:D.src,e:V.export,l:V.load}});let Q=X.some((V)=>V!==null),G=j?`<script type="module" ${rQ}="${FW(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return KW($,"</head>",G,!1);let B=(Y?`<meta name="${mO}" content="${FW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${FW(V)}"/>`).join("")+G,F=Y?YW:BW,O=(Q?`<script type="application/json" id="${vO}">${Q1({i:X})}</script>`:"")+`<script type="module">${W?gO+F:F}</script>`;return KW(KW($,"</head>",B,!1),"</body>",O,!0)}function hO($,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 $G($){let Z=`<template ${iQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=hO($,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=`<${c3} ${lQ}="${j}" style="display:contents"></${c3}>`;$=$.split(Q).join(`<${c3} style="display:contents">${X}</${c3}>`)}return $}function ZG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function JG($,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 pO=async()=>(await import("./chunk-0fjn202c.js")).default,VW,d3=async(...$)=>{return VW??=import("react-dom/server.browser").catch((Z)=>{throw VW=void 0,Z}),(await VW).renderToReadableStream(...$)},YG=1e4,jG="no-locale",cO="no-theme";async function dO($,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 UW="/assets";function uO($){return $===UW||$.startsWith(`${UW}/`)}function lO($){let Z=$.filter(uO);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 "${UW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function iO($){let Z=L(W1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function DW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function sO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class u3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=pQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;constructor($){let Z=GQ();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.theme=$.theme??Z.theme,this.hooks={onNotFound:$.onNotFound??Z.onNotFound,onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":AJ};this.flatViewRoutes=g4(J),lO(Object.keys(this.flatViewRoutes)),this.routeManifest=h4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=c4(J),this.flatComponentTree=ZW(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let Y=this.flatViewRoutes[W].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=L(o1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)d4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{l$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let K of J?.[G]??[])Q.add(K);return[...Q].map((G)=>y1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let K=OW(),B=new AbortController,F=setTimeout(()=>B.abort(),YG),O=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},V=uQ(async(D,U)=>{let H=await d3(D,{signal:B.signal,identifierPrefix:U,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let D,U=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(U)D={name:U,source:await GW(U)};let H;if(W.navigation){let x=W.navigation===!0?{}:W.navigation,E=x.version?String(await J(()=>x.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",D?.name??"",E].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let I=await d3(y1(sQ.Provider,{value:V,children:y1(WG,{children:[...G,y1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:Q,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});await I.allReady.catch(()=>{});let M=$G(await new Response(I).text());return new Response(eQ(M,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,D),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:K,noStream:B,noTheme:F,url:O,user:V,viewData:D,breadcrumbs:U,urlLocaleSegment:H,meta:I,isOgRequest:M,appId:x,features:E,staticView:f}=$,S=this.theme===!1||F||f?null:{cookie:this.theme.cookie??gJ,default:this.theme.default??null,value:nO(Z,this.theme.cookie??gJ)},R=H?gQ(Q,[H]).pathname:Q,P={kind:"view",data:{meta:I,pageData:{[R]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:V},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:H,pathname:Y,params:X,currentPath:Q,searchParams:O.search,is404:!Y?!0:!1,domain:Z.domain?iO(Z):null},appId:x,features:E,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},N=this.root,y=this.routeManifest[Y];return async(U$)=>{let{bootstrapModules:M0=[],loaders:g1,getStyles:s,viewImportMap:q,cssManifest:I0,ogMap:n$,viewModules:i3,clientEntry:L$,modulePreloadManifest:m1,assetBase:h1,resolveIsland:o$,buildId:Q0}=U$,oZ=L$?[]:M0,s3=(R0)=>[R0,`window.loaders=${g1}`,...L$?[`import(${JSON.stringify(L$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(M){let R0=null,t$=null;for(let e$ of y??[])if(typeof n$[e$]==="function")t$=e$,R0=n$[e$];if(!R0)return new Response("Not found",{status:404});let BK=Object.values(P.data.pageData)[0];try{await d3(y1(R0,BK[t$]),{onError:()=>{}})}catch(e$){let{fonts:VK,...DK}=e$.satoriOptions,OK=await Promise.all(VK.map((n3)=>{return dO(n3.name,n3.weight,n3.style).then((MK)=>({...n3,data:MK}))})),uW=new Headers(j);uW.set("Content-Type","image/png");let[UK,LK]=await Promise.all([pO(),y4("Rendering an OG image")]),HK=await UK(e$.jsx,{...DK,fonts:OK}),PK=await LK(Buffer.from(HK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(PK),{headers:uW})}return new Response("data")}if(f&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:f,currentViews:y,data:P.data,serverQueries:G,headers:j,getStyles:s,viewImportMap:q,viewModules:i3,resolveIsland:o$,buildId:Q0});if(P.data.cssManifest=I0,P.data.modulePreloadManifest=m1??{},h1&&h1!=="/")P.data.assetBase=h1;let a$=this.modulePreloadLinks({clientEntry:L$,modulePreloadManifest:m1,views:y??["404"],routeKey:Y??"404"}),aZ=await s(y??["404"]);P.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let p1=new AbortController,H$=setTimeout(()=>p1.abort(),YG),b=D6(K)||B,b0=Bun.env.NODE_ENV!=="production"&&!b&&Y&&this.shellReporter.shouldObserve(Y)?cQ():null,r$=OW();try{let R0=await d3(y1(WG,{children:[...a$,...aZ,...S?[y1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:VQ(Q1({cookie:S.cookie,default:S.default}))}})]:[],y1(N,{data:P.data,viewImportMap:q,viewModules:i3,serverQueries:G,dictionarySink:r$,key:"root"})]}),{bootstrapScriptContent:s3(`window.__GEMI_DATA__ = ${Q1(P.data)}`),bootstrapModules:oZ,signal:p1.signal,...b?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(t$){if(Bun.env.NODE_ENV!=="production")console.error(t$)}});if(R0.allReady.catch(()=>{}).finally(()=>clearTimeout(H$)),b)await R0.allReady.catch(()=>{});return new Response(c8(R0,G,{onShell:b?void 0:()=>G.markShell(),onChunk:b0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(p1.signal.aborted)),b0)this.shellReporter.report(Y,b0.measure())})},r$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(R0){if(clearTimeout(H$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(p1.signal.aborted))),R0;let t$=await d3(y1("div"),{bootstrapScriptContent:s3(`window.error= ${Q1(R0.message)}; window.stack_trace=${Q1(R0.stack)};window.__GEMI_DATA__ = ${Q1(P.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...oZ]:oZ});return new Response(c8(t$,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(p1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(M$(Z))return 404;if(Z?.kind===l1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(i1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof q1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,K=null,B=L(n),F=h3(this.flatViewRoutes,j),O=B.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(jG);if(O&&B.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,K=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&F===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let P=J.pathname.replace(/\/+$/,""),N=O&&B.supportedLocales.includes(P.slice(1));if(P&&!N)return new Response("",{status:301,headers:{Location:`${P}${J.search}`}})}if(O&&!Y&&K===null&&!(K===null&&F!==null)){let P=zG(z,B.supportedLocales,B.defaultLocale);if(P){let N=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${P}${N}${W?".json":""}${J.search}`}})}}if(O&&!Y){let P=L(n).detectLocale(new C($,{},"view",Q));if(K===null&&P!==B.defaultLocale){let N=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${P}${N}${J.search}`}})}}Q=Q.replace("//","/");let D=[],U=[],H=null,I={},M=null,x=!1,E=!1,f=[],S;try{let P=h3(this.flatViewRoutes,Q);if(K&&P?.route.middleware.includes(jG))P=null;if(P){if(H=P.routePath,I=P.params,D=P.route.exec,U=P.route.middleware,f=P.route.features,x=U.includes("no-stream"),E=U.includes(cO),S=P.route.static,W&&this.partialRendering){let N=$.headers.get($W),y=vQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:L(n).supportedLocales,from:N,origin:J.origin,to:{segments:P.route.segments,params:I,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),M={from:N,carriedViews:y.carriedViews}}}}catch(P){throw P}if(S&&W)return new Response("Not found",{status:404});let R=new C($,I,"view",H);return this.hooks.onRequestStart(R),await T.run(R,async()=>{let P=null,N=T.getStore(),y=uZ.getStore(),U$=(q)=>uZ.run(y,()=>T.runWith(N,q));N.serverQueries=new cZ(p3($));let M0=new Set;N.serverQueries.onQueryFail((q)=>{M0.add(q.error);try{U$(()=>Promise.resolve(this.hooks.onRequestFail(s,q.error)).catch(()=>{}))}catch{}});let g1=ZG(S);if(K){let q=K.replaceAll("/","");O$.setLocale(q,{cookie:g1.locale})}else if(B.isLocaleAware&&!O)N.setLocale(B.defaultLocale);else O$.setLocale(void 0,{cookie:g1.locale});let s=N.req;if(g1.session)d4();try{let q=null;try{await L(u1).runMiddleware(U)}catch(b){if(q=this.viewRefusalStatus(s,b,M0),q===null)throw b}if(q!==null||f.length>0&&!await this.passesFeatureGates(f))H=null,D=[],s.routePath="";let I0=L(n),n$=I0.isEnabled,i3=I0.isLocaleAware,L$=new C($,s.params),m1={defaultLocale:I0.defaultLocale,timeZone:I0.detectTimeZone(L$)};if(i3){let b=null;if(K)b=K.replaceAll("/",""),N.setLocale(b);else if(!O)b=N.locale??I0.defaultLocale;else b=I0.detectLocale(L$),N.setLocale(b);let b0=n$?I0.getPageTranslations(b,s.routePath):{};m1={...m1,supportedLocales:I0.supportedLocales,currentLocale:b,dictionary:{[b]:b0},defaultLocale:I0.defaultLocale,...O?{}:{localeRouting:"off"}}}await XG(m1.currentLocale??"");let h1;try{h1=await Promise.all(D.map((b)=>b(s)))}catch(b){if(q=this.viewRefusalStatus(s,b,M0),q===null)throw b;H=null,D=[],s.routePath="",h1=[]}if(H===null)await this.hooks.onNotFound(s,{status:q??404});let{cookies:o$,headers:Q0}=N;if(q!==null)Q0.set("Cache-Control","no-store");P={data:h1,cookies:o$,headers:Q0,user:N.user,prefetchedData:N.serverQueries.snapshotResolved(),currentPathName:H,params:s.params,urlLocaleSegment:G,meta:N.renderMeta(),appId:L(JW).id,features:await L(o1).forClient()};let{params:oZ,user:s3}=P,a$={},aZ={};for(let b of h1??[]){let[b0,r$]=Object.entries(b)?.[0]??[];if(!b0||!r$)continue;aZ[`${b0}:${H}`]=r$.breadcrumb,a$[b0]=r$}let p1=a$.FILE;if(p1){for(let b of o$)Q0.append("Set-Cookie",b.toString());try{await this.onRequestEnd(s)}catch(b){l$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await P8(p1,Q0)}if(W){Q0.set("Content-Type","application/x-ndjson; charset=utf-8"),Q0.append("Vary",$W),o$.forEach((b0)=>Q0.append("Set-Cookie",b0.toString())),await this.hooks.onRequestEnd(s);let b={meta:M&&!N.metadata.touched?null:P.meta,data:{[Q]:a$},breadcrumbs:aZ,prefetchedData:N.serverQueries.snapshotResolved(),i18n:m1,features:P.features,is404:!H,appId:P.appId,partial:M};return new Response(dQ(b,N.serverQueries,void 0,({aborted:b0})=>U$(()=>this.completeStream(s,N.serverQueries.summarize(b0)))),{headers:Q0})}if(Q0.set("Content-Type","text/html; charset=utf-8"),!x&&!(S&&H))Q0.append("Vary","User-Agent");let H$=Boolean(S&&H);if(!H$||g1.session)d4();for(let b of o$)Q0.append("Set-Cookie",b.toString());if(!H$||g1.csrf){let b=Bun.CSRF.generate(process.env.SECRET);Q0.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(s,{mintSession:!H$||g1.session})}catch(b){l$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(H$)JG(Q0,S);return await this.render({req:s,runInRequestScope:U$,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:Q0,i18n:m1,params:oZ,pathname:J.pathname,serverQueries:N.serverQueries,userAgent:$.headers.get("user-agent"),noStream:x,noTheme:E,url:J,user:s3,viewData:a$,breadcrumbs:aZ,urlLocaleSegment:G,meta:P.meta,appId:P.appId,features:P.features,isOgRequest:Y,staticView:H?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===l1){let I0=W?sO(q.payload.viewData??q.payload.api):DW(q.payload.view);for(let n$ of N.cookies)I0.headers.append("Set-Cookie",n$.toString());return I0}if(!M0.has(q))this.hooks.onRequestFail(s,q);if(i1(q))return console.error(q),W?dZ():DW(WW());if(q instanceof q1&&q.status===403)return W?dZ():DW(WW());throw q}},Z)}}function nO($,Z){let J=$.cookies?.get(Z);return BQ(J)?J:null}function LW(){let $=JSON.stringify({error:s1("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 BG extends T0{routes={"/api-routes":this.get(()=>{let $=L(l4).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 $=L(u3).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 oO=new Set([d1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),aO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function tO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(oO.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===d1)throw Error(`dispatchAs: credentials may not set the "${d1}" cookie. The access token stays the initiator's.`);if(!aO.test(Y)||!rO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function eO($,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 QG($){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 GG($,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})}}class l4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=QQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=qJ({"/":$.rootRouter,"/auth":EJ,"/__gemi__/services/i18n":fJ,"/__gemi__/services/logs":kJ,"/__gemi__/services/image":wJ,"/__gemi__/debug":BG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=FG(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 L(u1).runMiddleware(W)}catch(Y){if(Y.kind===l1)return QG(Y.payload.api);else{if(M$(Y))return LW();if(this.onRequestFail(Z,Y),console.error(Y),i1(Y))return dZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===l1)return QG(j.payload.api);if(M$(j))return LW();if(this.onRequestFail(J.req,j),console.error(j),i1(j))return dZ();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){l$.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:s1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=L(n);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),L(u1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let D=GG(K,z.headers,z.cookies);return await Q(),D}let B=await this.getRouteData(W),F=z.headers,O=z.cookies;if(B instanceof Response){let D=GG(B,F,O);if(this.isOpenEndedBody($,D)){let U=eO(D,()=>this.endRequest(z,j,W));return X=!0,U}return await Q(),D}let V=(c1(B)?B:Y1.json(B)).toResponse(F,O);return await Q(),V}catch(G){if(!X)try{await Q()}catch(K){console.error(K)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,K=[],B=Q?null:$.cookies.get(d1);if(B)K.push(`${d1}=${B}`);if(Y?.credentials)tO(G,K,Y.credentials,Q!==void 0);if(K.length>0)G.set("Cookie",K.join("; "));let F=Q?null:$.headers.get(d1);if(F)G.set(d1,F);let O=$.headers.get("User-Agent");if(O)G.set("User-Agent",O);let V;if(W instanceof FormData)V=W;else if(W!==void 0)G.set("Content-Type","application/json"),V=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:V,...Y?.signal?{signal:Y.signal}:{}});if(KG(D,jZ($),Q?.grant,Y?.progress),$.domain)lZ(D,$.domain);let U=Q?{user:Q.user}:void 0;return T.exit(()=>Z6.exit(()=>this.handleApiRequest(D,U)))}}import{timingSafeEqual as $U}from"crypto";var n4="",MW="*",ZU=60000,JU=1e4,PW=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,i4=16,HW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s4="x-forwarded-host";function VG($){return $.startsWith(":")}function iZ($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&$U(J,W)}function WU($){if(!$)return null;if($===!0)return{header:s4,clientIpHeader:null,secret:null};return{header:($.hostHeader??s4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function YU($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!HW.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"||!HW.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??s4).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"||!HW.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??s4).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<i4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${i4} characters. A guessable one lets any client name its own host.`)}function H1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function jU($){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 zU($){let Z=H1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>PW.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<i4)throw Error(`\`route.domains.ask.secret\` must be at least ${i4} characters. A guessable one is worse than leaving \`ask\` out.`);YU($.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),VG(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)=>PW.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 IW{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){zU($),this.root=H1($.root),this.hostTrust=WU($.trustProxy);for(let Z of $.groups??[])if(VG(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??ZU,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!iZ($.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(!iZ($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:T$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return H1(this.forwardedHost($))??H1(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&&H1(Y)?jU(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:MW,params:{},custom:!0};return null}async allows($,Z){let J=H1($);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:n4,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&&PW.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>=JU)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=H1($);if(Z)this.cache.delete(Z)}}}var XU={kind:"none"};function u_($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return XU;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 l_($,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:T$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var DG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,OG=16;function i_($){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(!DG.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!DG.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<OG)throw Error(`GEMI_PROXY_SECRET must be at least ${OG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function UG($,Z){if(!iZ($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:T$(J)}var QU="/__gemi__/domains/ask";class W1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;constructor($,Z){this.groups.set(n4,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new IW(J);let W=(Y)=>({api:Y.api?new l4({...Z.api,...Y.api}):$.api,view:Y.view?new u3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(MW,W(J.custom.fallback))}applyClientIp($){let Z=this.clientIpTrust;if(Z)TW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?UG($.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)TW($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return lZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==QU)return null;if(!iZ(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??n4)}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 o4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var LG=600000;function HG($,Z){return[G6($,Z),G6($,Z-1)]}class A{static token="auth";config;provider;constructor($={},Z=new s8){VY($.oauthProviders),this.config={...U1(DY($),$),emailCode:p8($.emailCode)},this.provider=Z}async oauthProvider($){return await FZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await AY(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=L().bound(W1)?L(W1).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"?L(W1).resolver?.root:H1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??H1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!q8($))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=o4(J.expiresAt),j=o4(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=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/LG),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=G6($,j),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of HG($,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(q8($)||!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()/LG),W=HG($,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=T.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=ZY(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){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),W=await this.config.generateCode($),Y=typeof W==="string"&&W!==""?W:QY(Z);return await this.userProvider.createMagicLinkToken({email:$,token:K6("link",$,J),pin:K6("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.userProvider.findMagicLinkTokenByEmail($);if(!j)return W3("pin",$,null,Z),{status:"invalid"};let z=o4(j.createdAt);if(z+W*60000<=Date.now())return W3("pin",$,null,Z),{status:"expired"};if(!await FY(j.id,z,Y,W))return await this.userProvider.claimMagicLinkToken(j.id),{status:"too_many_attempts"};if(!W3("pin",$,j.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(j.id))return{status:"invalid"};return{status:"ok",row:j}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=W3("link",$,J?.token,Z);if(!J||!W)return!1;if(o4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class w0 extends g{static getFacadeAccessor(){return A}static async user(){let $=await w0.userOrNull();if($)return $;throw new I$({redirectTo:J6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await t3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return z1(Z?.search.get(j1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new zZ}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 a4{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new cZ(p3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=a4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){a4.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new cZ(p3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function GU($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function NW($,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==="*"?GU(z):encodeURIComponent(String(z))}`});return`${r4}${J==="/"?"":J}`||r4}var PG=new Map;function MG($,Z){let J=PG.get($);if(!J)J=new URLPattern({pathname:`${r4}${$==="/"?"":$}`}),PG.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 IG($,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=KU(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 KU($){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 TG{static origin($){return _W($)}static absolute($,...Z){return`${m3()}${K0(String($),Z[0]??{})}`}static relative($,...Z){return K0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=L(W1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):m3();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return IG({root:W.root,origin:j},$,K0(String(Z),J[0]??{}))}static api($,...Z){return NW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${_W()}${NW(String($),Z[0]??{})}`}static matchApi($,Z){return MG(String($),Z)}}class NG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static robots($){T.getStore().metadata.robots($)}static fonts($){T.getStore().metadata.fonts($)}}var FU={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class v1 extends g{static getFacadeAccessor(){return i$}static get client(){return this.getFacadeRoot().client}static get($){return v1.client.get($)}static set($,Z){return v1.client.set($,Z)}static del(...$){return v1.client.del(...$)}static exists($){return v1.client.exists($)}static incr($){return v1.client.incr($)}static expire($,Z){return v1.client.expire($,Z)}static ttl($){return v1.client.ttl($)}}function dx($){return $}function _G(){return{store:"memory",ttl:null}}class xW{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 BU="500";class CW{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=`${VU(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",BU]),[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 $=L(),Z=$.bound(i$)?$.make(i$).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 VU($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var DU="k:",xG="tag:",OU="t:";class SW{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 AW extends SW{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=U1(_G(),$),this.config.ttl!==null&&this.config.ttl!==void 0)s$(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 SG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return DU+AG($)}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=xG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=CG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(xG+Z,CG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:s$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new xW(this.config.memory);if($==="redis"){let Z=this.options.application;return new CW({...this.config.redis,client:Z?{send:(J,W)=>Z.make(i$).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 SG extends SW{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){AG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${OU}${Z.join(",")}:${$}`}}function AG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function CG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class EG extends g{static getFacadeAccessor(){return AW}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 fG extends g{static getFacadeAccessor(){return X1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class RG extends g{static getFacadeAccessor(){return bG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class kG extends g{static getFacadeAccessor(){return wG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class qG extends g{static getFacadeAccessor(){return g3}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 LC($){return $}function yG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function t4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function EW($){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:UU}=globalThis.Bun;function LU(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var HU=async($)=>{let Z=new UU($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},PU=async($)=>{let Z;try{Z=(await import("./chunk-3nf0nmpp.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(()=>{})}},vG=($)=>LU()?HU($):PU($);var MU=/^[A-Za-z_][A-Za-z0-9_]*$/;class fW{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(!MU.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??vG}async createTable(){for(let $ of IU(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 gG(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 qO($){return`'sha256-${AO("sha256").update($).digest("base64")}'`}var jW,zW=new Map;function yO(){if(jW===void 0){let $=QW(XW(),"dist","server",bO);jW=oQ($)?JSON.parse(EO($,"utf8")):null}return jW??null}async function GW($){wO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=yO()?.[$];if(j!==void 0)return j;let z=zW.get($);if(z)return z}let J=QW(XW(),"app"),W=kO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${aQ}.ts (or .js).`);if(!Z)return nQ(W);let Y=nQ(W);return zW.set($,Y),Y.catch(()=>zW.delete($)),Y}async function BN($){return qO(await GW($))}var vO="gemi-islands",MN=`'sha256-${tQ("sha256").update(BW).digest("base64")}'`;function KW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var FW=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),IN=`'sha256-${tQ("sha256").update(YW).digest("base64")}'`,gO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',mO="gemi-static";function eQ($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((V)=>{let D=V.module?J(V.module):void 0;if(!D)return console.error(`[gemi] island ${V.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(V.load==="eager"){for(let U of D.preload)z.add(U);if(V.preloadDynamic)for(let U of D.dynamicPreload??[])z.add(U)}return{s:D.src,e:V.export,l:V.load}});let Q=X.some((V)=>V!==null),G=j?`<script type="module" ${rQ}="${FW(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return KW($,"</head>",G,!1);let B=(Y?`<meta name="${mO}" content="${FW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((V)=>`<link rel="modulepreload" href="${FW(V)}"/>`).join("")+G,F=Y?YW:BW,O=(Q?`<script type="application/json" id="${vO}">${Q1({i:X})}</script>`:"")+`<script type="module">${W?gO+F:F}</script>`;return KW(KW($,"</head>",B,!1),"</body>",O,!0)}function hO($,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 $G($){let Z=`<template ${iQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=hO($,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=`<${c3} ${lQ}="${j}" style="display:contents"></${c3}>`;$=$.split(Q).join(`<${c3} style="display:contents">${X}</${c3}>`)}return $}function ZG($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function JG($,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 pO=async()=>(await import("./chunk-yewj83ez.js")).default,VW,d3=async(...$)=>{return VW??=import("react-dom/server.browser").catch((Z)=>{throw VW=void 0,Z}),(await VW).renderToReadableStream(...$)},YG=1e4,jG="no-locale",cO="no-theme";async function dO($,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 UW="/assets";function uO($){return $===UW||$.startsWith(`${UW}/`)}function lO($){let Z=$.filter(uO);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 "${UW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function iO($){let Z=L(W1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function DW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function sO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class u3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=pQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;theme;constructor($){let Z=GQ();this.partialRendering=$.partialRendering??Z.partialRendering,this.localeRouting=$.localeRouting??Z.localeRouting,this.theme=$.theme??Z.theme,this.hooks={onNotFound:$.onNotFound??Z.onNotFound,onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":AJ};this.flatViewRoutes=g4(J),lO(Object.keys(this.flatViewRoutes)),this.routeManifest=h4(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,W])=>W.at(-1)!=="FILE")),this.componentTree=c4(J),this.flatComponentTree=ZW(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,W])=>W.static).map(([W])=>W);for(let W of this.staticRoutes){let Y=this.flatViewRoutes[W].static?.layout;if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=L(o1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)d4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{l$.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let K of J?.[G]??[])Q.add(K);return[...Q].map((G)=>y1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let K=OW(),B=new AbortController,F=setTimeout(()=>B.abort(),YG),O=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},V=uQ(async(D,U)=>{let H=await d3(D,{signal:B.signal,identifierPrefix:U,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});return await H.allReady.catch(()=>{}),await new Response(H).text()});try{let D,U=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(U)D={name:U,source:await GW(U)};let H;if(W.navigation){let x=W.navigation===!0?{}:W.navigation,E=x.version?String(await J(()=>x.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",D?.name??"",E].join("|"),prefetch:x.prefetch==="none"?"none":"intent"}}let I=await d3(y1(sQ.Provider,{value:V,children:y1(WG,{children:[...G,y1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:Q,key:"root"})]})}),{signal:B.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:O});await I.allReady.catch(()=>{});let M=$G(await new Response(I).text());return new Response(eQ(M,V,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,D),{status:200,headers:X})}finally{clearTimeout(F),J(()=>this.completeStream(Z,z.summarize(B.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:K,noStream:B,noTheme:F,url:O,user:V,viewData:D,breadcrumbs:U,urlLocaleSegment:H,meta:I,isOgRequest:M,appId:x,features:E,staticView:f}=$,S=this.theme===!1||F||f?null:{cookie:this.theme.cookie??gJ,default:this.theme.default??null,value:nO(Z,this.theme.cookie??gJ)},R=H?gQ(Q,[H]).pathname:Q,P={kind:"view",data:{meta:I,pageData:{[R]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:V},routeManifest:this.clientRouteManifest,breadcrumbs:U,router:{urlLocaleSegment:H,pathname:Y,params:X,currentPath:Q,searchParams:O.search,is404:!Y?!0:!1,domain:Z.domain?iO(Z):null},appId:x,features:E,theme:S,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},N=this.root,y=this.routeManifest[Y];return async(U$)=>{let{bootstrapModules:M0=[],loaders:g1,getStyles:s,viewImportMap:q,cssManifest:I0,ogMap:n$,viewModules:i3,clientEntry:L$,modulePreloadManifest:m1,assetBase:h1,resolveIsland:o$,buildId:Q0}=U$,oZ=L$?[]:M0,s3=(R0)=>[R0,`window.loaders=${g1}`,...L$?[`import(${JSON.stringify(L$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(M){let R0=null,t$=null;for(let e$ of y??[])if(typeof n$[e$]==="function")t$=e$,R0=n$[e$];if(!R0)return new Response("Not found",{status:404});let BK=Object.values(P.data.pageData)[0];try{await d3(y1(R0,BK[t$]),{onError:()=>{}})}catch(e$){let{fonts:VK,...DK}=e$.satoriOptions,OK=await Promise.all(VK.map((n3)=>{return dO(n3.name,n3.weight,n3.style).then((MK)=>({...n3,data:MK}))})),uW=new Headers(j);uW.set("Content-Type","image/png");let[UK,LK]=await Promise.all([pO(),y4("Rendering an OG image")]),HK=await UK(e$.jsx,{...DK,fonts:OK}),PK=await LK(Buffer.from(HK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(PK),{headers:uW})}return new Response("data")}if(f&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:f,currentViews:y,data:P.data,serverQueries:G,headers:j,getStyles:s,viewImportMap:q,viewModules:i3,resolveIsland:o$,buildId:Q0});if(P.data.cssManifest=I0,P.data.modulePreloadManifest=m1??{},h1&&h1!=="/")P.data.assetBase=h1;let a$=this.modulePreloadLinks({clientEntry:L$,modulePreloadManifest:m1,views:y??["404"],routeKey:Y??"404"}),aZ=await s(y??["404"]);P.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let p1=new AbortController,H$=setTimeout(()=>p1.abort(),YG),b=D6(K)||B,b0=Bun.env.NODE_ENV!=="production"&&!b&&Y&&this.shellReporter.shouldObserve(Y)?cQ():null,r$=OW();try{let R0=await d3(y1(WG,{children:[...a$,...aZ,...S?[y1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:VQ(Q1({cookie:S.cookie,default:S.default}))}})]:[],y1(N,{data:P.data,viewImportMap:q,viewModules:i3,serverQueries:G,dictionarySink:r$,key:"root"})]}),{bootstrapScriptContent:s3(`window.__GEMI_DATA__ = ${Q1(P.data)}`),bootstrapModules:oZ,signal:p1.signal,...b?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(t$){if(Bun.env.NODE_ENV!=="production")console.error(t$)}});if(R0.allReady.catch(()=>{}).finally(()=>clearTimeout(H$)),b)await R0.allReady.catch(()=>{});return new Response(c8(R0,G,{onShell:b?void 0:()=>G.markShell(),onChunk:b0?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(p1.signal.aborted)),b0)this.shellReporter.report(Y,b0.measure())})},r$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(R0){if(clearTimeout(H$),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(p1.signal.aborted))),R0;let t$=await d3(y1("div"),{bootstrapScriptContent:s3(`window.error= ${Q1(R0.message)}; window.stack_trace=${Q1(R0.stack)};window.__GEMI_DATA__ = ${Q1(P.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...oZ]:oZ});return new Response(c8(t$,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(p1.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(M$(Z))return 404;if(Z?.kind===l1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(i1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof q1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,K=null,B=L(n),F=h3(this.flatViewRoutes,j),O=B.isLocaleAware&&this.localeRouting==="prefix"&&!F?.route.middleware.includes(jG);if(O&&B.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,K=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&F===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let P=J.pathname.replace(/\/+$/,""),N=O&&B.supportedLocales.includes(P.slice(1));if(P&&!N)return new Response("",{status:301,headers:{Location:`${P}${J.search}`}})}if(O&&!Y&&K===null&&!(K===null&&F!==null)){let P=zG(z,B.supportedLocales,B.defaultLocale);if(P){let N=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${P}${N}${W?".json":""}${J.search}`}})}}if(O&&!Y){let P=L(n).detectLocale(new C($,{},"view",Q));if(K===null&&P!==B.defaultLocale){let N=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${P}${N}${J.search}`}})}}Q=Q.replace("//","/");let D=[],U=[],H=null,I={},M=null,x=!1,E=!1,f=[],S;try{let P=h3(this.flatViewRoutes,Q);if(K&&P?.route.middleware.includes(jG))P=null;if(P){if(H=P.routePath,I=P.params,D=P.route.exec,U=P.route.middleware,f=P.route.features,x=U.includes("no-stream"),E=U.includes(cO),S=P.route.static,W&&this.partialRendering){let N=$.headers.get($W),y=vQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:L(n).supportedLocales,from:N,origin:J.origin,to:{segments:P.route.segments,params:I,search:J.search}});if(y.startIndex>0)D=D.slice(y.startIndex),M={from:N,carriedViews:y.carriedViews}}}}catch(P){throw P}if(S&&W)return new Response("Not found",{status:404});let R=new C($,I,"view",H);return this.hooks.onRequestStart(R),await T.run(R,async()=>{let P=null,N=T.getStore(),y=uZ.getStore(),U$=(q)=>uZ.run(y,()=>T.runWith(N,q));N.serverQueries=new cZ(p3($));let M0=new Set;N.serverQueries.onQueryFail((q)=>{M0.add(q.error);try{U$(()=>Promise.resolve(this.hooks.onRequestFail(s,q.error)).catch(()=>{}))}catch{}});let g1=ZG(S);if(K){let q=K.replaceAll("/","");O$.setLocale(q,{cookie:g1.locale})}else if(B.isLocaleAware&&!O)N.setLocale(B.defaultLocale);else O$.setLocale(void 0,{cookie:g1.locale});let s=N.req;if(g1.session)d4();try{let q=null;try{await L(u1).runMiddleware(U)}catch(b){if(q=this.viewRefusalStatus(s,b,M0),q===null)throw b}if(q!==null||f.length>0&&!await this.passesFeatureGates(f))H=null,D=[],s.routePath="";let I0=L(n),n$=I0.isEnabled,i3=I0.isLocaleAware,L$=new C($,s.params),m1={defaultLocale:I0.defaultLocale,timeZone:I0.detectTimeZone(L$)};if(i3){let b=null;if(K)b=K.replaceAll("/",""),N.setLocale(b);else if(!O)b=N.locale??I0.defaultLocale;else b=I0.detectLocale(L$),N.setLocale(b);let b0=n$?I0.getPageTranslations(b,s.routePath):{};m1={...m1,supportedLocales:I0.supportedLocales,currentLocale:b,dictionary:{[b]:b0},defaultLocale:I0.defaultLocale,...O?{}:{localeRouting:"off"}}}await XG(m1.currentLocale??"");let h1;try{h1=await Promise.all(D.map((b)=>b(s)))}catch(b){if(q=this.viewRefusalStatus(s,b,M0),q===null)throw b;H=null,D=[],s.routePath="",h1=[]}if(H===null)await this.hooks.onNotFound(s,{status:q??404});let{cookies:o$,headers:Q0}=N;if(q!==null)Q0.set("Cache-Control","no-store");P={data:h1,cookies:o$,headers:Q0,user:N.user,prefetchedData:N.serverQueries.snapshotResolved(),currentPathName:H,params:s.params,urlLocaleSegment:G,meta:N.renderMeta(),appId:L(JW).id,features:await L(o1).forClient()};let{params:oZ,user:s3}=P,a$={},aZ={};for(let b of h1??[]){let[b0,r$]=Object.entries(b)?.[0]??[];if(!b0||!r$)continue;aZ[`${b0}:${H}`]=r$.breadcrumb,a$[b0]=r$}let p1=a$.FILE;if(p1){for(let b of o$)Q0.append("Set-Cookie",b.toString());try{await this.onRequestEnd(s)}catch(b){l$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await P8(p1,Q0)}if(W){Q0.set("Content-Type","application/x-ndjson; charset=utf-8"),Q0.append("Vary",$W),o$.forEach((b0)=>Q0.append("Set-Cookie",b0.toString())),await this.hooks.onRequestEnd(s);let b={meta:M&&!N.metadata.touched?null:P.meta,data:{[Q]:a$},breadcrumbs:aZ,prefetchedData:N.serverQueries.snapshotResolved(),i18n:m1,features:P.features,is404:!H,appId:P.appId,partial:M};return new Response(dQ(b,N.serverQueries,void 0,({aborted:b0})=>U$(()=>this.completeStream(s,N.serverQueries.summarize(b0)))),{headers:Q0})}if(Q0.set("Content-Type","text/html; charset=utf-8"),!x&&!(S&&H))Q0.append("Vary","User-Agent");let H$=Boolean(S&&H);if(!H$||g1.session)d4();for(let b of o$)Q0.append("Set-Cookie",b.toString());if(!H$||g1.csrf){let b=Bun.CSRF.generate(process.env.SECRET);Q0.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(s,{mintSession:!H$||g1.session})}catch(b){l$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(H$)JG(Q0,S);return await this.render({req:s,runInRequestScope:U$,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:Q0,i18n:m1,params:oZ,pathname:J.pathname,serverQueries:N.serverQueries,userAgent:$.headers.get("user-agent"),noStream:x,noTheme:E,url:J,user:s3,viewData:a$,breadcrumbs:aZ,urlLocaleSegment:G,meta:P.meta,appId:P.appId,features:P.features,isOgRequest:Y,staticView:H?S:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===l1){let I0=W?sO(q.payload.viewData??q.payload.api):DW(q.payload.view);for(let n$ of N.cookies)I0.headers.append("Set-Cookie",n$.toString());return I0}if(!M0.has(q))this.hooks.onRequestFail(s,q);if(i1(q))return console.error(q),W?dZ():DW(WW());if(q instanceof q1&&q.status===403)return W?dZ():DW(WW());throw q}},Z)}}function nO($,Z){let J=$.cookies?.get(Z);return BQ(J)?J:null}function LW(){let $=JSON.stringify({error:s1("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 BG extends T0{routes={"/api-routes":this.get(()=>{let $=L(l4).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 $=L(u3).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 oO=new Set([d1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),aO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function tO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(oO.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===d1)throw Error(`dispatchAs: credentials may not set the "${d1}" cookie. The access token stays the initiator's.`);if(!aO.test(Y)||!rO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function eO($,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 QG($){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 GG($,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})}}class l4{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=QQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=qJ({"/":$.rootRouter,"/auth":EJ,"/__gemi__/services/i18n":fJ,"/__gemi__/services/logs":kJ,"/__gemi__/services/image":wJ,"/__gemi__/debug":BG})}getRouteHandlerAndParams($){let Z=new URL($.url),J=FG(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 L(u1).runMiddleware(W)}catch(Y){if(Y.kind===l1)return QG(Y.payload.api);else{if(M$(Y))return LW();if(this.onRequestFail(Z,Y),console.error(Y),i1(Y))return dZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===l1)return QG(j.payload.api);if(M$(j))return LW();if(this.onRequestFail(J.req,j),console.error(j),i1(j))return dZ();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){l$.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:s1("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=L(n);if(G.isEnabled){let D=G.detectLocale(j);z.setLocale(D)}z.setRequest(j),L(u1).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(W,j);if(K instanceof Response){let D=GG(K,z.headers,z.cookies);return await Q(),D}let B=await this.getRouteData(W),F=z.headers,O=z.cookies;if(B instanceof Response){let D=GG(B,F,O);if(this.isOpenEndedBody($,D)){let U=eO(D,()=>this.endRequest(z,j,W));return X=!0,U}return await Q(),D}let V=(c1(B)?B:Y1.json(B)).toResponse(F,O);return await Q(),V}catch(G){if(!X)try{await Q()}catch(K){console.error(K)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,K=[],B=Q?null:$.cookies.get(d1);if(B)K.push(`${d1}=${B}`);if(Y?.credentials)tO(G,K,Y.credentials,Q!==void 0);if(K.length>0)G.set("Cookie",K.join("; "));let F=Q?null:$.headers.get(d1);if(F)G.set(d1,F);let O=$.headers.get("User-Agent");if(O)G.set("User-Agent",O);let V;if(W instanceof FormData)V=W;else if(W!==void 0)G.set("Content-Type","application/json"),V=JSON.stringify(W);let D=new Request(z,{method:Z,headers:G,body:V,...Y?.signal?{signal:Y.signal}:{}});if(KG(D,jZ($),Q?.grant,Y?.progress),$.domain)lZ(D,$.domain);let U=Q?{user:Q.user}:void 0;return T.exit(()=>Z6.exit(()=>this.handleApiRequest(D,U)))}}import{timingSafeEqual as $U}from"crypto";var n4="",MW="*",ZU=60000,JU=1e4,PW=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,i4=16,HW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s4="x-forwarded-host";function VG($){return $.startsWith(":")}function iZ($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&$U(J,W)}function WU($){if(!$)return null;if($===!0)return{header:s4,clientIpHeader:null,secret:null};return{header:($.hostHeader??s4).toLowerCase(),clientIpHeader:$.clientIpHeader?.toLowerCase()??null,secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function YU($){if(!$||$===!0)return;let{hostHeader:Z,clientIpHeader:J,secret:W}=$;if(Z!==void 0&&(typeof Z!=="string"||!HW.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"||!HW.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??s4).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"||!HW.test(W.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${W.header}".`);if(W.header.toLowerCase()===(Z??s4).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<i4)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${i4} characters. A guessable one lets any client name its own host.`)}function H1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function jU($){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 zU($){let Z=H1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>PW.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<i4)throw Error(`\`route.domains.ask.secret\` must be at least ${i4} characters. A guessable one is worse than leaving \`ask\` out.`);YU($.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),VG(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)=>PW.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 IW{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){zU($),this.root=H1($.root),this.hostTrust=WU($.trustProxy);for(let Z of $.groups??[])if(VG(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??ZU,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!iZ($.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(!iZ($.headers.get(Z.secret.header),Z.secret.value))return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:T$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return H1(this.forwardedHost($))??H1(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&&H1(Y)?jU(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:MW,params:{},custom:!0};return null}async allows($,Z){let J=H1($);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:n4,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&&PW.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>=JU)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=H1($);if(Z)this.cache.delete(Z)}}}var XU={kind:"none"};function u_($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return XU;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 l_($,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:T$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var DG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,OG=16;function i_($){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(!DG.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!DG.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<OG)throw Error(`GEMI_PROXY_SECRET must be at least ${OG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function UG($,Z){if(!iZ($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:T$(J)}var QU="/__gemi__/domains/ask";class W1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;constructor($,Z){this.groups.set(n4,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new IW(J);let W=(Y)=>({api:Y.api?new l4({...Z.api,...Y.api}):$.api,view:Y.view?new u3({...Z.view,...Y.view}):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(MW,W(J.custom.fallback))}applyClientIp($){let Z=this.clientIpTrust;if(Z)TW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?UG($.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)TW($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return lZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==QU)return null;if(!iZ(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??n4)}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 o4($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var LG=600000;function HG($,Z){return[G6($,Z),G6($,Z-1)]}class A{static token="auth";config;provider;constructor($={},Z=new s8){VY($.oauthProviders),this.config={...U1(DY($),$),emailCode:p8($.emailCode)},this.provider=Z}async oauthProvider($){return await FZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await AY(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=L().bound(W1)?L(W1).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"?L(W1).resolver?.root:H1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??H1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!q8($))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=o4(J.expiresAt),j=o4(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=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/LG),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=G6($,j),K=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:K,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of HG($,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(q8($)||!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()/LG),W=HG($,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=T.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=ZY(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){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),W=await this.config.generateCode($),Y=typeof W==="string"&&W!==""?W:QY(Z);return await this.userProvider.createMagicLinkToken({email:$,token:K6("link",$,J),pin:K6("pin",$,Y)}),{email:$,pin:Y,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.userProvider.findMagicLinkTokenByEmail($);if(!j)return W3("pin",$,null,Z),{status:"invalid"};let z=o4(j.createdAt);if(z+W*60000<=Date.now())return W3("pin",$,null,Z),{status:"expired"};if(!await FY(j.id,z,Y,W))return await this.userProvider.claimMagicLinkToken(j.id),{status:"too_many_attempts"};if(!W3("pin",$,j.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(j.id))return{status:"invalid"};return{status:"ok",row:j}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),W=W3("link",$,J?.token,Z);if(!J||!W)return!1;if(o4(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class w0 extends g{static getFacadeAccessor(){return A}static async user(){let $=await w0.userOrNull();if($)return $;throw new I$({redirectTo:J6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await t3(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return z1(Z?.search.get(j1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await w0.user();if(!await $(Z))throw new zZ}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 a4{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new cZ(p3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=a4.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){a4.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new cZ(p3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function GU($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function NW($,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==="*"?GU(z):encodeURIComponent(String(z))}`});return`${r4}${J==="/"?"":J}`||r4}var PG=new Map;function MG($,Z){let J=PG.get($);if(!J)J=new URLPattern({pathname:`${r4}${$==="/"?"":$}`}),PG.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 IG($,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=KU(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 KU($){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 TG{static origin($){return _W($)}static absolute($,...Z){return`${m3()}${K0(String($),Z[0]??{})}`}static relative($,...Z){return K0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=L(W1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):m3();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return IG({root:W.root,origin:j},$,K0(String(Z),J[0]??{}))}static api($,...Z){return NW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${_W()}${NW(String($),Z[0]??{})}`}static matchApi($,Z){return MG(String($),Z)}}class NG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static robots($){T.getStore().metadata.robots($)}static fonts($){T.getStore().metadata.fonts($)}}var FU={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class v1 extends g{static getFacadeAccessor(){return i$}static get client(){return this.getFacadeRoot().client}static get($){return v1.client.get($)}static set($,Z){return v1.client.set($,Z)}static del(...$){return v1.client.del(...$)}static exists($){return v1.client.exists($)}static incr($){return v1.client.incr($)}static expire($,Z){return v1.client.expire($,Z)}static ttl($){return v1.client.ttl($)}}function dx($){return $}function _G(){return{store:"memory",ttl:null}}class xW{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 BU="500";class CW{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=`${VU(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",BU]),[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 $=L(),Z=$.bound(i$)?$.make(i$).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 VU($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var DU="k:",xG="tag:",OU="t:";class SW{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 AW extends SW{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=U1(_G(),$),this.config.ttl!==null&&this.config.ttl!==void 0)s$(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 SG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return DU+AG($)}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=xG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=CG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(xG+Z,CG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:s$(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new xW(this.config.memory);if($==="redis"){let Z=this.options.application;return new CW({...this.config.redis,client:Z?{send:(J,W)=>Z.make(i$).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 SG extends SW{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){AG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${OU}${Z.join(",")}:${$}`}}function AG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function CG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class EG extends g{static getFacadeAccessor(){return AW}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 fG extends g{static getFacadeAccessor(){return X1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class RG extends g{static getFacadeAccessor(){return bG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class kG extends g{static getFacadeAccessor(){return wG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class qG extends g{static getFacadeAccessor(){return g3}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 LC($){return $}function yG(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function t4($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function EW($){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:UU}=globalThis.Bun;function LU(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var HU=async($)=>{let Z=new UU($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},PU=async($)=>{let Z;try{Z=(await import("./chunk-38kjpa6q.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(()=>{})}},vG=($)=>LU()?HU($):PU($);var MU=/^[A-Za-z_][A-Za-z0-9_]*$/;class fW{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(!MU.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??vG}async createTable(){for(let $ of IU(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 gG(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 eG=191,$K=30000;class W8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class Y8 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 dW{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=U1(aG(),$),this.store=EU(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(sZ);return this.ownFeed??=new sZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){WK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;WK("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:s$($.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 AU(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:JK(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 W8($);if(M1(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 Y8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,P1,{status:"failed",error:Q instanceof Y8?JK(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()+s$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new W8($);let z=null;for(;;){if(M1(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 ZK(z,Math.min(Q,X??1/0,$K),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 W8($);if(yield W,M1(W.status))return;for await(let Y of J){let j=SU(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,M1(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=s$($);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||M1(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(M1(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,ZK(j,Math.min(z??1/0,$K))]);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 ZK($,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 SU($,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 JK($){if(typeof $==="string")return{message:$};if($ instanceof Y8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function WK($,Z){if(typeof Z!=="string"||Z===""||Z.length>eG)throw TypeError(`A run's ${$} is a string of 1 to ${eG} characters; got ${JSON.stringify(Z)}.`)}function AU($){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 EU($,Z){if($==="memory")return new gW;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(_1).connection();return new cW(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 YK extends g{static getFacadeAccessor(){return dW}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 jK extends g{static getFacadeAccessor(){return o1}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 j8{bound;constructor($){this.bound=$}get name(){return this.bound??N1()}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 QK(J.sql,(W)=>zK(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-4y74s15p.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=KK($,GK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=i0();if($===void 0)return;return N1()===this.name?$:void 0}connection($=this.name){return XK($),L(_1).connection($)}}var nZ=new j8;class FK extends g{static getFacadeAccessor(){return _1}static connection($){return new j8($)}static get sql(){return nZ.sql}static get dialect(){return nZ.dialect}static query($){return nZ.query($)}static execute($){return nZ.execute($)}static transaction($){return nZ.transaction($)}static schema(){return nZ.schema()}static close(){return this.getFacadeRoot().close()}}export{Y1 as ae,TK as be,l0 as ce,rZ as de,G8 as ee,ZZ as fe,eZ as ge,T0 as he,t3 as ie,k8 as je,q8 as ke,ZY as le,n1 as me,X1 as ne,T$ as oe,r as pe,w9 as qe,jZ as re,JY as se,WY as te,v8 as ue,g8 as ve,K6 as we,W3 as xe,kF as ye,nP as ze,DY as Ae,IY as Be,d8 as Ce,TY as De,NY as Ee,cF as Fe,_Y as Ge,u8 as He,lF as Ie,iF as Je,l8 as Ke,xY as Le,CY as Me,o1 as Ne,SY as Oe,aF as Pe,s8 as Qe,I8 as Re,W6 as Se,I1 as Te,P8 as Ue,T1 as Ve,O$ as We,a4 as Xe,TG as Ye,NG as Ze,FU as _e,v1 as $e,dx as af,_G as bf,xW as cf,CW as df,AW as ef,SG as ff,EG as gf,fG as hf,RG as if,kG as jf,qG as kf,LC as lf,yG as mf,t4 as nf,EW as of,fW as pf,bW as qf,e4 as rf,sZ as sf,sG as tf,nG as uf,p as vf,$3 as wf,A4 as xf,RM as yf,wM as zf,kM as Af,gM as Bf,wX as Cf,PJ as Df,yX as Ef,dM as Ff,mX as Gf,h0 as Hf,q3 as If,hX as Jf,oG as Kf,aC as Lf,vW as Mf,P1 as Nf,M1 as Of,gW as Pf,cW as Qf,CU as Rf,W8 as Sf,Y8 as Tf,dW as Uf,YK as Vf,jK as Wf,j8 as Xf,FK as Yf,IJ as Zf,sD as _f,bJ as $f,RJ as ag,eI as bg,jQ as cg,zQ as dg,e3 as eg,u1 as fg,GT as gg,QQ as hg,GQ as ig,JW as jg,dZ as kg,WW as lg,BN as mg,MN as ng,IN as og,UW as pg,uO as qg,DW as rg,sO as sg,u3 as tg,LW as ug,QG as vg,GG as wg,l4 as xg,u_ as yg,l_ as zg,i_ as Ag,W1 as Bg,A as Cg,w0 as Dg,$6 as Eg,O9 as Fg,yK as Gg,B9 as Hg,L9 as Ig,O8 as Jg,U8 as Kg,L8 as Lg,H9 as Mg,pK as Ng,cK as Og,_9 as Pg,C9 as Qg,A9 as Rg,q9 as Sg,y9 as Tg,v9 as Ug,x8 as Vg,nK as Wg,J0 as Xg,n9 as Yg,QZ as Zg,e9 as _g};
|
|
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 eG=191,$K=30000;class W8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class Y8 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 dW{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=U1(aG(),$),this.store=EU(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(sZ);return this.ownFeed??=new sZ,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){WK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;WK("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:s$($.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 AU(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:JK(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 W8($);if(M1(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 Y8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,P1,{status:"failed",error:Q instanceof Y8?JK(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()+s$(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new W8($);let z=null;for(;;){if(M1(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 ZK(z,Math.min(Q,X??1/0,$K),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 W8($);if(yield W,M1(W.status))return;for await(let Y of J){let j=SU(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,M1(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=s$($);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||M1(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(M1(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,ZK(j,Math.min(z??1/0,$K))]);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 ZK($,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 SU($,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 JK($){if(typeof $==="string")return{message:$};if($ instanceof Y8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function WK($,Z){if(typeof Z!=="string"||Z===""||Z.length>eG)throw TypeError(`A run's ${$} is a string of 1 to ${eG} characters; got ${JSON.stringify(Z)}.`)}function AU($){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 EU($,Z){if($==="memory")return new gW;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(_1).connection();return new cW(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 YK extends g{static getFacadeAccessor(){return dW}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 jK extends g{static getFacadeAccessor(){return o1}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 j8{bound;constructor($){this.bound=$}get name(){return this.bound??N1()}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 QK(J.sql,(W)=>zK(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-0vc2akg0.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=KK($,GK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=i0();if($===void 0)return;return N1()===this.name?$:void 0}connection($=this.name){return XK($),L(_1).connection($)}}var nZ=new j8;class FK extends g{static getFacadeAccessor(){return _1}static connection($){return new j8($)}static get sql(){return nZ.sql}static get dialect(){return nZ.dialect}static query($){return nZ.query($)}static execute($){return nZ.execute($)}static transaction($){return nZ.transaction($)}static schema(){return nZ.schema()}static close(){return this.getFacadeRoot().close()}}export{Y1 as ce,TK as de,l0 as ee,rZ as fe,G8 as ge,ZZ as he,eZ as ie,T0 as je,t3 as ke,k8 as le,q8 as me,ZY as ne,n1 as oe,X1 as pe,T$ as qe,r as re,w9 as se,jZ as te,JY as ue,WY as ve,v8 as we,g8 as xe,K6 as ye,W3 as ze,kF as Ae,nP as Be,DY as Ce,IY as De,d8 as Ee,TY as Fe,NY as Ge,cF as He,_Y as Ie,u8 as Je,lF as Ke,iF as Le,l8 as Me,xY as Ne,CY as Oe,o1 as Pe,SY as Qe,aF as Re,s8 as Se,I8 as Te,W6 as Ue,I1 as Ve,P8 as We,T1 as Xe,O$ as Ye,a4 as Ze,TG as _e,NG as $e,FU as af,v1 as bf,dx as cf,_G as df,xW as ef,CW as ff,AW as gf,SG as hf,EG as if,fG as jf,RG as kf,kG as lf,qG as mf,LC as nf,yG as of,t4 as pf,EW as qf,fW as rf,bW as sf,e4 as tf,sZ as uf,sG as vf,nG as wf,p as xf,$3 as yf,A4 as zf,RM as Af,wM as Bf,kM as Cf,gM as Df,wX as Ef,PJ as Ff,yX as Gf,dM as Hf,mX as If,h0 as Jf,q3 as Kf,hX as Lf,oG as Mf,aC as Nf,vW as Of,P1 as Pf,M1 as Qf,gW as Rf,cW as Sf,CU as Tf,W8 as Uf,Y8 as Vf,dW as Wf,YK as Xf,jK as Yf,j8 as Zf,FK as _f,IJ as $f,sD as ag,bJ as bg,RJ as cg,eI as dg,jQ as eg,zQ as fg,e3 as gg,u1 as hg,GT as ig,QQ as jg,GQ as kg,JW as lg,dZ as mg,WW as ng,BN as og,MN as pg,IN as qg,UW as rg,uO as sg,DW as tg,sO as ug,u3 as vg,LW as wg,QG as xg,GG as yg,l4 as zg,u_ as Ag,l_ as Bg,i_ as Cg,W1 as Dg,A as Eg,w0 as Fg,$6 as Gg,O9 as Hg,yK as Ig,B9 as Jg,L9 as Kg,O8 as Lg,U8 as Mg,L8 as Ng,H9 as Og,pK as Pg,cK as Qg,_9 as Rg,C9 as Sg,A9 as Tg,q9 as Ug,y9 as Vg,v9 as Wg,x8 as Xg,nK as Yg,J0 as Zg,n9 as _g,QZ as $g,e9 as ah};
|
|
116
116
|
|
|
117
|
-
//# debugId=
|
|
117
|
+
//# debugId=A7458EF9A4E5CA2264756E2164756E21
|