@geekmidas/cli 10.0.0-alpha.13 → 10.0.0-alpha.130

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 (430) hide show
  1. package/README.md +313 -380
  2. package/bin/adjacent-tsconfig.mjs +46 -8
  3. package/bin/gkm.mjs +11 -3
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/EndpointGenerator-B99OGzbO.mjs +1035 -0
  7. package/dist/EndpointGenerator-B99OGzbO.mjs.map +1 -0
  8. package/dist/EndpointGenerator-De0lknKD.cjs +1094 -0
  9. package/dist/EndpointGenerator-De0lknKD.cjs.map +1 -0
  10. package/dist/GoDaddyProvider-D10Le3VX.mjs +388 -0
  11. package/dist/GoDaddyProvider-D10Le3VX.mjs.map +1 -0
  12. package/dist/GoDaddyProvider-DTfa47i3.cjs +388 -0
  13. package/dist/GoDaddyProvider-DTfa47i3.cjs.map +1 -0
  14. package/dist/{HostingerProvider-BY26bWwB.mjs → HostingerProvider-Cjh_2Ml6.mjs} +11 -6
  15. package/dist/HostingerProvider-Cjh_2Ml6.mjs.map +1 -0
  16. package/dist/{HostingerProvider-BZFGYYVA.cjs → HostingerProvider-OdQmKXE3.cjs} +11 -6
  17. package/dist/HostingerProvider-OdQmKXE3.cjs.map +1 -0
  18. package/dist/LegacyStateStore-C5c_zS4h.mjs +124 -0
  19. package/dist/LegacyStateStore-C5c_zS4h.mjs.map +1 -0
  20. package/dist/LegacyStateStore-CZSBR6ar.cjs +124 -0
  21. package/dist/LegacyStateStore-CZSBR6ar.cjs.map +1 -0
  22. package/dist/LocalStateStore-Ba0Y6q5C.mjs +167 -0
  23. package/dist/LocalStateStore-Ba0Y6q5C.mjs.map +1 -0
  24. package/dist/LocalStateStore-CgQtQix2.cjs +178 -0
  25. package/dist/LocalStateStore-CgQtQix2.cjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-DMLzN-LU.cjs +541 -0
  27. package/dist/OpenApiTsGenerator-DMLzN-LU.cjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-DNUCgkkx.mjs +536 -0
  29. package/dist/OpenApiTsGenerator-DNUCgkkx.mjs.map +1 -0
  30. package/dist/{Route53Provider-DVILBsvV.cjs → Route53Provider-Bllus2NR.cjs} +2 -2
  31. package/dist/Route53Provider-Bllus2NR.cjs.map +1 -0
  32. package/dist/{Route53Provider-Cvj40A8I.mjs → Route53Provider-QXxjkZO1.mjs} +2 -2
  33. package/dist/Route53Provider-QXxjkZO1.mjs.map +1 -0
  34. package/dist/S3StateStore-00mB2AG4.mjs +223 -0
  35. package/dist/S3StateStore-00mB2AG4.mjs.map +1 -0
  36. package/dist/S3StateStore-C6amZI39.cjs +222 -0
  37. package/dist/S3StateStore-C6amZI39.cjs.map +1 -0
  38. package/dist/SSMStateStore-CkYqOAzW.mjs +205 -0
  39. package/dist/SSMStateStore-CkYqOAzW.mjs.map +1 -0
  40. package/dist/SSMStateStore-Cnn5fHCg.cjs +204 -0
  41. package/dist/SSMStateStore-Cnn5fHCg.cjs.map +1 -0
  42. package/dist/SubscriberGenerator-0ruEmYXj.mjs +646 -0
  43. package/dist/SubscriberGenerator-0ruEmYXj.mjs.map +1 -0
  44. package/dist/SubscriberGenerator-CPjbWEOI.cjs +687 -0
  45. package/dist/SubscriberGenerator-CPjbWEOI.cjs.map +1 -0
  46. package/dist/add-CdMInvmN.cjs +719 -0
  47. package/dist/add-CdMInvmN.cjs.map +1 -0
  48. package/dist/add-DZSU5Tcc.mjs +717 -0
  49. package/dist/add-DZSU5Tcc.mjs.map +1 -0
  50. package/dist/appPorts-BoXMwolc.mjs +249 -0
  51. package/dist/appPorts-BoXMwolc.mjs.map +1 -0
  52. package/dist/appPorts-IW-OZmRi.cjs +296 -0
  53. package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
  54. package/dist/aws-8QQ8n-t6.mjs +89 -0
  55. package/dist/aws-8QQ8n-t6.mjs.map +1 -0
  56. package/dist/aws-DY9NqQIT.cjs +100 -0
  57. package/dist/aws-DY9NqQIT.cjs.map +1 -0
  58. package/dist/awsStore-Bx5nCFnS.mjs +121 -0
  59. package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
  60. package/dist/awsStore-u3ehhMoY.cjs +138 -0
  61. package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
  62. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  63. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  64. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  65. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  66. package/dist/backups/runner.cjs +519 -0
  67. package/dist/backups/runner.cjs.map +1 -0
  68. package/dist/backups/runner.d.cts +102 -0
  69. package/dist/backups/runner.d.cts.map +1 -0
  70. package/dist/backups/runner.d.mts +102 -0
  71. package/dist/backups/runner.d.mts.map +1 -0
  72. package/dist/backups/runner.mjs +506 -0
  73. package/dist/backups/runner.mjs.map +1 -0
  74. package/dist/{bundler-BodTL4kf.mjs → bundler-BzDMJbx8.mjs} +32 -11
  75. package/dist/bundler-BzDMJbx8.mjs.map +1 -0
  76. package/dist/{bundler-BeNDZdHQ.cjs → bundler-GKF4xpYI.cjs} +32 -11
  77. package/dist/bundler-GKF4xpYI.cjs.map +1 -0
  78. package/dist/cli-Ct6PQtc7.cjs +71 -0
  79. package/dist/cli-Ct6PQtc7.cjs.map +1 -0
  80. package/dist/cli-DXeLFtpA.mjs +71 -0
  81. package/dist/cli-DXeLFtpA.mjs.map +1 -0
  82. package/dist/compose-BfLDidYU.cjs +3977 -0
  83. package/dist/compose-BfLDidYU.cjs.map +1 -0
  84. package/dist/compose-CnanpQBB.mjs +3834 -0
  85. package/dist/compose-CnanpQBB.mjs.map +1 -0
  86. package/dist/config-DPsCfNpR.d.mts +268 -0
  87. package/dist/config-DPsCfNpR.d.mts.map +1 -0
  88. package/dist/config-azErNJSd.d.cts +268 -0
  89. package/dist/config-azErNJSd.d.cts.map +1 -0
  90. package/dist/config.cjs +420 -9
  91. package/dist/config.cjs.map +1 -0
  92. package/dist/config.d.cts +4 -117
  93. package/dist/config.d.mts +4 -117
  94. package/dist/config.mjs +406 -3
  95. package/dist/config.mjs.map +1 -0
  96. package/dist/credentialSchemas-CM0rxWmS.cjs +272 -0
  97. package/dist/credentialSchemas-CM0rxWmS.cjs.map +1 -0
  98. package/dist/credentialSchemas-DPOGqOrU.mjs +237 -0
  99. package/dist/credentialSchemas-DPOGqOrU.mjs.map +1 -0
  100. package/dist/credentials-D7XJypNd.cjs +520 -0
  101. package/dist/credentials-D7XJypNd.cjs.map +1 -0
  102. package/dist/credentials-DpfnUvIR.mjs +395 -0
  103. package/dist/credentials-DpfnUvIR.mjs.map +1 -0
  104. package/dist/databases-Db48ZIXL.mjs +588 -0
  105. package/dist/databases-Db48ZIXL.mjs.map +1 -0
  106. package/dist/databases-P824RTnx.cjs +703 -0
  107. package/dist/databases-P824RTnx.cjs.map +1 -0
  108. package/dist/define-6poNqm5O.mjs +106 -0
  109. package/dist/define-6poNqm5O.mjs.map +1 -0
  110. package/dist/define-crmMcXFS.cjs +153 -0
  111. package/dist/define-crmMcXFS.cjs.map +1 -0
  112. package/dist/deploy/public.cjs +211 -0
  113. package/dist/deploy/public.cjs.map +1 -0
  114. package/dist/deploy/public.d.cts +652 -0
  115. package/dist/deploy/public.d.cts.map +1 -0
  116. package/dist/deploy/public.d.mts +652 -0
  117. package/dist/deploy/public.d.mts.map +1 -0
  118. package/dist/deploy/public.mjs +144 -0
  119. package/dist/deploy/public.mjs.map +1 -0
  120. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  121. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  122. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  123. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  124. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  125. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  126. package/dist/deploy/sniffer-hooks.cjs +1 -1
  127. package/dist/deploy/sniffer-hooks.mjs +1 -1
  128. package/dist/deploy/sniffer-loader.cjs +2 -2
  129. package/dist/deploy/sniffer-loader.mjs +1 -1
  130. package/dist/deploy/sniffer-routes-worker.cjs +2 -2
  131. package/dist/deploy/sniffer-routes-worker.mjs +2 -2
  132. package/dist/deploy-B35L6CMr.mjs +3439 -0
  133. package/dist/deploy-B35L6CMr.mjs.map +1 -0
  134. package/dist/deploy-zFe_W4WS.cjs +3494 -0
  135. package/dist/deploy-zFe_W4WS.cjs.map +1 -0
  136. package/dist/derive-BtGidITm.cjs +161 -0
  137. package/dist/derive-BtGidITm.cjs.map +1 -0
  138. package/dist/derive-Dew0QoGe.mjs +150 -0
  139. package/dist/derive-Dew0QoGe.mjs.map +1 -0
  140. package/dist/discover-DEOspD9M.cjs +796 -0
  141. package/dist/discover-DEOspD9M.cjs.map +1 -0
  142. package/dist/discover-DOhYSKY_.mjs +693 -0
  143. package/dist/discover-DOhYSKY_.mjs.map +1 -0
  144. package/dist/dokploy-BGJxcEh0.cjs +38 -0
  145. package/dist/dokploy-BGJxcEh0.cjs.map +1 -0
  146. package/dist/dokploy-sDTohVj5.mjs +38 -0
  147. package/dist/dokploy-sDTohVj5.mjs.map +1 -0
  148. package/dist/drivers-C47nm-wB.cjs +311 -0
  149. package/dist/drivers-C47nm-wB.cjs.map +1 -0
  150. package/dist/drivers-CDjpjakg.mjs +252 -0
  151. package/dist/drivers-CDjpjakg.mjs.map +1 -0
  152. package/dist/eas-Bxb9pymo.mjs +334 -0
  153. package/dist/eas-Bxb9pymo.mjs.map +1 -0
  154. package/dist/eas-DogHTOxl.cjs +337 -0
  155. package/dist/eas-DogHTOxl.cjs.map +1 -0
  156. package/dist/{emit-BdoPFjZf.cjs → emit-CYloptRS.cjs} +44 -54
  157. package/dist/emit-CYloptRS.cjs.map +1 -0
  158. package/dist/{emit-Bzq7JsMP.mjs → emit-CiJGdy_f.mjs} +45 -43
  159. package/dist/emit-CiJGdy_f.mjs.map +1 -0
  160. package/dist/encryption-BZk_sxC-.mjs +89 -0
  161. package/dist/encryption-BZk_sxC-.mjs.map +1 -0
  162. package/dist/encryption-DRXgL9Lh.cjs +90 -0
  163. package/dist/encryption-DRXgL9Lh.cjs.map +1 -0
  164. package/dist/engine-BuPhWFVm.cjs +3328 -0
  165. package/dist/engine-BuPhWFVm.cjs.map +1 -0
  166. package/dist/engine-uQmNnvNQ.mjs +3215 -0
  167. package/dist/engine-uQmNnvNQ.mjs.map +1 -0
  168. package/dist/errors-D8Gwp5kU.mjs +23 -0
  169. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  170. package/dist/errors-DMC4Umsb.cjs +34 -0
  171. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  172. package/dist/github-BCRbDSQa.cjs +901 -0
  173. package/dist/github-BCRbDSQa.cjs.map +1 -0
  174. package/dist/github-YknZQnYF.mjs +900 -0
  175. package/dist/github-YknZQnYF.mjs.map +1 -0
  176. package/dist/googlePlay-B_2dIDSO.mjs +931 -0
  177. package/dist/googlePlay-B_2dIDSO.mjs.map +1 -0
  178. package/dist/googlePlay-Cm2uipeZ.cjs +931 -0
  179. package/dist/googlePlay-Cm2uipeZ.cjs.map +1 -0
  180. package/dist/identity-CBXr4wNi.mjs +129 -0
  181. package/dist/identity-CBXr4wNi.mjs.map +1 -0
  182. package/dist/identity-CbLfgQNT.cjs +182 -0
  183. package/dist/identity-CbLfgQNT.cjs.map +1 -0
  184. package/dist/{index-D-iAVHx-.d.cts → index-D-gNc445.d.cts} +39 -15
  185. package/dist/index-D-gNc445.d.cts.map +1 -0
  186. package/dist/{index-Cd-qeOam.d.mts → index-Ur-ZIDYC.d.mts} +39 -15
  187. package/dist/index-Ur-ZIDYC.d.mts.map +1 -0
  188. package/dist/index.cjs +13461 -12270
  189. package/dist/index.cjs.map +1 -1
  190. package/dist/index.mjs +13486 -12293
  191. package/dist/index.mjs.map +1 -1
  192. package/dist/local-B7Zv1NoA.mjs +224 -0
  193. package/dist/local-B7Zv1NoA.mjs.map +1 -0
  194. package/dist/local-OPC9BCZt.cjs +241 -0
  195. package/dist/local-OPC9BCZt.cjs.map +1 -0
  196. package/dist/migrate-BIl4kLb1.cjs +181 -0
  197. package/dist/migrate-BIl4kLb1.cjs.map +1 -0
  198. package/dist/migrate-Co3UnkrE.cjs +273 -0
  199. package/dist/migrate-Co3UnkrE.cjs.map +1 -0
  200. package/dist/migrate-D71REG0N.mjs +268 -0
  201. package/dist/migrate-D71REG0N.mjs.map +1 -0
  202. package/dist/migrate-zqsyod5I.mjs +181 -0
  203. package/dist/migrate-zqsyod5I.mjs.map +1 -0
  204. package/dist/openapi.cjs +214 -7
  205. package/dist/openapi.cjs.map +1 -0
  206. package/dist/openapi.d.cts +32 -8
  207. package/dist/openapi.d.cts.map +1 -1
  208. package/dist/openapi.d.mts +32 -8
  209. package/dist/openapi.d.mts.map +1 -1
  210. package/dist/openapi.mjs +209 -2
  211. package/dist/openapi.mjs.map +1 -0
  212. package/dist/projectBucket-BBbQ1lHF.cjs +263 -0
  213. package/dist/projectBucket-BBbQ1lHF.cjs.map +1 -0
  214. package/dist/projectBucket-C_DN4WzF.mjs +222 -0
  215. package/dist/projectBucket-C_DN4WzF.mjs.map +1 -0
  216. package/dist/provider-BqpjG9QM.cjs +57 -0
  217. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  218. package/dist/provider-CEOKk8NS.mjs +46 -0
  219. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  220. package/dist/publish-BUnnuLl_.cjs +124 -0
  221. package/dist/publish-BUnnuLl_.cjs.map +1 -0
  222. package/dist/publish-BtmLOhV9.mjs +123 -0
  223. package/dist/publish-BtmLOhV9.mjs.map +1 -0
  224. package/dist/ready-BwtLriAF.mjs +375 -0
  225. package/dist/ready-BwtLriAF.mjs.map +1 -0
  226. package/dist/ready-Cj4pI0dw.cjs +404 -0
  227. package/dist/ready-Cj4pI0dw.cjs.map +1 -0
  228. package/dist/reconcile/public.cjs +2 -4
  229. package/dist/reconcile/public.d.cts +8 -67
  230. package/dist/reconcile/public.d.cts.map +1 -1
  231. package/dist/reconcile/public.d.mts +8 -67
  232. package/dist/reconcile/public.d.mts.map +1 -1
  233. package/dist/reconcile/public.mjs +3 -3
  234. package/dist/{reconcile-DhQ00DpU.mjs → reconcile--I7V4Klj.mjs} +2 -2
  235. package/dist/{reconcile-DhQ00DpU.mjs.map → reconcile--I7V4Klj.mjs.map} +1 -1
  236. package/dist/{reconcile-Dd2iyILf.cjs → reconcile-CuCQBa5-.cjs} +3 -3
  237. package/dist/{reconcile-Dd2iyILf.cjs.map → reconcile-CuCQBa5-.cjs.map} +1 -1
  238. package/dist/resolve-B1zK9f8_.mjs +263 -0
  239. package/dist/resolve-B1zK9f8_.mjs.map +1 -0
  240. package/dist/resolve-BVVSf27Y.cjs +316 -0
  241. package/dist/resolve-BVVSf27Y.cjs.map +1 -0
  242. package/dist/rollback-CAPWtOm3.mjs +136 -0
  243. package/dist/rollback-CAPWtOm3.mjs.map +1 -0
  244. package/dist/rollback-hV8Kbbg_.cjs +165 -0
  245. package/dist/rollback-hV8Kbbg_.cjs.map +1 -0
  246. package/dist/runtime-C0okGPpK.d.cts +82 -0
  247. package/dist/runtime-C0okGPpK.d.cts.map +1 -0
  248. package/dist/runtime-DfwIeO8f.d.mts +82 -0
  249. package/dist/runtime-DfwIeO8f.d.mts.map +1 -0
  250. package/dist/s3-CkERdmxm.mjs +215 -0
  251. package/dist/s3-CkERdmxm.mjs.map +1 -0
  252. package/dist/s3-xJtWm6WN.cjs +215 -0
  253. package/dist/s3-xJtWm6WN.cjs.map +1 -0
  254. package/dist/sandbox/config-worker.cjs +43 -0
  255. package/dist/sandbox/config-worker.cjs.map +1 -0
  256. package/dist/sandbox/config-worker.d.cts +1 -0
  257. package/dist/sandbox/config-worker.d.mts +1 -0
  258. package/dist/sandbox/config-worker.mjs +44 -0
  259. package/dist/sandbox/config-worker.mjs.map +1 -0
  260. package/dist/sandbox/credentials-worker.cjs +54 -0
  261. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  262. package/dist/sandbox/credentials-worker.d.cts +1 -0
  263. package/dist/sandbox/credentials-worker.d.mts +1 -0
  264. package/dist/sandbox/credentials-worker.mjs +55 -0
  265. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  266. package/dist/sandbox/discover-worker.cjs +50 -0
  267. package/dist/sandbox/discover-worker.cjs.map +1 -0
  268. package/dist/sandbox/discover-worker.d.cts +1 -0
  269. package/dist/sandbox/discover-worker.d.mts +1 -0
  270. package/dist/sandbox/discover-worker.mjs +51 -0
  271. package/dist/sandbox/discover-worker.mjs.map +1 -0
  272. package/dist/sandbox/migrate-worker.cjs +76 -0
  273. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  274. package/dist/sandbox/migrate-worker.d.cts +1 -0
  275. package/dist/sandbox/migrate-worker.d.mts +1 -0
  276. package/dist/sandbox/migrate-worker.mjs +77 -0
  277. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  278. package/dist/sandbox-CHv3OYXg.cjs +165 -0
  279. package/dist/sandbox-CHv3OYXg.cjs.map +1 -0
  280. package/dist/sandbox-CbVB7uOD.mjs +118 -0
  281. package/dist/sandbox-CbVB7uOD.mjs.map +1 -0
  282. package/dist/{workspace-mFpI_ky_.cjs → schemas-BCwKKA42.mjs} +399 -1162
  283. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  284. package/dist/{workspace-CgwmXEtc.mjs → schemas-BQ_v0lEX.cjs} +487 -971
  285. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  286. package/dist/secretsManager-CQORubp9.mjs +97 -0
  287. package/dist/secretsManager-CQORubp9.mjs.map +1 -0
  288. package/dist/secretsManager-RAGcEDX1.cjs +108 -0
  289. package/dist/secretsManager-RAGcEDX1.cjs.map +1 -0
  290. package/dist/seeds-CNPdk_2f.mjs +9198 -0
  291. package/dist/seeds-CNPdk_2f.mjs.map +1 -0
  292. package/dist/seeds-MR13eS-F.cjs +10303 -0
  293. package/dist/seeds-MR13eS-F.cjs.map +1 -0
  294. package/dist/serverSetup-9kFFmA86.cjs +651 -0
  295. package/dist/serverSetup-9kFFmA86.cjs.map +1 -0
  296. package/dist/serverSetup-DgAERQ5s.mjs +651 -0
  297. package/dist/serverSetup-DgAERQ5s.mjs.map +1 -0
  298. package/dist/sniffer-Biw5SE1V.cjs +1998 -0
  299. package/dist/sniffer-Biw5SE1V.cjs.map +1 -0
  300. package/dist/sniffer-KS_EcbAk.mjs +1825 -0
  301. package/dist/sniffer-KS_EcbAk.mjs.map +1 -0
  302. package/dist/snsSubscriptions-Bl3CChIH.mjs +1472 -0
  303. package/dist/snsSubscriptions-Bl3CChIH.mjs.map +1 -0
  304. package/dist/snsSubscriptions-CQFfrCJf.cjs +1695 -0
  305. package/dist/snsSubscriptions-CQFfrCJf.cjs.map +1 -0
  306. package/dist/sst-DmVJRu5l.cjs +463 -0
  307. package/dist/sst-DmVJRu5l.cjs.map +1 -0
  308. package/dist/sst-fop6uZ25.mjs +440 -0
  309. package/dist/sst-fop6uZ25.mjs.map +1 -0
  310. package/dist/stage-BIKAMxNc.cjs +313 -0
  311. package/dist/stage-BIKAMxNc.cjs.map +1 -0
  312. package/dist/stage-tIMFTQtj.mjs +302 -0
  313. package/dist/stage-tIMFTQtj.mjs.map +1 -0
  314. package/dist/stages-C9uSkohw.cjs +190 -0
  315. package/dist/stages-C9uSkohw.cjs.map +1 -0
  316. package/dist/stages-DhmbURs_.mjs +190 -0
  317. package/dist/stages-DhmbURs_.mjs.map +1 -0
  318. package/dist/target/public.cjs +15 -0
  319. package/dist/target/public.d.cts +28 -0
  320. package/dist/target/public.d.cts.map +1 -0
  321. package/dist/target/public.d.mts +28 -0
  322. package/dist/target/public.d.mts.map +1 -0
  323. package/dist/target/public.mjs +4 -0
  324. package/dist/terminal-CebFDhWQ.mjs +85 -0
  325. package/dist/terminal-CebFDhWQ.mjs.map +1 -0
  326. package/dist/terminal-DBwedwSS.cjs +85 -0
  327. package/dist/terminal-DBwedwSS.cjs.map +1 -0
  328. package/dist/{types-BGo5TaNE.d.mts → types-Cjnqw1ta.d.cts} +2199 -462
  329. package/dist/types-Cjnqw1ta.d.cts.map +1 -0
  330. package/dist/{types-C5ZNpUad.d.cts → types-xBx-07__.d.mts} +2197 -462
  331. package/dist/types-xBx-07__.d.mts.map +1 -0
  332. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  333. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  334. package/dist/utils-D_fxUqvU.mjs +156 -0
  335. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  336. package/dist/vitest.cjs +65 -0
  337. package/dist/vitest.cjs.map +1 -0
  338. package/dist/vitest.d.cts +29 -0
  339. package/dist/vitest.d.cts.map +1 -0
  340. package/dist/vitest.d.mts +29 -0
  341. package/dist/vitest.d.mts.map +1 -0
  342. package/dist/vitest.mjs +65 -0
  343. package/dist/vitest.mjs.map +1 -0
  344. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  345. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  346. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  347. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  348. package/dist/workspace/index.cjs +6 -2
  349. package/dist/workspace/index.d.cts +3 -3
  350. package/dist/workspace/index.d.mts +3 -3
  351. package/dist/workspace/index.mjs +2 -2
  352. package/dist/workspace-CjSfjfMK.mjs +2396 -0
  353. package/dist/workspace-CjSfjfMK.mjs.map +1 -0
  354. package/dist/workspace-DImrdet4.cjs +2808 -0
  355. package/dist/workspace-DImrdet4.cjs.map +1 -0
  356. package/package.json +55 -20
  357. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  358. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  359. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  360. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  361. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  362. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  363. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  364. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  365. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  366. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  367. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  368. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  369. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  370. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  371. package/dist/bundler-BeNDZdHQ.cjs.map +0 -1
  372. package/dist/bundler-BodTL4kf.mjs.map +0 -1
  373. package/dist/config-Q1rvKHvw.cjs +0 -467
  374. package/dist/config-Q1rvKHvw.cjs.map +0 -1
  375. package/dist/config-pqGD3hF9.mjs +0 -414
  376. package/dist/config-pqGD3hF9.mjs.map +0 -1
  377. package/dist/config.d.cts.map +0 -1
  378. package/dist/config.d.mts.map +0 -1
  379. package/dist/credentials-BekkKtY_.mjs +0 -2780
  380. package/dist/credentials-BekkKtY_.mjs.map +0 -1
  381. package/dist/credentials-Q6F0uqJq.cjs +0 -2917
  382. package/dist/credentials-Q6F0uqJq.cjs.map +0 -1
  383. package/dist/discover-BERGFg8v.cjs +0 -288
  384. package/dist/discover-BERGFg8v.cjs.map +0 -1
  385. package/dist/discover-CK-n3w6b.mjs +0 -244
  386. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  387. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  388. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  389. package/dist/fullstack-secrets-BET8gqwK.mjs +0 -81
  390. package/dist/fullstack-secrets-BET8gqwK.mjs.map +0 -1
  391. package/dist/fullstack-secrets-DXsWO-5m.cjs +0 -92
  392. package/dist/fullstack-secrets-DXsWO-5m.cjs.map +0 -1
  393. package/dist/generator-LfZU7NlU.mjs +0 -247
  394. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  395. package/dist/generator-Wdfp0jCS.cjs +0 -282
  396. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  397. package/dist/github-BfflNPVe.cjs +0 -203
  398. package/dist/github-BfflNPVe.cjs.map +0 -1
  399. package/dist/github-CRwnxKmD.mjs +0 -203
  400. package/dist/github-CRwnxKmD.mjs.map +0 -1
  401. package/dist/index-Cd-qeOam.d.mts.map +0 -1
  402. package/dist/index-D-iAVHx-.d.cts.map +0 -1
  403. package/dist/keystore-B4PRlbgE.mjs +0 -81
  404. package/dist/keystore-B4PRlbgE.mjs.map +0 -1
  405. package/dist/keystore-DgGRj2Yy.cjs +0 -98
  406. package/dist/keystore-DgGRj2Yy.cjs.map +0 -1
  407. package/dist/openapi-Dcbme-Us.cjs +0 -2038
  408. package/dist/openapi-Dcbme-Us.cjs.map +0 -1
  409. package/dist/openapi-react-query.cjs +0 -158
  410. package/dist/openapi-react-query.cjs.map +0 -1
  411. package/dist/openapi-react-query.d.cts +0 -9
  412. package/dist/openapi-react-query.d.cts.map +0 -1
  413. package/dist/openapi-react-query.d.mts +0 -9
  414. package/dist/openapi-react-query.d.mts.map +0 -1
  415. package/dist/openapi-react-query.mjs +0 -158
  416. package/dist/openapi-react-query.mjs.map +0 -1
  417. package/dist/openapi-vy4JzhUv.mjs +0 -1991
  418. package/dist/openapi-vy4JzhUv.mjs.map +0 -1
  419. package/dist/storage-C-30BD1e.cjs +0 -272
  420. package/dist/storage-C-30BD1e.cjs.map +0 -1
  421. package/dist/storage-P_b3w7uj.mjs +0 -231
  422. package/dist/storage-P_b3w7uj.mjs.map +0 -1
  423. package/dist/sync-B3xxXtJT.mjs +0 -88
  424. package/dist/sync-B3xxXtJT.mjs.map +0 -1
  425. package/dist/sync-D7uTIIEi.cjs +0 -111
  426. package/dist/sync-D7uTIIEi.cjs.map +0 -1
  427. package/dist/types-BGo5TaNE.d.mts.map +0 -1
  428. package/dist/types-C5ZNpUad.d.cts.map +0 -1
  429. package/dist/workspace-CgwmXEtc.mjs.map +0 -1
  430. package/dist/workspace-mFpI_ky_.cjs.map +0 -1
