gemi 0.112.1 → 0.114.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 +32 -32
- package/dist/ai/index.js.map +3 -5
- package/dist/app/App.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/AuthController.d.ts +19 -2
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/config.d.ts +9 -0
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/oauth/GoogleOAuthProvider.d.ts +16 -17
- package/dist/auth/oauth/GoogleOAuthProvider.d.ts.map +1 -1
- package/dist/auth/oauth/OAuthProvider.d.ts +56 -7
- package/dist/auth/oauth/OAuthProvider.d.ts.map +1 -1
- package/dist/auth/oauth/XOAuthProvider.d.ts +10 -9
- package/dist/auth/oauth/XOAuthProvider.d.ts.map +1 -1
- package/dist/auth/oauth/oauthState.d.ts +70 -0
- package/dist/auth/oauth/oauthState.d.ts.map +1 -0
- package/dist/auth/routes.d.ts +3 -2
- package/dist/auth/routes.d.ts.map +1 -1
- package/dist/bin/gemi.js +8 -1
- package/dist/bin/gemi.js.map +3 -3
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/chunk-0n9vs1ad.js +14 -0
- package/dist/{chunk-j0sncgxc.js.map → chunk-0n9vs1ad.js.map} +4 -4
- package/dist/{chunk-18c3y8m3.js → chunk-1f9sqht5.js} +2 -2
- package/dist/{chunk-18c3y8m3.js.map → chunk-1f9sqht5.js.map} +1 -1
- package/dist/{chunk-bhw7k8vp.js → chunk-1p0dazvk.js} +2 -2
- package/dist/{chunk-bhw7k8vp.js.map → chunk-1p0dazvk.js.map} +1 -1
- package/dist/{chunk-b7cqwcbm.js → chunk-2rphhsr7.js} +2 -2
- package/dist/{chunk-b7cqwcbm.js.map → chunk-2rphhsr7.js.map} +1 -1
- package/dist/{chunk-qx87cdfg.js → chunk-2z1981d0.js} +2 -2
- package/dist/{chunk-qx87cdfg.js.map → chunk-2z1981d0.js.map} +1 -1
- package/dist/{chunk-tb126j80.js → chunk-329ggbcw.js} +2 -2
- package/dist/{chunk-tb126j80.js.map → chunk-329ggbcw.js.map} +1 -1
- package/dist/{chunk-dm59ze55.js → chunk-37qk5dh8.js} +2 -2
- package/dist/{chunk-dm59ze55.js.map → chunk-37qk5dh8.js.map} +1 -1
- package/dist/{chunk-b7qjp7r1.js → chunk-3ma9m432.js} +2 -2
- package/dist/{chunk-b7qjp7r1.js.map → chunk-3ma9m432.js.map} +1 -1
- package/dist/{chunk-5waxjsvv.js → chunk-4szjp84e.js} +2 -2
- package/dist/{chunk-5waxjsvv.js.map → chunk-4szjp84e.js.map} +1 -1
- package/dist/{chunk-8reepafh.js → chunk-56fgk5rq.js} +2 -2
- package/dist/{chunk-8reepafh.js.map → chunk-56fgk5rq.js.map} +1 -1
- package/dist/{chunk-hfyxvdjj.js → chunk-583vxa2v.js} +2 -2
- package/dist/{chunk-hfyxvdjj.js.map → chunk-583vxa2v.js.map} +1 -1
- package/dist/{chunk-6w79zajj.js → chunk-5j76r5q8.js} +3 -3
- package/dist/{chunk-6w79zajj.js.map → chunk-5j76r5q8.js.map} +1 -1
- package/dist/chunk-60nyk1w8.js +10 -0
- package/dist/chunk-60nyk1w8.js.map +38 -0
- package/dist/{chunk-jn59bsww.js → chunk-6h9j3f1x.js} +2 -2
- package/dist/{chunk-jn59bsww.js.map → chunk-6h9j3f1x.js.map} +1 -1
- package/dist/{chunk-teny6xkw.js → chunk-75wk4jxd.js} +2 -2
- package/dist/{chunk-teny6xkw.js.map → chunk-75wk4jxd.js.map} +1 -1
- package/dist/{chunk-k7rbkhhw.js → chunk-7fwp7vwh.js} +2 -2
- package/dist/{chunk-k7rbkhhw.js.map → chunk-7fwp7vwh.js.map} +1 -1
- package/dist/{chunk-beks65me.js → chunk-7rmjr8p7.js} +3 -3
- package/dist/{chunk-beks65me.js.map → chunk-7rmjr8p7.js.map} +1 -1
- package/dist/{chunk-jn8hh25v.js → chunk-7v8sgqen.js} +2 -2
- package/dist/{chunk-jn8hh25v.js.map → chunk-7v8sgqen.js.map} +1 -1
- package/dist/{chunk-57edag57.js → chunk-8c2fs0n0.js} +3 -3
- package/dist/{chunk-57edag57.js.map → chunk-8c2fs0n0.js.map} +1 -1
- package/dist/{chunk-0z2h35d7.js → chunk-8h7dh2h2.js} +2 -2
- package/dist/{chunk-0z2h35d7.js.map → chunk-8h7dh2h2.js.map} +1 -1
- package/dist/{chunk-b1mk12xg.js → chunk-8k8534kg.js} +2 -2
- package/dist/{chunk-b1mk12xg.js.map → chunk-8k8534kg.js.map} +1 -1
- package/dist/{chunk-ga7c7tq0.js → chunk-8rt4wx8z.js} +3 -3
- package/dist/{chunk-ga7c7tq0.js.map → chunk-8rt4wx8z.js.map} +1 -1
- package/dist/{chunk-es487acc.js → chunk-a5sbgffr.js} +1 -1
- package/dist/{chunk-vgdcz7tk.js → chunk-ap5gek56.js} +2 -2
- package/dist/{chunk-vgdcz7tk.js.map → chunk-ap5gek56.js.map} +1 -1
- package/dist/{chunk-851k0b26.js → chunk-awp3n119.js} +2 -2
- package/dist/{chunk-851k0b26.js.map → chunk-awp3n119.js.map} +1 -1
- package/dist/{chunk-d0trs736.js → chunk-cna105t6.js} +2 -2
- package/dist/{chunk-d0trs736.js.map → chunk-cna105t6.js.map} +1 -1
- package/dist/{chunk-amvy4r59.js → chunk-d4m4amy4.js} +2 -2
- package/dist/{chunk-amvy4r59.js.map → chunk-d4m4amy4.js.map} +1 -1
- package/dist/{chunk-ddad3902.js → chunk-e6fp6dxx.js} +2 -2
- package/dist/{chunk-ddad3902.js.map → chunk-e6fp6dxx.js.map} +1 -1
- package/dist/{chunk-qyp652jz.js → chunk-e7axa0d5.js} +3 -3
- package/dist/{chunk-qyp652jz.js.map → chunk-e7axa0d5.js.map} +1 -1
- package/dist/{chunk-dx7wpz5b.js → chunk-erxv1jz7.js} +2 -2
- package/dist/{chunk-dx7wpz5b.js.map → chunk-erxv1jz7.js.map} +1 -1
- package/dist/chunk-fakvf9wb.js +5 -0
- package/dist/{chunk-d9an2nra.js.map → chunk-fakvf9wb.js.map} +1 -1
- package/dist/{chunk-s9rfgxj5.js → chunk-fv9mr1t4.js} +2 -2
- package/dist/{chunk-s9rfgxj5.js.map → chunk-fv9mr1t4.js.map} +1 -1
- package/dist/{chunk-5az0mq4p.js → chunk-gdmsn3f5.js} +2 -2
- package/dist/{chunk-5az0mq4p.js.map → chunk-gdmsn3f5.js.map} +1 -1
- package/dist/{chunk-rend2sbk.js → chunk-gv91vjeb.js} +1 -1
- package/dist/{chunk-dan79jab.js → chunk-h2r2rdhj.js} +2 -2
- package/dist/{chunk-dan79jab.js.map → chunk-h2r2rdhj.js.map} +1 -1
- package/dist/{chunk-15a1mrdv.js → chunk-h4pazcgg.js} +2 -2
- package/dist/{chunk-15a1mrdv.js.map → chunk-h4pazcgg.js.map} +1 -1
- package/dist/{chunk-scbvv2e4.js → chunk-hrvzchxd.js} +2 -2
- package/dist/{chunk-scbvv2e4.js.map → chunk-hrvzchxd.js.map} +1 -1
- package/dist/{chunk-1pvkw2pq.js → chunk-hytt9qyj.js} +2 -2
- package/dist/{chunk-1pvkw2pq.js.map → chunk-hytt9qyj.js.map} +1 -1
- package/dist/{chunk-mx9y9mtx.js → chunk-hz6yzzbz.js} +1 -1
- package/dist/{chunk-eazqda9z.js → chunk-j3nr4cg0.js} +3 -3
- package/dist/{chunk-eazqda9z.js.map → chunk-j3nr4cg0.js.map} +1 -1
- package/dist/{chunk-2taa0brj.js → chunk-jk97wv0q.js} +2 -2
- package/dist/{chunk-2taa0brj.js.map → chunk-jk97wv0q.js.map} +1 -1
- package/dist/{chunk-mrdarm2q.js → chunk-jv4g8grc.js} +2 -2
- package/dist/{chunk-mrdarm2q.js.map → chunk-jv4g8grc.js.map} +1 -1
- package/dist/{chunk-gcs9ydjv.js → chunk-jyrsd1dn.js} +2 -2
- package/dist/{chunk-gcs9ydjv.js.map → chunk-jyrsd1dn.js.map} +1 -1
- package/dist/{chunk-yv1psptb.js → chunk-jzp0fs6h.js} +2 -2
- package/dist/{chunk-yv1psptb.js.map → chunk-jzp0fs6h.js.map} +1 -1
- package/dist/{chunk-tmrmwthr.js → chunk-kcx468qv.js} +2 -2
- package/dist/{chunk-tmrmwthr.js.map → chunk-kcx468qv.js.map} +1 -1
- package/dist/{chunk-zfter1x0.js → chunk-kg1nbxvm.js} +4 -4
- package/dist/{chunk-zfter1x0.js.map → chunk-kg1nbxvm.js.map} +1 -1
- package/dist/{chunk-9hr0bcfy.js → chunk-kqb4s1r0.js} +3 -3
- package/dist/{chunk-9hr0bcfy.js.map → chunk-kqb4s1r0.js.map} +1 -1
- package/dist/{chunk-53bek7sp.js → chunk-m17ktssc.js} +1 -1
- package/dist/{chunk-75ptmewf.js → chunk-m2yfvwrn.js} +2 -2
- package/dist/{chunk-75ptmewf.js.map → chunk-m2yfvwrn.js.map} +1 -1
- package/dist/{chunk-ck0v2kzw.js → chunk-mqcy5vja.js} +2 -2
- package/dist/{chunk-ck0v2kzw.js.map → chunk-mqcy5vja.js.map} +1 -1
- package/dist/{chunk-f1y8eggf.js → chunk-n672d4g8.js} +2 -2
- package/dist/{chunk-f1y8eggf.js.map → chunk-n672d4g8.js.map} +1 -1
- package/dist/{chunk-p2fhtf5r.js → chunk-nek1gzz2.js} +3 -3
- package/dist/{chunk-p2fhtf5r.js.map → chunk-nek1gzz2.js.map} +1 -1
- package/dist/{chunk-jdtn0zk2.js → chunk-pmywkp1w.js} +3 -3
- package/dist/{chunk-jdtn0zk2.js.map → chunk-pmywkp1w.js.map} +1 -1
- package/dist/chunk-q95k1ymq.js +4 -0
- package/dist/{chunk-ryzcfxq7.js.map → chunk-q95k1ymq.js.map} +3 -3
- package/dist/{chunk-30yg31sz.js → chunk-r4namj39.js} +2 -2
- package/dist/{chunk-30yg31sz.js.map → chunk-r4namj39.js.map} +1 -1
- package/dist/{chunk-a9q2cr4w.js → chunk-rrqr1dwq.js} +2 -2
- package/dist/{chunk-a9q2cr4w.js.map → chunk-rrqr1dwq.js.map} +1 -1
- package/dist/{chunk-xv74rhay.js → chunk-tp3mzj4v.js} +2 -2
- package/dist/{chunk-xv74rhay.js.map → chunk-tp3mzj4v.js.map} +1 -1
- package/dist/{chunk-csbc1fxa.js → chunk-ty4aj41k.js} +3 -3
- package/dist/{chunk-csbc1fxa.js.map → chunk-ty4aj41k.js.map} +1 -1
- package/dist/chunk-v9na3dny.js +46 -0
- package/dist/{chunk-4sb1484x.js.map → chunk-v9na3dny.js.map} +11 -9
- package/dist/{chunk-kk502yk2.js → chunk-w2fpr99k.js} +2 -2
- package/dist/{chunk-kk502yk2.js.map → chunk-w2fpr99k.js.map} +1 -1
- package/dist/{chunk-et3vhkbf.js → chunk-wwmdqhzy.js} +2 -2
- package/dist/{chunk-et3vhkbf.js.map → chunk-wwmdqhzy.js.map} +1 -1
- package/dist/chunk-wysm6qte.js +5 -0
- package/dist/chunk-wysm6qte.js.map +12 -0
- package/dist/{chunk-j9jqxv1d.js → chunk-x157wrgy.js} +2 -2
- package/dist/{chunk-j9jqxv1d.js.map → chunk-x157wrgy.js.map} +1 -1
- package/dist/{chunk-mvtgx1mr.js → chunk-xrh6k13s.js} +2 -2
- package/dist/{chunk-mvtgx1mr.js.map → chunk-xrh6k13s.js.map} +1 -1
- package/dist/{chunk-xs4c2nvz.js → chunk-y0wx6w80.js} +2 -2
- package/dist/{chunk-xs4c2nvz.js.map → chunk-y0wx6w80.js.map} +1 -1
- package/dist/{chunk-wexs11yy.js → chunk-yp5979we.js} +2 -2
- package/dist/{chunk-wexs11yy.js.map → chunk-yp5979we.js.map} +1 -1
- package/dist/{chunk-qtbf3w6w.js → chunk-z32xfe8c.js} +2 -2
- package/dist/{chunk-qtbf3w6w.js.map → chunk-z32xfe8c.js.map} +1 -1
- package/dist/{chunk-d8ekyng4.js → chunk-zgn0p8qr.js} +3 -3
- package/dist/{chunk-d8ekyng4.js.map → chunk-zgn0p8qr.js.map} +1 -1
- package/dist/{chunk-rx2shb3t.js → chunk-zns7xcz9.js} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +31 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/McpRouter.d.ts +54 -1
- package/dist/http/McpRouter.d.ts.map +1 -1
- package/dist/http/RateLimitMiddleware.d.ts +4 -1
- package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
- package/dist/http/index.d.ts +1 -0
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/modelOriginated.d.ts +36 -2
- package/dist/http/modelOriginated.d.ts.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/Kernel.d.ts +3 -0
- package/dist/kernel/Kernel.d.ts.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +3 -3
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.d.ts +8 -2
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +44 -9
- package/dist/services/index.js.map +8 -6
- package/dist/services/mcp/McpRegistry.d.ts +190 -29
- package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
- package/dist/services/mcp/http/McpHttpServer.d.ts +153 -0
- package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -0
- package/dist/services/mcp/http/callers.d.ts +131 -0
- package/dist/services/mcp/http/callers.d.ts.map +1 -0
- package/dist/services/mcp/http/limits.d.ts +11 -0
- package/dist/services/mcp/http/limits.d.ts.map +1 -0
- package/dist/services/mcp/http/oauth/McpOAuthServer.d.ts +150 -0
- package/dist/services/mcp/http/oauth/McpOAuthServer.d.ts.map +1 -0
- package/dist/services/mcp/http/oauth/consentPage.d.ts +14 -0
- package/dist/services/mcp/http/oauth/consentPage.d.ts.map +1 -0
- package/dist/services/mcp/http/oauth/store.d.ts +98 -0
- package/dist/services/mcp/http/oauth/store.d.ts.map +1 -0
- package/dist/services/mcp/http/protocol.d.ts +95 -0
- package/dist/services/mcp/http/protocol.d.ts.map +1 -0
- package/dist/services/mcp/http/signedState.d.ts +25 -0
- package/dist/services/mcp/http/signedState.d.ts.map +1 -0
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ApiRouteDispatcher.d.ts +29 -0
- package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/RouteServiceProvider.d.ts +6 -0
- package/dist/services/router/RouteServiceProvider.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +16 -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/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3z9vhjd7.js +0 -5
- package/dist/chunk-3z9vhjd7.js.map +0 -10
- package/dist/chunk-4sb1484x.js +0 -46
- package/dist/chunk-bf1ets45.js +0 -5
- package/dist/chunk-bf1ets45.js.map +0 -33
- package/dist/chunk-d9an2nra.js +0 -5
- package/dist/chunk-j0sncgxc.js +0 -14
- package/dist/chunk-ryzcfxq7.js +0 -4
- /package/dist/{chunk-es487acc.js.map → chunk-a5sbgffr.js.map} +0 -0
- /package/dist/{chunk-rend2sbk.js.map → chunk-gv91vjeb.js.map} +0 -0
- /package/dist/{chunk-mx9y9mtx.js.map → chunk-hz6yzzbz.js.map} +0 -0
- /package/dist/{chunk-53bek7sp.js.map → chunk-m17ktssc.js.map} +0 -0
- /package/dist/{chunk-rx2shb3t.js.map → chunk-zns7xcz9.js.map} +0 -0
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Finding the classes an application declared and never imported — the walk\n * #322 and #323 both end at.\n *\n * ### Why it has to run the files\n *\n * A job that is written and not listed does not fail; it disappears.\n * `QueueManager.run` looks a dispatched name up in the map its config built and\n * drops what is not there, so the dispatch is simply lost. A cron drifts worse:\n * nothing is waiting on a tick, so a job that never fires reports nothing to\n * anyone. What both come down to is that `app/config/queue.ts` naming every\n * `Job` subclass is the *only* thing putting those classes in the module graph —\n * the list and the directory are two spellings of one set, kept in step by hand.\n *\n * The way out of that is to read the directory, and there is no static read that\n * will do: the class does not exist until its module has run. So **every file\n * walked here is imported**, and a file that *does something* when imported does\n * it here — at boot, in production, on every start. `gemi check models` makes\n * the same trade for the same reason and pays it once per CI run; a caller of\n * this pays it once per process.\n *\n * ### What that asks of a caller\n *\n * **Point it at a directory of class declarations, not at `app/`.** The skip\n * rules on `sourceFiles` drop what certainly is not one — tests, benchmarks,\n * `.d.ts`, vendored packages — and nothing else. Widening the guesses is how a\n * discovery pass ends up quietly covering less than the directory holds, which\n * is the same silence in a new place.\n *\n * **Let a broken file stop the boot.** `discoverClasses` rethrows an import\n * failure naming the file rather than dropping it and carrying on, for the same\n * reason: four classes found out of five looks exactly like five out of five.\n *\n * **Leave a way out.** Discovery is what should happen when an app said\n * nothing. An app that lists its classes explicitly must not reach this file at\n * all — that is the escape hatch for a directory holding something this cannot\n * import, and it is the sentence an error from here should point at.\n *\n * ### One more thing worth knowing\n *\n * This imports by absolute path, while the application imports the same files\n * through the `@/app/*` alias. Bun keys its module registry by the *resolved*\n * path, so those two specifiers land on one module: a job already reached from\n * a controller is not evaluated a second time here, and the class object is the\n * same one. `gemi build` leaves that true in production — `packages: \"external\"`\n * keeps the app's own code out of `dist/server/server.mjs` and resolves it from\n * source at runtime, exactly as `gemi dev` does.\n *\n * Nothing here depends on that holding, and deliberately: `QueueManager` and the\n * `Scheduler`'s cross-reload registry are both keyed by name rather than by\n * class identity, so a build that did inline the app's modules would produce a\n * duplicate class object and still register the right job. Worth knowing before\n * writing a registry keyed the other way.\n */\n\n/**\n * The files under `dir` that could declare a class.\n *\n * Everything underneath it, because apps do group classes into folders, minus\n * what cannot be one. Each of these is going to be *imported*, so the exclusions\n * are about what is certainly not source rather than about what is probably not:\n *\n * - **Declaration files.** `.d.ts` has no runtime module behind it.\n * - **Tests, type tests and benchmarks**, by the suffix a runner already\n * recognises.\n * - **Dot-directories and `node_modules`.**\n * - **Any directory holding a `package.json`.** That is a package that happens\n * to live here — a vendored client, a generated SDK — not this app's source,\n * and importing its entry point runs somebody else's module graph. The\n * template has two under `app/models`.\n *\n * `ignore` is the escape hatch for the rest: a path prefix, relative to `dir`,\n * naming a file or a directory of adjacent code that runs something on import.\n * Nothing is ignored by default.\n *\n * The order is the same on every run over the same tree, which matters because\n * the caller is going to import in it: entries are sorted per directory before\n * recursing, and `readdirSync` order is the filesystem's rather than\n * alphabetical — a tree written `A.ts` then `B.ts` reads back `B.ts` first on\n * the machines this was tested on. Sorting per directory rather than sorting the\n * finished list is deliberate: for a tree holding both `a.ts` and `a/b.ts`, this\n * emits `a/b.ts` first, because the directory sorts before the file.\n *\n * A directory that does not exist yields an empty list rather than throwing.\n * \"The app has no jobs yet\" is an ordinary state and not this function's to\n * complain about — but it is indistinguishable from \"the app's source did not\n * ship\", so a caller that boots on the answer owes the reader a word about which\n * one it got.\n */\nexport function sourceFiles(dir: string, ignore: string[] = []): string[] {\n const out: string[] = [];\n\n const ignored = (path: string) => {\n const rel = relative(dir, path).split(\"\\\\\").join(\"/\");\n return ignore.some(\n (pattern) => rel === pattern || rel.startsWith(`${pattern}/`),\n );\n };\n\n const walk = (current: string) => {\n for (const entry of readdirSync(current, { withFileTypes: true }).sort(\n (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n )) {\n const path = join(current, entry.name);\n if (ignored(path)) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\")\n continue;\n if (existsSync(join(path, \"package.json\"))) continue;\n walk(path);\n continue;\n }\n\n if (!entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".tsx\")) continue;\n if (entry.name.endsWith(\".d.ts\")) continue;\n if (/\\.(test|test-d|spec|bench)\\.tsx?$/.test(entry.name)) continue;\n\n out.push(path);\n }\n };\n\n if (!existsSync(dir)) return out;\n\n walk(dir);\n return out;\n}\n\n/**\n * A class, as much of one as this file can name. `abstract` so that a base an\n * app never instantiates directly is a legal argument.\n */\ntype ClassLike = abstract new (...args: never[]) => unknown;\n\n/**\n * A file that would not import, reported with the file that would not import.\n *\n * Separate from a bare rethrow because the stack of a failed dynamic import\n * names the module that failed to *resolve*, several frames deep, and says\n * nothing about the walk that asked for it — so the reader learns that some\n * `?raw` specifier is unresolvable without learning that discovery is what\n * imported it, or that listing the classes explicitly is how they get their boot\n * back.\n */\nexport class DiscoveryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"DiscoveryError\";\n }\n}\n\n/**\n * Every exported class under `dir` whose prototype chain reaches `base`.\n *\n * `base` is a parameter rather than an import so that this file names no\n * service and stays cheap to depend on — `bin/check-models.ts` uses the walker\n * above and is bundled into `dist/bin/gemi.js`, which is not somewhere gemi's\n * service layer should end up. It is also what lets a test hand in a base class\n * of its own instead of standing up a project that can resolve `gemi/services`.\n *\n * `base` itself is never returned. A directory whose files import their base\n * from a sibling — the shape an app reaches for when several jobs share a gate —\n * re-exports it as often as not, and a framework that scheduled the abstract\n * base along with its subclasses would be running a job nobody wrote.\n *\n * A class is returned once no matter how many exports name it. A barrel in the\n * directory re-exporting everything beside it is the ordinary case, and it makes\n * every class reachable twice.\n *\n * The order is the walk's, and within a file the module namespace's, which the\n * language sorts by name. So the answer is the same on every run — worth having\n * where the caller is a scheduler and the alternative is a boot order that\n * depends on the filesystem.\n *\n * `onSkipped` is handed every export that did *not* match, with the file it came\n * from. Discovery's characteristic failure is a thing the author wrote and this\n * walk cannot see, and by the time an export has been discarded here the\n * information about why is gone — the caller is left holding \"four classes\"\n * where the directory holds five. A caller that can recognise its own\n * near-misses, as `discoverCommands` recognises a builder chain that was never\n * finished, uses this to say so by name instead.\n *\n * @throws DiscoveryError if a walked file cannot be imported. Not a skip: a file\n * that will not load is a class the caller was going to be told about and now is\n * not, which is the failure discovery exists to remove.\n */\nexport async function discoverClasses<T extends ClassLike>(\n dir: string,\n base: T,\n ignore: string[] = [],\n onSkipped?: (value: unknown, file: string) => void,\n): Promise<T[]> {\n const found = new Set<T>();\n\n for (const path of sourceFiles(dir, ignore)) {\n let module: Record<string, unknown>;\n\n try {\n module = (await import(path)) as Record<string, unknown>;\n } catch (error) {\n throw new DiscoveryError(\n `${path} could not be imported, so the classes in it could not be ` +\n `discovered:\\n ${(error as Error).message}\\n` +\n `List the classes explicitly in the config slice for this directory ` +\n `to skip the walk.`,\n { cause: error },\n );\n }\n\n for (const value of Object.values(module)) {\n if (\n typeof value === \"function\" &&\n value !== base &&\n Object.prototype.isPrototypeOf.call(base, value)\n ) {\n found.add(value as unknown as T);\n continue;\n }\n\n onSkipped?.(value, path);\n }\n }\n\n return [...found];\n}\n\n/**\n * The directory an app's `app/` sits in, as the running process can know it.\n *\n * `ROOT_DIR` is the obvious answer and is not available: `Server.start` awaits\n * `waitForBoot()` — every provider's `register` and `boot` — and only then\n * imports the http layer that sets it. Anything resolving paths during boot is\n * earlier than the variable it would want.\n *\n * What it can use is the same rule `httpProd` computes `ROOT_DIR` with a moment\n * later, which is why that file now calls this instead of repeating it. `gemi\n * dev` and `gemi start` both spawn the server with no `cwd`, so the process\n * inherits the CLI's, and the CLI takes `process.cwd()` for the project root\n * itself — `bun/preload.ts` reads `gemi.config` from it on the same assumption.\n *\n * `httpDev` computes a bare `process.cwd()`, so it and `httpProd` already\n * disagree whenever `GEMI_PROJECT_DIR` is set. Nothing in this repo sets it and\n * `gemi start` ignores it when locating the built entry point, so the two rules\n * are the same rule for every configuration that runs today; the divergence is\n * older than this function and wants its own fix.\n */\nexport function projectRoot(): string {\n return join(process.cwd(), process.env.GEMI_PROJECT_DIR ?? \"\");\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAAA,qBAAS,iBAAY,WACrB,eAAS,cAAM,aA2FR,SAAS,CAAW,CAAC,EAAa,EAAmB,CAAC,EAAa,CACxE,IAAM,EAAgB,CAAC,EAEjB,EAAU,CAAC,IAAiB,CAChC,IAAM,EAAM,EAAS,EAAK,CAAI,EAAE,MAAM,IAAI,EAAE,KAAK,GAAG,EACpD,OAAO,EAAO,KACZ,CAAC,IAAY,IAAQ,GAAW,EAAI,WAAW,GAAG,IAAU,CAC9D,GAGI,EAAO,CAAC,IAAoB,CAChC,QAAW,KAAS,EAAY,EAAS,CAAE,cAAe,EAAK,CAAC,EAAE,KAChE,CAAC,EAAG,IAAO,EAAE,KAAO,EAAE,KAAO,GAAK,EAAE,KAAO,EAAE,KAAO,EAAI,CAC1D,EAAG,CACD,IAAM,EAAO,EAAK,EAAS,EAAM,IAAI,EACrC,GAAI,EAAQ,CAAI,EAAG,SAEnB,GAAI,EAAM,YAAY,EAAG,CACvB,GAAI,EAAM,KAAK,WAAW,GAAG,GAAK,EAAM,OAAS,eAC/C,SACF,GAAI,EAAW,EAAK,EAAM,cAAc,CAAC,EAAG,SAC5C,EAAK,CAAI,EACT,SAGF,GAAI,CAAC,EAAM,KAAK,SAAS,KAAK,GAAK,CAAC,EAAM,KAAK,SAAS,MAAM,EAAG,SACjE,GAAI,EAAM,KAAK,SAAS,OAAO,EAAG,SAClC,GAAI,oCAAoC,KAAK,EAAM,IAAI,EAAG,SAE1D,EAAI,KAAK,CAAI,IAIjB,GAAI,CAAC,EAAW,CAAG,EAAG,OAAO,EAG7B,OADA,EAAK,CAAG,EACD,EAmBF,MAAM,UAAuB,KAAM,CACxC,WAAW,CAAC,EAAiB,EAA+B,CAC1D,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,iBAEhB,CAqCA,eAAsB,CAAoC,CACxD,EACA,EACA,EAAmB,CAAC,EACpB,EACc,CACd,IAAM,EAAQ,IAAI,IAElB,QAAW,KAAQ,EAAY,EAAK,CAAM,EAAG,CAC3C,IAAI,EAEJ,GAAI,CACF,EAAU,MAAa,UACvB,MAAO,EAAO,CACd,MAAM,IAAI,EACR,GAAG;AAAA,MACoB,EAAgB;AAAA,sFAGvC,CAAE,MAAO,CAAM,CACjB,EAGF,QAAW,KAAS,OAAO,OAAO,CAAM,EAAG,CACzC,GACE,OAAO,IAAU,YACjB,IAAU,GACV,OAAO,UAAU,cAAc,KAAK,EAAM,CAAK,EAC/C,CACA,EAAM,IAAI,CAAqB,EAC/B,SAGF,IAAY,EAAO,CAAI,GAI3B,MAAO,CAAC,GAAG,CAAK,EAuBX,SAAS,CAAW,EAAW,CACpC,OAAO,EAAK,QAAQ,IAAI,EAAG,QAAQ,IAAI,kBAAoB,EAAE",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "14338F7C3A99D22664756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Shallow-merges an app config slice over the framework defaults, ignoring keys\n * whose value is `undefined`.\n *\n * A plain `{ ...defaults, ...config }` lets an explicit `undefined` win — a\n * `defineMailConfig({ headers: undefined })`, or any optional property the app\n * spread in from another object, would erase the default and hand the service a\n * missing dependency. Omitting a key and setting it to `undefined` mean the\n * same thing for a config slice, so both fall back to the default here.\n */\nexport function withDefaults<T extends object>(\n defaults: Required<T>,\n config: Partial<T> | undefined,\n): Required<T>;\nexport function withDefaults<D extends object, C extends object>(\n defaults: D,\n config: C | undefined,\n): D & C;\nexport function withDefaults(\n defaults: Record<string, any>,\n config: Record<string, any> | undefined,\n) {\n const merged: Record<string, any> = { ...defaults };\n if (!config) {\n return merged;\n }\n for (const key of Object.keys(config)) {\n if (config[key] !== undefined) {\n merged[key] = config[key];\n }\n }\n return merged;\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAkBO,SAAS,CAAY,CAC1B,EACA,EACA,CACA,IAAM,EAA8B,IAAK,CAAS,EAClD,GAAI,CAAC,EACH,OAAO,EAET,QAAW,KAAO,OAAO,KAAK,CAAM,EAClC,GAAI,EAAO,KAAS,OAClB,EAAO,GAAO,EAAO,GAGzB,OAAO",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "DA0D92087274A54264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{F as
|
|
2
|
+
import{ti as P}from"./chunk-e6fp6dxx.js";class F{provider="custom";supportsIdempotencyKey=!1;async deliver(j){let x=await this.send(j);return{ok:Boolean(x),id:null}}}class G extends F{apiKey;provider="resend";supportsIdempotencyKey=!0;constructor(j=process.env.RESEND_API_KEY){super();this.apiKey=j}async send(j){return(await this.deliver(j)).ok}async deliver(j){let{Resend:x}=await import("./chunk-w2fpr99k.js"),A=new x(this.apiKey),{idempotencyKey:z,...N}=j,{data:H,error:B}=await A.emails.send(N,z?{idempotencyKey:z}:void 0);if(B)return console.error(B),{ok:!1,id:null,error:B};if(H)return{ok:!0,id:H.id??null};return{ok:!1,id:null}}}function Z(j){return j}function J(){return{driver:new G,headers:{},filterRecipients:(j)=>j}}function Q(j){for(let x=j;x;x=Object.getPrototypeOf(x)){let A=Object.prototype.hasOwnProperty.call(x,"deliver"),z=Object.prototype.hasOwnProperty.call(x,"send");if(A)return!1;if(z)return!0}return!0}async function M(j,x){if(typeof j.deliver==="function"&&!Q(j))return j.deliver(x);return{ok:Boolean(await j.send(x)),id:null}}class U{static token="mail";driver;headers;recipientFilter;constructor(j={}){let x=J();this.driver=j.driver??x.driver,this.headers=j.headers??x.headers,this.recipientFilter=j.filterRecipients??x.filterRecipients}filterRecipients(j){return this.recipientFilter(j)}send(j){return this.driver.send(j)}async deliver(j){return M(this.driver,j)}}
|
|
3
|
+
export{F as Oh,G as Ph,Z as Qh,J as Rh,M as Sh,U as Th};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=3A42775434D1F75064756E2164756E21
|
|
@@ -9,6 +9,6 @@
|
|
|
9
9
|
"import { mailConfigDefaults, type MailConfig } from \"./config\";\nimport { deliverThrough } from \"./deliver\";\nimport type { EmailDriver } from \"./drivers/EmailDriver\";\nimport type { EmailDeliveryResult, SendEmailParams } from \"./drivers/types\";\n\nexport class MailManager {\n static token = \"mail\";\n\n readonly driver: EmailDriver;\n readonly headers: Record<string, string>;\n\n private readonly recipientFilter: NonNullable<MailConfig[\"filterRecipients\"]>;\n\n constructor(config: MailConfig = {}) {\n const defaults = mailConfigDefaults();\n\n this.driver = config.driver ?? defaults.driver;\n this.headers = config.headers ?? defaults.headers;\n this.recipientFilter = config.filterRecipients ?? defaults.filterRecipients;\n }\n\n filterRecipients(emails: string[]): Promise<Array<string>> | Array<string> {\n return this.recipientFilter(emails);\n }\n\n send(params: SendEmailParams) {\n return this.driver.send(params);\n }\n\n /** Like `send`, but reports the outcome and the provider's message id. */\n async deliver(params: SendEmailParams): Promise<EmailDeliveryResult> {\n // A driver that doesn't extend `EmailDriver`, or a subclass that only\n // overrides `send`, is called through `send`.\n return deliverThrough(this.driver, params);\n }\n}\n"
|
|
10
10
|
],
|
|
11
11
|
"mappings": ";yCAEO,MAAe,CAAY,CAKvB,SAAmB,SAMnB,uBAAkC,QASrC,QAAO,CAAC,EAAuD,CACnE,IAAM,EAAK,MAAM,KAAK,KAAK,CAAM,EACjC,MAAO,CAAE,GAAI,QAAQ,CAAE,EAAG,GAAI,IAAK,EAEvC,CCvBO,MAAM,UAAqB,CAAY,CAIxB,OAHF,SAAW,SACX,uBAAyB,GAE3C,WAAW,CAAS,EAAS,QAAQ,IAAI,eAAgB,CACvD,MAAM,EADY,mBAId,KAAI,CAAC,EAAyB,CAClC,OAAQ,MAAM,KAAK,QAAQ,CAAM,GAAG,QAGvB,QAAO,CAAC,EAAuD,CAO5E,IAAQ,UAAW,KAAa,+BAC1B,EAAS,IAAI,EAAO,KAAK,MAAM,GAG7B,oBAAmB,GAAY,GAC/B,OAAM,SAAU,MAAM,EAAO,OAAO,KAC1C,EACA,EAAiB,CAAE,gBAAe,EAAI,MACxC,EAEA,GAAI,EAEF,OADA,QAAQ,MAAM,CAAK,EACZ,CAAE,GAAI,GAAO,GAAI,KAAM,OAAM,EAGtC,GAAI,EACF,MAAO,CAAE,GAAI,GAAM,GAAI,EAAK,IAAM,IAAK,EAGzC,MAAO,CAAE,GAAI,GAAO,GAAI,IAAK,EAEjC,CC7BO,SAAS,CAAgB,CAAC,EAAgC,CAC/D,OAAO,EAGF,SAAS,CAAkB,EAAyB,CACzD,MAAO,CACL,OAAQ,IAAI,EACZ,QAAS,CAAC,EACV,iBAAkB,CAAC,IAAW,CAChC,ECVF,SAAS,CAAgB,CAAC,EAAgB,CACxC,QAAS,EAAQ,EAAQ,EAAO,EAAQ,OAAO,eAAe,CAAK,EAAG,CACpE,IAAM,EAAa,OAAO,UAAU,eAAe,KAAK,EAAO,SAAS,EAClE,EAAU,OAAO,UAAU,eAAe,KAAK,EAAO,MAAM,EAClE,GAAI,EAAY,MAAO,GACvB,GAAI,EAAS,MAAO,GAEtB,MAAO,GAOT,eAAsB,CAAc,CAClC,EACA,EAC8B,CAC9B,GAAI,OAAO,EAAO,UAAY,YAAc,CAAC,EAAiB,CAAM,EAClE,OAAO,EAAO,QAAQ,CAAM,EAE9B,MAAO,CAAE,GAAI,QAAQ,MAAM,EAAO,KAAK,CAAM,CAAC,EAAG,GAAI,IAAK,EC7BrD,MAAM,CAAY,OAChB,OAAQ,OAEN,OACA,QAEQ,gBAEjB,WAAW,CAAC,EAAqB,CAAC,EAAG,CACnC,IAAM,EAAW,EAAmB,EAEpC,KAAK,OAAS,EAAO,QAAU,EAAS,OACxC,KAAK,QAAU,EAAO,SAAW,EAAS,QAC1C,KAAK,gBAAkB,EAAO,kBAAoB,EAAS,iBAG7D,gBAAgB,CAAC,EAA0D,CACzE,OAAO,KAAK,gBAAgB,CAAM,EAGpC,IAAI,CAAC,EAAyB,CAC5B,OAAO,KAAK,OAAO,KAAK,CAAM,OAI1B,QAAO,CAAC,EAAuD,CAGnE,OAAO,EAAe,KAAK,OAAQ,CAAM,EAE7C",
|
|
12
|
-
"debugId": "
|
|
12
|
+
"debugId": "3A42775434D1F75064756E2164756E21",
|
|
13
13
|
"names": []
|
|
14
14
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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
|
|
3
|
+
data: ${JSON.stringify(Z)}
|
|
4
|
+
|
|
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}
|
|
6
|
+
|
|
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
|
+
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
|
+
|
|
10
|
+
//# debugId=2530199B4524BCC864756E2164756E21
|