@geekmidas/cli 10.0.0-alpha.98 → 10.0.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 (684) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/FUNCTION_CRON_SUPPORT.md +266 -0
  3. package/README.md +533 -382
  4. package/bin/gkm.mjs +2 -16
  5. package/dist/CachedStateProvider-BdX7klRc.cjs +3 -0
  6. package/dist/CachedStateProvider-CzyFct42.mjs +54 -0
  7. package/dist/CachedStateProvider-CzyFct42.mjs.map +1 -0
  8. package/dist/CachedStateProvider-GcGziXh1.mjs +3 -0
  9. package/dist/CachedStateProvider-klLWZXWF.cjs +60 -0
  10. package/dist/CachedStateProvider-klLWZXWF.cjs.map +1 -0
  11. package/dist/{HostingerProvider-BNpS9aRJ.mjs → HostingerProvider-B2ZYz7Yc.mjs} +26 -31
  12. package/dist/HostingerProvider-B2ZYz7Yc.mjs.map +1 -0
  13. package/dist/{HostingerProvider-DR1iws1P.cjs → HostingerProvider-CrHfsgz9.cjs} +26 -31
  14. package/dist/HostingerProvider-CrHfsgz9.cjs.map +1 -0
  15. package/dist/LocalStateProvider-CP49rjzt.mjs +42 -0
  16. package/dist/LocalStateProvider-CP49rjzt.mjs.map +1 -0
  17. package/dist/LocalStateProvider-CalzNfNA.cjs +43 -0
  18. package/dist/LocalStateProvider-CalzNfNA.cjs.map +1 -0
  19. package/dist/{Route53Provider-Bllus2NR.cjs → Route53Provider-DwgXiLxt.cjs} +22 -21
  20. package/dist/Route53Provider-DwgXiLxt.cjs.map +1 -0
  21. package/dist/{Route53Provider-QXxjkZO1.mjs → Route53Provider-tlgBzrRQ.mjs} +13 -13
  22. package/dist/Route53Provider-tlgBzrRQ.mjs.map +1 -0
  23. package/dist/SSMStateProvider-BlrTiV5m.mjs +66 -0
  24. package/dist/SSMStateProvider-BlrTiV5m.mjs.map +1 -0
  25. package/dist/SSMStateProvider-Bt6r8CTL.cjs +66 -0
  26. package/dist/SSMStateProvider-Bt6r8CTL.cjs.map +1 -0
  27. package/dist/{backup-provisioner-oDEsPj02.cjs → backup-provisioner-B3HBN-2k.cjs} +20 -22
  28. package/dist/backup-provisioner-B3HBN-2k.cjs.map +1 -0
  29. package/dist/{backup-provisioner-C8DnCmxK.mjs → backup-provisioner-Xunq-p_8.mjs} +9 -12
  30. package/dist/backup-provisioner-Xunq-p_8.mjs.map +1 -0
  31. package/dist/bundler-DkA4qzUD.mjs +135 -0
  32. package/dist/bundler-DkA4qzUD.mjs.map +1 -0
  33. package/dist/bundler-Dufq3uvI.cjs +136 -0
  34. package/dist/bundler-Dufq3uvI.cjs.map +1 -0
  35. package/dist/{rolldown-runtime-C0BPl7ul.cjs → chunk-CUT6urMc.cjs} +10 -23
  36. package/dist/chunk-Duj1WY3L.mjs +7 -0
  37. package/dist/config-Bbu1JKvf.mjs +211 -0
  38. package/dist/config-Bbu1JKvf.mjs.map +1 -0
  39. package/dist/config-DujV8DbR.cjs +253 -0
  40. package/dist/config-DujV8DbR.cjs.map +1 -0
  41. package/dist/config.cjs +10 -421
  42. package/dist/config.d.cts +120 -4
  43. package/dist/config.d.cts.map +1 -0
  44. package/dist/config.d.mts +120 -4
  45. package/dist/config.d.mts.map +1 -0
  46. package/dist/config.mjs +3 -405
  47. package/dist/credentials-C8DWtnMY.cjs +174 -0
  48. package/dist/credentials-C8DWtnMY.cjs.map +1 -0
  49. package/dist/credentials-s1kLcIzK.mjs +126 -0
  50. package/dist/credentials-s1kLcIzK.mjs.map +1 -0
  51. package/dist/deploy/sniffer-envkit-patch.cjs +10 -18
  52. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  53. package/dist/deploy/sniffer-envkit-patch.d.cts +2 -0
  54. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  55. package/dist/deploy/sniffer-envkit-patch.d.mts +2 -0
  56. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  57. package/dist/deploy/sniffer-envkit-patch.mjs +2 -10
  58. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  59. package/dist/deploy/sniffer-hooks.cjs +7 -13
  60. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  61. package/dist/deploy/sniffer-hooks.d.cts +2 -1
  62. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  63. package/dist/deploy/sniffer-hooks.d.mts +2 -1
  64. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  65. package/dist/deploy/sniffer-hooks.mjs +3 -10
  66. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  67. package/dist/deploy/sniffer-loader.cjs +7 -16
  68. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  69. package/dist/deploy/sniffer-loader.d.cts +1 -1
  70. package/dist/deploy/sniffer-loader.d.mts +1 -1
  71. package/dist/deploy/sniffer-loader.mjs +3 -14
  72. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  73. package/dist/deploy/sniffer-routes-worker.cjs +13 -17
  74. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  75. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  76. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  77. package/dist/deploy/sniffer-routes-worker.mjs +6 -10
  78. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  79. package/dist/deploy/sniffer-worker.cjs +6 -15
  80. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  81. package/dist/deploy/sniffer-worker.d.cts +3 -1
  82. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  83. package/dist/deploy/sniffer-worker.d.mts +3 -1
  84. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  85. package/dist/deploy/sniffer-worker.mjs +4 -15
  86. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  87. package/dist/dokploy-api-BPYkG-ZZ.cjs +3 -0
  88. package/dist/dokploy-api-BiSzWM4v.mjs +3 -0
  89. package/dist/dokploy-api-CqOIKHme.cjs +609 -0
  90. package/dist/dokploy-api-CqOIKHme.cjs.map +1 -0
  91. package/dist/dokploy-api-sfZFlWuE.mjs +597 -0
  92. package/dist/dokploy-api-sfZFlWuE.mjs.map +1 -0
  93. package/dist/encryption-BVS7Vmzs.cjs +4 -0
  94. package/dist/encryption-Bd_m4q3g.mjs +3 -0
  95. package/dist/encryption-CO5Q4Bhf.mjs +42 -0
  96. package/dist/encryption-CO5Q4Bhf.mjs.map +1 -0
  97. package/dist/encryption-MfXAiFTm.cjs +54 -0
  98. package/dist/encryption-MfXAiFTm.cjs.map +1 -0
  99. package/dist/fullstack-secrets-BYzi6Hwl.cjs +402 -0
  100. package/dist/fullstack-secrets-BYzi6Hwl.cjs.map +1 -0
  101. package/dist/fullstack-secrets-l8s3II_H.mjs +336 -0
  102. package/dist/fullstack-secrets-l8s3II_H.mjs.map +1 -0
  103. package/dist/index-CoVW_fFS.d.cts +1737 -0
  104. package/dist/index-CoVW_fFS.d.cts.map +1 -0
  105. package/dist/index-oWibAYQY.d.mts +1737 -0
  106. package/dist/index-oWibAYQY.d.mts.map +1 -0
  107. package/dist/index.cjs +11337 -10263
  108. package/dist/index.cjs.map +1 -1
  109. package/dist/index.d.cts +1 -1
  110. package/dist/index.d.mts +1 -1
  111. package/dist/index.mjs +11303 -10217
  112. package/dist/index.mjs.map +1 -1
  113. package/dist/openapi-BzNOC7_i.cjs +1931 -0
  114. package/dist/openapi-BzNOC7_i.cjs.map +1 -0
  115. package/dist/openapi-Cfwi0fqF.mjs +1883 -0
  116. package/dist/openapi-Cfwi0fqF.mjs.map +1 -0
  117. package/dist/openapi-react-query-C4iIvpPf.mjs +167 -0
  118. package/dist/openapi-react-query-C4iIvpPf.mjs.map +1 -0
  119. package/dist/openapi-react-query-CYWik72n.cjs +173 -0
  120. package/dist/openapi-react-query-CYWik72n.cjs.map +1 -0
  121. package/dist/openapi-react-query.cjs +4 -0
  122. package/dist/openapi-react-query.d.cts +11 -0
  123. package/dist/openapi-react-query.d.cts.map +1 -0
  124. package/dist/openapi-react-query.d.mts +11 -0
  125. package/dist/openapi-react-query.d.mts.map +1 -0
  126. package/dist/openapi-react-query.mjs +4 -0
  127. package/dist/openapi.cjs +7 -214
  128. package/dist/openapi.d.cts +15 -72
  129. package/dist/openapi.d.cts.map +1 -1
  130. package/dist/openapi.d.mts +15 -72
  131. package/dist/openapi.d.mts.map +1 -1
  132. package/dist/openapi.mjs +4 -208
  133. package/dist/{reconcile--I7V4Klj.mjs → reconcile-B2FoJE0a.mjs} +8 -6
  134. package/dist/reconcile-B2FoJE0a.mjs.map +1 -0
  135. package/dist/{reconcile-CuCQBa5-.cjs → reconcile-BzqKJ2Rt.cjs} +8 -6
  136. package/dist/reconcile-BzqKJ2Rt.cjs.map +1 -0
  137. package/dist/setup-DDXUXzzl.mjs +765 -0
  138. package/dist/setup-DDXUXzzl.mjs.map +1 -0
  139. package/dist/setup-DLwhfyt-.cjs +8 -0
  140. package/dist/setup-Dh-B7YTX.mjs +8 -0
  141. package/dist/setup-WZ-xqAQO.cjs +849 -0
  142. package/dist/setup-WZ-xqAQO.cjs.map +1 -0
  143. package/dist/storage-B1wvztiJ.cjs +363 -0
  144. package/dist/storage-B1wvztiJ.cjs.map +1 -0
  145. package/dist/storage-Cs4WBsc4.mjs +3 -0
  146. package/dist/storage-DOEtT2Hr.cjs +7 -0
  147. package/dist/storage-dbb9RyBl.mjs +297 -0
  148. package/dist/storage-dbb9RyBl.mjs.map +1 -0
  149. package/dist/sync-B5UHXwRM.mjs +3 -0
  150. package/dist/sync-BLA94rgC.cjs +4 -0
  151. package/dist/sync-CSooqRQ8.mjs +76 -0
  152. package/dist/sync-CSooqRQ8.mjs.map +1 -0
  153. package/dist/sync-o_CtEbvR.cjs +93 -0
  154. package/dist/sync-o_CtEbvR.cjs.map +1 -0
  155. package/dist/types-B3GQUg3k.d.mts +280 -0
  156. package/dist/types-B3GQUg3k.d.mts.map +1 -0
  157. package/dist/types-BWQDiooe.d.cts +280 -0
  158. package/dist/types-BWQDiooe.d.cts.map +1 -0
  159. package/dist/workspace/index.cjs +4 -12
  160. package/dist/workspace/index.d.cts +3 -3
  161. package/dist/workspace/index.d.mts +3 -3
  162. package/dist/workspace/index.mjs +3 -2
  163. package/dist/workspace-CQTT7HJQ.cjs +4361 -0
  164. package/dist/workspace-CQTT7HJQ.cjs.map +1 -0
  165. package/dist/workspace-D-37Ylqo.mjs +4236 -0
  166. package/dist/workspace-D-37Ylqo.mjs.map +1 -0
  167. package/docs/OPENAPI_TYPESCRIPT_DESIGN.md +408 -0
  168. package/docs/dev-server-resilience-design.md +189 -0
  169. package/docs/manifest-refactor-design.md +287 -0
  170. package/examples/cron-example.ts +45 -0
  171. package/examples/env.ts +33 -0
  172. package/examples/function-example.ts +40 -0
  173. package/examples/gkm.config.json +22 -0
  174. package/examples/gkm.config.ts +14 -0
  175. package/examples/gkm.minimal.config.json +7 -0
  176. package/examples/gkm.production.config.json +27 -0
  177. package/examples/logger.ts +10 -0
  178. package/package.json +37 -87
  179. package/scripts/sync-versions.ts +108 -0
  180. package/src/__tests__/EndpointGenerator.hooks.spec.ts +204 -0
  181. package/src/__tests__/config.spec.ts +422 -0
  182. package/src/__tests__/loadEnvFiles.spec.ts +131 -0
  183. package/src/__tests__/normalizeHooksConfig.spec.ts +63 -0
  184. package/src/__tests__/openapi-react-query.spec.ts +506 -0
  185. package/src/__tests__/openapi.spec.ts +625 -0
  186. package/src/__tests__/test-helpers.ts +180 -0
  187. package/src/auth/__tests__/credentials.spec.ts +331 -0
  188. package/src/auth/__tests__/index.spec.ts +237 -0
  189. package/src/auth/credentials.ts +286 -0
  190. package/src/auth/index.ts +233 -0
  191. package/src/build/__tests__/bundler.spec.ts +446 -0
  192. package/src/build/__tests__/endpoint-analyzer.spec.ts +623 -0
  193. package/src/build/__tests__/handler-templates.spec.ts +1287 -0
  194. package/src/build/__tests__/index-new.spec.ts +550 -0
  195. package/src/build/__tests__/manifests.spec.ts +583 -0
  196. package/src/build/__tests__/partitions.spec.ts +110 -0
  197. package/src/build/__tests__/workspace-build.spec.ts +215 -0
  198. package/src/build/bundler.ts +256 -0
  199. package/src/build/endpoint-analyzer.ts +236 -0
  200. package/src/build/handler-templates.ts +1253 -0
  201. package/src/build/index.ts +616 -0
  202. package/src/build/manifests.ts +285 -0
  203. package/src/build/partitions.ts +58 -0
  204. package/src/build/providerResolver.ts +184 -0
  205. package/src/build/types.ts +104 -0
  206. package/src/config.ts +330 -0
  207. package/src/credentials/__tests__/fullDockerPorts.spec.ts +144 -0
  208. package/src/credentials/__tests__/helpers.ts +112 -0
  209. package/src/credentials/__tests__/prepareEntryCredentials.spec.ts +125 -0
  210. package/src/credentials/__tests__/readonlyDockerPorts.spec.ts +190 -0
  211. package/src/credentials/__tests__/workspaceCredentials.spec.ts +209 -0
  212. package/src/credentials/index.ts +843 -0
  213. package/src/debug.ts +68 -0
  214. package/src/deploy/CachedStateProvider.ts +86 -0
  215. package/src/deploy/LocalStateProvider.ts +57 -0
  216. package/src/deploy/SSMStateProvider.ts +117 -0
  217. package/src/deploy/StateProvider.ts +175 -0
  218. package/src/deploy/__tests__/CachedStateProvider.spec.ts +235 -0
  219. package/src/deploy/__tests__/HostingerProvider.spec.ts +347 -0
  220. package/src/deploy/__tests__/LocalStateProvider.spec.ts +130 -0
  221. package/src/deploy/__tests__/Route53Provider.spec.ts +425 -0
  222. package/src/deploy/__tests__/SSMStateProvider.spec.ts +201 -0
  223. package/src/deploy/__tests__/__fixtures__/entry-apps/async-entry.ts +24 -0
  224. package/src/deploy/__tests__/__fixtures__/entry-apps/nested-config-entry.ts +24 -0
  225. package/src/deploy/__tests__/__fixtures__/entry-apps/no-env-entry.ts +12 -0
  226. package/src/deploy/__tests__/__fixtures__/entry-apps/simple-entry.ts +14 -0
  227. package/src/deploy/__tests__/__fixtures__/entry-apps/throwing-entry.ts +16 -0
  228. package/src/deploy/__tests__/__fixtures__/env-parsers/non-function-export.ts +10 -0
  229. package/src/deploy/__tests__/__fixtures__/env-parsers/optional-env-parser.ts +21 -0
  230. package/src/deploy/__tests__/__fixtures__/env-parsers/parseable-env-parser.ts +18 -0
  231. package/src/deploy/__tests__/__fixtures__/env-parsers/throwing-env-parser.ts +16 -0
  232. package/src/deploy/__tests__/__fixtures__/env-parsers/valid-env-parser.ts +16 -0
  233. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/auth.ts +16 -0
  234. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/health.ts +13 -0
  235. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/users.ts +15 -0
  236. package/src/deploy/__tests__/__fixtures__/route-apps/services.ts +55 -0
  237. package/src/deploy/__tests__/backup-provisioner.spec.ts +428 -0
  238. package/src/deploy/__tests__/createDnsProvider.spec.ts +195 -0
  239. package/src/deploy/__tests__/createStateProvider.spec.ts +126 -0
  240. package/src/deploy/__tests__/dns-orchestration.spec.ts +192 -0
  241. package/src/deploy/__tests__/dns-verification.spec.ts +229 -0
  242. package/src/deploy/__tests__/docker.spec.ts +149 -0
  243. package/src/deploy/__tests__/dokploy-api.spec.ts +697 -0
  244. package/src/deploy/__tests__/dokploy.spec.ts +435 -0
  245. package/src/deploy/__tests__/domain.spec.ts +235 -0
  246. package/src/deploy/__tests__/env-resolver.spec.ts +903 -0
  247. package/src/deploy/__tests__/index.spec.ts +1091 -0
  248. package/src/deploy/__tests__/init.spec.ts +793 -0
  249. package/src/deploy/__tests__/secrets.spec.ts +303 -0
  250. package/src/deploy/__tests__/sniffer.spec.ts +838 -0
  251. package/src/deploy/__tests__/state-e2e.spec.ts +387 -0
  252. package/src/deploy/__tests__/state.spec.ts +876 -0
  253. package/src/deploy/__tests__/undeploy.spec.ts +758 -0
  254. package/src/deploy/backup-provisioner.ts +316 -0
  255. package/src/deploy/dns/DnsProvider.ts +201 -0
  256. package/src/deploy/dns/HostingerProvider.ts +174 -0
  257. package/src/deploy/dns/Route53Provider.ts +340 -0
  258. package/src/deploy/dns/hostinger-api.ts +261 -0
  259. package/src/deploy/dns/index.ts +627 -0
  260. package/src/deploy/docker.ts +260 -0
  261. package/src/deploy/dokploy-api.ts +1101 -0
  262. package/src/deploy/dokploy.ts +177 -0
  263. package/src/deploy/domain.ts +134 -0
  264. package/src/deploy/env-resolver.ts +305 -0
  265. package/src/deploy/index.ts +2094 -0
  266. package/src/deploy/init.ts +427 -0
  267. package/src/deploy/secrets.ts +187 -0
  268. package/src/deploy/sniffer-envkit-patch.ts +61 -0
  269. package/src/deploy/sniffer-hooks.ts +57 -0
  270. package/src/deploy/sniffer-loader.ts +28 -0
  271. package/src/deploy/sniffer-routes-worker.ts +104 -0
  272. package/src/deploy/sniffer-worker.ts +75 -0
  273. package/src/deploy/sniffer.ts +578 -0
  274. package/src/deploy/state-commands.ts +274 -0
  275. package/src/deploy/state.ts +482 -0
  276. package/src/deploy/types.ts +102 -0
  277. package/src/deploy/undeploy.ts +407 -0
  278. package/src/dev/__tests__/entry-integration.spec.ts +347 -0
  279. package/src/dev/__tests__/entry.spec.ts +144 -0
  280. package/src/dev/__tests__/index.spec.ts +2084 -0
  281. package/src/dev/index.ts +1649 -0
  282. package/src/docker/__tests__/compose.spec.ts +1142 -0
  283. package/src/docker/__tests__/templates.spec.ts +694 -0
  284. package/src/docker/compose.ts +812 -0
  285. package/src/docker/index.ts +523 -0
  286. package/src/docker/templates.ts +1067 -0
  287. package/src/exec/index.ts +118 -0
  288. package/src/generators/CronGenerator.ts +105 -0
  289. package/src/generators/EndpointGenerator.ts +954 -0
  290. package/src/generators/FunctionGenerator.ts +117 -0
  291. package/src/generators/Generator.ts +147 -0
  292. package/src/generators/OpenApiTsGenerator.ts +821 -0
  293. package/src/generators/QueueGenerator.ts +245 -0
  294. package/src/generators/SubscriberGenerator.ts +282 -0
  295. package/src/generators/TopicGenerator.ts +45 -0
  296. package/src/generators/__tests__/CronGenerator.spec.ts +445 -0
  297. package/src/generators/__tests__/EndpointGenerator.spec.ts +544 -0
  298. package/src/generators/__tests__/FunctionGenerator.spec.ts +256 -0
  299. package/src/generators/__tests__/Generator.bustCache.spec.ts +72 -0
  300. package/src/generators/__tests__/OpenApiTsGenerator.registry.spec.ts +98 -0
  301. package/src/generators/__tests__/OpenApiTsGenerator.responseType.spec.ts +56 -0
  302. package/src/generators/__tests__/QueueGenerator.spec.ts +141 -0
  303. package/src/generators/__tests__/SubscriberGenerator.spec.ts +410 -0
  304. package/src/generators/index.ts +11 -0
  305. package/src/index.ts +972 -0
  306. package/src/init/__tests__/generators.spec.ts +1072 -0
  307. package/src/init/__tests__/init.spec.ts +577 -0
  308. package/src/init/__tests__/utils.spec.ts +104 -0
  309. package/src/init/generators/auth.ts +225 -0
  310. package/src/init/generators/config.ts +316 -0
  311. package/src/init/generators/docker.ts +388 -0
  312. package/src/init/generators/env.ts +62 -0
  313. package/src/init/generators/index.ts +6 -0
  314. package/src/init/generators/mobile-expo.ts +576 -0
  315. package/src/init/generators/models.ts +153 -0
  316. package/src/init/generators/monorepo.ts +475 -0
  317. package/src/init/generators/package.ts +95 -0
  318. package/src/init/generators/source.ts +15 -0
  319. package/src/init/generators/test.ts +178 -0
  320. package/src/init/generators/ui.ts +1473 -0
  321. package/src/init/generators/web-tanstack.ts +348 -0
  322. package/src/init/generators/web.ts +363 -0
  323. package/src/init/index.ts +542 -0
  324. package/src/init/templates/api.ts +404 -0
  325. package/src/init/templates/index.ts +342 -0
  326. package/src/init/templates/minimal.ts +207 -0
  327. package/src/init/templates/serverless.ts +148 -0
  328. package/src/init/templates/worker.ts +216 -0
  329. package/src/init/utils.ts +197 -0
  330. package/src/init/versions.ts +52 -0
  331. package/src/openapi-react-query.ts +288 -0
  332. package/src/openapi.ts +259 -0
  333. package/src/secrets/__tests__/encryption.spec.ts +226 -0
  334. package/src/secrets/__tests__/generator.spec.ts +575 -0
  335. package/src/secrets/__tests__/index.spec.ts +91 -0
  336. package/src/secrets/__tests__/reconcile.spec.ts +123 -0
  337. package/src/secrets/__tests__/storage.spec.ts +645 -0
  338. package/src/secrets/encryption.ts +91 -0
  339. package/src/secrets/generator.ts +329 -0
  340. package/src/secrets/index.ts +417 -0
  341. package/src/secrets/keystore.ts +144 -0
  342. package/src/secrets/reconcile.ts +53 -0
  343. package/src/secrets/storage.ts +337 -0
  344. package/src/secrets/sync.ts +136 -0
  345. package/src/secrets/types.ts +70 -0
  346. package/src/setup/__tests__/auto-setup.spec.ts +147 -0
  347. package/src/setup/__tests__/reconcile-secrets.spec.ts +439 -0
  348. package/src/setup/fullstack-secrets.ts +140 -0
  349. package/src/setup/index.ts +411 -0
  350. package/src/test/__tests__/__fixtures__/workspace.ts +104 -0
  351. package/src/test/__tests__/api.spec.ts +199 -0
  352. package/src/test/__tests__/auth.spec.ts +162 -0
  353. package/src/test/__tests__/index.spec.ts +502 -0
  354. package/src/test/__tests__/web.spec.ts +210 -0
  355. package/src/test/index.ts +198 -0
  356. package/src/types.ts +363 -0
  357. package/src/upgrade/__tests__/index.spec.ts +354 -0
  358. package/src/upgrade/index.ts +253 -0
  359. package/src/workspace/__tests__/client-generator.spec.ts +326 -0
  360. package/src/workspace/__tests__/index.spec.ts +766 -0
  361. package/src/workspace/__tests__/publicEnv.spec.ts +64 -0
  362. package/src/workspace/__tests__/schema.spec.ts +737 -0
  363. package/src/workspace/__tests__/type-inference.spec.ts +251 -0
  364. package/src/workspace/client-generator.ts +109 -0
  365. package/src/workspace/index.ts +433 -0
  366. package/src/workspace/publicEnv.ts +57 -0
  367. package/src/workspace/schema.ts +861 -0
  368. package/src/workspace/types.ts +943 -0
  369. package/tsconfig.json +9 -0
  370. package/tsdown.config.ts +22 -0
  371. package/bin/adjacent-tsconfig.mjs +0 -97
  372. package/bin/owning-tsconfig-jsx-register.mjs +0 -18
  373. package/bin/owning-tsconfig-jsx.mjs +0 -108
  374. package/dist/EndpointGenerator-Bor2tZCm.mjs +0 -1031
  375. package/dist/EndpointGenerator-Bor2tZCm.mjs.map +0 -1
  376. package/dist/EndpointGenerator-De03t1hd.cjs +0 -1090
  377. package/dist/EndpointGenerator-De03t1hd.cjs.map +0 -1
  378. package/dist/GoDaddyProvider-C2fK-zeQ.mjs +0 -388
  379. package/dist/GoDaddyProvider-C2fK-zeQ.mjs.map +0 -1
  380. package/dist/GoDaddyProvider-SLlyDwD1.cjs +0 -388
  381. package/dist/GoDaddyProvider-SLlyDwD1.cjs.map +0 -1
  382. package/dist/HostingerProvider-BNpS9aRJ.mjs.map +0 -1
  383. package/dist/HostingerProvider-DR1iws1P.cjs.map +0 -1
  384. package/dist/LegacyStateStore-CAvxM8U5.cjs +0 -124
  385. package/dist/LegacyStateStore-CAvxM8U5.cjs.map +0 -1
  386. package/dist/LegacyStateStore-D9QDWCst.mjs +0 -124
  387. package/dist/LegacyStateStore-D9QDWCst.mjs.map +0 -1
  388. package/dist/LocalStateStore-DPQSqkSb.mjs +0 -167
  389. package/dist/LocalStateStore-DPQSqkSb.mjs.map +0 -1
  390. package/dist/LocalStateStore-QcrdjCl6.cjs +0 -178
  391. package/dist/LocalStateStore-QcrdjCl6.cjs.map +0 -1
  392. package/dist/OpenApiTsGenerator-CS_RtWOz.cjs +0 -541
  393. package/dist/OpenApiTsGenerator-CS_RtWOz.cjs.map +0 -1
  394. package/dist/OpenApiTsGenerator-DWAF-7Fu.mjs +0 -536
  395. package/dist/OpenApiTsGenerator-DWAF-7Fu.mjs.map +0 -1
  396. package/dist/Route53Provider-Bllus2NR.cjs.map +0 -1
  397. package/dist/Route53Provider-QXxjkZO1.mjs.map +0 -1
  398. package/dist/S3StateStore-C16tVikU.cjs +0 -222
  399. package/dist/S3StateStore-C16tVikU.cjs.map +0 -1
  400. package/dist/S3StateStore-jorgKaee.mjs +0 -223
  401. package/dist/S3StateStore-jorgKaee.mjs.map +0 -1
  402. package/dist/SSMStateStore-Dvjt_INw.mjs +0 -205
  403. package/dist/SSMStateStore-Dvjt_INw.mjs.map +0 -1
  404. package/dist/SSMStateStore-mPAEr2P2.cjs +0 -204
  405. package/dist/SSMStateStore-mPAEr2P2.cjs.map +0 -1
  406. package/dist/SubscriberGenerator-CyN2VF5X.mjs +0 -449
  407. package/dist/SubscriberGenerator-CyN2VF5X.mjs.map +0 -1
  408. package/dist/SubscriberGenerator-Dvz7EzqK.cjs +0 -490
  409. package/dist/SubscriberGenerator-Dvz7EzqK.cjs.map +0 -1
  410. package/dist/add-CZIIsTcv.mjs +0 -718
  411. package/dist/add-CZIIsTcv.mjs.map +0 -1
  412. package/dist/add-SRk65Udu.cjs +0 -720
  413. package/dist/add-SRk65Udu.cjs.map +0 -1
  414. package/dist/appPorts-C9z9Pzn9.mjs +0 -223
  415. package/dist/appPorts-C9z9Pzn9.mjs.map +0 -1
  416. package/dist/appPorts-Cu79hJF6.cjs +0 -264
  417. package/dist/appPorts-Cu79hJF6.cjs.map +0 -1
  418. package/dist/aws-8QQ8n-t6.mjs +0 -89
  419. package/dist/aws-8QQ8n-t6.mjs.map +0 -1
  420. package/dist/aws-DY9NqQIT.cjs +0 -100
  421. package/dist/aws-DY9NqQIT.cjs.map +0 -1
  422. package/dist/awsStore-Bx5nCFnS.mjs +0 -121
  423. package/dist/awsStore-Bx5nCFnS.mjs.map +0 -1
  424. package/dist/awsStore-u3ehhMoY.cjs +0 -138
  425. package/dist/awsStore-u3ehhMoY.cjs.map +0 -1
  426. package/dist/backup-provisioner-C8DnCmxK.mjs.map +0 -1
  427. package/dist/backup-provisioner-oDEsPj02.cjs.map +0 -1
  428. package/dist/bundler-B0Pj5FXT.cjs +0 -169
  429. package/dist/bundler-B0Pj5FXT.cjs.map +0 -1
  430. package/dist/bundler-DxJ-cIEt.mjs +0 -169
  431. package/dist/bundler-DxJ-cIEt.mjs.map +0 -1
  432. package/dist/cli-CRDJWWmZ.cjs +0 -73
  433. package/dist/cli-CRDJWWmZ.cjs.map +0 -1
  434. package/dist/cli-CV85bY3-.mjs +0 -73
  435. package/dist/cli-CV85bY3-.mjs.map +0 -1
  436. package/dist/compose-CQQRRJC3.mjs +0 -1511
  437. package/dist/compose-CQQRRJC3.mjs.map +0 -1
  438. package/dist/compose-DMY4ouEk.cjs +0 -1558
  439. package/dist/compose-DMY4ouEk.cjs.map +0 -1
  440. package/dist/config-CS76CzXM.d.cts +0 -269
  441. package/dist/config-CS76CzXM.d.cts.map +0 -1
  442. package/dist/config-pBzLfNef.d.mts +0 -269
  443. package/dist/config-pBzLfNef.d.mts.map +0 -1
  444. package/dist/config.cjs.map +0 -1
  445. package/dist/config.mjs.map +0 -1
  446. package/dist/credentialSchemas-BJFvfkaz.mjs +0 -237
  447. package/dist/credentialSchemas-BJFvfkaz.mjs.map +0 -1
  448. package/dist/credentialSchemas-CAPKFkrG.cjs +0 -272
  449. package/dist/credentialSchemas-CAPKFkrG.cjs.map +0 -1
  450. package/dist/credentials-B5N5yKk6.mjs +0 -267
  451. package/dist/credentials-B5N5yKk6.mjs.map +0 -1
  452. package/dist/credentials-Zqr3QQYB.cjs +0 -350
  453. package/dist/credentials-Zqr3QQYB.cjs.map +0 -1
  454. package/dist/databases-BeGP5eDh.mjs +0 -495
  455. package/dist/databases-BeGP5eDh.mjs.map +0 -1
  456. package/dist/databases-DGALFDG3.cjs +0 -598
  457. package/dist/databases-DGALFDG3.cjs.map +0 -1
  458. package/dist/define-6poNqm5O.mjs +0 -106
  459. package/dist/define-6poNqm5O.mjs.map +0 -1
  460. package/dist/define-crmMcXFS.cjs +0 -153
  461. package/dist/define-crmMcXFS.cjs.map +0 -1
  462. package/dist/deploy/public.cjs +0 -211
  463. package/dist/deploy/public.cjs.map +0 -1
  464. package/dist/deploy/public.d.cts +0 -664
  465. package/dist/deploy/public.d.cts.map +0 -1
  466. package/dist/deploy/public.d.mts +0 -664
  467. package/dist/deploy/public.d.mts.map +0 -1
  468. package/dist/deploy/public.mjs +0 -144
  469. package/dist/deploy/public.mjs.map +0 -1
  470. package/dist/deploy/sniffer-envparser-worker.cjs +0 -54
  471. package/dist/deploy/sniffer-envparser-worker.cjs.map +0 -1
  472. package/dist/deploy/sniffer-envparser-worker.d.cts +0 -1
  473. package/dist/deploy/sniffer-envparser-worker.d.mts +0 -1
  474. package/dist/deploy/sniffer-envparser-worker.mjs +0 -55
  475. package/dist/deploy/sniffer-envparser-worker.mjs.map +0 -1
  476. package/dist/deploy-277jek46.cjs +0 -2068
  477. package/dist/deploy-277jek46.cjs.map +0 -1
  478. package/dist/deploy-Dw8g3sLY.mjs +0 -2019
  479. package/dist/deploy-Dw8g3sLY.mjs.map +0 -1
  480. package/dist/derive-B4vDpzgP.mjs +0 -150
  481. package/dist/derive-B4vDpzgP.mjs.map +0 -1
  482. package/dist/derive-DAbo49sm.cjs +0 -161
  483. package/dist/derive-DAbo49sm.cjs.map +0 -1
  484. package/dist/discover-CU1LjCOf.d.cts +0 -108
  485. package/dist/discover-CU1LjCOf.d.cts.map +0 -1
  486. package/dist/discover-DJCCgimv.d.mts +0 -108
  487. package/dist/discover-DJCCgimv.d.mts.map +0 -1
  488. package/dist/discover-DPgu-ScS.cjs +0 -600
  489. package/dist/discover-DPgu-ScS.cjs.map +0 -1
  490. package/dist/discover-qjFapetL.mjs +0 -527
  491. package/dist/discover-qjFapetL.mjs.map +0 -1
  492. package/dist/dns-4RAiVFa7.cjs +0 -55
  493. package/dist/dns-4RAiVFa7.cjs.map +0 -1
  494. package/dist/dns-CU22K_i0.mjs +0 -44
  495. package/dist/dns-CU22K_i0.mjs.map +0 -1
  496. package/dist/dns-Dhjbnjgl.cjs +0 -663
  497. package/dist/dns-Dhjbnjgl.cjs.map +0 -1
  498. package/dist/dns-LqWzPb8l.mjs +0 -610
  499. package/dist/dns-LqWzPb8l.mjs.map +0 -1
  500. package/dist/dokploy-D_uCbZQ7.mjs +0 -38
  501. package/dist/dokploy-D_uCbZQ7.mjs.map +0 -1
  502. package/dist/dokploy-Dw4oCXqR.cjs +0 -38
  503. package/dist/dokploy-Dw4oCXqR.cjs.map +0 -1
  504. package/dist/drivers-CTaWrA_L.mjs +0 -177
  505. package/dist/drivers-CTaWrA_L.mjs.map +0 -1
  506. package/dist/drivers-DDojgzz0.cjs +0 -200
  507. package/dist/drivers-DDojgzz0.cjs.map +0 -1
  508. package/dist/emit-C1e8qD08.mjs +0 -193
  509. package/dist/emit-C1e8qD08.mjs.map +0 -1
  510. package/dist/emit-Dmc1nvdS.cjs +0 -210
  511. package/dist/emit-Dmc1nvdS.cjs.map +0 -1
  512. package/dist/encryption-C0uKYE9v.mjs +0 -89
  513. package/dist/encryption-C0uKYE9v.mjs.map +0 -1
  514. package/dist/encryption-CtVPHWWq.cjs +0 -90
  515. package/dist/encryption-CtVPHWWq.cjs.map +0 -1
  516. package/dist/engine-BE5PdE8S.mjs +0 -3080
  517. package/dist/engine-BE5PdE8S.mjs.map +0 -1
  518. package/dist/engine-HI8aLw1M.cjs +0 -3193
  519. package/dist/engine-HI8aLw1M.cjs.map +0 -1
  520. package/dist/errors-D8Gwp5kU.mjs +0 -23
  521. package/dist/errors-D8Gwp5kU.mjs.map +0 -1
  522. package/dist/errors-DMC4Umsb.cjs +0 -34
  523. package/dist/errors-DMC4Umsb.cjs.map +0 -1
  524. package/dist/github-BCdfZ9zO.cjs +0 -818
  525. package/dist/github-BCdfZ9zO.cjs.map +0 -1
  526. package/dist/github-CT3X720_.mjs +0 -818
  527. package/dist/github-CT3X720_.mjs.map +0 -1
  528. package/dist/index-DKtB01YC.d.cts +0 -190
  529. package/dist/index-DKtB01YC.d.cts.map +0 -1
  530. package/dist/index-ZAUrXH6Q.d.mts +0 -190
  531. package/dist/index-ZAUrXH6Q.d.mts.map +0 -1
  532. package/dist/local-BwC2v2Y8.mjs +0 -224
  533. package/dist/local-BwC2v2Y8.mjs.map +0 -1
  534. package/dist/local-DNhnkugT.cjs +0 -241
  535. package/dist/local-DNhnkugT.cjs.map +0 -1
  536. package/dist/migrate-CCZUgxMK.mjs +0 -266
  537. package/dist/migrate-CCZUgxMK.mjs.map +0 -1
  538. package/dist/migrate-Cs7kQxD5.cjs +0 -271
  539. package/dist/migrate-Cs7kQxD5.cjs.map +0 -1
  540. package/dist/migrate-DBGyoBvZ.cjs +0 -181
  541. package/dist/migrate-DBGyoBvZ.cjs.map +0 -1
  542. package/dist/migrate-DH-lOK3j.mjs +0 -181
  543. package/dist/migrate-DH-lOK3j.mjs.map +0 -1
  544. package/dist/openapi.cjs.map +0 -1
  545. package/dist/openapi.mjs.map +0 -1
  546. package/dist/projectBucket-BjeDcAYy.cjs +0 -206
  547. package/dist/projectBucket-BjeDcAYy.cjs.map +0 -1
  548. package/dist/projectBucket-DrkEht-j.mjs +0 -177
  549. package/dist/projectBucket-DrkEht-j.mjs.map +0 -1
  550. package/dist/provider-BqpjG9QM.cjs +0 -57
  551. package/dist/provider-BqpjG9QM.cjs.map +0 -1
  552. package/dist/provider-CEOKk8NS.mjs +0 -46
  553. package/dist/provider-CEOKk8NS.mjs.map +0 -1
  554. package/dist/ready-D3PIjx3S.cjs +0 -403
  555. package/dist/ready-D3PIjx3S.cjs.map +0 -1
  556. package/dist/ready-naOSJpeJ.mjs +0 -374
  557. package/dist/ready-naOSJpeJ.mjs.map +0 -1
  558. package/dist/reconcile/public.cjs +0 -7
  559. package/dist/reconcile/public.d.cts +0 -49
  560. package/dist/reconcile/public.d.cts.map +0 -1
  561. package/dist/reconcile/public.d.mts +0 -49
  562. package/dist/reconcile/public.d.mts.map +0 -1
  563. package/dist/reconcile/public.mjs +0 -3
  564. package/dist/reconcile--I7V4Klj.mjs.map +0 -1
  565. package/dist/reconcile-CuCQBa5-.cjs.map +0 -1
  566. package/dist/resolve-CScrqgdC.cjs +0 -316
  567. package/dist/resolve-CScrqgdC.cjs.map +0 -1
  568. package/dist/resolve-OfLaxaxY.mjs +0 -263
  569. package/dist/resolve-OfLaxaxY.mjs.map +0 -1
  570. package/dist/rollback-D7p4wJNO.cjs +0 -165
  571. package/dist/rollback-D7p4wJNO.cjs.map +0 -1
  572. package/dist/rollback-DQBSN-i7.mjs +0 -136
  573. package/dist/rollback-DQBSN-i7.mjs.map +0 -1
  574. package/dist/rolldown-runtime-BhDjJH2R.mjs +0 -15
  575. package/dist/run-BJLIerMM.mjs +0 -133
  576. package/dist/run-BJLIerMM.mjs.map +0 -1
  577. package/dist/run-fVZ-rLnc.cjs +0 -174
  578. package/dist/run-fVZ-rLnc.cjs.map +0 -1
  579. package/dist/runtime-BlHOVx8L.d.cts +0 -82
  580. package/dist/runtime-BlHOVx8L.d.cts.map +0 -1
  581. package/dist/runtime-DMq9C3KB.d.mts +0 -82
  582. package/dist/runtime-DMq9C3KB.d.mts.map +0 -1
  583. package/dist/s3-CUKzBBae.mjs +0 -215
  584. package/dist/s3-CUKzBBae.mjs.map +0 -1
  585. package/dist/s3-QQi4sNOQ.cjs +0 -215
  586. package/dist/s3-QQi4sNOQ.cjs.map +0 -1
  587. package/dist/sandbox/config-worker.cjs +0 -43
  588. package/dist/sandbox/config-worker.cjs.map +0 -1
  589. package/dist/sandbox/config-worker.d.cts +0 -1
  590. package/dist/sandbox/config-worker.d.mts +0 -1
  591. package/dist/sandbox/config-worker.mjs +0 -44
  592. package/dist/sandbox/config-worker.mjs.map +0 -1
  593. package/dist/sandbox/credentials-worker.cjs +0 -54
  594. package/dist/sandbox/credentials-worker.cjs.map +0 -1
  595. package/dist/sandbox/credentials-worker.d.cts +0 -1
  596. package/dist/sandbox/credentials-worker.d.mts +0 -1
  597. package/dist/sandbox/credentials-worker.mjs +0 -55
  598. package/dist/sandbox/credentials-worker.mjs.map +0 -1
  599. package/dist/sandbox/discover-worker.cjs +0 -47
  600. package/dist/sandbox/discover-worker.cjs.map +0 -1
  601. package/dist/sandbox/discover-worker.d.cts +0 -1
  602. package/dist/sandbox/discover-worker.d.mts +0 -1
  603. package/dist/sandbox/discover-worker.mjs +0 -48
  604. package/dist/sandbox/discover-worker.mjs.map +0 -1
  605. package/dist/sandbox/migrate-worker.cjs +0 -75
  606. package/dist/sandbox/migrate-worker.cjs.map +0 -1
  607. package/dist/sandbox/migrate-worker.d.cts +0 -1
  608. package/dist/sandbox/migrate-worker.d.mts +0 -1
  609. package/dist/sandbox/migrate-worker.mjs +0 -76
  610. package/dist/sandbox/migrate-worker.mjs.map +0 -1
  611. package/dist/sandbox-ArJ_hEKk.d.cts +0 -104
  612. package/dist/sandbox-ArJ_hEKk.d.cts.map +0 -1
  613. package/dist/sandbox-CHv3OYXg.cjs +0 -165
  614. package/dist/sandbox-CHv3OYXg.cjs.map +0 -1
  615. package/dist/sandbox-CbVB7uOD.mjs +0 -118
  616. package/dist/sandbox-CbVB7uOD.mjs.map +0 -1
  617. package/dist/sandbox-Cm4X6HRh.d.mts +0 -104
  618. package/dist/sandbox-Cm4X6HRh.d.mts.map +0 -1
  619. package/dist/schemas-BObwxB_t.cjs +0 -6017
  620. package/dist/schemas-BObwxB_t.cjs.map +0 -1
  621. package/dist/schemas-D-xeKJDD.mjs +0 -5916
  622. package/dist/schemas-D-xeKJDD.mjs.map +0 -1
  623. package/dist/secrets-AA_tQUl-.mjs +0 -36
  624. package/dist/secrets-AA_tQUl-.mjs.map +0 -1
  625. package/dist/secrets-B_biKsKx.cjs +0 -47
  626. package/dist/secrets-B_biKsKx.cjs.map +0 -1
  627. package/dist/secretsManager-CQORubp9.mjs +0 -97
  628. package/dist/secretsManager-CQORubp9.mjs.map +0 -1
  629. package/dist/secretsManager-RAGcEDX1.cjs +0 -108
  630. package/dist/secretsManager-RAGcEDX1.cjs.map +0 -1
  631. package/dist/seeds-BvxWUGKJ.mjs +0 -8263
  632. package/dist/seeds-BvxWUGKJ.mjs.map +0 -1
  633. package/dist/seeds-Df4BI-T3.cjs +0 -9266
  634. package/dist/seeds-Df4BI-T3.cjs.map +0 -1
  635. package/dist/sniffer-BqjXvcaK.mjs +0 -1825
  636. package/dist/sniffer-BqjXvcaK.mjs.map +0 -1
  637. package/dist/sniffer-DZeQJKty.cjs +0 -1998
  638. package/dist/sniffer-DZeQJKty.cjs.map +0 -1
  639. package/dist/sst-CGdjHn2A.mjs +0 -441
  640. package/dist/sst-CGdjHn2A.mjs.map +0 -1
  641. package/dist/sst-DGuHDxVU.cjs +0 -464
  642. package/dist/sst-DGuHDxVU.cjs.map +0 -1
  643. package/dist/stack-A6MAFZ6u.mjs +0 -1201
  644. package/dist/stack-A6MAFZ6u.mjs.map +0 -1
  645. package/dist/stack-BpkZEEfB.cjs +0 -1308
  646. package/dist/stack-BpkZEEfB.cjs.map +0 -1
  647. package/dist/stages-6SEoRA4x.mjs +0 -190
  648. package/dist/stages-6SEoRA4x.mjs.map +0 -1
  649. package/dist/stages-DH5z89eT.cjs +0 -190
  650. package/dist/stages-DH5z89eT.cjs.map +0 -1
  651. package/dist/target/public.cjs +0 -15
  652. package/dist/target/public.d.cts +0 -28
  653. package/dist/target/public.d.cts.map +0 -1
  654. package/dist/target/public.d.mts +0 -28
  655. package/dist/target/public.d.mts.map +0 -1
  656. package/dist/target/public.mjs +0 -4
  657. package/dist/terminal-CPHuH4S1.cjs +0 -85
  658. package/dist/terminal-CPHuH4S1.cjs.map +0 -1
  659. package/dist/terminal-iNmAXXjs.mjs +0 -85
  660. package/dist/terminal-iNmAXXjs.mjs.map +0 -1
  661. package/dist/types-DipUP9zp.d.cts +0 -7606
  662. package/dist/types-DipUP9zp.d.cts.map +0 -1
  663. package/dist/types-Drpl9HX9.d.mts +0 -7605
  664. package/dist/types-Drpl9HX9.d.mts.map +0 -1
  665. package/dist/utils-D2Nk1Nv2.cjs +0 -205
  666. package/dist/utils-D2Nk1Nv2.cjs.map +0 -1
  667. package/dist/utils-D_fxUqvU.mjs +0 -156
  668. package/dist/utils-D_fxUqvU.mjs.map +0 -1
  669. package/dist/vitest.cjs +0 -65
  670. package/dist/vitest.cjs.map +0 -1
  671. package/dist/vitest.d.cts +0 -29
  672. package/dist/vitest.d.cts.map +0 -1
  673. package/dist/vitest.d.mts +0 -29
  674. package/dist/vitest.d.mts.map +0 -1
  675. package/dist/vitest.mjs +0 -65
  676. package/dist/vitest.mjs.map +0 -1
  677. package/dist/workerRuntime-BXfhbe13.cjs +0 -108
  678. package/dist/workerRuntime-BXfhbe13.cjs.map +0 -1
  679. package/dist/workerRuntime-CsOyBRx2.mjs +0 -79
  680. package/dist/workerRuntime-CsOyBRx2.mjs.map +0 -1
  681. package/dist/workspace-BBeT6Pil.mjs +0 -2088
  682. package/dist/workspace-BBeT6Pil.mjs.map +0 -1
  683. package/dist/workspace-BJ78Bgvm.cjs +0 -2494
  684. package/dist/workspace-BJ78Bgvm.cjs.map +0 -1