@@ -1,2038 +0,0 @@
1
- const require_discover = require("./discover-BERGFg8v.cjs");
2
- const require_config = require("./config-Q1rvKHvw.cjs");
3
- let node_fs_promises = require("node:fs/promises");
4
- let node_path = require("node:path");
5
- let node_child_process = require("node:child_process");
6
- let _geekmidas_manifest = require("@geekmidas/manifest");
7
- let _geekmidas_constructs_endpoints = require("@geekmidas/constructs/endpoints");
8
- let node_url = require("node:url");
9
- let _geekmidas_schema_conversion = require("@geekmidas/schema/conversion");
10
- //#region src/build/endpoint-analyzer.ts
11
- /**
12
- * Analyze an endpoint to extract its features
13
- */
14
- function analyzeEndpointFeatures(endpoint) {
15
- return {
16
- hasAuth: !!endpoint.authorizer,
17
- hasServices: endpoint.services.length > 0,
18
- hasDatabase: !!endpoint.databaseService,
19
- hasBodyValidation: !!endpoint.input?.body,
20
- hasQueryValidation: !!endpoint.input?.query,
21
- hasParamValidation: !!endpoint.input?.params,
22
- hasAudits: (endpoint.audits?.length ?? 0) > 0,
23
- hasEvents: (endpoint.events?.length ?? 0) > 0,
24
- hasRateLimit: !!endpoint.rateLimit,
25
- hasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,
26
- hasOutputValidation: !!endpoint.outputSchema
27
- };
28
- }
29
- /**
30
- * Determine the optimization tier for an endpoint based on its features
31
- */
32
- function determineEndpointTier(features) {
33
- const { hasAuth, hasServices, hasDatabase, hasAudits, hasEvents, hasRateLimit, hasRls } = features;
34
- if (!hasAuth && !hasServices && !hasDatabase && !hasAudits && !hasEvents && !hasRateLimit && !hasRls) return "minimal";
35
- if (hasAudits || hasRls || hasRateLimit) return "full";
36
- return "standard";
37
- }
38
- /**
39
- * Perform complete analysis of an endpoint
40
- */
41
- function analyzeEndpoint(endpoint, exportName) {
42
- const features = analyzeEndpointFeatures(endpoint);
43
- const tier = determineEndpointTier(features);
44
- return {
45
- route: endpoint.route,
46
- method: endpoint.method,
47
- exportName,
48
- features,
49
- tier,
50
- serviceNames: endpoint.services.map((s) => s.serviceName),
51
- databaseServiceName: endpoint.databaseService?.serviceName
52
- };
53
- }
54
- /**
55
- * Generate a summary of endpoint analysis for logging
56
- */
57
- function summarizeAnalysis(analyses) {
58
- const byTier = {
59
- minimal: 0,
60
- standard: 0,
61
- full: 0
62
- };
63
- const byFeature = {
64
- hasAuth: 0,
65
- hasServices: 0,
66
- hasDatabase: 0,
67
- hasBodyValidation: 0,
68
- hasQueryValidation: 0,
69
- hasParamValidation: 0,
70
- hasAudits: 0,
71
- hasEvents: 0,
72
- hasRateLimit: 0,
73
- hasRls: 0,
74
- hasOutputValidation: 0
75
- };
76
- for (const analysis of analyses) {
77
- byTier[analysis.tier]++;
78
- for (const [feature, enabled] of Object.entries(analysis.features)) if (enabled) byFeature[feature]++;
79
- }
80
- return {
81
- total: analyses.length,
82
- byTier,
83
- byFeature
84
- };
85
- }
86
- //#endregion
87
- //#region src/build/handler-templates.ts
88
- /**
89
- * Generate validator references for an endpoint
90
- */
91
- function generateValidators(exportName, features) {
92
- const validators = [];
93
- if (features.hasBodyValidation) validators.push(`validateBody(${exportName})`);
94
- if (features.hasQueryValidation) validators.push(`validateQuery(${exportName})`);
95
- if (features.hasParamValidation) validators.push(`validateParams(${exportName})`);
96
- return validators.length > 0 ? `\n ${validators.join(",\n ")},` : "";
97
- }
98
- /**
99
- * Generate a minimal handler (near-raw-Hono performance)
100
- *
101
- * Used for: Health checks, public endpoints with no services
102
- */
103
- function generateMinimalHandler(analysis) {
104
- const { exportName, features } = analysis;
105
- const method = analysis.method.toLowerCase();
106
- const validators = generateValidators(exportName, features);
107
- if (!(validators.length > 0) && !features.hasOutputValidation) return `
108
- // Minimal handler: ${analysis.route} (${analysis.method})
109
- app.${method}('${analysis.route}', async (c) => {
110
- const result = await ${exportName}.handler(
111
- {
112
- services: {},
113
- logger,
114
- body: undefined,
115
- query: undefined,
116
- params: undefined,
117
- session: undefined,
118
- header: Endpoint.createHeaders(c.req.header()),
119
- cookie: Endpoint.createCookies(c.req.header().cookie),
120
- auditor: undefined,
121
- db: undefined,
122
- } as any,
123
- { getMetadata: () => ({}) } as any,
124
- );
125
- return c.json(result, ${exportName}.status as any);
126
- });`;
127
- return `
128
- // Minimal handler with validation: ${analysis.route} (${analysis.method})
129
- app.${method}('${analysis.route}',${validators}
130
- async (c) => {
131
- const result = await ${exportName}.handler(
132
- {
133
- services: {},
134
- logger,
135
- body: ${features.hasBodyValidation ? "(c.req.valid as any)('json')" : "undefined"},
136
- query: ${features.hasQueryValidation ? "(c.req.valid as any)('query')" : "undefined"},
137
- params: ${features.hasParamValidation ? "(c.req.valid as any)('param')" : "undefined"},
138
- session: undefined,
139
- header: Endpoint.createHeaders(c.req.header()),
140
- cookie: Endpoint.createCookies(c.req.header().cookie),
141
- auditor: undefined,
142
- db: undefined,
143
- } as any,
144
- { getMetadata: () => ({}) } as any,
145
- );
146
- ${features.hasOutputValidation ? `const output = await ${exportName}.parseOutput(result);
147
- return c.json(output, ${exportName}.status as any);` : `return c.json(result, ${exportName}.status as any);`}
148
- }
149
- );`;
150
- }
151
- /**
152
- * Generate a standard handler (auth and/or services)
153
- *
154
- * Used for: Authenticated endpoints, endpoints with services
155
- */
156
- function generateStandardHandler(analysis) {
157
- const { exportName, features } = analysis;
158
- const method = analysis.method.toLowerCase();
159
- const validators = generateValidators(exportName, features);
160
- let serviceResolution = "";
161
- if (features.hasServices || features.hasDatabase) serviceResolution = `
162
- const services = await serviceDiscovery.register(${exportName}.services);
163
- ${features.hasDatabase ? `const db = ${exportName}.databaseService
164
- ? (await serviceDiscovery.register([${exportName}.databaseService]) as any)[${exportName}.databaseService.serviceName]
165
- : undefined;` : "const db = undefined;"}`;
166
- else serviceResolution = `
167
- const services = {};
168
- const db = undefined;`;
169
- let authCode = "";
170
- if (features.hasAuth) authCode = `
171
- // Authentication
172
- const session = await ${exportName}.getSession({
173
- services,
174
- logger,
175
- header,
176
- cookie,
177
- ...(db !== undefined && { db }),
178
- } as any);
179
-
180
- const isAuthorized = await ${exportName}.authorize({
181
- header,
182
- cookie,
183
- services,
184
- logger,
185
- session,
186
- } as any);
187
-
188
- if (!isAuthorized) {
189
- return c.json({ error: 'Unauthorized' }, 401);
190
- }`;
191
- let eventCode = "";
192
- if (features.hasEvents) eventCode = `
193
- // Publish events on success
194
- if (Endpoint.isSuccessStatus(${exportName}.status)) {
195
- await (publishConstructEvents as any)(
196
- ${exportName},
197
- result,
198
- serviceDiscovery,
199
- logger,
200
- );
201
- }`;
202
- return `
203
- // Standard handler: ${analysis.route} (${analysis.method})
204
- app.${method}('${analysis.route}',${validators}
205
- async (c) => {
206
- const headerValues = c.req.header();
207
- const header = Endpoint.createHeaders(headerValues);
208
- const cookie = Endpoint.createCookies(headerValues.cookie);
209
- ${serviceResolution}
210
- ${authCode}
211
-
212
- const responseBuilder = new ResponseBuilder();
213
- const result = await ${exportName}.handler(
214
- {
215
- services,
216
- logger,
217
- body: ${features.hasBodyValidation ? "(c.req.valid as any)('json')" : "undefined"},
218
- query: ${features.hasQueryValidation ? "(c.req.valid as any)('query')" : "undefined"},
219
- params: ${features.hasParamValidation ? "(c.req.valid as any)('param')" : "undefined"},
220
- session: ${features.hasAuth ? "session" : "undefined"},
221
- header,
222
- cookie,
223
- auditor: undefined,
224
- db,
225
- } as any,
226
- responseBuilder,
227
- );
228
-
229
- let data = result;
230
- let metadata = responseBuilder.getMetadata();
231
-
232
- if (Endpoint.hasMetadata(result)) {
233
- data = result.data;
234
- metadata = result.metadata;
235
- }
236
-
237
- ${features.hasOutputValidation ? `const output = ${exportName}.outputSchema
238
- ? await ${exportName}.parseOutput(data)
239
- : data;` : "const output = data;"}
240
- ${eventCode}
241
-
242
- const status = (metadata.status ?? ${exportName}.status) as any;
243
- return c.json(output, status);
244
- }
245
- );`;
246
- }
247
- /**
248
- * Generate validators.ts - Shared validator middleware factories
249
- */
250
- function generateValidatorsFile(analyses) {
251
- const needsBody = analyses.some((a) => a.features.hasBodyValidation);
252
- const needsQuery = analyses.some((a) => a.features.hasQueryValidation);
253
- const needsParams = analyses.some((a) => a.features.hasParamValidation);
254
- if (!needsBody && !needsQuery && !needsParams) return `// No validators needed for this build\nexport {};\n`;
255
- const exports = [];
256
- const factories = [];
257
- if (needsBody) {
258
- exports.push("validateBody");
259
- factories.push(`
260
- export const validateBody = (endpoint: any) =>
261
- validator('json', async (value, c) => {
262
- if (!endpoint.input?.body) return undefined;
263
- const parsed = await Endpoint.validate(endpoint.input.body, value);
264
- if (parsed.issues) return c.json(parsed.issues, 422);
265
- return parsed.value;
266
- });`);
267
- }
268
- if (needsQuery) {
269
- exports.push("validateQuery");
270
- factories.push(`
271
- export const validateQuery = (endpoint: any) =>
272
- validator('query', async (_, c) => {
273
- if (!endpoint.input?.query) return undefined;
274
- const rawQuery = Object.fromEntries(new URL(c.req.url).searchParams);
275
- const parsed = await Endpoint.validate(endpoint.input.query, rawQuery);
276
- if (parsed.issues) return c.json(parsed.issues, 422);
277
- return parsed.value;
278
- });`);
279
- }
280
- if (needsParams) {
281
- exports.push("validateParams");
282
- factories.push(`
283
- export const validateParams = (endpoint: any) =>
284
- validator('param', async (params, c) => {
285
- if (!endpoint.input?.params) return undefined;
286
- const parsed = await Endpoint.validate(endpoint.input.params, params);
287
- if (parsed.issues) return c.json(parsed.issues, 422);
288
- return parsed.value;
289
- });`);
290
- }
291
- return `/**
292
- * Generated validator middleware factories
293
- * Shared across all endpoint tiers that need validation
294
- */
295
- import { validator } from 'hono/validator';
296
- import { Endpoint } from '@geekmidas/constructs/endpoints';
297
- ${factories.join("\n")}
298
- `;
299
- }
300
- /**
301
- * Generate a standalone minimal endpoint file
302
- */
303
- function generateMinimalEndpointFile(analysis, endpointImport) {
304
- const { exportName, features } = analysis;
305
- const validatorImport = features.hasBodyValidation || features.hasQueryValidation || features.hasParamValidation ? generateValidatorImportsForEndpoint(analysis) : "";
306
- const handler = generateMinimalHandler(analysis);
307
- return `/**
308
- * Minimal endpoint: ${analysis.route} (${analysis.method})
309
- * Near-raw-Hono performance
310
- */
311
- import type { Hono } from 'hono';
312
- import type { Logger } from '@geekmidas/logger';
313
- import { Endpoint } from '@geekmidas/constructs/endpoints';
314
- ${validatorImport}
315
- import { ${exportName} } from '${endpointImport.importPath}';
316
-
317
- export function setup${capitalize(exportName)}(
318
- app: Hono,
319
- logger: Logger,
320
- ): void {
321
- ${handler}
322
- }
323
- `;
324
- }
325
- /**
326
- * Generate a standalone standard endpoint file
327
- */
328
- function generateStandardEndpointFile(analysis, endpointImport) {
329
- const { exportName, features } = analysis;
330
- const validatorImport = features.hasBodyValidation || features.hasQueryValidation || features.hasParamValidation ? generateValidatorImportsForEndpoint(analysis) : "";
331
- const eventsImport = features.hasEvents ? `import { publishConstructEvents } from '@geekmidas/constructs/endpoints';` : "";
332
- const handler = generateStandardHandler(analysis);
333
- return `/**
334
- * Standard endpoint: ${analysis.route} (${analysis.method})
335
- * Auth and/or services enabled
336
- */
337
- import type { Hono } from 'hono';
338
- import type { Logger } from '@geekmidas/logger';
339
- import type { ServiceDiscovery } from '@geekmidas/services';
340
- import { Endpoint, ResponseBuilder } from '@geekmidas/constructs/endpoints';
341
- ${eventsImport}
342
- ${validatorImport}
343
- import { ${exportName} } from '${endpointImport.importPath}';
344
-
345
- export function setup${capitalize(exportName)}(
346
- app: Hono,
347
- serviceDiscovery: ServiceDiscovery<any, any>,
348
- logger: Logger,
349
- ): void {
350
- ${handler}
351
- }
352
- `;
353
- }
354
- /**
355
- * Generate a standalone full endpoint file
356
- */
357
- function generateFullEndpointFile(analysis, endpointImport) {
358
- const { exportName } = analysis;
359
- return `/**
360
- * Full endpoint: ${analysis.route} (${analysis.method})
361
- * Complex features: audits, RLS, rate limiting
362
- */
363
- import type { Hono } from 'hono';
364
- import type { ServiceDiscovery } from '@geekmidas/services';
365
- import { HonoEndpoint } from '@geekmidas/constructs/hono';
366
- import { ${exportName} } from '${endpointImport.importPath}';
367
-
368
- export function setup${capitalize(exportName)}(
369
- app: Hono,
370
- serviceDiscovery: ServiceDiscovery<any, any>,
371
- openApiOptions: any,
372
- ): void {
373
- HonoEndpoint.addRoutes([${exportName}] as any, serviceDiscovery, app, openApiOptions);
374
- }
375
- `;
376
- }
377
- /**
378
- * Generate tier index file that imports and calls all endpoint setup functions
379
- */
380
- function generateTierIndexFile(tier, analyses) {
381
- const tierEndpoints = analyses.filter((a) => a.tier === tier);
382
- if (tierEndpoints.length === 0) {
383
- if (tier === "minimal") return `// No minimal-tier endpoints in this build
384
- import type { Hono } from 'hono';
385
- import type { Logger } from '@geekmidas/logger';
386
-
387
- export function setupMinimalEndpoints(
388
- _app: Hono,
389
- _logger: Logger,
390
- ): void {
391
- // No minimal endpoints
392
- }
393
- `;
394
- if (tier === "standard") return `// No standard-tier endpoints in this build
395
- import type { Hono } from 'hono';
396
- import type { Logger } from '@geekmidas/logger';
397
- import type { ServiceDiscovery } from '@geekmidas/services';
398
-
399
- export function setupStandardEndpoints(
400
- _app: Hono,
401
- _serviceDiscovery: ServiceDiscovery<any, any>,
402
- _logger: Logger,
403
- ): void {
404
- // No standard endpoints
405
- }
406
- `;
407
- return `// No full-tier endpoints in this build
408
- import type { Hono } from 'hono';
409
- import type { ServiceDiscovery } from '@geekmidas/services';
410
-
411
- export function setupFullEndpoints(
412
- _app: Hono,
413
- _serviceDiscovery: ServiceDiscovery<any, any>,
414
- _enableOpenApi: boolean,
415
- ): void {
416
- // No full endpoints
417
- }
418
- `;
419
- }
420
- const imports = tierEndpoints.map((a) => `import { setup${capitalize(a.exportName)} } from './${a.exportName}.js';`).join("\n");
421
- if (tier === "minimal") {
422
- const calls = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, logger);`).join("\n");
423
- return `/**
424
- * Minimal-tier endpoint index (${tierEndpoints.length} endpoints)
425
- * Near-raw-Hono performance
426
- */
427
- import type { Hono } from 'hono';
428
- import type { Logger } from '@geekmidas/logger';
429
- ${imports}
430
-
431
- export function setupMinimalEndpoints(
432
- app: Hono,
433
- logger: Logger,
434
- ): void {
435
- ${calls}
436
- }
437
- `;
438
- }
439
- if (tier === "standard") {
440
- const calls = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, serviceDiscovery, logger);`).join("\n");
441
- return `/**
442
- * Standard-tier endpoint index (${tierEndpoints.length} endpoints)
443
- * Auth and/or services enabled
444
- */
445
- import type { Hono } from 'hono';
446
- import type { Logger } from '@geekmidas/logger';
447
- import type { ServiceDiscovery } from '@geekmidas/services';
448
- ${imports}
449
-
450
- export function setupStandardEndpoints(
451
- app: Hono,
452
- serviceDiscovery: ServiceDiscovery<any, any>,
453
- logger: Logger,
454
- ): void {
455
- ${calls}
456
- }
457
- `;
458
- }
459
- const calls = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, serviceDiscovery, openApiOptions);`).join("\n");
460
- return `/**
461
- * Full-tier endpoint index (${tierEndpoints.length} endpoints)
462
- * Complex features: audits, RLS, rate limiting
463
- */
464
- import type { Hono } from 'hono';
465
- import type { ServiceDiscovery } from '@geekmidas/services';
466
- ${imports}
467
-
468
- export function setupFullEndpoints(
469
- app: Hono,
470
- serviceDiscovery: ServiceDiscovery<any, any>,
471
- enableOpenApi: boolean,
472
- ): void {
473
- const openApiOptions: any = enableOpenApi ? {
474
- docsPath: '/__docs',
475
- openApiOptions: {
476
- title: 'API Documentation',
477
- version: '1.0.0',
478
- description: 'Generated API documentation'
479
- }
480
- } : { docsPath: false };
481
-
482
- ${calls}
483
- }
484
- `;
485
- }
486
- /**
487
- * Generate validator imports for a single endpoint
488
- */
489
- function generateValidatorImportsForEndpoint(analysis) {
490
- const imports = [];
491
- if (analysis.features.hasBodyValidation) imports.push("validateBody");
492
- if (analysis.features.hasQueryValidation) imports.push("validateQuery");
493
- if (analysis.features.hasParamValidation) imports.push("validateParams");
494
- if (imports.length === 0) return "";
495
- return `import { ${imports.join(", ")} } from '../validators.js';`;
496
- }
497
- /**
498
- * Capitalize first letter
499
- */
500
- function capitalize(str) {
501
- return str.charAt(0).toUpperCase() + str.slice(1);
502
- }
503
- /**
504
- * Generate all endpoint files with nested folder structure (per-endpoint files)
505
- */
506
- function generateEndpointFilesNested(analyses, endpointImports) {
507
- const files = {
508
- "validators.ts": generateValidatorsFile(analyses),
509
- "minimal/index.ts": generateTierIndexFile("minimal", analyses),
510
- "standard/index.ts": generateTierIndexFile("standard", analyses),
511
- "full/index.ts": generateTierIndexFile("full", analyses),
512
- "index.ts": generateNestedIndexFile(analyses)
513
- };
514
- for (const analysis of analyses) {
515
- const endpointImport = endpointImports.find((i) => i.exportName === analysis.exportName);
516
- if (!endpointImport) continue;
517
- const fileName = `${analysis.tier}/${analysis.exportName}.ts`;
518
- switch (analysis.tier) {
519
- case "minimal":
520
- files[fileName] = generateMinimalEndpointFile(analysis, endpointImport);
521
- break;
522
- case "standard":
523
- files[fileName] = generateStandardEndpointFile(analysis, endpointImport);
524
- break;
525
- case "full": files[fileName] = generateFullEndpointFile(analysis, endpointImport);
526
- }
527
- }
528
- return files;
529
- }
530
- /**
531
- * Generate index.ts for nested structure
532
- */
533
- function generateNestedIndexFile(analyses) {
534
- const minimalCount = analyses.filter((a) => a.tier === "minimal").length;
535
- const standardCount = analyses.filter((a) => a.tier === "standard").length;
536
- const fullCount = analyses.filter((a) => a.tier === "full").length;
537
- return `/**
538
- * Generated optimized endpoints
539
- *
540
- * Build-time optimization tiers:
541
- * - minimal: ${minimalCount} endpoints (near-raw-Hono)
542
- * - standard: ${standardCount} endpoints (auth/services)
543
- * - full: ${fullCount} endpoints (audits/rls/rate-limit)
544
- */
545
- import type { EnvironmentParser } from '@geekmidas/envkit';
546
- import type { Logger } from '@geekmidas/logger';
547
- import type { Hono } from 'hono';
548
- import { ServiceDiscovery } from '@geekmidas/services';
549
- import { setupMinimalEndpoints } from './minimal/index.js';
550
- import { setupStandardEndpoints } from './standard/index.js';
551
- import { setupFullEndpoints } from './full/index.js';
552
-
553
- export async function setupEndpoints(
554
- app: Hono,
555
- envParser: EnvironmentParser<any>,
556
- logger: Logger,
557
- enableOpenApi: boolean = false,
558
- ): Promise<void> {
559
- const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
560
-
561
- // Minimal handlers (${minimalCount} endpoints) - near-raw-Hono performance
562
- setupMinimalEndpoints(app, logger);
563
-
564
- // Standard handlers (${standardCount} endpoints) - auth/services
565
- setupStandardEndpoints(app, serviceDiscovery, logger);
566
-
567
- // Full handlers (${fullCount} endpoints) - audits/rls/rate-limit
568
- setupFullEndpoints(app, serviceDiscovery, enableOpenApi);
569
-
570
- // Add Swagger UI if OpenAPI is enabled
571
- if (enableOpenApi) {
572
- try {
573
- const { swaggerUI } = await import('@hono/swagger-ui');
574
- app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));
575
- } catch {
576
- // @hono/swagger-ui not installed, skip Swagger UI
577
- }
578
- }
579
- }
580
- `;
581
- }
582
- //#endregion
583
- //#region src/generators/EndpointGenerator.ts
584
- /**
585
- * How a generated entry gets its logger and environment parser.
586
- *
587
- * From the surface it serves, when there is one: the surface holds both as
588
- * *objects*, and discovery already recorded which module declares it, so the
589
- * entry imports that module and reads them off it.
590
- *
591
- * The alternative — the shape this replaces — was naming both in config as
592
- * module paths, `envParser: './config/env#envParser'`, and printing an import
593
- * for each. Two strings per app, checked by nothing, describing files the
594
- * surface was already holding the contents of.
595
- *
596
- * Falls back to the configured paths for an app that declares no surface.
597
- */
598
- function runtimeFor(context, fromDir, owner) {
599
- const module = owner ? context.owners?.[owner] ?? context.surface?.module : context.surface?.module;
600
- if (module) {
601
- const specifier = importSpecifier(fromDir, module.specifier);
602
- return {
603
- imports: `import { ${module.exportName} as __surface } from '${specifier}';`,
604
- bindings: [
605
- "// What this construct was declared with. Objects, not module paths:",
606
- "// the entry imports the owner, so there is nothing to print.",
607
- "const envParser = __surface.envParser;",
608
- "const logger = __surface.logger;"
609
- ].join("\n")
610
- };
611
- }
612
- throw new Error(`No owner to take a logger and an environment parser from${owner ? ` for "${owner}"` : ""}. Build it from a \`RestApi\` or a \`Worker\`.`);
613
- }
614
- /** A relative specifier ESM will accept: always prefixed, never bare. */
615
- function importSpecifier(fromDir, target) {
616
- const rel = (0, node_path.relative)(fromDir, target).replace(/\.ts$/, ".js");
617
- return rel.startsWith(".") ? rel : `./${rel}`;
618
- }
619
- /**
620
- * CORS for a surface, derived rather than hand-written.
621
- *
622
- * Who may call a surface is already in the graph — every construct that
623
- * declared an edge to it — and reaches the process as one comma-separated
624
- * value. An application that maintained this by hand maintained a list that was
625
- * wrong in two directions at once: it trusted origins nothing was serving, and
626
- * it could not name hosts a deploy had not chosen yet.
627
- *
628
- * Only the parts a graph cannot answer are configurable, and every one has a
629
- * default: a surface that says nothing about CORS still gets it.
630
- */
631
- function corsFor(surface) {
632
- if (!surface) return {
633
- imports: "",
634
- setup: ""
635
- };
636
- const cors = surface.cors ?? {};
637
- const allowHeaders = [
638
- "content-type",
639
- "authorization",
640
- ...cors.allowHeaders ?? []
641
- ];
642
- return {
643
- imports: `import { cors } from 'hono/cors';`,
644
- setup: `
645
- // Who may call ${surface.id}, read off the graph rather than listed here.
646
- {
647
- const { origins } = envParser
648
- .create((get) => ({
649
- origins: get('${surface.trustedOriginsKey}')
650
- .string()
651
- .default('')
652
- .transform((value: string) =>
653
- value.split(',').map((origin) => origin.trim()).filter(Boolean),
654
- ),
655
- }))
656
- .parse();
657
-
658
- honoApp.use('*', cors({
659
- origin: origins,
660
- allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
661
- allowHeaders: ${JSON.stringify(allowHeaders)},${cors.exposeHeaders ? `\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},` : ""}
662
- credentials: ${cors.credentials ?? true},
663
- maxAge: ${cors.maxAge ?? 86400},
664
- }));
665
- }
666
- `
667
- };
668
- }
669
- var EndpointGenerator = class extends require_discover.ConstructGenerator {
670
- isConstruct(value) {
671
- return _geekmidas_constructs_endpoints.Endpoint.isEndpoint(value);
672
- }
673
- async build(context, constructs, outputDir, options) {
674
- const provider = options?.provider || "aws-apigatewayv2";
675
- const enableOpenApi = options?.enableOpenApi || false;
676
- const logger = console;
677
- const routes = [];
678
- if (constructs.length === 0) return routes;
679
- if (provider === "server") {
680
- await this.generateEndpointsFile(outputDir, constructs, context);
681
- const appFile = await this.generateAppFile(outputDir, context);
682
- routes.push({
683
- path: "*",
684
- method: "ALL",
685
- handler: (0, node_path.relative)(process.cwd(), appFile),
686
- authorizer: "none"
687
- });
688
- logger.log(`Generated server with ${constructs.length} endpoints${enableOpenApi ? " (OpenAPI enabled)" : ""}`);
689
- } else if (provider === "aws-lambda") {
690
- const routesDir = (0, node_path.join)(outputDir, "routes");
691
- await (0, node_fs_promises.mkdir)(routesDir, { recursive: true });
692
- for (const { key, construct, path } of constructs) {
693
- const handlerFile = await this.generateHandlerFile(routesDir, path.relative, key, "aws-apigatewayv2", construct, context);
694
- const routeInfo = {
695
- path: construct._path,
696
- method: construct.method,
697
- handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
698
- timeout: construct.timeout,
699
- memorySize: construct.memorySize,
700
- environment: await construct.getEnvironment({ markOptional: context.markOptional }),
701
- dependencies: construct.constructs,
702
- authorizer: construct.authorizer?.name ?? "none"
703
- };
704
- routes.push(routeInfo);
705
- logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
706
- }
707
- } else for (const { key, construct, path } of constructs) {
708
- const handlerFile = await this.generateHandlerFile(outputDir, path.relative, key, provider, construct, context);
709
- const routeInfo = {
710
- path: construct._path,
711
- method: construct.method,
712
- handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
713
- timeout: construct.timeout,
714
- memorySize: construct.memorySize,
715
- environment: await construct.getEnvironment({ markOptional: context.markOptional }),
716
- dependencies: construct.constructs,
717
- authorizer: construct.authorizer?.name ?? "none"
718
- };
719
- routes.push(routeInfo);
720
- logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
721
- }
722
- return routes;
723
- }
724
- async generateHandlerFile(outputDir, sourceFile, exportName, provider, _endpoint, context) {
725
- const handlerFileName = `${exportName}.ts`;
726
- const handlerPath = (0, node_path.join)(outputDir, handlerFileName);
727
- const importPath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), sourceFile).replace(/\.ts$/, ".js");
728
- let content;
729
- switch (provider) {
730
- case "aws-apigatewayv1":
731
- content = this.generateAWSApiGatewayV1Handler(importPath, exportName, context.storageDrivers);
732
- break;
733
- case "aws-apigatewayv2":
734
- content = this.generateAWSApiGatewayV2Handler(importPath, exportName, context.storageDrivers);
735
- break;
736
- case "server":
737
- content = this.generateServerHandler(importPath, exportName);
738
- break;
739
- default: throw new Error(`Unsupported provider: ${provider}`);
740
- }
741
- await (0, node_fs_promises.writeFile)(handlerPath, content);
742
- return handlerPath;
743
- }
744
- async generateEndpointsFile(outputDir, endpoints, context) {
745
- const endpointsPath = (0, node_path.join)(outputDir, "endpoints.ts");
746
- const importsByFile = /* @__PURE__ */ new Map();
747
- for (const { path, key } of endpoints) {
748
- const importPath = (0, node_path.relative)((0, node_path.dirname)(endpointsPath), path.relative).replace(/\.ts$/, ".js");
749
- if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
750
- importsByFile.get(importPath)?.push(key);
751
- }
752
- const endpointImports = Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n");
753
- const allExportNames = endpoints.map(({ key }) => key);
754
- if (context.production?.enabled && context.production.optimizedHandlers) return this.generateOptimizedEndpointsFile(endpointsPath, endpoints, endpointImports, allExportNames);
755
- const content = `import type { EnvironmentParser } from '@geekmidas/envkit';
756
- import type { Logger } from '@geekmidas/logger';
757
- import { HonoEndpoint } from '@geekmidas/constructs/hono';
758
- import { Endpoint } from '@geekmidas/constructs/endpoints';
759
- import { ServiceDiscovery } from '@geekmidas/services';
760
- import type { Hono } from 'hono';
761
- ${endpointImports}
762
-
763
- export const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any, any, any>[] = [
764
- ${allExportNames.join(",\n ")}
765
- ];
766
-
767
- export async function setupEndpoints(
768
- app: Hono,
769
- envParser: EnvironmentParser<any>,
770
- logger: Logger,
771
- enableOpenApi: boolean = true,
772
- ): Promise<void> {
773
- const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
774
-
775
- // Configure OpenAPI options based on enableOpenApi flag
776
- const openApiOptions: any = enableOpenApi ? {
777
- docsPath: '/__docs',
778
- openApiOptions: {
779
- title: 'API Documentation',
780
- version: '1.0.0',
781
- description: 'Generated API documentation'
782
- }
783
- } : { docsPath: false };
784
-
785
- HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);
786
-
787
- // Add Swagger UI if OpenAPI is enabled
788
- if (enableOpenApi) {
789
- try {
790
- const { swaggerUI } = await import('@hono/swagger-ui');
791
- app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));
792
- } catch {
793
- // @hono/swagger-ui not installed, skip Swagger UI
794
- }
795
- }
796
- }
797
- `;
798
- await (0, node_fs_promises.writeFile)(endpointsPath, content);
799
- return endpointsPath;
800
- }
801
- /**
802
- * Generate optimized endpoints files with nested folder structure (per-endpoint files)
803
- */
804
- async generateOptimizedEndpointsFile(endpointsPath, endpoints, _endpointImports, _allExportNames) {
805
- const logger = console;
806
- const outputDir = (0, node_path.dirname)(endpointsPath);
807
- const endpointsDir = (0, node_path.join)(outputDir, "endpoints");
808
- await (0, node_fs_promises.mkdir)((0, node_path.join)(endpointsDir, "minimal"), { recursive: true });
809
- await (0, node_fs_promises.mkdir)((0, node_path.join)(endpointsDir, "standard"), { recursive: true });
810
- await (0, node_fs_promises.mkdir)((0, node_path.join)(endpointsDir, "full"), { recursive: true });
811
- const analyses = endpoints.map(({ key, construct }) => analyzeEndpoint(construct, key));
812
- const endpointImports = endpoints.map(({ key, path }) => {
813
- const tierDir = (0, node_path.join)(endpointsDir, "standard");
814
- return {
815
- exportName: key,
816
- importPath: (0, node_path.relative)(tierDir, path.relative).replace(/\.ts$/, ".js")
817
- };
818
- });
819
- const summary = summarizeAnalysis(analyses);
820
- logger.log(`\n📊 Endpoint Analysis:`);
821
- logger.log(` Total: ${summary.total} endpoints`);
822
- logger.log(` - Minimal (near-raw-Hono): ${summary.byTier.minimal} endpoints`);
823
- logger.log(` - Standard (auth/services): ${summary.byTier.standard} endpoints`);
824
- logger.log(` - Full (audits/rls/rate-limit): ${summary.byTier.full} endpoints`);
825
- const files = generateEndpointFilesNested(analyses, endpointImports);
826
- for (const [filename, content] of Object.entries(files)) {
827
- const filePath = (0, node_path.join)(endpointsDir, filename);
828
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(filePath), { recursive: true });
829
- await (0, node_fs_promises.writeFile)(filePath, content);
830
- }
831
- const endpointFiles = Object.keys(files).filter((f) => !f.endsWith("index.ts") && !f.endsWith("validators.ts")).length;
832
- const indexFiles = Object.keys(files).filter((f) => f.endsWith("index.ts")).length;
833
- logger.log(` Generated ${endpointFiles} endpoint files + ${indexFiles} index files + validators.ts`);
834
- return (0, node_path.join)(endpointsDir, "index.ts");
835
- }
836
- async generateAppFile(outputDir, context) {
837
- if (context.production?.enabled) return this.generateProductionAppFile(outputDir, context);
838
- const appPath = (0, node_path.join)(outputDir, "app.ts");
839
- const runtime = runtimeFor(context, (0, node_path.dirname)(appPath));
840
- const telescopeEnabled = context.telescope?.enabled;
841
- const telescopeWebSocketEnabled = context.telescope?.websocket;
842
- const usesExternalTelescope = !!context.telescope?.telescopePath;
843
- const studioEnabled = context.studio?.enabled;
844
- const usesExternalStudio = !!context.studio?.studioPath;
845
- const studioFromDatabase = !usesExternalStudio && !!context.studio?.database;
846
- const telescopeFromSurface = !!context.surface?.module && !usesExternalTelescope;
847
- let telescopeImports = "";
848
- if (telescopeEnabled) {
849
- if (telescopeFromSurface) telescopeImports = "import { createMiddleware, createUI } from '@geekmidas/telescope/hono';";
850
- else if (usesExternalTelescope) {
851
- const relativeTelescopePath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.telescope?.telescopePath);
852
- telescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';
853
- import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
854
- } else telescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
855
- import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
856
- }
857
- let studioImports = "";
858
- if (studioEnabled) {
859
- if (usesExternalStudio) {
860
- const relativeStudioPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.studio?.studioPath);
861
- studioImports = `import ${context.studio?.studioImportPattern} from '${relativeStudioPath}';
862
- import { createStudioApp } from '@geekmidas/studio/server/hono';`;
863
- } else if (studioFromDatabase) {
864
- const dbSpecifier = importSpecifier((0, node_path.dirname)(appPath), context.studio.database.specifier);
865
- studioImports = `import { snifferContext } from '@geekmidas/constructs';
866
- import { Direction, InMemoryMonitoringStorage, Studio } from '@geekmidas/studio';
867
- import { ${context.studio.database.exportName} as __studioDb } from '${dbSpecifier}';
868
- import { createStudioApp } from '@geekmidas/studio/server/hono';`;
869
- } else studioImports = "";
870
- }
871
- const cors = corsFor(context.surface);
872
- let hooksImports = "";
873
- let beforeSetupCall = "";
874
- let afterSetupCall = "";
875
- if (context.hooks?.serverHooksPath) {
876
- hooksImports = `import * as serverHooks from '${(0, node_path.relative)((0, node_path.dirname)(appPath), context.hooks.serverHooksPath)}';`;
877
- beforeSetupCall = `
878
- // Call beforeSetup hook if defined
879
- if (typeof serverHooks.beforeSetup === 'function') {
880
- await serverHooks.beforeSetup(honoApp, { envParser, logger });
881
- }
882
- `;
883
- afterSetupCall = `
884
- // Call afterSetup hook if defined
885
- if (typeof serverHooks.afterSetup === 'function') {
886
- await serverHooks.afterSetup(honoApp, { envParser, logger });
887
- }
888
- `;
889
- }
890
- const telescopeWebSocketSetupCode = telescopeWebSocketEnabled ? `
891
- // Setup WebSocket for real-time telescope updates
892
- try {
893
- const { createNodeWebSocket } = await import('@hono/node-ws');
894
- const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });
895
- // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)
896
- honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({
897
- onOpen: (_event: Event, ws: any) => {
898
- telescope.addWsClient(ws);
899
- },
900
- onClose: (_event: Event, ws: any) => {
901
- telescope.removeWsClient(ws);
902
- },
903
- onMessage: (event: MessageEvent, ws: any) => {
904
- try {
905
- const data = JSON.parse(event.data);
906
- if (data.type === 'ping') {
907
- ws.send(JSON.stringify({ type: 'pong' }));
908
- }
909
- } catch {
910
- // Ignore invalid messages
911
- }
912
- },
913
- })));
914
- // Store injectWebSocket for server entry to call after serve()
915
- (honoApp as any).__injectWebSocket = injectWebSocket;
916
- logger.info('Telescope WebSocket enabled');
917
- } catch (e) {
918
- logger.warn({ error: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');
919
- }
920
- ` : "";
921
- let telescopeSetup = "";
922
- if (telescopeEnabled) {
923
- if (telescopeFromSurface || usesExternalTelescope) telescopeSetup = `
924
- ${telescopeWebSocketSetupCode}
925
- // Add telescope middleware (before endpoints to capture all requests)
926
- honoApp.use('*', createMiddleware(telescope));
927
-
928
- // Mount telescope UI
929
- const telescopeUI = createUI(telescope);
930
- honoApp.route('${context.telescope?.path}', telescopeUI);
931
- `;
932
- else telescopeSetup = `
933
- // Setup Telescope for debugging/monitoring
934
- const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });
935
- const telescope = new Telescope({
936
- enabled: true,
937
- path: '${context.telescope?.path}',
938
- ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},
939
- recordBody: ${context.telescope?.recordBody},
940
- storage: telescopeStorage,
941
- });
942
- ${telescopeWebSocketSetupCode}
943
- // Add telescope middleware (before endpoints to capture all requests)
944
- honoApp.use('*', createMiddleware(telescope));
945
-
946
- // Mount telescope UI
947
- const telescopeUI = createUI(telescope);
948
- honoApp.route('${context.telescope?.path}', telescopeUI);
949
- `;
950
- }
951
- let studioSetup = "";
952
- if (studioEnabled && studioFromDatabase) studioSetup = `
953
- // Studio, built from the declared database. The client comes from the
954
- // construct, so what you inspect is by definition what the handlers write to.
955
- const studio = new Studio({
956
- monitoring: { storage: new InMemoryMonitoringStorage({ maxEntries: 100 }) },
957
- data: {
958
- db: await __studioDb.service.register({ envParser, context: snifferContext }),
959
- cursor: { field: 'id', direction: Direction.Desc },
960
- },
961
- enabled: true,
962
- });
963
-
964
- const studioApp = createStudioApp(studio);
965
- honoApp.route('${context.studio?.path}', studioApp);
966
- `;
967
- else if (studioEnabled && usesExternalStudio) studioSetup = `
968
- // Mount Studio data browser UI
969
- const studioApp = createStudioApp(studio);
970
- honoApp.route('${context.studio?.path}', studioApp);
971
- `;
972
- const content = `/**
973
- * Generated server application
974
- *
975
- * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
976
- * The subscriber polling mechanism is not production-ready.
977
- * For production, use AWS Lambda with SQS/SNS event sources.
978
- */
979
- import { Hono } from 'hono';
980
- import type { Hono as HonoType } from 'hono';
981
- import { setupEndpoints } from './endpoints.js';
982
- import { setupSubscribers } from './subscribers.js';
983
- import { setupQueues } from './queues.js';
984
- import { setupCrons } from './crons.js';
985
- ${runtime.imports}
986
- ${telescopeImports}
987
- ${studioImports}
988
- ${hooksImports}
989
- ${cors.imports}
990
- ${context.storageDrivers?.imports ?? ""}
991
-
992
- ${runtime.bindings}
993
- ${telescopeFromSurface ? "const telescope = __surface.telescope;" : ""}
994
-
995
- ${context.storageDrivers?.setup ? `// Which storage drivers exist is the entry point's decision: the scheme in
996
- // each injected URL picks one, so no construct and no application module names
997
- // a provider.
998
- ${context.storageDrivers.setup}
999
- ` : ""}
1000
- export interface ServerApp {
1001
- app: HonoType;
1002
- start: (options?: {
1003
- port?: number;
1004
- serve: (app: HonoType, port: number) => void | Promise<void>;
1005
- }) => Promise<void>;
1006
- }
1007
-
1008
- /**
1009
- * Create and configure the Hono application
1010
- *
1011
- * @param app - Optional Hono app instance to configure (creates new one if not provided)
1012
- * @param enableOpenApi - Enable OpenAPI documentation (default: true)
1013
- * @returns Server app with configured Hono app and start function
1014
- *
1015
- * @example
1016
- * // With Bun
1017
- * import { createApp } from './.gkm/server/app.js';
1018
- *
1019
- * const { app, start } = await createApp();
1020
- *
1021
- * await start({
1022
- * port: 3000,
1023
- * serve: (app, port) => {
1024
- * Bun.serve({ port, fetch: app.fetch });
1025
- * }
1026
- * });
1027
- *
1028
- * @example
1029
- * // With Node.js (using @hono/node-server)
1030
- * import { serve } from '@hono/node-server';
1031
- * import { createApp } from './.gkm/server/app.js';
1032
- *
1033
- * const { app, start } = await createApp();
1034
- *
1035
- * await start({
1036
- * port: 3000,
1037
- * serve: (app, port) => {
1038
- * serve({ fetch: app.fetch, port });
1039
- * }
1040
- * });
1041
- */
1042
- export async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {
1043
- const honoApp = app || new Hono();
1044
- ${telescopeSetup}${cors.setup}${beforeSetupCall}${studioSetup}
1045
- // Setup HTTP endpoints
1046
- await setupEndpoints(honoApp, envParser, logger, enableOpenApi);
1047
- ${afterSetupCall}
1048
-
1049
- return {
1050
- app: honoApp,
1051
- async start(options) {
1052
- if (!options?.serve) {
1053
- throw new Error(
1054
- 'serve function is required. Pass a serve function for your runtime:\\n' +
1055
- ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
1056
- ' - Node: (app, port) => serve({ fetch: app.fetch, port })'
1057
- );
1058
- }
1059
-
1060
- const port = options.port ?? 3000;
1061
-
1062
- // Start subscribers in background (non-blocking, local development only)
1063
- await setupSubscribers(envParser, logger).catch((error) => {
1064
- logger.error({ error }, 'Failed to start subscribers');
1065
- });
1066
-
1067
- // Start queue workers in background (non-blocking, local development only)
1068
- await setupQueues(envParser, logger).catch((error) => {
1069
- logger.error({ error }, 'Failed to start queue workers');
1070
- });
1071
-
1072
- // Schedule this app's crons. Caught like the others: a scheduler that
1073
- // cannot start is not a reason for the HTTP server not to.
1074
- await setupCrons(envParser, logger).catch((error) => {
1075
- logger.error({ error }, 'Failed to schedule crons');
1076
- });
1077
-
1078
- logger.info({ port }, 'Starting server');
1079
-
1080
- // Start HTTP server using provided serve function
1081
- await options.serve(honoApp, port);
1082
-
1083
- logger.info({ port }, 'Server started');
1084
- }
1085
- };
1086
- }
1087
-
1088
- // Default export for convenience
1089
- export default createApp;
1090
- `;
1091
- await (0, node_fs_promises.writeFile)(appPath, content);
1092
- return appPath;
1093
- }
1094
- /**
1095
- * One Lambda, one endpoint — and no environment import.
1096
- *
1097
- * The endpoint was built from its surface, so it carries the parser the
1098
- * adaptor needs. This used to read
1099
- * `import { envParser } from '../../config/env'`, a line the build wrote
1100
- * because a generator can print a module specifier and cannot print an
1101
- * object. Nothing has to be printed now, which is also why nothing has to be
1102
- * named in config.
1103
- */
1104
- generateAWSApiGatewayV1Handler(importPath, exportName, drivers) {
1105
- return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';
1106
- import { ${exportName} } from '${importPath}';
1107
- ${drivers?.imports ?? ""}
1108
- ${drivers?.setup ? `\n// The handler registers the drivers its target needs.\n${drivers.setup}\n` : ""}
1109
- const adapter = new AmazonApiGatewayV1Endpoint(${exportName});
1110
-
1111
- export const handler = adapter.handler;
1112
- `;
1113
- }
1114
- /**
1115
- * One Lambda, one endpoint — and no environment import.
1116
- *
1117
- * The endpoint was built from its surface, so it carries the parser the
1118
- * adaptor needs. This used to read
1119
- * `import { envParser } from '../../config/env'`, a line the build wrote
1120
- * because a generator can print a module specifier and cannot print an
1121
- * object. Nothing has to be printed now, which is also why nothing has to be
1122
- * named in config.
1123
- */
1124
- generateAWSApiGatewayV2Handler(importPath, exportName, drivers) {
1125
- return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';
1126
- import { ${exportName} } from '${importPath}';
1127
- ${drivers?.imports ?? ""}
1128
- ${drivers?.setup ? `\n// The handler registers the drivers its target needs.\n${drivers.setup}\n` : ""}
1129
- const adapter = new AmazonApiGatewayV2Endpoint(${exportName});
1130
-
1131
- export const handler = adapter.handler;
1132
- `;
1133
- }
1134
- generateServerHandler(importPath, exportName) {
1135
- return `import { ${exportName} } from '${importPath}';
1136
-
1137
- // Server handler - implement based on your server framework
1138
- export const handler = ${exportName};
1139
- `;
1140
- }
1141
- /**
1142
- * Generate a production-optimized app.ts file
1143
- * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown
1144
- */
1145
- async generateProductionAppFile(outputDir, context) {
1146
- const appPath = (0, node_path.join)(outputDir, "app.ts");
1147
- const runtime = runtimeFor(context, (0, node_path.dirname)(appPath));
1148
- const production = context.production;
1149
- const healthCheckPath = production.healthCheck;
1150
- const enableGracefulShutdown = production.gracefulShutdown;
1151
- const enableOpenApi = production.openapi;
1152
- const includeSubscribers = production.subscribers === "include";
1153
- const cors = corsFor(context.surface);
1154
- let hooksImports = "";
1155
- let beforeSetupCall = "";
1156
- let afterSetupCall = "";
1157
- if (context.hooks?.serverHooksPath) {
1158
- hooksImports = `import * as serverHooks from '${(0, node_path.relative)((0, node_path.dirname)(appPath), context.hooks.serverHooksPath)}';`;
1159
- beforeSetupCall = `
1160
- // Call beforeSetup hook if defined
1161
- if (typeof serverHooks.beforeSetup === 'function') {
1162
- await serverHooks.beforeSetup(honoApp, { envParser, logger });
1163
- }
1164
- `;
1165
- afterSetupCall = `
1166
- // Call afterSetup hook if defined
1167
- if (typeof serverHooks.afterSetup === 'function') {
1168
- await serverHooks.afterSetup(honoApp, { envParser, logger });
1169
- }
1170
- `;
1171
- }
1172
- const subscriberSetup = includeSubscribers ? `
1173
- // Start subscribers in background
1174
- await setupSubscribers(envParser, logger).catch((error) => {
1175
- logger.error({ error }, 'Failed to start subscribers');
1176
- });
1177
-
1178
- // Start queue workers in background
1179
- await setupQueues(envParser, logger).catch((error) => {
1180
- logger.error({ error }, 'Failed to start queue workers');
1181
- });
1182
-
1183
- // Schedule this app's crons. Caught like the others: a scheduler that
1184
- // cannot start is not a reason for the HTTP server not to.
1185
- await setupCrons(envParser, logger).catch((error) => {
1186
- logger.error({ error }, 'Failed to schedule crons');
1187
- });
1188
- ` : "";
1189
- const subscriberImport = includeSubscribers ? `import { setupSubscribers } from './subscribers.js';
1190
- import { setupQueues } from './queues.js';
1191
- import { setupCrons } from './crons.js';` : "";
1192
- const gracefulShutdownCode = enableGracefulShutdown ? `
1193
- // Graceful shutdown handling
1194
- let isShuttingDown = false;
1195
-
1196
- const shutdown = async () => {
1197
- if (isShuttingDown) return;
1198
- isShuttingDown = true;
1199
- logger.info('Graceful shutdown initiated');
1200
- // Allow in-flight requests to complete (30s timeout)
1201
- setTimeout(() => process.exit(0), 30000);
1202
- };
1203
-
1204
- process.on('SIGTERM', shutdown);
1205
- process.on('SIGINT', shutdown);
1206
- ` : "";
1207
- const content = `/**
1208
- * Generated production server application
1209
- *
1210
- * This is a production-optimized build without dev tools.
1211
- * - No Telescope debugging dashboard
1212
- * - No Studio database browser
1213
- * - No WebSocket updates
1214
- * - Includes health checks and graceful shutdown
1215
- */
1216
- import { Hono } from 'hono';
1217
- import type { Hono as HonoType } from 'hono';
1218
- import { setupEndpoints } from '${production.optimizedHandlers ? "./endpoints/index.js" : "./endpoints.js"}';
1219
- ${subscriberImport}
1220
- ${runtime.imports}
1221
- ${runtime.bindings}
1222
- ${hooksImports}
1223
- ${cors.imports}
1224
- ${context.storageDrivers?.imports ?? ""}
1225
-
1226
- ${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.
1227
- ${context.storageDrivers.setup}
1228
- ` : ""}
1229
- export interface ServerApp {
1230
- app: HonoType;
1231
- start: (options?: {
1232
- port?: number;
1233
- serve: (app: HonoType, port: number) => void | Promise<void>;
1234
- }) => Promise<void>;
1235
- }
1236
-
1237
- /**
1238
- * Create and configure the production Hono application
1239
- */
1240
- export async function createApp(app?: HonoType): Promise<ServerApp> {
1241
- const honoApp = app || new Hono();
1242
-
1243
- // Health check endpoint (always first)
1244
- honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));
1245
- honoApp.get('/ready', (c) => c.json({ ready: true }));
1246
- ${cors.setup}${beforeSetupCall}
1247
- // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})
1248
- await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});
1249
- ${afterSetupCall}
1250
- return {
1251
- app: honoApp,
1252
- async start(options) {
1253
- if (!options?.serve) {
1254
- throw new Error(
1255
- 'serve function is required. Pass a serve function for your runtime:\\n' +
1256
- ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
1257
- ' - Node: (app, port) => serve({ fetch: app.fetch, port })'
1258
- );
1259
- }
1260
-
1261
- const port = options.port ?? Number(process.env.PORT) ?? 3000;
1262
- ${gracefulShutdownCode}${subscriberSetup}
1263
- logger.info({ port }, 'Starting production server');
1264
-
1265
- // Start HTTP server using provided serve function
1266
- await options.serve(honoApp, port);
1267
-
1268
- logger.info({ port }, 'Production server started');
1269
- }
1270
- };
1271
- }
1272
-
1273
- // Default export for convenience
1274
- export default createApp;
1275
- `;
1276
- await (0, node_fs_promises.writeFile)(appPath, content);
1277
- await this.generateProductionServerEntry(outputDir);
1278
- return appPath;
1279
- }
1280
- /**
1281
- * Generate production server.ts entry point
1282
- */
1283
- async generateProductionServerEntry(outputDir) {
1284
- const serverPath = (0, node_path.join)(outputDir, "server.ts");
1285
- await (0, node_fs_promises.writeFile)(serverPath, `#!/usr/bin/env node
1286
- /**
1287
- * Production server entry point
1288
- * Generated by 'gkm build --provider server --production'
1289
- */
1290
- import { serve } from '@hono/node-server';
1291
- import { createApp } from './app.js';
1292
-
1293
- const port = Number(process.env.PORT) || 3000;
1294
-
1295
- const { start } = await createApp();
1296
-
1297
- await start({
1298
- port,
1299
- serve: (app, port) => { serve({ fetch: app.fetch, port }); },
1300
- });
1301
- `);
1302
- }
1303
- };
1304
- //#endregion
1305
- //#region src/generators/OpenApiTsGenerator.ts
1306
- /**
1307
- * Generates TypeScript OpenAPI module from endpoints.
1308
- * Outputs:
1309
- * - securitySchemes: typed security scheme definitions
1310
- * - endpointAuth: runtime map of endpoints to auth requirements
1311
- * - paths: TypeScript interface for type-safe fetcher
1312
- * - schema interfaces: reusable TypeScript types from Zod/Valibot schemas
1313
- */
1314
- var OpenApiTsGenerator = class {
1315
- async generate(endpoints, options = {}) {
1316
- const { title = "API", version = "1.0.0", description } = options;
1317
- const endpointInfos = await this.extractEndpointInfos(endpoints);
1318
- const securitySchemes = this.collectSecuritySchemes(endpointInfos);
1319
- const endpointAuth = this.buildEndpointAuthMap(endpointInfos);
1320
- const schemaInterfaces = await this.generateSchemaInterfaces(endpointInfos);
1321
- const pathsInterface = await this.generatePathsInterface(endpointInfos);
1322
- return this.buildModule({
1323
- title,
1324
- version,
1325
- description,
1326
- securitySchemes,
1327
- endpointAuth,
1328
- schemaInterfaces,
1329
- pathsInterface
1330
- });
1331
- }
1332
- async extractEndpointInfos(endpoints) {
1333
- return endpoints.map((ep) => {
1334
- const route = ep.route.replace(/:(\w+)/g, "{$1}");
1335
- const method = ep.method.toUpperCase();
1336
- const securityScheme = ep.authorizer?.securityScheme;
1337
- return {
1338
- endpoint: `${method} ${route}`,
1339
- route,
1340
- method,
1341
- authorizerName: ep.authorizer?.name ?? null,
1342
- authorizerType: ep.authorizer?.type ?? null,
1343
- securityScheme: securityScheme ?? null,
1344
- input: ep.input,
1345
- output: ep.outputSchema,
1346
- description: ep.description,
1347
- tags: ep.tags,
1348
- operationId: ep.operationId,
1349
- responseType: ep.responseType ?? "application/json"
1350
- };
1351
- });
1352
- }
1353
- collectSecuritySchemes(endpointInfos) {
1354
- const schemes = /* @__PURE__ */ new Map();
1355
- for (const info of endpointInfos) if (info.authorizerName && !schemes.has(info.authorizerName)) {
1356
- const scheme = info.securityScheme ?? (info.authorizerType ? this.mapAuthorizerToSecurityScheme(info.authorizerType, info.authorizerName) : null);
1357
- if (scheme) schemes.set(info.authorizerName, {
1358
- name: info.authorizerName,
1359
- type: scheme.type,
1360
- scheme
1361
- });
1362
- }
1363
- return Array.from(schemes.values());
1364
- }
1365
- mapAuthorizerToSecurityScheme(type, _name) {
1366
- switch (type.toLowerCase()) {
1367
- case "jwt":
1368
- case "bearer": return {
1369
- type: "http",
1370
- scheme: "bearer",
1371
- bearerFormat: "JWT"
1372
- };
1373
- case "iam":
1374
- case "aws-sigv4":
1375
- case "sigv4": return {
1376
- type: "apiKey",
1377
- in: "header",
1378
- name: "Authorization",
1379
- "x-amazon-apigateway-authtype": "awsSigv4"
1380
- };
1381
- case "apikey":
1382
- case "api-key": return {
1383
- type: "apiKey",
1384
- in: "header",
1385
- name: "X-API-Key"
1386
- };
1387
- case "oauth2": return {
1388
- type: "oauth2",
1389
- flows: {}
1390
- };
1391
- case "oidc":
1392
- case "openidconnect": return {
1393
- type: "openIdConnect",
1394
- openIdConnectUrl: ""
1395
- };
1396
- default: return {
1397
- type: "http",
1398
- scheme: "bearer"
1399
- };
1400
- }
1401
- }
1402
- buildEndpointAuthMap(endpointInfos) {
1403
- const authMap = {};
1404
- for (const info of endpointInfos) authMap[info.endpoint] = info.authorizerName;
1405
- return authMap;
1406
- }
1407
- async generateSchemaInterfaces(endpointInfos) {
1408
- const interfaces = [];
1409
- const generatedNames = /* @__PURE__ */ new Set();
1410
- const collectedDefs = /* @__PURE__ */ new Map();
1411
- for (const info of endpointInfos) {
1412
- const baseName = this.getSchemaBaseName(info);
1413
- if (info.input?.body) {
1414
- const name = await this.getSchemaName(info.input.body, `${baseName}Input`);
1415
- if (!generatedNames.has(name)) {
1416
- const schema = await this.schemaToInterfaceWithDefs(info.input.body, name, collectedDefs);
1417
- if (schema) {
1418
- interfaces.push(schema);
1419
- generatedNames.add(name);
1420
- }
1421
- }
1422
- }
1423
- if (info.input?.params) {
1424
- const name = await this.getSchemaName(info.input.params, `${baseName}Params`);
1425
- if (!generatedNames.has(name)) {
1426
- const schema = await this.schemaToInterfaceWithDefs(info.input.params, name, collectedDefs);
1427
- if (schema) {
1428
- interfaces.push(schema);
1429
- generatedNames.add(name);
1430
- }
1431
- }
1432
- }
1433
- if (info.input?.query) {
1434
- const name = await this.getSchemaName(info.input.query, `${baseName}Query`);
1435
- if (!generatedNames.has(name)) {
1436
- const schema = await this.schemaToInterfaceWithDefs(info.input.query, name, collectedDefs);
1437
- if (schema) {
1438
- interfaces.push(schema);
1439
- generatedNames.add(name);
1440
- }
1441
- }
1442
- }
1443
- if (info.output) {
1444
- const name = await this.getSchemaName(info.output, `${baseName}Output`);
1445
- if (!generatedNames.has(name)) {
1446
- const schema = await this.schemaToInterfaceWithDefs(info.output, name, collectedDefs);
1447
- if (schema) {
1448
- interfaces.push(schema);
1449
- generatedNames.add(name);
1450
- }
1451
- }
1452
- }
1453
- }
1454
- const registrySchemas = await (0, _geekmidas_schema_conversion.getRegisteredZodJsonSchemas)();
1455
- for (const [rawName, rawSchema] of Object.entries(registrySchemas)) {
1456
- const defName = this.pascalCase(rawName);
1457
- if (collectedDefs.has(defName) || generatedNames.has(defName)) continue;
1458
- const { id: _id, $defs: _defs, ...rest } = rawSchema;
1459
- collectedDefs.set(defName, rest);
1460
- }
1461
- for (const [defName, defSchema] of collectedDefs) if (!generatedNames.has(defName)) {
1462
- const interfaceStr = this.jsonSchemaToInterface(defSchema, defName);
1463
- interfaces.push(interfaceStr);
1464
- generatedNames.add(defName);
1465
- }
1466
- return interfaces.join("\n\n");
1467
- }
1468
- /**
1469
- * Get the name for a schema, using metadata `id` if available,
1470
- * otherwise falling back to the provided default name.
1471
- */
1472
- async getSchemaName(schema, defaultName) {
1473
- try {
1474
- const metadata = await (0, _geekmidas_schema_conversion.getSchemaMetadata)(schema);
1475
- if (metadata?.id) return this.pascalCase(metadata.id);
1476
- } catch {}
1477
- return defaultName;
1478
- }
1479
- getSchemaBaseName(info) {
1480
- if (info.operationId) return this.pascalCase(info.operationId);
1481
- const routeParts = info.route.replace(/[{}]/g, "").split("/").filter(Boolean).map((part) => this.pascalCase(part));
1482
- return `${this.pascalCase(info.method.toLowerCase())}${routeParts.join("")}`;
1483
- }
1484
- pascalCase(str) {
1485
- return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toUpperCase());
1486
- }
1487
- /**
1488
- * Convert schema to interface while collecting $defs for nested schemas
1489
- * with .meta({ id: 'X' }).
1490
- */
1491
- async schemaToInterfaceWithDefs(schema, name, collectedDefs) {
1492
- try {
1493
- const vendor = schema["~standard"]?.vendor;
1494
- if (!vendor || !(vendor in _geekmidas_schema_conversion.StandardSchemaJsonSchema)) return unknownType(name);
1495
- const toJsonSchema = _geekmidas_schema_conversion.StandardSchemaJsonSchema[vendor];
1496
- const jsonSchema = await toJsonSchema(schema);
1497
- if (!jsonSchema) return unknownType(name);
1498
- if (jsonSchema.$defs && typeof jsonSchema.$defs === "object") {
1499
- for (const [defName, defSchema] of Object.entries(jsonSchema.$defs)) if (!collectedDefs.has(defName)) {
1500
- const { id, ...schemaWithoutId } = defSchema;
1501
- collectedDefs.set(defName, schemaWithoutId);
1502
- }
1503
- }
1504
- const { $defs, ...schemaWithoutDefs } = jsonSchema;
1505
- const ref = schemaWithoutDefs.$ref;
1506
- if (ref && Object.keys(schemaWithoutDefs).every((k) => k === "$ref" || k === "$schema")) {
1507
- const target = ref.split("/").pop();
1508
- return target === name ? null : `export type ${name} = ${target};`;
1509
- }
1510
- return this.jsonSchemaToInterface(schemaWithoutDefs, name);
1511
- } catch {
1512
- return unknownType(name);
1513
- }
1514
- }
1515
- jsonSchemaToInterface(schema, name) {
1516
- if (schema.type !== "object" || !schema.properties) return `export type ${name} = ${this.jsonSchemaTypeToTs(schema)};`;
1517
- const props = [];
1518
- const required = new Set(schema.required || []);
1519
- for (const [propName, propSchema] of Object.entries(schema.properties)) {
1520
- const isRequired = required.has(propName);
1521
- const typeStr = this.jsonSchemaTypeToTs(propSchema);
1522
- const optionalMark = isRequired ? "" : "?";
1523
- props.push(` ${propName}${optionalMark}: ${typeStr};`);
1524
- }
1525
- return `export interface ${name} {\n${props.join("\n")}\n}`;
1526
- }
1527
- jsonSchemaTypeToTs(schema) {
1528
- if (!schema) return "unknown";
1529
- if (schema.$ref) return schema.$ref.split("/").pop() || "unknown";
1530
- if (schema.const !== void 0) return typeof schema.const === "string" ? `'${schema.const}'` : String(schema.const);
1531
- if (schema.anyOf) return schema.anyOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" | ");
1532
- if (schema.oneOf) return schema.oneOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" | ");
1533
- if (schema.allOf) return schema.allOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" & ");
1534
- if (Array.isArray(schema.type)) return schema.type.map((type) => this.jsonSchemaTypeToTs({
1535
- ...schema,
1536
- type
1537
- })).join(" | ");
1538
- switch (schema.type) {
1539
- case "string":
1540
- if (schema.enum) return schema.enum.map((e) => `'${e}'`).join(" | ");
1541
- return "string";
1542
- case "number":
1543
- case "integer": return "number";
1544
- case "boolean": return "boolean";
1545
- case "null": return "null";
1546
- case "array":
1547
- if (schema.items) return `Array<${this.jsonSchemaTypeToTs(schema.items)}>`;
1548
- return "Array<unknown>";
1549
- case "object":
1550
- if (schema.properties) {
1551
- const props = [];
1552
- const required = new Set(schema.required || []);
1553
- for (const [propName, propSchema] of Object.entries(schema.properties)) {
1554
- const isRequired = required.has(propName);
1555
- const typeStr = this.jsonSchemaTypeToTs(propSchema);
1556
- const optionalMark = isRequired ? "" : "?";
1557
- props.push(`${propName}${optionalMark}: ${typeStr}`);
1558
- }
1559
- return `{ ${props.join("; ")} }`;
1560
- }
1561
- if (schema.additionalProperties) return `Record<string, ${this.jsonSchemaTypeToTs(schema.additionalProperties)}>`;
1562
- return "Record<string, unknown>";
1563
- default: return "unknown";
1564
- }
1565
- }
1566
- async generatePathsInterface(endpointInfos) {
1567
- const pathGroups = /* @__PURE__ */ new Map();
1568
- for (const info of endpointInfos) {
1569
- const existing = pathGroups.get(info.route) || [];
1570
- existing.push(info);
1571
- pathGroups.set(info.route, existing);
1572
- }
1573
- const pathEntries = [];
1574
- for (const [route, infos] of pathGroups) {
1575
- const methodEntries = [];
1576
- for (const info of infos) {
1577
- const methodDef = await this.generateMethodDefinition(info);
1578
- methodEntries.push(` ${info.method.toLowerCase()}: ${methodDef};`);
1579
- }
1580
- const firstWithParams = infos.find((i) => i.input?.params);
1581
- let paramsEntry = "";
1582
- if (firstWithParams?.input?.params) paramsEntry = `\n parameters: {\n path: ${await this.getSchemaName(firstWithParams.input.params, `${this.getSchemaBaseName(firstWithParams)}Params`)};\n };`;
1583
- pathEntries.push(` '${route}': {${paramsEntry}\n${methodEntries.join("\n")}\n };`);
1584
- }
1585
- return `export interface paths {\n${pathEntries.join("\n")}\n}`;
1586
- }
1587
- async generateMethodDefinition(info) {
1588
- const parts = [];
1589
- const baseName = this.getSchemaBaseName(info);
1590
- if (info.input?.body) {
1591
- const bodyName = await this.getSchemaName(info.input.body, `${baseName}Input`);
1592
- parts.push(`requestBody: {
1593
- content: {
1594
- 'application/json': ${bodyName};
1595
- };
1596
- }`);
1597
- }
1598
- if (info.input?.query) {
1599
- const queryName = await this.getSchemaName(info.input.query, `${baseName}Query`);
1600
- parts.push(`parameters: {
1601
- query: ${queryName};
1602
- }`);
1603
- }
1604
- const outputName = info.output ? await this.getSchemaName(info.output, `${baseName}Output`) : "unknown";
1605
- parts.push(`responses: {
1606
- 200: {
1607
- content: {
1608
- '${info.responseType}': ${outputName};
1609
- };
1610
- };
1611
- }`);
1612
- return `{\n ${parts.join(";\n ")};\n }`;
1613
- }
1614
- buildModule(params) {
1615
- const { title, version, description, securitySchemes, endpointAuth, schemaInterfaces, pathsInterface } = params;
1616
- const securitySchemesObj = securitySchemes.reduce((acc, s) => {
1617
- acc[s.name] = s.scheme;
1618
- return acc;
1619
- }, {});
1620
- const schemeNames = securitySchemes.map((s) => `'${s.name}'`).join(" | ");
1621
- const createApiSection = schemeNames.length > 0 ? `
1622
- // ============================================================
1623
- // API Client Factory
1624
- // ============================================================
1625
-
1626
- import {
1627
- createAuthAwareFetcher,
1628
- type AuthStrategy,
1629
- } from '@geekmidas/client/auth-fetcher';
1630
- import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
1631
- import type { QueryClient } from '@tanstack/react-query';
1632
-
1633
- /**
1634
- * Options for creating the API client.
1635
- */
1636
- export interface CreateApiOptions {
1637
- /** Base URL for all API requests (required) */
1638
- baseURL: string;
1639
- /** Auth strategies for each security scheme used in this API */
1640
- authStrategies: Record<SecuritySchemeId, AuthStrategy>;
1641
- /** Optional React Query client instance */
1642
- queryClient?: QueryClient;
1643
- /** Optional request interceptor */
1644
- onRequest?: (config: RequestInit) => RequestInit | Promise<RequestInit>;
1645
- }
1646
-
1647
- /**
1648
- * Create a type-safe API client with authentication and React Query hooks.
1649
- *
1650
- * @example
1651
- * \`\`\`typescript
1652
- * const api = createApi({
1653
- * baseURL: 'https://api.example.com',
1654
- * authStrategies: {
1655
- * jwt: { type: 'bearer', tokenProvider },
1656
- * },
1657
- * });
1658
- *
1659
- * // Imperative fetch
1660
- * const user = await api('GET /users/{id}', { params: { id: '123' } });
1661
- *
1662
- * // React Query hooks
1663
- * const { data } = api.useQuery('GET /users/{id}', { params: { id: '123' } });
1664
- * const mutation = api.useMutation('POST /users');
1665
- * \`\`\`
1666
- */
1667
- export function createApi(options: CreateApiOptions) {
1668
- const fetcher = createAuthAwareFetcher<paths, typeof endpointAuth, typeof securitySchemes>({
1669
- baseURL: options.baseURL,
1670
- endpointAuth,
1671
- securitySchemes,
1672
- authStrategies: options.authStrategies,
1673
- onRequest: options.onRequest,
1674
- });
1675
-
1676
- const hooks = createEndpointHooks<paths>(fetcher, { queryClient: options.queryClient });
1677
-
1678
- return Object.assign(fetcher, hooks);
1679
- }
1680
- ` : `
1681
- // ============================================================
1682
- // API Client Factory
1683
- // ============================================================
1684
-
1685
- import { createTypedFetcher, type FetcherOptions } from '@geekmidas/client/fetcher';
1686
- import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
1687
- import type { QueryClient } from '@tanstack/react-query';
1688
-
1689
- /**
1690
- * Options for creating the API client.
1691
- */
1692
- export interface CreateApiOptions extends Omit<FetcherOptions, 'baseURL'> {
1693
- /** Base URL for all API requests (required) */
1694
- baseURL: string;
1695
- /** Optional React Query client instance */
1696
- queryClient?: QueryClient;
1697
- }
1698
-
1699
- /**
1700
- * Create a type-safe API client with React Query hooks.
1701
- *
1702
- * @example
1703
- * \`\`\`typescript
1704
- * const api = createApi({
1705
- * baseURL: 'https://api.example.com',
1706
- * });
1707
- *
1708
- * // Imperative fetch
1709
- * const data = await api('GET /health');
1710
- *
1711
- * // React Query hooks
1712
- * const { data } = api.useQuery('GET /health');
1713
- * \`\`\`
1714
- */
1715
- export function createApi(options: CreateApiOptions) {
1716
- const { queryClient, ...fetcherOptions } = options;
1717
- const request = createTypedFetcher<paths>(fetcherOptions);
1718
-
1719
- const hooks = createEndpointHooks<paths>(request, { queryClient });
1720
-
1721
- return Object.assign(request, hooks);
1722
- }
1723
- `;
1724
- return `// Auto-generated by @geekmidas/cli - DO NOT EDIT
1725
-
1726
- // ============================================================
1727
- // Security Scheme Type
1728
- // ============================================================
1729
-
1730
- interface SecuritySchemeObject {
1731
- type: 'apiKey' | 'http' | 'mutualTLS' | 'oauth2' | 'openIdConnect';
1732
- description?: string;
1733
- name?: string;
1734
- in?: 'query' | 'header' | 'cookie';
1735
- scheme?: string;
1736
- bearerFormat?: string;
1737
- flows?: Record<string, unknown>;
1738
- openIdConnectUrl?: string;
1739
- [key: string]: unknown;
1740
- }
1741
-
1742
- // ============================================================
1743
- // API Info
1744
- // ============================================================
1745
-
1746
- export const apiInfo = {
1747
- title: '${title}',
1748
- version: '${version}',${description ? `\n description: '${description.replace(/'/g, "\\'")}',` : ""}
1749
- } as const;
1750
-
1751
- // ============================================================
1752
- // Security Schemes
1753
- // ============================================================
1754
-
1755
- /**
1756
- * Available security schemes for this API.
1757
- * Maps authorizer names to OpenAPI security scheme definitions.
1758
- */
1759
- export const securitySchemes = ${JSON.stringify(securitySchemesObj, null, 2).replace(/"([a-zA-Z_$][a-zA-Z0-9_$]*)":/g, "$1:")} as const satisfies Record<string, SecuritySchemeObject>;
1760
-
1761
- export type SecuritySchemeId = ${schemeNames || "never"};
1762
-
1763
- // ============================================================
1764
- // Endpoint Authentication Map
1765
- // ============================================================
1766
-
1767
- /**
1768
- * Runtime map of endpoints to their required authentication scheme.
1769
- * \`null\` indicates a public endpoint (no auth required).
1770
- */
1771
- export const endpointAuth = ${JSON.stringify(endpointAuth, null, 2).replace(/"([^"]+)":/g, "'$1':")} as const satisfies Record<string, SecuritySchemeId | null>;
1772
-
1773
- export type EndpointString = keyof typeof endpointAuth;
1774
-
1775
- export type AuthenticatedEndpoint = {
1776
- [K in EndpointString]: typeof endpointAuth[K] extends null ? never : K;
1777
- }[EndpointString];
1778
-
1779
- export type PublicEndpoint = {
1780
- [K in EndpointString]: typeof endpointAuth[K] extends null ? K : never;
1781
- }[EndpointString];
1782
-
1783
- // ============================================================
1784
- // Schema Definitions
1785
- // ============================================================
1786
-
1787
- ${schemaInterfaces}
1788
-
1789
- // ============================================================
1790
- // OpenAPI Paths
1791
- // ============================================================
1792
-
1793
- ${pathsInterface}
1794
- ${createApiSection}
1795
- `;
1796
- }
1797
- };
1798
- /**
1799
- * The declaration for a schema that cannot be converted — a vendor with no
1800
- * converter, or one that fails. The paths interface names it either way, so
1801
- * leaving it undeclared made the generated client fail to compile.
1802
- */
1803
- function unknownType(name) {
1804
- return `export type ${name} = unknown;`;
1805
- }
1806
- //#endregion
1807
- //#region src/openapi.ts
1808
- /**
1809
- * Default output path for generated OpenAPI client (used for single-app configs)
1810
- */
1811
- const OPENAPI_OUTPUT_PATH = "./.gkm/openapi.ts";
1812
- /**
1813
- * Where a surface's generated client lands.
1814
- *
1815
- * Named from the surface, so `new RestApi('Webhooks')` writes
1816
- * `.gkm/openapi/webhooks.ts` — the same kebab form that gives it its container
1817
- * name and its `WEBHOOKS_URL`.
1818
- */
1819
- function openApiPathFor(surfaceId) {
1820
- return `./.gkm/openapi/${(0, _geekmidas_manifest.kebabCase)(surfaceId)}.ts`;
1821
- }
1822
- /**
1823
- * Resolve OpenAPI config from GkmConfig
1824
- */
1825
- function resolveOpenApiConfig(config) {
1826
- if (config.openapi === false) return { enabled: false };
1827
- if (config.openapi === true || config.openapi === void 0) return {
1828
- enabled: true,
1829
- title: "API Documentation",
1830
- version: "1.0.0",
1831
- description: "Auto-generated API documentation from endpoints"
1832
- };
1833
- return {
1834
- enabled: config.openapi.enabled !== false,
1835
- title: config.openapi.title || "API Documentation",
1836
- version: config.openapi.version || "1.0.0",
1837
- description: config.openapi.description || "Auto-generated API documentation from endpoints"
1838
- };
1839
- }
1840
- /**
1841
- * Load endpoints from a glob, then generate.
1842
- *
1843
- * For the callers that have no endpoints in hand — `gkm openapi`, and `gkm dev`
1844
- * regenerating on reload. The glob is the app's derived one — the conventional
1845
- * directories under it — not a `routes` field anybody wrote.
1846
- */
1847
- async function generateOpenApiFrom(routes, options = {}) {
1848
- return generateOpenApi((await new EndpointGenerator().load(routes, void 0, options.bustCache)).map(({ construct }) => construct), options);
1849
- }
1850
- /**
1851
- * Generate an OpenAPI spec for each surface these endpoints name.
1852
- *
1853
- * Takes the endpoints, not a glob to find them with. The build has already
1854
- * loaded every one of them to generate handlers, so globbing again was a second
1855
- * discovery pass over the same files — and the reason this function needed a
1856
- * `routes` to be told where to look, which is how a retired config field stayed
1857
- * load-bearing.
1858
- *
1859
- * @returns What was written, or null if disabled or there were none
1860
- */
1861
- async function generateOpenApi(endpoints, options = {}) {
1862
- const logger = options.silent ? { log: () => {} } : console;
1863
- const openApiConfig = resolveOpenApiConfig({ openapi: options.openapi });
1864
- if (!openApiConfig.enabled) return null;
1865
- if (endpoints.length === 0) {
1866
- logger.log("No valid endpoints found for OpenAPI generation");
1867
- return null;
1868
- }
1869
- const bySurface = /* @__PURE__ */ new Map();
1870
- for (const endpoint of endpoints) {
1871
- const owner = endpoint.owner ?? endpoint.surface?.id;
1872
- if (!owner) continue;
1873
- const existing = bySurface.get(owner);
1874
- if (existing) existing.push(endpoint);
1875
- else bySurface.set(owner, [endpoint]);
1876
- }
1877
- if (bySurface.size === 0) {
1878
- logger.log("No endpoints named a surface, so no OpenAPI was generated");
1879
- return null;
1880
- }
1881
- const tsGenerator = new OpenApiTsGenerator();
1882
- const written = [];
1883
- for (const [surfaceId, surfaceEndpoints] of bySurface) {
1884
- const relative = openApiPathFor(surfaceId);
1885
- const outputPath = (0, node_path.join)(process.cwd(), relative);
1886
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(outputPath), { recursive: true });
1887
- const tsContent = await tsGenerator.generate(surfaceEndpoints, {
1888
- title: openApiConfig.title ?? surfaceId,
1889
- version: openApiConfig.version,
1890
- description: openApiConfig.description
1891
- });
1892
- await (0, node_fs_promises.writeFile)(outputPath, tsContent);
1893
- written.push(relative);
1894
- logger.log(`📄 OpenAPI client generated: ${relative} (${surfaceEndpoints.length} endpoints)`);
1895
- }
1896
- return {
1897
- outputPath: (0, node_path.join)(process.cwd(), written[0]),
1898
- outputPaths: written.map((r) => (0, node_path.join)(process.cwd(), r)),
1899
- endpointCount: endpoints.length
1900
- };
1901
- }
1902
- async function openapiCommand(options = {}) {
1903
- const logger = console;
1904
- try {
1905
- const loadedConfig = await require_config.loadWorkspaceConfig(options.cwd);
1906
- if (loadedConfig.type === "single") {
1907
- const config = loadedConfig.raw;
1908
- if (!config.openapi) config.openapi = { enabled: true };
1909
- const result = await generateOpenApiFrom(config.constructs, { openapi: config.openapi });
1910
- if (result) logger.log(`Found ${result.endpointCount} endpoints`);
1911
- } else {
1912
- const { workspace } = loadedConfig;
1913
- const workspaceRoot = workspace.root;
1914
- const backendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "backend" && app.openapi !== false && (typeof app.openapi !== "object" || app.openapi.enabled !== false));
1915
- if (backendApps.length === 0) {
1916
- logger.log("No backend apps with OpenAPI enabled found");
1917
- return;
1918
- }
1919
- if (options.app) {
1920
- const entry = backendApps.find(([name]) => name === options.app);
1921
- if (!entry) throw new Error(`App "${options.app}" not found or has OpenAPI disabled`);
1922
- const [appName, app] = entry;
1923
- const result = await generateOpenApiForApp(workspaceRoot, appName, app);
1924
- if (result) logger.log(`📄 [${appName}] Generated OpenAPI (${result.endpointCount} endpoints)`);
1925
- return;
1926
- }
1927
- for (const [appName, app] of backendApps) {
1928
- const appPath = (0, node_path.join)(workspaceRoot, app.path);
1929
- if ((0, node_path.resolve)(appPath) === (0, node_path.resolve)(workspaceRoot)) {
1930
- const result = await generateOpenApiForApp(workspaceRoot, appName, app, false);
1931
- if (result) logger.log(`Found ${result.endpointCount} endpoints`);
1932
- continue;
1933
- }
1934
- await runOpenApiInSubprocess(appPath, appName);
1935
- }
1936
- }
1937
- } catch (error) {
1938
- throw new Error(`OpenAPI generation failed: ${error.message}`);
1939
- }
1940
- }
1941
- /**
1942
- * Generate OpenAPI for a single named app within a workspace.
1943
- * Runs in-process. The caller is responsible for ensuring `process.cwd()`
1944
- * is the app's directory so tsx loads the app's tsconfig path aliases.
1945
- */
1946
- async function generateOpenApiForApp(workspaceRoot, _appName, app, silent = true) {
1947
- if (app.type !== "backend") return null;
1948
- const appPath = (0, node_path.join)(workspaceRoot, app.path);
1949
- return generateOpenApiFrom([(0, node_path.join)(appPath, "**/*.ts")], {
1950
- openapi: app.openapi ?? { enabled: true },
1951
- silent
1952
- });
1953
- }
1954
- /**
1955
- * Resolve the gkm bin path. Tests can override via `GKM_BIN_PATH` env var
1956
- * to avoid depending on the built dist.
1957
- */
1958
- function resolveGkmBinPath() {
1959
- if (process.env.GKM_BIN_PATH) return process.env.GKM_BIN_PATH;
1960
- return (0, node_url.fileURLToPath)(new URL("../bin/gkm.mjs", require("url").pathToFileURL(__filename).href));
1961
- }
1962
- /**
1963
- * Spawn a subprocess that runs `gkm openapi --app <name>` with `cwd` set to
1964
- * the app's directory. Inherits `NODE_OPTIONS` (which already contains
1965
- * `--import tsx`), so the child gets a fresh tsx instance whose tsconfig
1966
- * discovery picks up the app's tsconfig path aliases.
1967
- */
1968
- async function runOpenApiInSubprocess(appCwd, appName) {
1969
- const binPath = resolveGkmBinPath();
1970
- await new Promise((resolve, reject) => {
1971
- const child = (0, node_child_process.spawn)(process.execPath, [
1972
- binPath,
1973
- "openapi",
1974
- "--app",
1975
- appName
1976
- ], {
1977
- cwd: appCwd,
1978
- stdio: "inherit",
1979
- env: process.env
1980
- });
1981
- child.on("error", reject);
1982
- child.on("close", (code) => {
1983
- if (code === 0) resolve();
1984
- else reject(/* @__PURE__ */ new Error(`OpenAPI generation for app "${appName}" exited with code ${code}`));
1985
- });
1986
- });
1987
- }
1988
- //#endregion
1989
- Object.defineProperty(exports, "EndpointGenerator", {
1990
- enumerable: true,
1991
- get: function() {
1992
- return EndpointGenerator;
1993
- }
1994
- });
1995
- Object.defineProperty(exports, "OPENAPI_OUTPUT_PATH", {
1996
- enumerable: true,
1997
- get: function() {
1998
- return OPENAPI_OUTPUT_PATH;
1999
- }
2000
- });
2001
- Object.defineProperty(exports, "generateOpenApi", {
2002
- enumerable: true,
2003
- get: function() {
2004
- return generateOpenApi;
2005
- }
2006
- });
2007
- Object.defineProperty(exports, "generateOpenApiFrom", {
2008
- enumerable: true,
2009
- get: function() {
2010
- return generateOpenApiFrom;
2011
- }
2012
- });
2013
- Object.defineProperty(exports, "openApiPathFor", {
2014
- enumerable: true,
2015
- get: function() {
2016
- return openApiPathFor;
2017
- }
2018
- });
2019
- Object.defineProperty(exports, "openapiCommand", {
2020
- enumerable: true,
2021
- get: function() {
2022
- return openapiCommand;
2023
- }
2024
- });
2025
- Object.defineProperty(exports, "resolveOpenApiConfig", {
2026
- enumerable: true,
2027
- get: function() {
2028
- return resolveOpenApiConfig;
2029
- }
2030
- });
2031
- Object.defineProperty(exports, "runtimeFor", {
2032
- enumerable: true,
2033
- get: function() {
2034
- return runtimeFor;
2035
- }
2036
- });
2037
-
2038
- //# sourceMappingURL=openapi-Dcbme-Us.cjs.map