gemi 0.114.0 → 0.116.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-75wk4jxd.js → chunk-15c2vgaf.js} +2 -2
- package/dist/{chunk-75wk4jxd.js.map → chunk-15c2vgaf.js.map} +1 -1
- package/dist/{chunk-56fgk5rq.js → chunk-1hr4xht1.js} +2 -2
- package/dist/{chunk-56fgk5rq.js.map → chunk-1hr4xht1.js.map} +1 -1
- package/dist/{chunk-8c2fs0n0.js → chunk-1myhm0g3.js} +3 -3
- package/dist/{chunk-8c2fs0n0.js.map → chunk-1myhm0g3.js.map} +1 -1
- package/dist/chunk-1q9kd20m.js +5 -0
- package/dist/{chunk-fakvf9wb.js.map → chunk-1q9kd20m.js.map} +1 -1
- package/dist/{chunk-37qk5dh8.js → chunk-1vzks22y.js} +2 -2
- package/dist/{chunk-37qk5dh8.js.map → chunk-1vzks22y.js.map} +1 -1
- package/dist/{chunk-8h7dh2h2.js → chunk-2tzm58j3.js} +2 -2
- package/dist/{chunk-8h7dh2h2.js.map → chunk-2tzm58j3.js.map} +1 -1
- package/dist/{chunk-x157wrgy.js → chunk-3hrj5rwm.js} +2 -2
- package/dist/{chunk-x157wrgy.js.map → chunk-3hrj5rwm.js.map} +1 -1
- package/dist/{chunk-wysm6qte.js → chunk-4088szy9.js} +2 -2
- package/dist/{chunk-wysm6qte.js.map → chunk-4088szy9.js.map} +1 -1
- package/dist/{chunk-m17ktssc.js → chunk-41da9628.js} +1 -1
- package/dist/chunk-49nyyjfe.js +5 -0
- package/dist/{chunk-jzp0fs6h.js.map → chunk-49nyyjfe.js.map} +3 -3
- package/dist/{chunk-cna105t6.js → chunk-56jky6vf.js} +2 -2
- package/dist/{chunk-cna105t6.js.map → chunk-56jky6vf.js.map} +1 -1
- package/dist/{chunk-h4pazcgg.js → chunk-6cx8ncd4.js} +2 -2
- package/dist/{chunk-h4pazcgg.js.map → chunk-6cx8ncd4.js.map} +1 -1
- package/dist/{chunk-7fwp7vwh.js → chunk-6d8rvr1v.js} +2 -2
- package/dist/{chunk-7fwp7vwh.js.map → chunk-6d8rvr1v.js.map} +1 -1
- package/dist/{chunk-h2r2rdhj.js → chunk-785b41h1.js} +2 -2
- package/dist/{chunk-h2r2rdhj.js.map → chunk-785b41h1.js.map} +1 -1
- package/dist/{chunk-7v8sgqen.js → chunk-79xg42e7.js} +2 -2
- package/dist/{chunk-7v8sgqen.js.map → chunk-79xg42e7.js.map} +1 -1
- package/dist/{chunk-8rt4wx8z.js → chunk-7vb4eey2.js} +2 -2
- package/dist/{chunk-8rt4wx8z.js.map → chunk-7vb4eey2.js.map} +1 -1
- package/dist/{chunk-ap5gek56.js → chunk-8rv62v14.js} +2 -2
- package/dist/{chunk-ap5gek56.js.map → chunk-8rv62v14.js.map} +1 -1
- package/dist/{chunk-1f9sqht5.js → chunk-98m15b9x.js} +2 -2
- package/dist/{chunk-1f9sqht5.js.map → chunk-98m15b9x.js.map} +1 -1
- package/dist/{chunk-d4m4amy4.js → chunk-9n1hx3mq.js} +2 -2
- package/dist/{chunk-d4m4amy4.js.map → chunk-9n1hx3mq.js.map} +1 -1
- package/dist/{chunk-erxv1jz7.js → chunk-aazmrxj9.js} +2 -2
- package/dist/{chunk-erxv1jz7.js.map → chunk-aazmrxj9.js.map} +1 -1
- package/dist/{chunk-pmywkp1w.js → chunk-aeh67ynz.js} +3 -3
- package/dist/{chunk-pmywkp1w.js.map → chunk-aeh67ynz.js.map} +1 -1
- package/dist/{chunk-hz6yzzbz.js → chunk-agyfv3f8.js} +1 -1
- package/dist/{chunk-tp3mzj4v.js → chunk-bra1a1fq.js} +2 -2
- package/dist/{chunk-tp3mzj4v.js.map → chunk-bra1a1fq.js.map} +1 -1
- package/dist/{chunk-583vxa2v.js → chunk-cbqazg9k.js} +2 -2
- package/dist/{chunk-583vxa2v.js.map → chunk-cbqazg9k.js.map} +1 -1
- package/dist/{chunk-m2yfvwrn.js → chunk-d2gfcf85.js} +2 -2
- package/dist/{chunk-m2yfvwrn.js.map → chunk-d2gfcf85.js.map} +1 -1
- package/dist/{chunk-4szjp84e.js → chunk-d9mar37g.js} +2 -2
- package/dist/{chunk-4szjp84e.js.map → chunk-d9mar37g.js.map} +1 -1
- package/dist/{chunk-a5sbgffr.js → chunk-e573yxpq.js} +1 -1
- package/dist/{chunk-gdmsn3f5.js → chunk-eqse2m6n.js} +2 -2
- package/dist/{chunk-gdmsn3f5.js.map → chunk-eqse2m6n.js.map} +1 -1
- package/dist/{chunk-jyrsd1dn.js → chunk-er3wf6ng.js} +2 -2
- package/dist/{chunk-jyrsd1dn.js.map → chunk-er3wf6ng.js.map} +1 -1
- package/dist/{chunk-2rphhsr7.js → chunk-fre6f4nk.js} +2 -2
- package/dist/{chunk-2rphhsr7.js.map → chunk-fre6f4nk.js.map} +1 -1
- package/dist/{chunk-1p0dazvk.js → chunk-fxgxf16k.js} +2 -2
- package/dist/{chunk-1p0dazvk.js.map → chunk-fxgxf16k.js.map} +1 -1
- package/dist/{chunk-ty4aj41k.js → chunk-gts5p6mw.js} +3 -3
- package/dist/{chunk-ty4aj41k.js.map → chunk-gts5p6mw.js.map} +1 -1
- package/dist/{chunk-rrqr1dwq.js → chunk-hdps9n52.js} +2 -2
- package/dist/{chunk-rrqr1dwq.js.map → chunk-hdps9n52.js.map} +1 -1
- package/dist/{chunk-jk97wv0q.js → chunk-jdhdrr2k.js} +2 -2
- package/dist/{chunk-jk97wv0q.js.map → chunk-jdhdrr2k.js.map} +1 -1
- package/dist/chunk-jmg2zsaf.js +5 -0
- package/dist/{chunk-fv9mr1t4.js.map → chunk-jmg2zsaf.js.map} +4 -4
- package/dist/{chunk-w2fpr99k.js → chunk-jmpw6bqz.js} +2 -2
- package/dist/{chunk-w2fpr99k.js.map → chunk-jmpw6bqz.js.map} +1 -1
- package/dist/{chunk-6h9j3f1x.js → chunk-kejwjerj.js} +2 -2
- package/dist/{chunk-6h9j3f1x.js.map → chunk-kejwjerj.js.map} +1 -1
- package/dist/{chunk-mqcy5vja.js → chunk-kqxdsv22.js} +2 -2
- package/dist/{chunk-mqcy5vja.js.map → chunk-kqxdsv22.js.map} +1 -1
- package/dist/{chunk-7rmjr8p7.js → chunk-ktr3k768.js} +2 -2
- package/dist/{chunk-7rmjr8p7.js.map → chunk-ktr3k768.js.map} +1 -1
- package/dist/{chunk-kcx468qv.js → chunk-m54s6jpr.js} +2 -2
- package/dist/{chunk-e6fp6dxx.js.map → chunk-m54s6jpr.js.map} +1 -1
- package/dist/{chunk-nek1gzz2.js → chunk-mazznq15.js} +3 -3
- package/dist/{chunk-nek1gzz2.js.map → chunk-mazznq15.js.map} +1 -1
- package/dist/{chunk-r4namj39.js → chunk-mqfzdfnz.js} +2 -2
- package/dist/{chunk-r4namj39.js.map → chunk-mqfzdfnz.js.map} +1 -1
- package/dist/chunk-ms9k0rx6.js +46 -0
- package/dist/{chunk-v9na3dny.js.map → chunk-ms9k0rx6.js.map} +5 -5
- package/dist/{chunk-hrvzchxd.js → chunk-mschc94q.js} +2 -2
- package/dist/{chunk-hrvzchxd.js.map → chunk-mschc94q.js.map} +1 -1
- package/dist/{chunk-329ggbcw.js → chunk-p91b8zcn.js} +2 -2
- package/dist/{chunk-329ggbcw.js.map → chunk-p91b8zcn.js.map} +1 -1
- package/dist/chunk-pn8v6fj2.js +14 -0
- package/dist/{chunk-0n9vs1ad.js.map → chunk-pn8v6fj2.js.map} +5 -5
- package/dist/{chunk-awp3n119.js → chunk-pyk3gzvc.js} +2 -2
- package/dist/{chunk-awp3n119.js.map → chunk-pyk3gzvc.js.map} +1 -1
- package/dist/{chunk-zns7xcz9.js → chunk-qjhw8nje.js} +1 -1
- package/dist/{chunk-5j76r5q8.js → chunk-qsrcdzan.js} +3 -3
- package/dist/{chunk-5j76r5q8.js.map → chunk-qsrcdzan.js.map} +1 -1
- package/dist/{chunk-xrh6k13s.js → chunk-sr942vb1.js} +2 -2
- package/dist/{chunk-xrh6k13s.js.map → chunk-sr942vb1.js.map} +1 -1
- package/dist/{chunk-yp5979we.js → chunk-t04f3akb.js} +2 -2
- package/dist/{chunk-yp5979we.js.map → chunk-t04f3akb.js.map} +1 -1
- package/dist/{chunk-j3nr4cg0.js → chunk-t4yh4nf9.js} +3 -3
- package/dist/{chunk-j3nr4cg0.js.map → chunk-t4yh4nf9.js.map} +1 -1
- package/dist/{chunk-8k8534kg.js → chunk-tn2bryy2.js} +2 -2
- package/dist/{chunk-8k8534kg.js.map → chunk-tn2bryy2.js.map} +1 -1
- package/dist/{chunk-q95k1ymq.js → chunk-tw5kwbx4.js} +2 -2
- package/dist/{chunk-q95k1ymq.js.map → chunk-tw5kwbx4.js.map} +1 -1
- package/dist/{chunk-kg1nbxvm.js → chunk-tzm3c7n6.js} +4 -4
- package/dist/{chunk-kg1nbxvm.js.map → chunk-tzm3c7n6.js.map} +1 -1
- package/dist/{chunk-zgn0p8qr.js → chunk-v1tfdgy1.js} +2 -2
- package/dist/{chunk-zgn0p8qr.js.map → chunk-v1tfdgy1.js.map} +1 -1
- package/dist/{chunk-e7axa0d5.js → chunk-vbdty91k.js} +3 -3
- package/dist/{chunk-e7axa0d5.js.map → chunk-vbdty91k.js.map} +1 -1
- package/dist/{chunk-e6fp6dxx.js → chunk-vw8849ys.js} +2 -2
- package/dist/{chunk-kcx468qv.js.map → chunk-vw8849ys.js.map} +1 -1
- package/dist/{chunk-y0wx6w80.js → chunk-vxm6yevm.js} +2 -2
- package/dist/{chunk-y0wx6w80.js.map → chunk-vxm6yevm.js.map} +1 -1
- package/dist/{chunk-kqb4s1r0.js → chunk-whtzggn6.js} +2 -2
- package/dist/{chunk-kqb4s1r0.js.map → chunk-whtzggn6.js.map} +1 -1
- package/dist/{chunk-3ma9m432.js → chunk-wyw6p3fg.js} +2 -2
- package/dist/{chunk-3ma9m432.js.map → chunk-wyw6p3fg.js.map} +1 -1
- package/dist/{chunk-gv91vjeb.js → chunk-x7cpth2f.js} +1 -1
- package/dist/{chunk-z32xfe8c.js → chunk-xt9tv99x.js} +2 -2
- package/dist/{chunk-z32xfe8c.js.map → chunk-xt9tv99x.js.map} +1 -1
- package/dist/{chunk-60nyk1w8.js → chunk-yf1njzd5.js} +2 -2
- package/dist/{chunk-60nyk1w8.js.map → chunk-yf1njzd5.js.map} +1 -1
- package/dist/{chunk-jv4g8grc.js → chunk-yhrye9cm.js} +2 -2
- package/dist/{chunk-jv4g8grc.js.map → chunk-yhrye9cm.js.map} +1 -1
- package/dist/{chunk-wwmdqhzy.js → chunk-zyt2w03d.js} +2 -2
- package/dist/{chunk-wwmdqhzy.js.map → chunk-zyt2w03d.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-BgLyzzOL.js → ThemeProvider-BLI4zpLu.js} +8 -3
- package/dist/chunks/ThemeProvider-BLI4zpLu.js.map +1 -0
- package/dist/client/ClientRouter.d.ts +3 -5
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/Head.d.ts +1 -1
- package/dist/client/Head.d.ts.map +1 -1
- package/dist/client/ServerDataProvider.d.ts +2 -0
- package/dist/client/ServerDataProvider.d.ts.map +1 -1
- package/dist/client/createRoot.d.ts +2 -4
- package/dist/client/createRoot.d.ts.map +1 -1
- package/dist/client/htmlAttributes.d.ts +18 -0
- package/dist/client/htmlAttributes.d.ts.map +1 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +79 -6
- package/dist/client/index.js.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Meta.d.ts +11 -1
- package/dist/facades/Meta.d.ts.map +1 -1
- package/dist/facades/Storage.d.ts +25 -1
- package/dist/facades/Storage.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +3 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/Metadata.d.ts +23 -0
- package/dist/http/Metadata.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/requestContext.d.ts +3 -0
- package/dist/http/requestContext.d.ts.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.d.ts +1 -0
- package/dist/i18n/index.d.ts.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/file-storage/drivers/AzureBlobDriver.d.ts +12 -1
- package/dist/services/file-storage/drivers/AzureBlobDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/FileStorageDriver.d.ts +32 -1
- package/dist/services/file-storage/drivers/FileStorageDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +22 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/S3Driver.d.ts +14 -1
- package/dist/services/file-storage/drivers/S3Driver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/types.d.ts +26 -0
- package/dist/services/file-storage/drivers/types.d.ts.map +1 -1
- package/dist/services/index.d.ts +3 -3
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +4 -4
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +19 -0
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-0n9vs1ad.js +0 -14
- package/dist/chunk-fakvf9wb.js +0 -5
- package/dist/chunk-fv9mr1t4.js +0 -5
- package/dist/chunk-jzp0fs6h.js +0 -5
- package/dist/chunk-v9na3dny.js +0 -46
- package/dist/chunks/ThemeProvider-BgLyzzOL.js.map +0 -1
- /package/dist/{chunk-m17ktssc.js.map → chunk-41da9628.js.map} +0 -0
- /package/dist/{chunk-hz6yzzbz.js.map → chunk-agyfv3f8.js.map} +0 -0
- /package/dist/{chunk-a5sbgffr.js.map → chunk-e573yxpq.js.map} +0 -0
- /package/dist/{chunk-zns7xcz9.js.map → chunk-qjhw8nje.js.map} +0 -0
- /package/dist/{chunk-gv91vjeb.js.map → chunk-x7cpth2f.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=(a,b)=>()=>(a&&(b=a(a=0)),b);var w=import.meta.require;
|
|
3
|
-
export{s as
|
|
3
|
+
export{s as qi,t as ri,u as si,v as ti,w as ui};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=8397121ACDCA415864756E2164756E21
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Q as T}from"./chunk-
|
|
2
|
+
import{Q as T}from"./chunk-d2gfcf85.js";import{_ as A}from"./chunk-eqse2m6n.js";import"./chunk-jdhdrr2k.js";import{aa as y}from"./chunk-fre6f4nk.js";import{qi as r}from"./chunk-vw8849ys.js";var u=r(A(),1);var i=r(y(),1),E=r(A(),1);import{exec as d}from"child_process";import{promisify as I}from"util";var x=r(T(),1),_=(c,n,e)=>{if(n.Version!==1)throw Error(`Profile ${c} credential_process did not return Version 1.`);if(n.AccessKeyId===void 0||n.SecretAccessKey===void 0)throw Error(`Profile ${c} credential_process returned invalid credentials.`);if(n.Expiration){let w=new Date;if(new Date(n.Expiration)<w)throw Error(`Profile ${c} credential_process returned expired credentials.`)}let s=n.AccountId;if(!s&&e?.[c]?.aws_account_id)s=e[c].aws_account_id;let t={accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,...n.SessionToken&&{sessionToken:n.SessionToken},...n.Expiration&&{expiration:new Date(n.Expiration)},...n.CredentialScope&&{credentialScope:n.CredentialScope},...s&&{accountId:s}};return x.setCredentialFeature(t,"CREDENTIALS_PROCESS","w"),t};var K=async(c,n,e)=>{let s=n[c];if(n[c]){let t=s.credential_process;if(t!==void 0){let w=I(E.externalDataInterceptor?.getTokenRecord?.().exec??d);try{let{stdout:o}=await w(t),S;try{S=JSON.parse(o.trim())}catch{throw Error(`Profile ${c} credential_process returned invalid JSON.`)}return _(c,S,n)}catch(o){throw new i.CredentialsProviderError(o.message,{logger:e})}}else throw new i.CredentialsProviderError(`Profile ${c} did not contain credential_process.`,{logger:e})}else throw new i.CredentialsProviderError(`Profile ${c} could not be found in shared credentials file.`,{logger:e})};var R=(c={})=>async({callerClientConfig:n}={})=>{c.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let e=await u.parseKnownFiles(c);return K(u.getProfileName({profile:c.profile??n?.profile}),e,c.logger)};export{R as fromProcess};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=6510817831B2FA3164756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";sNAAA,SCAA,SACA,KACA,SAAS,sBACT,oBAAS,aCHT,eACa,EAAiC,CAAC,EAAa,EAAM,IAAa,CAC3E,GAAI,EAAK,UAAY,EACjB,MAAM,MAAM,WAAW,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uB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "6510817831B2FA3164756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Af as _,Ef as R,Ff as W,Gf as F,Hf as C,If as G,Jf as Y,Kf as N,Lf as S,Rf as K,ef as O,ff as Z}from"./chunk-hytt9qyj.js";import{
|
|
2
|
+
import{Af as _,Ef as R,Ff as W,Gf as F,Hf as C,If as G,Jf as Y,Kf as N,Lf as S,Rf as K,ef as O,ff as Z}from"./chunk-hytt9qyj.js";import{si as P}from"./chunk-vw8849ys.js";var E={};P(E,{registeredNames:()=>b,register:()=>T,has:()=>y,get:()=>A,clearRegistry:()=>x});var J=new Map;function T(q,z){J.set(q,z)}function y(q){return J.has(q)}function A(q){let z=J.get(q);if(z===void 0)throw new _(q,[...J.keys()]);return z}function b(){return[...J.keys()]}function x(){J.clear()}var w=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,h=/^\s*as\s+(jsonb|json)\s*\)/i,c=/\bcast\s*\(\s*$/i,f=new Set;function U(q,z){if(!z.typesParametersFromStatement)return{fragment:q,jsonParameters:f};let B=C(q),D=new Set,H;for(let X=0;X<B.length-1;X++){let $=B[X+1],Q=w.exec($);if(Q){H??=[...B],H[X+1]=`::text::${Q[1]}${$.slice(Q[0].length)}`,D.add(X);continue}let V=h.exec($);if(V&&c.test((H??B)[X]))H??=[...B],H[X+1]=` as text)::${V[1]}${$.slice(V[0].length)}`,D.add(X)}if(!H)return{fragment:q,jsonParameters:D};return{fragment:G(H,q.binders),jsonParameters:D}}function M(q,z){if(q===null||q===void 0)return null;let B=K(q);if(B==="db")return null;if(B==="json")return"null";if(B==="any")throw new Z(z,"DB",z,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof q==="string")return q;let D;try{D=JSON.stringify(q)}catch(H){throw new Z(z,"DB",z,`A parameter cast to json could not be serialised: ${H instanceof Error?H.message:String(H)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(D===void 0)throw new Z(z,"DB",z,`A ${typeof q} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return D}var I=new WeakSet;function L(q){return I.add(q),q}function k(q){return typeof q==="object"&&q!==null&&I.has(q)}function t(q,...z){if(!Array.isArray(q)||!("raw"in q))throw new O("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let B=[];for(let D=0;D<q.length;D++)if(B.push(W(q[D])),D<z.length)B.push(j(z[D]));return L(Y(...B))}function r(q,z=", "){if(!Array.isArray(q))throw new Z("join","DB","sql",`Expected an array of fragments or values, got ${typeof q}.`);if(q.length===0)return p;let B=q.map(j);if(k(z)){let D=[];for(let H=0;H<B.length;H++){if(H>0)D.push(z);D.push(B[H])}return L(Y(...D))}return v(z),L(N(B,z))}var g=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function v(q){if(typeof q==="string"&&g.test(q))return;throw new Z("join","DB","sql",typeof q==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(q)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${q===null?"null":typeof q}.`)}var p=L(Object.freeze({text:"",binders:Object.freeze([])}));function a(q){if(typeof q!=="string")throw new Z("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(q)?"an array":typeof q}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return L(W(q))}function e(q,z,B="query"){if(!k(q))throw new Z(B,"DB",B,`Expected a fragment built with 'sql', got ${q===null?"null":typeof q}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let D=U(q,z),H=S(D.fragment,z,{model:"DB",operation:B});return{text:H.text,values:R(H.binders)(void 0).map((X,$)=>D.jsonParameters.has($)?M(X,B):X===null||X===void 0?X??null:z.encodeUntyped(X))}}function j(q){if(k(q))return q;return F(()=>q)}
|
|
3
3
|
export{T as We,y as Xe,A as Ye,b as Ze,E as _e,t as $e,r as af,p as bf,a as cf,e as df};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=FB86B3DB3224645264756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import type { SqlDialect } from \"./dialect\";\nimport {\n InvalidArgumentError,\n UnsupportedQueryError,\n} from \"./errors\";\nimport {\n type Fragment,\n bindValues,\n concat,\n joinFragments,\n param,\n render,\n sql as text,\n} from \"./compile/fragment\";\nimport { jsonTextParameter, retypeJsonParameters } from \"./json-param\";\n\n/**\n * SQL fragments as first-class values: `sql`, `join`, `empty`, and one door out.\n *\n * The ORM deliberately does not implement every SQL shape — `distinct`, cursor\n * pagination, window functions, recursive CTEs. That is the right call, but it\n * is only half a decision: the shapes it declines have to have somewhere to go,\n * and \"drop to raw SQL\" is not an answer if raw SQL cannot be *composed*.\n *\n * `DB.sql` — Bun's tagged template — covers a single self-contained statement,\n * and that is genuinely all it covers. The shape it cannot express is the common\n * one: a predicate list built conditionally, passed around as a value, and\n * interpolated into a larger statement.\n *\n * ```ts\n * const filters = []\n * if (q) filters.push(sql`name ilike ${`%${q}%`}`)\n * if (organizationId) filters.push(sql`\"organizationId\" = ${organizationId}`)\n *\n * const where = filters.length ? sql`where ${join(filters, \" and \")}` : empty\n * const rows = await DB.query(sql`select * from \"Product\" ${where} limit ${20}`)\n * ```\n *\n * ## This is the compiler's own `Fragment`, made public\n *\n * Not a parallel mechanism. `compile/fragment.ts` has held exactly this shape\n * since iteration 1 — text plus positional binders, composable, never\n * concatenating a value into the text — because that is what invariant 2 needs\n * internally. Reusing it means a public fragment binds by the same rule the\n * compiler's own SQL does, and it means the parameter ceiling, the placeholder\n * numbering and the dialect split are all already handled rather than\n * reimplemented one door down.\n *\n * **Placeholders are assigned at assembly, not at authoring.** SQLite writes\n * `?` and Postgres writes `$1`, `$2`, and a fragment does not know where in the\n * final statement it will land — so `sql` records a *position* and `render`\n * turns it into a placeholder once the whole statement exists. That is what lets\n * the same fragment be nested, reused twice in one statement, or built before\n * the dialect is even known.\n */\n\n/**\n * A composable piece of SQL. Its values are bound parameters, never text.\n *\n * Opaque on purpose: an application builds one with `sql`, combines it with\n * `join`, and hands it to `DB.query` / `DB.execute`. Reading `.text` off it is\n * not part of the contract — it holds parameter *markers* rather than the\n * dialect's placeholders, so it is not the statement that runs.\n */\nexport type SqlFragment = Fragment;\n\n/**\n * Every fragment this module has produced.\n *\n * **Identity, not shape, and the difference is a SQL injection.** `interpolate`\n * splices a fragment as text and binds everything else, so \"is this a fragment\"\n * decides whether a value reaches the statement or a parameter. Asking the\n * *shape* — a `text` string and a `binders` array — makes that decision\n * answerable by anything that can name two properties, and `{\"text\": \"…\",\n * \"binders\": []}` is two lines of JSON:\n *\n * ```ts\n * const body = await request.json()\n * await DB.query(sql`select \"email\" from \"User\" where \"email\" = ${body.email}`)\n * // body.email = { text: `'' union select \"password\" from \"User\"`, binders: [] }\n * // -> select \"email\" from \"User\" where \"email\" = '' union select \"password\" from \"User\"\n * ```\n *\n * That is the intended call site with the intended safe value, and it returned\n * the password column out of a statement selecting only `email`. The internal\n * `Fragment` never had the problem because nothing outside `compile/` could\n * construct one; making the type public is what turned \"text plus binders\" from\n * an implementation detail into a shape an attacker can name. `unsafeSql` is\n * built so that reaching for the escape hatch is a decision — a structural check\n * is a second, unmarked door beside it.\n *\n * A `WeakSet` the module owns cannot be forged: membership is granted only by\n * the constructors below. It registers the *returned* object rather than\n * stamping a property, because `concat` and `joinFragments` return fresh objects\n * — a marker property on the inputs would not survive them, and the version that\n * cannot drift is the one that brands what actually comes out.\n */\nconst FRAGMENTS = new WeakSet<object>();\n\nfunction brand(fragment: Fragment): SqlFragment {\n FRAGMENTS.add(fragment);\n return fragment;\n}\n\n/** Whether a value is a fragment *this module made*, so it splices rather than binds. */\nfunction isFragment(value: unknown): value is Fragment {\n return typeof value === \"object\" && value !== null && FRAGMENTS.has(value);\n}\n\n/**\n * A SQL fragment. Every `${value}` is bound as a parameter; a `${fragment}` is\n * spliced in, carrying its own parameters with it.\n *\n * ```ts\n * sql`where \"id\" = ${id}` // \"id\" = $1, with id bound\n * sql`where ${sql`\"a\" = ${1}`} and ${sql`\"b\" = ${2}`}` // nests to any depth\n * ```\n *\n * An interpolated **array** is bound as one value, not expanded — that is what\n * Postgres's `= any($1)` wants, and it is the only reading that does not depend\n * on the dialect. For a comma-separated list of placeholders, say so with\n * `join`.\n *\n * A value at a `::jsonb` cast the caller wrote is the one parameter with a type\n * behind it, and it is bound as **JSON text** so that the statement means what\n * the same statement meant under Prisma's `$executeRaw`:\n *\n * ```ts\n * sql`… set payload = payload || ${JSON.stringify(patch)}::jsonb` // merges\n * ```\n *\n * Without that the driver would JSON-encode the string and the column would\n * hold the document as a jsonb *string* — which `||` appends as an array\n * element rather than merging. `json-param.ts` has the measurements.\n */\nexport function sql(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): SqlFragment {\n // A defensive check rather than a type error, because the interesting misuse\n // is `sql(userInput)` — a plain call with a string, which would otherwise\n // reach `strings.raw` as `undefined` and produce a fragment of `undefined`\n // text rather than an error. It is also the shape somebody reaches for when\n // they want the escape hatch and have not found `unsafeSql`.\n if (!Array.isArray(strings) || !(\"raw\" in (strings as object))) {\n throw new UnsupportedQueryError(\n \"sql\",\n \"DB\",\n \"sql\",\n `'sql' is a tagged template — write sql\\`select 1\\`, not sql(\"select 1\"). ` +\n `To put text that is not a value into a statement, use 'unsafeSql', ` +\n `and read what it says first.`,\n );\n }\n\n const parts: Fragment[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n parts.push(text(strings[i]));\n if (i < values.length) parts.push(interpolate(values[i]));\n }\n\n return brand(concat(...parts));\n}\n\n/**\n * Fragments — or values — joined by a separator, the way `Array.join` reads.\n *\n * ```ts\n * join(filters, \" and \") // a and b and c\n * join([sql`\"a\" asc`, sql`\"b\" desc`]) // \"a\" asc, \"b\" desc\n * join(ids) // $1, $2, $3 — each bound\n * ```\n *\n * An **empty list produces `empty`**, not a separator and not a syntax error, so\n * `join` composes with a list that turned out to have nothing in it. That is the\n * case a caller forgets, and it is the one that would otherwise emit `where ` and\n * fail at the database rather than here.\n *\n * ## The separator is text, so it is not a free string\n *\n * It goes between the fragments *in the statement*, which makes it the one other\n * place a string could reach the SQL — and this module's whole claim is that\n * `unsafeSql` is **the** door. So a plain-string separator has to be glue and\n * nothing else: whitespace, commas, or a boolean connective. Anything more\n * expressive is legitimate and has to say so:\n *\n * ```ts\n * join(filters, \" and \") // fine\n * join(parts, unsafeSql(\") and (\")) // fine, and visibly a decision\n * join(ids, request.query.sep) // refused\n * ```\n *\n * A **blocklist would not do**, which is why this is an allowlist. The obvious\n * one — reject quotes, semicolons and comment markers — lets this through:\n *\n * join([1, 2], \") or 1=1 union select password from Users where 1=(1\")\n *\n * No quote, no `--`, still an injection. There is no sound way to say \"this\n * arbitrary text is safe glue\", so the rule is that glue is a small closed set\n * and everything else is a fragment somebody built on purpose.\n */\nexport function join(\n values: readonly unknown[],\n separator: string | SqlFragment = \", \",\n): SqlFragment {\n if (!Array.isArray(values)) {\n throw new InvalidArgumentError(\n \"join\",\n \"DB\",\n \"sql\",\n `Expected an array of fragments or values, got ${typeof values}.`,\n );\n }\n if (values.length === 0) return empty;\n\n const parts = values.map(interpolate);\n\n if (isFragment(separator)) {\n const woven: Fragment[] = [];\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) woven.push(separator);\n woven.push(parts[i]);\n }\n return brand(concat(...woven));\n }\n\n assertGlue(separator);\n return brand(joinFragments(parts, separator));\n}\n\n/**\n * Whitespace and commas, or a boolean connective surrounded by whitespace.\n *\n * Deliberately small. Every separator a composed statement actually needs is in\n * here — `\", \"`, `\" and \"`, `\" or \"`, `\" \"` — and everything outside it is\n * expressive enough to change what the statement *does*, which is the property\n * that makes it a `unsafeSql` decision rather than a string argument.\n */\nconst GLUE = /^[\\s,]*$|^\\s*(?:and|or)\\s*$/i;\n\nfunction assertGlue(separator: unknown): void {\n if (typeof separator === \"string\" && GLUE.test(separator)) return;\n\n throw new InvalidArgumentError(\n \"join\",\n \"DB\",\n \"sql\",\n typeof separator === \"string\"\n ? `A separator is written into the SQL text, so it may only be glue: ` +\n `whitespace, commas, or 'and' / 'or'. Got ` +\n `${JSON.stringify(separator)}. If that is deliberate, say so with ` +\n `unsafeSql(...) — and never build one from anything that came from ` +\n `outside the program.`\n : `Expected a separator string or a fragment, got ${\n separator === null ? \"null\" : typeof separator\n }.`,\n );\n}\n\n/**\n * The fragment that contributes nothing.\n *\n * The point of it is that `where ${empty}` and `where ${filter}` are the same\n * expression — a conditional predicate is a value, not a branch around the\n * statement. Frozen, because it is shared by every caller and a fragment is read\n * as immutable everywhere else.\n */\nexport const empty: SqlFragment = brand(\n Object.freeze({ text: \"\", binders: Object.freeze([]) as [] }),\n);\n\n/**\n * **Text straight into the SQL, with no parameter around it.** The one door in\n * this ORM through which a value reaches the statement text.\n *\n * Everything else in the compiler exists to make this impossible — identifiers\n * come from the generated schema, values are bound — so reaching for it should\n * feel like reaching for it. **Never give it a value that came from a request, a\n * form, a URL, a header, a queue payload or a database row.** There is no\n * escaping here and there will not be: escaping that is \"usually right\" is worse\n * than none, because it survives review.\n *\n * ## Why it exists at all, since that is the fair question\n *\n * Plan quality can depend on *not* parameterising. A partial index declared as\n *\n * ```sql\n * create index … on \"Job\" (…) where \"name\" is distinct from 'reaper'\n * ```\n *\n * is only usable if the planner can prove the query's predicate matches the\n * index's. A bound parameter is opaque at plan time, so `where \"name\" is\n * distinct from $1` does not match — and the query falls back to a sequential\n * scan over the whole table. The constant has to be *in the text*:\n *\n * ```ts\n * const REAPER = unsafeSql(`'reaper'`) // a literal in this file, never input\n * await DB.query(sql`\n * select … from \"Job\" where \"name\" is distinct from ${REAPER} …\n * `)\n * ```\n *\n * A builder with no escape hatch cannot express that at any price, and the\n * workaround — hand-writing the whole statement — loses composition for every\n * other part of it.\n *\n * The same applies to the other things that cannot be parameters in SQL:\n * identifiers, a sort direction, a table name chosen from a fixed set in code.\n * All of them share the rule above — the value is written in the source file, or\n * chosen from a set written in the source file, never passed in.\n */\nexport function unsafeSql(literal: string): SqlFragment {\n if (typeof literal !== \"string\") {\n throw new InvalidArgumentError(\n \"unsafeSql\",\n \"DB\",\n \"sql\",\n `Expected a string literal, got ${\n Array.isArray(literal) ? \"an array\" : typeof literal\n }. 'unsafeSql' is a plain call, not a tagged template — a template would ` +\n `interpolate values into the SQL text, which is the one thing it must ` +\n `never do.`,\n );\n }\n return brand(text(literal));\n}\n\n/**\n * A fragment as the statement a driver can run: the dialect's placeholders in\n * the text, and the values in the order they appear.\n *\n * Separate from the executing, and exported, because it is the half that is a\n * pure function of `(fragment, dialect)` — so a test can assert what a\n * composition emits on both dialects without a database anywhere near it, which\n * is exactly how the rest of the compiler is tested.\n *\n * `render` also applies the parameter ceiling here, which matters more for a\n * hand-built fragment than for a compiled plan: `join(ids)` over a\n * request-derived list is one placeholder per element on SQLite, and 40 000 of\n * them is a driver error rather than a clear one.\n */\nexport function renderFragment(\n fragment: SqlFragment,\n dialect: SqlDialect,\n operation = \"query\",\n): { text: string; values: unknown[] } {\n if (!isFragment(fragment)) {\n throw new InvalidArgumentError(\n operation,\n \"DB\",\n operation,\n `Expected a fragment built with 'sql', got ${\n fragment === null ? \"null\" : typeof fragment\n }. A plain string is not accepted here on purpose — it would be the one ` +\n `path into the SQL text that nobody had to think about.`,\n );\n }\n\n // The one thing a raw parameter can be *told* about its type: a `::jsonb` the\n // caller wrote onto their own placeholder. Where there is one, the parameter\n // is retyped through `text` and its value serialised, because Bun otherwise\n // JSON-encodes a string bound to a `jsonb` parameter and stores the document\n // as a jsonb *string* where Prisma stored the object. See `json-param.ts` —\n // the mechanism, the measurements, and why a string is not serialised here\n // while `fieldParam` serialises one.\n //\n // The dialect is passed because this is not universal, and the reason is\n // narrower than it looks: `::` is Postgres-only syntax, but `cast(? as json)`\n // *parses and runs* on SQLite, where it means NUMERIC affinity — so retyping\n // it would rewrite a working statement into `cast(? as text)::json`, which\n // SQLite cannot parse. `typesParametersFromStatement` is false there.\n const json = retypeJsonParameters(fragment, dialect);\n\n const rendered = render(json.fragment, dialect, { model: \"DB\", operation });\n return {\n text: rendered.text,\n // `encodeUntyped` and not `encode`: there is no field here to ask, which is\n // the whole difference between a fragment's parameters and a compiled\n // plan's. It normalises the two JavaScript types whose SQL form the ORM has\n // already decided — a `Date` and a boolean — so a raw statement compares\n // against ORM-written rows on both dialects rather than only on Postgres.\n values: bindValues(rendered.binders)(undefined).map((value, index) =>\n json.jsonParameters.has(index)\n ? jsonTextParameter(value, operation)\n : value === null || value === undefined\n ? (value ?? null)\n : dialect.encodeUntyped(value),\n ),\n };\n}\n\n/**\n * One interpolated slot: a fragment splices, anything else binds.\n *\n * The binder ignores both its arguments. A compiled plan's binders read the\n * *call's* argument tree, because one plan serves many calls; a fragment is\n * built per call and closes over the value it was given, which is the whole\n * difference between the compiler's fragments and these.\n */\nfunction interpolate(value: unknown): Fragment {\n if (isFragment(value)) return value;\n return param(() => value);\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";6QAeA,FAAM,EAAS,IAAI,IAEZ,SAAS,CAAQ,CAAC,EAAc,EAAsB,CAC3D,EAAO,IAAI,EAAM,CAAK,EAGjB,SAAS,CAAG,CAAC,EAA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AAO,CAAS,EAClC,IAAU,MAAQ,IAAU,OACzB,GAAS,KACV,EAAQ,cAAc,CAAK,CACnC,CACF,EAWF,SAAS,CAAW,CAAC,EAA0B,CAC7C,GAAI,EAAW,CAAK,EAAG,OAAO,EAC9B,OAAO,EAAM,IAAM,CAAK",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "FB86B3DB3224645264756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Lc as G}from"./chunk-n672d4g8.js";import{Uf as F}from"./chunk-hytt9qyj.js";import{
|
|
2
|
+
import{Lc as G}from"./chunk-n672d4g8.js";import{Uf as F}from"./chunk-hytt9qyj.js";import{_g as E}from"./chunk-cbqazg9k.js";import{Eh as x,rh as B}from"./chunk-kejwjerj.js";class J extends G{register(){this.app.singleton(x,()=>{let j=new x(E(B(),this.app.config.get("database",{})));return K(j),j})}async shutdown(){if(!this.app.resolved(x))return;await this.app.make(x).close()}}function K(j){if(Bun.env.NODE_ENV!=="development")return;for(let z of j.connectionNames){let A=j.connection(z);if(F(A.dialect))continue;let H=z===j.name?"DATABASE_URL":`The "${z}" database connection`;console.warn(`[gemi] ${H} points at ${A.dialect}, which the gemi ORM `+"does not implement \u2014 only sqlite and postgres are. The connection "+`works, so raw SQL through DB.query / DB.sql and transactions are fine, but every model operation will raise UnsupportedDialectError.
|
|
3
3
|
(development only)`)}}
|
|
4
4
|
export{J as Ia};
|
|
5
5
|
|
|
6
|
-
//# debugId=
|
|
6
|
+
//# debugId=832A59899C6D5B0964756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { ormSupports } from \"../orm/dialect\";\nimport { ServiceProvider } from \"../support/ServiceProvider\";\nimport { withDefaults } from \"../support/withDefaults\";\nimport { databaseConfigDefaults, type DatabaseConfig } from \"./config\";\nimport { DatabaseManager } from \"./DatabaseManager\";\n\nexport class DatabaseServiceProvider extends ServiceProvider {\n register() {\n this.app.singleton(\n DatabaseManager,\n () => {\n const database = new DatabaseManager(\n withDefaults(\n databaseConfigDefaults(),\n this.app.config.get<DatabaseConfig>(\"database\", {}),\n ),\n );\n\n warnIfOrmUnavailable(database);\n return database;\n },\n );\n }\n\n /**\n * Closes every connection's pool. Registered early, so it runs late: after\n * the queue and the scheduler have waited for their jobs, which still need\n * it. Bun's `close()` lets a query already sent finish.\n *\n * On the way out of a production server this only tidies up before the\n * exit. Under `gemi dev` it is the whole point: a `bun --hot` reload boots\n * a new application with a new pool, and the replaced one's is closed here\n * rather than left holding its connections for the life of the process\n * (#652).\n */\n async shutdown() {\n // Resolving the manager now would open a pool only to close it.\n if (!this.app.resolved(DatabaseManager)) return;\n await this.app.make(DatabaseManager).close();\n }\n}\n\n/**\n * Say it at boot, not on the first model query.\n *\n * `DatabaseManager` connects to MySQL and MariaDB without complaint — Bun's\n * client speaks them — and the ORM's compiler has no dialect for either. So a\n * deploy pointed at one starts, passes a health check, serves whatever does not\n * touch a model, and raises `UnsupportedDialectError` on the first `findMany`.\n * That is the latest and most expensive moment to learn it.\n *\n * A **warning rather than a throw**, deliberately: raw SQL through `DB.query`\n * and `DB.sql` genuinely works on those dialects, and so do transactions.\n * Refusing to construct the manager would break code that is correct today to\n * pre-empt an error the ORM already raises clearly. The supported set is a\n * property of the query compiler, not of the connection.\n *\n * Development only, for the same reason the slow-transaction warning is: it is\n * a diagnostic aimed at whoever is choosing the database, and it should not\n * add noise to a production log every time the container starts.\n */\nfunction warnIfOrmUnavailable(database: DatabaseManager): void {\n if (process.env.NODE_ENV !== \"development\") return;\n\n // Every connection, not only the default one. A named connection is a whole\n // pool an application will run model queries on — `Model.on(\"analytics\")` —\n // so it can be pointed at MySQL exactly as the default can, and warning about\n // only one of them would make the check pass while the query that raises is\n // on the other.\n for (const name of database.connectionNames) {\n const connection = database.connection(name);\n if (ormSupports(connection.dialect)) continue;\n\n const source =\n name === database.name\n ? \"DATABASE_URL\"\n : `The \"${name}\" database connection`;\n\n console.warn(\n `[gemi] ${source} points at ${connection.dialect}, which the gemi ORM ` +\n `does not implement — only sqlite and postgres are. The connection ` +\n `works, so raw SQL through DB.query / DB.sql and transactions are ` +\n `fine, but every model operation will raise ` +\n `UnsupportedDialectError.\\n(development only)`,\n );\n }\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";8LAMO,AAAM,IAAgC,LAAgB,CAC3D,QAAQ,EAAG,CACT,KAAK,IAAI,UACP,EACA,IAAM,CACJ,IAAM,EAAW,IAAI,EACnB,EACE,EAAuB,EACvB,KAAK,IAAI,OAAO,IAAoB,WAAY,CAAC,CAAC,CACpD,CACF,EAGA,OADA,EAAqB,CAAQ,EACtB,EAEX,OAcI,SAAQ,EAAG,CAEf,GAAI,CAAC,KAAK,IAAI,SAAS,CAAe,EAAG,OACzC,MAAM,KAAK,IAAI,KAAK,CAAe,EAAE,MAAM,EAE/C,CAqBA,SAAS,CAAoB,CAAC,EAAiC,CAC7D,GAAI,mBAAyB,cAAe,OAO5C,QAAW,KAAQ,EAAS,gBAAiB,CAC3C,IAAM,EAAa,EAAS,WAAW,CAAI,EAC3C,GAAI,EAAY,EAAW,OAAO,EAAG,SAErC,IAAM,EACJ,IAAS,EAAS,KACd,eACA,QAAQ,yBAEd,QAAQ,KACN,UAAU,eAAoB,EAAW,+BACvC,0EACA;AAAA,mBAGJ",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "832A59899C6D5B0964756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
+
import{a,b,c,d,e,f,g}from"./chunk-mqfzdfnz.js";import"./chunk-d2gfcf85.js";import"./chunk-fre6f4nk.js";import"./chunk-vw8849ys.js";export{g as fromEnv,c as ENV_SESSION,b as ENV_SECRET,a as ENV_KEY,d as ENV_EXPIRATION,e as ENV_CREDENTIAL_SCOPE,f as ENV_ACCOUNT_ID};
|
|
3
3
|
|
|
4
4
|
//# debugId=30E142423ED216F064756E2164756E21
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Q as ne}from"./chunk-
|
|
2
|
+
import{Q as ne}from"./chunk-d2gfcf85.js";import{_ as C}from"./chunk-eqse2m6n.js";import"./chunk-jdhdrr2k.js";import{aa as _}from"./chunk-fre6f4nk.js";import{qi as c,ui as F}from"./chunk-vw8849ys.js";var x=c(_(),1),T=c(C(),1);var q=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var D=c(ne(),1);var u=c(_(),1),m=c(C(),1);var W=300000,h="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var j=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-yhrye9cm.js").then((m)=>c(m.default,1)),n=(f)=>o.clientConfig?.[f]??o.parentClientConfig?.[f]??r?.[f];return new t(Object.assign({},o.clientConfig??{},{region:e??o.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))};var X=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-yhrye9cm.js").then((m)=>c(m.default,1));return(await j(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var z=c(_(),1);var P=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new z.TokenProviderError(`Token is expired. ${h}`,!1)};var J=c(_(),1);var g=(e,o,r=!1)=>{if(typeof o>"u")throw new J.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${h}`,!1)};var V=c(C(),1);import{promises as re}from"fs";var{writeFile:te}=re,Y=(e,o)=>{let r=V.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return te(r,t)};var B=new Date(0),Q=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await m.parseKnownFiles(e),t=m.getProfileName({profile:e.profile??o?.profile}),n=r[t];if(!n)throw new u.TokenProviderError(`Profile '${t}' could not be found in shared credentials file.`,!1);else if(!n.sso_session)throw new u.TokenProviderError(`Profile '${t}' is missing required property 'sso_session'.`);let a=n.sso_session,p=(await m.loadSsoSessionData(e))[a];if(!p)throw new u.TokenProviderError(`Sso session '${a}' could not be found in shared credentials file.`,!1);for(let i of["sso_start_url","sso_region"])if(!p[i])throw new u.TokenProviderError(`Sso session '${a}' is missing required property '${i}'.`,!1);let{sso_start_url:S,sso_region:I}=p,s;try{s=await m.getSSOTokenFromFile(a)}catch(i){throw new u.TokenProviderError(`The SSO session token associated with profile=${t} was not found or is invalid. ${h}`,!1)}g("accessToken",s.accessToken),g("expiresAt",s.expiresAt);let{accessToken:y,expiresAt:E}=s,l={token:y,expiration:new Date(E)};if(l.expiration.getTime()-Date.now()>W)return l;if(Date.now()-B.getTime()<30000)return P(l),l;g("clientId",s.clientId,!0),g("clientSecret",s.clientSecret,!0),g("refreshToken",s.refreshToken,!0);try{B.setTime(Date.now());let i=await X(s,I,e,o);g("accessToken",i.accessToken),g("expiresIn",i.expiresIn);let O=new Date(Date.now()+i.expiresIn*1000);try{await Y(a,{...s,accessToken:i.accessToken,expiresAt:O.toISOString(),refreshToken:i.refreshToken})}catch(R){}return{token:i.accessToken,expiration:O}}catch(i){return P(l),l}};var k=c(_(),1),Z=c(C(),1),A=!1,$=async({ssoStartUrl:e,ssoSession:o,ssoAccountId:r,ssoRegion:t,ssoRoleName:n,ssoClient:a,clientConfig:f,parentClientConfig:p,callerClientConfig:S,profile:I,filepath:s,configFilepath:y,ignoreCache:E,logger:l})=>{let i,O="To refresh this SSO session run aws sso login with the corresponding profile.";if(o)try{let w=await Q({profile:I,filepath:s,configFilepath:y,ignoreCache:E})();i={accessToken:w.token,expiresAt:new Date(w.expiration).toISOString()}}catch(w){throw new k.CredentialsProviderError(w.message,{tryNextLink:A,logger:l})}else try{i=await Z.getSSOTokenFromFile(e)}catch(w){throw new k.CredentialsProviderError("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:A,logger:l})}if(new Date(i.expiresAt).getTime()-Date.now()<=0)throw new k.CredentialsProviderError("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:A,logger:l});let{accessToken:R}=i,{SSOClient:d,GetRoleCredentialsCommand:N}=await import("./chunk-98m15b9x.js"),se=a||new d(Object.assign({},f??{},{logger:f?.logger??S?.logger??p?.logger,region:f?.region??t,userAgentAppId:f?.userAgentAppId??S?.userAgentAppId??p?.userAgentAppId})),L;try{L=await se.send(new N({accountId:r,roleName:n,accessToken:R}))}catch(w){throw new k.CredentialsProviderError(w,{tryNextLink:A,logger:l})}let{roleCredentials:{accessKeyId:M,secretAccessKey:G,sessionToken:K,expiration:b,credentialScope:H,accountId:U}={}}=L;if(!M||!G||!K||!b)throw new k.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:A,logger:l});let v={accessKeyId:M,secretAccessKey:G,sessionToken:K,expiration:new Date(b),...H&&{credentialScope:H},...U&&{accountId:U}};if(o)D.setCredentialFeature(v,"CREDENTIALS_SSO","s");else D.setCredentialFeature(v,"CREDENTIALS_SSO_LEGACY","u");return v};var ee=c(_(),1),oe=(e,o)=>{let{sso_start_url:r,sso_account_id:t,sso_region:n,sso_role_name:a}=e;if(!r||!t||!n||!a)throw new ee.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(e).join(", ")}
|
|
3
3
|
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:o});return e};var Ce=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoSession:f}=e,{ssoClient:p}=e,S=T.getProfileName({profile:e.profile??o?.profile});if(!r&&!t&&!n&&!a&&!f){let s=(await T.parseKnownFiles(e))[S];if(!s)throw new x.CredentialsProviderError(`Profile ${S} was not found.`,{logger:e.logger});if(!q(s))throw new x.CredentialsProviderError(`Profile ${S} is not configured with SSO credentials.`,{logger:e.logger});if(s?.sso_session){let d=(await T.loadSsoSessionData(e))[s.sso_session],N=` configurations in profile ${S} and sso-session ${s.sso_session}`;if(n&&n!==d.sso_region)throw new x.CredentialsProviderError("Conflicting SSO region"+N,{tryNextLink:!1,logger:e.logger});if(r&&r!==d.sso_start_url)throw new x.CredentialsProviderError("Conflicting SSO start_url"+N,{tryNextLink:!1,logger:e.logger});s.sso_region=d.sso_region,s.sso_start_url=d.sso_start_url}let{sso_start_url:y,sso_account_id:E,sso_region:l,sso_role_name:i,sso_session:O}=oe(s,e.logger);return $({ssoStartUrl:y,ssoSession:O,ssoAccountId:E,ssoRegion:l,ssoRoleName:i,ssoClient:p,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})}else if(!r||!t||!n||!a)throw new x.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:e.logger});else return $({ssoStartUrl:r,ssoSession:f,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoClient:p,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})};export{oe as validateSsoProfile,q as isSsoProfile,Ce as fromSSO};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=E84EDBCB5DB762B464756E2164756E21
|
|
@@ -15,6 +15,6 @@
|
|
|
15
15
|
"import { CredentialsProviderError } from \"@smithy/property-provider\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n"
|
|
16
16
|
],
|
|
17
17
|
"mappings": ";+NAAA,SACA,KCDO,FAAM,JAAe,CAAC,IAAQ,IAChC,OAAO,EAAI,gBAAkB,UAC1B,OAAO,EAAI,iBAAmB,UAC9B,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,aAAe,UAC1B,OAAO,EAAI,gBAAkB,UCLrC,gBCAA,eACA,WCDO,IAAM,EAAmB,OACnB,EAAkB,kFCDxB,IAAM,EAAmB,MAAO,EAAW,EAAO,CAAC,EAAG,IAAuB,CAChF,IAAQ,iBAAkB,KAAa,yDACjC,EAAW,CAAC,IAAS,EAAK,eAAe,IAAS,EAAK,qBAAqB,IAAS,IAAqB,GAMhH,OALsB,IAAI,EAAc,OAAO,OAAO,CAAC,EAAG,EAAK,cAAgB,CAAC,EAAG,CAC/E,OAAQ,GAAa,EAAK,cAAc,OACxC,OAAQ,EAAS,QAAQ,EACzB,eAAgB,EAAS,gBAAgB,CAC7C,CAAC,CAAC,GCNC,IAAM,EAAqB,MAAO,EAAU,EAAW,EAAO,CAAC,EAAG,IAAuB,CAC5F,IAAQ,sBAAuB,KAAa,yDAE5C,OADsB,MAAM,EAAiB,EAAW,EAAM,CAAkB,GAC3D,KAAK,IAAI,EAAmB,CAC7C,SAAU,EAAS,SACnB,aAAc,EAAS,aACvB,aAAc,EAAS,aACvB,UAAW,eACf,CAAC,CAAC,GCTN,eAE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C,IAAQ,gBAAe,iBAAgB,aAAY,gBAAe,eAAgB,GAAmB,EAAS,EAAK,MAAM,EACzH,OAAO,EAAsB,CACzB,YAAa,EACb,WAAY,EACZ,aAAc,EACd,UAAW,EACX,YAAa,EACb,UAAW,EACX,aAAc,EAAK,aACnB,mBAAoB,EAAK,mBACzB,mBAAoB,EAAK,mBACzB,QAAS,EACT,SAAU,EAAK,SACf,eAAgB,EAAK,eACrB,YAAa,EAAK,YAClB,OAAQ,EAAK,MACjB,CAAC,EAEA,QAAI,CAAC,GAAe,CAAC,GAAgB,CAAC,GAAa,CAAC,EACrD,MAAM,IAAI,2BAAyB,+HAC8B,CAAE,YAAa,GAAO,OAAQ,EAAK,MAAO,CAAC,EAG5G,YAAO,EAAsB,CACzB,cACA,aACA,eACA,YACA,cACA,YACA,aAAc,EAAK,aACnB,mBAAoB,EAAK,mBACzB,mBAAoB,EAAK,mBACzB,QAAS,EACT,SAAU,EAAK,SACf,eAAgB,EAAK,eACrB,YAAa,EAAK,YAClB,OAAQ,EAAK,MACjB,CAAC",
|
|
18
|
-
"debugId": "
|
|
18
|
+
"debugId": "E84EDBCB5DB762B464756E2164756E21",
|
|
19
19
|
"names": []
|
|
20
20
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sb as oZ,Vb as t,Wb as aZ,dc as XZ}from"./chunk-wysm6qte.js";import{oc as DZ,qc as e,sc as U3,tc as B3,vc as C3}from"./chunk-7rmjr8p7.js";import{Ac as N3,Cc as z3,Dc as X3,Ec as D,Fc as Y3,Gc as K3,Ic as H3,xc as W3}from"./chunk-8rt4wx8z.js";import{Lc as F}from"./chunk-n672d4g8.js";import{Ae as _Z,Jd as p,Td as J3,Ud as LZ,Ve as yZ,Yd as r,ad as D3,ed as v,ge as TZ,hd as sZ,ie as $Z,ld as A3,me as SZ,ue as l,ye as m,ze as WZ}from"./chunk-v9na3dny.js";import{Xe as I3,Ye as AZ}from"./chunk-kqb4s1r0.js";import{Fg as qZ,Hg as ZZ,Ig as a,Jg as i,pg as b,rg as PZ}from"./chunk-0n9vs1ad.js";import{Vg as tZ}from"./chunk-jzp0fs6h.js";import{Wg as G3,Yg as k}from"./chunk-8k8534kg.js";import{Zg as _}from"./chunk-583vxa2v.js";import{dh as P3}from"./chunk-8c2fs0n0.js";import{Th as OZ}from"./chunk-5j76r5q8.js";import{Zh as V3,ai as g}from"./chunk-j3nr4cg0.js";var T3="mcp",S3=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class L extends XZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}class d extends Error{reason;constructor(Z,$){super(Z);this.reason=$;this.name="McpCallRefusedError"}}var j3=/^[A-Za-z0-9_-]{1,64}$/,M3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,jZ=4000,y=1e5,k3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class f{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;constructor(Z,$,G={}){this.router=Z;this.dispatcher=$;this.files=E3(G.files);for(let[W,z]of Object.entries(Z.routes??{}))this.plans.set(W,this.plan(W,z));this.resolveScopes()}list(Z,$){if(MZ(Z),Z.kind==="local")return this.descriptors($);let G=[];for(let[W,z]of this.plans){if(!z.remote||!this.grants(Z.principal,W))continue;if(kZ(z.remote,$))G.push(z.remote)}return G}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values())if(kZ(G,Z))$.push(G);return $}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([Z,{description:$}])=>({name:Z,description:$}))}scopesFor(Z){return[...this.scopeTools].filter(([,{tools:$}])=>$.has(Z)).map(([$])=>$)}async execute(Z,$,G,W,z={}){MZ(Z);let X=this.plans.get($);if(Z.kind==="remote"){if(!X?.remote||!this.grants(Z.principal,$))throw new d(`There is no tool named "${$}".`,"unknown-tool");if(X.descriptor.requiresApproval&&z.approved!==!0)throw new d(`"${$}" needs the user's approval, and this call does not have it.`,"approval-required");W=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${$}".`);let Y=X,K=Z.kind==="remote"?Y.remote:Y.descriptor,U=K.inputSchema.safeParse(G);if(U.ok===!1)throw new L(`Invalid arguments for "${$}": ${U.errors.join(", ")}`);let H=U.value,Q={caller:Z,req:Z.req,tool:K,input:H,ctx:W},V=await this.fillPath(Y,Q),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(I!==K.url)throw new L(`"${$}" has nothing at ${V}.`,404);let C={};for(let q of Y.jsonKeys)if(H[q]!==void 0)C[q]=H[q];let P,x="";if(Y.fileFields.length>0)P=await this.formData(Y,C,Q);else if(K.method==="GET")x=c3(C);else if(Y.jsonKeys.length>0)P=C;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,w={...j?{credentials:j}:{},...z.signal?{signal:z.signal}:{},...z.progress?{progress:z.progress}:{},...Z.kind==="remote"?{identity:{user:Z.principal.user,grant:{via:Z.principal.via,id:Z.principal.id,scopes:Z.principal.scopes,...Z.principal.clientId?{clientId:Z.principal.clientId}:{}}}}:{}},u;try{let q=x?`${V}?${x}`:V;u=Object.keys(w).length>0?await this.dispatcher.dispatchAs(Z.req,K.method,q,P,w):await this.dispatcher.dispatchAs(Z.req,K.method,q,P)}catch(q){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,q),new L(`"${$}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await bZ($,u);return await this.project(Y,Q,u)}plan(Z,$){if(!j3.test(Z))throw Error(`McpRouter: "${Z}" 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 G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:W,url:z,meta:X}=$;if(z.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[z]?.[W];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...z.matchAll(M3)].map(([,B,A])=>({name:B,modifier:A})),U=X.params??{};for(let B of K)if(!(B.name in U))throw Error(`${G}: the path param "${B.name}" must be bound or declared "input".`);for(let[B,A]of Object.entries(U)){if(!K.some((M)=>M.name===B))throw Error(`${G}: "${B}" in params is not a param of the url.`);if(EZ(A))v3(G,`params.${B}`,A);else RZ(G,`params.${B}`,A)}let H=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(Q.properties)}let V=Object.entries(X.files??{}).map(([B,A])=>({name:B,binder:A}));for(let B of V)RZ(G,`files.${B.name}`,B.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${G}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${G}: title must be a non-empty string.`);let I=m3(G,W,X.annotations);if(V.length>0&&W==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let C={},P=(B,A)=>{if(B in C)throw Error(`${G}: "${B}" is the input key of two params or files, and the model can only send one.`);C[B]=A},x=new Map,j=new Map;for(let B of K){let A=U[B.name];if(A==="input"){let M=b.string().describe(`The ":${B.name}" segment of the url.`);P(B.name,B.modifier==="?"||B.modifier==="*"?M.optional():M)}else if(EZ(A)){let M=A.as??B.name;P(M,A.input),j.set(B.name,{key:M,param:A})}else x.set(B.name,A)}let w={};for(let B of V)if(B.binder==="input")P(B.name,b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),w[B.name]=this.remoteFileSchema();let u=[...Object.keys(C),...V.map((B)=>B.name)];for(let B of new Set(u))if(H.includes(B))throw Error(`${G}: "${B}" is both an input field and a param or file, and the model can only send one.`);let q=Object.freeze({name:Z,description:X.description,method:W,url:z,inputSchema:wZ(X.input,Q,b.object(C)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),q3=!V.every((B)=>B.binder==="input")?null:V.length===0?q:Object.freeze({...q,inputSchema:wZ(X.input,Q,b.object(u3(C,Object.keys(w))),w)});return{descriptor:q,remote:q3,params:K,paramBinders:x,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:Z,fetch:$}=this.files,G={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 ${Z} bytes decoded.`}};if($)G.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let W={type:"object",description:$?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:G,required:["name","mimeType"],additionalProperties:!1},z=Object.keys(G),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],U={};for(let H of Object.keys(Y))if(!z.includes(H))K.push(`a file has no field "${H}"`);for(let H of z){let Q=Y[H];if(Q===void 0||Q===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof Q!=="string")K.push(`a file's "${H}" must be a string`);else U[H]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:U}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}async fillPath(Z,$){let{input:G,req:W}=$,z=Z.descriptor.url;for(let X of Z.params){let Y=Z.paramBinders.get(X.name),K=Z.modelParams.get(X.name),U;if(Y||K){if(U=K?await this.bind(Z,`the param "${X.name}"`,()=>K.param.bind(G[K.key],W,$),{refusals:!0}):await this.bind(Z,`the param "${X.name}"`,()=>Y(W,$)),U===void 0||U===null||U==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(U)}.`),new L(`"${Z.descriptor.name}" failed on the server.`,500)}else U=G[X.name];let H=`:${X.name}${X.modifier}`;if(U===void 0||U===null||U===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new L(`"${X.name}" of "${Z.descriptor.name}" must not be empty.`);z=z.replace(`/${H}`,"");continue}z=z.replace(H,d3(Z.descriptor.name,X,String(U)))}return z}async formData(Z,$,G){let{input:W,ctx:z}=G,X=Z.descriptor.name;if(G.caller.kind==="remote"){let K=new FormData;for(let[U,H]of Object.entries($))zZ(K,U,H);for(let U of Z.fileFields)K.append(U.name,await this.remoteFile(X,U.name,W[U.name]));return K}if(!z)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,U]of Object.entries($))zZ(Y,K,U);for(let K of Z.fileFields){let U=K.binder==="input"?W[K.name]:await this.bind(Z,`the file "${K.name}"`,()=>K.binder(z,G));if(typeof U!=="string"||U==="")throw new L(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await z.attachments.file(U))}return Y}async remoteFile(Z,$,G){let W=(Q)=>new L(`"${$}" of "${Z}" ${Q}`,400),z=G,{maxBytes:X,fetch:Y}=this.files;if(!w3(z.name))throw W("needs a name of 1 to 255 characters, without control characters or slashes.");if(!b3.test(z.mimeType))throw W(`has a mimeType that is not a media type: "${z.mimeType.slice(0,100)}".`);let K=typeof z.data==="string",U=typeof z.url==="string";if(K===U)throw W(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=z.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-f3(Q)>X)throw W(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!y3.test(Q))throw W("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],z.name,{type:z.mimeType})}if(!Y)throw W("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(z.url)}catch{throw W("has a url that is not a URL.")}if(H.protocol!=="https:")throw W("can only be fetched from an https URL.");try{let Q=await yZ(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw W(`could not be fetched: ${H.host} answered ${Q.status}.`);let V=await Q.arrayBuffer();return new File([V],z.name,{type:z.mimeType})}catch(Q){if(Q instanceof L)throw Q;throw W(`could not be fetched from ${H.host}: ${Q instanceof Error?Q.message:"failed"}.`)}}grants(Z,$){for(let G of Z.scopes??[])if(this.scopeTools.get(G)?.tools.has($))return!0;return!1}resolveScopes(){let Z=this.router.scopes;if(Z===void 0){this.scopeTools.set(T3,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof Z!=="object"||Z===null)throw Error("McpRouter: scopes must be an object of scope names.");let $=new Set([...this.plans.values()].flatMap(({descriptor:G})=>G.tags));for(let[G,W]of Object.entries(Z)){let z=`McpRouter: scope "${G}"`;if(!S3.test(G))throw Error(`${z} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof W?.description!=="string"||W.description==="")throw Error(`${z} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of W.tags??[]){if(!$.has(Y))throw Error(`${z} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:U}]of this.plans)if(U.tags.includes(Y))X.add(K)}for(let Y of W.names??[]){if(!this.plans.has(Y))throw Error(`${z} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${z} reaches no tool. Give it tags or names.`);this.scopeTools.set(G,{description:W.description,tools:X})}}async project(Z,$,G){let{name:W,outputSchema:z}=Z.descriptor;if(G.status<200||G.status>=300)return await bZ(W,G);let X=(V,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${W}" ${V}`);else console.error(`[gemi/mcp] "${W}" ${V}`,I);return new L(`"${W}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),K=await G.text(),U=null;if(K!=="")try{U=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 H=U;if(Z.result)try{H=await Z.result(U,$)}catch(V){throw X("failed in its result projection:",V)}if(z){let V=z.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let Q=JSON.stringify(H);if(Q!==void 0&&Q.length>y)return`${Q.slice(0,y)}\u2026 [cut at ${y} of ${Q.length} characters]`;return H}async bind(Z,$,G,W={}){try{return await G()}catch(z){if(W.refusals&&z instanceof XZ)throw z;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,z),new L(`"${Z.descriptor.name}" failed on the server.`,500)}}}function MZ(Z){if(Z?.kind==="local"&&Z.req)return;if(Z?.kind==="remote"&&Z.req&&Z.principal?.user&&typeof Z.principal.id==="string"&&Array.isArray(Z.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 kZ(Z,$){if($?.names&&!$.names.includes(Z.name))return!1;if($?.tags&&!Z.tags.some((G)=>$.tags.includes(G)))return!1;return!0}var R3=10485760;function E3(Z){let $=Z?.maxBytes??R3;if(!Number.isSafeInteger($)||$<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let G=Z?.fetchUrls===!0?{}:typeof Z?.fetchUrls==="object"&&Z.fetchUrls!==null?Z.fetchUrls:null;return{maxBytes:$,fetch:G}}function w3(Z){if(Z.length===0||Z.length>255)return!1;for(let $ of Z){let G=$.codePointAt(0);if(G<32||G===127||$==="/"||$==="\\")return!1}return!0}var b3=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,y3=/^[A-Za-z0-9+/]*={0,2}$/;function f3(Z){return Z.endsWith("==")?2:Z.endsWith("=")?1:0}function RZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function EZ(Z){return Z instanceof Object&&Z.__internal_brand==="McpModelParam"}function v3(Z,$,G){if(G.as!==void 0&&(typeof G.as!=="string"||G.as===""))throw Error(`${Z}: ${$}.as must be a non-empty string.`);let W=G.input;if(typeof W?.safeParse!=="function"||typeof W.toJSONSchema!=="function")throw Error(`${Z}: ${$}.input must be a schema, built with s.`);if(typeof G.bind!=="function")throw Error(`${Z}: ${$}.bind must be a function.`)}var g3=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function h3(Z){switch(Z){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function m3(Z,$,G){if(G!==void 0&&(typeof G!=="object"||G===null))throw Error(`${Z}: annotations must be an object of hints.`);let W=h3($);for(let[z,X]of Object.entries(G??{})){if(!g3.has(z))throw Error(`${Z}: "${z}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${Z}: annotations.${z} must be true or false.`);W[z]=X}if(W.readOnlyHint===!0&&(W.destructiveHint||W.idempotentHint))throw Error(`${Z} is read-only${G?.readOnlyHint?"":` (a ${$})`} and also ${W.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(W)}function wZ(Z,$,G,W={}){let z=G.toJSONSchema(),X=Object.fromEntries(Object.entries(W).map(([U,H])=>[U,H.toJSONSchema()])),Y={...$??{},type:"object",properties:{...$?.properties??{},...z.properties,...X},required:[...$?.required??[],...z.required??[],...Object.keys(W)],additionalProperties:!1},K=(U)=>{if(typeof U!=="object"||U===null||Array.isArray(U))return{ok:!1,errors:["expected an object"]};let H=[],Q={};if(Z){let I=Z.safeParse(U);if(I.ok===!1)H.push(...I.errors);else Q={...I.value}}let V=G.safeParse(U);if(V.ok===!1)H.push(...V.errors);else Q={...Q,...V.value};for(let[I,C]of Object.entries(W)){let P=U[I];if(P===void 0){H.push(`"${I}" is required`);continue}let x=C.safeParse(P);if(x.ok===!1)H.push(...x.errors.map((j)=>`${I}: ${j}`));else Q[I]=x.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(U){let H=K(U);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function u3(Z,$){return Object.fromEntries(Object.entries(Z).filter(([G])=>!$.includes(G)))}function d3(Z,$,G){let W=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(W.some((z)=>z==="."||z===".."))throw new L(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return W.map(encodeURIComponent).join("/")}function zZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let W of G)zZ(Z,$,W);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function c3(Z){let $=new URLSearchParams,G=(W,z)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){for(let X of z)G(W,X);return}$.append(W,typeof z==="object"?JSON.stringify(z):String(z))};for(let[W,z]of Object.entries(Z))G(W,z);return $.toString()}async function bZ(Z,$){if($.status>=200&&$.status<300){let W=$.headers.get("Content-Type");if(W&&!k3.test(W)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${W}, which is not shown.`}let z=await $.text();if(z==="")return null;if(z.length>y)return`${z.slice(0,y)}\u2026 [cut at ${y} of ${z.length} characters]`;try{return JSON.parse(z)}catch{return z}}let G=await $.text();if($.status>=400&&$.status<500){let W=G.length>jZ?`${G.slice(0,jZ)}\u2026`:G;throw new L(`"${Z}" was refused with ${$.status}${W?`: ${W}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new L(`"${Z}" failed on the server.`,$.status)}import{createHash as p3,randomBytes as i3,timingSafeEqual as l3}from"crypto";function YZ(Z){let $=Z.headers.get("authorization");if(!$)return null;let G=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec($.trim());return G?G[1]:null}class n3{options;name="api-key";constructor(Z){this.options=Z;if(typeof Z?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test(Z.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof Z.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate(Z){return`${Z}${i3(32).toString("base64url")}`}static hash(Z){return p3("sha256").update(Z).digest("hex")}static hashesMatch(Z,$){let G=Buffer.from(Z),W=Buffer.from($);return G.length===W.length&&l3(G,W)}async resolve(Z){let $=YZ(Z);if(!$?.startsWith(this.options.prefix))return null;let G=await this.options.verify($,Z);if(!G)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!G.user||typeof G.id!=="string"||G.id===""||!Array.isArray(G.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:G.user,via:this.name,id:G.id,scopes:[...G.scopes]}}}}import{createHash as rZ,randomBytes as hZ}from"crypto";async function KZ(Z,$){let G=t3();if(!G)return null;let W=await G.consume(Z,$);return W.allowed?null:Math.max(1,Math.ceil(W.retryAfter/1000))}function t3(){try{let Z=g();return Z.bound(v)?Z.make(v):null}catch{return null}}var HZ=["2026-07-28"],n=["2025-11-25","2025-06-18","2025-03-26"],UZ=[...HZ,...n],QZ="io.modelcontextprotocol/protocolVersion",VZ="io.modelcontextprotocol/clientCapabilities";var BZ="io.modelcontextprotocol/serverInfo",N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class J extends Error{code;data;status;constructor(Z,$,G,W=200){super($);this.code=Z;this.data=G;this.status=W;this.name="JsonRpcError"}}function T(Z,$){return{jsonrpc:"2.0",id:Z,error:{code:$.code,message:$.message,...$.data!==void 0?{data:$.data}:{}}}}function fZ(Z){if(Array.isArray(Z))throw new J(N.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof Z!=="object"||Z===null||Z.jsonrpc!=="2.0")throw new J(N.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let $=Z,G=$.id,W=typeof G==="string"||typeof G==="number"&&Number.isFinite(G);if(typeof $.method==="string"){if($.params!==void 0&&(typeof $.params!=="object"||$.params===null||Array.isArray($.params)))throw new J(N.InvalidRequest,"params must be an object.",void 0,400);if(G===void 0)return{kind:"notification",message:$};if(!W)throw new J(N.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:$}}if(W&&(("result"in $)||("error"in $)))return{kind:"response",message:$};throw new J(N.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function IZ(Z,$){let G=Z.outputSchema?.toJSONSchema(),W={...Z.annotations,...Z.title&&!$?{title:Z.title}:{}};return{name:Z.name,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:Z.inputSchema.toJSONSchema(),...G&&($||G.type==="object")?{outputSchema:G}:{},...Object.keys(W).length>0?{annotations:W}:{}}}function O(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function vZ(Z){let $=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec(Z);if(!$)return Z;try{let G=Buffer.from($[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(G)}catch{return null}}import{createHmac as s3,timingSafeEqual as o3}from"crypto";function JZ(Z,$,G){let W=Buffer.from(JSON.stringify(G)).toString("base64url");return`${$}.${W}.${gZ(Z,$,W).toString("base64url")}`}function FZ(Z,$,G,W=Date.now()){if(typeof G!=="string"||G.length>8192)return null;let z=G.split(".");if(z.length!==3||z[0]!==$)return null;let[,X,Y]=z,K=Buffer.from(Y,"base64url"),U=gZ(Z,$,X);if(K.length!==U.length||!o3(K,U))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=W)return null;return H}function gZ(Z,$,G){return s3("sha256",t(Z)).update(`${$}.${G}`).digest()}var NZ="gemi.mcp.request-state.v1",mZ="gemi.mcp.session.v1",a3=86400000,uZ=600000,dZ="gemi_approval",xZ=2000,r3={limit:600,window:60},e3={limit:30,window:60};class c{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;pending=new Map;inflight=new Map;constructor(Z,$){this.registry=Z;if(typeof $.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=G8($.url);let G=$.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().");this.resolvers=G,t(NZ),this.context={resource:this.resource,registry:Z},this.allowedOrigins=new Set(($.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=$.rateLimit===!1?!1:$.rateLimit??r3,this.maxBodyBytes=$.maxBodyBytes??Math.ceil(Z.maxFileBytes*1.4)+1048576,this.serverInfo={name:$.server?.name??"gemi",version:$.server?.version??"1.0.0"},this.instructions=$.server?.instructions,this.nonces=$.nonces??new oZ,this.approvalTimeoutMs=$.approvalTimeoutMs??uZ;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle(Z){let $=new URL(Z.url);if($.host!==this.endpoint.host)return null;for(let z of this.resolvers){let X=await z.handle?.(Z,this.context);if(X)return X}if($.pathname!==this.endpoint.pathname)return null;let G=Z.headers.get("origin");if(G!==null&&!this.allowedOrigins.has(G))return S(T(null,new J(N.InvalidRequest,"Origin not allowed.")),403);let W=G?$8(G):{};if(Z.method==="OPTIONS")return new Response(null,{status:204,headers:{...W,"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(Z.method!=="POST")return cZ(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),W);return cZ(await this.post(Z),W)}async post(Z){let $=null;for(let Y of this.resolvers){let K=await Y.resolve(Z,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt(Z)??this.unauthorized(K.description);$={...K.principal,via:Y.name};break}if(!$)return(YZ(Z)!==null?await this.failedAttempt(Z):null)??this.unauthorized();let G=await this.spend($);if(G)return G;let W=Z.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(W))return new Response("Content-Type must be application/json.",{status:415});let z;try{z=JSON.parse(await Z8(Z,this.maxBodyBytes))}catch(Y){if(Y instanceof o)return S(T(null,new J(N.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return S(T(null,new J(N.ParseError,"Parse error.")),400)}let X=new PZ(Z,{},"api",this.endpoint.pathname);return await tZ.run(X,async()=>{try{return await this.dispatch(Z,X,$,z)}catch(Y){if(Y instanceof J){let K=O(z)&&(typeof z.id==="string"||typeof z.id==="number")?z.id:null;return S(T(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),S(T(null,new J(N.InternalError,"Internal error.")),500)}},{user:$.user})}async dispatch(Z,$,G,W){let z=fZ(W),X={kind:"remote",req:$,principal:G};if(z.kind==="response"){let P=this.session(Z,G),x=this.pending.get(String(z.message.id));if(x&&x.session===P.id)this.pending.delete(String(z.message.id)),x.resolve(z.message);return new Response(null,{status:202})}let{message:Y}=z,K=Y.params??{},U=O(K._meta)?K._meta:{};if(typeof U[QZ]==="string"){if(this.checkModernHeaders(Z,Y,U[QZ]),z.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,x)=>this.modern({principal:G,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:x}),iZ(K),Z.signal)}if(Y.method==="initialize"){if(z.kind!=="request")throw new J(N.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(z.message,K,G)}let H=this.session(Z,G),Q=Z.headers.get("mcp-protocol-version");if(Q!==null&&Q!==H.state.v)throw new J(N.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${H.state.v}.`,void 0,400);if(z.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(V,I);let C=AbortSignal.any([I.signal,Z.signal]);try{return await this.respond(Y,async(P,x)=>this.legacy({principal:G,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:x}),iZ(K)||z8(this.registry,Y,H.state),C,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern(Z){switch(Z.message.method){case"server/discover":return this.complete({supportedVersions:UZ,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:this.registry.list(Z.caller).map(($)=>IZ($,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`,void 0,404)}}async legacy(Z){switch(Z.message.method){case"ping":return{};case"tools/list":return{tools:this.registry.list(Z.caller).map(($)=>IZ($,!1))};case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`)}}complete(Z){return{resultType:"complete",...Z,_meta:{[BZ]:this.serverInfo}}}initialize(Z,$,G){let W=$.protocolVersion,z=n.includes(W)?W:n[0],X=O($.capabilities)?$.capabilities:{},Y={v:z,e:pZ(X.elicitation),p:s(G),exp:Date.now()+a3},K=JZ(mZ,"gms1",Y);return S({jsonrpc:"2.0",id:Z.id,result:{protocolVersion:z,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session(Z,$){let G=Z.headers.get("mcp-session-id");if(!G)throw new J(N.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let W=FZ(mZ,"gms1",G);if(!W||W.p!==s($))throw new J(N.InvalidRequest,"Session not found.",void 0,404);return{id:G,state:W}}checkModernHeaders(Z,$,G){if(!HZ.includes(G))throw new J(N.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:UZ,requested:G},400);let W=(Y)=>new J(N.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if(Z.headers.get("mcp-protocol-version")!==G)throw W("MCP-Protocol-Version does not match the protocol version in _meta.");if(Z.headers.get("mcp-method")!==$.method)throw W("Mcp-Method does not match the method.");let z=$.params??{},X=$.method==="tools/call"||$.method==="prompts/get"?z.name:$.method==="resources/read"?z.uri:void 0;if(X!==void 0){let Y=Z.headers.get("mcp-name");if(Y===null||vZ(Y)!==X)throw W("Mcp-Name does not match the request's name.")}}async callTool(Z){let{params:$,caller:G,principal:W}=Z,z=$.name;if(typeof z!=="string")throw new J(N.InvalidParams,"tools/call needs a tool name.");let X=$.arguments??{},Y=this.registry.list(G,{names:[z]})[0];if(!Y)throw new J(N.InvalidParams,`Unknown tool: ${z}`);let K=!1;if(Y.requiresApproval){let I=Y.inputSchema.safeParse(X);if(I.ok===!1)return this.toolResult(Z,{content:[{type:"text",text:`Invalid arguments for "${z}": ${I.errors.join(", ")}`}],isError:!0});let C=await this.approval(Z,Y,X);if(C.kind==="answer")return C.result;K=!0}let U=X8(Z),H;try{H=await this.registry.execute(G,z,X,void 0,{approved:K,signal:Z.signal,...U?{progress:U}:{}})}catch(I){if(I instanceof L)return this.toolResult(Z,{content:[{type:"text",text:I.message}],isError:!0});if(I instanceof d)throw new J(N.InvalidParams,I.reason==="unknown-tool"?`Unknown tool: ${z}`:I.message);return console.error(`[gemi/mcp] "${z}" failed for ${W.via}:${W.id}:`,I),this.toolResult(Z,{content:[{type:"text",text:`"${z}" failed on the server.`}],isError:!0})}let Q=typeof H==="string"?H:JSON.stringify(H??null),V=Y.outputSchema&&(Z.era.modern||O(H))?{structuredContent:H}:{};return this.toolResult(Z,{content:[{type:"text",text:Q}],...V,isError:!1})}toolResult(Z,$){return Z.era.modern?this.complete($):$}async approval(Z,$,G){let W=Y8($,G),z=(H)=>({kind:"answer",result:this.toolResult(Z,{content:[{type:"text",text:H}],isError:!0})});if(Z.era.modern){let H=O(Z.params._meta)?Z.params._meta:{},Q=O(H[VZ])?H[VZ]:{},V=O(Z.params.inputResponses)?Z.params.inputResponses:null,I=Z.params.requestState,C=W8(G);if(V&&I!==void 0){let x=FZ(NZ,"grs1",I);if(!x||x.p!==s(Z.principal)||x.t!==$.name||x.a!==C)throw new J(N.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(x.n,x.exp))throw new J(N.InvalidParams,"requestState has already been used.");return lZ(V[dZ])?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}if(!pZ(Q.elicitation))throw new J(N.MissingRequiredClientCapability,`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let P={p:s(Z.principal),t:$.name,a:C,n:hZ(16).toString("base64url"),exp:Date.now()+uZ};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[dZ]:{method:"elicitation/create",params:{mode:"form",...W}}},requestState:JZ(NZ,"grs1",P),_meta:{[BZ]:this.serverInfo}}}}let X=Z.era;if(!X.session.e||!Z.stream)return z(`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${hZ(12).toString("base64url")}`,K=X.sessionId,U=await new Promise((H)=>{let Q=setTimeout(()=>{this.pending.delete(Y),H(null)},this.approvalTimeoutMs),V=(I)=>{clearTimeout(Q),H(I)};this.pending.set(Y,{session:K,resolve:V}),Z.signal.addEventListener("abort",()=>{this.pending.delete(Y),V(null)}),Z.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...W}:W})});return U&&!U.error&&lZ(U.result)?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}async spendNonce(Z,$){try{return await this.nonces.consume(Z,$)}catch(G){return console.error("[gemi/mcp] Spending an approval failed:",G),!1}}async respond(Z,$,G,W,z){if(!G)try{let U=await $(null,W);return S({jsonrpc:"2.0",id:Z.id,result:U},200)}finally{z?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,W]),K=new eZ(()=>X.abort());return(async()=>{try{let U=await $(K,Y);K.send({jsonrpc:"2.0",id:Z.id,result:U})}catch(U){if(U instanceof J)K.send(T(Z.id,U));else console.error("[gemi/mcp] The MCP endpoint failed:",U),K.send(T(Z.id,new J(N.InternalError,"Internal error.")))}finally{z?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized(Z){let $=this.resolvers.map((W)=>W.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',G=Z?`${$}, error="invalid_token", error_description="${Z.replace(/["\\]/g,"")}"`:$;return S(T(null,new J(N.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":G})}async failedAttempt(Z){let $=sZ(new PZ(Z,{},"api",this.endpoint.pathname)),G=await KZ(`mcp-auth-failed:${$}`,e3);return G===null?null:nZ(G)}async spend(Z){if(!this.rateLimit)return null;let $=await KZ(`mcp-endpoint:${Z.via}:${Z.id}`,this.rateLimit);return $===null?null:nZ($)}}class eZ{readable;controller;closed=!1;encoder=new TextEncoder;constructor(Z){this.readable=new ReadableStream({start:($)=>{this.controller=$},cancel:()=>{this.closed=!0,Z()}})}send(Z){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
2
|
+
import{Sb as oZ,Vb as t,Wb as aZ,dc as XZ}from"./chunk-4088szy9.js";import{oc as DZ,qc as e,sc as U3,tc as B3,vc as C3}from"./chunk-ktr3k768.js";import{Ac as N3,Cc as z3,Dc as X3,Ec as D,Fc as Y3,Gc as K3,Ic as H3,xc as W3}from"./chunk-7vb4eey2.js";import{Lc as F}from"./chunk-n672d4g8.js";import{Ae as _Z,Jd as p,Td as J3,Ud as LZ,Ve as yZ,Yd as r,ad as D3,ed as v,ge as TZ,hd as sZ,ie as $Z,ld as A3,me as SZ,ue as l,ye as m,ze as WZ}from"./chunk-ms9k0rx6.js";import{Xe as I3,Ye as AZ}from"./chunk-whtzggn6.js";import{Gg as qZ,Ig as ZZ,Jg as a,Kg as i,pg as b,rg as PZ}from"./chunk-pn8v6fj2.js";import{Wg as tZ}from"./chunk-49nyyjfe.js";import{Xg as G3,Zg as k}from"./chunk-tn2bryy2.js";import{_g as _}from"./chunk-cbqazg9k.js";import{eh as P3}from"./chunk-1myhm0g3.js";import{Uh as OZ}from"./chunk-qsrcdzan.js";import{_h as V3,bi as g}from"./chunk-t4yh4nf9.js";var T3="mcp",S3=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class L extends XZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}class d extends Error{reason;constructor(Z,$){super(Z);this.reason=$;this.name="McpCallRefusedError"}}var j3=/^[A-Za-z0-9_-]{1,64}$/,M3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,jZ=4000,y=1e5,k3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class f{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;constructor(Z,$,G={}){this.router=Z;this.dispatcher=$;this.files=E3(G.files);for(let[W,z]of Object.entries(Z.routes??{}))this.plans.set(W,this.plan(W,z));this.resolveScopes()}list(Z,$){if(MZ(Z),Z.kind==="local")return this.descriptors($);let G=[];for(let[W,z]of this.plans){if(!z.remote||!this.grants(Z.principal,W))continue;if(kZ(z.remote,$))G.push(z.remote)}return G}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values())if(kZ(G,Z))$.push(G);return $}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([Z,{description:$}])=>({name:Z,description:$}))}scopesFor(Z){return[...this.scopeTools].filter(([,{tools:$}])=>$.has(Z)).map(([$])=>$)}async execute(Z,$,G,W,z={}){MZ(Z);let X=this.plans.get($);if(Z.kind==="remote"){if(!X?.remote||!this.grants(Z.principal,$))throw new d(`There is no tool named "${$}".`,"unknown-tool");if(X.descriptor.requiresApproval&&z.approved!==!0)throw new d(`"${$}" needs the user's approval, and this call does not have it.`,"approval-required");W=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${$}".`);let Y=X,K=Z.kind==="remote"?Y.remote:Y.descriptor,U=K.inputSchema.safeParse(G);if(U.ok===!1)throw new L(`Invalid arguments for "${$}": ${U.errors.join(", ")}`);let H=U.value,Q={caller:Z,req:Z.req,tool:K,input:H,ctx:W},V=await this.fillPath(Y,Q),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(I!==K.url)throw new L(`"${$}" has nothing at ${V}.`,404);let C={};for(let q of Y.jsonKeys)if(H[q]!==void 0)C[q]=H[q];let P,x="";if(Y.fileFields.length>0)P=await this.formData(Y,C,Q);else if(K.method==="GET")x=c3(C);else if(Y.jsonKeys.length>0)P=C;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,w={...j?{credentials:j}:{},...z.signal?{signal:z.signal}:{},...z.progress?{progress:z.progress}:{},...Z.kind==="remote"?{identity:{user:Z.principal.user,grant:{via:Z.principal.via,id:Z.principal.id,scopes:Z.principal.scopes,...Z.principal.clientId?{clientId:Z.principal.clientId}:{}}}}:{}},u;try{let q=x?`${V}?${x}`:V;u=Object.keys(w).length>0?await this.dispatcher.dispatchAs(Z.req,K.method,q,P,w):await this.dispatcher.dispatchAs(Z.req,K.method,q,P)}catch(q){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,q),new L(`"${$}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await bZ($,u);return await this.project(Y,Q,u)}plan(Z,$){if(!j3.test(Z))throw Error(`McpRouter: "${Z}" 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 G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:W,url:z,meta:X}=$;if(z.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[z]?.[W];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...z.matchAll(M3)].map(([,B,A])=>({name:B,modifier:A})),U=X.params??{};for(let B of K)if(!(B.name in U))throw Error(`${G}: the path param "${B.name}" must be bound or declared "input".`);for(let[B,A]of Object.entries(U)){if(!K.some((M)=>M.name===B))throw Error(`${G}: "${B}" in params is not a param of the url.`);if(EZ(A))v3(G,`params.${B}`,A);else RZ(G,`params.${B}`,A)}let H=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(Q.properties)}let V=Object.entries(X.files??{}).map(([B,A])=>({name:B,binder:A}));for(let B of V)RZ(G,`files.${B.name}`,B.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${G}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${G}: title must be a non-empty string.`);let I=m3(G,W,X.annotations);if(V.length>0&&W==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let C={},P=(B,A)=>{if(B in C)throw Error(`${G}: "${B}" is the input key of two params or files, and the model can only send one.`);C[B]=A},x=new Map,j=new Map;for(let B of K){let A=U[B.name];if(A==="input"){let M=b.string().describe(`The ":${B.name}" segment of the url.`);P(B.name,B.modifier==="?"||B.modifier==="*"?M.optional():M)}else if(EZ(A)){let M=A.as??B.name;P(M,A.input),j.set(B.name,{key:M,param:A})}else x.set(B.name,A)}let w={};for(let B of V)if(B.binder==="input")P(B.name,b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),w[B.name]=this.remoteFileSchema();let u=[...Object.keys(C),...V.map((B)=>B.name)];for(let B of new Set(u))if(H.includes(B))throw Error(`${G}: "${B}" is both an input field and a param or file, and the model can only send one.`);let q=Object.freeze({name:Z,description:X.description,method:W,url:z,inputSchema:wZ(X.input,Q,b.object(C)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),q3=!V.every((B)=>B.binder==="input")?null:V.length===0?q:Object.freeze({...q,inputSchema:wZ(X.input,Q,b.object(u3(C,Object.keys(w))),w)});return{descriptor:q,remote:q3,params:K,paramBinders:x,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:Z,fetch:$}=this.files,G={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 ${Z} bytes decoded.`}};if($)G.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let W={type:"object",description:$?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:G,required:["name","mimeType"],additionalProperties:!1},z=Object.keys(G),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],U={};for(let H of Object.keys(Y))if(!z.includes(H))K.push(`a file has no field "${H}"`);for(let H of z){let Q=Y[H];if(Q===void 0||Q===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof Q!=="string")K.push(`a file's "${H}" must be a string`);else U[H]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:U}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}async fillPath(Z,$){let{input:G,req:W}=$,z=Z.descriptor.url;for(let X of Z.params){let Y=Z.paramBinders.get(X.name),K=Z.modelParams.get(X.name),U;if(Y||K){if(U=K?await this.bind(Z,`the param "${X.name}"`,()=>K.param.bind(G[K.key],W,$),{refusals:!0}):await this.bind(Z,`the param "${X.name}"`,()=>Y(W,$)),U===void 0||U===null||U==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(U)}.`),new L(`"${Z.descriptor.name}" failed on the server.`,500)}else U=G[X.name];let H=`:${X.name}${X.modifier}`;if(U===void 0||U===null||U===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new L(`"${X.name}" of "${Z.descriptor.name}" must not be empty.`);z=z.replace(`/${H}`,"");continue}z=z.replace(H,d3(Z.descriptor.name,X,String(U)))}return z}async formData(Z,$,G){let{input:W,ctx:z}=G,X=Z.descriptor.name;if(G.caller.kind==="remote"){let K=new FormData;for(let[U,H]of Object.entries($))zZ(K,U,H);for(let U of Z.fileFields)K.append(U.name,await this.remoteFile(X,U.name,W[U.name]));return K}if(!z)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,U]of Object.entries($))zZ(Y,K,U);for(let K of Z.fileFields){let U=K.binder==="input"?W[K.name]:await this.bind(Z,`the file "${K.name}"`,()=>K.binder(z,G));if(typeof U!=="string"||U==="")throw new L(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await z.attachments.file(U))}return Y}async remoteFile(Z,$,G){let W=(Q)=>new L(`"${$}" of "${Z}" ${Q}`,400),z=G,{maxBytes:X,fetch:Y}=this.files;if(!w3(z.name))throw W("needs a name of 1 to 255 characters, without control characters or slashes.");if(!b3.test(z.mimeType))throw W(`has a mimeType that is not a media type: "${z.mimeType.slice(0,100)}".`);let K=typeof z.data==="string",U=typeof z.url==="string";if(K===U)throw W(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=z.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-f3(Q)>X)throw W(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!y3.test(Q))throw W("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],z.name,{type:z.mimeType})}if(!Y)throw W("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(z.url)}catch{throw W("has a url that is not a URL.")}if(H.protocol!=="https:")throw W("can only be fetched from an https URL.");try{let Q=await yZ(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw W(`could not be fetched: ${H.host} answered ${Q.status}.`);let V=await Q.arrayBuffer();return new File([V],z.name,{type:z.mimeType})}catch(Q){if(Q instanceof L)throw Q;throw W(`could not be fetched from ${H.host}: ${Q instanceof Error?Q.message:"failed"}.`)}}grants(Z,$){for(let G of Z.scopes??[])if(this.scopeTools.get(G)?.tools.has($))return!0;return!1}resolveScopes(){let Z=this.router.scopes;if(Z===void 0){this.scopeTools.set(T3,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof Z!=="object"||Z===null)throw Error("McpRouter: scopes must be an object of scope names.");let $=new Set([...this.plans.values()].flatMap(({descriptor:G})=>G.tags));for(let[G,W]of Object.entries(Z)){let z=`McpRouter: scope "${G}"`;if(!S3.test(G))throw Error(`${z} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof W?.description!=="string"||W.description==="")throw Error(`${z} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of W.tags??[]){if(!$.has(Y))throw Error(`${z} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:U}]of this.plans)if(U.tags.includes(Y))X.add(K)}for(let Y of W.names??[]){if(!this.plans.has(Y))throw Error(`${z} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${z} reaches no tool. Give it tags or names.`);this.scopeTools.set(G,{description:W.description,tools:X})}}async project(Z,$,G){let{name:W,outputSchema:z}=Z.descriptor;if(G.status<200||G.status>=300)return await bZ(W,G);let X=(V,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${W}" ${V}`);else console.error(`[gemi/mcp] "${W}" ${V}`,I);return new L(`"${W}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),K=await G.text(),U=null;if(K!=="")try{U=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 H=U;if(Z.result)try{H=await Z.result(U,$)}catch(V){throw X("failed in its result projection:",V)}if(z){let V=z.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let Q=JSON.stringify(H);if(Q!==void 0&&Q.length>y)return`${Q.slice(0,y)}\u2026 [cut at ${y} of ${Q.length} characters]`;return H}async bind(Z,$,G,W={}){try{return await G()}catch(z){if(W.refusals&&z instanceof XZ)throw z;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,z),new L(`"${Z.descriptor.name}" failed on the server.`,500)}}}function MZ(Z){if(Z?.kind==="local"&&Z.req)return;if(Z?.kind==="remote"&&Z.req&&Z.principal?.user&&typeof Z.principal.id==="string"&&Array.isArray(Z.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 kZ(Z,$){if($?.names&&!$.names.includes(Z.name))return!1;if($?.tags&&!Z.tags.some((G)=>$.tags.includes(G)))return!1;return!0}var R3=10485760;function E3(Z){let $=Z?.maxBytes??R3;if(!Number.isSafeInteger($)||$<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let G=Z?.fetchUrls===!0?{}:typeof Z?.fetchUrls==="object"&&Z.fetchUrls!==null?Z.fetchUrls:null;return{maxBytes:$,fetch:G}}function w3(Z){if(Z.length===0||Z.length>255)return!1;for(let $ of Z){let G=$.codePointAt(0);if(G<32||G===127||$==="/"||$==="\\")return!1}return!0}var b3=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,y3=/^[A-Za-z0-9+/]*={0,2}$/;function f3(Z){return Z.endsWith("==")?2:Z.endsWith("=")?1:0}function RZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function EZ(Z){return Z instanceof Object&&Z.__internal_brand==="McpModelParam"}function v3(Z,$,G){if(G.as!==void 0&&(typeof G.as!=="string"||G.as===""))throw Error(`${Z}: ${$}.as must be a non-empty string.`);let W=G.input;if(typeof W?.safeParse!=="function"||typeof W.toJSONSchema!=="function")throw Error(`${Z}: ${$}.input must be a schema, built with s.`);if(typeof G.bind!=="function")throw Error(`${Z}: ${$}.bind must be a function.`)}var g3=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function h3(Z){switch(Z){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function m3(Z,$,G){if(G!==void 0&&(typeof G!=="object"||G===null))throw Error(`${Z}: annotations must be an object of hints.`);let W=h3($);for(let[z,X]of Object.entries(G??{})){if(!g3.has(z))throw Error(`${Z}: "${z}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${Z}: annotations.${z} must be true or false.`);W[z]=X}if(W.readOnlyHint===!0&&(W.destructiveHint||W.idempotentHint))throw Error(`${Z} is read-only${G?.readOnlyHint?"":` (a ${$})`} and also ${W.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(W)}function wZ(Z,$,G,W={}){let z=G.toJSONSchema(),X=Object.fromEntries(Object.entries(W).map(([U,H])=>[U,H.toJSONSchema()])),Y={...$??{},type:"object",properties:{...$?.properties??{},...z.properties,...X},required:[...$?.required??[],...z.required??[],...Object.keys(W)],additionalProperties:!1},K=(U)=>{if(typeof U!=="object"||U===null||Array.isArray(U))return{ok:!1,errors:["expected an object"]};let H=[],Q={};if(Z){let I=Z.safeParse(U);if(I.ok===!1)H.push(...I.errors);else Q={...I.value}}let V=G.safeParse(U);if(V.ok===!1)H.push(...V.errors);else Q={...Q,...V.value};for(let[I,C]of Object.entries(W)){let P=U[I];if(P===void 0){H.push(`"${I}" is required`);continue}let x=C.safeParse(P);if(x.ok===!1)H.push(...x.errors.map((j)=>`${I}: ${j}`));else Q[I]=x.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(U){let H=K(U);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function u3(Z,$){return Object.fromEntries(Object.entries(Z).filter(([G])=>!$.includes(G)))}function d3(Z,$,G){let W=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(W.some((z)=>z==="."||z===".."))throw new L(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return W.map(encodeURIComponent).join("/")}function zZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let W of G)zZ(Z,$,W);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function c3(Z){let $=new URLSearchParams,G=(W,z)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){for(let X of z)G(W,X);return}$.append(W,typeof z==="object"?JSON.stringify(z):String(z))};for(let[W,z]of Object.entries(Z))G(W,z);return $.toString()}async function bZ(Z,$){if($.status>=200&&$.status<300){let W=$.headers.get("Content-Type");if(W&&!k3.test(W)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${W}, which is not shown.`}let z=await $.text();if(z==="")return null;if(z.length>y)return`${z.slice(0,y)}\u2026 [cut at ${y} of ${z.length} characters]`;try{return JSON.parse(z)}catch{return z}}let G=await $.text();if($.status>=400&&$.status<500){let W=G.length>jZ?`${G.slice(0,jZ)}\u2026`:G;throw new L(`"${Z}" was refused with ${$.status}${W?`: ${W}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new L(`"${Z}" failed on the server.`,$.status)}import{createHash as p3,randomBytes as i3,timingSafeEqual as l3}from"crypto";function YZ(Z){let $=Z.headers.get("authorization");if(!$)return null;let G=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec($.trim());return G?G[1]:null}class n3{options;name="api-key";constructor(Z){this.options=Z;if(typeof Z?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test(Z.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof Z.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate(Z){return`${Z}${i3(32).toString("base64url")}`}static hash(Z){return p3("sha256").update(Z).digest("hex")}static hashesMatch(Z,$){let G=Buffer.from(Z),W=Buffer.from($);return G.length===W.length&&l3(G,W)}async resolve(Z){let $=YZ(Z);if(!$?.startsWith(this.options.prefix))return null;let G=await this.options.verify($,Z);if(!G)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!G.user||typeof G.id!=="string"||G.id===""||!Array.isArray(G.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:G.user,via:this.name,id:G.id,scopes:[...G.scopes]}}}}import{createHash as rZ,randomBytes as hZ}from"crypto";async function KZ(Z,$){let G=t3();if(!G)return null;let W=await G.consume(Z,$);return W.allowed?null:Math.max(1,Math.ceil(W.retryAfter/1000))}function t3(){try{let Z=g();return Z.bound(v)?Z.make(v):null}catch{return null}}var HZ=["2026-07-28"],n=["2025-11-25","2025-06-18","2025-03-26"],UZ=[...HZ,...n],QZ="io.modelcontextprotocol/protocolVersion",VZ="io.modelcontextprotocol/clientCapabilities";var BZ="io.modelcontextprotocol/serverInfo",N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class J extends Error{code;data;status;constructor(Z,$,G,W=200){super($);this.code=Z;this.data=G;this.status=W;this.name="JsonRpcError"}}function T(Z,$){return{jsonrpc:"2.0",id:Z,error:{code:$.code,message:$.message,...$.data!==void 0?{data:$.data}:{}}}}function fZ(Z){if(Array.isArray(Z))throw new J(N.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof Z!=="object"||Z===null||Z.jsonrpc!=="2.0")throw new J(N.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let $=Z,G=$.id,W=typeof G==="string"||typeof G==="number"&&Number.isFinite(G);if(typeof $.method==="string"){if($.params!==void 0&&(typeof $.params!=="object"||$.params===null||Array.isArray($.params)))throw new J(N.InvalidRequest,"params must be an object.",void 0,400);if(G===void 0)return{kind:"notification",message:$};if(!W)throw new J(N.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:$}}if(W&&(("result"in $)||("error"in $)))return{kind:"response",message:$};throw new J(N.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function IZ(Z,$){let G=Z.outputSchema?.toJSONSchema(),W={...Z.annotations,...Z.title&&!$?{title:Z.title}:{}};return{name:Z.name,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:Z.inputSchema.toJSONSchema(),...G&&($||G.type==="object")?{outputSchema:G}:{},...Object.keys(W).length>0?{annotations:W}:{}}}function O(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function vZ(Z){let $=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec(Z);if(!$)return Z;try{let G=Buffer.from($[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(G)}catch{return null}}import{createHmac as s3,timingSafeEqual as o3}from"crypto";function JZ(Z,$,G){let W=Buffer.from(JSON.stringify(G)).toString("base64url");return`${$}.${W}.${gZ(Z,$,W).toString("base64url")}`}function FZ(Z,$,G,W=Date.now()){if(typeof G!=="string"||G.length>8192)return null;let z=G.split(".");if(z.length!==3||z[0]!==$)return null;let[,X,Y]=z,K=Buffer.from(Y,"base64url"),U=gZ(Z,$,X);if(K.length!==U.length||!o3(K,U))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=W)return null;return H}function gZ(Z,$,G){return s3("sha256",t(Z)).update(`${$}.${G}`).digest()}var NZ="gemi.mcp.request-state.v1",mZ="gemi.mcp.session.v1",a3=86400000,uZ=600000,dZ="gemi_approval",xZ=2000,r3={limit:600,window:60},e3={limit:30,window:60};class c{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;pending=new Map;inflight=new Map;constructor(Z,$){this.registry=Z;if(typeof $.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=G8($.url);let G=$.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().");this.resolvers=G,t(NZ),this.context={resource:this.resource,registry:Z},this.allowedOrigins=new Set(($.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=$.rateLimit===!1?!1:$.rateLimit??r3,this.maxBodyBytes=$.maxBodyBytes??Math.ceil(Z.maxFileBytes*1.4)+1048576,this.serverInfo={name:$.server?.name??"gemi",version:$.server?.version??"1.0.0"},this.instructions=$.server?.instructions,this.nonces=$.nonces??new oZ,this.approvalTimeoutMs=$.approvalTimeoutMs??uZ;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle(Z){let $=new URL(Z.url);if($.host!==this.endpoint.host)return null;for(let z of this.resolvers){let X=await z.handle?.(Z,this.context);if(X)return X}if($.pathname!==this.endpoint.pathname)return null;let G=Z.headers.get("origin");if(G!==null&&!this.allowedOrigins.has(G))return S(T(null,new J(N.InvalidRequest,"Origin not allowed.")),403);let W=G?$8(G):{};if(Z.method==="OPTIONS")return new Response(null,{status:204,headers:{...W,"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(Z.method!=="POST")return cZ(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),W);return cZ(await this.post(Z),W)}async post(Z){let $=null;for(let Y of this.resolvers){let K=await Y.resolve(Z,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt(Z)??this.unauthorized(K.description);$={...K.principal,via:Y.name};break}if(!$)return(YZ(Z)!==null?await this.failedAttempt(Z):null)??this.unauthorized();let G=await this.spend($);if(G)return G;let W=Z.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(W))return new Response("Content-Type must be application/json.",{status:415});let z;try{z=JSON.parse(await Z8(Z,this.maxBodyBytes))}catch(Y){if(Y instanceof o)return S(T(null,new J(N.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return S(T(null,new J(N.ParseError,"Parse error.")),400)}let X=new PZ(Z,{},"api",this.endpoint.pathname);return await tZ.run(X,async()=>{try{return await this.dispatch(Z,X,$,z)}catch(Y){if(Y instanceof J){let K=O(z)&&(typeof z.id==="string"||typeof z.id==="number")?z.id:null;return S(T(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),S(T(null,new J(N.InternalError,"Internal error.")),500)}},{user:$.user})}async dispatch(Z,$,G,W){let z=fZ(W),X={kind:"remote",req:$,principal:G};if(z.kind==="response"){let P=this.session(Z,G),x=this.pending.get(String(z.message.id));if(x&&x.session===P.id)this.pending.delete(String(z.message.id)),x.resolve(z.message);return new Response(null,{status:202})}let{message:Y}=z,K=Y.params??{},U=O(K._meta)?K._meta:{};if(typeof U[QZ]==="string"){if(this.checkModernHeaders(Z,Y,U[QZ]),z.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,x)=>this.modern({principal:G,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:x}),iZ(K),Z.signal)}if(Y.method==="initialize"){if(z.kind!=="request")throw new J(N.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(z.message,K,G)}let H=this.session(Z,G),Q=Z.headers.get("mcp-protocol-version");if(Q!==null&&Q!==H.state.v)throw new J(N.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${H.state.v}.`,void 0,400);if(z.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(V,I);let C=AbortSignal.any([I.signal,Z.signal]);try{return await this.respond(Y,async(P,x)=>this.legacy({principal:G,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:x}),iZ(K)||z8(this.registry,Y,H.state),C,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern(Z){switch(Z.message.method){case"server/discover":return this.complete({supportedVersions:UZ,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:this.registry.list(Z.caller).map(($)=>IZ($,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`,void 0,404)}}async legacy(Z){switch(Z.message.method){case"ping":return{};case"tools/list":return{tools:this.registry.list(Z.caller).map(($)=>IZ($,!1))};case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`)}}complete(Z){return{resultType:"complete",...Z,_meta:{[BZ]:this.serverInfo}}}initialize(Z,$,G){let W=$.protocolVersion,z=n.includes(W)?W:n[0],X=O($.capabilities)?$.capabilities:{},Y={v:z,e:pZ(X.elicitation),p:s(G),exp:Date.now()+a3},K=JZ(mZ,"gms1",Y);return S({jsonrpc:"2.0",id:Z.id,result:{protocolVersion:z,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session(Z,$){let G=Z.headers.get("mcp-session-id");if(!G)throw new J(N.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let W=FZ(mZ,"gms1",G);if(!W||W.p!==s($))throw new J(N.InvalidRequest,"Session not found.",void 0,404);return{id:G,state:W}}checkModernHeaders(Z,$,G){if(!HZ.includes(G))throw new J(N.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:UZ,requested:G},400);let W=(Y)=>new J(N.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if(Z.headers.get("mcp-protocol-version")!==G)throw W("MCP-Protocol-Version does not match the protocol version in _meta.");if(Z.headers.get("mcp-method")!==$.method)throw W("Mcp-Method does not match the method.");let z=$.params??{},X=$.method==="tools/call"||$.method==="prompts/get"?z.name:$.method==="resources/read"?z.uri:void 0;if(X!==void 0){let Y=Z.headers.get("mcp-name");if(Y===null||vZ(Y)!==X)throw W("Mcp-Name does not match the request's name.")}}async callTool(Z){let{params:$,caller:G,principal:W}=Z,z=$.name;if(typeof z!=="string")throw new J(N.InvalidParams,"tools/call needs a tool name.");let X=$.arguments??{},Y=this.registry.list(G,{names:[z]})[0];if(!Y)throw new J(N.InvalidParams,`Unknown tool: ${z}`);let K=!1;if(Y.requiresApproval){let I=Y.inputSchema.safeParse(X);if(I.ok===!1)return this.toolResult(Z,{content:[{type:"text",text:`Invalid arguments for "${z}": ${I.errors.join(", ")}`}],isError:!0});let C=await this.approval(Z,Y,X);if(C.kind==="answer")return C.result;K=!0}let U=X8(Z),H;try{H=await this.registry.execute(G,z,X,void 0,{approved:K,signal:Z.signal,...U?{progress:U}:{}})}catch(I){if(I instanceof L)return this.toolResult(Z,{content:[{type:"text",text:I.message}],isError:!0});if(I instanceof d)throw new J(N.InvalidParams,I.reason==="unknown-tool"?`Unknown tool: ${z}`:I.message);return console.error(`[gemi/mcp] "${z}" failed for ${W.via}:${W.id}:`,I),this.toolResult(Z,{content:[{type:"text",text:`"${z}" failed on the server.`}],isError:!0})}let Q=typeof H==="string"?H:JSON.stringify(H??null),V=Y.outputSchema&&(Z.era.modern||O(H))?{structuredContent:H}:{};return this.toolResult(Z,{content:[{type:"text",text:Q}],...V,isError:!1})}toolResult(Z,$){return Z.era.modern?this.complete($):$}async approval(Z,$,G){let W=Y8($,G),z=(H)=>({kind:"answer",result:this.toolResult(Z,{content:[{type:"text",text:H}],isError:!0})});if(Z.era.modern){let H=O(Z.params._meta)?Z.params._meta:{},Q=O(H[VZ])?H[VZ]:{},V=O(Z.params.inputResponses)?Z.params.inputResponses:null,I=Z.params.requestState,C=W8(G);if(V&&I!==void 0){let x=FZ(NZ,"grs1",I);if(!x||x.p!==s(Z.principal)||x.t!==$.name||x.a!==C)throw new J(N.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(x.n,x.exp))throw new J(N.InvalidParams,"requestState has already been used.");return lZ(V[dZ])?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}if(!pZ(Q.elicitation))throw new J(N.MissingRequiredClientCapability,`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let P={p:s(Z.principal),t:$.name,a:C,n:hZ(16).toString("base64url"),exp:Date.now()+uZ};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[dZ]:{method:"elicitation/create",params:{mode:"form",...W}}},requestState:JZ(NZ,"grs1",P),_meta:{[BZ]:this.serverInfo}}}}let X=Z.era;if(!X.session.e||!Z.stream)return z(`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${hZ(12).toString("base64url")}`,K=X.sessionId,U=await new Promise((H)=>{let Q=setTimeout(()=>{this.pending.delete(Y),H(null)},this.approvalTimeoutMs),V=(I)=>{clearTimeout(Q),H(I)};this.pending.set(Y,{session:K,resolve:V}),Z.signal.addEventListener("abort",()=>{this.pending.delete(Y),V(null)}),Z.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...W}:W})});return U&&!U.error&&lZ(U.result)?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}async spendNonce(Z,$){try{return await this.nonces.consume(Z,$)}catch(G){return console.error("[gemi/mcp] Spending an approval failed:",G),!1}}async respond(Z,$,G,W,z){if(!G)try{let U=await $(null,W);return S({jsonrpc:"2.0",id:Z.id,result:U},200)}finally{z?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,W]),K=new eZ(()=>X.abort());return(async()=>{try{let U=await $(K,Y);K.send({jsonrpc:"2.0",id:Z.id,result:U})}catch(U){if(U instanceof J)K.send(T(Z.id,U));else console.error("[gemi/mcp] The MCP endpoint failed:",U),K.send(T(Z.id,new J(N.InternalError,"Internal error.")))}finally{z?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized(Z){let $=this.resolvers.map((W)=>W.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',G=Z?`${$}, error="invalid_token", error_description="${Z.replace(/["\\]/g,"")}"`:$;return S(T(null,new J(N.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":G})}async failedAttempt(Z){let $=sZ(new PZ(Z,{},"api",this.endpoint.pathname)),G=await KZ(`mcp-auth-failed:${$}`,e3);return G===null?null:nZ(G)}async spend(Z){if(!this.rateLimit)return null;let $=await KZ(`mcp-endpoint:${Z.via}:${Z.id}`,this.rateLimit);return $===null?null:nZ($)}}class eZ{readable;controller;closed=!1;encoder=new TextEncoder;constructor(Z){this.readable=new ReadableStream({start:($)=>{this.controller=$},cancel:()=>{this.closed=!0,Z()}})}send(Z){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
3
3
|
data: ${JSON.stringify(Z)}
|
|
4
4
|
|
|
5
5
|
`))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class o extends Error{}async function Z8(Z,$){let G=Number(Z.headers.get("content-length"));if(Number.isFinite(G)&&G>$)throw new o;if(!Z.body)return"";let W=Z.body.getReader(),z=[],X=0;for(;;){let{done:Y,value:K}=await W.read();if(Y)break;if(X+=K.byteLength,X>$)throw await W.cancel(),new o;z.push(K)}return Buffer.concat(z).toString("utf8")}function S(Z,$,G={}){return new Response(JSON.stringify(Z),{status:$,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...G}})}function cZ(Z,$){for(let[G,W]of Object.entries($))Z.headers.set(G,W);return Z}function $8(Z){return{"Access-Control-Allow-Origin":Z,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function G8(Z){let $;try{$=new URL(Z)}catch{throw Error(`route.mcp.remote.url: "${Z}" is not a URL.`)}let G=$.hostname==="localhost"||$.hostname==="127.0.0.1"||$.hostname==="[::1]";if($.protocol!=="https:"&&!($.protocol==="http:"&&G))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if($.search||$.hash||$.username||$.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if($.pathname==="/"||$.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return $}function s(Z){return rZ("sha256").update(`${Z.via}\x00${Z.id}\x00${Z.user?.id}`).digest("base64url").slice(0,32)}function W8(Z){return rZ("sha256").update(aZ(Z??{})).digest("base64url")}function pZ(Z){if(!O(Z))return!1;if(Object.keys(Z).length===0)return!0;return"form"in Z}function iZ(Z){let $=O(Z._meta)?Z._meta:{};return typeof $.progressToken==="string"||typeof $.progressToken==="number"}function z8(Z,$,G){if($.method!=="tools/call"||!G.e)return!1;let W=$.params?.name;return typeof W==="string"&&Z.descriptors({names:[W]})[0]?.requiresApproval===!0}function X8(Z){let G=(O(Z.params._meta)?Z.params._meta:{}).progressToken;if(!Z.stream||typeof G!=="string"&&typeof G!=="number")return;let W=-1/0;return(z)=>{if(typeof z?.progress!=="number"||!Number.isFinite(z.progress)||z.progress<=W)return;W=z.progress,Z.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:G,progress:z.progress,...typeof z.total==="number"?{total:z.total}:{},...typeof z.message==="string"?{message:z.message.slice(0,1000)}:{}}})}}function Y8(Z,$){let G=JSON.stringify($??{},null,1),W=G.length>xZ?`${G.slice(0,xZ)}\u2026 (${G.length-xZ} more characters not shown)`:G;return{message:`Allow "${Z.title??Z.name}" to run? ${Z.description}
|
|
@@ -7,4 +7,4 @@ data: ${JSON.stringify(Z)}
|
|
|
7
7
|
Arguments: ${W}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${Z.title??Z.name}" with these arguments.`}},required:["approve"]}}}function lZ(Z){return O(Z)&&Z.action==="accept"&&O(Z.content)&&Z.content.approve===!0}function nZ(Z){return S(T(null,new J(N.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String(Z)})}async function K8(Z,$={}){try{if(!await Z.shouldRun.call(Z))return}catch(z){console.error(`Error evaluating shouldRun for cron job ${Z.name}:`,z);return}let G=H8(Z.withoutOverlapping);if(!Z.onOneServer&&G===void 0){await CZ(Z);return}let W;try{if(W=$.locks?.()??U8(),Z.onOneServer){let z=Math.floor(($.now??Date.now())/60000);if(!await W.store.advance(`gemi:cron-tick:${Z.name}`,z))return}}catch(z){console.error(`Could not claim the tick of cron job ${Z.name}; skipped it:`,z);return}if(G===void 0){await CZ(Z);return}try{await W.run(`gemi:cron:${Z.name}`,{ttl:G},(z)=>CZ(Z,z))}catch(z){if(z instanceof G3)console.error(`Cron job ${Z.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,z);else console.error(`Could not take the withoutOverlapping lock of cron job ${Z.name}:`,z)}}var Z3=300000;function H8(Z){if(!Z)return;if(Z===!0)return Z3;return Z.expiresAfter??Z3}var $3;function U8(){return $3??=new k(new W3),$3}async function CZ(Z,$){try{await Z.onTick.call(Z)}catch(G){console.error(`Error executing cron job ${Z.name}:`,G)}try{await Z.callback.call(Z,$)}catch(G){console.error(`Error in cron job ${Z.name}:`,G)}try{await Z.onComplete.call(Z)}catch(G){console.error(`Error completing cron job ${Z.name}:`,G)}}class R{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor(Z){this.resolved=Z.jobs}get jobs(){return[...this.resolved]}useJobs(Z){this.resolved=Z}useLocks(Z){this.locks=Z}start(Z=($)=>$()){if(this.stopped=!1,this.resolved.length===0)return;let $=globalThis.__gemiCronJobs??=new Map,G=new Map;for(let W of this.resolved){let z=new W;if(!z.name){console.error(`Cron job must have a name \u2014 ${W.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(!z.cron){console.error(`Cron job must have an expression. Job: ${z.name}`);continue}let X=G.get(z.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${z.name}" \u2014 ${X} is scheduled and ${W.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}G.set(z.name,W.name||"an anonymous class"),$.get(z.name)?.stop();let Y=Bun.cron(z.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(z.name,()=>Z(()=>K8(z,{locks:K})))});$.set(z.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let Z of this.handles)Z.stop();this.handles=[]}async drain(Z=1/0){this.stop();let $,G=new Promise((W)=>{if(Z!==1/0)$=setTimeout(W,Z)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((W)=>W.done)),G]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((W)=>({...W.tick}))}}get running(){return this.inFlight.size}track(Z,$){let G={},W=Promise.resolve().then($).finally(()=>this.inFlight.delete(G));return this.inFlight.set(G,{tick:{name:Z,startedAt:new Date},done:W}),W}}import{isMainThread as Q8}from"worker_threads";var V8=100,B8=(Z)=>Math.min(V8,Math.floor(Z/10));class I8 extends F{register(){this.app.singleton(D,()=>new D(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(k,()=>this.app.make(D).locks)}async boot(){let Z=this.app.config.get("queue",{});if(Z.jobs!==void 0)return;let{jobsDir:$}=_(z3(),Z);this.app.make(D).useJobs(await U3($))}async shutdown(Z){if(!this.app.resolved(D))return;let $=this.app.make(D);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running queued job(s).`);let G=Z?.timeoutMs,{unfinished:W}=await $.drain(G===void 0?1/0:Math.max(0,G-B8(G)));if(W.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+W.map((z)=>`${z.name} (${z.id})`).join(", ")),{abandoned:!0}}}function _9(Z){if(F8(Z),Bun.env.NODE_ENV!=="production")return N8(Z);if(Q3(Z))return;if(!Y3())return;if(!Z.bound(D))return;Z.make(D).start()}function Q3(Z){let $=Z.config.get("queue",{}).driver??"memory";return $==="memory"||$ instanceof X3}function J8(Z){if(Q3(Z))return!0;if(typeof Z.config.get("queue",{}).driver!=="function"||!Z.bound(D))return!1;try{return!Z.make(D).durable}catch{return!1}}function F8(Z){let $=process.env.GEMI_QUEUE_CLAIM;if($===void 0||H3())return;if(process.env.ROOT_DIR===void 0||!Q8)return;if(K3()){if(!J8(Z))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($.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${$}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function N8(Z){let $=globalThis.__gemiDevQueue;if(!$)return;if(globalThis.__gemiDevQueue=void 0,$.stop(),Z.bound(D))Z.make(D).start()}class x8 extends F{register(){this.app.singleton(p,()=>new p(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(p))return;await this.app.make(p).close()}}class P8 extends F{register(){this.app.singleton(_Z,()=>new _Z(this.app.config.get("auth",{})))}}var C8=100,_8=(Z)=>Math.min(C8,Math.floor(Z/10));class D8 extends F{register(){this.app.singleton(R,()=>new R(_(DZ(),this.app.config.get("schedule",{}))))}async boot(){let Z=this.app.make(R),$=this.app.config.get("schedule",{});if($.jobs===void 0){let{jobsDir:W}=_(DZ(),$);Z.useJobs(await B3(W))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let G=this.app;if(G.bound(k))Z.useLocks(()=>G.make(k));Z.start((W)=>V3.run(G,W))}async shutdown(Z){if(!this.app.resolved(R))return;let $=this.app.make(R);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running cron tick(s).`);let G=Z?.timeoutMs,{unfinished:W}=await $.drain(G===void 0?1/0:Math.max(0,G-_8(G)));if(W.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+W.map((z)=>`${z.name} (started ${z.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class h extends J3{modelName;constructor(Z="FeatureFlag"){super();this.modelName=Z}get available(){return I3(this.modelName)}async load(){if(!this.available)throw new LZ(this.modelName);let Z=AZ(this.modelName);return await Z.asSystem(()=>Z.findMany())}async write(Z,$,G){if(!this.available)throw new LZ(this.modelName);let W=AZ(this.modelName),z=this.hasActorColumn(W),X={active:$};if(z)X.updatedBy=G.actor;return await W.asSystem(()=>W.upsert({where:{key:Z},create:{key:Z,...X},update:X})),{actorRecorded:z}}hasActorColumn(Z){let $=Z?.$schema?.fields?.updatedBy;return $!==void 0&&$.type==="String"}}function m9(Z){return Z}function F3(){return{features:void 0,enabled:!0,source:new h,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class A8 extends F{register(){this.app.singleton(r,()=>{let Z=this.app.config.get("features",{}),$=_(F3(),Z);if(Z?.model!==void 0&&Z?.source===void 0)$.source=new h(Z.model);else if(Z?.model!==void 0&&Z.source instanceof h&&Z.source.modelName!==Z.model)a.warning(`app/config/features.ts sets \`model: "${Z.model}"\` and a source reading "${Z.source.modelName}". The source wins; drop \`model\` to silence this.`);return new r($,(G)=>a.warning(G))})}async boot(){let Z=this.app.make(r);if(!Z.config.enabled)return;try{await Z.refresh()}catch($){a.error(`Could not warm the feature flag cache at boot. ${$ instanceof Error?$.message:String($)}`)}}}class L8 extends F{register(){this.app.singleton(OZ,()=>new OZ(this.app.config.get("mail",{})))}}function O8(Z){return`listener:${Z}`}function x3(Z,$){q8(Z);let{maxAttempts:G,backoff:W,worker:z}=$,X=Z.event.name,Y=class extends N3{maxAttempts=G;backoff=W;worker=z;async run(...K){let[U,H]=T8(K),Q=g(E).rehydrate(U,H);await new Z().handle(Q)}onFail(K){console.error(`The listener ${Z.name} threw while handling ${X} off the queue. The queue will retry it up to ${G} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${Z.name} failed every one of its ${G} 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:O8(Z.name),writable:!0}),Y}function q8(Z){if(Object.getOwnPropertyDescriptor(Z,"name")?.writable)return;throw Error(`The listener ${Z.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 = "${Z.name}";`)}function T8(Z){return typeof Z[0]==="string"?Z:Z[0]}class E{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(Z={}){this.config=_(e(),Z),this.useListeners(this.config.listeners)}useListeners(Z){this.config.listeners=Z,this.listeners={},this.events={};let $=new Set;for(let G of Z){if(!G.event){console.error(`Listener ${G.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($.has(G.name)){console.error(`Two event listeners are named "${G.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}$.add(G.name);let W=G.event.name,z=new G;this.events[W]??=G.event,(this.listeners[W]??=[]).push({listener:G,job:z.queued?x3(G,z):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:Z})=>Z?[Z]:[])}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,$,G){let{name:W,afterCommit:z}=Z.constructor;if(!z)return!1;let X=P3(()=>this.runListeners(Z,$));if(X&&G)this.warnNothingIsWaitedFor(W);return X}async runListeners(Z,$){let G=Z.constructor.name,W=this.listeners[G];if(!W?.length){this.warnNothingIsListening(G);return}for(let{listener:z,job:X}of W){if(X){this.enqueue(X,z,G,$);continue}try{await new z().handle(Z)}catch(Y){console.error(`The listener ${z.name} threw while handling ${G}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",Y)}}}rehydrate(Z,$=[]){let G=this.events[Z];if(!G)throw Error(`Cannot rebuild the event "${Z}" 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 = "${Z}"\`.`);return new G(...$)}enqueue(Z,$,G,W){if(W===void 0){console.error(`The listener ${$.name} is queued, but ${G} 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 ${G}.dispatch(...) or ${G}.dispatchAndWait(...), which carry them.`);return}let z=(X)=>console.error(`The listener ${$.name} could not be queued for ${G}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{g(D).push(Z,JSON.stringify([G,W]),{reportFailure:!1}).catch(z)}catch(X){z(X)}}warnNothingIsWaitedFor(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has(Z))return;this.warnedAboutWaiting.add(Z),console.warn(`[gemi] ${Z}.dispatchAndWait() was called inside a transaction and ${Z} 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(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has(Z))return;this.warnedFor.add(Z),console.warn(`[gemi] ${Z} 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 = ${Z}\` and that ${Z} declares \`static name = "${Z}"\`. Development only.`)}}class S8 extends F{register(){this.app.singleton(E,()=>new E(this.app.config.get("events",{})))}async boot(){let Z=this.app.make(E),$=this.app.config.get("events",{});if($.listeners===void 0){let{listenersDir:z}=_(e(),$);Z.useListeners(await C3(z))}let G=Z.queuedListenerJobs;if(G.length===0)return;let W=this.app.make(D);for(let z of G)W.registerJob(z)}}class j8 extends F{register(){this.app.singleton(qZ,()=>new qZ(this.app.config.get("filesystem",{})))}}class M8 extends F{register(){this.app.singleton(TZ,()=>new TZ(this.app.config.get("image",{})))}}class k8 extends F{register(){this.app.instance(SZ,new SZ)}}function T$(Z){return Z}function _3(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class R8 extends F{register(){this.app.singleton(ZZ,()=>new ZZ(_(_3(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(ZZ).boot()}}class E8 extends F{register(){this.app.singleton($Z,()=>new $Z(_(D3(),this.app.config.get("middleware",{}))))}boot(){this.app.make($Z).assertGlobalMiddleware()}}function h$(Z){return Z}function L3(){return{driver:new A3,limit:1000,window:60}}class w8 extends F{register(){this.app.singleton(v,()=>new v(_(L3(),this.app.config.get("ratelimiter",{}))))}}function l$(Z){return Z}function O3(){return{url:process.env.REDIS_URL,options:void 0}}class b8 extends F{register(){this.app.singleton(i,()=>new i(_(O3(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(i))return;this.app.make(i).close()}}function GZ(Z,$){let G=Z.get($);if(!G)throw Error(`Missing "${$}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return G}class y8 extends F{register(){this.app.singleton(m,()=>new m(GZ(this.app.config,"route.api"))),this.app.singleton(l,()=>new l(GZ(this.app.config,"route.view"))),this.app.singleton(WZ,()=>new WZ({api:this.app.make(m),view:this.app.make(l)},{api:GZ(this.app.config,"route.api"),view:GZ(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(f,()=>{let Z=this.app.config.get("route.mcp");if(!Z?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new f(new Z.router,this.app.make(m),{files:Z.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton(c,()=>{let Z=this.app.config.get("route.mcp");if(!Z?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new c(this.app.make(f),Z.remote)})}boot(){if(this.app.make(m),this.app.make(l),this.app.make(WZ),this.app.config.get("route.mcp"))this.app.make(f);let Z=this.app.config.get("route.mcp.remote");if(Z?.enabled===!0)this.app.make(c);else if(Z?.enabled!==void 0&&Z.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}
|
|
8
8
|
export{T3 as hb,L as ib,d as jb,f as kb,YZ as lb,n3 as mb,KZ as nb,JZ as ob,FZ as pb,c as qb,R as rb,I8 as sb,_9 as tb,x8 as ub,P8 as vb,D8 as wb,h as xb,m9 as yb,F3 as zb,A8 as Ab,L8 as Bb,E as Cb,S8 as Db,j8 as Eb,M8 as Fb,k8 as Gb,T$ as Hb,_3 as Ib,R8 as Jb,E8 as Kb,h$ as Lb,L3 as Mb,w8 as Nb,l$ as Ob,O3 as Pb,b8 as Qb,y8 as Rb};
|
|
9
9
|
|
|
10
|
-
//# debugId=
|
|
10
|
+
//# debugId=B4C295A9D161FC3A64756E2164756E21
|