@@ -0,0 +1,1931 @@
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const require_config = require('./config-DujV8DbR.cjs');
3
+ const node_path = require_chunk.__toESM(require("node:path"));
4
+ const node_fs_promises = require_chunk.__toESM(require("node:fs/promises"));
5
+ const node_child_process = require_chunk.__toESM(require("node:child_process"));
6
+ const fast_glob = require_chunk.__toESM(require("fast-glob"));
7
+ const lodash_kebabcase = require_chunk.__toESM(require("lodash.kebabcase"));
8
+ const __geekmidas_constructs_endpoints = require_chunk.__toESM(require("@geekmidas/constructs/endpoints"));
9
+ const node_url = require_chunk.__toESM(require("node:url"));
10
+ const __geekmidas_schema_conversion = require_chunk.__toESM(require("@geekmidas/schema/conversion"));
11
+
12
+ //#region src/types.ts
13
+ function isPartitionedRoutes(routes) {
14
+ return typeof routes === "object" && routes !== null && !Array.isArray(routes) && "paths" in routes;
15
+ }
16
+
17
+ //#endregion
18
+ //#region src/generators/Generator.ts
19
+ /**
20
+ * Zod v4 maintains a process-wide registry of schemas registered via
21
+ * `.meta({ id })`. When we cache-bust user module imports (by appending a
22
+ * `?t=timestamp` query), those modules re-execute and try to register the
23
+ * same ids again, which throws `ID X already exists in the registry`.
24
+ *
25
+ * Clearing the registry in the CLI process is safe: the user's running
26
+ * server lives in a subprocess and has its own isolated registry.
27
+ *
28
+ * Exported for tests.
29
+ */
30
+ function clearZodGlobalRegistry() {
31
+ const registry = globalThis.__zod_globalRegistry;
32
+ if (registry && typeof registry.clear === "function") registry.clear();
33
+ }
34
+ var ConstructGenerator = class {
35
+ static async build(context, outputDir, generator, patterns, options) {
36
+ const constructs = await generator.load(patterns);
37
+ return generator.build(context, constructs, outputDir, options);
38
+ }
39
+ async load(patterns, cwd = process.cwd(), bustCache = false) {
40
+ const logger = console;
41
+ let globPatterns;
42
+ let partitionFn;
43
+ if (isPartitionedRoutes(patterns)) {
44
+ globPatterns = Array.isArray(patterns.paths) ? patterns.paths : [patterns.paths];
45
+ partitionFn = patterns.partition;
46
+ } else globPatterns = Array.isArray(patterns) ? patterns : patterns ? [patterns] : [];
47
+ const files = fast_glob.default.stream(globPatterns, {
48
+ cwd,
49
+ absolute: true
50
+ });
51
+ if (bustCache) clearZodGlobalRegistry();
52
+ const constructs = [];
53
+ for await (const f of files) try {
54
+ const file = f.toString();
55
+ const importPath = bustCache ? `${file}?t=${Date.now()}` : file;
56
+ const module$1 = await import(importPath);
57
+ const partition = partitionFn ? partitionFn(file) : void 0;
58
+ for (const [key, construct] of Object.entries(module$1)) if (this.isConstruct(construct)) constructs.push({
59
+ key,
60
+ name: (0, lodash_kebabcase.default)(key),
61
+ construct,
62
+ path: {
63
+ absolute: file,
64
+ relative: (0, node_path.relative)(process.cwd(), file)
65
+ },
66
+ partition
67
+ });
68
+ } catch (error) {
69
+ const err = error;
70
+ logger.error(`Failed to load ${f}: ${err.message}`);
71
+ if (err.stack) logger.error(err.stack);
72
+ throw error;
73
+ }
74
+ return constructs;
75
+ }
76
+ };
77
+
78
+ //#endregion
79
+ //#region src/build/endpoint-analyzer.ts
80
+ /**
81
+ * Analyze an endpoint to extract its features
82
+ */
83
+ function analyzeEndpointFeatures(endpoint) {
84
+ return {
85
+ hasAuth: !!endpoint.authorizer,
86
+ hasServices: endpoint.services.length > 0,
87
+ hasDatabase: !!endpoint.databaseService,
88
+ hasBodyValidation: !!endpoint.input?.body,
89
+ hasQueryValidation: !!endpoint.input?.query,
90
+ hasParamValidation: !!endpoint.input?.params,
91
+ hasAudits: (endpoint.audits?.length ?? 0) > 0,
92
+ hasEvents: (endpoint.events?.length ?? 0) > 0,
93
+ hasRateLimit: !!endpoint.rateLimit,
94
+ hasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,
95
+ hasOutputValidation: !!endpoint.outputSchema
96
+ };
97
+ }
98
+ /**
99
+ * Determine the optimization tier for an endpoint based on its features
100
+ */
101
+ function determineEndpointTier(features) {
102
+ const { hasAuth, hasServices, hasDatabase, hasAudits, hasEvents, hasRateLimit, hasRls } = features;
103
+ if (!hasAuth && !hasServices && !hasDatabase && !hasAudits && !hasEvents && !hasRateLimit && !hasRls) return "minimal";
104
+ if (hasAudits || hasRls || hasRateLimit) return "full";
105
+ return "standard";
106
+ }
107
+ /**
108
+ * Perform complete analysis of an endpoint
109
+ */
110
+ function analyzeEndpoint(endpoint, exportName) {
111
+ const features = analyzeEndpointFeatures(endpoint);
112
+ const tier = determineEndpointTier(features);
113
+ return {
114
+ route: endpoint.route,
115
+ method: endpoint.method,
116
+ exportName,
117
+ features,
118
+ tier,
119
+ serviceNames: endpoint.services.map((s) => s.serviceName),
120
+ databaseServiceName: endpoint.databaseService?.serviceName
121
+ };
122
+ }
123
+ /**
124
+ * Generate a summary of endpoint analysis for logging
125
+ */
126
+ function summarizeAnalysis(analyses) {
127
+ const byTier = {
128
+ minimal: 0,
129
+ standard: 0,
130
+ full: 0
131
+ };
132
+ const byFeature = {
133
+ hasAuth: 0,
134
+ hasServices: 0,
135
+ hasDatabase: 0,
136
+ hasBodyValidation: 0,
137
+ hasQueryValidation: 0,
138
+ hasParamValidation: 0,
139
+ hasAudits: 0,
140
+ hasEvents: 0,
141
+ hasRateLimit: 0,
142
+ hasRls: 0,
143
+ hasOutputValidation: 0
144
+ };
145
+ for (const analysis of analyses) {
146
+ byTier[analysis.tier]++;
147
+ for (const [feature, enabled] of Object.entries(analysis.features)) if (enabled) byFeature[feature]++;
148
+ }
149
+ return {
150
+ total: analyses.length,
151
+ byTier,
152
+ byFeature
153
+ };
154
+ }
155
+
156
+ //#endregion
157
+ //#region src/build/handler-templates.ts
158
+ /**
159
+ * Generate validator references for an endpoint
160
+ */
161
+ function generateValidators(exportName, features) {
162
+ const validators = [];
163
+ if (features.hasBodyValidation) validators.push(`validateBody(${exportName})`);
164
+ if (features.hasQueryValidation) validators.push(`validateQuery(${exportName})`);
165
+ if (features.hasParamValidation) validators.push(`validateParams(${exportName})`);
166
+ return validators.length > 0 ? `\n ${validators.join(",\n ")},` : "";
167
+ }
168
+ /**
169
+ * Generate a minimal handler (near-raw-Hono performance)
170
+ *
171
+ * Used for: Health checks, public endpoints with no services
172
+ */
173
+ function generateMinimalHandler(analysis) {
174
+ const { exportName, features } = analysis;
175
+ const method = analysis.method.toLowerCase();
176
+ const validators = generateValidators(exportName, features);
177
+ const hasValidators = validators.length > 0;
178
+ if (!hasValidators && !features.hasOutputValidation) return `
179
+ // Minimal handler: ${analysis.route} (${analysis.method})
180
+ app.${method}('${analysis.route}', async (c) => {
181
+ const result = await ${exportName}.handler(
182
+ {
183
+ services: {},
184
+ logger,
185
+ body: undefined,
186
+ query: undefined,
187
+ params: undefined,
188
+ session: undefined,
189
+ header: Endpoint.createHeaders(c.req.header()),
190
+ cookie: Endpoint.createCookies(c.req.header().cookie),
191
+ auditor: undefined,
192
+ db: undefined,
193
+ } as any,
194
+ { getMetadata: () => ({}) } as any,
195
+ );
196
+ return c.json(result, ${exportName}.status as any);
197
+ });`;
198
+ return `
199
+ // Minimal handler with validation: ${analysis.route} (${analysis.method})
200
+ app.${method}('${analysis.route}',${validators}
201
+ async (c) => {
202
+ const result = await ${exportName}.handler(
203
+ {
204
+ services: {},
205
+ logger,
206
+ body: ${features.hasBodyValidation ? "(c.req.valid as any)('json')" : "undefined"},
207
+ query: ${features.hasQueryValidation ? "(c.req.valid as any)('query')" : "undefined"},
208
+ params: ${features.hasParamValidation ? "(c.req.valid as any)('param')" : "undefined"},
209
+ session: undefined,
210
+ header: Endpoint.createHeaders(c.req.header()),
211
+ cookie: Endpoint.createCookies(c.req.header().cookie),
212
+ auditor: undefined,
213
+ db: undefined,
214
+ } as any,
215
+ { getMetadata: () => ({}) } as any,
216
+ );
217
+ ${features.hasOutputValidation ? `const output = await ${exportName}.parseOutput(result);
218
+ return c.json(output, ${exportName}.status as any);` : `return c.json(result, ${exportName}.status as any);`}
219
+ }
220
+ );`;
221
+ }
222
+ /**
223
+ * Generate a standard handler (auth and/or services)
224
+ *
225
+ * Used for: Authenticated endpoints, endpoints with services
226
+ */
227
+ function generateStandardHandler(analysis) {
228
+ const { exportName, features } = analysis;
229
+ const method = analysis.method.toLowerCase();
230
+ const validators = generateValidators(exportName, features);
231
+ let serviceResolution = "";
232
+ if (features.hasServices || features.hasDatabase) serviceResolution = `
233
+ const services = await serviceDiscovery.register(${exportName}.services);
234
+ ${features.hasDatabase ? `const db = ${exportName}.databaseService
235
+ ? (await serviceDiscovery.register([${exportName}.databaseService]) as any)[${exportName}.databaseService.serviceName]
236
+ : undefined;` : "const db = undefined;"}`;
237
+ else serviceResolution = `
238
+ const services = {};
239
+ const db = undefined;`;
240
+ let authCode = "";
241
+ if (features.hasAuth) authCode = `
242
+ // Authentication
243
+ const session = await ${exportName}.getSession({
244
+ services,
245
+ logger,
246
+ header,
247
+ cookie,
248
+ ...(db !== undefined && { db }),
249
+ } as any);
250
+
251
+ const isAuthorized = await ${exportName}.authorize({
252
+ header,
253
+ cookie,
254
+ services,
255
+ logger,
256
+ session,
257
+ } as any);
258
+
259
+ if (!isAuthorized) {
260
+ return c.json({ error: 'Unauthorized' }, 401);
261
+ }`;
262
+ let eventCode = "";
263
+ if (features.hasEvents) eventCode = `
264
+ // Publish events on success
265
+ if (Endpoint.isSuccessStatus(${exportName}.status)) {
266
+ await (publishConstructEvents as any)(
267
+ ${exportName},
268
+ result,
269
+ serviceDiscovery,
270
+ logger,
271
+ );
272
+ }`;
273
+ return `
274
+ // Standard handler: ${analysis.route} (${analysis.method})
275
+ app.${method}('${analysis.route}',${validators}
276
+ async (c) => {
277
+ const headerValues = c.req.header();
278
+ const header = Endpoint.createHeaders(headerValues);
279
+ const cookie = Endpoint.createCookies(headerValues.cookie);
280
+ ${serviceResolution}
281
+ ${authCode}
282
+
283
+ const responseBuilder = new ResponseBuilder();
284
+ const result = await ${exportName}.handler(
285
+ {
286
+ services,
287
+ logger,
288
+ body: ${features.hasBodyValidation ? "(c.req.valid as any)('json')" : "undefined"},
289
+ query: ${features.hasQueryValidation ? "(c.req.valid as any)('query')" : "undefined"},
290
+ params: ${features.hasParamValidation ? "(c.req.valid as any)('param')" : "undefined"},
291
+ session: ${features.hasAuth ? "session" : "undefined"},
292
+ header,
293
+ cookie,
294
+ auditor: undefined,
295
+ db,
296
+ } as any,
297
+ responseBuilder,
298
+ );
299
+
300
+ let data = result;
301
+ let metadata = responseBuilder.getMetadata();
302
+
303
+ if (Endpoint.hasMetadata(result)) {
304
+ data = result.data;
305
+ metadata = result.metadata;
306
+ }
307
+
308
+ ${features.hasOutputValidation ? `const output = ${exportName}.outputSchema
309
+ ? await ${exportName}.parseOutput(data)
310
+ : data;` : "const output = data;"}
311
+ ${eventCode}
312
+
313
+ const status = (metadata.status ?? ${exportName}.status) as any;
314
+ return c.json(output, status);
315
+ }
316
+ );`;
317
+ }
318
+ /**
319
+ * Generate validators.ts - Shared validator middleware factories
320
+ */
321
+ function generateValidatorsFile(analyses) {
322
+ const needsBody = analyses.some((a) => a.features.hasBodyValidation);
323
+ const needsQuery = analyses.some((a) => a.features.hasQueryValidation);
324
+ const needsParams = analyses.some((a) => a.features.hasParamValidation);
325
+ if (!needsBody && !needsQuery && !needsParams) return `// No validators needed for this build\nexport {};\n`;
326
+ const exports$1 = [];
327
+ const factories = [];
328
+ if (needsBody) {
329
+ exports$1.push("validateBody");
330
+ factories.push(`
331
+ export const validateBody = (endpoint: any) =>
332
+ validator('json', async (value, c) => {
333
+ if (!endpoint.input?.body) return undefined;
334
+ const parsed = await Endpoint.validate(endpoint.input.body, value);
335
+ if (parsed.issues) return c.json(parsed.issues, 422);
336
+ return parsed.value;
337
+ });`);
338
+ }
339
+ if (needsQuery) {
340
+ exports$1.push("validateQuery");
341
+ factories.push(`
342
+ export const validateQuery = (endpoint: any) =>
343
+ validator('query', async (_, c) => {
344
+ if (!endpoint.input?.query) return undefined;
345
+ const rawQuery = Object.fromEntries(new URL(c.req.url).searchParams);
346
+ const parsed = await Endpoint.validate(endpoint.input.query, rawQuery);
347
+ if (parsed.issues) return c.json(parsed.issues, 422);
348
+ return parsed.value;
349
+ });`);
350
+ }
351
+ if (needsParams) {
352
+ exports$1.push("validateParams");
353
+ factories.push(`
354
+ export const validateParams = (endpoint: any) =>
355
+ validator('param', async (params, c) => {
356
+ if (!endpoint.input?.params) return undefined;
357
+ const parsed = await Endpoint.validate(endpoint.input.params, params);
358
+ if (parsed.issues) return c.json(parsed.issues, 422);
359
+ return parsed.value;
360
+ });`);
361
+ }
362
+ return `/**
363
+ * Generated validator middleware factories
364
+ * Shared across all endpoint tiers that need validation
365
+ */
366
+ import { validator } from 'hono/validator';
367
+ import { Endpoint } from '@geekmidas/constructs/endpoints';
368
+ ${factories.join("\n")}
369
+ `;
370
+ }
371
+ /**
372
+ * Generate a standalone minimal endpoint file
373
+ */
374
+ function generateMinimalEndpointFile(analysis, endpointImport) {
375
+ const { exportName, features } = analysis;
376
+ const needsValidators = features.hasBodyValidation || features.hasQueryValidation || features.hasParamValidation;
377
+ const validatorImport = needsValidators ? generateValidatorImportsForEndpoint(analysis) : "";
378
+ const handler = generateMinimalHandler(analysis);
379
+ return `/**
380
+ * Minimal endpoint: ${analysis.route} (${analysis.method})
381
+ * Near-raw-Hono performance
382
+ */
383
+ import type { Hono } from 'hono';
384
+ import type { Logger } from '@geekmidas/logger';
385
+ import { Endpoint } from '@geekmidas/constructs/endpoints';
386
+ ${validatorImport}
387
+ import { ${exportName} } from '${endpointImport.importPath}';
388
+
389
+ export function setup${capitalize(exportName)}(
390
+ app: Hono,
391
+ logger: Logger,
392
+ ): void {
393
+ ${handler}
394
+ }
395
+ `;
396
+ }
397
+ /**
398
+ * Generate a standalone standard endpoint file
399
+ */
400
+ function generateStandardEndpointFile(analysis, endpointImport) {
401
+ const { exportName, features } = analysis;
402
+ const needsValidators = features.hasBodyValidation || features.hasQueryValidation || features.hasParamValidation;
403
+ const validatorImport = needsValidators ? generateValidatorImportsForEndpoint(analysis) : "";
404
+ const eventsImport = features.hasEvents ? `import { publishConstructEvents } from '@geekmidas/constructs/endpoints';` : "";
405
+ const handler = generateStandardHandler(analysis);
406
+ return `/**
407
+ * Standard endpoint: ${analysis.route} (${analysis.method})
408
+ * Auth and/or services enabled
409
+ */
410
+ import type { Hono } from 'hono';
411
+ import type { Logger } from '@geekmidas/logger';
412
+ import type { ServiceDiscovery } from '@geekmidas/services';
413
+ import { Endpoint, ResponseBuilder } from '@geekmidas/constructs/endpoints';
414
+ ${eventsImport}
415
+ ${validatorImport}
416
+ import { ${exportName} } from '${endpointImport.importPath}';
417
+
418
+ export function setup${capitalize(exportName)}(
419
+ app: Hono,
420
+ serviceDiscovery: ServiceDiscovery<any, any>,
421
+ logger: Logger,
422
+ ): void {
423
+ ${handler}
424
+ }
425
+ `;
426
+ }
427
+ /**
428
+ * Generate a standalone full endpoint file
429
+ */
430
+ function generateFullEndpointFile(analysis, endpointImport) {
431
+ const { exportName } = analysis;
432
+ return `/**
433
+ * Full endpoint: ${analysis.route} (${analysis.method})
434
+ * Complex features: audits, RLS, rate limiting
435
+ */
436
+ import type { Hono } from 'hono';
437
+ import type { ServiceDiscovery } from '@geekmidas/services';
438
+ import { HonoEndpoint } from '@geekmidas/constructs/hono';
439
+ import { ${exportName} } from '${endpointImport.importPath}';
440
+
441
+ export function setup${capitalize(exportName)}(
442
+ app: Hono,
443
+ serviceDiscovery: ServiceDiscovery<any, any>,
444
+ openApiOptions: any,
445
+ ): void {
446
+ HonoEndpoint.addRoutes([${exportName}] as any, serviceDiscovery, app, openApiOptions);
447
+ }
448
+ `;
449
+ }
450
+ /**
451
+ * Generate tier index file that imports and calls all endpoint setup functions
452
+ */
453
+ function generateTierIndexFile(tier, analyses) {
454
+ const tierEndpoints = analyses.filter((a) => a.tier === tier);
455
+ if (tierEndpoints.length === 0) {
456
+ if (tier === "minimal") return `// No minimal-tier endpoints in this build
457
+ import type { Hono } from 'hono';
458
+ import type { Logger } from '@geekmidas/logger';
459
+
460
+ export function setupMinimalEndpoints(
461
+ _app: Hono,
462
+ _logger: Logger,
463
+ ): void {
464
+ // No minimal endpoints
465
+ }
466
+ `;
467
+ if (tier === "standard") return `// No standard-tier endpoints in this build
468
+ import type { Hono } from 'hono';
469
+ import type { Logger } from '@geekmidas/logger';
470
+ import type { ServiceDiscovery } from '@geekmidas/services';
471
+
472
+ export function setupStandardEndpoints(
473
+ _app: Hono,
474
+ _serviceDiscovery: ServiceDiscovery<any, any>,
475
+ _logger: Logger,
476
+ ): void {
477
+ // No standard endpoints
478
+ }
479
+ `;
480
+ return `// No full-tier endpoints in this build
481
+ import type { Hono } from 'hono';
482
+ import type { ServiceDiscovery } from '@geekmidas/services';
483
+
484
+ export function setupFullEndpoints(
485
+ _app: Hono,
486
+ _serviceDiscovery: ServiceDiscovery<any, any>,
487
+ _enableOpenApi: boolean,
488
+ ): void {
489
+ // No full endpoints
490
+ }
491
+ `;
492
+ }
493
+ const imports = tierEndpoints.map((a) => `import { setup${capitalize(a.exportName)} } from './${a.exportName}.js';`).join("\n");
494
+ if (tier === "minimal") {
495
+ const calls$1 = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, logger);`).join("\n");
496
+ return `/**
497
+ * Minimal-tier endpoint index (${tierEndpoints.length} endpoints)
498
+ * Near-raw-Hono performance
499
+ */
500
+ import type { Hono } from 'hono';
501
+ import type { Logger } from '@geekmidas/logger';
502
+ ${imports}
503
+
504
+ export function setupMinimalEndpoints(
505
+ app: Hono,
506
+ logger: Logger,
507
+ ): void {
508
+ ${calls$1}
509
+ }
510
+ `;
511
+ }
512
+ if (tier === "standard") {
513
+ const calls$1 = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, serviceDiscovery, logger);`).join("\n");
514
+ return `/**
515
+ * Standard-tier endpoint index (${tierEndpoints.length} endpoints)
516
+ * Auth and/or services enabled
517
+ */
518
+ import type { Hono } from 'hono';
519
+ import type { Logger } from '@geekmidas/logger';
520
+ import type { ServiceDiscovery } from '@geekmidas/services';
521
+ ${imports}
522
+
523
+ export function setupStandardEndpoints(
524
+ app: Hono,
525
+ serviceDiscovery: ServiceDiscovery<any, any>,
526
+ logger: Logger,
527
+ ): void {
528
+ ${calls$1}
529
+ }
530
+ `;
531
+ }
532
+ const calls = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, serviceDiscovery, openApiOptions);`).join("\n");
533
+ return `/**
534
+ * Full-tier endpoint index (${tierEndpoints.length} endpoints)
535
+ * Complex features: audits, RLS, rate limiting
536
+ */
537
+ import type { Hono } from 'hono';
538
+ import type { ServiceDiscovery } from '@geekmidas/services';
539
+ ${imports}
540
+
541
+ export function setupFullEndpoints(
542
+ app: Hono,
543
+ serviceDiscovery: ServiceDiscovery<any, any>,
544
+ enableOpenApi: boolean,
545
+ ): void {
546
+ const openApiOptions: any = enableOpenApi ? {
547
+ docsPath: '/__docs',
548
+ openApiOptions: {
549
+ title: 'API Documentation',
550
+ version: '1.0.0',
551
+ description: 'Generated API documentation'
552
+ }
553
+ } : { docsPath: false };
554
+
555
+ ${calls}
556
+ }
557
+ `;
558
+ }
559
+ /**
560
+ * Generate validator imports for a single endpoint
561
+ */
562
+ function generateValidatorImportsForEndpoint(analysis) {
563
+ const imports = [];
564
+ if (analysis.features.hasBodyValidation) imports.push("validateBody");
565
+ if (analysis.features.hasQueryValidation) imports.push("validateQuery");
566
+ if (analysis.features.hasParamValidation) imports.push("validateParams");
567
+ if (imports.length === 0) return "";
568
+ return `import { ${imports.join(", ")} } from '../validators.js';`;
569
+ }
570
+ /**
571
+ * Capitalize first letter
572
+ */
573
+ function capitalize(str) {
574
+ return str.charAt(0).toUpperCase() + str.slice(1);
575
+ }
576
+ /**
577
+ * Generate all endpoint files with nested folder structure (per-endpoint files)
578
+ */
579
+ function generateEndpointFilesNested(analyses, endpointImports) {
580
+ const files = {
581
+ "validators.ts": generateValidatorsFile(analyses),
582
+ "minimal/index.ts": generateTierIndexFile("minimal", analyses),
583
+ "standard/index.ts": generateTierIndexFile("standard", analyses),
584
+ "full/index.ts": generateTierIndexFile("full", analyses),
585
+ "index.ts": generateNestedIndexFile(analyses)
586
+ };
587
+ for (const analysis of analyses) {
588
+ const endpointImport = endpointImports.find((i) => i.exportName === analysis.exportName);
589
+ if (!endpointImport) continue;
590
+ const fileName = `${analysis.tier}/${analysis.exportName}.ts`;
591
+ switch (analysis.tier) {
592
+ case "minimal":
593
+ files[fileName] = generateMinimalEndpointFile(analysis, endpointImport);
594
+ break;
595
+ case "standard":
596
+ files[fileName] = generateStandardEndpointFile(analysis, endpointImport);
597
+ break;
598
+ case "full":
599
+ files[fileName] = generateFullEndpointFile(analysis, endpointImport);
600
+ break;
601
+ }
602
+ }
603
+ return files;
604
+ }
605
+ /**
606
+ * Generate index.ts for nested structure
607
+ */
608
+ function generateNestedIndexFile(analyses) {
609
+ const minimalCount = analyses.filter((a) => a.tier === "minimal").length;
610
+ const standardCount = analyses.filter((a) => a.tier === "standard").length;
611
+ const fullCount = analyses.filter((a) => a.tier === "full").length;
612
+ return `/**
613
+ * Generated optimized endpoints
614
+ *
615
+ * Build-time optimization tiers:
616
+ * - minimal: ${minimalCount} endpoints (near-raw-Hono)
617
+ * - standard: ${standardCount} endpoints (auth/services)
618
+ * - full: ${fullCount} endpoints (audits/rls/rate-limit)
619
+ */
620
+ import type { EnvironmentParser } from '@geekmidas/envkit';
621
+ import type { Logger } from '@geekmidas/logger';
622
+ import type { Hono } from 'hono';
623
+ import { ServiceDiscovery } from '@geekmidas/services';
624
+ import { setupMinimalEndpoints } from './minimal/index.js';
625
+ import { setupStandardEndpoints } from './standard/index.js';
626
+ import { setupFullEndpoints } from './full/index.js';
627
+
628
+ export async function setupEndpoints(
629
+ app: Hono,
630
+ envParser: EnvironmentParser<any>,
631
+ logger: Logger,
632
+ enableOpenApi: boolean = false,
633
+ ): Promise<void> {
634
+ const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
635
+
636
+ // Minimal handlers (${minimalCount} endpoints) - near-raw-Hono performance
637
+ setupMinimalEndpoints(app, logger);
638
+
639
+ // Standard handlers (${standardCount} endpoints) - auth/services
640
+ setupStandardEndpoints(app, serviceDiscovery, logger);
641
+
642
+ // Full handlers (${fullCount} endpoints) - audits/rls/rate-limit
643
+ setupFullEndpoints(app, serviceDiscovery, enableOpenApi);
644
+
645
+ // Add Swagger UI if OpenAPI is enabled
646
+ if (enableOpenApi) {
647
+ try {
648
+ const { swaggerUI } = await import('@hono/swagger-ui');
649
+ app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));
650
+ } catch {
651
+ // @hono/swagger-ui not installed, skip Swagger UI
652
+ }
653
+ }
654
+ }
655
+ `;
656
+ }
657
+
658
+ //#endregion
659
+ //#region src/generators/EndpointGenerator.ts
660
+ var EndpointGenerator = class extends ConstructGenerator {
661
+ isConstruct(value) {
662
+ return __geekmidas_constructs_endpoints.Endpoint.isEndpoint(value);
663
+ }
664
+ async build(context, constructs, outputDir, options) {
665
+ const provider = options?.provider || "aws-apigatewayv2";
666
+ const enableOpenApi = options?.enableOpenApi || false;
667
+ const logger = console;
668
+ const routes = [];
669
+ if (constructs.length === 0) return routes;
670
+ if (provider === "server") {
671
+ await this.generateEndpointsFile(outputDir, constructs, context);
672
+ const appFile = await this.generateAppFile(outputDir, context);
673
+ routes.push({
674
+ path: "*",
675
+ method: "ALL",
676
+ handler: (0, node_path.relative)(process.cwd(), appFile),
677
+ authorizer: "none"
678
+ });
679
+ logger.log(`Generated server with ${constructs.length} endpoints${enableOpenApi ? " (OpenAPI enabled)" : ""}`);
680
+ } else if (provider === "aws-lambda") {
681
+ const routesDir = (0, node_path.join)(outputDir, "routes");
682
+ await (0, node_fs_promises.mkdir)(routesDir, { recursive: true });
683
+ for (const { key, construct, path } of constructs) {
684
+ const handlerFile = await this.generateHandlerFile(routesDir, path.relative, key, "aws-apigatewayv2", construct, context);
685
+ const routeInfo = {
686
+ path: construct._path,
687
+ method: construct.method,
688
+ handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
689
+ timeout: construct.timeout,
690
+ memorySize: construct.memorySize,
691
+ environment: await construct.getEnvironment({ markOptional: context.markOptional }),
692
+ authorizer: construct.authorizer?.name ?? "none"
693
+ };
694
+ routes.push(routeInfo);
695
+ logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
696
+ }
697
+ } else for (const { key, construct, path } of constructs) {
698
+ const handlerFile = await this.generateHandlerFile(outputDir, path.relative, key, provider, construct, context);
699
+ const routeInfo = {
700
+ path: construct._path,
701
+ method: construct.method,
702
+ handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
703
+ timeout: construct.timeout,
704
+ memorySize: construct.memorySize,
705
+ environment: await construct.getEnvironment({ markOptional: context.markOptional }),
706
+ authorizer: construct.authorizer?.name ?? "none"
707
+ };
708
+ routes.push(routeInfo);
709
+ logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
710
+ }
711
+ return routes;
712
+ }
713
+ async generateHandlerFile(outputDir, sourceFile, exportName, provider, _endpoint, context) {
714
+ const handlerFileName = `${exportName}.ts`;
715
+ const handlerPath = (0, node_path.join)(outputDir, handlerFileName);
716
+ const relativePath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), sourceFile);
717
+ const importPath = relativePath.replace(/\.ts$/, ".js");
718
+ const relativeEnvParserPath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), context.envParserPath);
719
+ let content;
720
+ switch (provider) {
721
+ case "aws-apigatewayv1":
722
+ content = this.generateAWSApiGatewayV1Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
723
+ break;
724
+ case "aws-apigatewayv2":
725
+ content = this.generateAWSApiGatewayV2Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
726
+ break;
727
+ case "server":
728
+ content = this.generateServerHandler(importPath, exportName);
729
+ break;
730
+ default: throw new Error(`Unsupported provider: ${provider}`);
731
+ }
732
+ await (0, node_fs_promises.writeFile)(handlerPath, content);
733
+ return handlerPath;
734
+ }
735
+ async generateEndpointsFile(outputDir, endpoints, context) {
736
+ const endpointsFileName = "endpoints.ts";
737
+ const endpointsPath = (0, node_path.join)(outputDir, endpointsFileName);
738
+ const importsByFile = /* @__PURE__ */ new Map();
739
+ for (const { path, key } of endpoints) {
740
+ const relativePath = (0, node_path.relative)((0, node_path.dirname)(endpointsPath), path.relative);
741
+ const importPath = relativePath.replace(/\.ts$/, ".js");
742
+ if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
743
+ importsByFile.get(importPath)?.push(key);
744
+ }
745
+ const endpointImports = Array.from(importsByFile.entries()).map(([importPath, exports$1]) => `import { ${exports$1.join(", ")} } from '${importPath}';`).join("\n");
746
+ const allExportNames = endpoints.map(({ key }) => key);
747
+ if (context.production?.enabled && context.production.optimizedHandlers) return this.generateOptimizedEndpointsFile(endpointsPath, endpoints, endpointImports, allExportNames);
748
+ const content = `import type { EnvironmentParser } from '@geekmidas/envkit';
749
+ import type { Logger } from '@geekmidas/logger';
750
+ import { HonoEndpoint } from '@geekmidas/constructs/hono';
751
+ import { Endpoint } from '@geekmidas/constructs/endpoints';
752
+ import { ServiceDiscovery } from '@geekmidas/services';
753
+ import type { Hono } from 'hono';
754
+ ${endpointImports}
755
+
756
+ export const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any, any, any>[] = [
757
+ ${allExportNames.join(",\n ")}
758
+ ];
759
+
760
+ export async function setupEndpoints(
761
+ app: Hono,
762
+ envParser: EnvironmentParser<any>,
763
+ logger: Logger,
764
+ enableOpenApi: boolean = true,
765
+ ): Promise<void> {
766
+ const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
767
+
768
+ // Configure OpenAPI options based on enableOpenApi flag
769
+ const openApiOptions: any = enableOpenApi ? {
770
+ docsPath: '/__docs',
771
+ openApiOptions: {
772
+ title: 'API Documentation',
773
+ version: '1.0.0',
774
+ description: 'Generated API documentation'
775
+ }
776
+ } : { docsPath: false };
777
+
778
+ HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);
779
+
780
+ // Add Swagger UI if OpenAPI is enabled
781
+ if (enableOpenApi) {
782
+ try {
783
+ const { swaggerUI } = await import('@hono/swagger-ui');
784
+ app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));
785
+ } catch {
786
+ // @hono/swagger-ui not installed, skip Swagger UI
787
+ }
788
+ }
789
+ }
790
+ `;
791
+ await (0, node_fs_promises.writeFile)(endpointsPath, content);
792
+ return endpointsPath;
793
+ }
794
+ /**
795
+ * Generate optimized endpoints files with nested folder structure (per-endpoint files)
796
+ */
797
+ async generateOptimizedEndpointsFile(endpointsPath, endpoints, _endpointImports, _allExportNames) {
798
+ const logger = console;
799
+ const outputDir = (0, node_path.dirname)(endpointsPath);
800
+ const endpointsDir = (0, node_path.join)(outputDir, "endpoints");
801
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(endpointsDir, "minimal"), { recursive: true });
802
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(endpointsDir, "standard"), { recursive: true });
803
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(endpointsDir, "full"), { recursive: true });
804
+ const analyses = endpoints.map(({ key, construct }) => analyzeEndpoint(construct, key));
805
+ const endpointImports = endpoints.map(({ key, path }) => {
806
+ const tierDir = (0, node_path.join)(endpointsDir, "standard");
807
+ const relativePath = (0, node_path.relative)(tierDir, path.relative);
808
+ const importPath = relativePath.replace(/\.ts$/, ".js");
809
+ return {
810
+ exportName: key,
811
+ importPath
812
+ };
813
+ });
814
+ const summary = summarizeAnalysis(analyses);
815
+ logger.log(`\n📊 Endpoint Analysis:`);
816
+ logger.log(` Total: ${summary.total} endpoints`);
817
+ logger.log(` - Minimal (near-raw-Hono): ${summary.byTier.minimal} endpoints`);
818
+ logger.log(` - Standard (auth/services): ${summary.byTier.standard} endpoints`);
819
+ logger.log(` - Full (audits/rls/rate-limit): ${summary.byTier.full} endpoints`);
820
+ const files = generateEndpointFilesNested(analyses, endpointImports);
821
+ for (const [filename, content] of Object.entries(files)) {
822
+ const filePath = (0, node_path.join)(endpointsDir, filename);
823
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(filePath), { recursive: true });
824
+ await (0, node_fs_promises.writeFile)(filePath, content);
825
+ }
826
+ const endpointFiles = Object.keys(files).filter((f) => !f.endsWith("index.ts") && !f.endsWith("validators.ts")).length;
827
+ const indexFiles = Object.keys(files).filter((f) => f.endsWith("index.ts")).length;
828
+ logger.log(` Generated ${endpointFiles} endpoint files + ${indexFiles} index files + validators.ts`);
829
+ return (0, node_path.join)(endpointsDir, "index.ts");
830
+ }
831
+ async generateAppFile(outputDir, context) {
832
+ if (context.production?.enabled) return this.generateProductionAppFile(outputDir, context);
833
+ const appFileName = "app.ts";
834
+ const appPath = (0, node_path.join)(outputDir, appFileName);
835
+ const relativeLoggerPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.loggerPath);
836
+ const relativeEnvParserPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.envParserPath);
837
+ const telescopeEnabled = context.telescope?.enabled;
838
+ const telescopeWebSocketEnabled = context.telescope?.websocket;
839
+ const usesExternalTelescope = !!context.telescope?.telescopePath;
840
+ const studioEnabled = context.studio?.enabled;
841
+ const usesExternalStudio = !!context.studio?.studioPath;
842
+ let telescopeImports = "";
843
+ if (telescopeEnabled) if (usesExternalTelescope) {
844
+ const relativeTelescopePath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.telescope?.telescopePath);
845
+ telescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';
846
+ import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
847
+ } else telescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
848
+ import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
849
+ let studioImports = "";
850
+ if (studioEnabled) if (usesExternalStudio) {
851
+ const relativeStudioPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.studio?.studioPath);
852
+ studioImports = `import ${context.studio?.studioImportPattern} from '${relativeStudioPath}';
853
+ import { createStudioApp } from '@geekmidas/studio/server/hono';`;
854
+ } else studioImports = `// Studio requires a configured instance - use studio config path
855
+ // import { createStudioApp } from '@geekmidas/studio/server/hono';`;
856
+ let hooksImports = "";
857
+ let beforeSetupCall = "";
858
+ let afterSetupCall = "";
859
+ if (context.hooks?.serverHooksPath) {
860
+ const relativeHooksPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.hooks.serverHooksPath);
861
+ hooksImports = `import * as serverHooks from '${relativeHooksPath}';`;
862
+ beforeSetupCall = `
863
+ // Call beforeSetup hook if defined
864
+ if (typeof serverHooks.beforeSetup === 'function') {
865
+ await serverHooks.beforeSetup(honoApp, { envParser, logger });
866
+ }
867
+ `;
868
+ afterSetupCall = `
869
+ // Call afterSetup hook if defined
870
+ if (typeof serverHooks.afterSetup === 'function') {
871
+ await serverHooks.afterSetup(honoApp, { envParser, logger });
872
+ }
873
+ `;
874
+ }
875
+ const telescopeWebSocketSetupCode = telescopeWebSocketEnabled ? `
876
+ // Setup WebSocket for real-time telescope updates
877
+ try {
878
+ const { createNodeWebSocket } = await import('@hono/node-ws');
879
+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });
880
+ // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)
881
+ honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({
882
+ onOpen: (_event: Event, ws: any) => {
883
+ telescope.addWsClient(ws);
884
+ },
885
+ onClose: (_event: Event, ws: any) => {
886
+ telescope.removeWsClient(ws);
887
+ },
888
+ onMessage: (event: MessageEvent, ws: any) => {
889
+ try {
890
+ const data = JSON.parse(event.data);
891
+ if (data.type === 'ping') {
892
+ ws.send(JSON.stringify({ type: 'pong' }));
893
+ }
894
+ } catch {
895
+ // Ignore invalid messages
896
+ }
897
+ },
898
+ })));
899
+ // Store injectWebSocket for server entry to call after serve()
900
+ (honoApp as any).__injectWebSocket = injectWebSocket;
901
+ logger.info('Telescope WebSocket enabled');
902
+ } catch (e) {
903
+ logger.warn({ error: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');
904
+ }
905
+ ` : "";
906
+ let telescopeSetup = "";
907
+ if (telescopeEnabled) if (usesExternalTelescope) telescopeSetup = `
908
+ ${telescopeWebSocketSetupCode}
909
+ // Add telescope middleware (before endpoints to capture all requests)
910
+ honoApp.use('*', createMiddleware(telescope));
911
+
912
+ // Mount telescope UI
913
+ const telescopeUI = createUI(telescope);
914
+ honoApp.route('${context.telescope?.path}', telescopeUI);
915
+ `;
916
+ else telescopeSetup = `
917
+ // Setup Telescope for debugging/monitoring
918
+ const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });
919
+ const telescope = new Telescope({
920
+ enabled: true,
921
+ path: '${context.telescope?.path}',
922
+ ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},
923
+ recordBody: ${context.telescope?.recordBody},
924
+ storage: telescopeStorage,
925
+ });
926
+ ${telescopeWebSocketSetupCode}
927
+ // Add telescope middleware (before endpoints to capture all requests)
928
+ honoApp.use('*', createMiddleware(telescope));
929
+
930
+ // Mount telescope UI
931
+ const telescopeUI = createUI(telescope);
932
+ honoApp.route('${context.telescope?.path}', telescopeUI);
933
+ `;
934
+ let studioSetup = "";
935
+ if (studioEnabled && usesExternalStudio) studioSetup = `
936
+ // Mount Studio data browser UI
937
+ const studioApp = createStudioApp(studio);
938
+ honoApp.route('${context.studio?.path}', studioApp);
939
+ `;
940
+ const content = `/**
941
+ * Generated server application
942
+ *
943
+ * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
944
+ * The subscriber polling mechanism is not production-ready.
945
+ * For production, use AWS Lambda with SQS/SNS event sources.
946
+ */
947
+ import { Hono } from 'hono';
948
+ import type { Hono as HonoType } from 'hono';
949
+ import { setupEndpoints } from './endpoints.js';
950
+ import { setupSubscribers } from './subscribers.js';
951
+ import { setupQueues } from './queues.js';
952
+ import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
953
+ import ${context.loggerImportPattern} from '${relativeLoggerPath}';
954
+ ${telescopeImports}
955
+ ${studioImports}
956
+ ${hooksImports}
957
+
958
+ export interface ServerApp {
959
+ app: HonoType;
960
+ start: (options?: {
961
+ port?: number;
962
+ serve: (app: HonoType, port: number) => void | Promise<void>;
963
+ }) => Promise<void>;
964
+ }
965
+
966
+ /**
967
+ * Create and configure the Hono application
968
+ *
969
+ * @param app - Optional Hono app instance to configure (creates new one if not provided)
970
+ * @param enableOpenApi - Enable OpenAPI documentation (default: true)
971
+ * @returns Server app with configured Hono app and start function
972
+ *
973
+ * @example
974
+ * // With Bun
975
+ * import { createApp } from './.gkm/server/app.js';
976
+ *
977
+ * const { app, start } = await createApp();
978
+ *
979
+ * await start({
980
+ * port: 3000,
981
+ * serve: (app, port) => {
982
+ * Bun.serve({ port, fetch: app.fetch });
983
+ * }
984
+ * });
985
+ *
986
+ * @example
987
+ * // With Node.js (using @hono/node-server)
988
+ * import { serve } from '@hono/node-server';
989
+ * import { createApp } from './.gkm/server/app.js';
990
+ *
991
+ * const { app, start } = await createApp();
992
+ *
993
+ * await start({
994
+ * port: 3000,
995
+ * serve: (app, port) => {
996
+ * serve({ fetch: app.fetch, port });
997
+ * }
998
+ * });
999
+ */
1000
+ export async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {
1001
+ const honoApp = app || new Hono();
1002
+ ${telescopeSetup}${beforeSetupCall}${studioSetup}
1003
+ // Setup HTTP endpoints
1004
+ await setupEndpoints(honoApp, envParser, logger, enableOpenApi);
1005
+ ${afterSetupCall}
1006
+
1007
+ return {
1008
+ app: honoApp,
1009
+ async start(options) {
1010
+ if (!options?.serve) {
1011
+ throw new Error(
1012
+ 'serve function is required. Pass a serve function for your runtime:\\n' +
1013
+ ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
1014
+ ' - Node: (app, port) => serve({ fetch: app.fetch, port })'
1015
+ );
1016
+ }
1017
+
1018
+ const port = options.port ?? 3000;
1019
+
1020
+ // Start subscribers in background (non-blocking, local development only)
1021
+ await setupSubscribers(envParser, logger).catch((error) => {
1022
+ logger.error({ error }, 'Failed to start subscribers');
1023
+ });
1024
+
1025
+ // Start queue workers in background (non-blocking, local development only)
1026
+ await setupQueues(envParser, logger).catch((error) => {
1027
+ logger.error({ error }, 'Failed to start queue workers');
1028
+ });
1029
+
1030
+ logger.info({ port }, 'Starting server');
1031
+
1032
+ // Start HTTP server using provided serve function
1033
+ await options.serve(honoApp, port);
1034
+
1035
+ logger.info({ port }, 'Server started');
1036
+ }
1037
+ };
1038
+ }
1039
+
1040
+ // Default export for convenience
1041
+ export default createApp;
1042
+ `;
1043
+ await (0, node_fs_promises.writeFile)(appPath, content);
1044
+ return appPath;
1045
+ }
1046
+ generateAWSApiGatewayV1Handler(importPath, exportName, envParserPath, envParserImportPattern) {
1047
+ return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';
1048
+ import { ${exportName} } from '${importPath}';
1049
+ import ${envParserImportPattern} from '${envParserPath}';
1050
+
1051
+ const adapter = new AmazonApiGatewayV1Endpoint(envParser, ${exportName});
1052
+
1053
+ export const handler = adapter.handler;
1054
+ `;
1055
+ }
1056
+ generateAWSApiGatewayV2Handler(importPath, exportName, envParserPath, envParserImportPattern) {
1057
+ return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';
1058
+ import { ${exportName} } from '${importPath}';
1059
+ import ${envParserImportPattern} from '${envParserPath}';
1060
+
1061
+ const adapter = new AmazonApiGatewayV2Endpoint(envParser, ${exportName});
1062
+
1063
+ export const handler = adapter.handler;
1064
+ `;
1065
+ }
1066
+ generateServerHandler(importPath, exportName) {
1067
+ return `import { ${exportName} } from '${importPath}';
1068
+
1069
+ // Server handler - implement based on your server framework
1070
+ export const handler = ${exportName};
1071
+ `;
1072
+ }
1073
+ /**
1074
+ * Generate a production-optimized app.ts file
1075
+ * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown
1076
+ */
1077
+ async generateProductionAppFile(outputDir, context) {
1078
+ const appFileName = "app.ts";
1079
+ const appPath = (0, node_path.join)(outputDir, appFileName);
1080
+ const relativeLoggerPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.loggerPath);
1081
+ const relativeEnvParserPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.envParserPath);
1082
+ const production = context.production;
1083
+ const healthCheckPath = production.healthCheck;
1084
+ const enableGracefulShutdown = production.gracefulShutdown;
1085
+ const enableOpenApi = production.openapi;
1086
+ const includeSubscribers = production.subscribers === "include";
1087
+ let hooksImports = "";
1088
+ let beforeSetupCall = "";
1089
+ let afterSetupCall = "";
1090
+ if (context.hooks?.serverHooksPath) {
1091
+ const relativeHooksPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.hooks.serverHooksPath);
1092
+ hooksImports = `import * as serverHooks from '${relativeHooksPath}';`;
1093
+ beforeSetupCall = `
1094
+ // Call beforeSetup hook if defined
1095
+ if (typeof serverHooks.beforeSetup === 'function') {
1096
+ await serverHooks.beforeSetup(honoApp, { envParser, logger });
1097
+ }
1098
+ `;
1099
+ afterSetupCall = `
1100
+ // Call afterSetup hook if defined
1101
+ if (typeof serverHooks.afterSetup === 'function') {
1102
+ await serverHooks.afterSetup(honoApp, { envParser, logger });
1103
+ }
1104
+ `;
1105
+ }
1106
+ const subscriberSetup = includeSubscribers ? `
1107
+ // Start subscribers in background
1108
+ await setupSubscribers(envParser, logger).catch((error) => {
1109
+ logger.error({ error }, 'Failed to start subscribers');
1110
+ });
1111
+
1112
+ // Start queue workers in background
1113
+ await setupQueues(envParser, logger).catch((error) => {
1114
+ logger.error({ error }, 'Failed to start queue workers');
1115
+ });
1116
+ ` : "";
1117
+ const subscriberImport = includeSubscribers ? `import { setupSubscribers } from './subscribers.js';
1118
+ import { setupQueues } from './queues.js';` : "";
1119
+ const gracefulShutdownCode = enableGracefulShutdown ? `
1120
+ // Graceful shutdown handling
1121
+ let isShuttingDown = false;
1122
+
1123
+ const shutdown = async () => {
1124
+ if (isShuttingDown) return;
1125
+ isShuttingDown = true;
1126
+ logger.info('Graceful shutdown initiated');
1127
+ // Allow in-flight requests to complete (30s timeout)
1128
+ setTimeout(() => process.exit(0), 30000);
1129
+ };
1130
+
1131
+ process.on('SIGTERM', shutdown);
1132
+ process.on('SIGINT', shutdown);
1133
+ ` : "";
1134
+ const endpointsImportPath = production.optimizedHandlers ? "./endpoints/index.js" : "./endpoints.js";
1135
+ const content = `/**
1136
+ * Generated production server application
1137
+ *
1138
+ * This is a production-optimized build without dev tools.
1139
+ * - No Telescope debugging dashboard
1140
+ * - No Studio database browser
1141
+ * - No WebSocket updates
1142
+ * - Includes health checks and graceful shutdown
1143
+ */
1144
+ import { Hono } from 'hono';
1145
+ import type { Hono as HonoType } from 'hono';
1146
+ import { setupEndpoints } from '${endpointsImportPath}';
1147
+ ${subscriberImport}
1148
+ import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
1149
+ import ${context.loggerImportPattern} from '${relativeLoggerPath}';
1150
+ ${hooksImports}
1151
+
1152
+ export interface ServerApp {
1153
+ app: HonoType;
1154
+ start: (options?: {
1155
+ port?: number;
1156
+ serve: (app: HonoType, port: number) => void | Promise<void>;
1157
+ }) => Promise<void>;
1158
+ }
1159
+
1160
+ /**
1161
+ * Create and configure the production Hono application
1162
+ */
1163
+ export async function createApp(app?: HonoType): Promise<ServerApp> {
1164
+ const honoApp = app || new Hono();
1165
+
1166
+ // Health check endpoint (always first)
1167
+ honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));
1168
+ honoApp.get('/ready', (c) => c.json({ ready: true }));
1169
+ ${beforeSetupCall}
1170
+ // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})
1171
+ await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});
1172
+ ${afterSetupCall}
1173
+ return {
1174
+ app: honoApp,
1175
+ async start(options) {
1176
+ if (!options?.serve) {
1177
+ throw new Error(
1178
+ 'serve function is required. Pass a serve function for your runtime:\\n' +
1179
+ ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
1180
+ ' - Node: (app, port) => serve({ fetch: app.fetch, port })'
1181
+ );
1182
+ }
1183
+
1184
+ const port = options.port ?? Number(process.env.PORT) ?? 3000;
1185
+ ${gracefulShutdownCode}${subscriberSetup}
1186
+ logger.info({ port }, 'Starting production server');
1187
+
1188
+ // Start HTTP server using provided serve function
1189
+ await options.serve(honoApp, port);
1190
+
1191
+ logger.info({ port }, 'Production server started');
1192
+ }
1193
+ };
1194
+ }
1195
+
1196
+ // Default export for convenience
1197
+ export default createApp;
1198
+ `;
1199
+ await (0, node_fs_promises.writeFile)(appPath, content);
1200
+ await this.generateProductionServerEntry(outputDir);
1201
+ return appPath;
1202
+ }
1203
+ /**
1204
+ * Generate production server.ts entry point
1205
+ */
1206
+ async generateProductionServerEntry(outputDir) {
1207
+ const serverPath = (0, node_path.join)(outputDir, "server.ts");
1208
+ const content = `#!/usr/bin/env node
1209
+ /**
1210
+ * Production server entry point
1211
+ * Generated by 'gkm build --provider server --production'
1212
+ */
1213
+ import { serve } from '@hono/node-server';
1214
+ import { createApp } from './app.js';
1215
+
1216
+ const port = Number(process.env.PORT) || 3000;
1217
+
1218
+ const { start } = await createApp();
1219
+
1220
+ await start({
1221
+ port,
1222
+ serve: (app, port) => { serve({ fetch: app.fetch, port }); },
1223
+ });
1224
+ `;
1225
+ await (0, node_fs_promises.writeFile)(serverPath, content);
1226
+ }
1227
+ };
1228
+
1229
+ //#endregion
1230
+ //#region src/generators/OpenApiTsGenerator.ts
1231
+ /**
1232
+ * Generates TypeScript OpenAPI module from endpoints.
1233
+ * Outputs:
1234
+ * - securitySchemes: typed security scheme definitions
1235
+ * - endpointAuth: runtime map of endpoints to auth requirements
1236
+ * - paths: TypeScript interface for type-safe fetcher
1237
+ * - schema interfaces: reusable TypeScript types from Zod/Valibot schemas
1238
+ */
1239
+ var OpenApiTsGenerator = class {
1240
+ async generate(endpoints, options = {}) {
1241
+ const { title = "API", version = "1.0.0", description } = options;
1242
+ const endpointInfos = await this.extractEndpointInfos(endpoints);
1243
+ const securitySchemes = this.collectSecuritySchemes(endpointInfos);
1244
+ const endpointAuth = this.buildEndpointAuthMap(endpointInfos);
1245
+ const schemaInterfaces = await this.generateSchemaInterfaces(endpointInfos);
1246
+ const pathsInterface = await this.generatePathsInterface(endpointInfos);
1247
+ return this.buildModule({
1248
+ title,
1249
+ version,
1250
+ description,
1251
+ securitySchemes,
1252
+ endpointAuth,
1253
+ schemaInterfaces,
1254
+ pathsInterface
1255
+ });
1256
+ }
1257
+ async extractEndpointInfos(endpoints) {
1258
+ return endpoints.map((ep) => {
1259
+ const route = ep.route.replace(/:(\w+)/g, "{$1}");
1260
+ const method = ep.method.toUpperCase();
1261
+ const securityScheme = ep.authorizer?.securityScheme;
1262
+ return {
1263
+ endpoint: `${method} ${route}`,
1264
+ route,
1265
+ method,
1266
+ authorizerName: ep.authorizer?.name ?? null,
1267
+ authorizerType: ep.authorizer?.type ?? null,
1268
+ securityScheme: securityScheme ?? null,
1269
+ input: ep.input,
1270
+ output: ep.outputSchema,
1271
+ description: ep.description,
1272
+ tags: ep.tags,
1273
+ operationId: ep.operationId,
1274
+ responseType: ep.responseType ?? "application/json"
1275
+ };
1276
+ });
1277
+ }
1278
+ collectSecuritySchemes(endpointInfos) {
1279
+ const schemes = /* @__PURE__ */ new Map();
1280
+ for (const info of endpointInfos) if (info.authorizerName && !schemes.has(info.authorizerName)) {
1281
+ const scheme = info.securityScheme ?? (info.authorizerType ? this.mapAuthorizerToSecurityScheme(info.authorizerType, info.authorizerName) : null);
1282
+ if (scheme) schemes.set(info.authorizerName, {
1283
+ name: info.authorizerName,
1284
+ type: scheme.type,
1285
+ scheme
1286
+ });
1287
+ }
1288
+ return Array.from(schemes.values());
1289
+ }
1290
+ mapAuthorizerToSecurityScheme(type, _name) {
1291
+ switch (type.toLowerCase()) {
1292
+ case "jwt":
1293
+ case "bearer": return {
1294
+ type: "http",
1295
+ scheme: "bearer",
1296
+ bearerFormat: "JWT"
1297
+ };
1298
+ case "iam":
1299
+ case "aws-sigv4":
1300
+ case "sigv4": return {
1301
+ type: "apiKey",
1302
+ in: "header",
1303
+ name: "Authorization",
1304
+ "x-amazon-apigateway-authtype": "awsSigv4"
1305
+ };
1306
+ case "apikey":
1307
+ case "api-key": return {
1308
+ type: "apiKey",
1309
+ in: "header",
1310
+ name: "X-API-Key"
1311
+ };
1312
+ case "oauth2": return {
1313
+ type: "oauth2",
1314
+ flows: {}
1315
+ };
1316
+ case "oidc":
1317
+ case "openidconnect": return {
1318
+ type: "openIdConnect",
1319
+ openIdConnectUrl: ""
1320
+ };
1321
+ default: return {
1322
+ type: "http",
1323
+ scheme: "bearer"
1324
+ };
1325
+ }
1326
+ }
1327
+ buildEndpointAuthMap(endpointInfos) {
1328
+ const authMap = {};
1329
+ for (const info of endpointInfos) authMap[info.endpoint] = info.authorizerName;
1330
+ return authMap;
1331
+ }
1332
+ async generateSchemaInterfaces(endpointInfos) {
1333
+ const interfaces = [];
1334
+ const generatedNames = /* @__PURE__ */ new Set();
1335
+ const collectedDefs = /* @__PURE__ */ new Map();
1336
+ for (const info of endpointInfos) {
1337
+ const baseName = this.getSchemaBaseName(info);
1338
+ if (info.input?.body) {
1339
+ const name = await this.getSchemaName(info.input.body, `${baseName}Input`);
1340
+ if (!generatedNames.has(name)) {
1341
+ const schema = await this.schemaToInterfaceWithDefs(info.input.body, name, collectedDefs);
1342
+ if (schema) {
1343
+ interfaces.push(schema);
1344
+ generatedNames.add(name);
1345
+ }
1346
+ }
1347
+ }
1348
+ if (info.input?.params) {
1349
+ const name = await this.getSchemaName(info.input.params, `${baseName}Params`);
1350
+ if (!generatedNames.has(name)) {
1351
+ const schema = await this.schemaToInterfaceWithDefs(info.input.params, name, collectedDefs);
1352
+ if (schema) {
1353
+ interfaces.push(schema);
1354
+ generatedNames.add(name);
1355
+ }
1356
+ }
1357
+ }
1358
+ if (info.input?.query) {
1359
+ const name = await this.getSchemaName(info.input.query, `${baseName}Query`);
1360
+ if (!generatedNames.has(name)) {
1361
+ const schema = await this.schemaToInterfaceWithDefs(info.input.query, name, collectedDefs);
1362
+ if (schema) {
1363
+ interfaces.push(schema);
1364
+ generatedNames.add(name);
1365
+ }
1366
+ }
1367
+ }
1368
+ if (info.output) {
1369
+ const name = await this.getSchemaName(info.output, `${baseName}Output`);
1370
+ if (!generatedNames.has(name)) {
1371
+ const schema = await this.schemaToInterfaceWithDefs(info.output, name, collectedDefs);
1372
+ if (schema) {
1373
+ interfaces.push(schema);
1374
+ generatedNames.add(name);
1375
+ }
1376
+ }
1377
+ }
1378
+ }
1379
+ const registrySchemas = await (0, __geekmidas_schema_conversion.getRegisteredZodJsonSchemas)();
1380
+ for (const [rawName, rawSchema] of Object.entries(registrySchemas)) {
1381
+ const defName = this.pascalCase(rawName);
1382
+ if (collectedDefs.has(defName) || generatedNames.has(defName)) continue;
1383
+ const { id: _id, $defs: _defs,...rest } = rawSchema;
1384
+ collectedDefs.set(defName, rest);
1385
+ }
1386
+ for (const [defName, defSchema] of collectedDefs) if (!generatedNames.has(defName)) {
1387
+ const interfaceStr = this.jsonSchemaToInterface(defSchema, defName);
1388
+ interfaces.push(interfaceStr);
1389
+ generatedNames.add(defName);
1390
+ }
1391
+ return interfaces.join("\n\n");
1392
+ }
1393
+ /**
1394
+ * Get the name for a schema, using metadata `id` if available,
1395
+ * otherwise falling back to the provided default name.
1396
+ */
1397
+ async getSchemaName(schema, defaultName) {
1398
+ try {
1399
+ const metadata = await (0, __geekmidas_schema_conversion.getSchemaMetadata)(schema);
1400
+ if (metadata?.id) return this.pascalCase(metadata.id);
1401
+ } catch {}
1402
+ return defaultName;
1403
+ }
1404
+ getSchemaBaseName(info) {
1405
+ if (info.operationId) return this.pascalCase(info.operationId);
1406
+ const routeParts = info.route.replace(/[{}]/g, "").split("/").filter(Boolean).map((part) => this.pascalCase(part));
1407
+ return `${this.pascalCase(info.method.toLowerCase())}${routeParts.join("")}`;
1408
+ }
1409
+ pascalCase(str) {
1410
+ return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toUpperCase());
1411
+ }
1412
+ /**
1413
+ * Convert schema to interface while collecting $defs for nested schemas
1414
+ * with .meta({ id: 'X' }).
1415
+ */
1416
+ async schemaToInterfaceWithDefs(schema, name, collectedDefs) {
1417
+ try {
1418
+ const vendor = schema["~standard"]?.vendor;
1419
+ if (!vendor || !(vendor in __geekmidas_schema_conversion.StandardSchemaJsonSchema)) return null;
1420
+ const toJsonSchema = __geekmidas_schema_conversion.StandardSchemaJsonSchema[vendor];
1421
+ const jsonSchema = await toJsonSchema(schema);
1422
+ if (!jsonSchema) return null;
1423
+ if (jsonSchema.$defs && typeof jsonSchema.$defs === "object") {
1424
+ for (const [defName, defSchema] of Object.entries(jsonSchema.$defs)) if (!collectedDefs.has(defName)) {
1425
+ const { id,...schemaWithoutId } = defSchema;
1426
+ collectedDefs.set(defName, schemaWithoutId);
1427
+ }
1428
+ }
1429
+ const { $defs,...schemaWithoutDefs } = jsonSchema;
1430
+ return this.jsonSchemaToInterface(schemaWithoutDefs, name);
1431
+ } catch {
1432
+ return null;
1433
+ }
1434
+ }
1435
+ jsonSchemaToInterface(schema, name) {
1436
+ if (schema.type !== "object" || !schema.properties) {
1437
+ const typeStr = this.jsonSchemaTypeToTs(schema);
1438
+ return `export type ${name} = ${typeStr};`;
1439
+ }
1440
+ const props = [];
1441
+ const required = new Set(schema.required || []);
1442
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
1443
+ const isRequired = required.has(propName);
1444
+ const typeStr = this.jsonSchemaTypeToTs(propSchema);
1445
+ const optionalMark = isRequired ? "" : "?";
1446
+ props.push(` ${propName}${optionalMark}: ${typeStr};`);
1447
+ }
1448
+ return `export interface ${name} {\n${props.join("\n")}\n}`;
1449
+ }
1450
+ jsonSchemaTypeToTs(schema) {
1451
+ if (!schema) return "unknown";
1452
+ if (schema.$ref) {
1453
+ const refName = schema.$ref.split("/").pop() || "unknown";
1454
+ return refName;
1455
+ }
1456
+ if (schema.anyOf) return schema.anyOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" | ");
1457
+ if (schema.oneOf) return schema.oneOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" | ");
1458
+ if (schema.allOf) return schema.allOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" & ");
1459
+ switch (schema.type) {
1460
+ case "string":
1461
+ if (schema.enum) return schema.enum.map((e) => `'${e}'`).join(" | ");
1462
+ return "string";
1463
+ case "number":
1464
+ case "integer": return "number";
1465
+ case "boolean": return "boolean";
1466
+ case "null": return "null";
1467
+ case "array":
1468
+ if (schema.items) return `Array<${this.jsonSchemaTypeToTs(schema.items)}>`;
1469
+ return "Array<unknown>";
1470
+ case "object":
1471
+ if (schema.properties) {
1472
+ const props = [];
1473
+ const required = new Set(schema.required || []);
1474
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
1475
+ const isRequired = required.has(propName);
1476
+ const typeStr = this.jsonSchemaTypeToTs(propSchema);
1477
+ const optionalMark = isRequired ? "" : "?";
1478
+ props.push(`${propName}${optionalMark}: ${typeStr}`);
1479
+ }
1480
+ return `{ ${props.join("; ")} }`;
1481
+ }
1482
+ if (schema.additionalProperties) {
1483
+ const valueType = this.jsonSchemaTypeToTs(schema.additionalProperties);
1484
+ return `Record<string, ${valueType}>`;
1485
+ }
1486
+ return "Record<string, unknown>";
1487
+ default: return "unknown";
1488
+ }
1489
+ }
1490
+ async generatePathsInterface(endpointInfos) {
1491
+ const pathGroups = /* @__PURE__ */ new Map();
1492
+ for (const info of endpointInfos) {
1493
+ const existing = pathGroups.get(info.route) || [];
1494
+ existing.push(info);
1495
+ pathGroups.set(info.route, existing);
1496
+ }
1497
+ const pathEntries = [];
1498
+ for (const [route, infos] of pathGroups) {
1499
+ const methodEntries = [];
1500
+ for (const info of infos) {
1501
+ const methodDef = await this.generateMethodDefinition(info);
1502
+ methodEntries.push(` ${info.method.toLowerCase()}: ${methodDef};`);
1503
+ }
1504
+ const firstWithParams = infos.find((i) => i.input?.params);
1505
+ let paramsEntry = "";
1506
+ if (firstWithParams?.input?.params) {
1507
+ const paramsName = await this.getSchemaName(firstWithParams.input.params, `${this.getSchemaBaseName(firstWithParams)}Params`);
1508
+ paramsEntry = `\n parameters: {\n path: ${paramsName};\n };`;
1509
+ }
1510
+ pathEntries.push(` '${route}': {${paramsEntry}\n${methodEntries.join("\n")}\n };`);
1511
+ }
1512
+ return `export interface paths {\n${pathEntries.join("\n")}\n}`;
1513
+ }
1514
+ async generateMethodDefinition(info) {
1515
+ const parts = [];
1516
+ const baseName = this.getSchemaBaseName(info);
1517
+ if (info.input?.body) {
1518
+ const bodyName = await this.getSchemaName(info.input.body, `${baseName}Input`);
1519
+ parts.push(`requestBody: {
1520
+ content: {
1521
+ 'application/json': ${bodyName};
1522
+ };
1523
+ }`);
1524
+ }
1525
+ if (info.input?.query) {
1526
+ const queryName = await this.getSchemaName(info.input.query, `${baseName}Query`);
1527
+ parts.push(`parameters: {
1528
+ query: ${queryName};
1529
+ }`);
1530
+ }
1531
+ const outputName = info.output ? await this.getSchemaName(info.output, `${baseName}Output`) : "unknown";
1532
+ parts.push(`responses: {
1533
+ 200: {
1534
+ content: {
1535
+ '${info.responseType}': ${outputName};
1536
+ };
1537
+ };
1538
+ }`);
1539
+ return `{\n ${parts.join(";\n ")};\n }`;
1540
+ }
1541
+ buildModule(params) {
1542
+ const { title, version, description, securitySchemes, endpointAuth, schemaInterfaces, pathsInterface } = params;
1543
+ const securitySchemesObj = securitySchemes.reduce((acc, s) => {
1544
+ acc[s.name] = s.scheme;
1545
+ return acc;
1546
+ }, {});
1547
+ const schemeNames = securitySchemes.map((s) => `'${s.name}'`).join(" | ");
1548
+ const hasSecuritySchemes = schemeNames.length > 0;
1549
+ const createApiSection = hasSecuritySchemes ? `
1550
+ // ============================================================
1551
+ // API Client Factory
1552
+ // ============================================================
1553
+
1554
+ import {
1555
+ createAuthAwareFetcher,
1556
+ type AuthStrategy,
1557
+ } from '@geekmidas/client/auth-fetcher';
1558
+ import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
1559
+ import type { QueryClient } from '@tanstack/react-query';
1560
+
1561
+ /**
1562
+ * Options for creating the API client.
1563
+ */
1564
+ export interface CreateApiOptions {
1565
+ /** Base URL for all API requests (required) */
1566
+ baseURL: string;
1567
+ /** Auth strategies for each security scheme used in this API */
1568
+ authStrategies: Record<SecuritySchemeId, AuthStrategy>;
1569
+ /** Optional React Query client instance */
1570
+ queryClient?: QueryClient;
1571
+ /** Optional request interceptor */
1572
+ onRequest?: (config: RequestInit) => RequestInit | Promise<RequestInit>;
1573
+ }
1574
+
1575
+ /**
1576
+ * Create a type-safe API client with authentication and React Query hooks.
1577
+ *
1578
+ * @example
1579
+ * \`\`\`typescript
1580
+ * const api = createApi({
1581
+ * baseURL: 'https://api.example.com',
1582
+ * authStrategies: {
1583
+ * jwt: { type: 'bearer', tokenProvider },
1584
+ * },
1585
+ * });
1586
+ *
1587
+ * // Imperative fetch
1588
+ * const user = await api('GET /users/{id}', { params: { id: '123' } });
1589
+ *
1590
+ * // React Query hooks
1591
+ * const { data } = api.useQuery('GET /users/{id}', { params: { id: '123' } });
1592
+ * const mutation = api.useMutation('POST /users');
1593
+ * \`\`\`
1594
+ */
1595
+ export function createApi(options: CreateApiOptions) {
1596
+ const fetcher = createAuthAwareFetcher<paths, typeof endpointAuth, typeof securitySchemes>({
1597
+ baseURL: options.baseURL,
1598
+ endpointAuth,
1599
+ securitySchemes,
1600
+ authStrategies: options.authStrategies,
1601
+ onRequest: options.onRequest,
1602
+ });
1603
+
1604
+ const hooks = createEndpointHooks<paths>(fetcher, { queryClient: options.queryClient });
1605
+
1606
+ return Object.assign(fetcher, hooks);
1607
+ }
1608
+ ` : `
1609
+ // ============================================================
1610
+ // API Client Factory
1611
+ // ============================================================
1612
+
1613
+ import { createTypedFetcher, type FetcherOptions } from '@geekmidas/client/fetcher';
1614
+ import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
1615
+ import type { QueryClient } from '@tanstack/react-query';
1616
+
1617
+ /**
1618
+ * Options for creating the API client.
1619
+ */
1620
+ export interface CreateApiOptions extends Omit<FetcherOptions, 'baseURL'> {
1621
+ /** Base URL for all API requests (required) */
1622
+ baseURL: string;
1623
+ /** Optional React Query client instance */
1624
+ queryClient?: QueryClient;
1625
+ }
1626
+
1627
+ /**
1628
+ * Create a type-safe API client with React Query hooks.
1629
+ *
1630
+ * @example
1631
+ * \`\`\`typescript
1632
+ * const api = createApi({
1633
+ * baseURL: 'https://api.example.com',
1634
+ * });
1635
+ *
1636
+ * // Imperative fetch
1637
+ * const data = await api('GET /health');
1638
+ *
1639
+ * // React Query hooks
1640
+ * const { data } = api.useQuery('GET /health');
1641
+ * \`\`\`
1642
+ */
1643
+ export function createApi(options: CreateApiOptions) {
1644
+ const { queryClient, ...fetcherOptions } = options;
1645
+ const request = createTypedFetcher<paths>(fetcherOptions);
1646
+
1647
+ const hooks = createEndpointHooks<paths>(request, { queryClient });
1648
+
1649
+ return Object.assign(request, hooks);
1650
+ }
1651
+ `;
1652
+ return `// Auto-generated by @geekmidas/cli - DO NOT EDIT
1653
+
1654
+ // ============================================================
1655
+ // Security Scheme Type
1656
+ // ============================================================
1657
+
1658
+ interface SecuritySchemeObject {
1659
+ type: 'apiKey' | 'http' | 'mutualTLS' | 'oauth2' | 'openIdConnect';
1660
+ description?: string;
1661
+ name?: string;
1662
+ in?: 'query' | 'header' | 'cookie';
1663
+ scheme?: string;
1664
+ bearerFormat?: string;
1665
+ flows?: Record<string, unknown>;
1666
+ openIdConnectUrl?: string;
1667
+ [key: string]: unknown;
1668
+ }
1669
+
1670
+ // ============================================================
1671
+ // API Info
1672
+ // ============================================================
1673
+
1674
+ export const apiInfo = {
1675
+ title: '${title}',
1676
+ version: '${version}',${description ? `\n description: '${description.replace(/'/g, "\\'")}',` : ""}
1677
+ } as const;
1678
+
1679
+ // ============================================================
1680
+ // Security Schemes
1681
+ // ============================================================
1682
+
1683
+ /**
1684
+ * Available security schemes for this API.
1685
+ * Maps authorizer names to OpenAPI security scheme definitions.
1686
+ */
1687
+ export const securitySchemes = ${JSON.stringify(securitySchemesObj, null, 2).replace(/"([a-zA-Z_$][a-zA-Z0-9_$]*)":/g, "$1:")} as const satisfies Record<string, SecuritySchemeObject>;
1688
+
1689
+ export type SecuritySchemeId = ${schemeNames || "never"};
1690
+
1691
+ // ============================================================
1692
+ // Endpoint Authentication Map
1693
+ // ============================================================
1694
+
1695
+ /**
1696
+ * Runtime map of endpoints to their required authentication scheme.
1697
+ * \`null\` indicates a public endpoint (no auth required).
1698
+ */
1699
+ export const endpointAuth = ${JSON.stringify(endpointAuth, null, 2).replace(/"([^"]+)":/g, "'$1':")} as const satisfies Record<string, SecuritySchemeId | null>;
1700
+
1701
+ export type EndpointString = keyof typeof endpointAuth;
1702
+
1703
+ export type AuthenticatedEndpoint = {
1704
+ [K in EndpointString]: typeof endpointAuth[K] extends null ? never : K;
1705
+ }[EndpointString];
1706
+
1707
+ export type PublicEndpoint = {
1708
+ [K in EndpointString]: typeof endpointAuth[K] extends null ? K : never;
1709
+ }[EndpointString];
1710
+
1711
+ // ============================================================
1712
+ // Schema Definitions
1713
+ // ============================================================
1714
+
1715
+ ${schemaInterfaces}
1716
+
1717
+ // ============================================================
1718
+ // OpenAPI Paths
1719
+ // ============================================================
1720
+
1721
+ ${pathsInterface}
1722
+ ${createApiSection}
1723
+ `;
1724
+ }
1725
+ };
1726
+
1727
+ //#endregion
1728
+ //#region src/workspace/client-generator.ts
1729
+ /**
1730
+ * Normalize routes to an array of patterns.
1731
+ * Handles string, string[], and PartitionedRoutes (extracts paths).
1732
+ * @internal Exported for use in dev command
1733
+ */
1734
+ function normalizeRoutes(routes) {
1735
+ if (!routes) return [];
1736
+ if (isPartitionedRoutes(routes)) return Array.isArray(routes.paths) ? routes.paths : [routes.paths];
1737
+ return Array.isArray(routes) ? routes : [routes];
1738
+ }
1739
+
1740
+ //#endregion
1741
+ //#region src/openapi.ts
1742
+ /**
1743
+ * Default output path for generated OpenAPI client (used for single-app configs)
1744
+ */
1745
+ const OPENAPI_OUTPUT_PATH = "./.gkm/openapi.ts";
1746
+ /**
1747
+ * Resolve OpenAPI config from GkmConfig
1748
+ */
1749
+ function resolveOpenApiConfig(config) {
1750
+ if (config.openapi === false) return { enabled: false };
1751
+ if (config.openapi === true || config.openapi === void 0) return {
1752
+ enabled: true,
1753
+ title: "API Documentation",
1754
+ version: "1.0.0",
1755
+ description: "Auto-generated API documentation from endpoints"
1756
+ };
1757
+ return {
1758
+ enabled: config.openapi.enabled !== false,
1759
+ title: config.openapi.title || "API Documentation",
1760
+ version: config.openapi.version || "1.0.0",
1761
+ description: config.openapi.description || "Auto-generated API documentation from endpoints"
1762
+ };
1763
+ }
1764
+ /**
1765
+ * Generate OpenAPI spec from endpoints
1766
+ * @returns Object with output path and endpoint count, or null if disabled
1767
+ */
1768
+ async function generateOpenApi(config, options = {}) {
1769
+ const logger = options.silent ? { log: () => {} } : console;
1770
+ const openApiConfig = resolveOpenApiConfig(config);
1771
+ if (!openApiConfig.enabled) return null;
1772
+ const endpointGenerator = new EndpointGenerator();
1773
+ const loadedEndpoints = await endpointGenerator.load(config.routes, void 0, options.bustCache);
1774
+ if (loadedEndpoints.length === 0) {
1775
+ logger.log("No valid endpoints found for OpenAPI generation");
1776
+ return null;
1777
+ }
1778
+ const endpoints = loadedEndpoints.map(({ construct }) => construct);
1779
+ const outputPath = (0, node_path.join)(process.cwd(), OPENAPI_OUTPUT_PATH);
1780
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(outputPath), { recursive: true });
1781
+ const tsGenerator = new OpenApiTsGenerator();
1782
+ const tsContent = await tsGenerator.generate(endpoints, {
1783
+ title: openApiConfig.title,
1784
+ version: openApiConfig.version,
1785
+ description: openApiConfig.description
1786
+ });
1787
+ await (0, node_fs_promises.writeFile)(outputPath, tsContent);
1788
+ logger.log(`📄 OpenAPI client generated: ${OPENAPI_OUTPUT_PATH}`);
1789
+ return {
1790
+ outputPath,
1791
+ endpointCount: loadedEndpoints.length
1792
+ };
1793
+ }
1794
+ async function openapiCommand(options = {}) {
1795
+ const logger = console;
1796
+ try {
1797
+ const loadedConfig = await require_config.loadWorkspaceConfig(options.cwd);
1798
+ if (loadedConfig.type === "single") {
1799
+ const config = loadedConfig.raw;
1800
+ if (!config.openapi) config.openapi = { enabled: true };
1801
+ const result = await generateOpenApi(config);
1802
+ if (result) logger.log(`Found ${result.endpointCount} endpoints`);
1803
+ } else {
1804
+ const { workspace } = loadedConfig;
1805
+ const workspaceRoot = workspace.root;
1806
+ const backendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "backend" && (app.openapi === true || typeof app.openapi === "object" && app.openapi.enabled !== false));
1807
+ if (backendApps.length === 0) {
1808
+ logger.log("No backend apps with OpenAPI enabled found");
1809
+ return;
1810
+ }
1811
+ if (options.app) {
1812
+ const entry = backendApps.find(([name]) => name === options.app);
1813
+ if (!entry) throw new Error(`App "${options.app}" not found or has OpenAPI disabled`);
1814
+ const [appName, app] = entry;
1815
+ const result = await generateOpenApiForApp(workspaceRoot, appName, app);
1816
+ if (result) logger.log(`📄 [${appName}] Generated OpenAPI (${result.endpointCount} endpoints)`);
1817
+ return;
1818
+ }
1819
+ for (const [appName, app] of backendApps) {
1820
+ if (app.type !== "backend" || !app.routes) continue;
1821
+ const appPath = (0, node_path.join)(workspaceRoot, app.path);
1822
+ await runOpenApiInSubprocess(appPath, appName);
1823
+ }
1824
+ }
1825
+ } catch (error) {
1826
+ throw new Error(`OpenAPI generation failed: ${error.message}`);
1827
+ }
1828
+ }
1829
+ /**
1830
+ * Generate OpenAPI for a single named app within a workspace.
1831
+ * Runs in-process. The caller is responsible for ensuring `process.cwd()`
1832
+ * is the app's directory so tsx loads the app's tsconfig path aliases.
1833
+ */
1834
+ async function generateOpenApiForApp(workspaceRoot, _appName, app) {
1835
+ if (app.type !== "backend" || !app.routes) return null;
1836
+ const appPath = (0, node_path.join)(workspaceRoot, app.path);
1837
+ const routes = normalizeRoutes(app.routes);
1838
+ const routesGlob = routes.map((r) => (0, node_path.join)(appPath, r));
1839
+ const gkmConfig = {
1840
+ routes: routesGlob,
1841
+ envParser: app.envParser || "",
1842
+ logger: app.logger || "",
1843
+ openapi: app.openapi
1844
+ };
1845
+ return generateOpenApi(gkmConfig, { silent: true });
1846
+ }
1847
+ /**
1848
+ * Resolve the gkm bin path. Tests can override via `GKM_BIN_PATH` env var
1849
+ * to avoid depending on the built dist.
1850
+ */
1851
+ function resolveGkmBinPath() {
1852
+ if (process.env.GKM_BIN_PATH) return process.env.GKM_BIN_PATH;
1853
+ return (0, node_url.fileURLToPath)(new URL("../bin/gkm.mjs", require("url").pathToFileURL(__filename).href));
1854
+ }
1855
+ /**
1856
+ * Spawn a subprocess that runs `gkm openapi --app <name>` with `cwd` set to
1857
+ * the app's directory. Inherits `NODE_OPTIONS` (which already contains
1858
+ * `--import tsx`), so the child gets a fresh tsx instance whose tsconfig
1859
+ * discovery picks up the app's tsconfig path aliases.
1860
+ */
1861
+ async function runOpenApiInSubprocess(appCwd, appName) {
1862
+ const binPath = resolveGkmBinPath();
1863
+ await new Promise((resolve, reject) => {
1864
+ const child = (0, node_child_process.spawn)(process.execPath, [
1865
+ binPath,
1866
+ "openapi",
1867
+ "--app",
1868
+ appName
1869
+ ], {
1870
+ cwd: appCwd,
1871
+ stdio: "inherit",
1872
+ env: process.env
1873
+ });
1874
+ child.on("error", reject);
1875
+ child.on("close", (code) => {
1876
+ if (code === 0) resolve();
1877
+ else reject(new Error(`OpenAPI generation for app "${appName}" exited with code ${code}`));
1878
+ });
1879
+ });
1880
+ }
1881
+
1882
+ //#endregion
1883
+ Object.defineProperty(exports, 'ConstructGenerator', {
1884
+ enumerable: true,
1885
+ get: function () {
1886
+ return ConstructGenerator;
1887
+ }
1888
+ });
1889
+ Object.defineProperty(exports, 'EndpointGenerator', {
1890
+ enumerable: true,
1891
+ get: function () {
1892
+ return EndpointGenerator;
1893
+ }
1894
+ });
1895
+ Object.defineProperty(exports, 'OPENAPI_OUTPUT_PATH', {
1896
+ enumerable: true,
1897
+ get: function () {
1898
+ return OPENAPI_OUTPUT_PATH;
1899
+ }
1900
+ });
1901
+ Object.defineProperty(exports, 'generateOpenApi', {
1902
+ enumerable: true,
1903
+ get: function () {
1904
+ return generateOpenApi;
1905
+ }
1906
+ });
1907
+ Object.defineProperty(exports, 'isPartitionedRoutes', {
1908
+ enumerable: true,
1909
+ get: function () {
1910
+ return isPartitionedRoutes;
1911
+ }
1912
+ });
1913
+ Object.defineProperty(exports, 'normalizeRoutes', {
1914
+ enumerable: true,
1915
+ get: function () {
1916
+ return normalizeRoutes;
1917
+ }
1918
+ });
1919
+ Object.defineProperty(exports, 'openapiCommand', {
1920
+ enumerable: true,
1921
+ get: function () {
1922
+ return openapiCommand;
1923
+ }
1924
+ });
1925
+ Object.defineProperty(exports, 'resolveOpenApiConfig', {
1926
+ enumerable: true,
1927
+ get: function () {
1928
+ return resolveOpenApiConfig;
1929
+ }
1930
+ });
1931
+ //# sourceMappingURL=openapi-BzNOC7_i.cjs.map