gemi 0.203.0 → 0.204.1
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 +20 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +5 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +52 -55
- package/dist/ai/index.js.map +3 -13
- package/dist/ai/providers/request.d.ts +1 -0
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/testing/Fingerprints.d.ts +106 -0
- package/dist/ai/testing/Fingerprints.d.ts.map +1 -0
- package/dist/ai/testing/RecordingProvider.d.ts +258 -0
- package/dist/ai/testing/RecordingProvider.d.ts.map +1 -0
- package/dist/ai/testing/index.d.ts +4 -0
- package/dist/ai/testing/index.d.ts.map +1 -0
- package/dist/ai/testing/index.js +6 -0
- package/dist/ai/testing/index.js.map +12 -0
- package/dist/ai/testing/pinClock.d.ts +19 -0
- package/dist/ai/testing/pinClock.d.ts.map +1 -0
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/{chunk-dj9nspcw.js → chunk-0hfzzb3k.js} +3 -3
- package/dist/{chunk-dj9nspcw.js.map → chunk-0hfzzb3k.js.map} +1 -1
- package/dist/chunk-0pgk811s.js +4 -0
- package/dist/{chunk-3e19n0f2.js.map → chunk-0pgk811s.js.map} +2 -2
- package/dist/{chunk-2fbsd1b0.js → chunk-0shq2d31.js} +2 -2
- package/dist/{chunk-2fbsd1b0.js.map → chunk-0shq2d31.js.map} +1 -1
- package/dist/{chunk-wfwpjx25.js → chunk-0t1d9s34.js} +3 -3
- package/dist/{chunk-wfwpjx25.js.map → chunk-0t1d9s34.js.map} +1 -1
- package/dist/{chunk-gz2ekvd6.js → chunk-13vtn7h9.js} +2 -2
- package/dist/{chunk-gz2ekvd6.js.map → chunk-13vtn7h9.js.map} +2 -2
- package/dist/{chunk-hergje99.js → chunk-1e82gfk9.js} +3 -3
- package/dist/{chunk-hergje99.js.map → chunk-1e82gfk9.js.map} +1 -1
- package/dist/{chunk-95re1b2y.js → chunk-1kehwa3s.js} +1 -1
- package/dist/chunk-1x60thpm.js +8 -0
- package/dist/chunk-1x60thpm.js.map +19 -0
- package/dist/{chunk-px2a83jv.js → chunk-2ngdhbz7.js} +2 -2
- package/dist/{chunk-px2a83jv.js.map → chunk-2ngdhbz7.js.map} +1 -1
- package/dist/{chunk-5dhp90cx.js → chunk-2t1eyzvq.js} +2 -2
- package/dist/{chunk-5dhp90cx.js.map → chunk-2t1eyzvq.js.map} +1 -1
- package/dist/{chunk-ggmznkqs.js → chunk-39hed4yr.js} +3 -3
- package/dist/{chunk-ggmznkqs.js.map → chunk-39hed4yr.js.map} +1 -1
- package/dist/{chunk-tgbj942e.js → chunk-3gkxnfef.js} +3 -3
- package/dist/{chunk-tgbj942e.js.map → chunk-3gkxnfef.js.map} +1 -1
- package/dist/{chunk-k3m1wr1c.js → chunk-3xzhbkya.js} +3 -3
- package/dist/{chunk-k3m1wr1c.js.map → chunk-3xzhbkya.js.map} +1 -1
- package/dist/chunk-418n4s1m.js +6 -0
- package/dist/{chunk-z97tptd1.js.map → chunk-418n4s1m.js.map} +2 -2
- package/dist/{chunk-95cs3r49.js → chunk-4c0rb2ng.js} +2 -2
- package/dist/{chunk-95cs3r49.js.map → chunk-4c0rb2ng.js.map} +1 -1
- package/dist/chunk-4ex4s616.js +4 -0
- package/dist/{chunk-tkskgvhc.js.map → chunk-4ex4s616.js.map} +2 -2
- package/dist/{chunk-n5g9a48h.js → chunk-4m8t67px.js} +2 -2
- package/dist/{chunk-n5g9a48h.js.map → chunk-4m8t67px.js.map} +1 -1
- package/dist/{chunk-1hpedme7.js → chunk-4v5c4mes.js} +2 -2
- package/dist/{chunk-1hpedme7.js.map → chunk-4v5c4mes.js.map} +1 -1
- package/dist/{chunk-g5j5hx6a.js → chunk-5gvc03cv.js} +3 -3
- package/dist/{chunk-g5j5hx6a.js.map → chunk-5gvc03cv.js.map} +1 -1
- package/dist/{chunk-r842yxd9.js → chunk-5km0np8s.js} +2 -2
- package/dist/{chunk-r842yxd9.js.map → chunk-5km0np8s.js.map} +1 -1
- package/dist/{chunk-m3xvm2va.js → chunk-6bfj0mbp.js} +3 -3
- package/dist/{chunk-m3xvm2va.js.map → chunk-6bfj0mbp.js.map} +1 -1
- package/dist/chunk-6g1xac70.js +7 -0
- package/dist/chunk-6g1xac70.js.map +10 -0
- package/dist/{chunk-kmpxda7j.js → chunk-6w6q9mxe.js} +3 -3
- package/dist/{chunk-kmpxda7j.js.map → chunk-6w6q9mxe.js.map} +2 -2
- package/dist/{chunk-dyb649h3.js → chunk-77x9vxht.js} +3 -3
- package/dist/{chunk-dyb649h3.js.map → chunk-77x9vxht.js.map} +1 -1
- package/dist/{chunk-5q2tt76t.js → chunk-7gxmf9rg.js} +2 -2
- package/dist/{chunk-5q2tt76t.js.map → chunk-7gxmf9rg.js.map} +1 -1
- package/dist/{chunk-vyp7d7xz.js → chunk-8jfnn7v6.js} +2 -2
- package/dist/{chunk-vyp7d7xz.js.map → chunk-8jfnn7v6.js.map} +1 -1
- package/dist/{chunk-zvhks9s7.js → chunk-8pw4zjnx.js} +1 -1
- package/dist/{chunk-9q5xhb64.js → chunk-9bjggtdt.js} +2 -2
- package/dist/{chunk-9q5xhb64.js.map → chunk-9bjggtdt.js.map} +1 -1
- package/dist/{chunk-rwe4bgt3.js → chunk-9hqnecjt.js} +2 -2
- package/dist/{chunk-rwe4bgt3.js.map → chunk-9hqnecjt.js.map} +1 -1
- package/dist/{chunk-s0z61m9j.js → chunk-9m7c4mws.js} +2 -2
- package/dist/{chunk-s0z61m9j.js.map → chunk-9m7c4mws.js.map} +1 -1
- package/dist/{chunk-r02em4jv.js → chunk-b1mdan5a.js} +2 -2
- package/dist/{chunk-r02em4jv.js.map → chunk-b1mdan5a.js.map} +1 -1
- package/dist/{chunk-7txst143.js → chunk-bq4pgzcd.js} +2 -2
- package/dist/{chunk-7txst143.js.map → chunk-bq4pgzcd.js.map} +1 -1
- package/dist/chunk-c7nbzryd.js +9 -0
- package/dist/chunk-c7nbzryd.js.map +10 -0
- package/dist/{chunk-pp34d463.js → chunk-cdgnwzwf.js} +2 -2
- package/dist/{chunk-pp34d463.js.map → chunk-cdgnwzwf.js.map} +1 -1
- package/dist/chunk-cf7xc02m.js +5 -0
- package/dist/{chunk-9mhr0kwd.js.map → chunk-cf7xc02m.js.map} +1 -1
- package/dist/{chunk-2nw8rf5y.js → chunk-cq7hk8v9.js} +2 -2
- package/dist/{chunk-2nw8rf5y.js.map → chunk-cq7hk8v9.js.map} +1 -1
- package/dist/{chunk-8m9kgynj.js → chunk-crqbzfd5.js} +2 -2
- package/dist/{chunk-8m9kgynj.js.map → chunk-crqbzfd5.js.map} +1 -1
- package/dist/{chunk-vee6v6qf.js → chunk-d3k38gk1.js} +3 -3
- package/dist/{chunk-vee6v6qf.js.map → chunk-d3k38gk1.js.map} +1 -1
- package/dist/{chunk-41fqkygr.js → chunk-d5d3a8bm.js} +3 -3
- package/dist/{chunk-41fqkygr.js.map → chunk-d5d3a8bm.js.map} +1 -1
- package/dist/chunk-d7kknkmq.js +13 -0
- package/dist/{chunk-4fw84bh6.js.map → chunk-d7kknkmq.js.map} +3 -4
- package/dist/{chunk-ke7d7j2y.js → chunk-dk1xxtgk.js} +2 -2
- package/dist/{chunk-ke7d7j2y.js.map → chunk-dk1xxtgk.js.map} +1 -1
- package/dist/{chunk-nqg7hdy8.js → chunk-e3ehv27z.js} +3 -3
- package/dist/{chunk-nqg7hdy8.js.map → chunk-e3ehv27z.js.map} +1 -1
- package/dist/{chunk-se58ty45.js → chunk-e5mqjren.js} +4 -4
- package/dist/{chunk-se58ty45.js.map → chunk-e5mqjren.js.map} +2 -2
- package/dist/{chunk-t91x2k88.js → chunk-efnerp0c.js} +2 -2
- package/dist/{chunk-t91x2k88.js.map → chunk-efnerp0c.js.map} +1 -1
- package/dist/{chunk-ys4q1jg2.js → chunk-ek0dvbck.js} +3 -3
- package/dist/{chunk-ys4q1jg2.js.map → chunk-ek0dvbck.js.map} +1 -1
- package/dist/{chunk-a4twd6qh.js → chunk-ezvtkbp9.js} +2 -2
- package/dist/{chunk-a4twd6qh.js.map → chunk-ezvtkbp9.js.map} +1 -1
- package/dist/{chunk-h19qtrg9.js → chunk-f52maa9b.js} +2 -2
- package/dist/{chunk-h19qtrg9.js.map → chunk-f52maa9b.js.map} +1 -1
- package/dist/{chunk-nfbf388w.js → chunk-f9c8bnzx.js} +3 -3
- package/dist/{chunk-nfbf388w.js.map → chunk-f9c8bnzx.js.map} +2 -2
- package/dist/{chunk-bwg7genv.js → chunk-fq5b1k4n.js} +2 -2
- package/dist/{chunk-bwg7genv.js.map → chunk-fq5b1k4n.js.map} +1 -1
- package/dist/{chunk-dvw8cr6n.js → chunk-gc9g7c4p.js} +3 -3
- package/dist/{chunk-dvw8cr6n.js.map → chunk-gc9g7c4p.js.map} +1 -1
- package/dist/{chunk-sq5ytcpd.js → chunk-jeq8wvj6.js} +2 -2
- package/dist/{chunk-sq5ytcpd.js.map → chunk-jeq8wvj6.js.map} +1 -1
- package/dist/{chunk-vw57atx4.js → chunk-jma5d7zd.js} +3 -3
- package/dist/{chunk-vw57atx4.js.map → chunk-jma5d7zd.js.map} +1 -1
- package/dist/{chunk-nsxw6v2b.js → chunk-jmsfkzav.js} +2 -2
- package/dist/{chunk-nsxw6v2b.js.map → chunk-jmsfkzav.js.map} +1 -1
- package/dist/chunk-js9rm7g0.js +4 -0
- package/dist/{chunk-02s440vh.js.map → chunk-js9rm7g0.js.map} +2 -2
- package/dist/{chunk-6t9n4qdm.js → chunk-k1gt7fgy.js} +3 -3
- package/dist/{chunk-6t9n4qdm.js.map → chunk-k1gt7fgy.js.map} +1 -1
- package/dist/{chunk-cbmne0wt.js → chunk-k62338g2.js} +2 -2
- package/dist/{chunk-cbmne0wt.js.map → chunk-k62338g2.js.map} +1 -1
- package/dist/{chunk-05k9201j.js → chunk-k9882kqg.js} +2 -2
- package/dist/{chunk-05k9201j.js.map → chunk-k9882kqg.js.map} +1 -1
- package/dist/chunk-ks6dczvn.js +24 -0
- package/dist/{chunk-70qqpvd9.js.map → chunk-ks6dczvn.js.map} +2 -2
- package/dist/{chunk-bzaespn5.js → chunk-n26atakz.js} +3 -3
- package/dist/{chunk-bzaespn5.js.map → chunk-n26atakz.js.map} +1 -1
- package/dist/{chunk-vbdy4k14.js → chunk-n3kg99yw.js} +3 -3
- package/dist/{chunk-vbdy4k14.js.map → chunk-n3kg99yw.js.map} +1 -1
- package/dist/{chunk-c6v3sjvh.js → chunk-n5k42dh7.js} +3 -3
- package/dist/{chunk-c6v3sjvh.js.map → chunk-n5k42dh7.js.map} +1 -1
- package/dist/chunk-p2nqksdq.js +10 -0
- package/dist/{chunk-ht5mq6ev.js.map → chunk-p2nqksdq.js.map} +2 -2
- package/dist/{chunk-mvd4mc8p.js → chunk-p9pwskv6.js} +2 -2
- package/dist/{chunk-mvd4mc8p.js.map → chunk-p9pwskv6.js.map} +1 -1
- package/dist/{chunk-14dtbk7d.js → chunk-phvvxv1a.js} +3 -3
- package/dist/{chunk-14dtbk7d.js.map → chunk-phvvxv1a.js.map} +1 -1
- package/dist/chunk-pq15dt8j.js +46 -0
- package/dist/chunk-pq15dt8j.js.map +27 -0
- package/dist/{chunk-q05648ac.js → chunk-ptpzh61m.js} +3 -3
- package/dist/{chunk-q05648ac.js.map → chunk-ptpzh61m.js.map} +1 -1
- package/dist/{chunk-nkasdjx2.js → chunk-qcrj4t72.js} +3 -3
- package/dist/{chunk-nkasdjx2.js.map → chunk-qcrj4t72.js.map} +1 -1
- package/dist/{chunk-bfhcx1ca.js → chunk-re9ac4tc.js} +27 -27
- package/dist/{chunk-bfhcx1ca.js.map → chunk-re9ac4tc.js.map} +7 -6
- package/dist/{chunk-q093ph67.js → chunk-rr8bzm6k.js} +2 -2
- package/dist/{chunk-q093ph67.js.map → chunk-rr8bzm6k.js.map} +1 -1
- package/dist/{chunk-gm34n6da.js → chunk-s5hdrpam.js} +3 -3
- package/dist/{chunk-gm34n6da.js.map → chunk-s5hdrpam.js.map} +1 -1
- package/dist/{chunk-k0220nam.js → chunk-s6bq91cm.js} +2 -2
- package/dist/{chunk-k0220nam.js.map → chunk-s6bq91cm.js.map} +1 -1
- package/dist/{chunk-vt0vybw8.js → chunk-vsd5h2d9.js} +3 -3
- package/dist/{chunk-vt0vybw8.js.map → chunk-vsd5h2d9.js.map} +1 -1
- package/dist/{chunk-a1cwr0wh.js → chunk-w3mc696j.js} +2 -2
- package/dist/{chunk-a1cwr0wh.js.map → chunk-w3mc696j.js.map} +1 -1
- package/dist/{chunk-811qpkzd.js → chunk-wn4j741t.js} +2 -2
- package/dist/{chunk-811qpkzd.js.map → chunk-wn4j741t.js.map} +1 -1
- package/dist/{chunk-xmy09pr9.js → chunk-wxyxnbh6.js} +4 -4
- package/dist/{chunk-xmy09pr9.js.map → chunk-wxyxnbh6.js.map} +1 -1
- package/dist/{chunk-tp37k8c0.js → chunk-x244kqcc.js} +2 -2
- package/dist/{chunk-tp37k8c0.js.map → chunk-x244kqcc.js.map} +1 -1
- package/dist/chunk-x26jb60f.js +4 -0
- package/dist/{chunk-z7wchajg.js.map → chunk-x26jb60f.js.map} +2 -2
- package/dist/{chunk-4ehzm7p1.js → chunk-xvk6aqd7.js} +3 -3
- package/dist/{chunk-4ehzm7p1.js.map → chunk-xvk6aqd7.js.map} +1 -1
- package/dist/chunk-xwqdh388.js +5 -0
- package/dist/chunk-xwqdh388.js.map +13 -0
- package/dist/{chunk-56b6m0d4.js → chunk-y45whafz.js} +2 -2
- package/dist/{chunk-56b6m0d4.js.map → chunk-y45whafz.js.map} +1 -1
- package/dist/{chunk-q8a7ncvs.js → chunk-y5kfqq4f.js} +2 -2
- package/dist/{chunk-q8a7ncvs.js.map → chunk-y5kfqq4f.js.map} +1 -1
- package/dist/chunk-ybcdxrqx.js +4 -0
- package/dist/{chunk-wqphnrej.js.map → chunk-ybcdxrqx.js.map} +2 -2
- package/dist/{chunk-7nmbzdys.js → chunk-yrbvfda9.js} +1 -1
- package/dist/{chunk-wc3q88a2.js → chunk-yykrvrpt.js} +1 -1
- package/dist/{chunk-fxvqtwte.js → chunk-zk1vwwv6.js} +2 -2
- package/dist/{chunk-fxvqtwte.js.map → chunk-zk1vwwv6.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-BnNSz8AK.js → RealtimeClient-CLXePUcE.js} +2 -2
- package/dist/chunks/{RealtimeClient-BnNSz8AK.js.map → RealtimeClient-CLXePUcE.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-CoQ-vnvy.js → ThemeProvider-COjYIalw.js} +74 -1273
- package/dist/chunks/ThemeProvider-COjYIalw.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-Bhp0oJ0T.js → fetchFileRequest-BaufNZpI.js} +2 -2
- package/dist/chunks/{fetchFileRequest-Bhp0oJ0T.js.map → fetchFileRequest-BaufNZpI.js.map} +1 -1
- package/dist/chunks/{live-Dt8sq9W4.js → live-Dz_rk7fm.js} +4 -15
- package/dist/chunks/{live-Dt8sq9W4.js.map → live-Dz_rk7fm.js.map} +1 -1
- package/dist/chunks/{mutationExtras-ChOGPZlY.js → mutationExtras-DtSw6BcX.js} +2 -2
- package/dist/chunks/{mutationExtras-ChOGPZlY.js.map → mutationExtras-DtSw6BcX.js.map} +1 -1
- package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/chunks/{subscriptionStream-DDl_H-QM.js → subscriptionStream-CqhJOfPn.js} +2 -2
- package/dist/chunks/{subscriptionStream-DDl_H-QM.js.map → subscriptionStream-CqhJOfPn.js.map} +1 -1
- package/dist/chunks/urlpattern-polyfill-Cc7YrzJf.js +913 -0
- package/dist/chunks/urlpattern-polyfill-Cc7YrzJf.js.map +1 -0
- package/dist/client/ClientRouter.d.ts +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/ClientRouterContext.d.ts +1 -1
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/browserHistory.d.ts +13 -0
- package/dist/client/browserHistory.d.ts.map +1 -0
- package/dist/client/index.js +9 -6
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts.map +1 -1
- package/dist/client/scrollRestoration.d.ts +1 -1
- package/dist/client/scrollRestoration.d.ts.map +1 -1
- package/dist/client/urlPattern.d.ts +30 -0
- package/dist/client/urlPattern.d.ts.map +1 -0
- 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/DB.d.ts +10 -0
- package/dist/facades/DB.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/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 +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +2 -2
- package/dist/orm/Model.d.ts.map +1 -1
- package/dist/orm/context.d.ts +54 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.d.ts +1 -1
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +4 -4
- package/dist/orm/index.js.map +3 -3
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +1 -0
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +234 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +1 -1
- package/package.json +2 -1
- package/dist/chunk-02s440vh.js +0 -4
- package/dist/chunk-3e19n0f2.js +0 -4
- package/dist/chunk-4fw84bh6.js +0 -15
- package/dist/chunk-70qqpvd9.js +0 -24
- package/dist/chunk-9mhr0kwd.js +0 -5
- package/dist/chunk-ht5mq6ev.js +0 -10
- package/dist/chunk-rczmh97n.js +0 -9
- package/dist/chunk-rczmh97n.js.map +0 -10
- package/dist/chunk-tkskgvhc.js +0 -4
- package/dist/chunk-v325k8qj.js +0 -46
- package/dist/chunk-v325k8qj.js.map +0 -31
- package/dist/chunk-wqphnrej.js +0 -4
- package/dist/chunk-z7wchajg.js +0 -4
- package/dist/chunk-z97tptd1.js +0 -6
- package/dist/chunks/ThemeProvider-CoQ-vnvy.js.map +0 -1
- /package/dist/{chunk-95re1b2y.js.map → chunk-1kehwa3s.js.map} +0 -0
- /package/dist/{chunk-zvhks9s7.js.map → chunk-8pw4zjnx.js.map} +0 -0
- /package/dist/{chunk-7nmbzdys.js.map → chunk-yrbvfda9.js.map} +0 -0
- /package/dist/{chunk-wc3q88a2.js.map → chunk-yykrvrpt.js.map} +0 -0
package/dist/chunk-3e19n0f2.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{h as Tr}from"./chunk-2nw8rf5y.js";import{A as Dr,B as ur,C as Hr,i as je,k as C,l as wr,m as fr,n as jr,p as It,q as Tt,r as qr,s as mr,t as We,u as zr,v as kr,w as Qe,x as Pr,y as Nr,z as br}from"./chunk-nfbf388w.js";import{D as Ir}from"./chunk-a1cwr0wh.js";import{E as lt,F as pr,H as vr,L as Te,P as q}from"./chunk-kmpxda7j.js";import{Q as gr}from"./chunk-2fbsd1b0.js";import{R as ar}from"./chunk-nkasdjx2.js";import"./chunk-tgbj942e.js";import"./chunk-41fqkygr.js";import"./chunk-vee6v6qf.js";import"./chunk-q05648ac.js";import{ba as ir}from"./chunk-dyb649h3.js";import{ma as Or}from"./chunk-m3xvm2va.js";import{bm as us,cm as u}from"./chunk-05k9201j.js";var G=u((Y)=>{Object.defineProperty(Y,"__esModule",{value:!0});Y.resolveHttpAuthSchemeConfig=Y.defaultSSOHttpAuthSchemeProvider=Y.defaultSSOHttpAuthSchemeParametersProvider=void 0;var _t=C(),U=lt(),Et=async(e,t,r)=>{return{operation:(0,U.getSmithyContext)(t).operation,region:await(0,U.normalizeProvider)(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};Y.defaultSSOHttpAuthSchemeParametersProvider=Et;function Rt(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"awsssoportal",region:e.region},propertiesExtractor:(t,r)=>({signingProperties:{config:t,context:r}})}}function yt(e){return{schemeId:"smithy.api#noAuth"}}var St=(e)=>{let t=[];switch(e.operation){case"GetRoleCredentials":{t.push(yt(e));break}default:t.push(Rt(e))}return t};Y.defaultSSOHttpAuthSchemeProvider=St;var xt=(e)=>{let t=(0,_t.resolveAwsSdkSigV4Config)(e);return Object.assign(t,{authSchemePreference:(0,U.normalizeProvider)(e.authSchemePreference??[])})};Y.resolveHttpAuthSchemeConfig=xt});var Ee=u((le)=>{Object.defineProperty(le,"__esModule",{value:!0});le.ruleSet=void 0;var ae="required",n="fn",i="argv",y="ref",X=!0,Z="isSet",S="booleanEquals",E="error",R="endpoint",c="tree",A="PartitionResult",g="getAttr",ee={[ae]:!1,type:"string"},te={[ae]:!0,default:!1,type:"boolean"},re={[y]:"Endpoint"},ue={[n]:S,[i]:[{[y]:"UseFIPS"},!0]},ce={[n]:S,[i]:[{[y]:"UseDualStack"},!0]},o={},se={[n]:g,[i]:[{[y]:A},"supportsFIPS"]},de={[y]:A},oe={[n]:S,[i]:[!0,{[n]:g,[i]:[de,"supportsDualStack"]}]},ne=[ue],ie=[ce],pe=[{[y]:"Region"}],qt={version:"1.0",parameters:{Region:ee,UseDualStack:te,UseFIPS:te,Endpoint:ee},rules:[{conditions:[{[n]:Z,[i]:[re]}],rules:[{conditions:ne,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:E},{conditions:ie,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:E},{endpoint:{url:re,properties:o,headers:o},type:R}],type:c},{conditions:[{[n]:Z,[i]:pe}],rules:[{conditions:[{[n]:"aws.partition",[i]:pe,assign:A}],rules:[{conditions:[ue,ce],rules:[{conditions:[{[n]:S,[i]:[X,se]},oe],rules:[{endpoint:{url:"https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:o,headers:o},type:R}],type:c},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:E}],type:c},{conditions:ne,rules:[{conditions:[{[n]:S,[i]:[se,X]}],rules:[{conditions:[{[n]:"stringEquals",[i]:[{[n]:g,[i]:[de,"name"]},"aws-us-gov"]}],endpoint:{url:"https://portal.sso.{Region}.amazonaws.com",properties:o,headers:o},type:R},{endpoint:{url:"https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",properties:o,headers:o},type:R}],type:c},{error:"FIPS is enabled but this partition does not support FIPS",type:E}],type:c},{conditions:ie,rules:[{conditions:[oe],rules:[{endpoint:{url:"https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:o,headers:o},type:R}],type:c},{error:"DualStack is enabled but this partition does not support DualStack",type:E}],type:c},{endpoint:{url:"https://portal.sso.{Region}.{PartitionResult#dnsSuffix}",properties:o,headers:o},type:R}],type:c}],type:c},{error:"Invalid Configuration: Missing Region",type:E}]};le.ruleSet=qt});var Se=u((Re)=>{Object.defineProperty(Re,"__esModule",{value:!0});Re.defaultEndpointResolver=void 0;var Pt=Tt(),w=It(),Nt=Ee(),bt=new w.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Dt=(e,t={})=>{return bt.get(e,()=>(0,w.resolveEndpoint)(Nt.ruleSet,{endpointParams:e,logger:t.logger}))};Re.defaultEndpointResolver=Dt;w.customEndpointFunctions.aws=Pt.awsEndpointFunctions});var I=u((j)=>{Object.defineProperty(j,"__esModule",{value:!0});j.SSOServiceException=j.__ServiceException=void 0;var xe=q();Object.defineProperty(j,"__ServiceException",{enumerable:!0,get:function(){return xe.ServiceException}});class f extends xe.ServiceException{constructor(e){super(e);Object.setPrototypeOf(this,f.prototype)}}j.SSOServiceException=f});var K=u((Oe)=>{Object.defineProperty(Oe,"__esModule",{value:!0});Oe.UnauthorizedException=Oe.TooManyRequestsException=Oe.ResourceNotFoundException=Oe.InvalidRequestException=void 0;var T=I();class m extends T.SSOServiceException{name="InvalidRequestException";$fault="client";constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,m.prototype)}}Oe.InvalidRequestException=m;class z extends T.SSOServiceException{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e});Object.setPrototypeOf(this,z.prototype)}}Oe.ResourceNotFoundException=z;class k extends T.SSOServiceException{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e});Object.setPrototypeOf(this,k.prototype)}}Oe.TooManyRequestsException=k;class H extends T.SSOServiceException{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e});Object.setPrototypeOf(this,H.prototype)}}Oe.UnauthorizedException=H});var L=u((De)=>{Object.defineProperty(De,"__esModule",{value:!0});De.GetRoleCredentials$=De.RoleCredentials$=De.GetRoleCredentialsResponse$=De.GetRoleCredentialsRequest$=De.errorTypeRegistries=De.UnauthorizedException$=De.TooManyRequestsException$=De.ResourceNotFoundException$=De.InvalidRequestException$=De.SSOServiceException$=void 0;var Mt="AccessTokenType",Ut="GetRoleCredentials",Ct="GetRoleCredentialsRequest",Gt="GetRoleCredentialsResponse",At="InvalidRequestException",gt="RoleCredentials",wt="ResourceNotFoundException",ft="SecretAccessKeyType",jt="SessionTokenType",mt="TooManyRequestsException",zt="UnauthorizedException",kt="accountId",Ht="accessKeyId",Kt="accessToken",Lt="account_id",P="client",N="error",Vt="expiration",Bt="http",b="httpError",Wt="httpHeader",Ie="httpQuery",D="message",Qt="roleCredentials",Yt="roleName",Jt="role_name",Pe="smithy.ts.sdk.synthetic.com.amazonaws.sso",Xt="secretAccessKey",Zt="sessionToken",er="x-amz-sso_bearer_token",p="com.amazonaws.sso",Ne=Te(),$=K(),tr=I(),be=Ne.TypeRegistry.for(Pe);De.SSOServiceException$=[-3,Pe,"SSOServiceException",0,[],[]];be.registerError(De.SSOServiceException$,tr.SSOServiceException);var x=Ne.TypeRegistry.for(p);De.InvalidRequestException$=[-3,p,At,{[N]:P,[b]:400},[D],[0]];x.registerError(De.InvalidRequestException$,$.InvalidRequestException);De.ResourceNotFoundException$=[-3,p,wt,{[N]:P,[b]:404},[D],[0]];x.registerError(De.ResourceNotFoundException$,$.ResourceNotFoundException);De.TooManyRequestsException$=[-3,p,mt,{[N]:P,[b]:429},[D],[0]];x.registerError(De.TooManyRequestsException$,$.TooManyRequestsException);De.UnauthorizedException$=[-3,p,zt,{[N]:P,[b]:401},[D],[0]];x.registerError(De.UnauthorizedException$,$.UnauthorizedException);De.errorTypeRegistries=[be,x];var rr=[0,p,Mt,8,0],sr=[0,p,ft,8,0],or=[0,p,jt,8,0];De.GetRoleCredentialsRequest$=[3,p,Ct,0,[Yt,kt,Kt],[[0,{[Ie]:Jt}],[0,{[Ie]:Lt}],[()=>rr,{[Wt]:er}]],3];De.GetRoleCredentialsResponse$=[3,p,Gt,0,[Qt],[[()=>De.RoleCredentials$,0]]];De.RoleCredentials$=[3,p,gt,0,[Ht,Xt,Zt,Vt],[0,[()=>sr,0],[()=>or,0],1]];De.GetRoleCredentials$=[9,p,Ut,{[Bt]:["GET","/federation/credentials",200]},()=>De.GetRoleCredentialsRequest$,()=>De.GetRoleCredentialsResponse$]});var ke=u((me)=>{Object.defineProperty(me,"__esModule",{value:!0});me.getRuntimeConfig=void 0;var cr=C(),dr=ur(),lr=je(),_r=q(),Er=ar(),we=pr(),fe=ir(),Rr=G(),yr=Se(),Sr=L(),xr=(e)=>{return{apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??we.fromBase64,base64Encoder:e?.base64Encoder??we.toBase64,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??yr.defaultEndpointResolver,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??Rr.defaultSSOHttpAuthSchemeProvider,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new cr.AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new lr.NoAuthSigner}],logger:e?.logger??new _r.NoOpLogger,protocol:e?.protocol??dr.AwsRestJsonProtocol,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.sso",errorTypeRegistries:Sr.errorTypeRegistries,version:"2019-06-10",serviceTarget:"SWBPortalService"},serviceId:e?.serviceId??"SSO",urlParser:e?.urlParser??Er.parseUrl,utf8Decoder:e?.utf8Decoder??fe.fromUtf8,utf8Encoder:e?.utf8Encoder??fe.toUtf8}};me.getRuntimeConfig=xr});var Xe=u((Ye)=>{Object.defineProperty(Ye,"__esModule",{value:!0});Ye.getRuntimeConfig=void 0;var $r=Or(),Fr=$r.__importDefault(Tr()),He=C(),Ke=Pr(),F=We(),hr=Nr(),Le=Qe(),l=Ir(),Ve=vr(),Be=q(),Mr=br(),Ur=Dr(),Cr=qr(),Gr=ke(),Ar=(e)=>{(0,Be.emitWarningIfUnsupportedVersion)(process.version);let t=(0,Ur.resolveDefaultsModeConfig)(e),r=()=>t().then(Be.loadConfigsForDefaultMode),a=(0,Gr.getRuntimeConfig)(e);(0,He.emitWarningIfUnsupportedVersion)(process.version);let s={profile:e?.profile,logger:a.logger};return{...a,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??(0,l.loadConfig)(He.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:e?.bodyLengthChecker??Mr.calculateBodyLength,defaultUserAgentProvider:e?.defaultUserAgentProvider??(0,Ke.createDefaultUserAgentProvider)({serviceId:a.serviceId,clientVersion:Fr.default.version}),maxAttempts:e?.maxAttempts??(0,l.loadConfig)(Le.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,e),region:e?.region??(0,l.loadConfig)(F.NODE_REGION_CONFIG_OPTIONS,{...F.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:Ve.NodeHttpHandler.create(e?.requestHandler??r),retryMode:e?.retryMode??(0,l.loadConfig)({...Le.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await r()).retryMode||Cr.DEFAULT_RETRY_MODE},e),sha256:e?.sha256??hr.Hash.bind(null,"sha256"),streamCollector:e?.streamCollector??Ve.streamCollector,useDualstackEndpoint:e?.useDualstackEndpoint??(0,l.loadConfig)(F.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:e?.useFipsEndpoint??(0,l.loadConfig)(F.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:e?.userAgentAppId??(0,l.loadConfig)(Ke.NODE_APP_ID_CONFIG_OPTIONS,s)}};Ye.getRuntimeConfig=Ar});var it=u((d)=>{var Ze=wr(),Kr=fr(),Lr=jr(),et=mr(),Vr=We(),V=je(),Br=Te(),Wr=zr(),nt=kr(),tt=Qe(),_=q(),rt=G(),Qr=Xe(),st=Hr(),ot=gr(),v=L(),h=K(),Yr=I(),Jr=(e)=>{return Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"awsssoportal"})},Xr={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Zr=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:r,credentials:a}=e;return{setHttpAuthScheme(s){let O=t.findIndex((M)=>M.schemeId===s.schemeId);if(O===-1)t.push(s);else t.splice(O,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){r=s},httpAuthSchemeProvider(){return r},setCredentials(s){a=s},credentials(){return a}}},es=(e)=>{return{httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}},ts=(e,t)=>{let r=Object.assign(st.getAwsRegionExtensionConfiguration(e),_.getDefaultExtensionConfiguration(e),ot.getHttpHandlerExtensionConfiguration(e),Zr(e));return t.forEach((a)=>a.configure(r)),Object.assign(e,st.resolveAwsRegionExtensionConfiguration(r),_.resolveDefaultRuntimeConfig(r),ot.resolveHttpHandlerRuntimeConfig(r),es(r))};class B extends _.Client{config;constructor(...[e]){let t=Qr.getRuntimeConfig(e||{});super(t);this.initConfig=t;let r=Jr(t),a=et.resolveUserAgentConfig(r),s=tt.resolveRetryConfig(a),O=Vr.resolveRegionConfig(s),M=Ze.resolveHostHeaderConfig(O),at=nt.resolveEndpointConfig(M),ut=rt.resolveHttpAuthSchemeConfig(at),ct=ts(ut,e?.extensions||[]);this.config=ct,this.middlewareStack.use(Br.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(et.getUserAgentPlugin(this.config)),this.middlewareStack.use(tt.getRetryPlugin(this.config)),this.middlewareStack.use(Wr.getContentLengthPlugin(this.config)),this.middlewareStack.use(Ze.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Kr.getLoggerPlugin(this.config)),this.middlewareStack.use(Lr.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(V.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:rt.defaultSSOHttpAuthSchemeParametersProvider,identityProviderConfigProvider:async(dt)=>new V.DefaultIdentityProviderConfig({"aws.auth#sigv4":dt.credentials})})),this.middlewareStack.use(V.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class W extends _.Command.classBuilder().ep(Xr).m(function(e,t,r,a){return[nt.getEndpointPlugin(r,e.getEndpointParameterInstructions())]}).s("SWBPortalService","GetRoleCredentials",{}).n("SSOClient","GetRoleCredentialsCommand").sc(v.GetRoleCredentials$).build(){}var rs={GetRoleCredentialsCommand:W};class Q extends B{}_.createAggregatedClient(rs,Q);d.$Command=_.Command;d.__Client=_.Client;d.SSOServiceException=Yr.SSOServiceException;d.GetRoleCredentialsCommand=W;d.SSO=Q;d.SSOClient=B;Object.prototype.hasOwnProperty.call(v,"__proto__")&&!Object.prototype.hasOwnProperty.call(d,"__proto__")&&Object.defineProperty(d,"__proto__",{enumerable:!0,value:v.__proto__});Object.keys(v).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(d,e))d[e]=v[e]});Object.prototype.hasOwnProperty.call(h,"__proto__")&&!Object.prototype.hasOwnProperty.call(d,"__proto__")&&Object.defineProperty(d,"__proto__",{enumerable:!0,value:h.__proto__});Object.keys(h).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(d,e))d[e]=h[e]})});var pt=us(it(),1);var export_SSOClient=pt.SSOClient;var export_GetRoleCredentialsCommand=pt.GetRoleCredentialsCommand;export{export_SSOClient as SSOClient,export_GetRoleCredentialsCommand as GetRoleCredentialsCommand};
|
|
3
|
-
|
|
4
|
-
//# debugId=BA3E2ABDDB37DDC264756E2164756E21
|
package/dist/chunk-4fw84bh6.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{nj as F,oj as I1,pj as A1}from"./chunk-q8a7ncvs.js";import{uj as c1,xj as k}from"./chunk-a4twd6qh.js";import{yl as S0}from"./chunk-n5g9a48h.js";import{Cl as O1}from"./chunk-vbdy4k14.js";import{Zl as W1}from"./chunk-1hpedme7.js";import{fm as UZ}from"./chunk-05k9201j.js";class G0{static kind="controller";constructor(){}}class QQ extends G0{}function q1(Q){let Z=new Map;if(!Q)return Z;for(let $ of Q.split(";")){let X=$.indexOf("=");if(X===-1)continue;let G=$.slice(0,X).trim();if(!G)continue;Z.set(G,$.slice(X+1).trim())}return Z}function xZ(Q){return q1(Q.headers.get("cookie"))}function u(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function Y0(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let X=Z.slice(6).split(",").map((z)=>z.trim()).filter((z)=>z!=="");if(X.length!==1)return null;let G=X[0],Y=G.indexOf("-");if(Y===-1)return null;let K=G.slice(0,Y),H=G.slice(Y+1);if(K===""){let z=u(H);if(z===null)return null;return{kind:"suffix",suffixLength:z}}let J=u(K);if(J===null)return null;if(H==="")return{kind:"offset",start:J,end:null};let W=u(H);if(W===null||W<J)return null;return{kind:"offset",start:J,end:W}}function K0(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let $,X;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;$=Math.max(0,Z-Q.suffixLength),X=Z-1}else{if(Q.start>=Z)return null;if($=Q.start,X=Q.end===null?Z-1:Math.min(Q.end,Z-1),X<$)return null}return{start:$,end:X,length:X-$+1}}function gZ(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function bZ(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let $=u(Z[1]),X=u(Z[2]),G=u(Z[3]);if($===null||X===null||G===null||X<$)return null;return{start:$,end:X,total:G}}function yZ(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function J0(Q){return`bytes */${Q}`}import{randomBytes as ZQ}from"crypto";var x1=new WeakMap;function k1(Q){let Z=x1.get(Q);if(!Z)Z=ZQ(16).toString("base64"),x1.set(Q,Z);return Z}function mZ(Q){return x1.get(Q)}function pZ(){let Q=k.getStore()?.req?.rawRequest;if(!Q)throw Error("cspNonce() is only available while a request is being handled.");return k1(Q)}class e extends F{errors={};constructor(Q){super("Validation error");this.name="ValidationError",this.errors=Q,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:Q,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function W0(Q){let[Z,$]=Q.match(/\d+|\D+/g)??[];if(!Z||!$)return 0;let X=Number.parseInt(Z);switch($){case"B":return X;case"KB":return X*1024;case"MB":return X*1024*1024;case"GB":return X*1024*1024*1024;case"TB":return X*1024*1024*1024*1024;default:return 0}}function $Q(Q){switch(Q){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return Q}}function H0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function g1(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var XQ=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class g extends Error{name="InvalidValidationRuleError"}function B1(Q,Z){let $=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN($))throw new g(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return $}function V0(Q){let Z=!1,$=0;for(let X of Object.values(Q)){if(!X||typeof X!=="object")continue;for(let G of Object.keys(X)){let Y=G.indexOf(":"),K=Y===-1?G:G.slice(0,Y);if(K!=="file"&&K!=="fileType"&&K!=="fileSize")continue;if(Z=!0,K==="fileSize")$+=W0(G.slice(Y+1))}}return Z?$:null}function z0(Q){let Z=Q.indexOf(":"),$=Z===-1?Q:Q.slice(0,Z),X=Z===-1?void 0:Q.slice(Z+1);switch($){case"required":return(G)=>{if(G instanceof Blob)return G.size>0;if(G===null||G===void 0)return!1;if(typeof G==="string"||Array.isArray(G))return G.length>0;return!0};case"string":return(G)=>typeof G==="string";case"boolean":return(G)=>typeof G==="boolean";case"number":return(G)=>g1(G);case"password":return(G)=>{return typeof G==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(G)};case"min":{let G=B1($,X);return(Y)=>{let K=H0(Y);return K!==void 0&&K>=G}}case"max":{let G=B1($,X);return(Y)=>{let K=H0(Y);return K!==void 0&&K<=G}}case"gte":{let G=B1($,X);return(Y)=>g1(Y)&&Y>=G}case"lte":{let G=B1($,X);return(Y)=>g1(Y)&&Y<=G}case"email":return(G)=>{return typeof G==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)};case"file":return(G)=>{return G instanceof Blob};case"fileType":{if(!X)throw new g('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let G=$Q(X);return(Y)=>Y instanceof Blob&&Y.type.startsWith(G)}case"fileSize":{let G=W0(X??"");if(G===0&&!/^0+(B|KB|MB|GB|TB)$/.test(X??""))throw new g(`Validation rule "fileSize:${X??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(Y)=>Y instanceof Blob&&Y.size<=G}case"array":return(G)=>Array.isArray(G);case"object":return(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G)&&!(G instanceof Blob);case"in":{let G=(X??"").split(",").filter((Y)=>Y!=="");if(G.length===0)throw new g('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(Y)=>typeof Y==="string"&&G.includes(Y)}default:throw new g(`Unknown validation rule "${Q}". Known rules: ${XQ.join(", ")}`)}}class y1 extends F{limit;constructor(Q){super("The request body is too large.",{status:413});this.limit=Q}}var P0={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function iZ(Q){if(typeof Q==="number"){if(Number.isFinite(Q)&&Q>=0)return Math.floor(Q);if(Q===1/0)return 1/0}else{let Z=Q.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let $=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if($&&($[2]===""||($[2]in P0)))return Math.floor(Number($[1])*(P0[$[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify(Q)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var l=new WeakMap;function oZ(Q){return l.has(Q)}function sZ(Q){return l.get(Q)?.limit??null}function tZ(Q){let Z=l.get(Q);return Z?Z.read>Z.limit:!1}function GQ(Q){let Z=Q.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function f1(Q,Z){let $=GQ(Q);if($!==null&&$>Z)throw new y1(Z)}function aZ(Q,Z,$={}){let X=$.uploadLimit??null,G=l.get(Q);if(G)G.limit=Z,G.uploadLimit=X;else{let Y={limit:Z,uploadLimit:X,read:0,stream:void 0,used:!1};l.set(Q,Y),KQ(Q,Y)}if($.checkDeclared!==!1)f1(Q,Z)}function M0(Q,Z){let $=l.get(Q);if(!$||$.uploadLimit===null||$.used||$.read>0)return;$.limit=Math.max($.limit,$.uploadLimit,Z+$.limit),$.uploadLimit=null}function YQ(Q){return Reflect.get(Object.getPrototypeOf(Q),"body",Q)??null}function b1(Q,Z){if(Z.stream!==void 0)return Z.stream;let $=YQ(Q);if(!$)return Z.stream=null;let X;return Z.stream=new ReadableStream({async pull(G){X??=$.getReader();let{done:Y,value:K}=await X.read();if(Y){G.close();return}if(Z.read+=K.byteLength,Z.read>Z.limit){let H=new y1(Z.limit);G.error(H),X.cancel(H).catch(()=>{});return}G.enqueue(K)},cancel(G){return X?X.cancel(G):$.cancel(G)}},{highWaterMark:0}),Z.stream}async function d(Q,Z){if(f1(Q,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let $=b1(Q,Z);if(!$)return new Uint8Array(0);let X=$.getReader(),G=[],Y=0;for(;;){let{done:J,value:W}=await X.read();if(J)break;G.push(W),Y+=W.byteLength}let K=new Uint8Array(Y),H=0;for(let J of G)K.set(J,H),H+=J.byteLength;return K}function U0(Q){return Q.headers.get("Content-Type")??""}function KQ(Q,Z){let $=(X,G)=>Object.defineProperty(Q,X,{configurable:!0,...G});$("body",{get:()=>b1(Q,Z)}),$("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf(Q),"bodyUsed",Q)}),$("bytes",{value:()=>d(Q,Z)}),$("arrayBuffer",{value:async()=>{let X=await d(Q,Z);return X.buffer.slice(X.byteOffset,X.byteOffset+X.byteLength)}}),$("text",{value:async()=>new TextDecoder().decode(await d(Q,Z))}),$("json",{value:async()=>JSON.parse(new TextDecoder().decode(await d(Q,Z)))}),$("blob",{value:async()=>new Blob([await d(Q,Z)],{type:U0(Q)})}),$("formData",{value:async()=>new Response(await d(Q,Z),{headers:{"Content-Type":U0(Q)}}).formData()}),$("clone",{value:()=>{f1(Q,Z.limit);let X=b1(Q,Z),G=null;if(X){let[Y,K]=X.tee();Z.stream=Y,G=K}return new Request(Q.url,{method:Q.method,headers:Q.headers,body:G,signal:Q.signal,duplex:"half"})}})}function n(Q){if(!Q.definition)throw Error(`gemi/ai: the recursive schema "${Q.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return Q.definition}var L1=new WeakMap;function m1(Q){return typeof Q==="object"&&Q!==null&&L1.has(Q)}function j1(Q){let Z=L1.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function JQ(Q){let Z={defs:{},cells:new Map},$=Q;if(Q.node.kind==="ref"){let G=n(Q.node.cell);$={...G,...Q.description?{description:Q.description}:{},optional:Q.optional,nullable:Q.nullable||G.nullable}}let X=Z1($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function Z1(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=VQ(WQ(Q.node,Z),$),G=[Q.description,HQ(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function HQ(Q){let Z=[];if(Q.kind==="string"||Q.kind==="enum"){let $=Q.checks;if($?.format)Z.push(`Format: ${$.format.name}.`);if($?.minLength!==void 0)Z.push(`At least ${$.minLength} characters.`);if($?.maxLength!==void 0)Z.push(`At most ${$.maxLength} characters.`)}else if(Q.kind==="number"){let $=Q.checks;if($?.minimum!==void 0)Z.push(`Minimum ${$.minimum}.`);if($?.exclusiveMinimum!==void 0)Z.push(`Greater than ${$.exclusiveMinimum}.`);if($?.maximum!==void 0)Z.push(`Maximum ${$.maximum}.`);if($?.exclusiveMaximum!==void 0)Z.push(`Less than ${$.exclusiveMaximum}.`)}else if(Q.kind==="array"){let $=Q.checks;if($?.minItems!==void 0)Z.push(`At least ${$.minItems} items.`);if($?.maxItems!==void 0)Z.push(`At most ${$.maxItems} items.`)}return Z.join(" ")}function WQ(Q,Z){switch(Q.kind){case"string":return{type:"string"};case"number":return{type:Q.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof Q.value,const:Q.value};case"enum":return{type:"string",enum:Q.values};case"array":return{type:"array",items:Z1(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,Z1(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>Z1($,Z))};case"json":return{};case"ref":{let{cell:$}=Q,X=Z.cells.get($.name);if(X&&X!==$)throw Error(`gemi/ai: two different recursive schemas are named "${$.name}" in one schema; give each s.recursive(...) its own name`);if(!X)Z.cells.set($.name,$),Z.defs[$.name]={},Z.defs[$.name]=Z1(n($),Z);return{$ref:`#/$defs/${$.name}`}}}}function VQ(Q,Z){if(!Z)return Q;if(Q.anyOf)return{...Q,anyOf:[...Q.anyOf,{type:"null"}]};if(Q.enum||Q.const!==void 0)return{anyOf:[Q,{type:"null"}]};if(typeof Q.type==="string")return{...Q,type:[Q.type,"null"]};return{anyOf:[Q,{type:"null"}]}}function zQ(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function PQ(Q,Z){if(typeof Z==="number"&&!Number.isFinite(Z))return String(Z);if(Q.kind==="literal"||Q.kind==="enum"){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return JSON.stringify(Z)}return zQ(Z)}function j0(Q){let Z=Q.node,$=(()=>{switch(Z.kind){case"number":return Z.checks?.integer?"integer":"number";case"string":case"boolean":return Z.kind;case"literal":return JSON.stringify(Z.value);case"enum":return`one of ${Z.values.map((X)=>JSON.stringify(X)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return j0({...n(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function UQ(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function MQ(Q){let Z=UQ(Q);return Z?`${Z}: `:""}function v1(Q){return`${MQ(Q.path)}${Q.message}`}function R1(Q,Z){if(Z===null||Z===void 0)return Q.optional||Q.nullable?1:0;let $=Q.node;switch($.kind){case"string":return typeof Z==="string"?1:0;case"number":return typeof Z==="number"?1:0;case"boolean":return typeof Z==="boolean"?1:0;case"literal":return Z===$.value?10:0;case"enum":return typeof Z==="string"&&$.values.includes(Z)?10:0;case"array":return Array.isArray(Z)?1:0;case"object":{if(typeof Z!=="object"||Array.isArray(Z))return 0;let X=Z,G=1;for(let[Y,K]of Object.entries($.shape))G+=R1(K,X[Y]);return G}case"union":return $.members.reduce((X,G)=>Math.max(X,R1(G,Z)),0);case"json":return 1;case"ref":return R0($.cell,Z,()=>1,()=>R1(n($.cell),Z))}}function R0(Q,Z,$,X){if(typeof Z!=="object"||Z===null)return X();if(Q.active.has(Z))return $();Q.active.add(Z);try{return X()}finally{Q.active.delete(Z)}}function h(Q,Z,$,X){if(Q.optional&&(Z===null||Z===void 0))return{drop:!0,value:void 0};if(Q.nullable&&Z===null)return{drop:!1,value:null};return{drop:!1,value:BQ(Q,Z,$,X)}}function BQ(Q,Z,$,X){let G=Q.node,Y=()=>{let K=Z===void 0?"required":G.kind==="literal"?"const":G.kind==="enum"&&typeof Z==="string"?"enum":"type",H=K==="const"?{allowedValue:G.value}:K==="enum"?{allowedValues:G.values}:{};X.push({path:$,code:K,message:`expected ${j0(Q)}, got ${PQ(G,Z)}`,params:H});return};switch(G.kind){case"string":if(typeof Z!=="string")return Y();return B0(G.checks,Z,$,X),Z;case"number":if(typeof Z!=="number"||!Number.isFinite(Z))return Y();if(G.checks?.integer&&!Number.isInteger(Z))return Y();return jQ(G.checks,Z,$,X),Z;case"boolean":return typeof Z==="boolean"?Z:Y();case"literal":return Z===G.value?Z:Y();case"enum":if(typeof Z!=="string"||!G.values.includes(Z))return Y();return B0(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return Y();let K=Z.map((W,z)=>{let P=h(G.item,W,[...$,z],X);return P.drop?void 0:P.value}),{minItems:H,maxItems:J}=G.checks??{};if(H!==void 0&&Z.length<H)X.push({path:$,code:"minItems",message:`expected at least ${H} items, got ${Z.length}`,params:{limit:H}});if(J!==void 0&&Z.length>J)X.push({path:$,code:"maxItems",message:`expected at most ${J} items, got ${Z.length}`,params:{limit:J}});return K}case"object":{if(typeof Z!=="object"||Z===null||Array.isArray(Z))return Y();let K=Z,H={};for(let[J,W]of Object.entries(G.shape)){let z=h(W,K[J],[...$,J],X);if(!z.drop)H[J]=z.value}if(G.unknownKeys)for(let J of Object.keys(K)){if(Object.hasOwn(G.shape,J)||K[J]===void 0)continue;if(G.unknownKeys==="error"){X.push({path:[...$,J],code:"additionalProperties",message:"unknown key",params:{additionalProperty:J}});continue}G1(K[J],[...$,J],X,new Set),Object.defineProperty(H,J,{value:K[J],enumerable:!0,writable:!0,configurable:!0})}return H}case"union":{let K;for(let H of G.members){let J=[],W=h(H,Z,$,J);if(J.length===0)return W.drop?void 0:W.value;let z=R1(H,Z);if(!K||z>K.score)K={issues:J,score:z}}X.push({path:$,code:"anyOf",message:`no matching variant; closest: ${K.issues.map(v1).join("; ")}`,params:{closest:K.issues}});return}case"json":if(Z===void 0)return Y();return G1(Z,$,X,new Set),Z;case"ref":return R0(G.cell,Z,()=>{X.push({path:$,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>h(n(G.cell),Z,$,X).value)}}function DQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function B0(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:Y,format:K}=Q;if(G!==void 0||Y!==void 0){let H=DQ(Z);if(G!==void 0&&H<G)X.push({path:$,code:"minLength",message:`expected at least ${G} characters, got ${H}`,params:{limit:G}});if(Y!==void 0&&H>Y)X.push({path:$,code:"maxLength",message:`expected at most ${Y} characters, got ${H}`,params:{limit:Y}})}if(K){let H=!1;try{H=K.test(Z)===!0}catch{}if(!H)X.push({path:$,code:"format",message:`expected a string in format "${K.name}"`,params:{format:K.name}})}}function jQ(Q,Z,$,X){if(!Q)return;let G=(Y,K,H,J)=>{if(K===void 0||H(K))return;X.push({path:$,code:Y,message:`expected ${J} ${K}, got ${Z}`,params:{limit:K}})};G("minimum",Q.minimum,(Y)=>Z>=Y,"at least"),G("exclusiveMinimum",Q.exclusiveMinimum,(Y)=>Z>Y,"more than"),G("maximum",Q.maximum,(Y)=>Z<=Y,"at most"),G("exclusiveMaximum",Q.exclusiveMaximum,(Y)=>Z<Y,"less than")}function G1(Q,Z,$,X,G=!0){let Y=(H)=>{$.push({path:Z,code:"type",message:`expected a JSON value, got ${H}`,params:{}})};switch(typeof Q){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(Q))Y(String(Q));return;case"bigint":return Y("a bigint");case"function":return Y("a function");case"symbol":return Y("a symbol")}if(Q===null)return;let K=Q;if(X.has(K))return Y("a circular reference");X.add(K);try{let H=G?K.toJSON:void 0;if(typeof H==="function"){let J;try{J=H.call(K)}catch{return Y("a toJSON that threw")}if(J===void 0)return Y("a toJSON that returns undefined");return G1(J,Z,$,X,!1)}if(Array.isArray(Q))Q.forEach((J,W)=>G1(J,[...Z,W],$,X));else for(let[J,W]of Object.entries(K))G1(W,[...Z,J],$,X)}finally{X.delete(K)}}function E(Q){return C1(Q)}function C1(Q){let Z={toJSONSchema:()=>JQ(Q),parse($){let X=[],G=h(Q,$,[],X);if(X.length>0)throw Error(X.map(v1).join("; "));return G.drop?void 0:G.value},safeParse($){let X=[],G=h(Q,$,[],X);if(X.length>0)return{ok:!1,errors:X.map(v1)};return{ok:!0,value:G.drop?void 0:G.value}},validate($){let X=[],G=h(Q,$,[],X);if(X.length>0)return{ok:!1,issues:X};return{ok:!0,value:G.drop?void 0:G.value}},describe:($)=>C1({...Q,description:$}),optional:()=>C1({...Q,optional:!0}),nullable:()=>C1({...Q,nullable:!0,optional:!1})};return L1.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var D0=["strip","error","passthrough"];class C0 extends Error{problems;constructor(Q){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
3
|
-
${Q.map((Z)=>`- ${Z}`).join(`
|
|
4
|
-
`)}`);this.name="JSONSchemaError",this.problems=Q}}var RQ=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),Q1={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function D1(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function _1(Q,Z,$,X){let G=(V,B=$)=>{X.push(B?`${B}: ${V}`:V);return},Y=(V)=>$?`${$}.${V}`:V;if(!D1(Q))return G("expected a schema object");let K=new Set(Z.ignoreKeywords??[]),H=(V)=>RQ.has(V)||V.startsWith("x-")||K.has(V),J=!1,W=Q.type;if(Array.isArray(W)){let V=W.filter((B)=>B!=="null");if(V.length!==1)return G(`type ${JSON.stringify(W)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,Y("type"));J=V.length<W.length,W=V[0]}if(W!==void 0&&(typeof W!=="string"||!(W in Q1)))return G(`type ${JSON.stringify(W)} is not supported; expected one of ${Object.keys(Q1).join(", ")}`,Y("type"));let z=new Set(["type","description","enum","const","anyOf",...W?Q1[W]:[]]),P=!1;for(let V of Object.keys(Q)){if(z.has(V)||H(V))continue;P=!0;let B=Object.entries(Q1).find(([,U])=>U.includes(V));G(B&&B[0]!==W?`"${V}" applies to type ${B[0]}, and this schema is ${W?`type ${W}`:"untyped"}`:`"${V}" is not supported by s.fromJSONSchema`,Y(V))}if(P)return;if(Q.description!==void 0&&typeof Q.description!=="string")return G("expected a string",Y("description"));let C=Q.description,M=(V)=>({node:V,optional:!1,nullable:J,...C?{description:C}:{}});if(Q.anyOf!==void 0){if(W!==void 0||Q.enum!==void 0||Q.const!==void 0)return G("anyOf cannot be combined with type, enum or const here",Y("anyOf"));if(!Array.isArray(Q.anyOf)||Q.anyOf.length===0)return G("expected a non-empty array",Y("anyOf"));let V=[],B=!1;if(Q.anyOf.forEach((U,j)=>{if(D1(U)&&U.type==="null"&&Object.keys(U).length===1){J=!0;return}let I=_1(U,Z,Y(`anyOf[${j}]`),X);if(I)V.push(I);else B=!0}),B)return;if(V.length===0)return G("anyOf has only null in it",Y("anyOf"));if(V.length===1){let U=V[0];return{...U,nullable:U.nullable||J,...C?{description:C}:{}}}return M({kind:"union",members:V})}if(Q.const!==void 0){let V=Q.const;if(typeof V!=="string"&&typeof V!=="number"&&typeof V!=="boolean")return G("only a string, number or boolean const is supported",Y("const"));if(W!==void 0&&typeof V!==(W==="integer"?"number":W))return G(`const ${JSON.stringify(V)} is not of type ${W}`,Y("const"));return M({kind:"literal",value:V})}let D;if(W==="string"){if(D=CQ(Q,Z,Y,X),D===null)return}if(Q.enum!==void 0){if(!Array.isArray(Q.enum)||Q.enum.length===0)return G("expected a non-empty array",Y("enum"));let V=Q.enum.filter((j)=>j!==null);if(V.length<Q.enum.length)J=!0;let B=V.find((j)=>!(typeof j==="string"||typeof j==="number"||typeof j==="boolean")||W!==void 0&&typeof j!==(W==="integer"?"number":W));if(B!==void 0||V.length===0)return G(W?`every value must be of type ${W}${V.length===0?", and there must be one":`; ${JSON.stringify(B)} is not`}`:"only strings, numbers and booleans are supported",Y("enum"));if(V.every((j)=>typeof j==="string"))return M({kind:"enum",values:[...new Set(V)],...D?{checks:D}:{}});let U=[...new Set(V)];if(U.length===1)return M({kind:"literal",value:U[0]});return M({kind:"union",members:U.map((j)=>x({kind:"literal",value:j}))})}switch(W){case void 0:return G("a schema needs a type, an enum, a const or an anyOf");case"string":return M({kind:"string",...D?{checks:D}:{}});case"number":case"integer":{let V=W==="integer"?{integer:!0}:{},B=!1;for(let U of Q1.number){let j=Q[U];if(j===void 0)continue;if(typeof j!=="number"||!Number.isFinite(j)){G("expected a number",Y(U)),B=!0;continue}V[U]=j}if(B)return;return M({kind:"number",...Object.keys(V).length>0?{checks:V}:{}})}case"boolean":return M({kind:"boolean"});case"array":{if(!D1(Q.items))return G('an array needs "items" to be one schema (tuples are not supported)',Y("items"));let V={},B=!1;for(let j of["minItems","maxItems"]){let I=Q[j];if(I===void 0)continue;if(typeof I!=="number"||!Number.isInteger(I)||I<0){G("expected a non-negative integer",Y(j)),B=!0;continue}V[j]=I}let U=_1(Q.items,Z,Y("items"),X);if(!U||B)return;return M({kind:"array",item:U,...Object.keys(V).length>0?{checks:V}:{}})}case"object":{let V=Q.properties??{};if(!D1(V))return G("expected an object",Y("properties"));if(Q.additionalProperties!==void 0&&Q.additionalProperties!==!1)return G("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",Y("additionalProperties"));let B=Q.required??[];if(!Array.isArray(B)||!B.every((N)=>typeof N==="string"))return G("expected an array of property names",Y("required"));let U=B.filter((N)=>!Object.hasOwn(V,N));if(U.length>0)return G(`lists properties the schema doesn't have: ${U.join(", ")}`,Y("required"));let j={},I=!1;for(let[N,O]of Object.entries(V)){let _=_1(O,Z,Y(`properties.${N}`),X);if(!_){I=!0;continue}j[N]=B.includes(N)?_:{..._,optional:!0}}if(I)return;let A=Z.unknownKeys;return M({kind:"object",shape:j,...A==="error"||A==="passthrough"?{unknownKeys:A}:{}})}}return}function CQ(Q,Z,$,X){let G={},Y=!1;for(let K of["minLength","maxLength"]){let H=Q[K];if(H===void 0)continue;if(typeof H!=="number"||!Number.isInteger(H)||H<0){X.push(`${$(K)}: expected a non-negative integer`),Y=!0;continue}G[K]=H}if(Q.format!==void 0){let K=Q.format,H=typeof K==="string"?Z.formats?.[K]:void 0;if(typeof K!=="string")X.push(`${$("format")}: expected a string`),Y=!0;else if(!H||!Object.hasOwn(Z.formats,K))X.push(`${$("format")}: unknown format ${JSON.stringify(K)}; pass a check for it in the formats option`),Y=!0;else G.format={name:K,test:_Q(H)}}if(Y)return null;return Object.keys(G).length>0?G:void 0}function _Q(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var eZ={string:()=>E(x({kind:"string"})),number:()=>E(x({kind:"number"})),boolean:()=>E(x({kind:"boolean"})),literal:(Q)=>E(x({kind:"literal",value:Q})),enum:(Q)=>E(x({kind:"enum",values:Q})),object:(Q)=>E(x({kind:"object",shape:Object.fromEntries(Object.entries(Q).map(([Z,$])=>[Z,j1($)]))})),array:(Q)=>E(x({kind:"array",item:j1(Q)})),union:(Q)=>E(x({kind:"union",members:Q.map(j1)})),json:()=>E(x({kind:"json"})),recursive:OQ,fromJSONSchema:(Q,Z={})=>{let $=[];if(Z.unknownKeys!==void 0&&!D0.includes(Z.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${D0.map((G)=>JSON.stringify(G)).join(", ")}, got ${JSON.stringify(Z.unknownKeys)}`);let X=_1(Q,Z,"",$);if(!X||$.length>0)throw new C0($.length>0?$:["unreadable schema"]);return E(X)}};function Q8(Q){let Z=L1.get(Q);if(Z)return X1(Z.node);return $1(Q.toJSONSchema())}function $1(Q){if(!(Q.$ref!==void 0||Q.type!==void 0||Q.enum!==void 0||Q.const!==void 0||Q.anyOf!==void 0||Q.properties!==void 0||Q.items!==void 0))return!1;for(let $ of Object.values(Q.properties??{}))if(!$1($))return!1;if(Q.items&&!$1(Q.items))return!1;for(let $ of Q.anyOf??[])if(!$1($))return!1;for(let $ of Object.values(Q.$defs??{}))if(!$1($))return!1;return!0}function X1(Q,Z=new Set){switch(Q.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(Q.shape).every(($)=>X1($.node,Z));case"array":return X1(Q.item.node,Z);case"union":return Q.members.every(($)=>X1($.node,Z));case"json":return!1;case"ref":if(Z.has(Q.cell))return!0;return Z.add(Q.cell),X1(n(Q.cell).node,Z)}}function h1(Q,Z,$=new Set){let X=Q.node;if(X.kind==="union")return X.members.some((G)=>h1(G,Z,$));if(X.kind!=="ref")return!1;if(X.cell===Z)return!0;if($.has(X.cell)||!X.cell.definition)return!1;return $.add(X.cell),h1(X.cell.definition,Z,$)}var LQ=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function OQ(Q,Z){if(typeof Q!=="string"||!LQ.test(Q))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(Q)}`);let $={name:Q,active:new Set},X=()=>x({kind:"ref",cell:$}),G=j1(Z(E(X())));if(G.optional)throw Error(`gemi/ai: the recursive schema "${Q}" is optional() as a whole; mark the places that use it optional instead`);if(h1(G,$))throw Error(`gemi/ai: the recursive schema "${Q}" refers to itself outside any object or array, so it describes no finite value; nest \`self\` in an s.object(...) field or an s.array(...)`);return $.definition=G,E(X())}function _0(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),$=Z.trim().toLowerCase();return $===""?null:$}function L0(Q){if(Q===null)return!1;if(Q==="application/json")return!0;let Z=Q.indexOf("/");return Z>0&&Q.endsWith("+json")&&Q.length>Z+1+5}var Y1=new WeakMap;function X8(Q,Z,$,X){Y1.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function O0(Q){return Y1.get(Q)?.progress}function I0(Q){return Y1.get(Q)?.grant}function A0(Q){return Y1.has(Q)}function G8(Q){return Y1.get(Q)?.clientAddress}var N0=new WeakMap;function K8(Q,Z){N0.set(Q,Z)}function F0(Q){return N0.get(Q)??null}var p1=new WeakMap;function J8(Q,Z){let $=p1.get(Q)??[];if(!$.includes(Z))p1.set(Q,[...$,Z])}function H8(Q){return p1.get(Q)??[]}class i{data;constructor(Q){this.data=Q}get(Q){return this.data[Q]}has(Q){return this.data[Q]!==void 0}toJSON(){return this.data}}function T0(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function IQ(Q,Z){if(!Z.includes(".")||Object.hasOwn(Q,Z))return[{path:[Z],value:Q[Z]}];let $=[{path:[],value:Q}];for(let X of Z.split(".")){let G=[];for(let{path:Y,value:K}of $){if(X==="*"){if(Array.isArray(K))K.forEach((H,J)=>G.push({path:[...Y,J],value:H}));else if(T0(K))for(let[H,J]of Object.entries(K))G.push({path:[...Y,H],value:J});continue}if(Array.isArray(K)&&/^\d+$/.test(X)){G.push({path:[...Y,Number(X)],value:K[Number(X)]});continue}G.push({path:[...Y,X],value:T0(K)&&Object.hasOwn(K,X)?K[X]:void 0})}$=G}return $}function w0(Q){return Q.join(".")}class AQ{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(Q,Z,$,X){if(!Q){let J=k.getStore().req;this.params=J.params,this.rawRequest=J.rawRequest,this.kind=J.kind,this.routePath=J.routePath,this.domain=J.domain??null,this.state=J.state??new c1}else this.params=Z,this.rawRequest=Q,this.routePath=X,this.kind=$??"api",this.domain=F0(Q),this.state=new c1;this.headers=this.rawRequest.headers;let G=q1(this.rawRequest.headers.get("Cookie")),Y=new URL(this.rawRequest.url),K=new Map;for(let[J,W]of Y.searchParams)if(K.has(J)){let z=K.get(J);if(Array.isArray(z))z.push(W),K.set(J,z);else K.set(J,[z,W])}else K.set(J,W);let H=Object.fromEntries(K.entries());this.search=new i(H),this.cookies=G}locale(){let Q=k.getStore();if(Q.locale)return Q.locale;let Z=O1(S0);return Z.isLocaleAware?Z.detectLocale(Q.req):Q.locale}ctx(){return k.getStore()}isModelOriginated(){return A0(this.rawRequest)}mcpGrant(){return I0(this.rawRequest)??null}cspNonce(){return k1(this.rawRequest)}reportProgress(Q){let Z=O0(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return Y0(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=_0(this.rawRequest.headers.get("Content-Type"));if(L0(Q))return new i(await this.parseJsonBody());if(Q==="application/x-www-form-urlencoded"||Q==="multipart/form-data"){if(Q==="multipart/form-data"&&!m1(this.schema)){let X=V0(this.schema??{});if(X!==null)M0(this.rawRequest,X)}let Z;try{Z=await this.rawRequest.formData()}catch(X){if(X instanceof F)throw X;throw new F("The request body could not be read as a form.")}let $=new Map;for(let[X,G]of Z.entries())if($.has(X)){let Y=$.get(X);if(Array.isArray(Y))Y.push(G);else $.set(X,[Y,G])}else $.set(X,G);return new i(Object.fromEntries($.entries()))}return new i({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch($){if($ instanceof F)throw $;throw new F("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new F("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new F("The request body must be a JSON object.");return Z}validateInput(Q){if(m1(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},$={},X=Object.entries(this.schema).map(([G,Y])=>({key:G,rules:Object.entries(Y).map(([K,H])=>({rule:K,message:H,check:typeof H==="function"?null:this.ruleFor(G,K)}))}));for(let{key:G,rules:Y}of X)for(let{path:K,value:H}of IQ(Z,G)){let J=this.checkField(H,Y);if(J.length>0){let W=$[w0(K)]??=[];for(let z of J)if(!W.includes(z))W.push(z)}}if(this.addRefinements($,Z),Object.keys($).length>0)throw new e($);return Q}checkField(Q,Z){let $=Z.some(({rule:Y})=>Y==="required"),X=Q===void 0||Q===null||Q==="",G=[];for(let{rule:Y,message:K,check:H}of Z){let J=K,W=!1;if(typeof K==="function")J=K(Q),W=typeof J>"u";else W=H(Q);if(W)continue;if(X&&!$)continue;if(Y==="required")return[String(J)];if(!G.includes(String(J)))G.push(String(J))}return G}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),$={};if("issues"in Z)for(let G of Z.issues){let Y=w0(G.path),K=$[Y]??=[];if(!K.includes(G.message))K.push(G.message)}let X="value"in Z?new i(Z.value):Q;if(this.addRefinements($,X.toJSON()),Object.keys($).length>0)throw new e($);return X}addRefinements(Q,Z){for(let[$,X]of Object.entries(this.refine(Z)??{})){let G=Q[$]??[];Q[$]=G.includes(X)?G:[...G,X]}}ruleFor(Q,Z){try{return z0(Z)}catch($){if($ instanceof g)throw new g(`${this.constructor.name}.schema.${Q}: ${$.message}`);throw $}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let Q=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(Q)}}catch(Z){if(!(Z instanceof e))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}var E0="x-gemi-sign-in";class NQ extends F{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:A1("authorization",this.error,401)}},view:{}}}}class u1 extends F{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:u1.apiStatus,data:{error:A1("permission",this.error,u1.apiStatus)}},view:{status:403}}}}class d1 extends F{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:I1("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":J0(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class FQ extends F{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:I1("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class m extends F{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:I1("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class TQ extends F{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:A1("authentication","Authentication error",401)},headers:{[E0]:Z}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Z}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Z}}}}}class K1{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return O1(this.getFacadeAccessor())}}import{Buffer as wQ}from"buffer";function N1(Q){if(typeof Q!=="string"||/^[\s/.]*$/.test(Q))throw Error(`Refusing to delete by prefix ${JSON.stringify(Q)}: it would match the whole store`)}class J1{async putStream({body:Q,...Z},$={}){$.signal?.throwIfAborted();let X=[],G=Q.getReader();try{for(;;){$.signal?.throwIfAborted();let{done:Y,value:K}=await G.read();if(Y)break;X.push(K)}}catch(Y){throw await G.cancel(Y).catch(()=>{}),Y}return this.put({...Z,body:wQ.concat(X)},$)}async*objects(Q,Z={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(Q,Z={}){N1(Q);let $=[];for await(let X of this.objects(Q,Z))$.push(X.name);for(let X of $)Z.signal?.throwIfAborted(),await this.delete({name:X,bucket:Z.bucket});return $.length}async delete(Q){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,$=await this.fetch({name:Z.name,bucket:Z.bucket});if(!$.ok)throw new m(Z.name);let X=$.headers.get("Content-Type")??"application/octet-stream",G=$.headers.get("ETag")??void 0,Y=$.headers.get("Last-Modified"),K=Y?new Date(Y):void 0;if(Z.range){let W=await $.blob();return{body:W,start:0,end:W.size-1,total:W.size,partial:!1,type:X,etag:G,lastModified:K,name:Z.name}}let H=Number($.headers.get("Content-Length")),J=Number.isFinite(H)?H:0;return{body:$.body,start:0,end:J-1,total:J,partial:!1,type:X,etag:G,lastModified:K,name:Z.name}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=typeof Q==="string"?void 0:Q.bucket,X=await this.fetch({name:Z,bucket:$});if(!X.ok)throw new m(Z);let G=Number(X.headers.get("Content-Length"));if(Number.isFinite(G))return await X.body?.cancel(),G;return(await X.blob()).size}}function q0(Q,Z){if(!Z)return Q;let $=Q.getReader(),X=!1,G,Y=()=>{if(X=!0,G)Z.removeEventListener("abort",G)};return new ReadableStream({start(K){if(G=()=>{if(X)return;Y(),K.error(Z.reason),$.cancel(Z.reason).catch(()=>{})},Z.aborted)G();else Z.addEventListener("abort",G,{once:!0})},async pull(K){let H;try{H=await $.read()}catch(J){if(X)return;Y(),K.error(J);return}if(X)return;if(H.done){Y(),K.close();return}K.enqueue(H.value)},cancel(K){return Y(),$.cancel(K)}},{highWaterMark:0})}import{mkdir as SQ,open as EQ,readdir as l1,rename as qQ,rmdir as xQ,stat as kQ,unlink as x0}from"fs/promises";import{dirname as gQ,isAbsolute as n1,relative as H1,resolve as o,sep as f}from"path";class i1 extends J1{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${W1()}/storage`}async put(Q,{signal:Z}={}){Z?.throwIfAborted();let $,X;if(Q instanceof Blob)$=Q,X=`${Bun.randomUUIDv7()}.${Q.type.split("/")[1].split(";")[0]}`;else $=Q.body,X=Q.name;let G=$ instanceof Buffer?$:$ instanceof Blob||$ instanceof File?Buffer.from(await $.arrayBuffer()):"",Y=`${this.folderPath}/${X}`;return Z?.throwIfAborted(),await Bun.write(Y,G),X}async putStream({name:Q,body:Z},{signal:$}={}){let X=Z.getReader(),G=null;try{if($?.throwIfAborted(),!Q)throw Error("Object name has to be specified");let Y=o(this.folderPath),K=o(Y,Q),H=H1(Y,K);if(!H||H===".."||H.startsWith(`..${f}`)||n1(H))throw Error(`Refusing to write "${Q}": it is outside the storage folder`);await SQ(gQ(K),{recursive:!0}),G=`${K}.${Bun.randomUUIDv7()}.partial`;let J=await EQ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:W,value:z}=await X.read();if(W)break;for(let P=0;P<z.byteLength;){let{bytesWritten:C}=await J.write(z,P);P+=C}}}finally{await J.close()}return $?.throwIfAborted(),await qQ(G,K),Q}catch(Y){if(await X.cancel(Y).catch(()=>{}),G)await x0(G).catch(()=>{});throw Y}}async fetch(Q,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,X;if(typeof Q==="string")X=Q;else $=Q.bucket??$,X=Q.name;if(!X)throw Error("Object name has to be specified");let G=`${this.folderPath}/${X}`,Y=Bun.file(G),K=q0(Bun.file(G).stream(),Z),H=new Date(Y.lastModified).toUTCString();return new Response(K,{headers:{"Content-Type":Y.type,"Content-Length":String(Y.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":H}})}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,{name:$,range:X=null}=Z;if(!$)throw Error("Object name has to be specified");let G=Bun.file(`${this.folderPath}/${$}`);if(!await G.exists())throw new m($);let Y=G.size,K=X?K0(X,Y):null;if(X&&!K)throw new d1(Y);let H=K?.start??0,J=K?K.end:Y-1;return{body:K?G.slice(H,J+1):G,start:H,end:J,total:Y,partial:Boolean(K),type:G.type||"application/octet-stream",lastModified:new Date(G.lastModified),name:$}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=Bun.file(`${this.folderPath}/${Z}`);if(!await $.exists())throw new m(Z);return $.size}async delete(Q){let Z=typeof Q==="string"?Q:Q.name;if(!Z)throw Error("Object name has to be specified");let $=o(this.folderPath),X=o($,Z),G=H1($,X);if(!G||G===".."||G.startsWith(`..${f}`)||n1(G))throw Error(`Refusing to delete "${Z}": it is outside the storage folder`);try{await x0(X)}catch(Y){if(Y?.code==="ENOENT")return;throw Y}}resolvePrefix(Q){let Z=o(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),Y=o(Z,X),K=H1(Z,Y);if(K===".."||K.startsWith(`..${f}`)||n1(K))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let H=K.split(f).join("/");return{root:Z,dir:Y,match:H?`${H}/${G}`:G}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:$,dir:X,match:G}=this.resolvePrefix(Q),Y=[],K=async(H)=>{let J;try{J=await l1(H,{withFileTypes:!0})}catch(W){if(W?.code==="ENOENT"||W?.code==="ENOTDIR")return;throw W}for(let W of J){let z=`${H}${f}${W.name}`,P=H1($,z).split(f).join("/");if(W.isDirectory()){if(`${P}/`.startsWith(G)||G.startsWith(`${P}/`))await K(z)}else if(W.isFile()&&P.startsWith(G))Y.push(P)}};await K(X),Y.sort();for(let H of Y){Z?.throwIfAborted();let J;try{J=await kQ(`${$}/${H}`)}catch(W){if(W?.code==="ENOENT")continue;throw W}yield{name:H,size:J.size,lastModified:J.mtime}}}async deletePrefix(Q,Z={}){N1(Q);let{root:$,match:X}=this.resolvePrefix(Q);N1(X);let G=await super.deletePrefix(Q,Z);if(G>0)await this.pruneEmptyDirs($,X);return G}async pruneEmptyDirs(Q,Z){let $=[],X=async(G)=>{let Y;try{Y=await l1(G,{withFileTypes:!0})}catch{return}for(let K of Y){if(!K.isDirectory())continue;let H=`${G}${f}${K.name}`,J=H1(Q,H).split(f).join("/");if(`${J}/`.startsWith(Z)||Z.startsWith(`${J}/`)){if(await X(H),`${J}/`.startsWith(Z))$.push(H)}}};await X(Q);for(let G of $)try{await xQ(G)}catch{}}async list(){return await l1(this.folderPath)}}var v=30000;function n8(Q){return Q}function k0(){return{driver:new i1,fetchTimeoutMs:v,fetchIdleTimeoutMs:v}}class o1{static token="filesystem";driver;fetchTimeoutMs;fetchIdleTimeoutMs;constructor(Q={}){this.driver=Q.driver??k0().driver,this.fetchTimeoutMs=Q.fetchTimeoutMs??v,this.fetchIdleTimeoutMs=Q.fetchIdleTimeoutMs??v}}class g0 extends Error{driver;limit;timeoutMs;object;code="storage-fetch-timeout";constructor(Q,Z,$,X){super(Z==="fetchTimeoutMs"?`${Q}: no response for "${X}" within ${$}ms (fetchTimeoutMs)`:`${Q}: the body of "${X}" sent nothing for ${$}ms (fetchIdleTimeoutMs)`);this.driver=Q;this.limit=Z;this.timeoutMs=$;this.object=X;this.name="StorageFetchTimeoutError"}}async function b0(Q,Z,$,X){let{fetchTimeoutMs:G,fetchIdleTimeoutMs:Y}=X;if($.signal||!G&&!Y)return Q.fetch(Z,$);let K=new AbortController,H=Q.constructor?.name||"FileStorageDriver",J=typeof Z==="string"?Z:Z.name,W=(C,M)=>{let D=new g0(H,C,M,J);return K.abort(D),D},z=Promise.resolve(Q.fetch(Z,{...$,signal:K.signal})),P;if(G){let C,M=new Promise((D,V)=>{C=setTimeout(()=>V(W("fetchTimeoutMs",G)),G)});try{P=await Promise.race([z,M])}catch(D){if(K.signal.aborted)throw z.then((V)=>V.body?.cancel(K.signal.reason).catch(()=>{}),()=>{}),K.signal.reason;throw D}finally{clearTimeout(C)}}else P=await z;if(!Y||!P.body)return P;return new Response(bQ(P.body,Y,()=>W("fetchIdleTimeoutMs",Y)),{status:P.status,statusText:P.statusText,headers:P.headers})}function bQ(Q,Z,$){let X=Q.getReader();return new ReadableStream({async pull(G){let Y,K,H=new Promise((J,W)=>{Y=setTimeout(()=>{K=$(),W(K)},Z)});try{let J=await Promise.race([X.read(),H]);if(J.done)G.close();else G.enqueue(J.value)}catch(J){let W=K??J;G.error(W),X.cancel(W).catch(()=>{})}finally{clearTimeout(Y)}},cancel(G){return X.cancel(G)}},{highWaterMark:0})}class w extends Error{code="safe-fetch";url;constructor(Q,Z,$){super(Q,$);this.name=new.target.name,this.url=Z}}class p extends w{reason;code="invalid-url";constructor(Q,Z,$){super($,Q);this.reason=Z}}class F1 extends w{host;reason;code="blocked-host";constructor(Q,Z,$){super($==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,Q);this.host=Z;this.reason=$}}class s extends w{host;address;range;code="blocked-address";constructor(Q,Z,$,X){super(Z===$?`${$} is not a public address (${X}).`:`${Z} resolves to ${$}, which is not a public address (${X}).`,Q);this.host=Z;this.address=$;this.range=X}}class T1 extends w{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class w1 extends w{phase;ms;code="timeout";constructor(Q,Z,$){super(Z==="connect"?`Couldn't connect within ${$} ms.`:`The request didn't finish within ${$} ms.`,Q);this.phase=Z;this.ms=$}}class S1 extends w{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class V1 extends w{contentType;allowed;code="content-type";constructor(Q,Z,$){super(`The response is ${Z??"of no content type"}, not ${$.join(" or ")}.`,Q);this.contentType=Z;this.allowed=$}}class s1 extends w{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class t extends w{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class t1 extends w{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function yQ(Q){if(Q==="")return null;let Z=Q.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let $=[];for(let Y of Z){let K=fQ(Y);if(K===null)return null;$.push(K)}let X=$.pop();for(let Y of $)if(Y>255)return null;if(X>=256**(4-$.length))return null;let G=X;return $.forEach((Y,K)=>{G+=Y*256**(3-K)}),new Uint8Array([Math.floor(G/16777216)&255,Math.floor(G/65536)&255,Math.floor(G/256)&255,G&255])}function fQ(Q){if(Q==="")return null;let Z=Q,$=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),$=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),$=8;if(!($===16?/^[0-9a-f]+$/i:$===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let G=parseInt(Z,$);return Number.isSafeInteger(G)?G:null}function y0(Q){let Z=Q;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let $=Z.indexOf("%");if($!==-1)Z=Z.slice(0,$);if(!Z.includes(":"))return null;let X=Z.split("::");if(X.length>2)return null;let G=(W,z)=>{if(W==="")return[];let P=[],C=W.split(":");for(let M=0;M<C.length;M++){let D=C[M];if(z&&M===C.length-1&&D.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(D))return null;let V=D.split(".").map(Number);if(V.some((B)=>B>255))return null;P.push(V[0]<<8|V[1],V[2]<<8|V[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(D))return null;P.push(parseInt(D,16))}return P},Y=G(X[0],X.length===1),K=X.length===2?G(X[1],!0):[];if(!Y||!K)return null;let H;if(X.length===2){let W=8-Y.length-K.length;if(W<1)return null;H=[...Y,...Array.from({length:W},()=>0),...K]}else H=Y;if(H.length!==8)return null;let J=new Uint8Array(16);return H.forEach((W,z)=>{J[z*2]=W>>8,J[z*2+1]=W&255}),J}function z1(Q){let Z=y0(Q);if(Z)return{family:6,bytes:Z};let $=yQ(Q);if($)return{family:4,bytes:$};return null}function c(Q){if(Q.family===6&&vQ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function vQ(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function P1(Q){if(Q.family===4)return Array.from(Q.bytes).join(".");let Z=[];for(let $=0;$<16;$+=2)Z.push((Q.bytes[$]<<8|Q.bytes[$+1]).toString(16));return Z.join(":")}function a(Q){let Z=Q.lastIndexOf("/"),$=Z===-1?Q:Q.slice(0,Z),X=/^[0-9.]+$/.test($)?hQ($):y0($);if(!X)return null;let G=c(X.length===4?{family:4,bytes:X}:{family:6,bytes:X}),Y=G.family===4?32:128,K=Y;if(Z!==-1){let H=Q.slice(Z+1);if(!/^\d{1,3}$/.test(H))return null;if(K=Number(H),X.length===16&&G.family===4)K-=96;if(K<0||K>Y)return null}return{family:G.family,bytes:G.bytes,prefix:K}}function hQ(Q){return/^\d{1,3}(\.\d{1,3}){3}$/.test(Q)&&Q.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array(Q.split(".").map(Number)):null}function b(Q,Z){let $=c(Q);if($.family!==Z.family)return!1;let X=Z.prefix;for(let G=0;X>0;G++){let Y=Math.min(8,X),K=255<<8-Y&255;if(($.bytes[G]&K)!==(Z.bytes[G]&K))return!1;X-=Y}return!0}var L=(Q,Z)=>({cidr:a(Q),kind:Z,text:Q}),mQ=[L("0.0.0.0/8","unspecified"),L("10.0.0.0/8","private"),L("100.64.0.0/10","shared"),L("127.0.0.0/8","loopback"),L("169.254.169.254/32","metadata"),L("169.254.0.0/16","link-local"),L("168.63.129.16/32","metadata"),L("172.16.0.0/12","private"),L("192.0.0.0/24","reserved"),L("192.0.2.0/24","documentation"),L("192.88.99.0/24","reserved"),L("192.168.0.0/16","private"),L("198.18.0.0/15","benchmarking"),L("198.51.100.0/24","documentation"),L("203.0.113.0/24","documentation"),L("224.0.0.0/4","multicast"),L("255.255.255.255/32","broadcast"),L("240.0.0.0/4","reserved")],pQ=[L("::/128","unspecified"),L("::1/128","loopback"),L("64:ff9b:1::/48","private"),L("::/8","reserved"),L("100::/64","reserved"),L("2001:db8::/32","documentation"),L("2001::/23","reserved"),L("3fff::/20","documentation"),L("fd00:ec2::254/128","metadata"),L("fc00::/7","unique-local"),L("fe80::/10","link-local"),L("fec0::/10","private"),L("ff00::/8","multicast")],cQ=a("64:ff9b::/96"),uQ=a("2002::/16"),dQ=a("2000::/3");function E1(Q){let Z=typeof Q==="string"?z1(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let $=c(Z);if($.family===4){let G=mQ.find((Y)=>b($,Y.cidr));return G?{kind:G.kind,range:G.text}:null}if(b($,cQ))return E1({family:4,bytes:$.bytes.slice(12)});if(b($,uQ))return E1({family:4,bytes:$.bytes.slice(2,6)});let X=pQ.find((G)=>b($,G.cidr));if(X)return{kind:X.kind,range:X.text};return b($,dQ)?null:{kind:"reserved",range:"outside 2000::/3"}}function f0(Q,Z){let $=c(Q),X=c(Z);return $.family===X.family&&$.bytes.every((G,Y)=>G===X.bytes[Y])}import{lookup as lQ}from"dns/promises";import*as nQ from"http";import*as iQ from"https";import*as r from"zlib";class a1 extends Response{#Q;#Z;address;constructor(Q,Z,$){super(Q,Z);this.#Q=$.url,this.#Z=$.redirected,this.address=$.address}get url(){return this.#Q}get redirected(){return this.#Z}}var U1={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},oQ=new Set([301,302,303,307,308]),sQ=new Set([101,103,204,205,304]),tQ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],aQ=["authorization","cookie","proxy-authorization"];async function m0(Q,Z={}){let $=rQ(Z),X=Z.signal;X?.throwIfAborted();let G=new AbortController,Y=G.signal,K=String(Q),H=(P)=>{if(!Y.aborted)G.abort(P)},J=setTimeout(()=>H(new w1(K,"total",$.timeout)),$.timeout),W=()=>H(X.reason);X?.addEventListener("abort",W,{once:!0});let z=()=>{clearTimeout(J),X?.removeEventListener("abort",W)};try{let P=h0(K,$),C=(Z.method??"GET").toUpperCase(),M=new Headers(Z.headers);for(let V of tQ)M.delete(V);if(!M.has("accept"))M.set("accept","*/*");if(!M.has("user-agent"))M.set("user-agent","gemi");if(!M.has("accept-encoding"))M.set("accept-encoding","gzip, deflate, br");let D=await $Z(C,Z.body,M);for(let V=0;;V++){K=P.href;let{request:B,response:U,address:j}=await XZ(P,C,M,D,$,Y),I=U.statusCode??0,A=U.headers.location;if(oQ.has(I)&&A&&Z.redirect!=="manual"){if(B.destroy(),V>=$.maxRedirects)throw new s1(P.href,$.maxRedirects);let N;try{N=new URL(A,P)}catch{throw new p(A,"malformed",`The redirect to "${A}" is not a URL.`)}if(I===303?C!=="HEAD":(I===301||I===302)&&C==="POST"){C="GET",D=null;let O=[];M.forEach((_,R)=>{if(R.startsWith("content-"))O.push(R)});for(let _ of O)M.delete(_)}if(N.origin!==P.origin)for(let O of aQ)M.delete(O);P=h0(N.href,$);continue}return GZ({url:P,hop:V,method:C,request:B,response:U,address:j,policy:$,signal:Y,release:z})}}catch(P){throw z(),Y.aborted?Y.reason:P}}function rQ(Q){let Z=(X,G)=>{let Y={hosts:[],ranges:[]};for(let K of X){let H=K.includes("/")||K.includes(":")||/^[\d.]+$/.test(K),J=H?a(K):null;if(J)Y.ranges.push(J);else if(!H&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(K))Y.hosts.push(p0(K));else throw TypeError(`safeFetch: "${K}" in ${G} is not a host name or an IP range.`)}return Y},$=Q.allowPrivate;return{timeout:Q.timeout??U1.timeout,connectTimeout:Q.connectTimeout??U1.connectTimeout,maxSize:Q.maxSize??U1.maxSize,maxRedirects:Q.maxRedirects??U1.maxRedirects,ports:Q.ports??U1.ports,allow:Q.allow&&Q.allow.length>0?Z(Q.allow,"allow"):null,deny:Z(Q.deny??[],"deny"),allowPrivate:$===!0?!0:Z($||[],"allowPrivate").ranges,contentTypes:Q.contentTypes?.length?Q.contentTypes:null,resolve:Q.resolve??eQ}}async function eQ(Q){return(await lQ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function p0(Q){return Q.toLowerCase().replace(/\.$/,"")}function v0(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function h0(Q,Z){let $;try{$=new URL(Q)}catch{throw new p(Q,"malformed",`"${Q}" is not a URL.`)}if($.protocol!=="http:"&&$.protocol!=="https:")throw new p($.href,"scheme",`Only http and https URLs can be fetched, not ${$.protocol.slice(0,-1)}.`);if($.username||$.password)throw new p($.href,"credentials","The URL has a username or password in it.");let X=c0($);if(Z.ports!=="any"&&!Z.ports.includes(X))throw new p($.href,"port",`Port ${X} is not allowed.`);return $}function c0(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function QZ(Q,Z,$){let X=p0(Q.hostname.replace(/^\[(.*)\]$/,"$1")),G=z1(X),Y=G!==null&&(X.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(X));if(!Y&&v0(X,Z.deny.hosts))throw new F1(Q.href,X,"denied");let K=!Y&&Z.allow!==null&&v0(X,Z.allow.hosts);if(Z.allow&&!K&&Z.allow.ranges.length===0)throw new F1(Q.href,X,"not-allowed");let H;if(Y)H=[G];else{let J;try{J=await ZZ(Z.resolve(X),$)}catch(W){if($.aborted)throw $.reason;throw new T1(Q.href,X,W)}if(H=J.map((W)=>z1(W)).filter((W)=>W!==null),H.length===0)throw new T1(Q.href,X)}for(let J of H){let W=P1(J);if(Z.deny.ranges.some((P)=>b(J,P)))throw new s(Q.href,X,W,"denied");if(Z.allow&&!K&&!Z.allow.ranges.some((P)=>b(J,P)))throw new s(Q.href,X,W,"not-allowed");let z=E1(J);if(z&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((P)=>b(J,P)))throw new s(Q.href,X,W,z.kind)}return{host:X,addresses:H,isLiteral:Y}}function ZZ(Q,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise(($,X)=>{let G=()=>X(Z.reason);Z.addEventListener("abort",G,{once:!0}),Q.then((Y)=>{Z.removeEventListener("abort",G),$(Y)},(Y)=>{Z.removeEventListener("abort",G),X(Y)})})}async function $Z(Q,Z,$){if(Z===void 0||Z===null)return null;if(Q==="GET"||Q==="HEAD")throw TypeError(`safeFetch: a ${Q} request can't have a body.`);let X=new Request("http://body.invalid/",{method:"POST",body:Z}),G=X.headers.get("content-type");if(G&&!$.has("content-type"))$.set("content-type",G);return new Uint8Array(await X.arrayBuffer())}async function XZ(Q,Z,$,X,G,Y){let K=new AbortController,H=setTimeout(()=>K.abort(new w1(Q.href,"connect",G.connectTimeout)),G.connectTimeout),J=AbortSignal.any([Y,K.signal]);try{let{host:W,addresses:z,isLiteral:P}=await QZ(Q,G,J),C=Q.protocol==="https:",M={};if($.forEach((D,V)=>{M[V]=D}),X)M["content-length"]=String(X.byteLength);return await new Promise((D,V)=>{let B={method:Z,host:W,port:c0(Q),path:`${Q.pathname}${Q.search}`,headers:M,agent:!1,lookup:(O,_,R)=>{let S=_?.family,T=z.filter((M1)=>!S||M1.family===S);if(T.length===0)R(Object.assign(Error(`No IPv${S} address for ${W}`),{code:"ENOTFOUND"}));else if(_?.all)R(null,T.map((M1)=>({address:P1(M1),family:M1.family})));else R(null,P1(T[0]),T[0].family)}};if(C&&!P)B.servername=W;let U=(C?iQ:nQ).request(B),j=null,I=(O)=>{J.removeEventListener("abort",A),U.destroy(),V(O)},A=()=>I(J.aborted?J.reason:Y.reason);J.addEventListener("abort",A,{once:!0});let N=(O)=>{let _=O?.remoteAddress;if(!_||j!==null)return!0;let R=z1(_);if(!R||!z.some((S)=>f0(S,R)))return I(new s(Q.href,W,_,"not-allowed")),!1;return j=P1(c(R)),!0};U.once("socket",(O)=>{let _=()=>{if(N(O)&&!C)clearTimeout(H)};if(O.connecting)O.once("connect",_);else _();if(C)O.once("secureConnect",()=>clearTimeout(H))}),U.once("response",(O)=>{if(clearTimeout(H),O.on("error",()=>{}),!N(O.socket))return;J.removeEventListener("abort",A),D({request:U,response:O,address:j})}),U.on("error",(O)=>{if(J.aborted)return I(J.reason);I(O instanceof w?O:new t(Q.href,O))}),U.end(X??void 0)})}finally{clearTimeout(H)}}function GZ({url:Q,hop:Z,method:$,request:X,response:G,address:Y,policy:K,signal:H,release:J}){let W=G.statusCode??0;if(W<200||W>599)throw X.destroy(),new t(Q.href,Error(`Unexpected status ${W}`));let z=new Headers,P=G.rawHeaders;for(let _=0;_<P.length;_+=2)z.append(P[_],P[_+1]);if(K.contentTypes){let _=z.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!_||!K.contentTypes.some((R)=>YZ(_,R)))throw X.destroy(),new V1(Q.href,_,K.contentTypes)}let C={url:Q.href,redirected:Z>0,address:Y},M={status:W,statusText:G.statusMessage??"",headers:z};if($==="HEAD"||sQ.has(W))return X.destroy(),J(),new a1(null,M,C);let D=z.get("content-encoding")?.trim().toLowerCase(),V=D==="gzip"||D==="x-gzip"?r.createGunzip():D==="deflate"?r.createInflate():D==="br"?r.createBrotliDecompress():null,B=Number(z.get("content-length"));if(!V&&Number.isFinite(B)&&B>K.maxSize)throw X.destroy(),new S1(Q.href,K.maxSize);if(V)z.delete("content-encoding"),z.delete("content-length");let U=V?G.pipe(V):G,j=0,I=!1,A=()=>{},N=()=>{I=!0,H.removeEventListener("abort",A),J()},O=new ReadableStream({start(_){let R=(T)=>{if(I)return;if(N(),T===void 0)_.close();else X.destroy(),V?.destroy(),_.error(T)};if(A=()=>R(H.reason),H.addEventListener("abort",A,{once:!0}),H.aborted)return A();U.on("data",(T)=>{if(I)return;if(j+=T.byteLength,j>K.maxSize)return R(new S1(Q.href,K.maxSize));if(_.enqueue(new Uint8Array(T)),(_.desiredSize??1)<=0)U.pause()}),U.once("end",()=>R());let S=(T)=>R(T instanceof w?T:new t(Q.href,T));if(U.on("error",S),V)G.on("error",S);G.once("aborted",()=>R(new t(Q.href,Error("The response was cut off."))))},pull(){U.resume()},cancel(){if(I)return;N(),X.destroy(),V?.destroy()}});return new a1(O,M,C)}function YZ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function d0(Q){return HZ(Q)??VZ(Q)??zZ(Q)}var r1=4096,KZ={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/heic":"heic","image/heif":"heif","image/bmp":"bmp","image/tiff":"tiff","image/x-icon":"ico","image/svg+xml":"svg","audio/mpeg":"mp3","audio/aac":"aac","audio/mp4":"m4a","audio/ogg":"ogg","audio/flac":"flac","audio/wav":"wav","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm","video/x-matroska":"mkv","video/x-msvideo":"avi","font/woff":"woff","font/woff2":"woff2","font/ttf":"ttf","font/otf":"otf","application/pdf":"pdf","application/zip":"zip","application/gzip":"gz","application/xml":"xml","text/html":"html","text/plain":"txt","application/octet-stream":"bin"};function l0(Q){return KZ[Q]??"bin"}function q(Q,Z,$=0){if(Q.length<$+Z.length)return!1;return Z.every((X,G)=>Q[$+G]===X)}function y(Q,Z,$){return String.fromCharCode(...Q.subarray(Z,$))}var JZ={avif:"image/avif",avis:"image/avif",heic:"image/heic",heix:"image/heic",hevc:"image/heic",hevx:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif","qt ":"video/quicktime","M4A ":"audio/mp4","M4B ":"audio/mp4"};function HZ(Q){if(q(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(q(Q,[255,216,255]))return"image/jpeg";if(Q.length>=6&&(y(Q,0,6)==="GIF87a"||y(Q,0,6)==="GIF89a"))return"image/gif";if(Q.length>=12&&y(Q,0,4)==="RIFF"){let Z=y(Q,8,12);if(Z==="WEBP")return"image/webp";if(Z==="WAVE")return"audio/wav";if(Z==="AVI ")return"video/x-msvideo"}if(Q.length>=12&&y(Q,4,8)==="ftyp"){let Z=y(Q,8,12);return JZ[Z]??"video/mp4"}if(q(Q,[73,73,42,0])||q(Q,[77,77,0,42]))return"image/tiff";if(q(Q,[66,77])&&q(Q,[0,0,0,0],6))return"image/bmp";if(q(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(q(Q,[37,80,68,70,45]))return"application/pdf";if(q(Q,[80,75,3,4]))return"application/zip";if(q(Q,[31,139]))return"application/gzip";if(q(Q,[26,69,223,163]))return y(Q,0,Math.min(Q.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(Q.length>=4){let Z=y(Q,0,4);if(Z==="OggS")return"audio/ogg";if(Z==="fLaC")return"audio/flac";if(Z==="wOFF")return"font/woff";if(Z==="wOF2")return"font/woff2";if(Z==="OTTO")return"font/otf"}if(q(Q,[0,1,0,0,0]))return"font/ttf";if(Q.length>=3&&y(Q,0,3)==="ID3")return"audio/mpeg";if(Q.length>=2&&Q[0]===255){if((Q[1]&246)===240)return"audio/aac";if((Q[1]&224)===224&&(Q[1]&6)!==0)return"audio/mpeg"}return null}var WZ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function VZ(Q){let Z=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(Z.charCodeAt(0)===65279)Z=Z.slice(1);if(Z=Z.trimStart(),!Z.startsWith("<"))return null;let $=Z.toLowerCase(),X=$;for(;;){X=X.trimStart();let G=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(X);if(!G)break;X=X.slice(G[0].length)}if(/^<svg[\s>/]/.test(X))return"image/svg+xml";for(let G of WZ){if(!$.startsWith(`<${G}`))continue;if(/^[\s>]/.test($.charAt(G.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(X))return"text/html";if($.startsWith("<?xml"))return"application/xml";return null}function zZ(Q){if(Q.length===0)return"application/octet-stream";for(let Z of Q)if(Z<32&&Z!==9&&Z!==10&&Z!==12&&Z!==13&&Z!==27)return"application/octet-stream";try{return new TextDecoder("utf-8",{fatal:!0}).decode(Q,{stream:!0}),"text/plain"}catch{return"application/octet-stream"}}var PZ=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function u0(Q){let Z=Q.split(";")[0].trim().toLowerCase();return PZ.has(Z)||Z.endsWith("+xml")}function n0(Q,Z){let $=Q.split(";")[0].trim().toLowerCase();return Z.some((X)=>{let G=X.split(";")[0].trim().toLowerCase();if(G==="*/*"||G==="*")return!u0($);if(G.endsWith("/*"))return $.startsWith(G.slice(0,-1))&&!u0($);return $===G})}import{Buffer as BZ}from"buffer";async function i0(Q){try{return(await import("sharp")).default}catch(Z){throw Error(`${Q} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Z})}}async function o0(Q,Z,$={}){let{name:X,directory:G,bucket:Y,maxSize:K,timeout:H,contentTypes:J,signal:W}=$;if(X!==void 0&&G!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(X!==void 0&&!X)throw TypeError("Storage.putFromUrl(): `name` is empty.");let z=await m0(Z,{...$.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:W,timeout:H,maxSize:K});if(!z.ok)throw await z.body?.cancel().catch(()=>{}),new t1(z.url,z.status);let P=(z.body??new Response(new Uint8Array).body).getReader(),C=async(R)=>{throw await P.cancel(R).catch(()=>{}),R},M=[],D=0,V=!1;while(D<r1){let{done:R,value:S}=await P.read();if(R){V=!0;break}M.push(S),D+=S.byteLength}let B=MZ(M,D),U=d0(B.subarray(0,Math.min(D,r1))),j=J?.length?J:["*/*"];if(!n0(U,j))await C(new V1(z.url,U,j));let I=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${l0(U)}`].filter(Boolean).join("/"),A=D,N=new ReadableStream({start(R){if(D>0)R.enqueue(B);if(V)R.close()},async pull(R){let{done:S,value:T}=await P.read();if(S){R.close();return}A+=T.byteLength,R.enqueue(T)},cancel(R){return P.cancel(R)}}),O={name:I,bucket:Y,body:N,contentType:U},_;try{_=Q.putStream?await Q.putStream(O,{signal:W}):await J1.prototype.putStream.call(Q,O,{signal:W})}catch(R){throw await C(R),R}return{name:_,contentType:U,size:A,url:z.url}}function MZ(Q,Z){if(Q.length===1)return Q[0];let $=new Uint8Array(Z),X=0;for(let G of Q)$.set(G,X),X+=G.byteLength;return $}class DZ extends K1{static getFacadeAccessor(){return o1}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return o0(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=BZ.from(await Q.arrayBuffer()),$=await i0("Storage.metadata()");try{return await $(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){Z.signal?.throwIfAborted();let $=this.getFacadeRoot();return b0($.driver,Q,Z,{fetchTimeoutMs:$.fetchTimeoutMs??v,fetchIdleTimeoutMs:$.fetchIdleTimeoutMs??v})}static async read(Q,Z={}){let $=typeof Q==="string"?{name:Q}:{...Q},X="range"in Z?Z.range??null:$.range!==void 0?$.range:k.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...$,range:X})}static list(Q){return this.getFacadeRoot().driver.list(Q)}static objects(Q,Z={}){return this.getFacadeRoot().driver.objects(Q,Z)}static async deletePrefix(Q,Z={}){return this.getFacadeRoot().driver.deletePrefix(Q,Z)}static async delete(Q){return this.getFacadeRoot().driver.delete(Q)}}var s0=["cookie","set-cookie","authorization","proxy-authorization","x-api-key"];function C4(Q){return Q}function _4(){let Q=Bun.env.NODE_ENV==="development";return{maxFileSize:10485760,console:Q,consoleFormat:Q?"text":"json",requestFields:[],redactHeaders:[],onLogFileClosed:()=>{},onLogCreated:()=>{}}}import{mkdir as Q0,readdir as _Z,access as LZ}from"fs/promises";var e1=["debug","info","notice","warning","error","critical","alert","emergency"],jZ=e1.indexOf("warning");function a0(Q){if(!Q)return-1;if(Q===!0)return 0;let Z=e1.indexOf(Q);return Z===-1?0:Z}function RZ(){let Q=new WeakSet;return function(Z,$){if(typeof $==="bigint")return $.toString();if($ instanceof Error){let X={name:$.name,message:$.message,stack:$.stack};for(let G of Object.keys($))X[G]=$[G];if($.cause!==void 0)X.cause=$.cause;return X}if($!==null&&typeof $==="object"){if(Q.has($))return"[Circular]";Q.add($)}return $}}function t0(Q){try{return JSON.stringify(Q,RZ())}catch{return'"[Unserializable]"'}}function CZ(Q,Z){if(Z==="json")return t0({...Q.metadata,timestamp:Q.timestamp,level:Q.level,message:Q.message});let $=Object.keys(Q.metadata).length>0;return`${Q.timestamp} ${Q.level.toUpperCase()} ${Q.message}${$?` ${t0(Q.metadata)}`:""}`}function r0(Q,Z){let $=e1.indexOf(Q.level);if(Z.threshold===-1||$<Z.threshold)return;try{let X=CZ(Q,Z.format)+`
|
|
5
|
-
`;if($>=jZ)process.stderr.write(X);else process.stdout.write(X)}catch{}}async function Z0(Q){try{return await LZ(Q),!0}catch{return!1}}class $0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${W1()}/storage/logs`}consoleThreshold;redactedHeaders;constructor(Q){this.config=Q;this.consoleThreshold=a0(Q.console),this.redactedHeaders=new Set([...s0,...Q.redactHeaders??[]].map((Z)=>Z.toLowerCase()))}requestMetadata(Q){let Z=new URL(Q.url),$={method:Q.method,path:Z.pathname,userAgent:Q.headers.get("user-agent")??void 0},X=Q.headers.get("x-request-id");if(X)$.requestId=X;let G=this.config.requestFields??[];if(G.includes("url"))$.url=Q.url;if(G.includes("headers")){let Y={};Q.headers.forEach((K,H)=>{Y[H]=this.redactedHeaders.has(H)?"[redacted]":K}),$.headers=Y}return $}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((Q)=>{console.error("Log storage unavailable, file logging disabled",Q)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let Q=`${W1()}/storage`;if(!await Z0(Q))await Q0(Q);if(!await Z0(this.logsDirPath))await Q0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await Z0(this.logsDirPath))await Q0(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let $=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed($),this.fileSize=0,this.writerSize=0}let Z=(await _Z(this.logsDirPath)).sort().reverse()[0];if(Z){let $=Bun.file(`${this.logsDirPath}/${Z}`);if($.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Z}`,this.writer=$.writer(),this.writer.write(await $.text()),this.writer.write(`
|
|
6
|
-
`),this.writer.flush(),this.fileSize=$.size}if(!this.writer){let $=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${$}`;let X=Bun.file(`${this.logsDirPath}/${$}`);this.writer=X.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(Q,Z,$={}){if(!this.isReady)await this.boot();let X=k.getStore(),G={},Y={};if(X)Y={method:X.req.rawRequest.method,path:new URL(X.req.rawRequest.url).pathname},G=this.requestMetadata(X.req.rawRequest);let K={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:Q,message:Z,metadata:{...G,...$}};if(this.consoleThreshold!==-1)r0({timestamp:K.timestamp,level:Q,message:Z,metadata:{...Y,...$}},{threshold:this.consoleThreshold,format:this.config.consoleFormat});let H="";try{H=JSON.stringify(K)}catch(J){console.log("Error parsing log object",J)}try{let J=this.config.onLogCreated(K);if(J instanceof Promise)J.catch((W)=>console.error("Error in onLogCreated",W))}catch(J){console.error("Error in onLogCreated",J)}if(!this.writer)return;this.writerSize+=H.length,this.fileSize+=H.length;try{this.writer.write(H),this.writer.write(`
|
|
7
|
-
`),this.tryFlush()}catch(J){console.error("Error writing log",J)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class OZ extends K1{static getFacadeAccessor(){return $0}static debug(Q,Z){this.getFacadeRoot().log("debug",Q,Z)}static info(Q,Z){this.getFacadeRoot().log("info",Q,Z)}static notice(Q,Z){this.getFacadeRoot().log("notice",Q,Z)}static warning(Q,Z){this.getFacadeRoot().log("warning",Q,Z)}static error(Q,Z){this.getFacadeRoot().log("error",Q,Z)}static critical(Q,Z){this.getFacadeRoot().log("critical",Q,Z)}static alert(Q,Z){this.getFacadeRoot().log("alert",Q,Z)}static emergency(Q,Z){this.getFacadeRoot().log("emergency",Q,Z)}}class IZ{config;static token="redis";instance=null;connectingSince=null;downSince=null;replaceDelay=500;constructor(Q={}){this.config=Q}get client(){if(this.instance===null)return this.build();let Q=this.instance;if(this.isDown(Q,Date.now())){this.instance=null;try{Q.close()}catch{}return this.build()}return Q}set client(Q){this.instance=Q,this.connectingSince=null,this.downSince=null,this.replaceDelay=500}close(){let Q=this.instance;this.instance=null,this.connectingSince=null,this.downSince=null,this.replaceDelay=500,Q?.close()}build(){let Q=new(AZ())(this.config.url,this.config.options);if(this.instance=Q,this.downSince=null,this.connectingSince=null,typeof Q.connect==="function"){this.connectingSince=Date.now();let Z;try{Z=Promise.resolve(Q.connect())}catch($){Z=Promise.reject($)}Z.then(()=>{if(this.instance!==Q)return;this.connectingSince=null,this.replaceDelay=500},()=>{if(this.instance!==Q)return;this.connectingSince=null})}return Q}isDown(Q,Z){if(Q.connected!==!1||typeof Q.connect!=="function")return this.downSince=null,!1;if(this.connectingSince!==null){let $=(this.config.options?.connectionTimeout??1e4)+5000;if(Z-this.connectingSince<$)return!1;this.connectingSince=null}if(this.downSince??=Z,Z-this.downSince<this.replaceDelay)return!1;return this.replaceDelay=Math.min(this.replaceDelay*2,1e4),!0}}function AZ(){let Q=globalThis.Bun?.RedisClient;if(typeof Q!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return Q}var X0=new TextEncoder;function e0(Q){return`id: ${Q.seq}
|
|
8
|
-
data: ${JSON.stringify(Q.event)}
|
|
9
|
-
|
|
10
|
-
`}var NZ=5000,FZ=`: keepalive
|
|
11
|
-
|
|
12
|
-
`;function TZ(Q,Z=NZ){let $=null,X=!1,G=()=>{if(X)return;if($!==null)clearTimeout($);$=setTimeout(()=>{if($=null,X)return;try{Q.enqueue(X0.encode(FZ))}catch{Y();return}G()},Z)},Y=()=>{if(X=!0,$!==null)clearTimeout($);$=null};return G(),{touch:G,stop:Y}}function wZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function k4(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,Y=new ReadableStream({start(K){G=TZ(K)},async pull(K){try{let H=await $.next();if(H.done){G.stop(),K.close();return}X=H.value.seq,K.enqueue(X0.encode(e0(H.value))),G.touch()}catch(H){let J={type:"error",error:EZ(H)};G.stop(),K.enqueue(X0.encode(e0({seq:X+1,event:J}))),K.close()}},cancel(K){G.stop(),$.return?.(K)}});return new Response(Y,{status:Z,headers:wZ()})}var SZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function EZ(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&SZ.has(Z))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}
|
|
13
|
-
export{G0 as Ph,QQ as Qh,xZ as Rh,_0 as Sh,X8 as Th,I0 as Uh,G8 as Vh,Y0 as Wh,K0 as Xh,gZ as Yh,bZ as Zh,yZ as _h,J0 as $h,k1 as ai,mZ as bi,pZ as ci,K8 as di,F0 as ei,J8 as fi,H8 as gi,e as hi,g as ii,y1 as ji,iZ as ki,oZ as li,sZ as mi,tZ as ni,aZ as oi,m1 as pi,C0 as qi,eZ as ri,Q8 as si,AQ as ti,E0 as ui,NQ as vi,u1 as wi,d1 as xi,FQ as yi,m as zi,TQ as Ai,K1 as Bi,i0 as Ci,N1 as Di,J1 as Ei,q0 as Fi,i1 as Gi,n8 as Hi,k0 as Ii,o1 as Ji,g0 as Ki,w as Li,p as Mi,F1 as Ni,s as Oi,T1 as Pi,w1 as Qi,S1 as Ri,V1 as Si,s1 as Ti,t as Ui,t1 as Vi,z1 as Wi,E1 as Xi,a1 as Yi,m0 as Zi,d0 as _i,u0 as $i,DZ as aj,C4 as bj,_4 as cj,$0 as dj,OZ as ej,IZ as fj,e0 as gj,FZ as hj,TZ as ij,wZ as jj,k4 as kj};
|
|
14
|
-
|
|
15
|
-
//# debugId=5AB4A5E841CE059164756E2164756E21
|
package/dist/chunk-70qqpvd9.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{X as p,Y as AJ,Z as DJ,_ as PJ}from"./chunk-z97tptd1.js";import{pa as b,ta as T,ua as NJ}from"./chunk-bwg7genv.js";import"./chunk-s0z61m9j.js";import{Gg as xJ,Hg as k,Pg as IJ,Qg as MJ,Rg as FJ,qe as jJ}from"./chunk-bfhcx1ca.js";import"./chunk-ggmznkqs.js";import"./chunk-vw57atx4.js";import{Wh as ZJ,Xh as XJ,_h as QJ}from"./chunk-4fw84bh6.js";import{pj as LJ}from"./chunk-q8a7ncvs.js";import"./chunk-a4twd6qh.js";import"./chunk-hergje99.js";import"./chunk-vt0vybw8.js";import"./chunk-9q5xhb64.js";import"./chunk-t91x2k88.js";import"./chunk-5dhp90cx.js";import"./chunk-ke7d7j2y.js";import"./chunk-rczmh97n.js";import"./chunk-cbmne0wt.js";import"./chunk-r02em4jv.js";import"./chunk-n5g9a48h.js";import"./chunk-vbdy4k14.js";import"./chunk-vyp7d7xz.js";import{Hl as GJ}from"./chunk-px2a83jv.js";import"./chunk-rwe4bgt3.js";import{Zl as _J}from"./chunk-1hpedme7.js";import{$l as y}from"./chunk-pp34d463.js";import"./chunk-05k9201j.js";import{createHash as U2}from"crypto";import{join as d,resolve as TJ,sep as BJ}from"path";import{Duplex as gJ}from"stream";import{constants as E,createBrotliCompress as fJ,createGzip as mJ}from"zlib";var uJ=["br","gzip"],hJ=1024,cJ=5,pJ=19,dJ=6;function lJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function oJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...j]=Z.split(";"),H=X.trim().toLowerCase();if(H==="")continue;let W=1;for(let G of j){let U=G.indexOf("=");if(U===-1)continue;if(G.slice(0,U).trim().toLowerCase()==="q"){W=lJ(G.slice(U+1));break}}$.set(H,W)}return $}function m(J,$=uJ){let Z=oJ(J);if(!Z)return null;let X=Z.get("*"),j=null,H=0;for(let W of $){let G=Z.get(W)??X??0;if(G>H)j=W,H=G}return j}function nJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function iJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(nJ($.headers.get("Cache-Control"),"no-transform"))return!1;let j=$.headers.get("Content-Length");if(j!==null&&Number(j)<hJ)return!1;return!0}function aJ(J){let $=J==="br"?fJ({params:{[E.BROTLI_PARAM_QUALITY]:cJ,[E.BROTLI_PARAM_LGWIN]:pJ},flush:E.BROTLI_OPERATION_FLUSH}):mJ({level:dJ,flush:E.Z_SYNC_FLUSH});return gJ.toWeb($)}function rJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function s(J,$){if(!iJ(J.method,$))return $;let Z=new Headers($.headers);rJ(Z);let X=m(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let j;try{j=aJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(j),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as X2,stat as HJ}from"fs/promises";import{join as Q2}from"path";import{mkdir as F2,readFile as tJ,stat as N2,writeFile as A2}from"fs/promises";import{dirname as P2,join as sJ}from"path";import{promisify as e}from"util";import{brotliCompress as eJ,constants as R2,gzip as J2}from"zlib";var $2=".vite/static-assets.json";var JJ={br:".br",gzip:".gz"},Z2=["br","gzip"],S2=e(eJ),b2=e(J2);async function $J(J){let $;try{$=await tJ(sJ(J,$2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[j,H]of Object.entries(Z)){if(!Array.isArray(H))continue;X.files[j]=Z2.filter((W)=>H.includes(W))}return X}function u(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function WJ(J){let $=new Set;async function Z(X,j){let H;try{H=await X2(X,{withFileTypes:!0})}catch{return}for(let W of H){if(W.name.startsWith("."))continue;if(j&&W.name==="assets")continue;let G=Q2(X,W.name),U=W.isDirectory(),O=W.isFile();if(W.isSymbolicLink())try{let _=await HJ(G);U=_.isDirectory(),O=_.isFile()}catch{continue}if(O)$.add(G);else if(U&&!W.isSymbolicLink())await Z(G,!1)}}return await Z(J,!0),$}var j2="public, max-age=31536000, must-revalidate",H2="public, max-age=31536000, immutable";async function W2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=m(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let j=$+JJ[X];try{let H=await HJ(j);return H.isFile()?{encoding:X,path:j,size:H.size}:null}catch{return null}}async function YJ(J,$,Z={}){let X=Bun.file($),j=Z.encodings??[],H={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?H2:j2,"Accept-Ranges":"bytes"};if(j.length>0)H.Vary="Accept-Encoding";let W=await W2(J,$,j);if(W){let O=Bun.file(W.path);return new Response(O.stream(),{headers:{...H,"Content-Encoding":W.encoding,"Content-Length":String(W.size),ETag:`${u(O.lastModified)}-${W.encoding}`}})}let G=X.size;H.ETag=u(X.lastModified);let U=ZJ(J.headers.get("Range"));if(U){let O=XJ(U,G);if(!O)return jJ(G);return new Response(X.slice(O.start,O.end+1).stream(),{status:206,headers:{...H,"Content-Range":QJ(O.start,O.end,G),"Content-Length":String(O.length)}})}return new Response(X.stream(),{headers:{...H,"Content-Length":String(G)}})}import{stat as z2}from"fs/promises";var v="app/client.tsx";function OJ(J,$=b){let Z=J[v]?.file;if(!Z)return;return{module:T(Z,$),preload:P(J,v,$)}}function P(J,$,Z=b){let X=[],j=new Set,H=(W)=>{if(j.has(W))return;j.add(W);let G=J[W];if(!G?.file)return;X.push(T(G.file,Z));for(let U of G.imports??[])H(U)};return H($),X}function Y2(J,$,Z=b){let X=new Set(P(J,$,Z)),j=[],H=new Set,W=(U)=>{if(H.has(U))return;H.add(U);let O=J[U];if(!O)return;for(let _ of O.dynamicImports??[])if(!/(^|\/)node_modules\//.test(_)&&!j.includes(_))j.push(_);for(let _ of O.imports??[])W(_)};W($);let G=[];for(let U of j)for(let O of P(J,U,Z))if(!X.has(O))X.add(O),G.push(O);return G}function VJ(J,$){let Z=[],X=new Set,j=new Set,H=(W)=>{if(j.has(W))return;j.add(W);let G=J[W];if(!G)return;for(let U of G.imports??[])H(U);for(let U of G.css??[])if(!X.has(U))X.add(U),Z.push(U)};return H($),Z}function UJ(J,$=b){let Z=new Map;return(X)=>{if(!Z.has(X)){let j=`${X}${GJ}`,H=J[j]?.file;Z.set(X,H?{src:T(H,$),preload:P(J,j,$),dynamicPreload:Y2(J,j,$)}:void 0)}return Z.get(X)}}var zJ="x-gemi-build";function G2(J,$,Z,X){let j=Date.now(),H=function(V){return typeof V==="number"&&j-V>=0&&j-V<Z},W=function(V){try{let z=V?JSON.parse(V):null;return z&&typeof z==="object"&&!Array.isArray(z)?z:{}}catch{return{}}},G=function(V){let z={};for(let I in V)if(H(V[I]))z[I]=V[I];return z},U=function(V){let z=2166136261;for(let I=0;I<V.length;I++)z=Math.imul(z^V.charCodeAt(I),16777619);return(z>>>0).toString(36)},O=null,_={};try{O=window.sessionStorage,_=W(O.getItem(J))}catch{O=null}let F=J+":",N="",A="";try{let V=new URL($,window.location.href);N=U(new URL(window.location.href).origin),A=U(V.origin+V.pathname)}catch{}let C=null;try{let V=window.name;if(!A)C=null;else if(V==="")C={};else if(V.indexOf(F)===0){let z=W(V.slice(F.length)),I=z.m;C=z.o===N&&I&&typeof I==="object"&&!Array.isArray(I)?I:{}}}catch{C=null}if(X==="tidy"){try{let V=window.name;if(C===null||V.indexOf(F)!==0)return"ok";for(let z in C)if(H(C[z]))return"cooldown";window.name=""}catch{}return"ok"}if(H(_[$])||C&&H(C[A]))return"cooldown";if(!O&&!C)return"storage";if(!X)return"ok";if(O)try{let V=G(_);V[$]=j;let z=JSON.stringify(V);if(O.setItem(J,z),O.getItem(J)===z)return"ok"}catch{}if(C)try{let V=G(C);V[A]=j;let z=F+JSON.stringify({o:N,m:V});if(window.name=z,window.name===z)return"ok"}catch{}return"storage"}function KJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${G2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${X});export {}`}var O2=new RegExp(`^${xJ}/.+\\.m?js$`);function h(J){return O2.test(J)}function CJ(J){if(h(J))return new Response(KJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(k(J))return new Response("Not found",{status:404});return}var V2=`<!DOCTYPE html>
|
|
3
|
-
<html lang="en">
|
|
4
|
-
<head>
|
|
5
|
-
<meta charset="UTF-8" />
|
|
6
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
|
-
<title>Internal Server Error</title>
|
|
8
|
-
<style>
|
|
9
|
-
body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: grid; place-items: center; }
|
|
10
|
-
main { text-align: center; padding: 16px; }
|
|
11
|
-
h1 { font-size: 1.5rem; margin: 0 0 0.5rem; }
|
|
12
|
-
p { margin: 0; opacity: 0.7; }
|
|
13
|
-
</style>
|
|
14
|
-
</head>
|
|
15
|
-
<body>
|
|
16
|
-
<main>
|
|
17
|
-
<h1>Something went wrong</h1>
|
|
18
|
-
<p>Please try again later.</p>
|
|
19
|
-
</main>
|
|
20
|
-
</body>
|
|
21
|
-
</html>`;function c(J,$,Z){if(!Z)console.error(J);else try{Z(J instanceof Error?J:Error(String(J),{cause:J}))}catch(X){console.error(J),console.error(X)}if(y($))return new Response(JSON.stringify({error:LJ("server_error","Internal Server Error",500)}),{status:500,headers:{"Content-Type":"application/json"}});return new Response(V2,{status:500,headers:{"Content-Type":"text/html; charset=utf-8"}})}var g=_J(),K2=d(g,"app"),M=d(g,"dist"),B=d(M,"client");function x2(J){let $;try{$=decodeURIComponent(J)}catch{return null}let Z=TJ(B,"."+$.replace("/assets/assets","/assets"));return Z.startsWith(B+BJ)?Z:null}async function C2(J){try{return(await z2(J)).isFile()}catch{return!1}}async function x3(J,$){let Z=await import(`${M}/client/.vite/manifest.json`),X=await import(`${M}/server/.vite/manifest.json`),j=await NJ(`${M}/client`);process.env.ROOT_DIR=g,process.env.APP_DIR=K2,process.env.DIST_DIR=M;let H={},W={},G={},U={},O={},_=(Q,Y)=>`"${Q}": () => import("${Y}")`,F=[],N=J.getRequiredViews.call(J);for(let Q of["404",...J.getFlatComponentTree.call(J)]){let Y=X[`app/views/${Q}.tsx`];if(!Y?.file&&N[Q])throw DJ(Q,N[Q]);if(!Y?.file){console.log(`Server file not found for ${Q}`),console.log(Y);let L=Object.keys(X),D=`app/views/${Q}.tsx`;console.log(`${D} not found in server manifest`),console.log(L)}let K=await import(`${process.env.DIST_DIR}/server/${Y?.file}`);H[Q]=K.default,W[Q]=K.OpenGraph,G[Q]=K;let x=Z[`app/views/${Q}.tsx`];if(x?.css&&x?.css.length>0)U[Q]=x?.css;if(x)F.push(_(Q,T(x?.file,j))),O[Q]=P(Z,`app/views/${Q}.tsx`,j)}let A=`{${F.join(",")}}`,C=OJ(Z,j);if(!C)console.error(`Client manifest has no "${v}" entry \u2014 dist/client is incomplete, so documents will render but never hydrate.`);let V=Z["app/client.tsx"]?.css??[],z=(await Promise.all(V.map((Q)=>Bun.file(`${M}/client/${Q}`).text()))).join(`
|
|
22
|
-
`),I=UJ(Z,j),l=U2("sha256").update(await Bun.file(`${M}/client/.vite/manifest.json`).text()).digest("base64url").slice(0,12),o=new Map,RJ=(Q)=>{let Y=o.get(Q);if(!Y)Y=Bun.file(`${M}/client/${Q}`).text(),o.set(Q,Y);return Y},SJ=async(Q,Y)=>{let K=new Set;for(let L of Y?[Y,...Q]:Q)for(let D of VJ(Z,`app/views/${L}.tsx`))K.add(D);let x=await Promise.all([...K].map(async(L)=>({id:L,content:await RJ(L)})));return p(Y?x:[{content:z},...x])},bJ=await WJ(B),n=new Map;for(let[Q,Y]of Object.entries((await $J(B))?.files??{})){let K=TJ(B,Q);if(K.startsWith(B+BJ))n.set(K,{immutable:!0,encodings:Y})}async function qJ(Q){let{pathname:Y}=new URL(Q.url);if(y(Y))return await R(Q,Y);let K=x2(Y),x=k(Y),L=!x&&K!==null&&bJ.has(K),D=x||Y.startsWith("/.well-known")||L;if(L&&!(await i(Q)).publicFiles)return await R(Q,Y);if(D){if(!K||!await C2(K)){if(x&&!h(Y)&&(await i(Q)).assetRoutes)return await R(Q,Y);return CJ(Y)??await R(Q,Y)}try{return await YJ(Q,K,n.get(K))}catch(w){return J.onException?.(w),new Response("Not found",{status:404})}}let q=await R(Q,Y);if(Y.endsWith(".json"))try{q.headers.set(zJ,l)}catch{}return q}async function i(Q){try{return await J.staticFiles?.(Q)??{publicFiles:!0,assetRoutes:!1}}catch{return{publicFiles:!1,assetRoutes:!0}}}async function R(Q,Y){let K=J.fetch.bind(J);try{let x=await K(Q);if(x instanceof Response)return x;else{let L=[];return L.push({content:z}),await x({getStyles:async(q,w)=>{let r=q??["404"];if(w?.static)return SJ(r,w.layout);for(let vJ of r){let kJ=Z[`app/views/${vJ}.tsx`];for(let t of kJ?.css??[]){let yJ=Bun.file(`${process.env.DIST_DIR}/client/${t}`);L.push({id:t,content:await yJ.text()})}}return p(L)},clientEntry:C,modulePreloadManifest:O,loaders:A,viewImportMap:H,viewModules:G,ogMap:W,cssManifest:U,assetBase:j,resolveIsland:I,buildId:l})}}catch(x){return c(x,Y,J.onException)}}let wJ=(process.env.GEMI_COMPRESSION??"auto").toLowerCase()!=="off",a=IJ(process.env.GEMI_TRUST_PROXY),EJ=FJ(process.env),S=J.sockets();if(S&&a.kind==="none"&&!EJ)console.warn("[gemi] Broadcast sockets: GEMI_TRUST_PROXY is not set, so a socket's address is its TCP peer. Behind a proxy or load balancer every client shares the proxy's address, and broadcast.maxConnectionsPerIp caps the whole app per process. Set GEMI_TRUST_PROXY (see forwardedFor) or raise that limit.");let f=Bun.serve({maxRequestBodySize:10737418240,fetch:async(Q,Y)=>{if(MJ(Q.headers,Y.requestIP(Q)?.address??null,a),J.applyTrustedClientIp(Q),S?.matches(Q))return S.upgrade(Q,Y);let K=await $(Q,(x)=>J.withGlobalMiddleware(x,qJ,(L)=>c(L,new URL(x.url).pathname,J.onException)));return wJ?s(Q,K):K},idleTimeout:PJ(),port:process.env.PORT||5173,websocket:S?.websocket});return await S?.start(f),AJ({port:f.port,rootDir:g}),f}export{x3 as httpProd};
|
|
23
|
-
|
|
24
|
-
//# debugId=9AFBBEBC66F47A1864756E2164756E21
|
package/dist/chunk-9mhr0kwd.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{le as o}from"./chunk-wfwpjx25.js";import{me as i}from"./chunk-h19qtrg9.js";import{yk as t}from"./chunk-ke7d7j2y.js";import{yl as r}from"./chunk-n5g9a48h.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
|
|
3
|
-
export{n as bb};
|
|
4
|
-
|
|
5
|
-
//# debugId=9924A3C74C50796164756E2164756E21
|
package/dist/chunk-ht5mq6ev.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$b as b3,Cc as B3,Pc as P3,Wb as E3,_b as K2,dc as N3,ic as e,wc as F3,zd as I3}from"./chunk-v325k8qj.js";import{Gd as i2,Id as B2,Ld as i3,Md as l3,Nd as N$,Pd as j$}from"./chunk-nqg7hdy8.js";import{Sd as h3,Xd as m3,Zd as u3,ee as x,fe as d3,ge as c3,ie as p3,je as _$}from"./chunk-c6v3sjvh.js";import{me as P}from"./chunk-h19qtrg9.js";import{$e as J2,Ce as R3,Dg as g2,Eg as f2,Ge as C$,Gf as Z2,Ig as w2,Je as U$,Jg as $$,Kg as G2,Lg as Z$,Me as J$,Mf as H2,Mg as z$,Nf as u2,Ng as v2,Of as M,Og as a,Rf as V$,Rg as T$,Sf as Y$,Sg as L2,Tf as K$,Tg as p2,Vf as w,We as F$,Xe as l2,Yg as Q$,Zg as H$,af as X2,dh as x$,gg as e2,rg as a2,sf as d2,tg as n,xg as r2,ye as l,yg as r3,ze as X$,zg as e3}from"./chunk-bfhcx1ca.js";import{Ji as o2,Zi as J3,cj as A$,dj as P2,ej as N2,fj as z2,ri as p,ti as m}from"./chunk-4fw84bh6.js";import{mj as t3}from"./chunk-q8a7ncvs.js";import{xj as g}from"./chunk-a4twd6qh.js";import{Dj as c2}from"./chunk-hergje99.js";import{Gj as B$,Hj as n2,Kj as F2,Lj as s2,Oj as I$}from"./chunk-vt0vybw8.js";import{ak as s3,fk as o3}from"./chunk-9q5xhb64.js";import{vk as g3,xk as u}from"./chunk-5dhp90cx.js";import{yk as A}from"./chunk-ke7d7j2y.js";import{Ek as O$}from"./chunk-rczmh97n.js";import{sl as t2}from"./chunk-g5j5hx6a.js";import{Cl as y,zl as U2}from"./chunk-vbdy4k14.js";import{Ll as m2}from"./chunk-rwe4bgt3.js";import{$l as a3}from"./chunk-pp34d463.js";var M$="mcp",k$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends e{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class v extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $3=/^[A-Za-z0-9_-]{1,64}$/,R$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z3=4000,k=1e5,E$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function H8($){return L3.get($)}class i{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=v$(z.files),this.featureOn=z.featureOn??X2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,b$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(Y3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){D2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new v(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new v(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!W2(X))throw new v(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let V=Q.value,H={caller:$,req:$.req,tool:K,input:V,ctx:G},U=await this.fillPath(Y,H),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${U}`));if(I!==K.url)throw new O(`"${Z}" has nothing at ${U}.`,404);let J={};for(let _ of Y.jsonKeys)if(V[_]!==void 0)J[_]=V[_];let N,B="";if(Y.fileFields.length>0)N=await this.formData(Y,J,H);else if(K.method==="GET")B=n$(J);else if(Y.jsonKeys.length>0)N=J;let T=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(H)):void 0,j={...T?{credentials:T}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},C;try{let _=B?`${U}?${B}`:U;C=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,_,N,j):await this.dispatcher.dispatchAs($.req,K.method,_,N)}catch(_){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,_),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await U3(Z,C);return await this.project(Y,H,C)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(R$)].map(([,F,S])=>({name:F,modifier:S})),Q=X.params??{};for(let F of K)if(!(F.name in Q))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,S]of Object.entries(Q)){if(!K.some((h)=>h.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(Q3(S))d$(z,`params.${F}`,S);else K3(z,`params.${F}`,S)}let V=[],H;if(X.input){if(H=X.input.toJSONSchema(),H.type!=="object"||!H.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);V=Object.keys(H.properties)}let U=Object.entries(X.files??{}).map(([F,S])=>({name:F,binder:S}));for(let F of U)K3(z,`files.${F.name}`,F.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let I=V3(z,G,X.annotations);if(U.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let J={},N=(F,S)=>{if(F in J)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);J[F]=S},B=new Map,T=new Map;for(let F of K){let S=Q[F.name];if(S==="input"){let h=p.string().describe(`The ":${F.name}" segment of the url.`);N(F.name,F.modifier==="?"||F.modifier==="*"?h.optional():h)}else if(Q3(S)){let h=S.as??F.name;N(h,S.input),T.set(F.name,{key:h,param:S})}else B.set(F.name,S)}let j={};for(let F of U)if(F.binder==="input")N(F.name,p.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[F.name]=this.remoteFileSchema();let C=[...Object.keys(J),...U.map((F)=>F.name)];for(let F of new Set(C))if(V.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let _=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:H3(X.input,H,p.object(J)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),r=!U.every((F)=>F.binder==="input")?null:U.length===0?_:Object.freeze({..._,inputSchema:H3(X.input,H,p.object(i$(J,Object.keys(j))),j)});return{kind:"route",descriptor:_,remote:r,params:K,paramBinders:B,modelParams:T,fileFields:U,jsonKeys:V,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let V of Object.keys(Y))if(!W.includes(V))K.push(`a file has no field "${V}"`);for(let V of W){let H=Y[V];if(H===void 0||H===null){if(V==="name"||V==="mimeType")K.push(`a file needs "${V}"`);continue}if(typeof H!=="string")K.push(`a file's "${V}" must be a string`);else Q[V]=H}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:V3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!W2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let V=G.signal??new AbortController().signal;return X3(X,Y.value,W3(G3(X,Q,V)))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return W2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(D2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return L3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(_,_2)=>{if(!W.progress)return;let r;try{r=$.meta.remote?.progress?$.meta.remote.progress(_,_2):f$(_,_2)}catch(F){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,F);return}if(r)W.progress(r)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z3(this.runNative($,{...K,ctx:G},G),Q)}let V=$.meta.remote,H=await this.bind($,"the remote context",()=>V.context(K));if(typeof H!=="object"||H===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,H),new O(`"${X}" failed on the server.`,500);let U=$.tool.timeoutMs,I=[...W.signal?[W.signal]:[],...U!==void 0?[AbortSignal.timeout(U)]:[]],J=I.length===0?new AbortController().signal:I.length===1?I[0]:AbortSignal.any(I),N=G3($,H,J);if(!W.approved&&W2($)&&await X3($,K.input,W3(N)))throw new v(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let B;try{B=await z3(this.runNative($,{...K,ctx:N},N),Q,J)}catch(_){if(J.aborted&&_===J.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${U} ms.`,504)}if(_ instanceof O)throw _;if(_ instanceof e||_ instanceof v)throw new O(_.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,_),new O(`"${X}" failed on the server.`,500)}let T=(_)=>{return console.error(`[gemi/mcp] "${X}" ${_}`),new O(`"${X}" failed on the server.`,500)};if(F3(B))throw T("answered a job handle, and a remote call has no background jobs.");let j=B;if($.descriptor.outputSchema){let _=$.descriptor.outputSchema.safeParse(j);if(_.ok===!1)throw T(`answered what its output schema refuses: ${_.errors.join(", ")}`);j=_.value}if(j===void 0)return null;if(typeof j==="string")return j.length>k?`${j.slice(0,k)}\u2026 [cut at ${k} of ${j.length} characters]`:j;let C=JSON.stringify(j);if(C!==void 0&&C.length>k)return`${C.slice(0,k)}\u2026 [cut at ${k} of ${C.length} characters]`;return j}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let V=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${V}`,"");continue}W=W.replace(V,l$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,V]of Object.entries(Z))O2(K,Q,V);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(H)=>new O(`"${Z}" of "${$}" ${H}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!g$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!h$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let H=W.data.replace(/\s+/g,"");if(Math.floor(H.length*3/4)-u$(H)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(H.length%4!==0||!m$.test(H))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(H,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let V;try{V=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(V.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let H=await J3(V.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!H.ok)throw G(`could not be fetched: ${V.host} answered ${H.status}.`);let U=await H.arrayBuffer();return new File([U],W.name,{type:W.mimeType})}catch(H){if(H instanceof O)throw H;throw G(`could not be fetched from ${V.host}: ${H instanceof Error?H.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(M$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!k$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await U3(G,z);let X=(U,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${G}" ${U}`);else console.error(`[gemi/mcp] "${G}" ${U}`,I);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let V=Q;if($.result)try{V=await $.result(Q,Z)}catch(U){throw X("failed in its result projection:",U)}if(W){let U=W.safeParse(V);if(U.ok===!1)throw X(`answered what its output schema refuses: ${U.errors.join(", ")}`);V=U.value}if(V===void 0)return null;let H=JSON.stringify(V);if(H!==void 0&&H.length>k)return`${H.slice(0,k)}\u2026 [cut at ${k} of ${H.length} characters]`;return V}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof e)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function b$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function y$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!y$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function f$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function G3($,Z,z){let G=$.descriptor.name,W=`mcp_${crypto.randomUUID()}`,X=`mcp_call_${crypto.randomUUID()}`,Y=(Q)=>async()=>{throw new e(`"${G}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},K={put:Y("attachment store"),get:Y("attachment store"),read:Y("attachment store"),file:Y("attachment store")};return{context:Z,body:{},runId:W,toolCallId:X,signal:z,step:1,depth:0,resumed:!1,attachments:K,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:Y("agent run to nest a sub-agent in"),generateImage:Y("attachment store to put an image in"),editImage:Y("attachment store to put an image in"),generate:(Q)=>I3({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:G,runId:W,toolCallId:X}}),jobs:B3({jobs:void 0,threadId:void 0,runId:W,toolCallId:X,toolName:G,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:N3().meter}}function W2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function D2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Y3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var w$=10485760;function v$($){let Z=$?.maxBytes??w$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function g$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var h$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,m$=/^[A-Za-z0-9+/]*={0,2}$/;function u$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function d$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var c$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function p$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function V3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?p$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!c$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function H3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,V])=>[Q,V.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let V=[],H={};if($){let I=$.safeParse(Q);if(I.ok===!1)V.push(...I.errors);else H={...I.value}}let U=z.safeParse(Q);if(U.ok===!1)V.push(...U.errors);else H={...H,...U.value};for(let[I,J]of Object.entries(G)){let N=Q[I];if(N===void 0){V.push(`"${I}" is required`);continue}let B=J.safeParse(N);if(B.ok===!1)V.push(...B.errors.map((T)=>`${I}: ${T}`));else H[I]=B.value}return V.length>0?{ok:!1,errors:V}:{ok:!0,value:H}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let V=K(Q);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function i$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function l$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function O2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function n$($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function U3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!E$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>k)return`${W.slice(0,k)}\u2026 [cut at ${k} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>Z3?`${z.slice(0,Z3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as t$,randomBytes as s$,timingSafeEqual as o$}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class a${options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${s$(32).toString("base64url")}`}static hash($){return t$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&o$(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as y3,randomBytes as j3}from"crypto";async function A2($,Z){let z=r$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function r$(){try{let $=y();return $.bound(l)?$.make(l):null}catch{return null}}var x2=["2026-07-28"],Y2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...Y2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",D={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function R($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _3($){if(Array.isArray($))throw new L(D.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(D.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new L(D.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(D.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new L(D.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function q($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as e$,timingSafeEqual as $6}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=O3($,Z,X);if(K.length!==Q.length||!$6(K,Q))return null;let V;try{V=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof V!=="object"||V===null)return null;if(typeof V.exp!=="number"||V.exp<=G)return null;return V}function O3($,Z,z){return e$("sha256",K2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",A3="gemi.mcp.session.v1",Z6=86400000,x3=600000,C3="gemi_approval",b2=2000,z6={limit:600,window:60},G6={limit:30,window:60};class $2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=Y6(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");if(this.resolvers=G,K2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??z6,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new E3,this.approvalTimeoutMs=Z.approvalTimeoutMs??x3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??X2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(Z.host!==this.endpoint.host)return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return f(R(null,new L(D.InvalidRequest,"Origin not allowed.")),403);let G=z?X6(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return S3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await W6($,this.maxBodyBytes))}catch(Y){if(Y instanceof V2)return f(R(null,new L(D.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return f(R(null,new L(D.ParseError,"Parse error.")),400)}let X=new m($,{},"api",this.endpoint.pathname);return await g.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=q(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return f(R(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),f(R(null,new L(D.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let N=this.session($,z),B=this.pending.get(String(W.message.id));if(B&&B.session===N.id)this.pending.delete(String(W.message.id)),B.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=q(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(N,B)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:N,signal:B}),T3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(D.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let V=this.session($,z),H=$.headers.get("mcp-protocol-version");if(H!==null&&H!==V.state.v)throw new L(D.InvalidRequest,`MCP-Protocol-Version ${H} is not the session's ${V.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let N=K.requestId;this.inflight.get(`${V.id}:${String(N)}`)?.abort()}return new Response(null,{status:202})}let U=`${V.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(U,I);let J=AbortSignal.any([I.signal,$.signal]);try{return await this.respond(Y,async(N,B)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:V.state,sessionId:V.id},stream:N,signal:B}),T3(K)||Q6(this.registry,Y,V.state),J,()=>this.inflight.delete(U))}catch(N){throw this.inflight.delete(U),N}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(D.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(D.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Y2.includes(G)?G:Y2[0],X=q(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q3(X.elicitation),p:Q2(z),exp:Date.now()+Z6},K=k2(A3,"gms1",Y);return f({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(D.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(A3,"gms1",z);if(!G||G.p!==Q2(Z))throw new L(D.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new L(D.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new L(D.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||D3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new L(D.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,N)=>{G.outcome="denied",G.reason=J,G.message=N},K=(J,N,B)=>{if(G.outcome="error",G.message=J,N!==void 0)G.status=N;if(B!==void 0)G.error=B},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(D.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let B=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(B),this.toolResult($,{content:[{type:"text",text:B}],isError:!0})}if($.era.modern&&q($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let B=await this.approval($,Q,z,Y,G);if(B.kind==="answer")return B.result;G.approved=!0}}let V=V6($),H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,...V?{progress:V}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof v){let B=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,B),new L(D.InvalidParams,B)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let N=`"${Z}" failed on the server.`;return K(N,void 0,J),this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}let U=typeof H==="string"?H:JSON.stringify(H??null),I=Q.outputSchema&&($.era.modern||q(H))?{structuredContent:H}:{};return G.outcome="ok",this.toolResult($,{content:[{type:"text",text:U}],...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=H6(Z,z),Y=(I,J="approval-declined")=>{return G(J,I),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:I}],isError:!0})}},K=(I,J)=>{return G(I,J.message),J};if($.era.modern){let I=q($.params._meta)?$.params._meta:{},J=q(I[q2])?I[q2]:{},N=q($.params.inputResponses)?$.params.inputResponses:null,B=$.params.requestState,T=K6(z);if(N&&B!==void 0){let C=R2(E2,"grs1",B);if(!C||C.p!==Q2($.principal)||C.t!==Z.name||C.a!==T)throw K("approval-invalid",new L(D.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(C.n,C.exp))throw K("approval-replayed",new L(D.InvalidParams,"requestState has already been used."));return M3(N[C3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q3(J.elicitation))throw K("approval-unavailable",new L(D.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:Q2($.principal),t:Z.name,a:T,n:j3(16).toString("base64url"),exp:Date.now()+x3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",j),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let V=`gemi-approval-${j3(12).toString("base64url")}`,H=Q.sessionId,U=await new Promise((I)=>{let J=setTimeout(()=>{this.pending.delete(V),I(null)},this.approvalTimeoutMs),N=(B)=>{clearTimeout(J),I(B)};this.pending.set(V,{session:H,resolve:N}),$.signal.addEventListener("abort",()=>{this.pending.delete(V),N(null)}),$.stream.send({jsonrpc:"2.0",id:V,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return U&&!U.error&&M3(U.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return f({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(R($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(R($.id,new L(D.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return f(R(null,new L(D.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R3(new m($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,G6);return z===null?null:k3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:k3(Z)}}class f3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
3
|
-
data: ${JSON.stringify($)}
|
|
4
|
-
|
|
5
|
-
`))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class V2 extends Error{}async function W6($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new V2;W.push(K)}return Buffer.concat(W).toString("utf8")}function f($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function S3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function X6($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function Y6($){let Z;try{Z=new URL($)}catch{throw Error(`route.mcp.remote.url: "${$}" is not a URL.`)}let z=Z.hostname==="localhost"||Z.hostname==="127.0.0.1"||Z.hostname==="[::1]";if(Z.protocol!=="https:"&&!(Z.protocol==="http:"&&z))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if(Z.search||Z.hash||Z.username||Z.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if(Z.pathname==="/"||Z.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return Z}function Q2($){return y3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function K6($){return y3("sha256").update(b3($??{})).digest("base64url")}function q3($){if(!q($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function T3($){let Z=q($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function Q6($,Z,z){if(Z.method!=="tools/call"||!z.e)return!1;let G=Z.params?.name;return typeof G==="string"&&$.descriptors({names:[G]})[0]?.requiresApproval===!0}function V6($){let z=(q($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function H6($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
|
|
6
|
-
|
|
7
|
-
Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function M3($){return q($)&&$.action==="accept"&&q($.content)&&$.content.approve===!0}function k3($){return f(R(null,new L(D.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function U6($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=J6($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y2($);return}let G;try{if(G=Z.locks?.()??N6(),$.onOneServer){let W=Math.floor((Z.now??Date.now())/60000);if(!await G.store.advance(`gemi:cron-tick:${$.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${$.name}; skipped it:`,W);return}if(z===void 0){await y2($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y2($,W))}catch(W){if(W instanceof g3)console.error(`Cron job ${$.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,W);else console.error(`Could not take the withoutOverlapping lock of cron job ${$.name}:`,W)}}var w3=300000;function J6($){if(!$)return;if($===!0)return w3;return $.expiresAfter??w3}var v3;function N6(){return v3??=new u(new h3),v3}async function y2($,Z){try{await $.onTick.call($)}catch(z){console.error(`Error executing cron job ${$.name}:`,z)}try{await $.callback.call($,Z)}catch(z){console.error(`Error in cron job ${$.name}:`,z)}try{await $.onComplete.call($)}catch(z){console.error(`Error completing cron job ${$.name}:`,z)}}class d{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor($){this.resolved=$.jobs}get jobs(){return[...this.resolved]}useJobs($){this.resolved=$}useLocks($){this.locks=$}start($=(Z)=>Z()){if(this.stopped=!1,this.resolved.length===0)return;let Z=globalThis.__gemiCronJobs??=new Map,z=new Map;for(let G of this.resolved){let W=new G;if(!W.name){console.error(`Cron job must have a name \u2014 ${G.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let X=z.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${G.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}z.set(W.name,G.name||"an anonymous class"),Z.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(W.name,()=>$(()=>U6(W,{locks:K})))});Z.set(W.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let $ of this.handles)$.stop();this.handles=[]}async drain($=1/0){this.stop();let Z,z=new Promise((G)=>{if($!==1/0)Z=setTimeout(G,$)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((G)=>G.done)),z]),clearTimeout(Z),{unfinished:[...this.inFlight.values()].map((G)=>({...G.tick}))}}get running(){return this.inFlight.size}track($,Z){let z={},G=Promise.resolve().then(Z).finally(()=>this.inFlight.delete(z));return this.inFlight.set(z,{tick:{name:$,startedAt:new Date},done:G}),G}}import{isMainThread as F6}from"worker_threads";var B6=100,P6=($)=>Math.min(B6,Math.floor($/10));class I6 extends P{register(){this.app.singleton(x,()=>new x(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(u,()=>this.app.make(x).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=A(m3(),$);if($.jobs===void 0)this.app.make(x).useJobs(await i3(Z));if($.workflows===void 0){let G=await l3(z);if(G.length>0)this.app.make(x).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(x))return;let Z=this.app.make(x);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running queued job(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-P6(z)));if(G.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+G.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function l8($){if(_6($),Bun.env.NODE_ENV!=="production")return D6($);if(n3($))return;if(!d3())return;if(!$.bound(x))return;$.make(x).start()}function n3($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof u3}function L6($){if(n3($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(x))return!1;try{return!$.make(x).durable}catch{return!1}}function _6($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||p3())return;if(process.env.ROOT_DIR===void 0||!F6)return;if(c3()){if(!L6($))return;console.warn('[gemi] GEMI_QUEUE_CLAIM=off is ignored: the memory queue driver keeps jobs in the process that dispatched them, so no worker could run them. This server runs its own jobs. Use a driver other processes can read, such as "database", to hand jobs to `gemi queue:work`.')}else if(Z.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${Z}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function D6($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(x))$.make(x).start()}var O6=new Set,j6={refusal:null,apply:($)=>$,carried:null};async function G$($){let Z=y(n);if(Z.config.global.length===0)return j6;let{pathname:z}=new URL($.url),G=a3(z),W=new m($,{},G?"api":"view","");return await g.run(W,async()=>{let X=g.getStore(),{headers:Y,cookies:K}=X,Q=(V)=>{if(!g2(V)){let U=v2(V,Y,K);return G?U:A6(U,z)}let H=new Headers(Y);return H.delete("Set-Cookie"),v2(V,H,O6)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(V){let H=!G&&z.endsWith(".json");if(V?.kind===t3){let U=G?z$(V.payload.api):H?$$(V.payload.viewData??V.payload.api):w2(V.payload.view);return{refusal:Q(U),apply:Q,carried:null}}if(s3(V)&&(G||H))return{refusal:Q(Z$()),apply:Q,carried:null};if(o3(V)){console.error(V);let U=G||H?r3():w2(e3());return{refusal:Q(U),apply:Q,carried:null}}throw V}finally{X.destroy()}})}function A6($,Z){if(!g2($)||$.headers.getSetCookie().length===0)return $;try{return f2($.headers,Z),$}catch{let z=new Headers($.headers);return f2(z,Z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}var x6=120,C6=2000,S6=3;class s{manager;application;static token="broadcast.sockets";server=null;sockets=new Set;byTopic=new Map;topicReady=new Map;perIp=new Map;perUser=new Map;connections=0;revocationSeq=0;revokedAt=new Map;closing=!1;closed=null;onAllClosed=null;startPromise=null;constructor($,Z){this.manager=$;this.application=Z}get config(){return this.manager.config}matches($){try{return new URL($.url).pathname===this.config.path}catch{return!1}}get size(){return this.sockets.size}start($){return this.server=$,this.startPromise??=this.manager.start((Z,z)=>this.deliver(Z,z),{onGap:()=>this.onGap(),onRevoke:(Z)=>this.applyRevocation(Z)}).catch((Z)=>{this.startPromise=null,console.error("[gemi] The broadcast driver could not start; events reach no socket.",Z)}),this.startPromise}upgrade($,Z){return this.run(()=>this.tryUpgrade($,Z))}async tryUpgrade($,Z){if(this.closing||m2())return b(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return b(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(H2))return b(400,`Open the socket with the "${H2}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return b(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return b(503,"Too many connections.",{"Retry-After":"10"});let W=k6($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return b(429,"Too many connections from this address.",{"Retry-After":"30"});let X=this.reserve(W),Y=!1;try{let K=await this.authenticate($,Z,X);return Y=K===void 0,K}finally{if(!Y)this.release(X)}}async authenticate($,Z,z){let G=await G$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||m2())return b(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let H=new m($,{},"api",this.config.path);X=await g.run(H,async()=>{let U=g.getStore();try{return await Q$(H)}finally{U.destroy()}},W)}catch(H){return console.error("[gemi] Resolving the session of a socket upgrade failed.",H),b(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=M6(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return b(429,"Too many connections for this user.",{"Retry-After":"30"});if(Y)z.userId=Y,this.perUser.set(Y,(this.perUser.get(Y)??0)+1);let K=K$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:Y$(K),request:{url:$.url,headers:[...$.headers]},carried:W,userId:Y,ip:z.ip,subs:new Map,topics:new Map,rate:{windowStart:Date.now(),subs:0,pings:0},reservation:z,closing:!1,closed:!1};if(!Z.upgrade($,{headers:{"Sec-WebSocket-Protocol":H2},data:Q}))return b(400,"The WebSocket upgrade failed.");return}checkOrigin($){let Z=$.headers.get("origin"),z=Boolean($.headers.get("cookie"));if(!Z)return z?"A socket that carries cookies must send an Origin header.":!0;return this.originAllowed(Z,$)?!0:"This origin may not open a socket."}originAllowed($,Z){let z;try{z=new URL($)}catch{return!1}if(z.protocol!=="https:"&&z.protocol!=="http:")return!1;let G=Z.headers.get("host");if(G&&z.host.toLowerCase()===G.toLowerCase())return!0;for(let W of[process.env.APP_URL,process.env.HOST_NAME,...this.config.allowedOrigins])if(W&&q6(W.trim(),z))return!0;return!1}reserve($){if(this.connections++,$)this.perIp.set($,(this.perIp.get($)??0)+1);return{ip:$,userId:null}}release($){this.connections--,W$(this.perIp,$.ip),W$(this.perUser,$.userId)}get websocket(){return{open:($)=>$.data.hub.onOpen($),message:($,Z)=>$.data.hub.onMessage($,Z),close:($)=>$.data.hub.onClose($),...this.socketOptions()}}socketOptions(){return{maxPayloadLength:this.config.maxInboundMessageBytes,idleTimeout:this.config.idleTimeout,backpressureLimit:this.config.backpressureLimit*2,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1}}onOpen($){let Z=$.data;if(this.closing){this.sayBye($);return}this.sockets.add($),t($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(M.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(M.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(M.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))t($,{op:"pong"});return;case"sub":this.subscribe($,z).catch((G)=>{if(console.error("[gemi] A socket subscription failed.",G),typeof z.id==="string"&&$.data.subs.has(z.id)){let W=$.data.subs.get(z.id);if($.data.subs.delete(z.id),W.topic&&!$.data.closed)this.leave($,W.topic);if(!$.data.closed)E($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(M.UnsupportedData,"Unknown op.")}}onClose($){let Z=$.data;if(Z.closed)return;Z.closed=!0;for(let[,z]of Z.subs)if(z.topic)this.leave($,z.topic);if(Z.subs.clear(),this.sockets.delete($),Z.reservation)this.release(Z.reservation),Z.reservation=null;if(this.closing&&this.sockets.size===0)this.onAllClosed?.()}rateWindow($){let Z=$.data.rate,z=Date.now();if(z-Z.windowStart>=this.config.subscribeRate.windowMs)Z.windowStart=z,Z.subs=0,Z.pings=0;return Z}countSub($){let{limit:Z}=this.config.subscribeRate,z=this.rateWindow($);if(z.subs++,z.subs>Z*2)return console.warn("[gemi] Socket closed for sending too many subscribe frames (1008)."),$.close(M.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=x6)return!0;return $.close(M.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!u2.test(G)){$.close(M.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return E($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!T6(Y))return E($,G,"invalid");if(z.subs.has(G))return E($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return E($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),E($,G,"unknown_channel");let Q;for(let V=1;;V++){let H=this.revocationSeq;if(Q=await this.authorize($,K),z.closed||z.subs.get(G)!==K)return;if(Q.ok!==!0)break;if((this.revokedAt.get(Q.topic)??0)<=H)break;if(V>=S6)return z.subs.delete(G),E($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),E($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(V){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,V),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);E($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;t($,{op:"subscribed",id:G,t:Q.topic})}authorize($,Z){let z=$.data,G=this.manager.channels;if(!G)return Promise.resolve({ok:!1,code:"unknown_channel"});return this.run(()=>G.authorize(new Request(z.request.url,{headers:z.request.headers}),Z.pattern,Z.params,{carried:z.carried}))}unsubscribeFrame($,Z){let z=Z.id;if(typeof z!=="string"||!u2.test(z)){$.close(M.UnsupportedData,"An unsub needs an id.");return}let G=$.data.subs.get(z);if(!G)return;if($.data.subs.delete(z),G.topic)this.leave($,G.topic)}join($,Z){let z=$.data,G=z.topics.get(Z)??0;if(z.topics.set(Z,G+1),G===0){$.subscribe(Z);let W=this.byTopic.get(Z);if(!W){W=new Set,this.byTopic.set(Z,W);let X=Promise.resolve().then(()=>this.manager.topicAdded(Z));this.topicReady.set(Z,X),X.catch(()=>{if(this.topicReady.get(Z)===X)this.topicReady.delete(Z)})}W.add($)}return this.topicReady.get(Z)??Promise.resolve()}leave($,Z){let z=$.data,G=z.topics.get(Z)??0;if(G>1){z.topics.set(Z,G-1);return}if(z.topics.delete(Z),!z.closed)$.unsubscribe(Z);let W=this.byTopic.get(Z);if(!W)return;if(W.delete($),W.size>0)return;this.byTopic.delete(Z),this.topicReady.delete(Z),Promise.resolve().then(()=>this.manager.topicRemoved(Z)).catch((X)=>console.error(`[gemi] The broadcast driver could not unsubscribe from "${Z}".`,X))}deliver($,Z){let z=this.byTopic.get($);if(!z||!this.server)return;let G=this.config.backpressureLimit;for(let W of z)if(!W.data.closing&&W.getBufferedAmount()>G)console.warn(`[gemi] Socket closed for backpressure (1013) on "${$}".`),h2(W,M.TryAgainLater,"Too far behind; reconnect.");this.server.publish($,Z)}onGap(){this.sendAll({op:"gap"});for(let $ of this.byTopic.keys()){let Z=Math.floor(Math.random()*C6);setTimeout(()=>{if(!this.closing)this.applyRevocation({topic:$})},Z).unref?.()}}applyRevocation($){if("user"in $){for(let W of this.sockets)if(W.data.userId===$.user&&!W.data.closing)h2(W,M.Revoked,"Revoked.");return}let Z=$.topic,z=++this.revocationSeq;this.revokedAt.set(Z,z);let G=this.byTopic.get(Z);if(!G)return;for(let W of G)this.reauthorize(W,Z,z)}async reauthorize($,Z,z){let G=$.data,W=[...G.subs].filter(([,Y])=>Y.topic===Z);if(W.length===0)return;$.unsubscribe(Z);let X=await Promise.all(W.map(([,Y])=>this.authorize($,Y).catch((K)=>{return console.error(`[gemi] Authorizing "${Z}" again after a revoke failed.`,K),{ok:!1,code:"revoked"}})));if(G.closed)return;if(this.revokedAt.get(Z)!==z)return;if(W.forEach(([Y,K],Q)=>{let V=X[Q];if(G.subs.get(Y)!==K)return;if(V.ok===!0&&V.topic===Z)return;G.subs.delete(Y),this.leave($,Z),E($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)t($,{op:"subscribed",id:Y,t:Z})}sendAll($){let Z=JSON.stringify($);for(let z of this.sockets)z.send(Z)}shutdown($={}){if(this.closed)return this.closed;this.closing=!0,this.closed=new Promise((G)=>{this.onAllClosed=G});let Z=[...this.sockets];if(Z.length===0)this.onAllClosed?.();if(Z.length>0)console.log(`[gemi] Closing ${Z.length} broadcast socket(s) (1012).`);for(let G of Z)this.sayBye(G);return setTimeout(()=>{for(let G of Z)try{G.terminate()}catch{}this.onAllClosed?.()},$.terminateAfterMs??2000).unref?.(),this.closed}get isClosing(){return this.closing}sayBye($){t($,{op:"bye",code:M.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),h2($,M.Restart,"Server restarting.")}run($){return U2.run(this.application,$)}}function q6($,Z){let z=/^(?:(https?):\/\/)?\*\.([^/:]+)(?::(\d+))?\/?$/i.exec($);if(z){let[,G,W,X]=z;if(G&&`${G.toLowerCase()}:`!==Z.protocol)return!1;if((X??"")!==Z.port)return!1;return Z.hostname.toLowerCase().endsWith(`.${W.toLowerCase().replace(/\.$/,"")}`)}if(/^https?:\/\//i.test($))try{return new URL($).origin===Z.origin}catch{return!1}return $.toLowerCase().replace(/\/$/,"")===Z.host.toLowerCase()}function h2($,Z,z){$.data.closing=!0,$.close(Z,z)}function t($,Z){$.send(JSON.stringify(Z))}function E($,Z,z){t($,{op:"denied",id:Z,code:z})}function b($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function T6($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function M6($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function k6($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return X$(z)??z;try{return Z.requestIP($)?.address??null}catch{return null}}function W$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class R6 extends P{register(){this.app.singleton(w,()=>new w(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(s,()=>new s(this.app.make(w),this.app))}boot(){let $=this.app.config.get("route.channels");if($)H$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(w).driver:void 0;E6(Z,process.env,z)}async shutdown(){if(this.app.resolved(s))this.app.make(s).shutdown();if(!this.app.resolved(w))return;await this.app.make(w).close()}}function E6($,Z=process.env,z){if(!($.driver==="redis"||z instanceof V$)||Z.SECRET)return;let W=`[gemi] The "redis" broadcast driver needs SECRET set, the same on every instance: Broadcast.toOthers tags the sender's socket with a key derived from it, and every instance must derive the same one.`;if(Z.NODE_ENV==="production")throw Error(W);console.warn(W)}class b6 extends P{register(){this.app.singleton(d2,()=>new d2(this.app.config.get("cache",{}),{application:this.app}))}}class y6 extends P{register(){this.app.singleton(Z2,()=>new Z2(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(Z2))return;await this.app.make(Z2).close()}}class f6 extends P{register(){this.app.singleton(p2,()=>new p2(this.app.config.get("auth",{}))),this.app.singleton(c2,()=>{let $=this.app.config.get("auth",{});return new c2({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){let $=this.app.config.get("auth",{});J$($),U$($?.emailCode?.fixedCode)}}var w6=100,v6=($)=>Math.min(w6,Math.floor($/10));class g6 extends P{register(){this.app.singleton(d,()=>new d(A(i2(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(d),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=A(i2(),Z);$.useJobs(await N$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let z=this.app;if(z.bound(u))$.useLocks(()=>z.make(u));$.start((G)=>U2.run(z,G))}async shutdown($){if(!this.app.resolved(d))return;let Z=this.app.make(d);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running cron tick(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-v6(z)));if(G.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+G.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class o extends F${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return B$(this.modelName)}async load(){if(!this.available)throw new l2(this.modelName);let $=n2(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new l2(this.modelName);let G=n2(this.modelName),W=this.hasActorColumn(G),X={active:Z};if(W)X.updatedBy=z.actor;return await G.asSystem(()=>G.upsert({where:{key:$},create:{key:$,...X},update:X})),{actorRecorded:W}}hasActorColumn($){let Z=$?.$schema?.fields?.updatedBy;return Z!==void 0&&Z.type==="String"}}function n9($){return $}function P$(){return{features:void 0,enabled:!0,source:new o,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class h6 extends P{register(){this.app.singleton(J2,()=>{let $=this.app.config.get("features",{}),Z=A(P$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new o($.model);else if($?.model!==void 0&&$.source instanceof o&&$.source.modelName!==$.model)N2.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new J2(Z,(z)=>N2.warning(z))})}async boot(){let $=this.app.make(J2);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){N2.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class m6 extends P{register(){this.app.singleton(t2,()=>new t2(this.app.config.get("mail",{})))}}class u6 extends P{register(){this.app.singleton(F2,()=>new F2(this.app.config.get("encryption",{})))}boot(){if(this.app.make(F2).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new s2(`auth.connections (${z.join(", ")}) keeps OAuth tokens encrypted, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`);let G=I$();if(G.length===0)return;throw new s2(`${G.join(", ")} ${G.length===1?"is an encrypted column":"are encrypted columns"}, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`)}}var d6=Symbol.for("gemi.broadcastEvent");function L$($){return typeof $==="object"&&$!==null&&$[d6]===!0}function c6($){return`listener:${$}`}function D$($,Z){p6($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends _${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,V]=i6(K),H=y(c).rehydrate(Q,V);await new $().handle(H)}onFail(K){console.error(`The listener ${$.name} threw while handling ${X} off the queue. The queue will retry it up to ${z} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${$.name} failed every one of its ${z} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,K)}};return Object.defineProperty(Y,"name",{value:c6($.name),writable:!0}),Y}function p6($){if(Object.getOwnPropertyDescriptor($,"name")?.writable)return;throw Error(`The listener ${$.name} sets \`queued = true\` but does not declare \`static name\`, so it would be registered with the queue `+"under its class name \u2014 which a production build renames while the "+`payload that names it does not. Add: static name = "${$.name}";`)}function i6($){return typeof $[0]==="string"?$:$[0]}class c{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=A(B2(),$),this.useListeners(this.config.listeners)}useListeners($){this.config.listeners=$,this.listeners={},this.events={};let Z=new Set;for(let z of $){if(!z.event){console.error(`Listener ${z.name} does not declare \`static event\`, so there is no event name to register it under and its handle will never run. Add: static event = SomeEvent;`);continue}if(Z.has(z.name)){console.error(`Two event listeners are named "${z.name}" \u2014 the first is `+"registered and this one is not. A listener's name identifies it across the framework, so only one class can hold it. Rename one.");continue}Z.add(z.name);let G=z.event.name,W=new z;this.events[G]??=z.event,(this.listeners[G]??=[]).push({listener:z,job:W.queued?D$(z,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:$})=>$?[$]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch($,Z){if(this.deferToCommit($,Z,!1))return;this.runListeners($,Z)}async dispatchAndWait($,Z){if(this.deferToCommit($,Z,!0))return;return this.runListeners($,Z)}deferToCommit($,Z,z){let{name:G,afterCommit:W}=$.constructor;if(!W)return!1;let X=O$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=L$($);if(G.length===0&&!W){this.warnNothingIsListening(z);return}for(let{listener:X,job:Y}of G){if(Y){this.enqueue(Y,X,z,Z);continue}try{await new X().handle($)}catch(K){console.error(`The listener ${X.name} threw while handling ${z}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",K)}}if(W)this.broadcast($,z)}broadcast($,Z){try{y(w).broadcastEvent($)}catch(z){console.error(`The event ${Z} could not be broadcast.`,z)}}rehydrate($,Z=[]){let z=this.events[$];if(!z)throw Error(`Cannot rebuild the event "${$}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${$}"\`.`);return new z(...Z)}enqueue($,Z,z,G){if(G===void 0){console.error(`The listener ${Z.name} is queued, but ${z} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${z}.dispatch(...) or ${z}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${Z.name} could not be queued for ${z}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{y(x).push($,JSON.stringify([z,G]),{reportFailure:!1}).catch(W)}catch(X){W(X)}}warnNothingIsWaitedFor($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has($))return;this.warnedAboutWaiting.add($),console.warn(`[gemi] ${$}.dispatchAndWait() was called inside a transaction and ${$} declares \`static afterCommit = true\`, so it resolved `+"immediately with no listener having run \u2014 they run when the "+"transaction commits. Await the transaction instead, or drop afterCommit if the caller needs the side effects first. Development only.")}warnNothingIsListening($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has($))return;this.warnedFor.add($),console.warn(`[gemi] ${$} was dispatched and nothing is listening for it. A listener registers under the name its event declares, so check that app/listeners holds a Listener with \`static event = ${$}\` and that ${$} declares \`static name = "${$}"\`. Development only.`)}}class l6 extends P{register(){this.app.singleton(c,()=>new c(this.app.config.get("events",{})))}async boot(){let $=this.app.make(c),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=A(B2(),Z);$.useListeners(await j$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(x);for(let W of z)G.registerJob(W)}}class n6 extends P{register(){this.app.singleton(o2,()=>new o2(this.app.config.get("filesystem",{})))}}class t6 extends P{register(){this.app.singleton(a2,()=>new a2(this.app.config.get("image",{})))}}class s6 extends P{register(){this.app.instance(r2,new r2)}}class o6 extends P{register(){this.app.singleton(P2,()=>new P2(A(A$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(P2).boot()}}class a6 extends P{register(){this.app.singleton(n,()=>new n(A(x$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(n).assertGlobalMiddleware()}}function aZ($){return $}function S$(){return{driver:new C$,limit:1000,window:60}}class r6 extends P{register(){this.app.singleton(l,()=>new l(A(S$(),this.app.config.get("ratelimiter",{}))))}}function W4($){return $}function q$(){return{url:process.env.REDIS_URL,options:void 0}}class e6 extends P{register(){this.app.singleton(z2,()=>new z2(A(q$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(z2))return;this.app.make(z2).close()}}function I2($,Z){let z=$.get(Z);if(!z)throw Error(`Missing "${Z}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return z}class $8 extends P{register(){this.app.singleton(a,()=>new a(I2(this.app.config,"route.api"))),this.app.singleton(G2,()=>new G2(I2(this.app.config,"route.view"),this.app.config.get("auth",{}))),this.app.singleton(L2,()=>new L2({api:this.app.make(a),view:this.app.make(G2)},{api:I2(this.app.config,"route.api"),view:I2(this.app.config,"route.view"),auth:this.app.config.get("auth",{}),domains:this.app.config.get("route.domains"),clientIpTrust:T$(process.env)})),this.app.singleton(i,()=>{let $=this.app.config.get("route.mcp");if(!$?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new i(new $.router,this.app.make(a),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton($2,()=>{let $=this.app.config.get("route.mcp");if(!$?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new $2(this.app.make(i),$.remote)})}boot(){if(this.app.make(a),this.app.make(G2),this.app.make(L2),this.app.config.get("route.mcp"))this.app.make(i);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make($2);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class Z8 extends P{register(){this.app.singleton(e2,()=>new e2(this.app.config.get("runs",{}),{application:this.app}))}}
|
|
8
|
-
export{M$ as eb,O as fb,v as gb,H8 as hb,i as ib,j2 as jb,a$ as kb,A2 as lb,k2 as mb,R2 as nb,$2 as ob,d as pb,I6 as qb,l8 as rb,G$ as sb,s as tb,R6 as ub,b6 as vb,y6 as wb,f6 as xb,g6 as yb,o as zb,n9 as Ab,P$ as Bb,h6 as Cb,m6 as Db,u6 as Eb,d6 as Fb,L$ as Gb,c as Hb,l6 as Ib,n6 as Jb,t6 as Kb,s6 as Lb,o6 as Mb,a6 as Nb,aZ as Ob,S$ as Pb,r6 as Qb,W4 as Rb,q$ as Sb,e6 as Tb,$8 as Ub,Z8 as Vb};
|
|
9
|
-
|
|
10
|
-
//# debugId=FF6F5EAB6D170DEF64756E2164756E21
|
package/dist/chunk-rczmh97n.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Sk as Y,Zk as K,al as y}from"./chunk-cbmne0wt.js";import{AsyncLocalStorage as U}from"async_hooks";var z=new U;function O(){return z.getStore()?.tx}function _(){return z.getStore()?.connection??K}function h(j,q){let v=z.getStore();if(_()===j)return q();return F(j),z.run({...v,depth:v?.depth??0,connection:j===K?void 0:j},q)}function F(j){let q=z.getStore();if(q?.tx===void 0)return;let v=q.connection??K;if(v===j)return;throw new y(v,j)}function A(j){let q=z.getStore();if(q?.tx===void 0||q.afterCommit===void 0)return!1;let v=Z.get(q.afterCommit);if(v==="committed")return!1;if(v==="rolled_back")return!0;return q.afterCommit.push(j),!0}var Z=new WeakMap;function k(j){if(A(j))return Promise.resolve();let q=(v)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",v)};try{return Promise.resolve(j()).catch(q)}catch(v){return q(v),Promise.resolve()}}function N(j){let q=z.getStore();if(q?.tx===void 0||q.commitDependsOn===void 0)return!1;return q.commitDependsOn.push(j),!0}class I extends Error{constructor(j){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${j instanceof Error?j.message:String(j)}`,{cause:j});this.name="TransactionDependencyError"}}async function W(j,q){if(j.length===q)return;let B=(await Promise.allSettled(j.slice(q))).find((J)=>J.status==="rejected");if(B)throw new I(B.reason)}function T(){let j=z.getStore();return j?.tx===void 0?null:j.depth}function x(){return z.getStore()?.system===!0}function p(j){let q=z.getStore();return z.run({...q,depth:q?.depth??0,system:!0},j)}function f(j){return z.getStore()?.trashed?.get(j)}function C(j,q,v){let B=z.getStore(),J=new Map(B?.trashed);return J.set(j,q),z.run({...B,depth:B?.depth??0,trashed:J},v)}function l(){return z.getStore()?.actor}function u(j,q){let v=z.getStore();return z.run({...v,depth:v?.depth??0,system:!1,actor:{user:j??null}},q)}function D(j){if(Bun.env.NODE_ENV!=="development")return null;if(j===!1)return null;if(j===void 0)return Y;if(!Number.isFinite(j)||j<=0)return Y;return j}function w(j){let q=D(j);if(q===null)return()=>{};let v=Error("transaction opened here"),B=setTimeout(()=>{let J=v.stack?.split(`
|
|
3
|
-
`).slice(1).join(`
|
|
4
|
-
`)??"";console.warn(`[gemi] A database transaction has not settled after ${q}ms. It `+"reserves a pooled connection until it does \u2014 check for network or "+`filesystem I/O inside the callback, and move it outside the transaction if you find any.
|
|
5
|
-
${J}
|
|
6
|
-
(development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},q);return B.unref?.(),()=>clearTimeout(B)}async function L(j,q){if(j.length===0)return;await z.run({...q,tx:void 0,afterCommit:void 0,commitDependsOn:void 0,depth:q?.depth??0},async()=>{for(let v of j)try{await v()}catch(B){console.error("An after-commit callback threw. The transaction it was waiting on had already committed and stays committed, and the callbacks after it still ran.",B)}})}function m(j,q,v){let B=z.getStore(),J=v?.connection??K;if(F(J),B?.tx){let G=B.afterCommit,V=G?.length??0,P=B.commitDependsOn,H=P?.length??0;return B.tx.savepoint((X)=>{let R=X;return z.run({...B,tx:R,depth:B.depth+1},async()=>{let S=await q(R);if(P)await W(P,H);return S})}).catch((X)=>{if(G)G.length=V;if(P)P.length=H;throw X})}let $=w(v?.slowTransactionThreshold),Q=[],M=[];try{return j.begin((G)=>z.run({...B,tx:G,depth:0,connection:J===K?void 0:J,afterCommit:Q,commitDependsOn:M},async()=>{let V=await q(G);return await W(M,0),V})).finally($).then(async(G)=>{return Z.set(Q,"committed"),await L(Q,B),G},(G)=>{throw Z.set(Q,"rolled_back"),G})}catch(G){throw $(),G}}
|
|
7
|
-
export{z as zk,O as Ak,_ as Bk,h as Ck,F as Dk,A as Ek,k as Fk,N as Gk,I as Hk,T as Ik,x as Jk,p as Kk,f as Lk,C as Mk,l as Nk,u as Ok,m as Pk};
|
|
8
|
-
|
|
9
|
-
//# debugId=D7A47963FCDCF0F964756E2164756E21
|