gemi 0.107.0 → 0.109.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.
Files changed (217) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +1 -1
  4. package/dist/bin/gemi.js +242 -33
  5. package/dist/bin/gemi.js.map +9 -7
  6. package/dist/bun/plugin.js +1 -1
  7. package/dist/bun/preload.js +1 -1
  8. package/dist/{chunk-9jz4rggd.js → chunk-1es50p4k.js} +2 -2
  9. package/dist/{chunk-9jz4rggd.js.map → chunk-1es50p4k.js.map} +1 -1
  10. package/dist/{chunk-2gmgd05c.js → chunk-367kyrdx.js} +2 -2
  11. package/dist/{chunk-2gmgd05c.js.map → chunk-367kyrdx.js.map} +1 -1
  12. package/dist/{chunk-h7pafjej.js → chunk-3x86bhfn.js} +3 -3
  13. package/dist/{chunk-h7pafjej.js.map → chunk-3x86bhfn.js.map} +1 -1
  14. package/dist/{chunk-kda25fn4.js → chunk-52vsdnny.js} +1 -1
  15. package/dist/{chunk-m31pfz1s.js → chunk-5d6eaxab.js} +2 -2
  16. package/dist/{chunk-m31pfz1s.js.map → chunk-5d6eaxab.js.map} +1 -1
  17. package/dist/{chunk-njkk498k.js → chunk-6zekebzt.js} +2 -2
  18. package/dist/{chunk-njkk498k.js.map → chunk-6zekebzt.js.map} +1 -1
  19. package/dist/{chunk-00y49jcf.js → chunk-7mc5e61r.js} +2 -2
  20. package/dist/{chunk-00y49jcf.js.map → chunk-7mc5e61r.js.map} +1 -1
  21. package/dist/{chunk-47rgq59q.js → chunk-7ssjzp87.js} +2 -2
  22. package/dist/{chunk-47rgq59q.js.map → chunk-7ssjzp87.js.map} +1 -1
  23. package/dist/{chunk-5wt25tyd.js → chunk-9m18pknp.js} +2 -2
  24. package/dist/{chunk-5wt25tyd.js.map → chunk-9m18pknp.js.map} +1 -1
  25. package/dist/{chunk-vj2t77x1.js → chunk-9qw9fa6z.js} +2 -2
  26. package/dist/{chunk-vj2t77x1.js.map → chunk-9qw9fa6z.js.map} +1 -1
  27. package/dist/{chunk-v52dyw0q.js → chunk-c8dhvdrs.js} +2 -2
  28. package/dist/{chunk-v52dyw0q.js.map → chunk-c8dhvdrs.js.map} +1 -1
  29. package/dist/{chunk-kstvyvr0.js → chunk-d2tngs73.js} +2 -2
  30. package/dist/{chunk-kstvyvr0.js.map → chunk-d2tngs73.js.map} +1 -1
  31. package/dist/{chunk-q7y9v2v5.js → chunk-d5sbnzng.js} +13 -13
  32. package/dist/{chunk-q7y9v2v5.js.map → chunk-d5sbnzng.js.map} +5 -4
  33. package/dist/{chunk-1npdp1w2.js → chunk-dpy08xw4.js} +2 -2
  34. package/dist/{chunk-1npdp1w2.js.map → chunk-dpy08xw4.js.map} +1 -1
  35. package/dist/{chunk-h3t4n0bn.js → chunk-ehasw3qm.js} +2 -2
  36. package/dist/{chunk-h3t4n0bn.js.map → chunk-ehasw3qm.js.map} +1 -1
  37. package/dist/{chunk-331s9wqr.js → chunk-eyg88bgv.js} +2 -2
  38. package/dist/{chunk-331s9wqr.js.map → chunk-eyg88bgv.js.map} +1 -1
  39. package/dist/{chunk-fq3sb3xt.js → chunk-f7jhkg8x.js} +3 -3
  40. package/dist/{chunk-fq3sb3xt.js.map → chunk-f7jhkg8x.js.map} +1 -1
  41. package/dist/chunk-fe1pcnw6.js +6 -0
  42. package/dist/chunk-fe1pcnw6.js.map +11 -0
  43. package/dist/chunk-fj6yftm7.js +58 -0
  44. package/dist/{chunk-6zqqec7r.js.map → chunk-fj6yftm7.js.map} +3 -3
  45. package/dist/{chunk-vbm1ng3f.js → chunk-g5a3ptsa.js} +2 -2
  46. package/dist/{chunk-vbm1ng3f.js.map → chunk-g5a3ptsa.js.map} +1 -1
  47. package/dist/{chunk-2q7m8a16.js → chunk-g74qwhvf.js} +2 -2
  48. package/dist/{chunk-2q7m8a16.js.map → chunk-g74qwhvf.js.map} +1 -1
  49. package/dist/{chunk-eytdyahy.js → chunk-g7fr2cy2.js} +2 -2
  50. package/dist/{chunk-eytdyahy.js.map → chunk-g7fr2cy2.js.map} +1 -1
  51. package/dist/{chunk-yebaheh7.js → chunk-ga533cpz.js} +2 -2
  52. package/dist/{chunk-yebaheh7.js.map → chunk-ga533cpz.js.map} +1 -1
  53. package/dist/{chunk-q2fyp44f.js → chunk-gdsby5jh.js} +2 -2
  54. package/dist/{chunk-q2fyp44f.js.map → chunk-gdsby5jh.js.map} +1 -1
  55. package/dist/{chunk-sbyqs03h.js → chunk-grs8dnkd.js} +2 -2
  56. package/dist/{chunk-sbyqs03h.js.map → chunk-grs8dnkd.js.map} +1 -1
  57. package/dist/{chunk-k17prwhx.js → chunk-h15eae7g.js} +2 -2
  58. package/dist/{chunk-k17prwhx.js.map → chunk-h15eae7g.js.map} +1 -1
  59. package/dist/{chunk-9mqqr05d.js → chunk-h6g9g8qc.js} +3 -3
  60. package/dist/{chunk-9mqqr05d.js.map → chunk-h6g9g8qc.js.map} +1 -1
  61. package/dist/{chunk-82hpq0bq.js → chunk-hf32yq23.js} +2 -2
  62. package/dist/{chunk-82hpq0bq.js.map → chunk-hf32yq23.js.map} +1 -1
  63. package/dist/{chunk-xpyhmg45.js → chunk-hgz8sx40.js} +2 -2
  64. package/dist/{chunk-3s3awh38.js.map → chunk-hgz8sx40.js.map} +1 -1
  65. package/dist/{chunk-8pynv9rw.js → chunk-jc4j61xb.js} +2 -2
  66. package/dist/{chunk-8pynv9rw.js.map → chunk-jc4j61xb.js.map} +1 -1
  67. package/dist/{chunk-h4x7cba0.js → chunk-jgtean4t.js} +2 -2
  68. package/dist/{chunk-h4x7cba0.js.map → chunk-jgtean4t.js.map} +1 -1
  69. package/dist/{chunk-6rz8kyqb.js → chunk-jm4jn28j.js} +2 -2
  70. package/dist/{chunk-6rz8kyqb.js.map → chunk-jm4jn28j.js.map} +1 -1
  71. package/dist/{chunk-jnw73s8c.js → chunk-k1ezptt8.js} +2 -2
  72. package/dist/{chunk-jnw73s8c.js.map → chunk-k1ezptt8.js.map} +1 -1
  73. package/dist/{chunk-xg9vye7c.js → chunk-m9609t1y.js} +1 -1
  74. package/dist/{chunk-mhq2bd9c.js → chunk-mp5krm14.js} +3 -3
  75. package/dist/{chunk-mhq2bd9c.js.map → chunk-mp5krm14.js.map} +1 -1
  76. package/dist/{chunk-k9qmr2wa.js → chunk-ngw4xzrt.js} +3 -3
  77. package/dist/{chunk-k9qmr2wa.js.map → chunk-ngw4xzrt.js.map} +1 -1
  78. package/dist/{chunk-ydkjf626.js → chunk-nxxx0m1a.js} +2 -2
  79. package/dist/{chunk-ydkjf626.js.map → chunk-nxxx0m1a.js.map} +1 -1
  80. package/dist/{chunk-rn2kgbg4.js → chunk-pa3khk46.js} +2 -2
  81. package/dist/{chunk-rn2kgbg4.js.map → chunk-pa3khk46.js.map} +1 -1
  82. package/dist/{chunk-wsftnxzs.js → chunk-q8k7f11z.js} +2 -2
  83. package/dist/{chunk-wsftnxzs.js.map → chunk-q8k7f11z.js.map} +1 -1
  84. package/dist/{chunk-rjernda5.js → chunk-qnq110tw.js} +2 -2
  85. package/dist/{chunk-rjernda5.js.map → chunk-qnq110tw.js.map} +1 -1
  86. package/dist/{chunk-ftgd68se.js → chunk-qyyxzy04.js} +2 -2
  87. package/dist/{chunk-ftgd68se.js.map → chunk-qyyxzy04.js.map} +1 -1
  88. package/dist/{chunk-pj2e1p07.js → chunk-qz9aaw5x.js} +2 -2
  89. package/dist/{chunk-pj2e1p07.js.map → chunk-qz9aaw5x.js.map} +1 -1
  90. package/dist/{chunk-2xqrh6d0.js → chunk-r9gzbjc5.js} +1 -1
  91. package/dist/{chunk-wedwkqe7.js → chunk-rgfzqwpg.js} +3 -3
  92. package/dist/{chunk-wedwkqe7.js.map → chunk-rgfzqwpg.js.map} +1 -1
  93. package/dist/{chunk-hdhahvd4.js → chunk-rjcsdazt.js} +2 -2
  94. package/dist/{chunk-hdhahvd4.js.map → chunk-rjcsdazt.js.map} +1 -1
  95. package/dist/chunk-s5aa4hty.js +17 -0
  96. package/dist/{chunk-5mj7a141.js.map → chunk-s5aa4hty.js.map} +9 -7
  97. package/dist/{chunk-rh9j8cwv.js → chunk-sp2v357a.js} +3 -3
  98. package/dist/{chunk-rh9j8cwv.js.map → chunk-sp2v357a.js.map} +1 -1
  99. package/dist/{chunk-cfsscms3.js → chunk-t0bp8nrc.js} +4 -4
  100. package/dist/{chunk-cfsscms3.js.map → chunk-t0bp8nrc.js.map} +1 -1
  101. package/dist/{chunk-kqff894s.js → chunk-t3qw9syt.js} +2 -2
  102. package/dist/{chunk-kqff894s.js.map → chunk-t3qw9syt.js.map} +1 -1
  103. package/dist/{chunk-zrdbytx4.js → chunk-t85rca2p.js} +2 -2
  104. package/dist/{chunk-zrdbytx4.js.map → chunk-t85rca2p.js.map} +1 -1
  105. package/dist/{chunk-tyhrrnp5.js → chunk-tr9mxdth.js} +3 -3
  106. package/dist/{chunk-tyhrrnp5.js.map → chunk-tr9mxdth.js.map} +1 -1
  107. package/dist/{chunk-6wrhc9bq.js → chunk-vee4j6ft.js} +2 -2
  108. package/dist/{chunk-6wrhc9bq.js.map → chunk-vee4j6ft.js.map} +1 -1
  109. package/dist/{chunk-kqz8jp6v.js → chunk-vna85rdq.js} +2 -2
  110. package/dist/{chunk-kqz8jp6v.js.map → chunk-vna85rdq.js.map} +1 -1
  111. package/dist/{chunk-4rr9wmh8.js → chunk-vsnmdtrs.js} +2 -2
  112. package/dist/{chunk-4rr9wmh8.js.map → chunk-vsnmdtrs.js.map} +1 -1
  113. package/dist/{chunk-anp4kv3w.js → chunk-vwkdfngg.js} +1 -1
  114. package/dist/chunk-w3j53r0a.js +24 -0
  115. package/dist/chunk-w3j53r0a.js.map +19 -0
  116. package/dist/{chunk-gqpge54c.js → chunk-wdpdqjr1.js} +2 -2
  117. package/dist/{chunk-gqpge54c.js.map → chunk-wdpdqjr1.js.map} +1 -1
  118. package/dist/{chunk-wzqkdmjd.js → chunk-whe0x70j.js} +2 -2
  119. package/dist/{chunk-wzqkdmjd.js.map → chunk-whe0x70j.js.map} +1 -1
  120. package/dist/{chunk-1rs13253.js → chunk-wqsdjweb.js} +3 -3
  121. package/dist/{chunk-1rs13253.js.map → chunk-wqsdjweb.js.map} +1 -1
  122. package/dist/{chunk-3s3awh38.js → chunk-wvwee7dn.js} +2 -2
  123. package/dist/{chunk-xpyhmg45.js.map → chunk-wvwee7dn.js.map} +1 -1
  124. package/dist/{chunk-ffagkj3x.js → chunk-y66ntxbg.js} +2 -2
  125. package/dist/{chunk-ffagkj3x.js.map → chunk-y66ntxbg.js.map} +1 -1
  126. package/dist/chunk-z9x8x3wq.js +5 -0
  127. package/dist/{chunk-mrvcaakf.js.map → chunk-z9x8x3wq.js.map} +1 -1
  128. package/dist/{chunk-we2sj339.js → chunk-zh1t33nq.js} +2 -2
  129. package/dist/{chunk-we2sj339.js.map → chunk-zh1t33nq.js.map} +1 -1
  130. package/dist/{chunk-661wezaf.js → chunk-zhm3qvrc.js} +2 -2
  131. package/dist/{chunk-661wezaf.js.map → chunk-zhm3qvrc.js.map} +1 -1
  132. package/dist/{chunk-kh273hj0.js → chunk-zys7kecf.js} +2 -2
  133. package/dist/{chunk-kh273hj0.js.map → chunk-zys7kecf.js.map} +1 -1
  134. package/dist/{chunk-fwympxqk.js → chunk-zz7h6tdr.js} +2 -2
  135. package/dist/{chunk-fwympxqk.js.map → chunk-zz7h6tdr.js.map} +1 -1
  136. package/dist/chunks/{ThemeProvider-Cqfwr6dk.js → ThemeProvider-BgLyzzOL.js} +8 -2
  137. package/dist/chunks/ThemeProvider-BgLyzzOL.js.map +1 -0
  138. package/dist/client/ClientRouter.d.ts +2 -0
  139. package/dist/client/ClientRouter.d.ts.map +1 -1
  140. package/dist/client/ClientRouterContext.d.ts.map +1 -1
  141. package/dist/client/ServerDataProvider.d.ts +2 -0
  142. package/dist/client/ServerDataProvider.d.ts.map +1 -1
  143. package/dist/client/createRoot.d.ts.map +1 -1
  144. package/dist/client/index.d.ts +2 -0
  145. package/dist/client/index.d.ts.map +1 -1
  146. package/dist/client/index.js +76 -6
  147. package/dist/client/index.js.map +1 -1
  148. package/dist/client/islands.d.ts +84 -0
  149. package/dist/client/islands.d.ts.map +1 -0
  150. package/dist/config/index.js +1 -1
  151. package/dist/console/run.js +2 -2
  152. package/dist/console/run.js.map +1 -1
  153. package/dist/container/index.js +2 -2
  154. package/dist/container/index.js.map +1 -1
  155. package/dist/database/index.js +2 -2
  156. package/dist/database/index.js.map +1 -1
  157. package/dist/email/index.js +2 -2
  158. package/dist/email/index.js.map +1 -1
  159. package/dist/facades/index.js +2 -2
  160. package/dist/facades/index.js.map +1 -1
  161. package/dist/foundation/index.js +2 -2
  162. package/dist/foundation/index.js.map +1 -1
  163. package/dist/http/ViewRouter.d.ts +38 -0
  164. package/dist/http/ViewRouter.d.ts.map +1 -1
  165. package/dist/http/index.d.ts +1 -1
  166. package/dist/http/index.d.ts.map +1 -1
  167. package/dist/http/index.js +2 -2
  168. package/dist/http/index.js.map +1 -1
  169. package/dist/i18n/dictionaryRuntime.js +2 -2
  170. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  171. package/dist/i18n/index.js +2 -2
  172. package/dist/i18n/index.js.map +1 -1
  173. package/dist/kernel/index.js +2 -2
  174. package/dist/kernel/index.js.map +1 -1
  175. package/dist/orm/index.js +2 -2
  176. package/dist/orm/index.js.map +1 -1
  177. package/dist/server/devFetch.d.ts.map +1 -1
  178. package/dist/server/httpProd.d.ts.map +1 -1
  179. package/dist/server/index.js +2 -2
  180. package/dist/server/index.js.map +1 -1
  181. package/dist/server/modulePreloads.d.ts +17 -0
  182. package/dist/server/modulePreloads.d.ts.map +1 -1
  183. package/dist/server/staticFile.d.ts +20 -1
  184. package/dist/server/staticFile.d.ts.map +1 -1
  185. package/dist/server/styles.d.ts +3 -1
  186. package/dist/server/styles.d.ts.map +1 -1
  187. package/dist/services/index.d.ts +1 -0
  188. package/dist/services/index.d.ts.map +1 -1
  189. package/dist/services/index.js +3 -3
  190. package/dist/services/index.js.map +2 -2
  191. package/dist/services/queue/work.js +2 -2
  192. package/dist/services/queue/work.js.map +1 -1
  193. package/dist/services/router/ViewRouteDispatcher.d.ts +27 -1
  194. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  195. package/dist/services/router/createComponentTree.d.ts.map +1 -1
  196. package/dist/services/router/createFlatViewRoutes.d.ts +13 -1
  197. package/dist/services/router/createFlatViewRoutes.d.ts.map +1 -1
  198. package/dist/services/router/staticDocument.d.ts +44 -0
  199. package/dist/services/router/staticDocument.d.ts.map +1 -0
  200. package/dist/support/index.js +2 -2
  201. package/dist/support/index.js.map +1 -1
  202. package/dist/testing/index.js +1 -1
  203. package/dist/vite/index.mjs +72 -3
  204. package/dist/vitest/index.js +1 -1
  205. package/package.json +1 -1
  206. package/dist/chunk-5mj7a141.js +0 -17
  207. package/dist/chunk-6tyf0h6k.js +0 -24
  208. package/dist/chunk-6tyf0h6k.js.map +0 -18
  209. package/dist/chunk-6zqqec7r.js +0 -58
  210. package/dist/chunk-mrvcaakf.js +0 -5
  211. package/dist/chunk-z38355mx.js +0 -6
  212. package/dist/chunk-z38355mx.js.map +0 -11
  213. package/dist/chunks/ThemeProvider-Cqfwr6dk.js.map +0 -1
  214. /package/dist/{chunk-kda25fn4.js.map → chunk-52vsdnny.js.map} +0 -0
  215. /package/dist/{chunk-xg9vye7c.js.map → chunk-m9609t1y.js.map} +0 -0
  216. /package/dist/{chunk-2xqrh6d0.js.map → chunk-r9gzbjc5.js.map} +0 -0
  217. /package/dist/{chunk-anp4kv3w.js.map → chunk-vwkdfngg.js.map} +0 -0
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../server/styles.ts", "../server/banner.ts"],
4
+ "sourcesContent": [
5
+ "import { createElement } from \"react\";\nimport { type ModuleNode, type ViteDevServer } from \"vite\";\n\nfunction replaceStrings(text: string, record: Record<string, string>): string {\n const escapedKeys = Object.keys(record)\n .sort((a, b) => b.length - a.length)\n .map((key) => key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"));\n\n // Create a single regex with all keys\n const regex = new RegExp(escapedKeys.join(\"|\"), \"g\");\n\n return text.replace(regex, (match) => record[match]);\n}\n\nexport async function createDevStyles(\n appDir: string,\n vite: ViteDevServer,\n currentViews: string[] = [],\n /** A static view's own document layout, which replaces `RootLayout`. */\n layout?: string,\n) {\n const views = [\n ...currentViews.map((view) => `${appDir}/views/${view}.tsx`),\n layout ? `${appDir}/views/${layout}.tsx` : `${appDir}/views/RootLayout.tsx`,\n ];\n\n const modules = new Set<ModuleNode>();\n for (const view of views) {\n const mod = vite.moduleGraph.getModulesByFile(view);\n if (mod) {\n for (const m of mod) modules.add(m);\n }\n }\n\n const styles = [];\n const cssModules = [];\n const cssModuleContent: Record<string, string> = {};\n for (const mod of modules as any) {\n if (mod) {\n for (const imported of mod.importedModules) {\n if (imported.file.includes(\"module.css\")) {\n cssModuleContent[imported.file] = imported.ssrTransformResult.map.sourcesContent.join(\"\");\n }\n if (imported.file.includes(\".css\")) {\n cssModules.push(imported.file);\n }\n }\n }\n }\n\n for (const cssModulePath of cssModules) {\n const transform = await vite.transformRequest(cssModulePath + \"?direct\");\n\n const isCssModule = cssModulePath.includes(\"module.css\");\n\n let transformedCssModule = \"\";\n\n if (isCssModule) {\n transformedCssModule = replaceStrings(\n cssModuleContent[cssModulePath],\n // Vite's `TransformResult` type has no `default`, but the CSS-module\n // transform attaches the class-name mapping there at runtime.\n (transform as unknown as { default: Record<string, string> }).default,\n );\n }\n\n styles.push({\n isDev: true,\n id: cssModulePath,\n content: isCssModule ? transformedCssModule : transform.code,\n });\n }\n\n return styles.map((style, i) => {\n return createElement(\"style\", {\n key: i,\n type: \"text/css\",\n \"data-vite-dev-id\": style.id,\n dangerouslySetInnerHTML: { __html: style.content },\n });\n });\n}\n\nexport async function createStyles(styles = []) {\n return styles.map((style, i) => {\n return createElement(\"style\", {\n key: i,\n id: style?.id,\n type: \"text/css\",\n dangerouslySetInnerHTML: { __html: style.content },\n });\n });\n}\n",
6
+ "import { existsSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport { networkInterfaces } from \"node:os\";\nimport { envFiles } from \"./watchEnv\";\nimport pkg from \"../package.json\";\n\n// \"GEMI\" — ANSI Shadow figlet font.\nconst ART = [\n \" ██████╗ ███████╗███╗ ███╗██╗\",\n \"██╔════╝ ██╔════╝████╗ ████║██║\",\n \"██║ ███╗█████╗ ██╔████╔██║██║\",\n \"██║ ██║██╔══╝ ██║╚██╔╝██║██║\",\n \"╚██████╔╝███████╗██║ ╚═╝ ██║██║\",\n \" ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝\",\n];\n\nconst useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;\nconst paint = (code: string, text: string) =>\n useColor ? `\\x1b[${code}m${text}\\x1b[0m` : text;\nconst bold = (t: string) => paint(\"1\", t);\nconst dim = (t: string) => paint(\"2\", t);\nconst cyan = (t: string) => paint(\"36\", t);\nconst green = (t: string) => paint(\"32\", t);\nconst magenta = (t: string) => paint(\"35\", t);\n\nfunction gemiVersion(): string {\n return (pkg as { version?: string }).version ?? \"?\";\n}\n\nfunction networkUrl(port: number | string): string | null {\n for (const ifaces of Object.values(networkInterfaces())) {\n for (const iface of ifaces ?? []) {\n // Node <18 reported `family` as the number 4; newer Bun/Node use \"IPv4\".\n const isV4 = iface.family === \"IPv4\" || (iface.family as unknown) === 4;\n if (isV4 && !iface.internal) return `http://${iface.address}:${port}`;\n }\n }\n return null;\n}\n\nfunction loadedEnvFiles(rootDir: string): string[] {\n return envFiles(rootDir)\n .filter((file) => existsSync(file))\n .map((file) => basename(file));\n}\n\nexport function printStartupBanner(params: {\n port: number | string;\n rootDir: string;\n}) {\n const { port, rootDir } = params;\n const local = `http://localhost:${port}`;\n const network = networkUrl(port);\n const env = loadedEnvFiles(rootDir);\n\n const row = (label: string, value: string) =>\n ` ${green(\"➜\")} ${bold(label.padEnd(9))}${value}`;\n\n const out = [\n \"\",\n ...ART.map((line) => magenta(line)),\n \"\",\n ` ${dim(\"gemi\")} ${cyan(`v${gemiVersion()}`)}`,\n \"\",\n row(\"Local:\", cyan(local)),\n row(\"Network:\", network ? cyan(network) : dim(\"unavailable\")),\n row(\"Env:\", env.length ? env.join(\", \") : dim(\"none\")),\n \"\",\n ];\n\n console.log(out.join(\"\\n\"));\n}\n"
7
+ ],
8
+ "mappings": ";yCAAA,wBAAS,cAGT,SAAS,CAAc,CAAC,EAAc,EAAwC,CAC5E,IAAM,EAAc,OAAO,KAAK,CAAM,EACnC,KAAK,CAAC,EAAG,IAAM,EAAE,OAAS,EAAE,MAAM,EAClC,IAAI,CAAC,IAAQ,EAAI,QAAQ,sBAAuB,MAAM,CAAC,EAGpD,EAAQ,IAAI,OAAO,EAAY,KAAK,GAAG,EAAG,GAAG,EAEnD,OAAO,EAAK,QAAQ,EAAO,CAAC,IAAU,EAAO,EAAM,EAGrD,eAAsB,CAAe,CACnC,EACA,EACA,EAAyB,CAAC,EAE1B,EACA,CACA,IAAM,EAAQ,CACZ,GAAG,EAAa,IAAI,CAAC,IAAS,GAAG,WAAgB,OAAU,EAC3D,EAAS,GAAG,WAAgB,QAAe,GAAG,wBAChD,EAEM,EAAU,IAAI,IACpB,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAK,YAAY,iBAAiB,CAAI,EAClD,GAAI,EACF,QAAW,KAAK,EAAK,EAAQ,IAAI,CAAC,EAItC,IAAM,EAAS,CAAC,EACV,EAAa,CAAC,EACd,EAA2C,CAAC,EAClD,QAAW,KAAO,EAChB,GAAI,EACF,QAAW,KAAY,EAAI,gBAAiB,CAC1C,GAAI,EAAS,KAAK,SAAS,YAAY,EACrC,EAAiB,EAAS,MAAQ,EAAS,mBAAmB,IAAI,eAAe,KAAK,EAAE,EAE1F,GAAI,EAAS,KAAK,SAAS,MAAM,EAC/B,EAAW,KAAK,EAAS,IAAI,EAMrC,QAAW,KAAiB,EAAY,CACtC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QAAW,EAAM,SAAuB,IAC1D,CAAC,EAAM,SAAU,MAAO,UAAU,EAAM,WAAW,IAGnE,OAAO,KAGT,SAAS,CAAc,CAAC,EAA2B,CACjD,OAAO,EAAS,CAAO,EACpB,OAAO,CAAC,IAAS,EAAW,CAAI,CAAC,EACjC,IAAI,CAAC,IAAS,EAAS,CAAI,CAAC,EAG1B,SAAS,CAAkB,CAAC,EAGhC,CACD,IAAQ,OAAM,WAAY,EACpB,EAAQ,oBAAoB,IAC5B,EAAU,EAAW,CAAI,EACzB,EAAM,EAAe,CAAO,EAE5B,EAAM,CAAC,EAAe,IAC1B,KAAK,EAAM,QAAE,MAAM,EAAK,EAAM,OAAO,CAAC,CAAC,IAAI,IAEvC,EAAM,CACV,GACA,GAAG,EAAI,IAAI,CAAC,IAAS,EAAQ,CAAI,CAAC,EAClC,GACA,KAAK,EAAI,MAAM,KAAK,EAAK,IAAI,EAAY,GAAG,IAC5C,GACA,EAAI,SAAU,EAAK,CAAK,CAAC,EACzB,EAAI,WAAY,EAAU,EAAK,CAAO,EAAI,EAAI,aAAa,CAAC,EAC5D,EAAI,OAAQ,EAAI,OAAS,EAAI,KAAK,IAAI,EAAI,EAAI,MAAM,CAAC,EACrD,EACF,EAEA,QAAQ,IAAI,EAAI,KAAK;AAAA,CAAI,CAAC",
9
+ "debugId": "0084180CD93381AF64756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,58 @@
1
+ // @bun
2
+ import{h as y,j as q}from"./chunk-fe1pcnw6.js";import{ka as E,la as w}from"./chunk-d5sbnzng.js";import"./chunk-a1g0bahx.js";import"./chunk-564zfdd1.js";import"./chunk-9r3znmqq.js";import"./chunk-tvy2fqza.js";import"./chunk-q8k7f11z.js";import{Vf as _}from"./chunk-zz7h6tdr.js";import{ph as N}from"./chunk-hf32yq23.js";import"./chunk-wvwee7dn.js";import{join as QJ}from"path";import{createServer as WJ}from"vite";import{join as u}from"path";import{IncomingMessage as v,ServerResponse as l}from"http";import{Socket as d}from"net";function c(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
+ `).split(`
4
+ `).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).join(`
5
+ `).trim()}function F(J){return`
6
+ <!DOCTYPE html>
7
+ <html lang="en">
8
+ <head>
9
+ <meta charset="UTF-8" />
10
+ <meta
11
+ name="viewport"
12
+ content="width=device-width, initial-scale=1.0"
13
+ />
14
+
15
+ <title>Error</title>
16
+ <style>
17
+ body {
18
+ font-family: Arial, sans-serif;
19
+ padding: 20px;
20
+ }
21
+ h1 {
22
+ color: red;
23
+ }
24
+ </style>
25
+ </head>
26
+ <body>
27
+ <div id="overlay"></div>
28
+ <script type="module" src="/refresh.js"></script>
29
+ <script type="module" src="/@vite/client"></script>
30
+ <script>
31
+ ${c.toString()}
32
+ const err = ${JSON.stringify(J,Object.getOwnPropertyNames(J),2)}
33
+
34
+ window.addEventListener('load', () => {
35
+ const container = document.getElementById('overlay')
36
+ const ErrorOverlay = customElements.get('vite-error-overlay')
37
+ if (ErrorOverlay) {
38
+ const overlay = new ErrorOverlay({ ...err, message: cleanupTerminalText(err.message) });
39
+ container.appendChild(overlay)
40
+ }
41
+ })
42
+ </script>
43
+ </body>
44
+ </html>
45
+ `}function i(J,Q){let W=new URL(Q.url),Z=new v(new d);Z.url=W.pathname+W.search,Z.method=Q.method,Z.headers=Object.fromEntries(Q.headers);let z=new l(Z),X=[];return new Promise((L)=>{z.write=(G)=>{if(G)X.push(Buffer.from(G));return!0},z.end=(G)=>{if(G&&typeof G!=="function")X.push(Buffer.from(G));let $=new Headers;for(let[U,Y]of Object.entries(z.getHeaders())){if(Y==null)continue;for(let B of Array.isArray(Y)?Y:[Y])$.append(U,String(B))}return L(new Response(X.length?Buffer.concat(X):null,{status:z.statusCode,headers:$})),z},J.middlewares(Z,z,()=>L(null))})}function p(J,Q,W){let Z=String(Q),z=" ".repeat(Z.length),X=" ".repeat(Math.max(0,W-1))+"^";return`${Z} | ${J}
46
+ ${z} | ${X}
47
+ `}function I(J){if(J&&typeof J==="object"){let Q=J.position;if(Q&&typeof Q==="object"&&typeof Q.file==="string")return{message:typeof J.message==="string"?J.message:String(J),stack:"",frame:typeof Q.lineText==="string"?p(Q.lineText,Q.line,Q.column):void 0,loc:{file:Q.file,line:Q.line,column:Q.column}};return{message:typeof J.message==="string"?J.message:String(J),stack:typeof J.stack==="string"?J.stack:""}}return{message:String(J),stack:""}}function O(J){let Q=globalThis.__gemiVite;if(!Q)return;Q.ws.send({type:"error",err:I(J)}),globalThis.__gemiErrorActive=!0}function H(J){let Q=J.environments.ssr;if(typeof Q?.runner?.import!=="function")throw Error("gemi dev requires a runnable Vite SSR environment.");return Q.runner}var S="/@gemi/dev-entry.js",n=`const report = (error) => console.error(error);
48
+ await import("/refresh.js").catch(report);
49
+ await import("/@vite/client").catch(report);
50
+ await import("/app/client.tsx");
51
+ `,o=`import RefreshRuntime from "/@react-refresh";
52
+ RefreshRuntime.injectIntoGlobalHook(window);
53
+ window.$RefreshReg$ = () => {};
54
+ window.$RefreshSig$ = () => (type) => type;
55
+ window.__vite_plugin_react_preamble_installed__ = true;
56
+ `;function s(J){let{pathname:Q}=new URL(J.url),W=(Z)=>new Response(Z,{headers:{"Content-Type":"application/javascript"}});if(Q===S)return W(n);if(Q.startsWith("/render-error.js"))return W("window.render_error = true");if(Q.startsWith("/refresh.js"))return W(o);return null}function C(J,Q,W){let Z=u(process.cwd(),"app");return async(z)=>{let{pathname:X}=new URL(z.url),L=($)=>{if(console.error($),W.ssrFixStacktrace?.($),O($),N(X))return new Response(JSON.stringify({error:_("server_error",$?.message??String($),500)}),{status:500,headers:{"Content-Type":"application/json"}});return globalThis.__gemiErrorPageServed=!0,new Response(F(I($)),{status:500,headers:{"Content-Type":"text/html"}})},G=async($)=>{let U=s($);if(U)return U;try{let Y=J.fetch.bind(J),B=await i(W,$)??await Y($);if(B instanceof Response)return B;let A={},b={},M={},h=(K,j)=>`"${K}": () => import("${j}")`,D=[];for(let K of["404",...J.getFlatComponentTree.call(J)]){if(Bun.env.NODE_ENV==="test")break;let j=`${process.env.APP_DIR}`,x=await H(W).import(`${j}/views/${K}.tsx`);A[K]=x.default,b[K]=x?.OpenGraph,M[K]=x,D.push(h(K,`/app/views/${K}.tsx`))}let m=`{${D.join(",")}}`;return await B({getStyles:async(K,j)=>await y(Z,W,K,j?.layout),resolveIsland:(K)=>({src:`/${K}`,preload:[]}),bootstrapModules:[S],viewImportMap:A,viewModules:M,ogMap:b,loaders:m,cssManifest:{}})}catch(Y){return L(Y)}};return await Q(z,($)=>J.withGlobalMiddleware($,G,L))}}function a(J){try{return Bun.listen({hostname:"0.0.0.0",port:J,socket:{data(){}}}).stop(!0),!0}catch(Q){return Q?.code!=="EADDRINUSE"}}function T(J,Q=a){let W=24678+(J-5173);if(W>65471)W=24678;for(let Z=W;Z<W+64;Z++)if(Q(Z))return Z;throw Error(`Could not find a free port for Vite's HMR websocket: tried ${W}-${W+64-1}. Set one explicitly in gemi.config.ts as \`vite: { server: { ws: { port } } }\`.`)}import{createServer as t}from"http";var r=new Set(["vite-hmr","vite-ping"]);async function k(J){let Q=t((W,Z)=>{Z.writeHead(426,{"Content-Type":"text/plain"}),Z.end("Upgrade Required")});return await new Promise((W,Z)=>{Q.once("error",Z),Q.listen(J,"127.0.0.1",()=>{Q.off("error",Z),W()})}),Q}function P(J){if(!J||typeof J!=="object")return null;let W=J.server?.address?.();if(W&&typeof W==="object"&&"port"in W)return Number(W.port)||null;return null}function f(J){if(J.headers.get("upgrade")?.toLowerCase()!=="websocket")return!1;return r.has(J.headers.get("sec-websocket-protocol")??"")}var e=(J)=>typeof J==="string"?J:new Uint8Array(J);async function R(J,Q,W){let Z=new URL(J.url),z=J.headers.get("sec-websocket-protocol")??"vite-hmr",X={host:J.headers.get("host")??Z.host},L=J.headers.get("origin");if(L)X.origin=L;let G=new WebSocket(`ws://127.0.0.1:${W}${Z.pathname}${Z.search}`,{protocols:[z],headers:X});G.binaryType="arraybuffer";let $={upstream:G,early:[]};if(G.onmessage=(B)=>{let A=e(B.data);if($.browser)$.browser.send(A);else $.early.push(A)},G.onclose=(B)=>{$.browser?.close(JJ(B.code),B.reason)},G.onerror=()=>{},!await new Promise((B)=>{G.addEventListener("open",()=>B(!0),{once:!0}),G.addEventListener("close",()=>B(!1),{once:!0})}))return new Response("Vite refused the HMR websocket",{status:403});if(!Q.upgrade(J,{headers:{"Sec-WebSocket-Protocol":z},data:$}))return G.close(),new Response("WebSocket upgrade failed",{status:400});return}function JJ(J){if(J===1000||J>=1001&&J<=1003||J>=1007&&J<=1014)return J;if(J>=3000&&J<=4999)return J;return 1000}var g={open(J){let Q=J.data;for(let W of Q.early)J.send(W);if(Q.early=[],Q.browser=J,Q.upstream.readyState!==WebSocket.OPEN)J.close(1000)},message(J,Q){if(J.data.upstream.readyState===WebSocket.OPEN)J.data.upstream.send(Q)},close(J){let{upstream:Q}=J.data;if(Q.readyState<=WebSocket.OPEN)Q.close()}};var V=process.cwd(),ZJ=QJ(V,"app");if(!globalThis.__gemiErrorHooked)globalThis.__gemiErrorHooked=!0,process.on("unhandledRejection",(J)=>{console.error(J),O(J)}),process.on("uncaughtException",(J)=>{console.error(J),O(J)});async function _J(J,Q){let W=Number(process.env.PORT)||5173,Z=Boolean(globalThis.__gemiVite),z=globalThis.__gemiVite??=await WJ({configFile:!1,plugins:[w()],server:{middlewareMode:!0,port:W,ws:{server:await k(T(W))},allowedHosts:J.devAllowedHosts.call(J),watch:{ignored:($)=>{let U=$.split(/[/\\]/).pop()??"";return U===".env"||U.startsWith(".env.")}}},appType:"custom",resolve:{dedupe:["react","react-dom"]},optimizeDeps:{include:["react","react-dom","react-dom/client"]},ssr:{external:[...E]}});process.env.ROOT_DIR=V,process.env.APP_DIR=ZJ;let X=C(J,Q,z),L=P(z.config?.server?.ws),G=Bun.serve({port:W,fetch:($,U)=>{if(L!==null&&f($))return R($,U,L);return X($)},websocket:g});if(Z)H(z).clearCache();if(Z)if(globalThis.__gemiErrorActive&&globalThis.__gemiErrorPageServed)globalThis.__gemiErrorActive=!1,globalThis.__gemiErrorPageServed=!1,z.ws.send({type:"full-reload"});else globalThis.__gemiErrorActive=!1,z.ws.send({type:"custom",event:"http-reload"});else q({port:G.port,rootDir:V});return G}export{I as viteErrorPayload,_J as httpDev};
57
+
58
+ //# debugId=BDE7E65D52E6D0DE64756E2164756E21
@@ -3,12 +3,12 @@
3
3
  "sources": ["../server/httpDev.ts", "../server/devFetch.ts", "../server/renderErrorPage.ts", "../server/hmrPort.ts", "../server/hmrRelay.ts"],
4
4
  "sourcesContent": [
5
5
  "import { join } from \"node:path\";\n\nimport { createServer } from \"vite\";\n\nimport { App } from \"../app\";\nimport gemiVite from \"../vite\";\nimport { Instrumentation } from \"./types\";\nimport { printStartupBanner } from \"./banner\";\nimport { GEMI_EXTERNAL_SPECIFIERS } from \"../internal/gemiExternals\";\nimport { createDevFetch, sendErrorToClient, ssrRunner } from \"./devFetch\";\nimport { resolveHmrPort } from \"./hmrPort\";\nimport {\n type HmrRelayData,\n hmrRelayHandler,\n hmrRelayPort,\n isHmrUpgrade,\n listenHmrServer,\n upgradeHmr,\n} from \"./hmrRelay\";\n\nexport { viteErrorPayload } from \"./devFetch\";\n\nconst rootDir = process.cwd();\nconst appDir = join(rootDir, \"app\");\n\n// `bun --hot` re-evaluates the module graph on every server-code change. A\n// syntax error or top-level throw in app code therefore fails during *module\n// load* — outside any request, and before `httpDev` re-runs — so Bun only\n// prints it to the console. Bun surfaces these as `unhandledRejection` (the\n// reload re-imports the entry and the failing dynamic import rejects), so hook\n// that here and forward it to the client. Registered once; process listeners\n// persist across reloads.\nif (!globalThis.__gemiErrorHooked) {\n globalThis.__gemiErrorHooked = true;\n process.on(\"unhandledRejection\", (reason) => {\n console.error(reason);\n sendErrorToClient(reason);\n });\n process.on(\"uncaughtException\", (err) => {\n console.error(err);\n sendErrorToClient(err);\n });\n}\n\nexport async function httpDev(app: App, instrumentation: Instrumentation) {\n // Same override the prod server honors (`httpProd.ts`). Read here rather than\n // inline at `Bun.serve` because the HMR port is derived from it.\n const httpPort = Number(process.env.PORT) || 5173;\n\n // `bun --hot` re-runs this module on every server-code change, so keep a\n // single Vite server on `globalThis` instead of spawning a new one (and a new\n // HMR socket) on each reload.\n const isReload = Boolean(globalThis.__gemiVite);\n const vite = (globalThis.__gemiVite ??= await createServer({\n // gemi owns the Vite setup — the app has no `vite.config.mjs` to discover.\n // Register the gemi plugin explicitly instead; it loads `gemi.config.ts` and\n // appends the app's Vite plugins (e.g. `@vitejs/plugin-react`, which serves\n // `/@react-refresh` and the HMR preamble referenced below).\n configFile: false,\n plugins: [gemiVite()],\n server: {\n middlewareMode: true,\n // The page's own port, so the HMR client's fallback (\"direct\") socket\n // also targets this server rather than Vite's default 5173.\n port: httpPort,\n // In middleware mode Vite would stand up a second HTTP server for the HMR\n // websocket on a fixed port — so two `gemi dev` processes fought over one\n // socket, and a proxy or tunnel, which carries only the page's port,\n // could not reach it at all. Hand Vite a loopback server instead, on a\n // port of this process's own (see `hmrPort.ts` for how it is chosen):\n // given a server, Vite tells the browser to connect to the page's origin,\n // and `Bun.serve` below relays that socket to it (see `hmrRelay.ts`).\n // `ws` and not the older `hmr`: `server.hmr.{port,host,…}` is\n // deprecated in Vite 8 and warns. An app overriding either one in\n // `gemi.config.ts` still wins — plugin config (where `gemi.config.ts`'s\n // `vite` block is applied) is merged over this inline config, and Vite's\n // own `hmr`→`ws` compat shim forwards the deprecated spelling here.\n ws: { server: await listenHmrServer(resolveHmrPort(httpPort)) },\n // Vite answers any host other than `localhost` and `*.localhost` with a\n // 403, which would block a `route.domains` root such as `lvh.me` and\n // every custom domain pointed here from `/etc/hosts`.\n allowedHosts: app.devAllowedHosts.call(app),\n // gemi reloads `.env` into process.env itself (see `watchEnv`). Stop Vite\n // from *also* watching env files: Vite's env-change handler restarts the\n // dev server, which closes the SSR module runner — but gemi keeps a single\n // Vite instance across `bun --hot` reloads, so an in-flight view import\n // hits the closed runner (\"Vite module runner has been closed\"). Ignoring\n // env files here only disables the restart; env *loading* at startup (and\n // `import.meta.env`) is unaffected.\n watch: {\n ignored: (file: string) => {\n const base = file.split(/[/\\\\]/).pop() ?? \"\";\n return base === \".env\" || base.startsWith(\".env.\");\n },\n },\n },\n appType: \"custom\",\n // Views are loaded through this SSR graph while the renderer\n // (react-dom/server in ViewRouteDispatcher) is imported by Bun.\n // Dedupe so Vite can never resolve a second React copy — a mismatch makes\n // the SSR dispatcher null (\"Invalid hook call\") after an HMR reload.\n resolve: { dedupe: [\"react\", \"react-dom\"] },\n // Pre-bundle the whole React surface the client uses in one pass. The client\n // imports `react-dom/client` (`init.tsx`) and `react-dom` (`createPortal` in\n // `HttpReload.tsx`); if only the first is discovered at startup, the first\n // request to a module using the second triggers a *second* optimize pass,\n // and the already-served page ends up importing a now-stale dep — surfacing\n // as \"does not provide an export named 't'\". Listing them up front bundles\n // them together so no re-optimization (and no version skew) happens.\n optimizeDeps: { include: [\"react\", \"react-dom\", \"react-dom/client\"] },\n // `gemi` is a linked package, so Vite would otherwise compile its own copy\n // into this graph — giving views a *different* `RouteStateContext` (and\n // other module-level singletons) than the Bun-loaded renderer's `Root`\n // provider, so `useRouteData()` reads the empty default (`i18n` undefined).\n // Externalizing makes view imports of `gemi/*` resolve to the one Bun\n // instance. Vite's `ssr.external` matches exact specifiers (subpaths are NOT\n // covered by the bare name, and regexes are ignored here), so every subpath\n // a view might import must be listed — see `internal/gemiExternals`, the\n // shared source of truth this and the SSR build (`vite/index.ts`) both use.\n ssr: {\n external: [...GEMI_EXTERNAL_SPECIFIERS],\n },\n }));\n\n process.env.ROOT_DIR = rootDir;\n process.env.APP_DIR = appDir;\n\n const devFetch = createDevFetch(app, instrumentation, vite);\n // `null` when an app's own `server.ws` in `gemi.config.ts` sent Vite's\n // websocket elsewhere; the browser then connects there directly.\n const relayPort = hmrRelayPort(vite.config?.server?.ws);\n const server = Bun.serve<HmrRelayData>({\n port: httpPort,\n fetch: (req, server) => {\n if (relayPort !== null && isHmrUpgrade(req)) {\n return upgradeHmr(req, server, relayPort);\n }\n return devFetch(req);\n },\n websocket: hmrRelayHandler,\n });\n\n // `bun --hot` re-evaluates its *whole* module graph on a server-code change —\n // node_modules included — so after a reload `react`, `react-dom/server` and the\n // Bun-loaded `gemi` are all fresh instances. This Vite server is not reloaded\n // with them (it is deliberately kept on `globalThis` above), and its SSR runner\n // still holds every view module it has evaluated — each bound, through the\n // externalized `gemi/*` imports, to the *previous* `gemi` and therefore the\n // previous `react`. The next render then sets the dispatcher on the new React\n // while a cached view calls hooks on the old one: \"Invalid hook call\", a null\n // `dispatcher.useContext` thrown from `useRouteData` inside a view nobody\n // touched. Editing a *view* never showed it — Vite's own watcher invalidates\n // that module, so it re-evaluates against the new instances. Editing a\n // server-only file (`app/config/*`, a feature declaration, a controller) is\n // the case with nothing to invalidate the views, so drop the evaluated\n // modules here, once per reload.\n //\n // Here and not before `Bun.serve`, with nothing awaited in between, because\n // both sides of the swap have to see a consistent pair. Until that call\n // returns the *previous* fetch handler is still serving — old dispatcher, old\n // `react-dom/server` — and a request landing there after an early clear would\n // re-evaluate its views against the *new* `gemi`: the same mismatch, reversed.\n // After it, the new handler is live and must not be given the stale ones. The\n // two statements are synchronous neighbours, so no request can be dispatched\n // between them.\n //\n // Only the *evaluated* modules go: the server-side transform cache is\n // untouched, so this costs a re-evaluation and not a re-transform. Clearing\n // the module graph as well would not have been enough anyway — externalized\n // deps (`gemi`, and React through it) are cached in the runner by URL and\n // carry no invalidation flag, which is exactly where the stale React hides.\n if (isReload) {\n ssrRunner(vite).clearCache();\n }\n\n // On a reload `app` has already been rebuilt with the new code and Bun.serve\n // above has swapped in the new fetch handler, so the updated controllers are\n // live *now*. Tell the client to re-run its queries only at this point —\n // firing it from Vite's file watcher instead races Bun's reload and leaves\n // the UI one change behind.\n if (isReload) {\n // We got here, so the reload succeeded. Recover from any error that was\n // showing: a standalone error page must be fully reloaded to get the app\n // back, whereas an overlay pushed onto a live page is cleared by the\n // client's `http-reload` handler (no jarring full-page reload). A normal\n // reload just re-runs client queries against the now-live controllers.\n if (globalThis.__gemiErrorActive && globalThis.__gemiErrorPageServed) {\n globalThis.__gemiErrorActive = false;\n globalThis.__gemiErrorPageServed = false;\n vite.ws.send({ type: \"full-reload\" });\n } else {\n globalThis.__gemiErrorActive = false;\n vite.ws.send({ type: \"custom\", event: \"http-reload\" });\n }\n } else {\n // First start (not a `bun --hot` reload) — print the startup banner once.\n printStartupBanner({ port: server.port, rootDir });\n }\n\n return server;\n}\n",
6
- "import { stringEraRefusal } from \"../http/Error\";\nimport { join } from \"node:path\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nimport type { RunnableDevEnvironment, ViteDevServer } from \"vite\";\n\nimport type { App } from \"../app\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport { renderErrorPage } from \"./renderErrorPage\";\nimport { createDevStyles } from \"./styles\";\nimport type { Instrumentation } from \"./types\";\n\n// Run a Web `Request` through Vite's Connect middleware.\n// Resolves to a `Response` when Vite handles the request (module transforms,\n// assets, the HMR client, ...), or `null` when it calls `next()` — which, with\n// `appType: \"custom\"`, it does for everything it doesn't own.\nfunction viteMiddleware(vite: ViteDevServer, request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n\n const req = new IncomingMessage(new Socket());\n req.url = url.pathname + url.search;\n req.method = request.method;\n req.headers = Object.fromEntries(request.headers);\n\n const res = new ServerResponse(req);\n const chunks: Buffer[] = [];\n\n return new Promise((resolve) => {\n res.write = ((chunk: any) => {\n if (chunk) chunks.push(Buffer.from(chunk));\n return true;\n }) as typeof res.write;\n\n res.end = ((chunk?: any) => {\n if (chunk && typeof chunk !== \"function\") chunks.push(Buffer.from(chunk));\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n if (value == null) continue;\n for (const v of Array.isArray(value) ? value : [value]) {\n headers.append(key, String(v));\n }\n }\n\n resolve(\n new Response(chunks.length ? Buffer.concat(chunks) : null, {\n status: res.statusCode,\n headers,\n }),\n );\n return res;\n }) as typeof res.end;\n\n vite.middlewares(req, res, () => resolve(null));\n });\n}\n\ndeclare global {\n // Created once and reused across `bun --hot` reloads (see below).\n var __gemiVite: ViteDevServer | undefined;\n // Guards one-time registration of the process error hooks across reloads.\n var __gemiErrorHooked: boolean | undefined;\n // An error overlay is currently showing on the client (clear it on recovery).\n var __gemiErrorActive: boolean | undefined;\n // We served a standalone error *page* (not just a pushed overlay), so the\n // visible document has no live app — recovery needs a full page reload.\n var __gemiErrorPageServed: boolean | undefined;\n}\n\n// Build the `> 1 | ...\\n | ^` codeframe Vite's overlay renders — must\n// match its `codeframeRE` (a `<line> | <text>` line followed by a `| ^` line,\n// each ending in a newline).\nfunction codeFrame(lineText: string, line: number, column: number) {\n const gutter = String(line);\n const pad = \" \".repeat(gutter.length);\n const caret = \" \".repeat(Math.max(0, column - 1)) + \"^\";\n return `${gutter} | ${lineText}\\n${pad} | ${caret}\\n`;\n}\n\n// Normalize whatever Bun/JS throws into the { message, stack, frame, loc }\n// shape Vite's error overlay consumes. Two cases matter:\n// - a real `Error` (runtime top-level throw) carries a proper `.stack`;\n// - a Bun `BuildMessage` (syntax error) has NO `.stack`, only a `.position`\n// ({ file, line, column, lineText }) — so synthesize a codeframe + loc from\n// it, otherwise the overlay shows a bare message with no location.\n// (An `Error` instance also JSON-stringifies to `{}`, so fields are copied by\n// hand either way.)\nexport function viteErrorPayload(err: any) {\n if (err && typeof err === \"object\") {\n const pos = err.position;\n if (pos && typeof pos === \"object\" && typeof pos.file === \"string\") {\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: \"\",\n frame:\n typeof pos.lineText === \"string\"\n ? codeFrame(pos.lineText, pos.line, pos.column)\n : undefined,\n loc: { file: pos.file, line: pos.line, column: pos.column },\n };\n }\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: typeof err.stack === \"string\" ? err.stack : \"\",\n };\n }\n return { message: String(err), stack: \"\" };\n}\n\n// Push an error into the browser via Vite's HMR socket. `__gemiVite` persists\n// across `bun --hot` reloads, so this works even when the reload that produced\n// the error never got far enough to (re)run `httpDev`.\nexport function sendErrorToClient(err: any) {\n const vite = globalThis.__gemiVite;\n if (!vite) return;\n vite.ws.send({ type: \"error\", err: viteErrorPayload(err) as any });\n globalThis.__gemiErrorActive = true;\n}\n\n/**\n * The SSR environment's module runner — what `vite.ssrLoadModule` is a thin\n * (and, in Vite 8, deprecated) wrapper over. Going through it directly is what\n * gives `httpDev` a handle on the evaluated-module cache it has to drop after a\n * `bun --hot` reload; `ssrLoadModule` keeps its own runner private.\n *\n * Duck-typed rather than `isRunnableDevEnvironment(environment)`: this server\n * outlives the module instance that created it, and after a reload the freshly\n * evaluated `vite` brings a *new* `RunnableDevEnvironment` class object, so the\n * `instanceof` that predicate performs is false for a perfectly runnable\n * environment. (The same one-copy-per-reload rule this whole dance is about.)\n */\nexport function ssrRunner(vite: ViteDevServer) {\n const environment = vite.environments.ssr as RunnableDevEnvironment;\n if (typeof environment?.runner?.import !== \"function\") {\n throw new Error(\"gemi dev requires a runnable Vite SSR environment.\");\n }\n return environment.runner;\n}\n\n/**\n * The dev document's single bootstrap module. It loads, in this order:\n *\n * 1. `/refresh.js` — the React Refresh preamble;\n * 2. `/@vite/client` — the HMR client;\n * 3. `/app/client.tsx` — the app.\n *\n * One module, because React emits every `bootstrapModules` entry as\n * `<script type=\"module\" async>`, and async module scripts run in whatever\n * order they finish loading. The preamble has to have installed\n * `window.$RefreshReg$` before any component module evaluates, or\n * `@vitejs/plugin-react`'s transform throws \"can't detect preamble\" and the\n * app never hydrates. Awaiting each `import()` is what makes the order a\n * guarantee rather than a race.\n *\n * The preamble and the HMR client are each caught: an app without\n * `@vitejs/plugin-react` has no `/@react-refresh` and needs no preamble, and a\n * broken HMR client must not stop the app from booting. The app's own import\n * is not caught, so its errors surface as they would from a script tag.\n */\nexport const DEV_ENTRY_PATH = \"/@gemi/dev-entry.js\";\n\nexport const DEV_ENTRY_SOURCE = `const report = (error) => console.error(error);\nawait import(\"/refresh.js\").catch(report);\nawait import(\"/@vite/client\").catch(report);\nawait import(\"/app/client.tsx\");\n`;\n\n/**\n * Installs the React Refresh preamble, as `@vitejs/plugin-react`'s own\n * `index.html` transform would.\n *\n * The runtime is imported by an origin-relative URL. An absolute one, built\n * from the request URL the server sees, breaks behind a TLS-terminating proxy\n * or tunnel: the browser is on `https://<tunnel>` while the server sees\n * `http://localhost:5173`, so the import is blocked as mixed content or points\n * at a host the browser cannot reach.\n */\nexport const REFRESH_PREAMBLE_SOURCE = `import RefreshRuntime from \"/@react-refresh\";\nRefreshRuntime.injectIntoGlobalHook(window);\nwindow.$RefreshReg$ = () => {};\nwindow.$RefreshSig$ = () => (type) => type;\nwindow.__vite_plugin_react_preamble_installed__ = true;\n`;\n\n/**\n * The scripts the dev document loads that nothing on disk backs: the\n * bootstrap entry above, `/refresh.js` with the React Refresh preamble, and\n * `/render-error.js`, which the dev error page loads. `null` for any other\n * path.\n *\n * Answered inside the global middleware, not in front of it as they were. They\n * have no production counterpart, but a gate that must hold in dev as well,\n * one that refuses traffic without a header, is only complete if nothing the\n * dev server answers goes around it.\n */\nfunction devScript(req: Request): Response | null {\n const { pathname } = new URL(req.url);\n const script = (source: string) =>\n new Response(source, {\n headers: {\n \"Content-Type\": \"application/javascript\",\n },\n });\n if (pathname === DEV_ENTRY_PATH) {\n return script(DEV_ENTRY_SOURCE);\n }\n if (pathname.startsWith(\"/render-error.js\")) {\n return script(\"window.render_error = true\");\n }\n if (pathname.startsWith(\"/refresh.js\")) {\n return script(REFRESH_PREAMBLE_SOURCE);\n }\n return null;\n}\n\n/**\n * The dev server's `fetch` handler, apart from `Bun.serve` and from creating\n * Vite, so a test can hand it a stub Vite server and drive it with plain\n * `Request`s. `httpDev` is the only other caller. This module has no import\n * side effects, unlike `httpDev.ts`, which installs process-wide error hooks.\n */\nexport function createDevFetch(\n app: App,\n instrumentation: Instrumentation,\n vite: ViteDevServer,\n): (req: Request) => Promise<Response> {\n const appDir = join(process.cwd(), \"app\");\n\n return async (req) => {\n const { pathname } = new URL(req.url);\n const errorResponse = (err: any): Response => {\n // Errors thrown *while handling a request* (a controller throwing, a\n // failing view import, ...) never hit `httpDev`'s module-load hooks,\n // so surface them here: forward to the overlay for any already-open\n // page, and render an error page for this response so a fresh load\n // (which has no live HMR socket yet) still shows the failure.\n console.error(err);\n vite.ssrFixStacktrace?.(err);\n sendErrorToClient(err);\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({\n error: stringEraRefusal(\"server_error\", err?.message ?? String(err), 500),\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n // This document has no live app (so no HttpReload listener to clear the\n // overlay) — remember that, so recovery forces a full page reload.\n globalThis.__gemiErrorPageServed = true;\n return new Response(renderErrorPage(viteErrorPayload(err)), {\n status: 500,\n headers: { \"Content-Type\": \"text/html\" },\n });\n };\n const requestHandler = async (req: Request): Promise<Response> => {\n const script = devScript(req);\n if (script) {\n return script;\n }\n try {\n const handler = app.fetch.bind(app);\n const result = (await viteMiddleware(vite, req)) ?? (await handler(req));\n if (result instanceof Response) {\n return result;\n }\n\n const viewImportMap = {};\n const ogMap = {};\n const viewModules = {};\n const template = (viewName: string, path: string) =>\n `\"${viewName}\": () => import(\"${path}\")`;\n const templates = [];\n\n for (const fileName of [\"404\", ...app.getFlatComponentTree.call(app)]) {\n if (process.env.NODE_ENV === \"test\") {\n break;\n }\n const appDir = `${process.env.APP_DIR}`;\n const mod = await ssrRunner(vite).import(`${appDir}/views/${fileName}.tsx`);\n\n viewImportMap[fileName] = mod.default;\n ogMap[fileName] = mod?.OpenGraph;\n // The whole module, so a streaming render can put the view's\n // `Loading`/`Error` exports into the shell it sends.\n viewModules[fileName] = mod;\n // Emit a root-relative URL (`/app/views/Foo.tsx`), NOT the absolute\n // filesystem path the runner import above uses. The browser's\n // `window.loaders` preload and `client.tsx`'s `import.meta.glob` map\n // must import the exact same URL — otherwise Vite serves the module\n // under two URLs (`/app/views/Foo.tsx` vs `/Users/.../app/views/Foo.tsx`)\n // and loads/instantiates the view twice.\n templates.push(template(fileName, `/app/views/${fileName}.tsx`));\n }\n\n const loaders = `{${templates.join(\",\")}}`;\n\n return await result({\n getStyles: async (currentViews: string[]) =>\n await createDevStyles(appDir, vite, currentViews),\n bootstrapModules: [DEV_ENTRY_PATH],\n viewImportMap,\n viewModules,\n ogMap,\n loaders,\n cssManifest: {},\n });\n } catch (err: any) {\n return errorResponse(err);\n }\n };\n\n // In front of Vite's middleware, the dev scripts and the app, as\n // `httpProd` puts the global middleware in front of its static files, so a\n // check that passes here passes there. A throw from it is answered like\n // one from a route. Vite's HMR websocket is the one thing it cannot cover:\n // its upgrade is relayed to Vite by `Bun.serve` (see `hmrRelay.ts`) before\n // this handler runs, and Vite checks the token and host itself.\n return await instrumentation(req, (req) =>\n app.withGlobalMiddleware(req, requestHandler, errorResponse),\n );\n };\n}\n",
6
+ "import { stringEraRefusal } from \"../http/Error\";\nimport { join } from \"node:path\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nimport type { RunnableDevEnvironment, ViteDevServer } from \"vite\";\n\nimport type { App } from \"../app\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport { renderErrorPage } from \"./renderErrorPage\";\nimport { createDevStyles } from \"./styles\";\nimport type { Instrumentation } from \"./types\";\n\n// Run a Web `Request` through Vite's Connect middleware.\n// Resolves to a `Response` when Vite handles the request (module transforms,\n// assets, the HMR client, ...), or `null` when it calls `next()` — which, with\n// `appType: \"custom\"`, it does for everything it doesn't own.\nfunction viteMiddleware(vite: ViteDevServer, request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n\n const req = new IncomingMessage(new Socket());\n req.url = url.pathname + url.search;\n req.method = request.method;\n req.headers = Object.fromEntries(request.headers);\n\n const res = new ServerResponse(req);\n const chunks: Buffer[] = [];\n\n return new Promise((resolve) => {\n res.write = ((chunk: any) => {\n if (chunk) chunks.push(Buffer.from(chunk));\n return true;\n }) as typeof res.write;\n\n res.end = ((chunk?: any) => {\n if (chunk && typeof chunk !== \"function\") chunks.push(Buffer.from(chunk));\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n if (value == null) continue;\n for (const v of Array.isArray(value) ? value : [value]) {\n headers.append(key, String(v));\n }\n }\n\n resolve(\n new Response(chunks.length ? Buffer.concat(chunks) : null, {\n status: res.statusCode,\n headers,\n }),\n );\n return res;\n }) as typeof res.end;\n\n vite.middlewares(req, res, () => resolve(null));\n });\n}\n\ndeclare global {\n // Created once and reused across `bun --hot` reloads (see below).\n var __gemiVite: ViteDevServer | undefined;\n // Guards one-time registration of the process error hooks across reloads.\n var __gemiErrorHooked: boolean | undefined;\n // An error overlay is currently showing on the client (clear it on recovery).\n var __gemiErrorActive: boolean | undefined;\n // We served a standalone error *page* (not just a pushed overlay), so the\n // visible document has no live app — recovery needs a full page reload.\n var __gemiErrorPageServed: boolean | undefined;\n}\n\n// Build the `> 1 | ...\\n | ^` codeframe Vite's overlay renders — must\n// match its `codeframeRE` (a `<line> | <text>` line followed by a `| ^` line,\n// each ending in a newline).\nfunction codeFrame(lineText: string, line: number, column: number) {\n const gutter = String(line);\n const pad = \" \".repeat(gutter.length);\n const caret = \" \".repeat(Math.max(0, column - 1)) + \"^\";\n return `${gutter} | ${lineText}\\n${pad} | ${caret}\\n`;\n}\n\n// Normalize whatever Bun/JS throws into the { message, stack, frame, loc }\n// shape Vite's error overlay consumes. Two cases matter:\n// - a real `Error` (runtime top-level throw) carries a proper `.stack`;\n// - a Bun `BuildMessage` (syntax error) has NO `.stack`, only a `.position`\n// ({ file, line, column, lineText }) — so synthesize a codeframe + loc from\n// it, otherwise the overlay shows a bare message with no location.\n// (An `Error` instance also JSON-stringifies to `{}`, so fields are copied by\n// hand either way.)\nexport function viteErrorPayload(err: any) {\n if (err && typeof err === \"object\") {\n const pos = err.position;\n if (pos && typeof pos === \"object\" && typeof pos.file === \"string\") {\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: \"\",\n frame:\n typeof pos.lineText === \"string\"\n ? codeFrame(pos.lineText, pos.line, pos.column)\n : undefined,\n loc: { file: pos.file, line: pos.line, column: pos.column },\n };\n }\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: typeof err.stack === \"string\" ? err.stack : \"\",\n };\n }\n return { message: String(err), stack: \"\" };\n}\n\n// Push an error into the browser via Vite's HMR socket. `__gemiVite` persists\n// across `bun --hot` reloads, so this works even when the reload that produced\n// the error never got far enough to (re)run `httpDev`.\nexport function sendErrorToClient(err: any) {\n const vite = globalThis.__gemiVite;\n if (!vite) return;\n vite.ws.send({ type: \"error\", err: viteErrorPayload(err) as any });\n globalThis.__gemiErrorActive = true;\n}\n\n/**\n * The SSR environment's module runner — what `vite.ssrLoadModule` is a thin\n * (and, in Vite 8, deprecated) wrapper over. Going through it directly is what\n * gives `httpDev` a handle on the evaluated-module cache it has to drop after a\n * `bun --hot` reload; `ssrLoadModule` keeps its own runner private.\n *\n * Duck-typed rather than `isRunnableDevEnvironment(environment)`: this server\n * outlives the module instance that created it, and after a reload the freshly\n * evaluated `vite` brings a *new* `RunnableDevEnvironment` class object, so the\n * `instanceof` that predicate performs is false for a perfectly runnable\n * environment. (The same one-copy-per-reload rule this whole dance is about.)\n */\nexport function ssrRunner(vite: ViteDevServer) {\n const environment = vite.environments.ssr as RunnableDevEnvironment;\n if (typeof environment?.runner?.import !== \"function\") {\n throw new Error(\"gemi dev requires a runnable Vite SSR environment.\");\n }\n return environment.runner;\n}\n\n/**\n * The dev document's single bootstrap module. It loads, in this order:\n *\n * 1. `/refresh.js` — the React Refresh preamble;\n * 2. `/@vite/client` — the HMR client;\n * 3. `/app/client.tsx` — the app.\n *\n * One module, because React emits every `bootstrapModules` entry as\n * `<script type=\"module\" async>`, and async module scripts run in whatever\n * order they finish loading. The preamble has to have installed\n * `window.$RefreshReg$` before any component module evaluates, or\n * `@vitejs/plugin-react`'s transform throws \"can't detect preamble\" and the\n * app never hydrates. Awaiting each `import()` is what makes the order a\n * guarantee rather than a race.\n *\n * The preamble and the HMR client are each caught: an app without\n * `@vitejs/plugin-react` has no `/@react-refresh` and needs no preamble, and a\n * broken HMR client must not stop the app from booting. The app's own import\n * is not caught, so its errors surface as they would from a script tag.\n */\nexport const DEV_ENTRY_PATH = \"/@gemi/dev-entry.js\";\n\nexport const DEV_ENTRY_SOURCE = `const report = (error) => console.error(error);\nawait import(\"/refresh.js\").catch(report);\nawait import(\"/@vite/client\").catch(report);\nawait import(\"/app/client.tsx\");\n`;\n\n/**\n * Installs the React Refresh preamble, as `@vitejs/plugin-react`'s own\n * `index.html` transform would.\n *\n * The runtime is imported by an origin-relative URL. An absolute one, built\n * from the request URL the server sees, breaks behind a TLS-terminating proxy\n * or tunnel: the browser is on `https://<tunnel>` while the server sees\n * `http://localhost:5173`, so the import is blocked as mixed content or points\n * at a host the browser cannot reach.\n */\nexport const REFRESH_PREAMBLE_SOURCE = `import RefreshRuntime from \"/@react-refresh\";\nRefreshRuntime.injectIntoGlobalHook(window);\nwindow.$RefreshReg$ = () => {};\nwindow.$RefreshSig$ = () => (type) => type;\nwindow.__vite_plugin_react_preamble_installed__ = true;\n`;\n\n/**\n * The scripts the dev document loads that nothing on disk backs: the\n * bootstrap entry above, `/refresh.js` with the React Refresh preamble, and\n * `/render-error.js`, which the dev error page loads. `null` for any other\n * path.\n *\n * Answered inside the global middleware, not in front of it as they were. They\n * have no production counterpart, but a gate that must hold in dev as well,\n * one that refuses traffic without a header, is only complete if nothing the\n * dev server answers goes around it.\n */\nfunction devScript(req: Request): Response | null {\n const { pathname } = new URL(req.url);\n const script = (source: string) =>\n new Response(source, {\n headers: {\n \"Content-Type\": \"application/javascript\",\n },\n });\n if (pathname === DEV_ENTRY_PATH) {\n return script(DEV_ENTRY_SOURCE);\n }\n if (pathname.startsWith(\"/render-error.js\")) {\n return script(\"window.render_error = true\");\n }\n if (pathname.startsWith(\"/refresh.js\")) {\n return script(REFRESH_PREAMBLE_SOURCE);\n }\n return null;\n}\n\n/**\n * The dev server's `fetch` handler, apart from `Bun.serve` and from creating\n * Vite, so a test can hand it a stub Vite server and drive it with plain\n * `Request`s. `httpDev` is the only other caller. This module has no import\n * side effects, unlike `httpDev.ts`, which installs process-wide error hooks.\n */\nexport function createDevFetch(\n app: App,\n instrumentation: Instrumentation,\n vite: ViteDevServer,\n): (req: Request) => Promise<Response> {\n const appDir = join(process.cwd(), \"app\");\n\n return async (req) => {\n const { pathname } = new URL(req.url);\n const errorResponse = (err: any): Response => {\n // Errors thrown *while handling a request* (a controller throwing, a\n // failing view import, ...) never hit `httpDev`'s module-load hooks,\n // so surface them here: forward to the overlay for any already-open\n // page, and render an error page for this response so a fresh load\n // (which has no live HMR socket yet) still shows the failure.\n console.error(err);\n vite.ssrFixStacktrace?.(err);\n sendErrorToClient(err);\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({\n error: stringEraRefusal(\"server_error\", err?.message ?? String(err), 500),\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n // This document has no live app (so no HttpReload listener to clear the\n // overlay) — remember that, so recovery forces a full page reload.\n globalThis.__gemiErrorPageServed = true;\n return new Response(renderErrorPage(viteErrorPayload(err)), {\n status: 500,\n headers: { \"Content-Type\": \"text/html\" },\n });\n };\n const requestHandler = async (req: Request): Promise<Response> => {\n const script = devScript(req);\n if (script) {\n return script;\n }\n try {\n const handler = app.fetch.bind(app);\n const result = (await viteMiddleware(vite, req)) ?? (await handler(req));\n if (result instanceof Response) {\n return result;\n }\n\n const viewImportMap = {};\n const ogMap = {};\n const viewModules = {};\n const template = (viewName: string, path: string) =>\n `\"${viewName}\": () => import(\"${path}\")`;\n const templates = [];\n\n for (const fileName of [\"404\", ...app.getFlatComponentTree.call(app)]) {\n if (process.env.NODE_ENV === \"test\") {\n break;\n }\n const appDir = `${process.env.APP_DIR}`;\n const mod = await ssrRunner(vite).import(`${appDir}/views/${fileName}.tsx`);\n\n viewImportMap[fileName] = mod.default;\n ogMap[fileName] = mod?.OpenGraph;\n // The whole module, so a streaming render can put the view's\n // `Loading`/`Error` exports into the shell it sends.\n viewModules[fileName] = mod;\n // Emit a root-relative URL (`/app/views/Foo.tsx`), NOT the absolute\n // filesystem path the runner import above uses. The browser's\n // `window.loaders` preload and `client.tsx`'s `import.meta.glob` map\n // must import the exact same URL — otherwise Vite serves the module\n // under two URLs (`/app/views/Foo.tsx` vs `/Users/.../app/views/Foo.tsx`)\n // and loads/instantiates the view twice.\n templates.push(template(fileName, `/app/views/${fileName}.tsx`));\n }\n\n const loaders = `{${templates.join(\",\")}}`;\n\n return await result({\n getStyles: async (currentViews: string[], options?: { static?: boolean; layout?: string }) =>\n await createDevStyles(appDir, vite, currentViews, options?.layout),\n // Vite serves app files by their root-relative path.\n resolveIsland: (moduleKey: string) => ({ src: `/${moduleKey}`, preload: [] }),\n bootstrapModules: [DEV_ENTRY_PATH],\n viewImportMap,\n viewModules,\n ogMap,\n loaders,\n cssManifest: {},\n });\n } catch (err: any) {\n return errorResponse(err);\n }\n };\n\n // In front of Vite's middleware, the dev scripts and the app, as\n // `httpProd` puts the global middleware in front of its static files, so a\n // check that passes here passes there. A throw from it is answered like\n // one from a route. Vite's HMR websocket is the one thing it cannot cover:\n // its upgrade is relayed to Vite by `Bun.serve` (see `hmrRelay.ts`) before\n // this handler runs, and Vite checks the token and host itself.\n return await instrumentation(req, (req) =>\n app.withGlobalMiddleware(req, requestHandler, errorResponse),\n );\n };\n}\n",
7
7
  "function cleanupTerminalText(text) {\n return (\n text\n // Remove ANSI escape sequences (colors, formatting)\n .replace(/\\x1b\\[[0-9;]*m/g, \"\")\n // Remove ANSI escape sequences with different format\n .replace(/\\[[0-9;]*m/g, \"\")\n // Remove excessive whitespace and normalize line breaks\n .replace(/\\n\\s*\\n/g, \"\\n\")\n // Trim each line\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(\"\\n\")\n .trim()\n );\n}\n\nexport function renderErrorPage(err: any) {\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />\n\n <title>Error</title>\n <style>\n body {\n font-family: Arial, sans-serif;\n padding: 20px;\n }\n h1 {\n color: red;\n }\n </style>\n </head>\n <body>\n <div id=\"overlay\"></div>\n <script type=\"module\" src=\"/refresh.js\"></script>\n <script type=\"module\" src=\"/@vite/client\"></script>\n <script>\n ${cleanupTerminalText.toString()}\n const err = ${JSON.stringify(err, Object.getOwnPropertyNames(err), 2)}\n\n window.addEventListener('load', () => {\n const container = document.getElementById('overlay')\n const ErrorOverlay = customElements.get('vite-error-overlay')\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({ ...err, message: cleanupTerminalText(err.message) });\n container.appendChild(overlay)\n }\n })\n </script>\n </body>\n</html>\n`;\n}\n",
8
8
  "// Vite's HMR websocket needs a port of its own, and in middleware mode Vite\n// always picks the same one.\n//\n// `httpDev` runs Vite with `middlewareMode: true`, so Vite has no HTTP server of\n// its own to hang the websocket off — it stands up a second HTTP server just for\n// the upgrade. When nothing names a port, that server binds Vite's default 24678\n// in *every* `gemi dev` process. `PORT` moves the Bun server and nothing else, so\n// a second dev server logs\n//\n// WebSocket server error: Port undefined is already in use\n//\n// and carries on with a dead socket. (Vite logs that failure rather than throwing\n// — which is why the symptom is not a crash but pages that hot-reload on the\n// *other* checkout's edits: their `/@vite/client` was told 24678, and 24678 is\n// the first server's.) So gemi names the port instead of letting Vite default it.\n//\n// Why derive from the HTTP port rather than just scan for a free one: two dev\n// servers must already differ in `PORT` to run at all, so deriving makes their\n// HMR ports differ *before* either one binds anything. A scan alone would hand\n// both the same port when they start at the same moment, each having probed\n// before the other bound. The scan is still here, for the port being taken by\n// something that is not a gemi dev server.\n\nconst VITE_DEFAULT_HTTP_PORT = 5173;\nconst VITE_DEFAULT_HMR_PORT = 24678;\n\n// A port is 16 bits.\nconst MAX_PORT = 65535;\n\n// How far to walk up from the derived port before giving up. Large enough that\n// only a pathological machine exhausts it, small enough to fail in well under a\n// second rather than appearing to hang.\nconst SEARCH_WINDOW = 64;\n\n/**\n * Bind-test a port the same way Vite will.\n *\n * Vite calls `wsHttpServer.listen(port, host)` with no host unless one is\n * configured, so its websocket server takes the wildcard address — which is what\n * this binds too. The match matters: a wildcard bind collides with a wildcard\n * *or* a loopback holder, while a loopback bind only collides with loopback. A\n * process holding `127.0.0.1:P` alone therefore reads as free here, correctly —\n * Vite would fail to bind `*:P` against it, but nothing in gemi makes Vite bind\n * loopback-only, so that case cannot arise from a second `gemi dev`.\n *\n * Only `EADDRINUSE` counts as taken. Any other failure — a permission error, an\n * unroutable address — is not something a different port would fix, so it is\n * reported free and left for Vite to surface.\n */\nfunction isPortFree(port: number): boolean {\n try {\n const listener = Bun.listen({\n hostname: \"0.0.0.0\",\n port,\n socket: { data() {} },\n });\n // `true` closes active connections too. There are none — nothing has been\n // told this port exists yet — but it also makes the close synchronous, so\n // the port is released before the next probe or before Vite binds it.\n listener.stop(true);\n return true;\n } catch (error) {\n return (error as { code?: string })?.code !== \"EADDRINUSE\";\n }\n}\n\n/**\n * Pick the port for Vite's HMR websocket, given the port the dev server's HTTP\n * side is on.\n *\n * `5173` returns `24678` — Vite's two defaults stay paired, so a single dev\n * server behaves exactly as it did before, and anything pointed at 24678 (a\n * firewall rule, a container port mapping, a note in a README) keeps working.\n * Every other HTTP port is offset by the same distance, so distinct `PORT`s\n * always yield distinct HMR ports.\n *\n * @param isFree Injected for tests. Production callers use the bind test above.\n */\nexport function resolveHmrPort(\n httpPort: number,\n isFree: (port: number) => boolean = isPortFree,\n): number {\n let start = VITE_DEFAULT_HMR_PORT + (httpPort - VITE_DEFAULT_HTTP_PORT);\n\n // A high `PORT` can push the derived port past the top of the range — or so\n // close to it that the walk would run off the end. Fall back to the default\n // and let the scan sort it out; being *adjacent* to another server's port is\n // fine, landing *on* it is what has to be avoided, and the scan does that.\n //\n // There is deliberately no matching floor. The offset is only -5173, so the\n // lowest a real HTTP port can derive is 19505 (from `PORT=0`) — a guard for\n // the bottom of the range would be a branch no input can take.\n if (start > MAX_PORT - SEARCH_WINDOW) {\n start = VITE_DEFAULT_HMR_PORT;\n }\n\n for (let port = start; port < start + SEARCH_WINDOW; port++) {\n if (isFree(port)) return port;\n }\n\n throw new Error(\n `Could not find a free port for Vite's HMR websocket: tried ${start}-${\n start + SEARCH_WINDOW - 1\n }. Set one explicitly in gemi.config.ts as \\`vite: { server: { ws: { port } } }\\`.`,\n );\n}\n",
9
9
  "import { createServer, type Server as NodeServer } from \"node:http\";\n\nimport type { Server, ServerWebSocket, WebSocketHandler } from \"bun\";\n\n// Vite's HMR websocket, carried on the dev server's own port.\n//\n// In middleware mode Vite has no HTTP server of its own, so by default it\n// stands up a second one for the websocket, on a second port (see\n// `hmrPort.ts`), and tells the browser to connect to `<page host>:<that port>`.\n// A reverse proxy or tunnel (ngrok, a container port mapping, a phone on the\n// LAN through https) only carries the port the page came from, so HMR could\n// not connect there, and the client logged connection failures forever.\n//\n// Vite can attach its websocket to a server it is handed (`server.ws.server`)\n// instead, and then tells the browser to connect to the page's own origin. That\n// server has to be a Node `http.Server`; the dev server is `Bun.serve`. So:\n//\n// - the Node server Vite is handed listens on loopback only, on the port\n// `resolveHmrPort` picked, and answers nothing but websocket upgrades;\n// - `Bun.serve` accepts the browser's upgrade on the page's origin and relays\n// frames both ways to that loopback server.\n//\n// The relay forwards the browser's `Host` and `Origin` and the request's query\n// (the `token`), so Vite still runs its own host and token checks against what\n// the browser actually sent.\n\n/** The subprotocols Vite's client opens its sockets with. */\nconst VITE_PROTOCOLS = new Set([\"vite-hmr\", \"vite-ping\"]);\n\n/**\n * Start the loopback Node server Vite attaches its HMR websocket to.\n * Everything but an upgrade gets `426 Upgrade Required`, as Vite's own\n * websocket server answers.\n */\nexport async function listenHmrServer(port: number): Promise<NodeServer> {\n const server = createServer((_req, res) => {\n res.writeHead(426, { \"Content-Type\": \"text/plain\" });\n res.end(\"Upgrade Required\");\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n return server;\n}\n\n/**\n * The loopback port to relay to, read from the config Vite actually resolved,\n * so an app that set its own `server.ws` in `gemi.config.ts` is relayed to\n * where Vite really is, or not relayed at all. `null` when Vite was not given\n * a server (its websocket is then on a port of its own, and the client goes\n * there directly) or when HMR is off.\n */\nexport function hmrRelayPort(wsConfig: unknown): number | null {\n if (!wsConfig || typeof wsConfig !== \"object\") return null;\n const server = (wsConfig as { server?: { address?: () => unknown } }).server;\n const address = server?.address?.();\n if (address && typeof address === \"object\" && \"port\" in address) {\n return Number((address as { port: number }).port) || null;\n }\n return null;\n}\n\n/** Whether a request is the Vite client opening its HMR (or ping) socket. */\nexport function isHmrUpgrade(req: Request): boolean {\n if (req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") return false;\n return VITE_PROTOCOLS.has(req.headers.get(\"sec-websocket-protocol\") ?? \"\");\n}\n\nexport type HmrRelayData = {\n /** The socket to Vite, already open when the browser's is accepted. */\n upstream: WebSocket;\n /** Frames Vite sent before the browser's socket opened (its `connected`). */\n early: (string | Uint8Array)[];\n browser?: ServerWebSocket<HmrRelayData>;\n};\n\ntype Frame = string | Uint8Array;\n\nconst frameOf = (data: unknown): Frame =>\n typeof data === \"string\" ? data : new Uint8Array(data as ArrayBuffer);\n\n/**\n * Open the socket to Vite first, and accept the browser's upgrade only once\n * Vite has accepted it. Returns `undefined` once Bun has taken the request\n * over, or a refusal.\n *\n * The order matters. Vite refuses a socket whose host is not in\n * `allowedHosts`, or a cross-origin one without its token. Had the browser's\n * socket been accepted first and closed when Vite refused, the client would\n * read that as \"server connection lost\", ping (which Vite always answers),\n * and reload the page, forever. Refused before it opens, the client logs one\n * \"failed to connect to websocket\" and the page keeps working.\n */\nexport async function upgradeHmr(\n req: Request,\n server: Server<HmrRelayData>,\n port: number,\n): Promise<Response | undefined> {\n const url = new URL(req.url);\n const protocol = req.headers.get(\"sec-websocket-protocol\") ?? \"vite-hmr\";\n // `Host` is what Vite's `allowedHosts` check reads; the URL's host is the\n // same value `Bun.serve` derived it from.\n const headers: Record<string, string> = {\n host: req.headers.get(\"host\") ?? url.host,\n };\n const origin = req.headers.get(\"origin\");\n if (origin) headers.origin = origin;\n\n const upstream = new WebSocket(\n `ws://127.0.0.1:${port}${url.pathname}${url.search}`,\n {\n protocols: [protocol],\n headers,\n } as any,\n );\n upstream.binaryType = \"arraybuffer\";\n const data: HmrRelayData = { upstream, early: [] };\n\n upstream.onmessage = (event) => {\n const frame = frameOf(event.data);\n if (data.browser) data.browser.send(frame);\n else data.early.push(frame);\n };\n upstream.onclose = (event) => {\n data.browser?.close(sendableCloseCode(event.code), event.reason);\n };\n upstream.onerror = () => {\n // A `close` follows; it ends the browser's socket if there is one.\n };\n\n const opened = await new Promise<boolean>((resolve) => {\n upstream.addEventListener(\"open\", () => resolve(true), { once: true });\n upstream.addEventListener(\"close\", () => resolve(false), { once: true });\n });\n if (!opened) {\n return new Response(\"Vite refused the HMR websocket\", { status: 403 });\n }\n\n const upgraded = server.upgrade(req, {\n // The browser fails a connection whose response does not echo the\n // subprotocol it asked for.\n headers: { \"Sec-WebSocket-Protocol\": protocol },\n data,\n });\n if (!upgraded) {\n upstream.close();\n return new Response(\"WebSocket upgrade failed\", { status: 400 });\n }\n return undefined;\n}\n\n// A close code that may be sent in a close frame. 1005, 1006 and 1015 are\n// reported locally and never sent.\nfunction sendableCloseCode(code: number): number {\n if (\n code === 1000 ||\n (code >= 1001 && code <= 1003) ||\n (code >= 1007 && code <= 1014)\n ) {\n return code;\n }\n if (code >= 3000 && code <= 4999) return code;\n return 1000;\n}\n\n/** `Bun.serve`'s `websocket` option: relays frames to and from Vite. */\nexport const hmrRelayHandler: WebSocketHandler<HmrRelayData> = {\n open(ws: ServerWebSocket<HmrRelayData>) {\n const data = ws.data;\n for (const frame of data.early) ws.send(frame);\n data.early = [];\n data.browser = ws;\n // Vite may have hung up while the upgrade was in flight.\n if (data.upstream.readyState !== WebSocket.OPEN) ws.close(1000);\n },\n message(ws: ServerWebSocket<HmrRelayData>, message) {\n if (ws.data.upstream.readyState === WebSocket.OPEN) {\n ws.data.upstream.send(message);\n }\n },\n close(ws: ServerWebSocket<HmrRelayData>) {\n const { upstream } = ws.data;\n if (upstream.readyState <= WebSocket.OPEN) upstream.close();\n },\n};\n"
10
10
  ],
11
- "mappings": ";gZAAA,SAAS,QAET,iBAAS,QCDT,SAAS,OACT,oBAAS,cAAiB,OAC1B,iBAAS,YCHT,SAAS,CAAmB,CAAC,EAAM,CACjC,OACE,EAEG,QAAQ,kBAAmB,EAAE,EAE7B,QAAQ,cAAe,EAAE,EAEzB,QAAQ,WAAY;AAAA,CAAI,EAExB,MAAM;AAAA,CAAI,EACV,IAAI,CAAC,IAAS,EAAK,KAAK,CAAC,EACzB,OAAO,CAAC,IAAS,EAAK,OAAS,CAAC,EAChC,KAAK;AAAA,CAAI,EACT,KAAK,EAIL,SAAS,CAAe,CAAC,EAAU,CACxC,MAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QA0BD,EAAoB,SAAS;AAAA,oBACjB,KAAK,UAAU,EAAK,OAAO,oBAAoB,CAAG,EAAG,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ED7B1E,SAAS,CAAc,CAAC,EAAqB,EAA4C,CACvF,IAAM,EAAM,IAAI,IAAI,EAAQ,GAAG,EAEzB,EAAM,IAAI,EAAgB,IAAI,CAAQ,EAC5C,EAAI,IAA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Z,_b as WZ,ac as q,bc as zZ,cc as VZ,ec as KZ}from"./chunk-6wrhc9bq.js";import{hc as I}from"./chunk-9hbwvcxn.js";import{Cc as r,Ed as M,Id as R,Jc as AZ,Jd as c,Kd as p,ed as UZ,fd as i,jd as w,rd as t,td as v,xd as o,yc as _Z}from"./chunk-5mj7a141.js";import{de as CZ,ee as l}from"./chunk-h7pafjej.js";import{Lf as n,Nf as g,Of as y,Pf as j,wf as m}from"./chunk-rh9j8cwv.js";import{Yf as $Z,_f as x}from"./chunk-gqpge54c.js";import{$f as U}from"./chunk-5wt25tyd.js";import{fg as OZ}from"./chunk-k9qmr2wa.js";import{Ug as s}from"./chunk-tyhrrnp5.js";import{_g as IZ,bh as f}from"./chunk-9mqqr05d.js";async function jZ(Z,$={}){try{if(!await Z.shouldRun.call(Z))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${Z.name}:`,W);return}let G=kZ(Z.withoutOverlapping);if(!Z.onOneServer&&G===void 0){await u(Z);return}let H;try{if(H=$.locks?.()??MZ(),Z.onOneServer){let W=Math.floor(($.now??Date.now())/60000);if(!await H.store.advance(`gemi:cron-tick:${Z.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${Z.name}; skipped it:`,W);return}if(G===void 0){await u(Z);return}try{await H.run(`gemi:cron:${Z.name}`,{ttl:G},(W)=>u(Z,W))}catch(W){if(W instanceof $Z)console.error(`Cron job ${Z.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,W);else console.error(`Could not take the withoutOverlapping lock of cron job ${Z.name}:`,W)}}var e=300000;function kZ(Z){if(!Z)return;if(Z===!0)return e;return Z.expiresAfter??e}var ZZ;function MZ(){return ZZ??=new x(new GZ),ZZ}async function u(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 P{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 H of this.resolved){let W=new H;if(!W.name){console.error(`Cron job must have a name \u2014 ${H.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let z=G.get(W.name);if(z!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${z} is scheduled and ${H.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(W.name,H.name||"an anonymous class"),$.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let V=this.locks;return this.track(W.name,()=>Z(()=>jZ(W,{locks:V})))});$.set(W.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((H)=>{if(Z!==1/0)$=setTimeout(H,Z)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((H)=>H.done)),G]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((H)=>({...H.tick}))}}get running(){return this.inFlight.size}track(Z,$){let G={},H=Promise.resolve().then($).finally(()=>this.inFlight.delete(G));return this.inFlight.set(G,{tick:{name:Z,startedAt:new Date},done:H}),H}}import{isMainThread as yZ}from"worker_threads";var wZ=100,fZ=(Z)=>Math.min(wZ,Math.floor(Z/10));class bZ extends I{register(){this.app.singleton(q,()=>new q(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(x,()=>this.app.make(q).locks)}async boot(){let Z=this.app.config.get("queue",{});if(Z.jobs!==void 0)return;let{jobsDir:$}=U(WZ(),Z);this.app.make(q).useJobs(await XZ($))}async shutdown(Z){if(!this.app.resolved(q))return;let $=this.app.make(q);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running queued job(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-fZ(G)));if(H.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+H.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function L3(Z){if(vZ(Z),Bun.env.NODE_ENV!=="production")return mZ(Z);if(YZ(Z))return;if(!zZ())return;if(!Z.bound(q))return;Z.make(q).start()}function YZ(Z){let $=Z.config.get("queue",{}).driver??"memory";return $==="memory"||$ instanceof HZ}function gZ(Z){if(YZ(Z))return!0;if(typeof Z.config.get("queue",{}).driver!=="function"||!Z.bound(q))return!1;try{return!Z.make(q).durable}catch{return!1}}function vZ(Z){let $=process.env.GEMI_QUEUE_CLAIM;if($===void 0||KZ())return;if(process.env.ROOT_DIR===void 0||!yZ)return;if(VZ()){if(!gZ(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 mZ(Z){let $=globalThis.__gemiDevQueue;if(!$)return;if(globalThis.__gemiDevQueue=void 0,$.stop(),Z.bound(q))Z.make(q).start()}class hZ extends I{register(){this.app.singleton(p,()=>new p(this.app.config.get("auth",{})))}}var cZ=100,uZ=(Z)=>Math.min(cZ,Math.floor(Z/10));class pZ extends I{register(){this.app.singleton(P,()=>new P(U(d(),this.app.config.get("schedule",{}))))}async boot(){let Z=this.app.make(P),$=this.app.config.get("schedule",{});if($.jobs===void 0){let{jobsDir:H}=U(d(),$);Z.useJobs(await JZ(H))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let G=this.app;if(G.bound(x))Z.useLocks(()=>G.make(x));Z.start((H)=>IZ.run(G,H))}async shutdown(Z){if(!this.app.resolved(P))return;let $=this.app.make(P);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running cron tick(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-uZ(G)));if(H.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+H.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class T extends UZ{modelName;constructor(Z="FeatureFlag"){super();this.modelName=Z}get available(){return CZ(this.modelName)}async load(){if(!this.available)throw new i(this.modelName);let Z=l(this.modelName);return await Z.asSystem(()=>Z.findMany())}async write(Z,$,G){if(!this.available)throw new i(this.modelName);let H=l(this.modelName),W=this.hasActorColumn(H),z={active:$};if(W)z.updatedBy=G.actor;return await H.asSystem(()=>H.upsert({where:{key:Z},create:{key:Z,...z},update:z})),{actorRecorded:W}}hasActorColumn(Z){let $=Z?.$schema?.fields?.updatedBy;return $!==void 0&&$.type==="String"}}function c3(Z){return Z}function BZ(){return{features:void 0,enabled:!0,source:new T,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class dZ extends I{register(){this.app.singleton(w,()=>{let Z=this.app.config.get("features",{}),$=U(BZ(),Z);if(Z?.model!==void 0&&Z?.source===void 0)$.source=new T(Z.model);else if(Z?.model!==void 0&&Z.source instanceof T&&Z.source.modelName!==Z.model)y.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 w($,(G)=>y.warning(G))})}async boot(){let Z=this.app.make(w);if(!Z.config.enabled)return;try{await Z.refresh()}catch($){y.error(`Could not warm the feature flag cache at boot. ${$ instanceof Error?$.message:String($)}`)}}}class lZ extends I{register(){this.app.singleton(s,()=>new s(this.app.config.get("mail",{})))}}function iZ(Z){return`listener:${Z}`}function NZ(Z,$){sZ(Z);let{maxAttempts:G,backoff:H,worker:W}=$,z=Z.event.name,Y=class extends qZ{maxAttempts=G;backoff=H;worker=W;async run(...V){let[K,J]=nZ(V),B=f(L).rehydrate(K,J);await new Z().handle(B)}onFail(V){console.error(`The listener ${Z.name} threw while handling ${z} off the queue. The queue will retry it up to ${G} times in total; nothing the dispatcher did is waiting on it.`,V)}onDeadletter(V){console.error(`The listener ${Z.name} failed every one of its ${G} attempts at ${z} and has been dead-lettered, so this side effect did not happen and will not be retried.`,V)}};return Object.defineProperty(Y,"name",{value:iZ(Z.name),writable:!0}),Y}function sZ(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 nZ(Z){return typeof Z[0]==="string"?Z:Z[0]}class L{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(Z={}){this.config=U(b(),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 H=G.event.name,W=new G;this.events[H]??=G.event,(this.listeners[H]??=[]).push({listener:G,job:W.queued?NZ(G,W):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:H,afterCommit:W}=Z.constructor;if(!W)return!1;let z=OZ(()=>this.runListeners(Z,$));if(z&&G)this.warnNothingIsWaitedFor(H);return z}async runListeners(Z,$){let G=Z.constructor.name,H=this.listeners[G];if(!H?.length){this.warnNothingIsListening(G);return}for(let{listener:W,job:z}of H){if(z){this.enqueue(z,W,G,$);continue}try{await new W().handle(Z)}catch(Y){console.error(`The listener ${W.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,H){if(H===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 W=(z)=>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.`,z);try{f(q).push(Z,JSON.stringify([G,H]),{reportFailure:!1}).catch(W)}catch(z){W(z)}}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 tZ extends I{register(){this.app.singleton(L,()=>new L(this.app.config.get("events",{})))}async boot(){let Z=this.app.make(L),$=this.app.config.get("events",{});if($.listeners===void 0){let{listenersDir:W}=U(b(),$);Z.useListeners(await QZ(W))}let G=Z.queuedListenerJobs;if(G.length===0)return;let H=this.app.make(q);for(let W of G)H.registerJob(W)}}class oZ extends I{register(){this.app.singleton(n,()=>new n(this.app.config.get("filesystem",{})))}}class rZ extends I{register(){this.app.singleton(t,()=>new t(this.app.config.get("image",{})))}}class aZ extends I{register(){this.app.instance(o,new o)}}function E4(Z){return Z}function FZ(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class eZ extends I{register(){this.app.singleton(g,()=>new g(U(FZ(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(g).boot()}}class Z3 extends I{register(){this.app.singleton(v,()=>new v(U(_Z(),this.app.config.get("middleware",{}))))}boot(){this.app.make(v).assertGlobalMiddleware()}}function h4(Z){return Z}function xZ(){return{driver:new AZ,limit:1000,window:60}}class $3 extends I{register(){this.app.singleton(r,()=>new r(U(xZ(),this.app.config.get("ratelimiter",{}))))}}function s4(Z){return Z}function PZ(){return{url:process.env.REDIS_URL,options:void 0}}class G3 extends I{register(){this.app.singleton(j,()=>new j(U(PZ(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(j))return;this.app.make(j).close()}}class Q extends a{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}var W3=/^[A-Za-z0-9_-]{1,64}$/,H3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,LZ=4000,E=1e5,z3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class k{router;dispatcher;static token="router.mcp";plans=new Map;constructor(Z,$){this.router=Z;this.dispatcher=$;for(let[G,H]of Object.entries(Z.routes??{}))this.plans.set(G,this.plan(G,H))}list(Z,$){return SZ(Z),this.descriptors($)}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values()){if(Z?.names&&!Z.names.includes(G.name))continue;if(Z?.tags&&!G.tags.some((H)=>Z.tags.includes(H)))continue;$.push(G)}return $}async execute(Z,$,G,H){SZ(Z);let W=this.plans.get($);if(!W)throw Error(`McpRegistry: there is no tool named "${$}".`);let{descriptor:z}=W,Y=z.inputSchema.safeParse(G);if(Y.ok===!1)throw new Q(`Invalid arguments for "${$}": ${Y.errors.join(", ")}`);let V=Y.value,K={caller:Z,req:Z.req,tool:z,input:V,ctx:H},J=await this.fillPath(W,K),{path:B}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${J}`));if(B!==z.url)throw new Q(`"${$}" has nothing at ${J}.`,404);let C={};for(let F of W.jsonKeys)if(V[F]!==void 0)C[F]=V[F];let O,_="";if(W.fileFields.length>0)O=await this.formData(W,C,K);else if(z.method==="GET")_=I3(C);else if(W.jsonKeys.length>0)O=C;let D=this.router.credentials?await this.bind(W,"the credentials",()=>this.router.credentials(K)):void 0,S;try{let F=_?`${J}?${_}`:J;S=D?await this.dispatcher.dispatchAs(Z.req,z.method,F,O,{credentials:D}):await this.dispatcher.dispatchAs(Z.req,z.method,F,O)}catch(F){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,F),new Q(`"${$}" failed on the server.`,500)}if(!W.result&&!z.outputSchema)return await RZ($,S);return await this.project(W,K,S)}plan(Z,$){if(!W3.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:H,url:W,meta:z}=$;if(W.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[H];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let V=[...W.matchAll(H3)].map(([,X,N])=>({name:X,modifier:N})),K=z.params??{};for(let X of V)if(!(X.name in K))throw Error(`${G}: the path param "${X.name}" must be bound or declared "input".`);for(let[X,N]of Object.entries(K)){if(!V.some((A)=>A.name===X))throw Error(`${G}: "${X}" in params is not a param of the url.`);if(EZ(N))V3(G,`params.${X}`,N);else TZ(G,`params.${X}`,N)}let J=[],B;if(z.input){if(B=z.input.toJSONSchema(),B.type!=="object"||!B.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);J=Object.keys(B.properties)}let C=Object.entries(z.files??{}).map(([X,N])=>({name:X,binder:N}));for(let X of C)TZ(G,`files.${X.name}`,X.binder);if(z.result!==void 0&&typeof z.result!=="function")throw Error(`${G}: result must be a function.`);if(z.output!==void 0&&typeof z.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(C.length>0&&H==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let O={},_=(X,N)=>{if(X in O)throw Error(`${G}: "${X}" is the input key of two params or files, and the model can only send one.`);O[X]=N},D=new Map,S=new Map;for(let X of V){let N=K[X.name];if(N==="input"){let A=m.string().describe(`The ":${X.name}" segment of the url.`);_(X.name,X.modifier==="?"||X.modifier==="*"?A.optional():A)}else if(EZ(N)){let A=N.as??X.name;_(A,N.input),S.set(X.name,{key:A,param:N})}else D.set(X.name,N)}for(let X of C)if(X.binder==="input")_(X.name,m.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field."));let F=[...Object.keys(O),...C.map((X)=>X.name)];for(let X of new Set(F))if(J.includes(X))throw Error(`${G}: "${X}" is both an input field and a param or file, and the model can only send one.`);return{descriptor:Object.freeze({name:Z,description:z.description,method:H,url:W,inputSchema:X3(z.input,B,m.object(O)),...z.output?{outputSchema:z.output}:{},annotations:K3(H),tags:Object.freeze([...z.tags??[]]),requiresApproval:z.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),params:V,paramBinders:D,modelParams:S,fileFields:C,jsonKeys:J,...z.result?{result:z.result}:{}}}async fillPath(Z,$){let{input:G,req:H}=$,W=Z.descriptor.url;for(let z of Z.params){let Y=Z.paramBinders.get(z.name),V=Z.modelParams.get(z.name),K;if(Y||V){if(K=V?await this.bind(Z,`the param "${z.name}"`,()=>V.param.bind(G[V.key],H,$),{refusals:!0}):await this.bind(Z,`the param "${z.name}"`,()=>Y(H,$)),K===void 0||K===null||K==="")throw console.error(`[gemi/mcp] The ${V?"resolver":"binder"} for "${z.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(K)}.`),new Q(`"${Z.descriptor.name}" failed on the server.`,500)}else K=G[z.name];let J=`:${z.name}${z.modifier}`;if(K===void 0||K===null||K===""){if(z.modifier!=="?"&&z.modifier!=="*")throw new Q(`"${z.name}" of "${Z.descriptor.name}" must not be empty.`);W=W.replace(`/${J}`,"");continue}W=W.replace(J,Y3(Z.descriptor.name,z,String(K)))}return W}async formData(Z,$,G){let{input:H,ctx:W}=G,z=Z.descriptor.name;if(!W)throw Error(`McpRegistry: "${z}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[V,K]of Object.entries($))DZ(Y,V,K);for(let V of Z.fileFields){let K=V.binder==="input"?H[V.name]:await this.bind(Z,`the file "${V.name}"`,()=>V.binder(W,G));if(typeof K!=="string"||K==="")throw new Q(`"${z}" needs a file for "${V.name}", and this turn has none. Ask the user to attach one.`);Y.append(V.name,await W.attachments.file(K))}return Y}async project(Z,$,G){let{name:H,outputSchema:W}=Z.descriptor;if(G.status<200||G.status>=300)return await RZ(H,G);let z=(C,O)=>{if(O===void 0)console.error(`[gemi/mcp] "${H}" ${C}`);else console.error(`[gemi/mcp] "${H}" ${C}`,O);return new Q(`"${H}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),V=await G.text(),K=null;if(V!=="")try{K=JSON.parse(V)}catch{throw z(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let J=K;if(Z.result)try{J=await Z.result(K,$)}catch(C){throw z("failed in its result projection:",C)}if(W){let C=W.safeParse(J);if(C.ok===!1)throw z(`answered what its output schema refuses: ${C.errors.join(", ")}`);J=C.value}if(J===void 0)return null;let B=JSON.stringify(J);if(B!==void 0&&B.length>E)return`${B.slice(0,E)}\u2026 [cut at ${E} of ${B.length} characters]`;return J}async bind(Z,$,G,H={}){try{return await G()}catch(W){if(H.refusals&&W instanceof a)throw W;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,W),new Q(`"${Z.descriptor.name}" failed on the server.`,500)}}}function SZ(Z){if(Z?.kind!=="local")throw Error("McpRegistry: only local callers are implemented. A remote caller needs a bearer-token resolver, which v1 does not have \u2014 and until it does there is no remote surface to call from.")}function TZ(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 H=G.input;if(typeof H?.safeParse!=="function"||typeof H.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.`)}function K3(Z){switch(Z){case"GET":return Object.freeze({readOnlyHint:!0});case"DELETE":return Object.freeze({destructiveHint:!0});case"PUT":return Object.freeze({idempotentHint:!0});default:return Object.freeze({})}}function X3(Z,$,G){let H=G.toJSONSchema(),W={...$??{},type:"object",properties:{...$?.properties??{},...H.properties},required:[...$?.required??[],...H.required??[]],additionalProperties:!1},z=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["expected an object"]};let V=[],K={};if(Z){let B=Z.safeParse(Y);if(B.ok===!1)V.push(...B.errors);else K={...B.value}}let J=G.safeParse(Y);if(J.ok===!1)V.push(...J.errors);else K={...K,...J.value};return V.length>0?{ok:!1,errors:V}:{ok:!0,value:K}};return{toJSONSchema:()=>W,safeParse:z,parse(Y){let V=z(Y);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function Y3(Z,$,G){let H=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(H.some((W)=>W==="."||W===".."))throw new Q(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return H.map(encodeURIComponent).join("/")}function DZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let H of G)DZ(Z,$,H);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function I3(Z){let $=new URLSearchParams,G=(H,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let z of W)G(H,z);return}$.append(H,typeof W==="object"?JSON.stringify(W):String(W))};for(let[H,W]of Object.entries(Z))G(H,W);return $.toString()}async function RZ(Z,$){if($.status>=200&&$.status<300){let H=$.headers.get("Content-Type");if(H&&!z3.test(H)){let z=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${z} bytes of ${H}, which is not shown.`}let W=await $.text();if(W==="")return null;if(W.length>E)return`${W.slice(0,E)}\u2026 [cut at ${E} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let G=await $.text();if($.status>=400&&$.status<500){let H=G.length>LZ?`${G.slice(0,LZ)}\u2026`:G;throw new Q(`"${Z}" was refused with ${$.status}${H?`: ${H}`:"."}`,$.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 Q(`"${Z}" failed on the server.`,$.status)}function h(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 J3 extends I{register(){this.app.singleton(R,()=>new R(h(this.app.config,"route.api"))),this.app.singleton(M,()=>new M(h(this.app.config,"route.view"))),this.app.singleton(c,()=>new c({api:this.app.make(R),view:this.app.make(M)},{api:h(this.app.config,"route.api"),view:h(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(k,()=>{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 k(new Z.router,this.app.make(R))})}boot(){if(this.app.make(R),this.app.make(M),this.app.make(c),this.app.config.get("route.mcp"))this.app.make(k)}}
2
+ import{Bb as a}from"./chunk-t26n9vzw.js";import{Nb as d,Pb as b,Rb as XZ,Sb as JZ,Ub as QZ}from"./chunk-qyyxzy04.js";import{$b as HZ,Vb as GZ,Yb as qZ,_b as WZ,ac as q,bc as zZ,cc as VZ,ec as KZ}from"./chunk-vee4j6ft.js";import{hc as I}from"./chunk-9hbwvcxn.js";import{Cc as r,Fd as M,Jc as AZ,Jd as R,Kd as c,Ld as p,ed as UZ,fd as i,jd as w,rd as t,td as v,xd as o,yc as _Z}from"./chunk-s5aa4hty.js";import{ee as CZ,fe as l}from"./chunk-3x86bhfn.js";import{Mf as n,Of as g,Pf as y,Qf as j,xf as m}from"./chunk-sp2v357a.js";import{$f as x,Zf as $Z}from"./chunk-wdpdqjr1.js";import{ag as U}from"./chunk-9m18pknp.js";import{gg as OZ}from"./chunk-ngw4xzrt.js";import{Vg as s}from"./chunk-tr9mxdth.js";import{$g as IZ,ch as f}from"./chunk-h6g9g8qc.js";async function jZ(Z,$={}){try{if(!await Z.shouldRun.call(Z))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${Z.name}:`,W);return}let G=kZ(Z.withoutOverlapping);if(!Z.onOneServer&&G===void 0){await u(Z);return}let H;try{if(H=$.locks?.()??MZ(),Z.onOneServer){let W=Math.floor(($.now??Date.now())/60000);if(!await H.store.advance(`gemi:cron-tick:${Z.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${Z.name}; skipped it:`,W);return}if(G===void 0){await u(Z);return}try{await H.run(`gemi:cron:${Z.name}`,{ttl:G},(W)=>u(Z,W))}catch(W){if(W instanceof $Z)console.error(`Cron job ${Z.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,W);else console.error(`Could not take the withoutOverlapping lock of cron job ${Z.name}:`,W)}}var e=300000;function kZ(Z){if(!Z)return;if(Z===!0)return e;return Z.expiresAfter??e}var ZZ;function MZ(){return ZZ??=new x(new GZ),ZZ}async function u(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 P{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 H of this.resolved){let W=new H;if(!W.name){console.error(`Cron job must have a name \u2014 ${H.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let z=G.get(W.name);if(z!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${z} is scheduled and ${H.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(W.name,H.name||"an anonymous class"),$.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let V=this.locks;return this.track(W.name,()=>Z(()=>jZ(W,{locks:V})))});$.set(W.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((H)=>{if(Z!==1/0)$=setTimeout(H,Z)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((H)=>H.done)),G]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((H)=>({...H.tick}))}}get running(){return this.inFlight.size}track(Z,$){let G={},H=Promise.resolve().then($).finally(()=>this.inFlight.delete(G));return this.inFlight.set(G,{tick:{name:Z,startedAt:new Date},done:H}),H}}import{isMainThread as yZ}from"worker_threads";var wZ=100,fZ=(Z)=>Math.min(wZ,Math.floor(Z/10));class bZ extends I{register(){this.app.singleton(q,()=>new q(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(x,()=>this.app.make(q).locks)}async boot(){let Z=this.app.config.get("queue",{});if(Z.jobs!==void 0)return;let{jobsDir:$}=U(WZ(),Z);this.app.make(q).useJobs(await XZ($))}async shutdown(Z){if(!this.app.resolved(q))return;let $=this.app.make(q);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running queued job(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-fZ(G)));if(H.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+H.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function L3(Z){if(vZ(Z),Bun.env.NODE_ENV!=="production")return mZ(Z);if(YZ(Z))return;if(!zZ())return;if(!Z.bound(q))return;Z.make(q).start()}function YZ(Z){let $=Z.config.get("queue",{}).driver??"memory";return $==="memory"||$ instanceof HZ}function gZ(Z){if(YZ(Z))return!0;if(typeof Z.config.get("queue",{}).driver!=="function"||!Z.bound(q))return!1;try{return!Z.make(q).durable}catch{return!1}}function vZ(Z){let $=process.env.GEMI_QUEUE_CLAIM;if($===void 0||KZ())return;if(process.env.ROOT_DIR===void 0||!yZ)return;if(VZ()){if(!gZ(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 mZ(Z){let $=globalThis.__gemiDevQueue;if(!$)return;if(globalThis.__gemiDevQueue=void 0,$.stop(),Z.bound(q))Z.make(q).start()}class hZ extends I{register(){this.app.singleton(p,()=>new p(this.app.config.get("auth",{})))}}var cZ=100,uZ=(Z)=>Math.min(cZ,Math.floor(Z/10));class pZ extends I{register(){this.app.singleton(P,()=>new P(U(d(),this.app.config.get("schedule",{}))))}async boot(){let Z=this.app.make(P),$=this.app.config.get("schedule",{});if($.jobs===void 0){let{jobsDir:H}=U(d(),$);Z.useJobs(await JZ(H))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let G=this.app;if(G.bound(x))Z.useLocks(()=>G.make(x));Z.start((H)=>IZ.run(G,H))}async shutdown(Z){if(!this.app.resolved(P))return;let $=this.app.make(P);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running cron tick(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-uZ(G)));if(H.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+H.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class T extends UZ{modelName;constructor(Z="FeatureFlag"){super();this.modelName=Z}get available(){return CZ(this.modelName)}async load(){if(!this.available)throw new i(this.modelName);let Z=l(this.modelName);return await Z.asSystem(()=>Z.findMany())}async write(Z,$,G){if(!this.available)throw new i(this.modelName);let H=l(this.modelName),W=this.hasActorColumn(H),z={active:$};if(W)z.updatedBy=G.actor;return await H.asSystem(()=>H.upsert({where:{key:Z},create:{key:Z,...z},update:z})),{actorRecorded:W}}hasActorColumn(Z){let $=Z?.$schema?.fields?.updatedBy;return $!==void 0&&$.type==="String"}}function c3(Z){return Z}function BZ(){return{features:void 0,enabled:!0,source:new T,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class dZ extends I{register(){this.app.singleton(w,()=>{let Z=this.app.config.get("features",{}),$=U(BZ(),Z);if(Z?.model!==void 0&&Z?.source===void 0)$.source=new T(Z.model);else if(Z?.model!==void 0&&Z.source instanceof T&&Z.source.modelName!==Z.model)y.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 w($,(G)=>y.warning(G))})}async boot(){let Z=this.app.make(w);if(!Z.config.enabled)return;try{await Z.refresh()}catch($){y.error(`Could not warm the feature flag cache at boot. ${$ instanceof Error?$.message:String($)}`)}}}class lZ extends I{register(){this.app.singleton(s,()=>new s(this.app.config.get("mail",{})))}}function iZ(Z){return`listener:${Z}`}function NZ(Z,$){sZ(Z);let{maxAttempts:G,backoff:H,worker:W}=$,z=Z.event.name,Y=class extends qZ{maxAttempts=G;backoff=H;worker=W;async run(...V){let[K,J]=nZ(V),B=f(L).rehydrate(K,J);await new Z().handle(B)}onFail(V){console.error(`The listener ${Z.name} threw while handling ${z} off the queue. The queue will retry it up to ${G} times in total; nothing the dispatcher did is waiting on it.`,V)}onDeadletter(V){console.error(`The listener ${Z.name} failed every one of its ${G} attempts at ${z} and has been dead-lettered, so this side effect did not happen and will not be retried.`,V)}};return Object.defineProperty(Y,"name",{value:iZ(Z.name),writable:!0}),Y}function sZ(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 nZ(Z){return typeof Z[0]==="string"?Z:Z[0]}class L{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(Z={}){this.config=U(b(),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 H=G.event.name,W=new G;this.events[H]??=G.event,(this.listeners[H]??=[]).push({listener:G,job:W.queued?NZ(G,W):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:H,afterCommit:W}=Z.constructor;if(!W)return!1;let z=OZ(()=>this.runListeners(Z,$));if(z&&G)this.warnNothingIsWaitedFor(H);return z}async runListeners(Z,$){let G=Z.constructor.name,H=this.listeners[G];if(!H?.length){this.warnNothingIsListening(G);return}for(let{listener:W,job:z}of H){if(z){this.enqueue(z,W,G,$);continue}try{await new W().handle(Z)}catch(Y){console.error(`The listener ${W.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,H){if(H===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 W=(z)=>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.`,z);try{f(q).push(Z,JSON.stringify([G,H]),{reportFailure:!1}).catch(W)}catch(z){W(z)}}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 tZ extends I{register(){this.app.singleton(L,()=>new L(this.app.config.get("events",{})))}async boot(){let Z=this.app.make(L),$=this.app.config.get("events",{});if($.listeners===void 0){let{listenersDir:W}=U(b(),$);Z.useListeners(await QZ(W))}let G=Z.queuedListenerJobs;if(G.length===0)return;let H=this.app.make(q);for(let W of G)H.registerJob(W)}}class oZ extends I{register(){this.app.singleton(n,()=>new n(this.app.config.get("filesystem",{})))}}class rZ extends I{register(){this.app.singleton(t,()=>new t(this.app.config.get("image",{})))}}class aZ extends I{register(){this.app.instance(o,new o)}}function E4(Z){return Z}function FZ(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class eZ extends I{register(){this.app.singleton(g,()=>new g(U(FZ(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(g).boot()}}class Z3 extends I{register(){this.app.singleton(v,()=>new v(U(_Z(),this.app.config.get("middleware",{}))))}boot(){this.app.make(v).assertGlobalMiddleware()}}function h4(Z){return Z}function xZ(){return{driver:new AZ,limit:1000,window:60}}class $3 extends I{register(){this.app.singleton(r,()=>new r(U(xZ(),this.app.config.get("ratelimiter",{}))))}}function s4(Z){return Z}function PZ(){return{url:process.env.REDIS_URL,options:void 0}}class G3 extends I{register(){this.app.singleton(j,()=>new j(U(PZ(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(j))return;this.app.make(j).close()}}class Q extends a{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}var W3=/^[A-Za-z0-9_-]{1,64}$/,H3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,LZ=4000,E=1e5,z3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class k{router;dispatcher;static token="router.mcp";plans=new Map;constructor(Z,$){this.router=Z;this.dispatcher=$;for(let[G,H]of Object.entries(Z.routes??{}))this.plans.set(G,this.plan(G,H))}list(Z,$){return SZ(Z),this.descriptors($)}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values()){if(Z?.names&&!Z.names.includes(G.name))continue;if(Z?.tags&&!G.tags.some((H)=>Z.tags.includes(H)))continue;$.push(G)}return $}async execute(Z,$,G,H){SZ(Z);let W=this.plans.get($);if(!W)throw Error(`McpRegistry: there is no tool named "${$}".`);let{descriptor:z}=W,Y=z.inputSchema.safeParse(G);if(Y.ok===!1)throw new Q(`Invalid arguments for "${$}": ${Y.errors.join(", ")}`);let V=Y.value,K={caller:Z,req:Z.req,tool:z,input:V,ctx:H},J=await this.fillPath(W,K),{path:B}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${J}`));if(B!==z.url)throw new Q(`"${$}" has nothing at ${J}.`,404);let C={};for(let F of W.jsonKeys)if(V[F]!==void 0)C[F]=V[F];let O,_="";if(W.fileFields.length>0)O=await this.formData(W,C,K);else if(z.method==="GET")_=I3(C);else if(W.jsonKeys.length>0)O=C;let D=this.router.credentials?await this.bind(W,"the credentials",()=>this.router.credentials(K)):void 0,S;try{let F=_?`${J}?${_}`:J;S=D?await this.dispatcher.dispatchAs(Z.req,z.method,F,O,{credentials:D}):await this.dispatcher.dispatchAs(Z.req,z.method,F,O)}catch(F){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,F),new Q(`"${$}" failed on the server.`,500)}if(!W.result&&!z.outputSchema)return await RZ($,S);return await this.project(W,K,S)}plan(Z,$){if(!W3.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:H,url:W,meta:z}=$;if(W.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[H];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let V=[...W.matchAll(H3)].map(([,X,N])=>({name:X,modifier:N})),K=z.params??{};for(let X of V)if(!(X.name in K))throw Error(`${G}: the path param "${X.name}" must be bound or declared "input".`);for(let[X,N]of Object.entries(K)){if(!V.some((A)=>A.name===X))throw Error(`${G}: "${X}" in params is not a param of the url.`);if(EZ(N))V3(G,`params.${X}`,N);else TZ(G,`params.${X}`,N)}let J=[],B;if(z.input){if(B=z.input.toJSONSchema(),B.type!=="object"||!B.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);J=Object.keys(B.properties)}let C=Object.entries(z.files??{}).map(([X,N])=>({name:X,binder:N}));for(let X of C)TZ(G,`files.${X.name}`,X.binder);if(z.result!==void 0&&typeof z.result!=="function")throw Error(`${G}: result must be a function.`);if(z.output!==void 0&&typeof z.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(C.length>0&&H==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let O={},_=(X,N)=>{if(X in O)throw Error(`${G}: "${X}" is the input key of two params or files, and the model can only send one.`);O[X]=N},D=new Map,S=new Map;for(let X of V){let N=K[X.name];if(N==="input"){let A=m.string().describe(`The ":${X.name}" segment of the url.`);_(X.name,X.modifier==="?"||X.modifier==="*"?A.optional():A)}else if(EZ(N)){let A=N.as??X.name;_(A,N.input),S.set(X.name,{key:A,param:N})}else D.set(X.name,N)}for(let X of C)if(X.binder==="input")_(X.name,m.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field."));let F=[...Object.keys(O),...C.map((X)=>X.name)];for(let X of new Set(F))if(J.includes(X))throw Error(`${G}: "${X}" is both an input field and a param or file, and the model can only send one.`);return{descriptor:Object.freeze({name:Z,description:z.description,method:H,url:W,inputSchema:X3(z.input,B,m.object(O)),...z.output?{outputSchema:z.output}:{},annotations:K3(H),tags:Object.freeze([...z.tags??[]]),requiresApproval:z.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),params:V,paramBinders:D,modelParams:S,fileFields:C,jsonKeys:J,...z.result?{result:z.result}:{}}}async fillPath(Z,$){let{input:G,req:H}=$,W=Z.descriptor.url;for(let z of Z.params){let Y=Z.paramBinders.get(z.name),V=Z.modelParams.get(z.name),K;if(Y||V){if(K=V?await this.bind(Z,`the param "${z.name}"`,()=>V.param.bind(G[V.key],H,$),{refusals:!0}):await this.bind(Z,`the param "${z.name}"`,()=>Y(H,$)),K===void 0||K===null||K==="")throw console.error(`[gemi/mcp] The ${V?"resolver":"binder"} for "${z.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(K)}.`),new Q(`"${Z.descriptor.name}" failed on the server.`,500)}else K=G[z.name];let J=`:${z.name}${z.modifier}`;if(K===void 0||K===null||K===""){if(z.modifier!=="?"&&z.modifier!=="*")throw new Q(`"${z.name}" of "${Z.descriptor.name}" must not be empty.`);W=W.replace(`/${J}`,"");continue}W=W.replace(J,Y3(Z.descriptor.name,z,String(K)))}return W}async formData(Z,$,G){let{input:H,ctx:W}=G,z=Z.descriptor.name;if(!W)throw Error(`McpRegistry: "${z}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[V,K]of Object.entries($))DZ(Y,V,K);for(let V of Z.fileFields){let K=V.binder==="input"?H[V.name]:await this.bind(Z,`the file "${V.name}"`,()=>V.binder(W,G));if(typeof K!=="string"||K==="")throw new Q(`"${z}" needs a file for "${V.name}", and this turn has none. Ask the user to attach one.`);Y.append(V.name,await W.attachments.file(K))}return Y}async project(Z,$,G){let{name:H,outputSchema:W}=Z.descriptor;if(G.status<200||G.status>=300)return await RZ(H,G);let z=(C,O)=>{if(O===void 0)console.error(`[gemi/mcp] "${H}" ${C}`);else console.error(`[gemi/mcp] "${H}" ${C}`,O);return new Q(`"${H}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),V=await G.text(),K=null;if(V!=="")try{K=JSON.parse(V)}catch{throw z(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let J=K;if(Z.result)try{J=await Z.result(K,$)}catch(C){throw z("failed in its result projection:",C)}if(W){let C=W.safeParse(J);if(C.ok===!1)throw z(`answered what its output schema refuses: ${C.errors.join(", ")}`);J=C.value}if(J===void 0)return null;let B=JSON.stringify(J);if(B!==void 0&&B.length>E)return`${B.slice(0,E)}\u2026 [cut at ${E} of ${B.length} characters]`;return J}async bind(Z,$,G,H={}){try{return await G()}catch(W){if(H.refusals&&W instanceof a)throw W;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,W),new Q(`"${Z.descriptor.name}" failed on the server.`,500)}}}function SZ(Z){if(Z?.kind!=="local")throw Error("McpRegistry: only local callers are implemented. A remote caller needs a bearer-token resolver, which v1 does not have \u2014 and until it does there is no remote surface to call from.")}function TZ(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 H=G.input;if(typeof H?.safeParse!=="function"||typeof H.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.`)}function K3(Z){switch(Z){case"GET":return Object.freeze({readOnlyHint:!0});case"DELETE":return Object.freeze({destructiveHint:!0});case"PUT":return Object.freeze({idempotentHint:!0});default:return Object.freeze({})}}function X3(Z,$,G){let H=G.toJSONSchema(),W={...$??{},type:"object",properties:{...$?.properties??{},...H.properties},required:[...$?.required??[],...H.required??[]],additionalProperties:!1},z=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["expected an object"]};let V=[],K={};if(Z){let B=Z.safeParse(Y);if(B.ok===!1)V.push(...B.errors);else K={...B.value}}let J=G.safeParse(Y);if(J.ok===!1)V.push(...J.errors);else K={...K,...J.value};return V.length>0?{ok:!1,errors:V}:{ok:!0,value:K}};return{toJSONSchema:()=>W,safeParse:z,parse(Y){let V=z(Y);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function Y3(Z,$,G){let H=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(H.some((W)=>W==="."||W===".."))throw new Q(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return H.map(encodeURIComponent).join("/")}function DZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let H of G)DZ(Z,$,H);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function I3(Z){let $=new URLSearchParams,G=(H,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let z of W)G(H,z);return}$.append(H,typeof W==="object"?JSON.stringify(W):String(W))};for(let[H,W]of Object.entries(Z))G(H,W);return $.toString()}async function RZ(Z,$){if($.status>=200&&$.status<300){let H=$.headers.get("Content-Type");if(H&&!z3.test(H)){let z=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${z} bytes of ${H}, which is not shown.`}let W=await $.text();if(W==="")return null;if(W.length>E)return`${W.slice(0,E)}\u2026 [cut at ${E} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let G=await $.text();if($.status>=400&&$.status<500){let H=G.length>LZ?`${G.slice(0,LZ)}\u2026`:G;throw new Q(`"${Z}" was refused with ${$.status}${H?`: ${H}`:"."}`,$.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 Q(`"${Z}" failed on the server.`,$.status)}function h(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 J3 extends I{register(){this.app.singleton(R,()=>new R(h(this.app.config,"route.api"))),this.app.singleton(M,()=>new M(h(this.app.config,"route.view"))),this.app.singleton(c,()=>new c({api:this.app.make(R),view:this.app.make(M)},{api:h(this.app.config,"route.api"),view:h(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(k,()=>{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 k(new Z.router,this.app.make(R))})}boot(){if(this.app.make(R),this.app.make(M),this.app.make(c),this.app.config.get("route.mcp"))this.app.make(k)}}
3
3
  export{P as $a,bZ as ab,L3 as bb,hZ as cb,pZ as db,T as eb,c3 as fb,BZ as gb,dZ as hb,lZ as ib,L as jb,tZ as kb,oZ as lb,rZ as mb,aZ as nb,E4 as ob,FZ as pb,eZ as qb,Z3 as rb,h4 as sb,xZ as tb,$3 as ub,s4 as vb,PZ as wb,G3 as xb,Q as yb,k as zb,J3 as Ab};
4
4
 
5
- //# debugId=260EA1B2BA70C67264756E2164756E21
5
+ //# debugId=1AB60F6D824394D164756E2164756E21
@@ -27,6 +27,6 @@
27
27
  "import { ServiceProvider } from \"../../support/ServiceProvider\";\nimport { McpRegistry } from \"../mcp/McpRegistry\";\nimport { ApiRouteDispatcher } from \"./ApiRouteDispatcher\";\nimport { DomainRouter } from \"./DomainRouter\";\nimport { ViewRouteDispatcher } from \"./ViewRouteDispatcher\";\nimport type { ApiRouteConfig, DomainsConfig, McpRouteConfig, ViewRouteConfig } from \"./config\";\nimport type { Repository } from \"../../support/Repository\";\n\nfunction readConfig<T>(config: Repository, key: string): T {\n const slice = config.get<T>(key);\n if (!slice) {\n throw new Error(\n `Missing \"${key}\" configuration. Route dispatching needs a root router — declare it in \"app/config/route.ts\".`,\n );\n }\n return slice;\n}\n\n/**\n * Owns both route dispatchers. Laravel ships a single RouteServiceProvider for\n * every route file it loads; the api/view split is a config slice, not a\n * separate provider.\n */\nexport class RouteServiceProvider extends ServiceProvider {\n register() {\n this.app.singleton(\n ApiRouteDispatcher,\n () =>\n new ApiRouteDispatcher(\n readConfig<ApiRouteConfig>(this.app.config, \"route.api\"),\n ),\n );\n\n this.app.singleton(\n ViewRouteDispatcher,\n () =>\n new ViewRouteDispatcher(\n readConfig<ViewRouteConfig>(this.app.config, \"route.view\"),\n ),\n );\n\n // The root pair above is the root group's; the other `route.domains`\n // groups get their own only when they bring their own routers.\n this.app.singleton(\n DomainRouter,\n () =>\n new DomainRouter(\n { api: this.app.make(ApiRouteDispatcher), view: this.app.make(ViewRouteDispatcher) },\n {\n api: readConfig<ApiRouteConfig>(this.app.config, \"route.api\"),\n view: readConfig<ViewRouteConfig>(this.app.config, \"route.view\"),\n domains: this.app.config.get<DomainsConfig | undefined>(\"route.domains\"),\n },\n ),\n );\n\n // Bound whether or not the app declares one, so asking for it without\n // `route.mcp` fails with a sentence rather than an unbound token.\n this.app.singleton(McpRegistry, () => {\n const config = this.app.config.get<McpRouteConfig | undefined>(\"route.mcp\");\n if (!config?.router) {\n throw new Error(\n 'No MCP router is configured. Declare one as `mcp: { router }` in \"app/config/route.ts\".',\n );\n }\n return new McpRegistry(new config.router(), this.app.make(ApiRouteDispatcher));\n });\n }\n\n /**\n * The dispatchers of every host group, and the MCP registry when an app declares one, must\n * not be built lazily: constructing the dispatchers flattens the route\n * tables and runs `assertNoReservedRoutePaths`, and constructing the registry\n * resolves every tool against those tables. A missing `route` config, a\n * route under a reserved prefix or a tool naming a route that is gone has to\n * fail the boot rather than the first request, or the first tool call, that\n * happens to hit it.\n */\n boot() {\n this.app.make(ApiRouteDispatcher);\n this.app.make(ViewRouteDispatcher);\n // Builds every host group's disp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AAI,UACP,EACA,IACE,IAAI,EACF,CAAE,IAAK,KAAK,IAAI,KAAK,CAAkB,EAAG,KAAM,KAAK,IAAI,KAAK,CAAmB,CAAE,EACnF,CACE,IAAK,EAA2B,KAAK,IAAI,OAAQ,WAAW,EAC5D,KAAM,EAA4B,KAAK,IAAI,OAAQ,YAAY,EAC/D,QAAS,KAAK,IAAI,OAAO,IAA+B,eAAe,CACzE,CACF,CACJ,EAIA,KAAK,IAAI,UAAU,EAAa,IAAM,CACpC,IAAM,EAAS,KAAK,IAAI,OAAO,IAAgC,WAAW,EAC1E,GAAI,CAAC,GAAQ,OACX,MAAU,MACR,yFACF,EAEF,OAAO,IAAI,EAAY,IAAI,EAAO,OAAU,KAAK,IAAI,KAAK,CAAkB,CAAC,EAC9E,EAYH,IAAI,EAAG,CAKL,GAJA,KAAK,IAAI,KAAK,CAAkB,EAChC,KAAK,IAAI,KAAK,CAAmB,EAEjC,KAAK,IAAI,KAAK,CAAY,EACtB,KAAK,IAAI,OAAO,IAAI,WAAW,EACjC,KAAK,IAAI,KAAK,CAAW,EAG/B",
30
- "debugId": "260EA1B2BA70C67264756E2164756E21",
30
+ "debugId": "1AB60F6D824394D164756E2164756E21",
31
31
  "names": []
32
32
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  var b="UTC";function W(j){if(typeof j!=="string"||j.length===0)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:j}),!0}catch{return!1}}var S=new Map,H=500;function U(j,B){let N=S.get(j);if(N===void 0){if(S.size>=H)S.delete(S.keys().next().value);N=B(),S.set(j,N)}return N}function Y(j){return j instanceof Date?j:new Date(j)}function M(j){return j.dateStyle!==void 0||j.timeStyle!==void 0||j.weekday!==void 0||j.era!==void 0||j.year!==void 0||j.month!==void 0||j.day!==void 0||j.dayPeriod!==void 0||j.hour!==void 0||j.minute!==void 0||j.second!==void 0||j.fractionalSecondDigits!==void 0||j.timeZoneName!==void 0}function $(j){let{locale:B,timeZone:N}=j,Q=(J={})=>{let K={...J,timeZone:J.timeZone??N};return U(`dt|${B}|${JSON.stringify(K)}`,()=>{return new Intl.DateTimeFormat(B,K)})},P=(J,K)=>{if(J&&M(J))return J;return{...K,...J}};return{locale:B,timeZone:N,date(J,K){return Q(P(K,{dateStyle:"medium"})).format(Y(J))},time(J,K){return Q(P(K,{timeStyle:"short"})).format(Y(J))},dateTime(J,K){return Q(P(K,{dateStyle:"medium",timeStyle:"short"})).format(Y(J))},number(J,K={}){return U(`n|${B}|${JSON.stringify(K)}`,()=>new Intl.NumberFormat(B,K)).format(J)},relative(J,K,R={}){return U(`r|${B}|${JSON.stringify(R)}`,()=>new Intl.RelativeTimeFormat(B,R)).format(J,K)},list(J,K={}){return U(`l|${B}|${JSON.stringify(K)}`,()=>new Intl.ListFormat(B,K)).format(J)},plural(J,K={}){return U(`p|${B}|${JSON.stringify(K)}`,()=>new Intl.PluralRules(B,K)).select(J)},dateTimeFormat:Q}}var x=/^[a-z]{2,3}(?:[-_][a-z0-9]{2,8})*$/i;function I(j){return x.test(j)}function z(j){return j.split(/[-_]/)[0].toLowerCase()}function G(j,B,N){let Q=j?.split(";")[0].trim();if(!Q||!I(Q))return null;let P=Q.replaceAll("_","-").toLowerCase(),J=B.find((X)=>X.toLowerCase()===P);if(J)return J;let K=z(Q),R=B.filter((X)=>z(X)===K);if(R.length===0)return null;if(N&&R.includes(N))return N;return R[0]}class _{config;static token="translator";translations={};isEnabled=!1;constructor(j){this.config=j;if(!W(this.config.timeZone))throw Error(`translation.timeZone: "${String(this.config.timeZone)}" is not a time zone this runtime knows. Use an IANA name such as "UTC" or "Europe/Istanbul".`);let B={};for(let[N,Q]of Object.entries(this.config.prefetch))for(let P of this.config.supportedLocales){if(!B[P])B[P]={};B[P][N]={};for(let J of Q){B[P][N][J.name]={};for(let[K,R]of Object.entries(J.dictionary))this.isEnabled=!0,B[P][N][J.name][K]=R[P]}}this.translations=B}get isLocaleAware(){return this.isEnabled||this.config.supportedLocales.length>0}get supportedLocales(){return this.config.supportedLocales}get defaultLocale(){return this.config.defaultLocale}get components(){return this.config.components}get timeZone(){return this.config.timeZone}detectTimeZone(j){if(j){let B=this.config.detectTimeZone(j);if(W(B))return B}return this.config.timeZone}formatter(j,B){return $({locale:j||this.defaultLocale,timeZone:W(B)?B:this.timeZone})}onLocaleChange(j){return this.config.onLocaleChange(j)}detectLocale(j){let B=this.config.defaultLocale??this.config.supportedLocales[0]??"en-US",N=(K)=>G(K,this.config.supportedLocales,this.config.defaultLocale),Q=N(this.config.detectLocale(j));if(Q)return Q;let P=N(j.cookies.get("i18n-locale"));if(P)return P;let J=j.headers.get("accept-language")??"";for(let K of J.split(",")){let R=N(K);if(R)return R}return B}getPageTranslations(j,B){if(this.translations[j][B])return this.translations[j][B];return{}}}
3
- export{G as Vg,b as Wg,W as Xg,$ as Yg,_ as Zg};
3
+ export{G as Wg,b as Xg,W as Yg,$ as Zg,_ as _g};
4
4
 
5
- //# debugId=CA5044CF1067F83464756E2164756E21
5
+ //# debugId=C78FAC5A3C4B101F64756E2164756E21
@@ -7,6 +7,6 @@
7
7
  "import type { HttpRequest } from \"../http/HttpRequest\";\nimport type { Dictionary } from \"./Dictionary\";\nimport type { TranslationConfig } from \"./config\";\nimport { resolveLocale } from \"./resolveLocale\";\nimport {\n createFormatter,\n isValidTimeZone,\n type Formatter,\n} from \"./formatter\";\n\nexport class Translator {\n static token = \"translator\";\n\n translations = {};\n isEnabled = false;\n\n constructor(public config: Required<TranslationConfig>) {\n // Fail at boot rather than on the first page that prints a date: `Intl`\n // throws a `RangeError` for a zone it does not know.\n if (!isValidTimeZone(this.config.timeZone)) {\n throw new Error(\n `translation.timeZone: \"${String(this.config.timeZone)}\" is not a time zone this runtime knows. Use an IANA name such as \"UTC\" or \"Europe/Istanbul\".`,\n );\n }\n\n const translations = {};\n\n for (const [route, dicArray] of Object.entries(this.config.prefetch)) {\n for (const locale of this.config.supportedLocales) {\n if (!translations[locale]) {\n translations[locale] = {};\n }\n translations[locale][route] = {};\n for (const dic of dicArray) {\n translations[locale][route][dic.name] = {};\n for (const [key, value] of Object.entries(dic.dictionary)) {\n this.isEnabled = true;\n translations[locale][route][dic.name][key] = value[locale];\n }\n }\n }\n }\n this.translations = translations;\n }\n\n /**\n * Whether the app does locale-aware routing and rendering at all.\n *\n * `isEnabled` only means the legacy `prefetch` config has dictionaries to\n * serve. An app on `defineDictionary` has an empty `prefetch` and declares\n * its locales through `supportedLocales` alone, so gating on `isEnabled`\n * leaves it without locale detection or a locale URL prefix. Both the render\n * path and the redirect read this, because when they disagreed a migrated app\n * rendered a non-default locale at `/` with no redirect and no `Vary` — one\n * cache fill away from serving that document to everyone.\n */\n get isLocaleAware(): boolean {\n return this.isEnabled || this.config.supportedLocales.length > 0;\n }\n\n get supportedLocales(): string[] {\n return this.config.supportedLocales;\n }\n\n get defaultLocale(): string {\n return this.config.defaultLocale;\n }\n\n get components(): Record<string, Dictionary<any>> {\n return this.config.components;\n }\n\n /** The configured zone; `UTC` unless `translation.timeZone` says otherwise. */\n get timeZone(): string {\n return this.config.timeZone;\n }\n\n /**\n * The zone dates are formatted in for this request: `detectTimeZone`'s\n * answer when it gives a zone `Intl` knows, the configured zone otherwise.\n * A bad value from a cookie must not take the page down, so it is ignored\n * rather than thrown.\n */\n detectTimeZone(req: HttpRequest<any, any> | null | undefined): string {\n if (req) {\n const detected = this.config.detectTimeZone(req);\n if (isValidTimeZone(detected)) {\n return detected;\n }\n }\n return this.config.timeZone;\n }\n\n /**\n * A formatter for `locale` (the default locale when omitted) in `timeZone`\n * (the configured zone when omitted). For server code outside a request —\n * jobs, emails. Inside a request, `Lang.formatter()` picks up the request's\n * locale and zone.\n */\n formatter(locale?: string, timeZone?: string): Formatter {\n return createFormatter({\n locale: locale || this.defaultLocale,\n timeZone: isValidTimeZone(timeZone) ? timeZone : this.timeZone,\n });\n }\n\n onLocaleChange(locale: string): Promise<void> | void {\n return this.config.onLocaleChange(locale);\n }\n\n detectLocale(req: HttpRequest<any, any>) {\n const fallbackLocale =\n this.config.defaultLocale ?? this.config.supportedLocales[0] ?? \"en-US\";\n const resolve = (tag: string | null | undefined) =>\n resolveLocale(tag, this.config.supportedLocales, this.config.defaultLocale);\n\n const detectedLocale = resolve(this.config.detectLocale(req));\n if (detectedLocale) {\n return detectedLocale;\n }\n\n const previousLocale = resolve(req.cookies.get(\"i18n-locale\"));\n if (previousLocale) {\n return previousLocale;\n }\n\n // Entries are in the browser's preference order; the first one the app can\n // serve, even by language alone (`de-AT` → `de-DE`), wins.\n const acceptLanguage = req.headers.get(\"accept-language\") ?? \"\";\n for (const entry of acceptLanguage.split(\",\")) {\n const locale = resolve(entry);\n if (locale) {\n return locale;\n }\n }\n\n return fallbackLocale;\n }\n\n getPageTranslations(locale: string, scope: string) {\n if (this.translations[locale][scope]) {\n return this.translations[locale][scope];\n }\n return {};\n }\n}\n"
8
8
  ],
9
9
  "mappings": ";AAmDO,IAAM,EAAoB,MAO1B,SAAS,CAAe,CAAC,EAAuC,CACrE,GAAI,OAAO,IAAa,UAAY,EAAS,SAAW,EACtD,MAAO,GAET,GAAI,CAEF,OADA,IAAI,KAAK,eAAe,QAAS,CAAE,UAAS,CAAC,EACtC,GACP,KAAM,CACN,MAAO,IAQX,IAAM,EAAQ,IAAI,IACZ,EAAc,IAEpB,SAAS,CAAS,CAAC,EAAa,EAAoB,CAClD,IAAI,EAAQ,EAAM,IAAI,CAAG,EACzB,GAAI,IAAU,OAAW,CACvB,GAAI,EAAM,MAAQ,EAGhB,EAAM,OAAO,EAAM,KAAK,EAAE,KAAK,EAAE,KAAM,EAEzC,EAAQ,EAAO,EACf,EAAM,IAAI,EAAK,CAAK,EAEtB,OAAO,EAGT,SAAS,CAAM,CAAC,EAAwB,CACtC,OAAO,aAAiB,KAAO,EAAQ,IAAI,KAAK,CAAK,EAGvD,SAAS,CAAiB,CAAC,EAA8C,CACvE,OACE,EAAQ,YAAc,QACtB,EAAQ,YAAc,QACtB,EAAQ,UAAY,QACpB,EAAQ,MAAQ,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,EACF,OAAO,EAGT,IAAM,EAAiB,EAAQ,EAAI,QAAQ,IAAI,aAAa,CAAC,EAC7D,GAAI,EACF,OAAO,EAKT,IAAM,EAAiB,EAAI,QAAQ,IAAI,iBAAiB,GAAK,GAC7D,QAAW,KAAS,EAAe,MAAM,GAAG,EAAG,CAC7C,IAAM,EAAS,EAAQ,CAAK,EAC5B,GAAI,EACF,OAAO,EAIX,OAAO,EAGT,mBAAmB,CAAC,EAAgB,EAAe,CACjD,GAAI,KAAK,aAAa,GAAQ,GAC5B,OAAO,KAAK,aAAa,GAAQ,GAEnC,MAAO,CAAC,EAEZ",
10
- "debugId": "CA5044CF1067F83464756E2164756E21",
10
+ "debugId": "C78FAC5A3C4B101F64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{rh as h}from"./chunk-3s3awh38.js";var A=h((f)=>{f.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpAuthLocation||(f.HttpAuthLocation={}));f.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpApiKeyAuthLocation||(f.HttpApiKeyAuthLocation={}));f.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})(f.EndpointURLScheme||(f.EndpointURLScheme={}));f.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(f.AlgorithmId||(f.AlgorithmId={}));var x=(t)=>{let o=[];if(t.sha256!==void 0)o.push({algorithmId:()=>f.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)o.push({algorithmId:()=>f.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){o.push(s)},checksumAlgorithms(){return o}}},d=(t)=>{let o={};return t.checksumAlgorithms().forEach((s)=>{o[s.algorithmId()]=s.checksumConstructor()}),o},a=(t)=>{return x(t)},E=(t)=>{return d(t)};f.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(f.FieldPosition||(f.FieldPosition={}));var m="__smithy_context";f.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(f.IniSectionType||(f.IniSectionType={}));f.RequestHandlerProtocol=void 0;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(f.RequestHandlerProtocol||(f.RequestHandlerProtocol={}));f.SMITHY_CONTEXT_KEY=m;f.getDefaultClientConfiguration=a;f.resolveDefaultRuntimeConfig=E});
2
+ import{sh as h}from"./chunk-wvwee7dn.js";var A=h((f)=>{f.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpAuthLocation||(f.HttpAuthLocation={}));f.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpApiKeyAuthLocation||(f.HttpApiKeyAuthLocation={}));f.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})(f.EndpointURLScheme||(f.EndpointURLScheme={}));f.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(f.AlgorithmId||(f.AlgorithmId={}));var x=(t)=>{let o=[];if(t.sha256!==void 0)o.push({algorithmId:()=>f.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)o.push({algorithmId:()=>f.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){o.push(s)},checksumAlgorithms(){return o}}},d=(t)=>{let o={};return t.checksumAlgorithms().forEach((s)=>{o[s.algorithmId()]=s.checksumConstructor()}),o},a=(t)=>{return x(t)},E=(t)=>{return d(t)};f.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(f.FieldPosition||(f.FieldPosition={}));var m="__smithy_context";f.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(f.IniSectionType||(f.IniSectionType={}));f.RequestHandlerProtocol=void 0;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(f.RequestHandlerProtocol||(f.RequestHandlerProtocol={}));f.SMITHY_CONTEXT_KEY=m;f.getDefaultClientConfiguration=a;f.resolveDefaultRuntimeConfig=E});
3
3
  export{A as _};
4
4
 
5
- //# debugId=B11D43A53BBA0C3764756E2164756E21
5
+ //# debugId=46313E534C295D3E64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "'use strict';\n\nexports.HttpAuthLocation = void 0;\n(function (HttpAuthLocation) {\n HttpAuthLocation[\"HEADER\"] = \"header\";\n HttpAuthLocation[\"QUERY\"] = \"query\";\n})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));\n\nexports.HttpApiKeyAuthLocation = void 0;\n(function (HttpApiKeyAuthLocation) {\n HttpApiKeyAuthLocation[\"HEADER\"] = \"header\";\n HttpApiKeyAuthLocation[\"QUERY\"] = \"query\";\n})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));\n\nexports.EndpointURLScheme = void 0;\n(function (EndpointURLScheme) {\n EndpointURLScheme[\"HTTP\"] = \"http\";\n EndpointURLScheme[\"HTTPS\"] = \"https\";\n})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));\n\nexports.AlgorithmId = void 0;\n(function (AlgorithmId) {\n AlgorithmId[\"MD5\"] = \"md5\";\n AlgorithmId[\"CRC32\"] = \"crc32\";\n AlgorithmId[\"CRC32C\"] = \"crc32c\";\n AlgorithmId[\"SHA1\"] = \"sha1\";\n AlgorithmId[\"SHA256\"] = \"sha256\";\n})(exports.AlgorithmId || (exports.AlgorithmId = {}));\nconst getChecksumConfiguration = (runtimeConfig) => {\n const checksumAlgorithms = [];\n if (runtimeConfig.sha256 !== undefined) {\n checksumAlgorithms.push({\n algorithmId: () => exports.AlgorithmId.SHA256,\n checksumConstructor: () => runtimeConfig.sha256,\n });\n }\n if (runtimeConfig.md5 != undefined) {\n checksumAlgorithms.push({\n algorithmId: () => exports.AlgorithmId.MD5,\n checksumConstructor: () => runtimeConfig.md5,\n });\n }\n return {\n addChecksumAlgorithm(algo) {\n checksumAlgorithms.push(algo);\n },\n checksumAlgorithms() {\n return checksumAlgorithms;\n },\n };\n};\nconst resolveChecksumRuntimeConfig = (clientConfig) => {\n const runtimeConfig = {};\n clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {\n runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();\n });\n return runtimeConfig;\n};\n\nconst getDefaultClientConfiguration = (runtimeConfig) => {\n return getChecksumConfiguration(runtimeConfig);\n};\nconst resolveDefaultRuntimeConfig = (config) => {\n return resolveChecksumRuntimeConfig(config);\n};\n\nexports.FieldPosition = void 0;\n(function (FieldPosition) {\n FieldPosition[FieldPosition[\"HEADER\"] = 0] = \"HEADER\";\n FieldPosition[FieldPosition[\"TRAILER\"] = 1] = \"TRAILER\";\n})(exports.FieldPosition || (exports.FieldPosition = {}));\n\nconst SMITHY_CONTEXT_KEY = \"__smithy_context\";\n\nexports.IniSectionType = void 0;\n(function (IniSectionType) {\n IniSectionType[\"PROFILE\"] = \"profile\";\n IniSectionType[\"SSO_SESSION\"] = \"sso-session\";\n IniSectionType[\"SERVICES\"] = \"services\";\n})(exports.IniSectionType || (exports.IniSectionType = {}));\n\nexports.RequestHandlerProtocol = void 0;\n(function (RequestHandlerProtocol) {\n RequestHandlerProtocol[\"HTTP_0_9\"] = \"http/0.9\";\n RequestHandlerProtocol[\"HTTP_1_0\"] = \"http/1.0\";\n RequestHandlerProtocol[\"TDS_8_0\"] = \"tds/8.0\";\n})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));\n\nexports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY;\nexports.getDefaultClientConfiguration = getDefaultClientConfiguration;\nexports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;\n"
6
6
  ],
7
7
  "mappings": ";uDAEQ,mBAAwB,QAC/B,QAAS,CAAC,EAAkB,CACzB,EAAiB,OAAY,SAC7B,EAAiB,MAAW,UACrB,qBAA6B,mBAAmB,CAAC,EAAE,EAEtD,yBAA8B,QACrC,QAAS,CAAC,EAAwB,CAC/B,EAAuB,OAAY,SACnC,EAAuB,MAAW,UAC3B,2BAAmC,yBAAyB,CAAC,EAAE,EAElE,oBAAyB,QAChC,QAAS,CAAC,EAAmB,CAC1B,EAAkB,KAAU,OAC5B,EAAkB,MAAW,UACtB,sBAA8B,oBAAoB,CAAC,EAAE,EAExD,cAAmB,QAC1B,QAAS,CAAC,EAAa,CACpB,EAAY,IAAS,MACrB,EAAY,MAAW,QACvB,EAAY,OAAY,SACxB,EAAY,KAAU,OACtB,EAAY,OAAY,WACjB,gBAAwB,cAAc,CAAC,EAAE,EACpD,IAAM,EAA2B,CAAC,IAAkB,CAChD,IAAM,EAAqB,CAAC,EAC5B,GAAI,EAAc,SAAW,OACzB,EAAmB,KAAK,CACpB,YAAa,IAAc,cAAY,OACvC,oBAAqB,IAAM,EAAc,MAC7C,CAAC,EAEL,GAAI,EAAc,KAAO,KACrB,EAAmB,KAAK,CACpB,YAAa,IAAc,cAAY,IACvC,oBAAqB,IAAM,EAAc,GAC7C,CAAC,EAEL,MAAO,CACH,oBAAoB,CAAC,EAAM,CACvB,EAAmB,KAAK,CAAI,GAEhC,kBAAkB,EAAG,CACjB,OAAO,EAEf,GAEE,EAA+B,CAAC,IAAiB,CACnD,IAAM,EAAgB,CAAC,EAIvB,OAHA,EAAa,mBAAmB,EAAE,QAAQ,CAAC,IAAsB,CAC7D,EAAc,EAAkB,YAAY,GAAK,EAAkB,oBAAoB,EAC1F,EACM,GAGL,EAAgC,CAAC,IAAkB,CACrD,OAAO,EAAyB,CAAa,GAE3C,EAA8B,CAAC,IAAW,CAC5C,OAAO,EAA6B,CAAM,GAGtC,gBAAqB,QAC5B,QAAS,CAAC,EAAe,CACtB,EAAc,EAAc,OAAY,GAAK,SAC7C,EAAc,EAAc,QAAa,GAAK,YACvC,kBAA0B,gBAAgB,CAAC,EAAE,EAExD,IAAM,EAAqB,mBAEnB,iBAAsB,QAC7B,QAAS,CAAC,EAAgB,CACvB,EAAe,QAAa,UAC5B,EAAe,YAAiB,cAChC,EAAe,SAAc,aACtB,mBAA2B,iBAAiB,CAAC,EAAE,EAElD,yBAA8B,QACrC,QAAS,CAAC,EAAwB,CAC/B,EAAuB,SAAc,WACrC,EAAuB,SAAc,WACrC,EAAuB,QAAa,YAC7B,2BAAmC,yBAAyB,CAAC,EAAE,EAElE,qBAAqB,EACrB,gCAAgC,EAChC,8BAA8B",
8
- "debugId": "B11D43A53BBA0C3764756E2164756E21",
8
+ "debugId": "46313E534C295D3E64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{hc as G}from"./chunk-9hbwvcxn.js";import{af as F}from"./chunk-1npdp1w2.js";import{$f as E}from"./chunk-5wt25tyd.js";import{Eg as x,rg as B}from"./chunk-4rr9wmh8.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.
2
+ import{hc as G}from"./chunk-9hbwvcxn.js";import{bf as F}from"./chunk-dpy08xw4.js";import{ag as E}from"./chunk-9m18pknp.js";import{Fg as x,sg as B}from"./chunk-vsnmdtrs.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 Aa};
5
5
 
6
- //# debugId=5C767FE5F61C583664756E2164756E21
6
+ //# debugId=ED37821385015D0C64756E2164756E21