@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,2780 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { a as DEFAULT_EVENTS$1, i as DEFAULT_CACHE, o as DEFAULT_STORAGE, t as discover } from "./discover-CK-n3w6b.mjs";
3
- import { a as loadWorkspaceAppInfo, c as appKey, n as getAppNameFromCwd } from "./config-pqGD3hF9.mjs";
4
- import { s as getDependencyEnvVars, t as allConstructGlobs } from "./workspace-CgwmXEtc.mjs";
5
- import { r as generatePgBossUrl } from "./generator-LfZU7NlU.mjs";
6
- import { n as readStageSecrets, o as toEmbeddableSecrets, r as secretsExist } from "./storage-P_b3w7uj.mjs";
7
- import { existsSync, readFileSync } from "node:fs";
8
- import { mkdir, readFile, writeFile } from "node:fs/promises";
9
- import { dirname, join, resolve } from "node:path";
10
- import { execFile, execSync } from "node:child_process";
11
- import { DEFAULT_POSTGRES_VERSION, cacheTable, cookieDomain, dependentsOf, provideKey, providedKeyFor, provisionOrder, publicEnvFor } from "@geekmidas/manifest";
12
- import { createServer } from "node:net";
13
- import { config } from "dotenv";
14
- import { parse as parse$1, stringify } from "yaml";
15
- import { createHash } from "node:crypto";
16
- import { ownerRole, readerRole, roleStatements } from "@geekmidas/db/pg/roles";
17
- import { CreateBucketCommand, GetBucketPolicyCommand, HeadBucketCommand, PutBucketPolicyCommand, S3Client } from "@aws-sdk/client-s3";
18
- import { Client } from "pg";
19
- import { promisify } from "node:util";
20
- import { cacheTableStatements } from "@geekmidas/cache/postgres";
21
- //#region src/workspace/backends.ts
22
- /**
23
- * Which backend each declared kind resolves to — decided by where the project
24
- * deploys, and by nothing else.
25
- *
26
- * These used to be read out of a `services:` block, where one key answered two
27
- * questions: *does this exist* and *what backs it*. The first is the manifest's
28
- * — a declared `Cache` is why there is a cache — and the second is the deploy
29
- * target's, because the right cache for a Lambda is not the right cache for a
30
- * box already running Postgres. With both answered elsewhere there was nothing
31
- * left for the block to say, so it is gone and these read the target.
32
- *
33
- * Mail has no answer here at all: every provider speaks SMTP, so the provider
34
- * is whichever one the stage's mail URL points at.
35
- */
36
- /**
37
- * Which family of defaults a workspace's deploy target belongs to.
38
- *
39
- * One question, asked once: **does this target run containers the project
40
- * controls?** Dokploy and a bare server do, so a bucket or a cache can live
41
- * beside the app; AWS, Vercel and Cloudflare do not, so the default has to be
42
- * something managed. That is the whole of the distinction, and it is why
43
- * `MainProvider` is the right axis rather than the deploy target's own name —
44
- * three targets share one answer.
45
- *
46
- * An AWS deploy names no `deploy.default` at all, because it goes through SST,
47
- * which is why the absence is what selects `aws`.
48
- */
49
- function providerOf(workspace) {
50
- const target = workspace.deploy?.default;
51
- return target === "dokploy" || target === "server" ? "server" : "aws";
52
- }
53
- /**
54
- * The cache backend a target implies.
55
- *
56
- * The same answer locally and deployed: a local `gkm dev` for an AWS app still
57
- * uses the Upstash protocol, because a backend that differed between the two
58
- * would be worse than a slower one.
59
- */
60
- function cacheBackendFor(on) {
61
- return DEFAULT_CACHE[on];
62
- }
63
- /** Where a declared bucket lives on a target. */
64
- function storageBackendFor(on) {
65
- return DEFAULT_STORAGE[on];
66
- }
67
- /**
68
- * Which broker carries declared queues and topics on a target.
69
- *
70
- * Only consulted when something declares one; a project with no `Topic` or
71
- * `Queue` has no events at all, whatever the target.
72
- */
73
- function eventsBackendFor(on) {
74
- return DEFAULT_EVENTS$1[on];
75
- }
76
- //#endregion
77
- //#region src/reconcile/containers.ts
78
- /**
79
- * What gkm knows about each container it can derive.
80
- *
81
- * Everything provider-specific about the local target lives here: the image, the
82
- * ports the image listens on, and whether its data is worth keeping. The plan
83
- * says *which* containers exist and never says any of this, which is the split
84
- * the design asks for — neutral facts from the declaration, provider detail
85
- * from here and from config.
86
- *
87
- * Shared by allocation and by the compose writer so the two cannot disagree
88
- * about how many ports a container needs.
89
- */
90
- /**
91
- * The Postgres image for a major version.
92
- *
93
- * One place that knows the tag shape, so a declared version reaches the
94
- * container without anyone restating `-alpine` beside it.
95
- */
96
- function postgresImage(version) {
97
- return `postgres:${version}-alpine`;
98
- }
99
- /**
100
- * The default image for each container.
101
- *
102
- * Pinned to a major rather than `latest` where the image publishes one, so a
103
- * rebuild does not silently move a developer's Postgres a version. Overridable
104
- * per project: a project needing `postgis/postgis` says so in config.
105
- */
106
- const DEFAULT_IMAGES = {
107
- postgres: postgresImage(DEFAULT_POSTGRES_VERSION),
108
- minio: "pgsty/minio:RELEASE.2026-08-04T00-00-00Z",
109
- mailpit: "axllent/mailpit:latest",
110
- redis: "redis:8-alpine",
111
- "redis-http": "hiett/serverless-redis-http:latest",
112
- rabbitmq: "rabbitmq:4-management-alpine",
113
- localstack: "floci/floci:latest",
114
- caddy: "caddy:2-alpine"
115
- };
116
- /**
117
- * The ports each container listens on.
118
- *
119
- * The first is always the one an app connects to; the rest are consoles and
120
- * management UIs, published because a bucket or an inbox you can look at is most
121
- * of why these are real containers rather than stubs.
122
- */
123
- const PORTS = {
124
- postgres: [{
125
- key: "postgres",
126
- inside: 5432,
127
- label: "postgres"
128
- }],
129
- minio: [{
130
- key: "minio",
131
- inside: 9e3,
132
- label: "minio api"
133
- }, {
134
- key: "minio-console",
135
- inside: 9001,
136
- label: "minio console"
137
- }],
138
- mailpit: [{
139
- key: "mailpit",
140
- inside: 1025,
141
- label: "smtp"
142
- }, {
143
- key: "mailpit-web",
144
- inside: 8025,
145
- label: "mailpit inbox"
146
- }],
147
- redis: [{
148
- key: "redis",
149
- inside: 6379,
150
- label: "redis"
151
- }],
152
- "redis-http": [{
153
- key: "redis-http",
154
- inside: 80,
155
- label: "cache"
156
- }],
157
- rabbitmq: [{
158
- key: "rabbitmq",
159
- inside: 5672,
160
- label: "amqp"
161
- }, {
162
- key: "rabbitmq-management",
163
- inside: 15672,
164
- label: "rabbitmq console"
165
- }],
166
- localstack: [{
167
- key: "localstack",
168
- inside: 4566,
169
- label: "localstack"
170
- }],
171
- caddy: [{
172
- key: "caddy",
173
- inside: 443,
174
- label: "https edge"
175
- }]
176
- };
177
- /** The ports a container needs published. Empty for one gkm does not know. */
178
- function portsOf(container) {
179
- return PORTS[container] ?? [];
180
- }
181
- /** The key a container's primary port is allocated under. */
182
- function primaryPortKey(container) {
183
- return portsOf(container)[0]?.key ?? container;
184
- }
185
- /**
186
- * Every port key a set of containers needs, in a stable order.
187
- *
188
- * What allocation is handed: it assigns ports to names and knows nothing about
189
- * what listens on them.
190
- */
191
- function portKeys(containers) {
192
- return [...containers].sort().flatMap((container) => portsOf(container).map((port) => port.key));
193
- }
194
- /**
195
- * The named volume a container's data lives in.
196
- *
197
- * Mailpit deliberately has none: local mail is disposable, and an inbox that
198
- * survives days of dev is noise rather than state.
199
- */
200
- function volumeOf(container) {
201
- return {
202
- postgres: "postgres-data",
203
- minio: "minio-data",
204
- redis: "redis-data",
205
- rabbitmq: "rabbitmq-data",
206
- localstack: "localstack-data",
207
- caddy: "caddy-data"
208
- }[container];
209
- }
210
- //#endregion
211
- //#region src/reconcile/caddyfile.ts
212
- /**
213
- * The kinds the edge serves.
214
- *
215
- * Everything that owns a *public address*. Deployed, each of these has a real
216
- * hostname and a certificate, so this is what makes the local shape the same
217
- * one rather than a near-enough one — and the application is indifferent
218
- * either way, because it reads whichever address was injected and never
219
- * composes one.
220
- *
221
- * Adding a kind here is the whole of adding it to the edge.
222
- */
223
- const EDGE_KINDS = {
224
- "file-server": true,
225
- "rest-api": true,
226
- site: true
227
- };
228
- /**
229
- * How the edge reaches the host, from inside its container.
230
- *
231
- * A surface and a site are served by processes `gkm dev` starts on the host,
232
- * not by containers — so the edge has to leave Docker's network to reach them.
233
- * Docker Desktop resolves this name already; on Linux the compose definition
234
- * maps it to the host gateway.
235
- */
236
- const HOST_GATEWAY = "host.docker.internal";
237
- /**
238
- * The suffix every local host shares.
239
- *
240
- * `.localhost` rather than a made-up TLD because it resolves to loopback
241
- * without touching `/etc/hosts` — macOS and systemd-resolved both answer for
242
- * subdomains of it, and Caddy issues internal certificates for it by default.
243
- */
244
- const LOCAL_TLD = "localhost";
245
- /**
246
- * The sites a plan implies, one per file server.
247
- *
248
- * The leading label is the *server's* stage-scoped name rather than the
249
- * bucket's, which is the difference that matters: two servers over one bucket
250
- * are a legitimate arrangement — two cache behaviours, one origin — and naming
251
- * the host after the bucket would make them collide.
252
- */
253
- function sitesFor(plan, project, addresses = {}) {
254
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
255
- const sites = [];
256
- for (const resource of plan.resources) {
257
- if (!EDGE_KINDS[resource.kind]) continue;
258
- const host = hostFor(resource, project);
259
- if (resource.kind === "file-server") {
260
- const origin = resource.of ? byId.get(resource.of) : void 0;
261
- if (!origin) continue;
262
- sites.push({
263
- host,
264
- upstream: "http://minio:9000",
265
- rewrite: `/${origin.name}{uri}`
266
- });
267
- continue;
268
- }
269
- const address = addresses[resource.id];
270
- if (!address) continue;
271
- const port = portOf(address);
272
- if (!port) continue;
273
- sites.push({
274
- host,
275
- upstream: `http://${HOST_GATEWAY}:${port}`
276
- });
277
- }
278
- return sites;
279
- }
280
- /** The port a local address answers on, defaulting by scheme. */
281
- function portOf(address) {
282
- try {
283
- const { port, protocol } = new URL(address);
284
- return port || (protocol === "https:" ? "443" : "80");
285
- } catch {
286
- return;
287
- }
288
- }
289
- /**
290
- * Where one file server answers, including the stage its name carries.
291
- *
292
- * The project is a label rather than a decoration: it is what keeps two
293
- * checkouts from answering on one address. Omitted when there is no project to
294
- * name, because an empty label makes `uploads..localhost` — a host nothing
295
- * resolves and no certificate can be issued for.
296
- */
297
- function hostFor(resource, project) {
298
- return [
299
- resource.name,
300
- project,
301
- LOCAL_TLD
302
- ].filter(Boolean).join(".");
303
- }
304
- /**
305
- * The static root config, which only ever imports.
306
- *
307
- * Written once and identical for every stage, because the *sites* are what
308
- * differ and they live in their own files. That split is not tidiness: one
309
- * container serves every stage — the same way one Postgres holds `orders` and
310
- * `orders_test` — so a single Caddyfile would mean `gkm test` deleting the
311
- * routes `gkm dev` is serving, and each command silently breaking the other.
312
- */
313
- function caddyfileRoot() {
314
- return `${GENERATED}
315
- {
316
- # No ACME, no public DNS: the CA is local and so are the names.
317
- local_certs
318
- auto_https disable_redirects
319
- }
320
-
321
- # One file per stage, so two stages share this edge the way they already share
322
- # one Postgres and one MinIO.
323
- import /etc/caddy/sites/*.caddy
324
- `;
325
- }
326
- /**
327
- * One stage's sites, as the file imported above.
328
- *
329
- * `rewrite` rather than a path prefix on the address: the bucket is the
330
- * origin's business, and the client asks for the key it stored.
331
- *
332
- * `header_up Host {upstream_hostport}` matters more than it looks. MinIO routes
333
- * and signs on the Host header, so forwarding the requested hostname would make
334
- * it look for a bucket named after the domain.
335
- */
336
- function toCaddyfile(sites) {
337
- if (sites.length === 0) return `${GENERATED}
338
- # No file server is declared in this stage, so it routes nothing.
339
- `;
340
- const blocks = sites.map(({ host, upstream, rewrite }) => `
341
- https://${host} {
342
- tls internal
343
-
344
- reverse_proxy ${upstream} {${rewrite ? `
345
- rewrite ${rewrite}
346
- # MinIO routes and signs on the Host header, so forwarding the requested
347
- # hostname would make it look for a bucket named after the domain.
348
- header_up Host {upstream_hostport}` : `
349
- # The application reads whatever address was injected, so it has to see
350
- # the one a caller used — that is what makes a redirect, a cookie domain
351
- # and a generated link point back here rather than at the upstream.
352
- header_up Host {host}
353
- header_up X-Forwarded-Proto {scheme}`}
354
- }
355
- }`);
356
- return `${GENERATED}${blocks.join("\n")}\n`;
357
- }
358
- const GENERATED = `# Generated by gkm from the construct manifest — do not edit.
359
- #
360
- # One host per declared file server, in front of the object store that holds its
361
- # objects. This is the shape a file server has deployed — a domain serving a
362
- # bucket — which MinIO alone cannot produce: its virtual-host mode reads the
363
- # leading label as the bucket name.
364
- #
365
- # Certificates come from Caddy's own CA. "gkm dev" and "gkm test" export its
366
- # root and point Node at it, so nothing has to be installed to use these URLs
367
- # from code; a browser needs the root trusted once.
368
- `;
369
- //#endregion
370
- //#region src/reconcile/plan.ts
371
- /**
372
- * The reconcile plan — what a manifest wants to exist, for one stage.
373
- *
374
- * Pure. Turning the plan into running containers and provisioned resources is
375
- * the applier's job; deciding *what* should exist is this, so the decisions can
376
- * be asserted as data rather than by starting Docker.
377
- *
378
- * One plan serves every stage. `gkm dev` reconciles `development` and `gkm test`
379
- * reconciles `test`; they differ only in what the resources are called, never in
380
- * what infrastructure exists. Roles are cluster-scoped in Postgres while grants
381
- * are per-object, so one container and one role pair serve both.
382
- */
383
- /**
384
- * Which container serves a kind.
385
- *
386
- * Derived kinds map to the same container as their parent — a schema tenant
387
- * lives in its parent's Postgres — so the set is deduplicated rather than
388
- * counted.
389
- */
390
- const CONTAINERS = {
391
- database: "postgres",
392
- "database-reader": "postgres",
393
- "database-schema": "postgres",
394
- objects: "minio",
395
- "file-server": "caddy",
396
- email: "mailpit"
397
- };
398
- /**
399
- * The container a cache backend needs locally.
400
- *
401
- * Each one matches the protocol its deployed form speaks, which is the property
402
- * worth having: a cache that behaves differently in the two places is worse than
403
- * a slower one.
404
- *
405
- * `db` is deliberately absent, the same way `pgboss` is absent from
406
- * `EVENT_CONTAINERS`: the cache is a table in a database the manifest already
407
- * declares, so mapping it here would start a container for a project that needs
408
- * none.
409
- */
410
- const CACHE_CONTAINERS = {
411
- upstash: "redis-http",
412
- elasticache: "redis"
413
- };
414
- /**
415
- * Kinds that resolve a value without anything running.
416
- *
417
- * A secret is the case: it has no address, so there is nothing to start and
418
- * nothing to connect to — but it still appears in the plan, because the target
419
- * still has to resolve it.
420
- */
421
- const CONTAINERLESS = {
422
- secret: true,
423
- credential: true,
424
- "rest-api": true,
425
- site: true
426
- };
427
- /**
428
- * Containers that cannot run alone.
429
- *
430
- * The one case is the cache: `serverless-redis-http` is a proxy and needs the
431
- * Redis it proxies. Kept here rather than in the compose definition so the plan
432
- * -- which is what decides what must be running -- still names everything.
433
- */
434
- const REQUIRES = { "redis-http": ["redis"] };
435
- /**
436
- * The role each kind's one key plays, where it is not a URL.
437
- *
438
- * The twin of `ProvidesByKind` in `@geekmidas/manifest`: that is what a
439
- * construct declares, this is what the local target resolves, and both derive
440
- * the key from the same `provideKey` so they cannot disagree.
441
- */
442
- const ROLES = {
443
- queue: "publisherConnectionString",
444
- topic: "publisherConnectionString",
445
- credential: "credential"
446
- };
447
- /** The kinds whose container is the events backend's rather than their own. */
448
- const EVENT_KINDS = {
449
- queue: true,
450
- topic: true
451
- };
452
- /**
453
- * Which kinds provision something *inside* their container.
454
- *
455
- * A database creates a database, a bucket creates a bucket; mail creates
456
- * nothing — Mailpit accepts whatever is sent to it and has no per-stage object
457
- * to name. Both still appear in the plan, because both still resolve a URL; the
458
- * flag is the difference between "must be running" and "must be created".
459
- */
460
- const PROVISIONS = {
461
- database: true,
462
- "database-reader": true,
463
- "database-schema": true,
464
- objects: true,
465
- cache: true,
466
- "file-server": true
467
- };
468
- /**
469
- * The container each events backend needs, where it needs one of its own.
470
- *
471
- * `pgboss` is deliberately absent rather than mapped to `postgres`: it is a
472
- * schema tenant in a database the manifest already declares, so mapping it here
473
- * would start a Postgres for a project that declared no database at all.
474
- *
475
- * This one comes from config rather than from a declaration because there are
476
- * no `topic` or `queue` kinds yet. When they land the mapping moves to
477
- * {@link CONTAINERS} keyed by kind, and this constant goes with them.
478
- */
479
- const EVENT_CONTAINERS = {
480
- sns: "localstack",
481
- rabbitmq: "rabbitmq"
482
- };
483
- /** The backend a project gets when it declares queues or topics and says nothing. */
484
- const DEFAULT_EVENTS = "pgboss";
485
- /**
486
- * How a resource of each kind separates its stage suffix.
487
- *
488
- * Postgres identifiers are snake_case and a hyphen would need quoting
489
- * everywhere; buckets and queues are kebab and disallow underscores in some
490
- * providers. The suffix is the same word either way.
491
- */
492
- const SEPARATORS = {
493
- database: "_",
494
- "database-reader": "_",
495
- "database-schema": "_",
496
- objects: "-"
497
- };
498
- /**
499
- * The stage-scoped name for a resource.
500
- *
501
- * The local stage carries no suffix, so `gkm dev` keeps using `orders` and a
502
- * developer's psql history, saved connections, and muscle memory survive a
503
- * change of stage name. Every other stage is suffixed.
504
- */
505
- function resourceName(id, kind, stage, localStage) {
506
- const base = id.toLowerCase();
507
- if (stage === localStage) return base;
508
- return `${base}${SEPARATORS[kind] ?? "-"}${stage}`;
509
- }
510
- /**
511
- * The container a kind needs, or `undefined` if it needs none.
512
- *
513
- * Queues and topics have no container of their own — they live in whichever
514
- * broker the project selected, which is why the backend is an argument here
515
- * rather than a second pass that adds containers after the fact.
516
- */
517
- function containerFor(kind, events = DEFAULT_EVENTS, cache = DEFAULT_CACHE.aws, derived = false, edge = true) {
518
- if (EVENT_KINDS[kind]) return EVENT_CONTAINERS[events] ?? CONTAINERS.database;
519
- if (kind === "file-server") return edge ? "caddy" : CONTAINERS.objects;
520
- if (kind === "cache") {
521
- if (derived) return CONTAINERS.database;
522
- return CACHE_CONTAINERS[cache] ?? CONTAINERS.database;
523
- }
524
- return CONTAINERS[kind];
525
- }
526
- /**
527
- * Build the plan for a manifest and stage.
528
- *
529
- * `order` is the caller's provisioning order — parents before children — which
530
- * `provisionOrder` produces from the manifest. Passing it in keeps this
531
- * function free of the traversal and makes the ordering assertable on its own.
532
- */
533
- function planFor(manifest, stage, order, options = {}) {
534
- const containers = /* @__PURE__ */ new Set();
535
- const resources = [];
536
- const events = options.events ?? "pgboss";
537
- const cache = options.cache ?? DEFAULT_CACHE.aws;
538
- for (const id of order) {
539
- const declaration = manifest[id];
540
- if (!declaration) continue;
541
- const container = containerFor(declaration.kind, events, cache, "of" in declaration && typeof declaration.of === "string", options.edge !== false);
542
- if (!container && !CONTAINERLESS[declaration.kind]) continue;
543
- if (container) {
544
- containers.add(container);
545
- for (const required of REQUIRES[container] ?? []) containers.add(required);
546
- }
547
- resources.push({
548
- id,
549
- kind: declaration.kind,
550
- ...container ? { container } : {},
551
- name: resourceName(id, declaration.kind, stage, options.localStage),
552
- envKey: providedKeyFor(id, declaration.kind, ROLES[declaration.kind] ?? "url"),
553
- provisions: PROVISIONS[declaration.kind] === true,
554
- ...declaration.kind === "rest-api" ? { callers: dependentsOf(manifest, id) } : {},
555
- ...declaration.kind === "site" ? { publicEnv: publicEnvFor(declaration, manifest) } : {},
556
- ...declaration.kind === "file-server" && declaration.open?.length ? { open: declaration.open } : {},
557
- ..."of" in declaration ? { of: declaration.of } : {},
558
- ..."schema" in declaration && declaration.schema ? { schema: declaration.schema } : {},
559
- ..."version" in declaration && declaration.version ? { version: declaration.version } : {},
560
- ..."roles" in declaration && declaration.roles === false ? { roles: false } : {},
561
- ..."table" in declaration && declaration.table ? { table: declaration.table } : {}
562
- });
563
- }
564
- if (options.edge !== false && resources.some((r) => EDGE_KINDS[r.kind] === true)) containers.add("caddy");
565
- for (const extra of options.extraContainers ?? []) containers.add(extra);
566
- if (events === "pgboss" && resources.some((r) => EVENT_KINDS[r.kind]) && !resources.some((r) => r.kind === "database")) throw new PgBossNeedsDatabase(resources.filter((r) => EVENT_KINDS[r.kind]).map((r) => r.id));
567
- if (cache === "db") {
568
- const placeless = resources.filter((r) => r.kind === "cache" && !r.of);
569
- if (placeless.length > 0) {
570
- const databases = resources.filter((r) => r.kind === "database");
571
- const [only] = databases;
572
- if (!only) throw new CacheNeedsDatabase(resources.filter((r) => r.kind === "cache").map((r) => r.id));
573
- if (databases.length > 1) throw new CacheIsAmbiguous(placeless.map((r) => r.id), databases.map((r) => r.id));
574
- for (const resource of placeless) resource.of = only.id;
575
- }
576
- }
577
- return {
578
- stage,
579
- events,
580
- cache,
581
- containers: [...containers],
582
- resources
583
- };
584
- }
585
- /**
586
- * Queues or topics were declared with pg-boss and no database to hold them.
587
- *
588
- * Not a reconcile failure but a manifest one: the fix is a line of application
589
- * code either way — declare a database, or select a backend that brings its own
590
- * broker.
591
- */
592
- var CacheNeedsDatabase = class extends Error {
593
- ids;
594
- constructor(ids) {
595
- super(`A cache backed by the database needs a declared database, and none was declared, and on this deploy target that is where a cache lives. Declare one. Caches affected: ${ids.join(", ")}.`);
596
- this.ids = ids;
597
- this.name = "CacheNeedsDatabase";
598
- }
599
- };
600
- /**
601
- * A `'db'` cache — a server target's default — in an app that declares more
602
- * than one database.
603
- *
604
- * The target says *a* database and the graph offers several, so there is no
605
- * answer to give — and the wrong kind of failure would be to pick one, since a
606
- * cache silently landing in the wrong database is a bug that surfaces as
607
- * missing rows much later. The fix is a stronger statement in application code:
608
- * `orders.cache('Sessions')` names the database, which is a fact about the
609
- * application rather than a deployment choice.
610
- */
611
- var CacheIsAmbiguous = class extends Error {
612
- ids;
613
- databases;
614
- constructor(ids, databases) {
615
- super(`A cache backed by the database needs to know which one, and this app declares ${databases.length}: ${databases.join(", ")}. Declare the cache from its database — e.g. ${databases[0]}.cache('Sessions') — rather than as a bare new Cache(). Caches affected: ${ids.join(", ")}.`);
616
- this.ids = ids;
617
- this.databases = databases;
618
- this.name = "CacheIsAmbiguous";
619
- }
620
- };
621
- var PgBossNeedsDatabase = class extends Error {
622
- ids;
623
- constructor(ids) {
624
- super(`pg-boss keeps its queues in a declared database, and none was declared. Declare one: on this deploy target, events are carried by pg-boss. Queues and topics affected: ${ids.join(", ")}.`);
625
- this.ids = ids;
626
- this.name = "PgBossNeedsDatabase";
627
- }
628
- };
629
- //#endregion
630
- //#region src/reconcile/env.ts
631
- /**
632
- * The URLs a reconciled stage injects.
633
- *
634
- * One `<NAME>_URL` per construct, and the protocol picks the driver. This is the
635
- * seam between the target that writes a URL and the client that parses it, so
636
- * every component of it is read off the resource — never inherited from ambient
637
- * environment. A bucket can live in a different region than the function reading
638
- * it, and `AWS_REGION` in a Lambda is the *function's* region, so a URL that
639
- * omits `?region=` breaks cross-region silently at runtime.
640
- *
641
- * Locally that self-containment is what lets the port be whatever was free: the
642
- * app reads `ORDERS_URL` and never sees a host or a port.
643
- */
644
- /**
645
- * The credential local containers are brought up with.
646
- *
647
- * The design's `roles: false` case — both URLs fall back to the cluster's master
648
- * credential. A deliberate downgrade, not a default: it holds until the role DDL
649
- * lands in `@geekmidas/db`, at which point the runtime role's URL replaces this
650
- * and the owner URL stops being reachable from any manifest edge.
651
- */
652
- const LOCAL_USER$2 = "geekmidas";
653
- /** The host containers are published on. */
654
- const LOCAL_HOST = "localhost";
655
- /** The region local buckets claim, so the client has one to sign with. */
656
- const LOCAL_REGION = "us-east-1";
657
- /**
658
- * The credentials the S3 client resolves for MinIO.
659
- *
660
- * An `s3://` URL deliberately carries none: deployed, the SDK reads them from
661
- * the execution role, so a URL that embedded a key would be one more thing to
662
- * rotate and one more thing to leak into a log. Locally there is no role, and
663
- * the same chain reads these — which is why they are injected beside the URL
664
- * rather than written into it.
665
- */
666
- const STORAGE_CREDENTIALS = {
667
- AWS_ACCESS_KEY_ID: LOCAL_USER$2,
668
- AWS_SECRET_ACCESS_KEY: LOCAL_USER$2,
669
- AWS_REGION: LOCAL_REGION
670
- };
671
- /** The token the local cache proxy accepts. Matches the compose definition. */
672
- const LOCAL_TOKEN$1 = "geekmidas";
673
- /** The schema pg-boss keeps its tables in, inside the declared database. */
674
- const PGBOSS_SCHEMA = "pgboss";
675
- /** The exchange every local topic and queue shares on RabbitMQ. */
676
- const RABBITMQ_EXCHANGE = "geekmidas.events";
677
- /**
678
- * Every env key a reconciled plan resolves, and its value.
679
- *
680
- * Keys come from the declaration rather than being re-derived, so what the build
681
- * publishes and what the app reads cannot drift.
682
- */
683
- function envFor(plan, options) {
684
- const env = {};
685
- const resolved = {};
686
- for (const resource of plan.resources) {
687
- const url = urlFor(resource, plan, options.ports, options.project ?? "", options.addresses);
688
- if (url) resolved[resource.id] = url;
689
- }
690
- for (const resource of plan.resources) {
691
- const url = resolved[resource.id];
692
- if (resource.kind === "rest-api") Object.assign(env, surfaceEnv(resource, url, resolved));
693
- if (url) env[resource.envKey] = url;
694
- if (isDatabase(resource.kind) && resource.roles !== false) {
695
- const owner = ownerUrl(resource, plan, options.ports, options.project ?? "");
696
- if (owner) env[provideKey(resource.id, "ownerUrl")] = owner;
697
- }
698
- if (resource.kind === "email" && url) env[provideKey(resource.id, "from")] = options.mailFrom ?? `noreply@${LOCAL_HOST}`;
699
- }
700
- Object.assign(env, publicEnv(plan, env));
701
- Object.assign(env, brokerEnv(plan, options.ports));
702
- if (plan.resources.some((r) => r.kind === "objects" && env[r.envKey])) Object.assign(env, STORAGE_CREDENTIALS);
703
- return env;
704
- }
705
- /**
706
- * The values a site's bundler inlines, under the names it inlines them by.
707
- *
708
- * A rename and nothing more. `API_URL` was resolved once, by the same code that
709
- * resolved it for the server; a site reads the same value under `VITE_API_URL`
710
- * because that prefix is how its bundler is told to ship it. Nothing is derived
711
- * twice, so a site and its API cannot come to disagree about where the API is.
712
- *
713
- * A source that resolved to nothing is skipped rather than written empty: an
714
- * inlined empty string is a frontend that builds and then fails at runtime
715
- * against `http:///`, where a missing variable fails at build with the name of
716
- * the thing that is missing.
717
- */
718
- function publicEnv(plan, resolved) {
719
- const env = {};
720
- for (const resource of plan.resources) for (const [key, source] of Object.entries(resource.publicEnv ?? {})) {
721
- const value = resolved[source];
722
- if (value) env[key] = value;
723
- }
724
- return env;
725
- }
726
- /**
727
- * What a surface publishes beyond its own address: who may call it, and where
728
- * a cookie set by it is readable.
729
- *
730
- * Both are read off the same list — the constructs that declared an edge to
731
- * this surface — which is why neither appears in application code. A surface
732
- * that listed its own callers would be edited every time something new called
733
- * it, and the thing being edited is already recorded in the graph.
734
- *
735
- * An empty origin list is written, and a surface with no address writes nothing
736
- * at all. The two cases look alike and are not: "nothing depends on this yet" is
737
- * a real state a target should publish, while "this surface has no address here"
738
- * means it is not running in this stage, and keys belong with the address they
739
- * describe.
740
- */
741
- function surfaceEnv(resource, url, resolved = {}) {
742
- if (!url) return {};
743
- const origins = [...new Set((resource.callers ?? []).map((caller) => resolved[caller]).filter((address) => Boolean(address)).map(originOf).filter((origin) => Boolean(origin)))].sort();
744
- const domain = cookieDomain([url, ...origins]);
745
- return {
746
- [provideKey(resource.id, "trustedOrigins")]: origins.join(","),
747
- ...domain ? { [provideKey(resource.id, "cookieDomain")]: domain } : {}
748
- };
749
- }
750
- /** An address reduced to the origin a browser compares against. */
751
- function originOf(address) {
752
- try {
753
- return new URL(address).origin;
754
- } catch {
755
- return;
756
- }
757
- }
758
- /**
759
- * The runtime role of whatever a derived node hangs off.
760
- *
761
- * A reader's parent may itself be a schema tenant, so this follows `of` by one
762
- * hop rather than assuming the cluster — the reader of a tenant reads that
763
- * tenant's schema, not the database's.
764
- */
765
- function parentRole(resource, plan) {
766
- const parent = plan.resources.find((r) => r.id === resource.of);
767
- return parent ? localRole(parent) : resource.name;
768
- }
769
- /** Whether a kind connects to Postgres and therefore has an owner role. */
770
- function isDatabase(kind) {
771
- return kind === "database" || kind === "database-schema";
772
- }
773
- /**
774
- * The URL a migrator connects with — the owner role, which can create, alter
775
- * and drop.
776
- *
777
- * Never in `provides`, which is the whole point. A handler that could reach this
778
- * could `DROP TABLE`, and the security property the role split exists for is
779
- * that it cannot: the value is injected by `gkm exec` for the migrate step and
780
- * by nothing else.
781
- */
782
- function ownerUrl(resource, plan, ports, project) {
783
- if (!resource.container) return void 0;
784
- const port = ports[primaryPortKey(resource.container)];
785
- if (port === void 0) return void 0;
786
- const owner = ownerRole(localRole(resource));
787
- return postgres(port, rootDatabase(resource, plan), {
788
- user: owner,
789
- password: localRolePassword(project, plan, owner)
790
- });
791
- }
792
- /**
793
- * The shared broker keys, when anything is published or consumed.
794
- *
795
- * A queue's own key is the producer's. These two are the *connection* itself,
796
- * which locally is one broker for every queue and topic in the project: the
797
- * generated pollers open a single connection and subscribe each worker by name
798
- * on it. Deployed there is no such thing — a Lambda is handed its own event
799
- * source — so this pair exists for the local target and says so.
800
- */
801
- function brokerEnv(plan, ports) {
802
- const carrier = plan.resources.find((r) => r.kind === "queue" || r.kind === "topic");
803
- if (!carrier) return {};
804
- const publisher = urlFor(carrier, plan, ports, "");
805
- if (!publisher) return {};
806
- return {
807
- EVENT_PUBLISHER_CONNECTION_STRING: publisher,
808
- EVENT_SUBSCRIBER_CONNECTION_STRING: plan.events === "sns" ? publisher.replace(/^sns:/, "sqs:") : publisher
809
- };
810
- }
811
- /**
812
- * The URL for one planned resource.
813
- *
814
- * Every part of it comes from the resource and the port it was published on.
815
- */
816
- function urlFor(resource, plan, ports, project, addresses = {}) {
817
- if (resource.kind === "secret") return localSecret(project, plan, resource);
818
- if (resource.kind === "credential") return void 0;
819
- if (resource.kind === "rest-api" || resource.kind === "site") {
820
- const address = addresses[resource.id];
821
- const edge = plan.containers.includes("caddy") ? ports[primaryPortKey("caddy")] : void 0;
822
- return address && edge !== void 0 ? `https://${hostFor(resource, project)}:${edge}` : address;
823
- }
824
- if (!resource.container) return void 0;
825
- const port = ports[primaryPortKey(resource.container)];
826
- if (port === void 0) return void 0;
827
- switch (resource.kind) {
828
- case "database":
829
- case "database-schema":
830
- case "database-reader": {
831
- const database = rootDatabase(resource, plan);
832
- if (resource.roles === false) {
833
- const schema = schemaOf(resource, plan);
834
- return schema ? `${postgres(port, database)}?search_path=${schema}` : postgres(port, database);
835
- }
836
- const role = resource.kind === "database-reader" ? readerRole(parentRole(resource, plan)) : localRole(resource);
837
- return postgres(port, database, {
838
- user: role,
839
- password: localRolePassword(project, plan, role)
840
- });
841
- }
842
- case "email": return `smtp://${LOCAL_HOST}:${port}`;
843
- case "objects": return `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${LOCAL_HOST}:${port}&forcePathStyle=true`;
844
- case "file-server": {
845
- const origin = plan.resources.find((r) => r.id === resource.of);
846
- if (!origin) return void 0;
847
- return plan.containers.includes("caddy") ? `https://${hostFor(resource, project)}:${port}` : `http://${LOCAL_HOST}:${port}/${origin.name}`;
848
- }
849
- case "cache":
850
- if (resource.of) {
851
- const parent = plan.resources.find((r) => r.id === resource.of);
852
- const url = parent ? urlFor(parent, plan, ports, project, addresses) : void 0;
853
- return url ? withTable(url, resource.table ?? cacheTable(resource.id)) : void 0;
854
- }
855
- switch (plan.cache) {
856
- case "elasticache": return `redis://${LOCAL_HOST}:${port}`;
857
- default: return `http://:${LOCAL_TOKEN$1}@${LOCAL_HOST}:${port}`;
858
- }
859
- case "queue":
860
- case "topic": return broker(plan, port);
861
- default: return;
862
- }
863
- }
864
- /**
865
- * The producer's connection string, composed from the backend the plan chose.
866
- *
867
- * The protocol is what picks the transport, so a producer never branches: the
868
- * same `.publish()` reaches pg-boss here and SQS deployed because the string it
869
- * was handed said so.
870
- */
871
- function broker(plan, port) {
872
- switch (plan.events) {
873
- case "pgboss": {
874
- const database = plan.resources.find((r) => r.kind === "database");
875
- if (!database) throw new PgBossNeedsDatabase([]);
876
- return `pgboss://${LOCAL_USER$2}:${LOCAL_USER$2}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;
877
- }
878
- case "rabbitmq": return `rabbitmq://${LOCAL_USER$2}:${LOCAL_USER$2}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;
879
- case "sns": throw new UnprovisionedEventsBackend("sns");
880
- }
881
- }
882
- /** A local Postgres URL, master credential and all. */
883
- function postgres(port, database, credential = {
884
- user: LOCAL_USER$2,
885
- password: LOCAL_USER$2
886
- }) {
887
- return `postgres://${credential.user}:${credential.password}@${LOCAL_HOST}:${port}/${database}`;
888
- }
889
- /**
890
- * The role a handler connects as, for one database or tenant.
891
- *
892
- * The construct's id, lowercased and stage-scoped exactly as its database or
893
- * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two
894
- * stages sharing one cluster cannot share a credential. Roles are cluster-scoped
895
- * in Postgres, which is why the suffix is not optional here the way it is for a
896
- * schema.
897
- */
898
- function localRole(resource) {
899
- return resource.name;
900
- }
901
- /**
902
- * The password for a derived local role.
903
- *
904
- * Derived rather than random, for the same reason the local secret is: a
905
- * password that changed on every `gkm dev` would lock a developer out of the
906
- * data they had a moment ago. Seeded by the project so two checkouts do not
907
- * share one, and by the stage so `test` and `development` do not.
908
- *
909
- * It is a *local* credential by construction — the cluster is on loopback and
910
- * the seed is a checkout path — and no deployed target uses this function.
911
- */
912
- function localRolePassword(project, plan, role) {
913
- return createHash("sha256").update(`${project}:${plan.stage}:role:${role}`).digest("base64url").slice(0, 32);
914
- }
915
- /**
916
- * A cache's address: its database's URL, carrying the table it reads.
917
- *
918
- * Appended rather than kept beside the URL as a second key, for the reason the
919
- * design gives everywhere else — an address and what it opens are one fact, and
920
- * two keys are one more thing to keep in step.
921
- */
922
- function withTable(url, table) {
923
- const parsed = new URL(url);
924
- parsed.searchParams.set("table", table);
925
- return parsed.toString();
926
- }
927
- /**
928
- * The physical database a derived resource lives in.
929
- *
930
- * Walks `of` to the top rather than reading the immediate parent, because a
931
- * reader's parent may itself be a schema tenant — two hops from the database
932
- * that actually exists.
933
- */
934
- function rootDatabase(resource, plan) {
935
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
936
- let current = resource;
937
- while (current.of) {
938
- const parent = byId.get(current.of);
939
- if (!parent) break;
940
- current = parent;
941
- }
942
- return current.name;
943
- }
944
- /** The schema a derived resource puts on its search path, if it has one. */
945
- function schemaOf(resource, plan) {
946
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
947
- let current = resource;
948
- while (current) {
949
- if (current.kind === "database-schema") return current.schema;
950
- current = current.of ? byId.get(current.of) : void 0;
951
- }
952
- }
953
- /**
954
- * A backend whose local addresses cannot be derived yet.
955
- *
956
- * SNS and SQS are addressed by ARN, which means the topic and queue have to be
957
- * created in LocalStack before a URL can name them. Until that provisioning
958
- * lands, saying so is better than handing out a string that fails on first use.
959
- */
960
- var UnprovisionedEventsBackend = class extends Error {
961
- backend;
962
- constructor(backend) {
963
- super(`The local target cannot derive addresses for '${backend}' yet — its topics and queues are named by ARN, which nothing creates locally. Use 'pgboss' (the default) or 'rabbitmq' for local development.`);
964
- this.backend = backend;
965
- this.name = "UnprovisionedEventsBackend";
966
- }
967
- };
968
- /**
969
- * The value a secret resolves to locally.
970
- *
971
- * A hash of what identifies it, so it is stable, distinct per project, stage
972
- * and construct, and never written to disk as a literal. Deployed this is the
973
- * one kind whose value does *not* come from here — a secret manager generates
974
- * it once and the target reads it back.
975
- */
976
- function localSecret(project, plan, resource) {
977
- return createHash("sha256").update(`${project}:${plan.stage}:${resource.id}`).digest("base64url").slice(0, 43);
978
- }
979
- //#endregion
980
- //#region src/reconcile/apps.ts
981
- /**
982
- * The apps, as services beside the containers their constructs derive.
983
- *
984
- * `gkm docker` used to write these by hand: every backend got
985
- * `DATABASE_URL=postgresql://…@postgres:5432/app` and `REDIS_URL=redis://redis`,
986
- * which was right only for a project whose single database happened to be
987
- * called `Database` — an `Orders` database publishes `ORDERS_URL`, a schema
988
- * tenant has a URL of its own, and buckets and mail were not wired at all.
989
- *
990
- * Now an app's environment is exactly what reconcile hands `gkm dev`: every key
991
- * the declared constructs provide, from the same derivation. The only
992
- * difference is where the addresses point — at the containers by service name
993
- * on the compose network, rather than at `localhost` on the ports published for
994
- * the host.
995
- *
996
- * Always from the *local* stage's plan, whichever stage is being reconciled:
997
- * `gkm test` rewrites the same file, and running the tests must not quietly
998
- * point these apps at the test databases.
999
- */
1000
- /** The profile app services carry, so `gkm dev` starts only the containers. */
1001
- const APPS_PROFILE = "apps";
1002
- /**
1003
- * Where an app's image is built from.
1004
- *
1005
- * An app at the project root is a single-app project, whose `gkm docker`
1006
- * writes `.gkm/docker/Dockerfile`; a workspace writes one per app.
1007
- */
1008
- function dockerfileOf(appName, path) {
1009
- return path === "." ? ".gkm/docker/Dockerfile" : `.gkm/docker/Dockerfile.${appName}`;
1010
- }
1011
- /**
1012
- * Every construct key, addressed across the compose network.
1013
- *
1014
- * `envFor` is asked with a placeholder port for every port key, so each
1015
- * `localhost:<placeholder>` in its answer names exactly one container port —
1016
- * two containers listening on the same port inside cannot be confused — and is
1017
- * rewritten to `<container>:<inside>`.
1018
- */
1019
- function inNetworkEnv(workspace, manifest) {
1020
- const plan = planFor(manifest, workspace.stages.local, provisionOrder(manifest), {
1021
- localStage: workspace.stages.local,
1022
- ...backendsOf(workspace)
1023
- });
1024
- const placeholders = {};
1025
- const targets = /* @__PURE__ */ new Map();
1026
- let next = 49152;
1027
- for (const container of [...plan.containers].sort()) for (const port of portsOf(container)) {
1028
- placeholders[port.key] = next;
1029
- targets.set(next, `${container}:${port.inside}`);
1030
- next += 1;
1031
- }
1032
- for (const key of portKeys(plan.containers)) placeholders[key] ??= next++;
1033
- const env = envFor(plan, {
1034
- ports: placeholders,
1035
- project: workspace.name,
1036
- addresses: surfaceAddresses(workspace, manifest, (app, port) => `http://${app}:${port}`)
1037
- });
1038
- const rewrite = (value) => value.replace(/(?:localhost|127\.0\.0\.1):(\d+)/g, (match, port) => {
1039
- return targets.get(Number(port)) ?? match;
1040
- });
1041
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, rewrite(value)]));
1042
- }
1043
- /** One compose service per app the workspace runs, behind the apps profile. */
1044
- function appServices(workspace, manifest, containers) {
1045
- const env = inNetworkEnv(workspace, manifest);
1046
- const services = {};
1047
- for (const [name, app] of Object.entries(workspace.apps)) {
1048
- if (app.type === "mobile" || !app.port) continue;
1049
- const key = appKey(name);
1050
- const health = app.type === "web" ? "/" : "/health";
1051
- services[key] = {
1052
- image: `${key}:\${TAG:-latest}`,
1053
- build: {
1054
- context: ".",
1055
- dockerfile: dockerfileOf(name, app.path)
1056
- },
1057
- profiles: [APPS_PROFILE],
1058
- ports: [`${app.port}:${app.port}`],
1059
- environment: {
1060
- NODE_ENV: "production",
1061
- PORT: String(app.port),
1062
- ...env
1063
- },
1064
- ...containers.some((c) => c !== "caddy") ? { depends_on: containers.filter((c) => c !== "caddy") } : {},
1065
- healthcheck: {
1066
- test: [
1067
- "CMD",
1068
- "wget",
1069
- "-q",
1070
- "--spider",
1071
- `http://localhost:${app.port}${health}`
1072
- ],
1073
- interval: "10s",
1074
- timeout: "5s",
1075
- retries: 5
1076
- }
1077
- };
1078
- }
1079
- return services;
1080
- }
1081
- //#endregion
1082
- //#region src/reconcile/clients.ts
1083
- /**
1084
- * The real Postgres and MinIO clients the applier runs against.
1085
- *
1086
- * Kept apart from `provision.ts` so the rules there — what gets created, in what
1087
- * order, and never dropping anything — are asserted against fakes, while the
1088
- * drivers live here where there is nothing to assert but wiring.
1089
- *
1090
- * Both are constructed from the same local addresses the env writer composes,
1091
- * so the applier cannot end up talking to a different container than the app.
1092
- */
1093
- /** The credential local containers are brought up with. */
1094
- const LOCAL_USER$1 = "geekmidas";
1095
- /**
1096
- * A Postgres client that opens one connection per database it is asked about.
1097
- *
1098
- * `CREATE DATABASE` cannot run from a connection to the database being created,
1099
- * and a schema must be created from inside its own database — so the database is
1100
- * part of each query rather than fixed when the client is built.
1101
- */
1102
- function pgClient(port) {
1103
- return { async query(database, sql, values) {
1104
- const client = new Client({
1105
- host: "localhost",
1106
- port,
1107
- user: LOCAL_USER$1,
1108
- password: LOCAL_USER$1,
1109
- database: database ?? LOCAL_USER$1
1110
- });
1111
- await client.connect();
1112
- try {
1113
- return (await client.query(sql, values)).rows;
1114
- } finally {
1115
- await client.end();
1116
- }
1117
- } };
1118
- }
1119
- /** A bucket client pointed at the local MinIO. */
1120
- function bucketClient(port) {
1121
- const s3 = new S3Client({
1122
- region: "us-east-1",
1123
- endpoint: `http://localhost:${port}`,
1124
- forcePathStyle: true,
1125
- credentials: {
1126
- accessKeyId: LOCAL_USER$1,
1127
- secretAccessKey: LOCAL_USER$1
1128
- }
1129
- });
1130
- return {
1131
- async exists(bucket) {
1132
- try {
1133
- await s3.send(new HeadBucketCommand({ Bucket: bucket }));
1134
- return true;
1135
- } catch {
1136
- return false;
1137
- }
1138
- },
1139
- async create(bucket) {
1140
- await s3.send(new CreateBucketCommand({ Bucket: bucket }));
1141
- },
1142
- async policy(bucket) {
1143
- try {
1144
- return (await s3.send(new GetBucketPolicyCommand({ Bucket: bucket }))).Policy;
1145
- } catch {
1146
- return;
1147
- }
1148
- },
1149
- async setPolicy(bucket, policy) {
1150
- await s3.send(new PutBucketPolicyCommand({
1151
- Bucket: bucket,
1152
- Policy: policy
1153
- }));
1154
- }
1155
- };
1156
- }
1157
- //#endregion
1158
- //#region src/reconcile/compose.ts
1159
- /**
1160
- * The compose document a plan implies.
1161
- *
1162
- * The third declaration of the same containers disappears here: today a
1163
- * `services: ['postgres','minio']` block is kept in step with the code by hand,
1164
- * which is the triplication this design exists to remove, in the one place you
1165
- * touch every day. A `database` implies Postgres; the list is derived.
1166
- *
1167
- * Returns an object rather than a string for the same reason `plan` is pure —
1168
- * what should exist is asserted as data, and turning it into YAML is one line at
1169
- * the edge.
1170
- *
1171
- * What stays config is unchanged: images and versions are pinned explicitly, and
1172
- * a container no construct implies is still declared by hand. Neutral facts come
1173
- * from the declaration, provider detail from config.
1174
- */
1175
- /** The credential every derived container is brought up with locally. */
1176
- const LOCAL_USER = "geekmidas";
1177
- /**
1178
- * The token the local cache accepts.
1179
- *
1180
- * Fixed rather than generated: it is only ever reachable on a port this project
1181
- * published, and the URL that carries it is derived, so nothing is made safer
1182
- * by making it unguessable and a stable one keeps `redis-cli` sessions working.
1183
- */
1184
- const LOCAL_TOKEN = "geekmidas";
1185
- /**
1186
- * Build the compose document for a plan.
1187
- *
1188
- * Every container is published on its assigned port, never on the image's
1189
- * default: the point of allocation is that two projects can run at once, and
1190
- * one container publishing 5432 puts that back.
1191
- */
1192
- function composeFor(plan, options) {
1193
- const services = {};
1194
- const volumes = {};
1195
- for (const container of [...plan.containers].sort()) {
1196
- const declared = container === "postgres" ? plan.resources.find((r) => r.version)?.version : void 0;
1197
- const image = declared ? postgresImage(declared) : DEFAULT_IMAGES[container];
1198
- if (!image) throw new UnknownContainer(container);
1199
- services[container] = define(container, image, publish(container, options.ports));
1200
- const volume = volumeOf(container);
1201
- if (volume) volumes[volume] = {};
1202
- }
1203
- return {
1204
- name: options.project,
1205
- services: {
1206
- ...services,
1207
- ...options.apps
1208
- },
1209
- ...Object.keys(volumes).length ? { volumes } : {}
1210
- };
1211
- }
1212
- /** Render a compose document as the file it becomes. */
1213
- function toYaml(file) {
1214
- return `# Generated by gkm from the construct manifest — do not edit.
1215
- # Containers are derived from what the app declares. Image pins and anything
1216
- # no construct implies go in your own docker-compose.yml, which is merged over
1217
- # this file and wins:
1218
- #
1219
- # docker compose -f docker-compose.constructs.yml -f docker-compose.yml …
1220
- #
1221
- # "gkm dev" and "gkm test" start the containers. The apps sit behind the
1222
- # "apps" profile: run "gkm setup", then
1223
- # docker compose -f docker-compose.constructs.yml --profile apps up --build
1224
- ${stringify(file, { lineWidth: 0 })}`;
1225
- }
1226
- /** A container with no image, from config or from the defaults. */
1227
- var UnknownContainer = class extends Error {
1228
- /** The container that could not be resolved. */
1229
- container;
1230
- /** The containers that have a default, so the caller can see the set. */
1231
- known = Object.keys(DEFAULT_IMAGES).sort();
1232
- constructor(container) {
1233
- super("No image is known for this container; pin one in config");
1234
- this.name = "UnknownContainer";
1235
- this.container = container;
1236
- }
1237
- };
1238
- /** One container's definition, published on the port it was assigned. */
1239
- function define(container, image, published) {
1240
- switch (container) {
1241
- case "postgres": return {
1242
- image,
1243
- restart: "unless-stopped",
1244
- ports: published,
1245
- environment: {
1246
- POSTGRES_USER: LOCAL_USER,
1247
- POSTGRES_PASSWORD: LOCAL_USER,
1248
- POSTGRES_DB: LOCAL_USER
1249
- },
1250
- volumes: ["postgres-data:/var/lib/postgresql"],
1251
- healthcheck: {
1252
- test: ["CMD-SHELL", `pg_isready -U ${LOCAL_USER}`],
1253
- interval: "5s",
1254
- timeout: "3s",
1255
- retries: 10,
1256
- start_period: "10s"
1257
- }
1258
- };
1259
- case "minio": return {
1260
- image,
1261
- restart: "unless-stopped",
1262
- ports: published,
1263
- environment: {
1264
- MINIO_ROOT_USER: LOCAL_USER,
1265
- MINIO_ROOT_PASSWORD: LOCAL_USER
1266
- },
1267
- command: "server --console-address \":9001\" /data",
1268
- volumes: ["minio-data:/data"],
1269
- healthcheck: {
1270
- test: [
1271
- "CMD",
1272
- "mc",
1273
- "ready",
1274
- "local"
1275
- ],
1276
- interval: "10s",
1277
- timeout: "5s",
1278
- retries: 5,
1279
- start_period: "10s"
1280
- }
1281
- };
1282
- case "caddy": return {
1283
- image,
1284
- restart: "unless-stopped",
1285
- ports: published,
1286
- volumes: [
1287
- "./.gkm/Caddyfile:/etc/caddy/Caddyfile:ro",
1288
- "./.gkm/caddy-sites:/etc/caddy/sites:ro",
1289
- "caddy-data:/data"
1290
- ],
1291
- extra_hosts: ["host.docker.internal:host-gateway"],
1292
- healthcheck: {
1293
- test: [
1294
- "CMD",
1295
- "caddy",
1296
- "version"
1297
- ],
1298
- interval: "10s",
1299
- timeout: "5s",
1300
- retries: 5
1301
- }
1302
- };
1303
- case "mailpit": return {
1304
- image,
1305
- restart: "unless-stopped",
1306
- ports: published,
1307
- environment: {
1308
- MP_SMTP_AUTH_ACCEPT_ANY: "1",
1309
- MP_SMTP_AUTH_ALLOW_INSECURE: "1"
1310
- },
1311
- healthcheck: {
1312
- test: [
1313
- "CMD",
1314
- "wget",
1315
- "-q",
1316
- "--spider",
1317
- "http://localhost:8025"
1318
- ],
1319
- interval: "10s",
1320
- timeout: "5s",
1321
- retries: 5
1322
- }
1323
- };
1324
- case "redis": return {
1325
- image,
1326
- restart: "unless-stopped",
1327
- ports: published,
1328
- volumes: ["redis-data:/data"],
1329
- healthcheck: {
1330
- test: [
1331
- "CMD",
1332
- "redis-cli",
1333
- "ping"
1334
- ],
1335
- interval: "5s",
1336
- timeout: "3s",
1337
- retries: 5
1338
- }
1339
- };
1340
- case "redis-http": return {
1341
- image,
1342
- restart: "unless-stopped",
1343
- ports: published,
1344
- environment: {
1345
- SRH_MODE: "env",
1346
- SRH_TOKEN: LOCAL_TOKEN,
1347
- SRH_CONNECTION_STRING: "redis://redis:6379"
1348
- },
1349
- depends_on: ["redis"],
1350
- healthcheck: {
1351
- test: [
1352
- "CMD",
1353
- "wget",
1354
- "-q",
1355
- "-O",
1356
- "/dev/null",
1357
- "http://127.0.0.1:80/"
1358
- ],
1359
- interval: "5s",
1360
- timeout: "3s",
1361
- retries: 10
1362
- }
1363
- };
1364
- case "rabbitmq": return {
1365
- image,
1366
- restart: "unless-stopped",
1367
- ports: published,
1368
- environment: {
1369
- RABBITMQ_DEFAULT_USER: LOCAL_USER,
1370
- RABBITMQ_DEFAULT_PASS: LOCAL_USER
1371
- },
1372
- volumes: ["rabbitmq-data:/var/lib/rabbitmq"],
1373
- healthcheck: {
1374
- test: [
1375
- "CMD",
1376
- "rabbitmq-diagnostics",
1377
- "-q",
1378
- "ping"
1379
- ],
1380
- interval: "10s",
1381
- timeout: "5s",
1382
- retries: 5
1383
- }
1384
- };
1385
- case "localstack": return {
1386
- image,
1387
- restart: "unless-stopped",
1388
- ports: published,
1389
- environment: {
1390
- AWS_DEFAULT_REGION: "us-east-1",
1391
- AWS_ACCESS_KEY_ID: "LSIAQAAAAAAVNCBMPNSG",
1392
- AWS_SECRET_ACCESS_KEY: LOCAL_USER
1393
- },
1394
- volumes: ["localstack-data:/var/lib/localstack"],
1395
- healthcheck: {
1396
- test: [
1397
- "CMD",
1398
- "curl",
1399
- "-f",
1400
- "http://localhost:4566/_localstack/health"
1401
- ],
1402
- interval: "10s",
1403
- timeout: "5s",
1404
- retries: 5,
1405
- start_period: "10s"
1406
- }
1407
- };
1408
- default: throw new UnknownContainer(container);
1409
- }
1410
- }
1411
- /**
1412
- * The published port mappings for a container.
1413
- *
1414
- * Every port is looked up by its own key rather than being derived as an offset
1415
- * from the container's first, so MinIO's console cannot land on whatever was
1416
- * allocated to the next container.
1417
- */
1418
- function publish(container, ports) {
1419
- return portsOf(container).map((port) => {
1420
- const assigned = ports[port.key];
1421
- if (assigned === void 0) throw new UnassignedPort(port.key);
1422
- return `${assigned}:${port.inside}`;
1423
- });
1424
- }
1425
- /** A planned port that allocation never assigned. */
1426
- var UnassignedPort = class extends Error {
1427
- /** The port key that went unassigned, e.g. `minio-console`. */
1428
- key;
1429
- constructor(key) {
1430
- super("No port was assigned for this container port");
1431
- this.name = "UnassignedPort";
1432
- this.key = key;
1433
- }
1434
- };
1435
- //#endregion
1436
- //#region src/reconcile/docker.ts
1437
- /**
1438
- * The real Docker, behind the small interface reconcile needs.
1439
- *
1440
- * Shells out to `docker compose` rather than talking to the daemon socket: it is
1441
- * what a developer runs by hand when something is wrong, so the two cannot
1442
- * disagree, and it keeps Docker out of this package's dependencies.
1443
- *
1444
- * Every call is scoped to the generated compose file. Nothing here can touch a
1445
- * container this project did not generate.
1446
- */
1447
- const run = promisify(execFile);
1448
- /**
1449
- * The generated file, then the project's own if it has one.
1450
- *
1451
- * Merged in that order so the project's wins — an `image:` there pins a
1452
- * container this file derived, and a service there is added beside them.
1453
- */
1454
- function composeFiles(composePath) {
1455
- const project = join(dirname(composePath), "docker-compose.yml");
1456
- return [
1457
- "-f",
1458
- composePath,
1459
- ...existsSync(project) ? ["-f", project] : []
1460
- ];
1461
- }
1462
- /** How long to wait for containers to pass their health checks. */
1463
- const HEALTH_TIMEOUT_MS = 12e4;
1464
- const dockerCli = {
1465
- async publishedPort(composePath, service, inside) {
1466
- try {
1467
- const { stdout } = await run("docker", [
1468
- "compose",
1469
- ...composeFiles(composePath),
1470
- "port",
1471
- service,
1472
- String(inside)
1473
- ]);
1474
- const port = Number(stdout.trim().split(":").pop());
1475
- return Number.isFinite(port) && port > 0 ? port : void 0;
1476
- } catch {
1477
- return;
1478
- }
1479
- },
1480
- async up(composePath, services) {
1481
- await run("docker", [
1482
- "compose",
1483
- ...composeFiles(composePath),
1484
- "up",
1485
- "-d",
1486
- "--remove-orphans",
1487
- "--wait",
1488
- `--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1e3)}`,
1489
- ...services
1490
- ]);
1491
- },
1492
- async copyOut(composePath, service, from, to) {
1493
- await mkdir(dirname(to), { recursive: true });
1494
- await run("docker", [
1495
- "compose",
1496
- ...composeFiles(composePath),
1497
- "cp",
1498
- `${service}:${from}`,
1499
- to
1500
- ]);
1501
- },
1502
- async reload(composePath, service) {
1503
- await run("docker", [
1504
- "compose",
1505
- ...composeFiles(composePath),
1506
- "exec",
1507
- "-T",
1508
- service,
1509
- "caddy",
1510
- "reload",
1511
- "--config",
1512
- "/etc/caddy/Caddyfile"
1513
- ]);
1514
- },
1515
- async healthy(composePath, services) {
1516
- if (services.length === 0) return true;
1517
- try {
1518
- const { stdout } = await run("docker", [
1519
- "compose",
1520
- ...composeFiles(composePath),
1521
- "ps",
1522
- "--format",
1523
- "json",
1524
- ...services
1525
- ]);
1526
- const running = /* @__PURE__ */ new Set();
1527
- for (const line of stdout.trim().split("\n").filter(Boolean)) {
1528
- const entry = JSON.parse(line);
1529
- if (entry.State === "running" && (entry.Health === void 0 || entry.Health === "" || entry.Health === "healthy") && entry.Service) running.add(entry.Service);
1530
- }
1531
- return services.every((service) => running.has(service));
1532
- } catch {
1533
- return false;
1534
- }
1535
- }
1536
- };
1537
- //#endregion
1538
- //#region src/reconcile/ports.ts
1539
- /**
1540
- * Port allocation — why two projects can run at once.
1541
- *
1542
- * Publishing `5432:5432` means the second project on your machine cannot start.
1543
- * Nothing solves that except giving each project its own ports, and what makes
1544
- * it *possible* is the single-`<NAME>_URL` rule: an app reads `ORDERS_URL` and
1545
- * never sees a host or a port, so reconcile is free to bind whatever is
1546
- * available and compose the URL from what it bound. An app reading `DB_HOST` and
1547
- * `DB_PORT` separately could not be moved this way.
1548
- *
1549
- * Assignments are **persisted, not recomputed**. Recomputing means adding a
1550
- * construct renumbers its neighbours, and every running container, saved
1551
- * connection string, and `psql` history goes stale at once.
1552
- *
1553
- * Pure, with the liveness probe injected — a collision with another project's
1554
- * stack is a fact about the machine, and keeping it a parameter is what lets the
1555
- * rules be asserted without binding a socket.
1556
- */
1557
- /**
1558
- * The window ports are drawn from.
1559
- *
1560
- * Above the registered range so nothing here needs privileges, and below the
1561
- * ephemeral range both Linux (32768+) and macOS (49152+) allocate from — a port
1562
- * the kernel might hand to an outgoing connection is one that is free when
1563
- * checked and taken by the time it is bound.
1564
- */
1565
- const WINDOW = {
1566
- min: 2e4,
1567
- max: 32e3
1568
- };
1569
- /**
1570
- * How far apart two projects start.
1571
- *
1572
- * Wide enough that a project can add containers without walking into its
1573
- * neighbour's block, narrow enough that the window holds many projects.
1574
- */
1575
- const BLOCK = 50;
1576
- /**
1577
- * Where a project's ports start.
1578
- *
1579
- * Derived from the name rather than assigned sequentially so that a fresh clone
1580
- * of the same project on the same machine lands on the same block — the first
1581
- * run has nothing persisted to read, and hashing is what keeps that first run
1582
- * from colliding with whatever else is already allocated.
1583
- *
1584
- * @example startingPort('toolbox') // stable for a given name
1585
- */
1586
- function startingPort(project) {
1587
- const digest = createHash("sha256").update(project).digest();
1588
- const blocks = Math.floor((WINDOW.max - WINDOW.min) / BLOCK);
1589
- return WINDOW.min + digest.readUInt32BE(0) % blocks * BLOCK;
1590
- }
1591
- /**
1592
- * Assign a port to every container that has none, keeping the ones that do.
1593
- *
1594
- * Existing assignments are returned untouched even when the container is no
1595
- * longer in the plan: removing a construct must not renumber what is left, and
1596
- * keeping the entry means re-adding it later restores the same port rather than
1597
- * inventing a new one.
1598
- *
1599
- * @param probe - reports what is actually listening. A port assigned to this
1600
- * project is skipped without probing, because on a converged reconcile our own
1601
- * container is the thing listening on it.
1602
- * @throws {NoPortAvailable} when the window is exhausted.
1603
- */
1604
- async function allocate(project, containers, existing = {}, probe = isPortFree) {
1605
- const assignments = { ...existing };
1606
- const taken = new Set(Object.values(assignments));
1607
- for (const container of [...containers].sort()) {
1608
- if (assignments[container] !== void 0) continue;
1609
- const port = await nextFree(startingPort(project), taken, probe);
1610
- assignments[container] = port;
1611
- taken.add(port);
1612
- }
1613
- return assignments;
1614
- }
1615
- /** The window was exhausted. */
1616
- var NoPortAvailable = class extends Error {
1617
- /** Where the search started. */
1618
- from;
1619
- /** The window searched, so the caller can report what was full. */
1620
- window = WINDOW;
1621
- constructor(from) {
1622
- super("No free port is available in the local port range");
1623
- this.name = "NoPortAvailable";
1624
- this.from = from;
1625
- }
1626
- };
1627
- /**
1628
- * The first port at or after `from` that is neither ours nor in use.
1629
- *
1630
- * Wraps at the top of the window rather than stopping, so a project whose block
1631
- * sits near the end is not the one that fails.
1632
- */
1633
- async function nextFree(from, taken, probe) {
1634
- const span = WINDOW.max - WINDOW.min;
1635
- for (let offset = 0; offset < span; offset++) {
1636
- const port = WINDOW.min + (from - WINDOW.min + offset) % span;
1637
- if (taken.has(port)) continue;
1638
- if (await probe(port)) return port;
1639
- }
1640
- throw new NoPortAvailable(from);
1641
- }
1642
- /**
1643
- * Whether nothing is listening on a port.
1644
- *
1645
- * Binds rather than connects: a refused connection says nothing about whether
1646
- * the port can be *published*, which is the question Docker will ask. Binds on
1647
- * `0.0.0.0` for the same reason — a port free on loopback can still be taken on
1648
- * the address Docker publishes to.
1649
- *
1650
- * Inherently racy, and that is acceptable: Docker failing to bind stays the real
1651
- * check. This exists so the common case surfaces as a message at reconcile
1652
- * rather than as a connection failure ten minutes later.
1653
- */
1654
- function isPortFree(port) {
1655
- return new Promise((resolve) => {
1656
- const server = createServer();
1657
- server.once("error", () => resolve(false));
1658
- server.once("listening", () => server.close(() => resolve(true)));
1659
- server.listen(port, "0.0.0.0");
1660
- });
1661
- }
1662
- //#endregion
1663
- //#region src/reconcile/provision.ts
1664
- /**
1665
- * Creating what the URLs name.
1666
- *
1667
- * Convergent and idempotent: every statement asks whether the thing exists
1668
- * first, so reconciling repeatedly is free and a half-applied run recovers by
1669
- * being run again. That property is what lets `gkm dev` do this on every start.
1670
- *
1671
- * The line the design draws is at data, not at side effects — this creates
1672
- * databases, schemas, and buckets, and it never seeds, resets, or drops. A
1673
- * developer who wants their data gone asks for it explicitly.
1674
- *
1675
- * Statement generation is separated from application for the reason the design
1676
- * gives: the same DDL has to run in-process locally and from a provisioner in a
1677
- * VPC, and one implementation is what stops "works locally, fails deployed".
1678
- * When the role DDL lands in `@geekmidas/db` this delegates to it rather than
1679
- * growing its own.
1680
- */
1681
- /**
1682
- * The Postgres work a plan implies.
1683
- *
1684
- * Databases before the schemas inside them, which `provisionOrder` already
1685
- * guarantees by putting parents first.
1686
- */
1687
- function postgresStatements(plan, project = "") {
1688
- const statements = [];
1689
- for (const resource of plan.resources) {
1690
- if (!resource.provisions || resource.container !== "postgres") continue;
1691
- if (resource.kind === "database") {
1692
- statements.push({
1693
- id: resource.id,
1694
- describe: `database ${resource.name}`,
1695
- exists: {
1696
- sql: "SELECT 1 FROM pg_database WHERE datname = $1",
1697
- values: [resource.name]
1698
- },
1699
- create: `CREATE DATABASE ${quoteIdentifier(resource.name)}`
1700
- });
1701
- if (resource.schema) statements.push(...rolesFor(resource, resource.schema, plan, project));
1702
- continue;
1703
- }
1704
- if (resource.kind === "database-schema" && resource.schema) statements.push(...rolesFor(resource, resource.schema, plan, project));
1705
- const cacheHome = resource.kind === "cache" && resource.of ? plan.resources.find((r) => r.id === resource.of) : void 0;
1706
- if (cacheHome) statements.push(...cacheTableDdl(resource, cacheHome, plan));
1707
- }
1708
- return statements;
1709
- }
1710
- /**
1711
- * A cache's table, in the schema the role that reads it resolves names in.
1712
- *
1713
- * Two things have to line up, and neither is the table's contents. The driver
1714
- * names the table unqualified and lets the connection's `search_path` place it
1715
- * — which the role carries — so creating it from the master connection, whose
1716
- * path is `public`, leaves a table the application cannot see and a
1717
- * `relation "cache" does not exist` on the first request. And the default
1718
- * privileges that make a tenant's tables reachable are granted *for the owner
1719
- * role*, so nothing covers a table the master created.
1720
- *
1721
- * Hence: qualified with the tenant's schema, handed to its owner, and granted
1722
- * explicitly — `roleStatements` grants what exists at the time it runs, and
1723
- * this table does not exist yet.
1724
- *
1725
- * A database that opted out of roles needs none of it: everything connects as
1726
- * the master, whose `search_path` finds `public`, and the table it creates
1727
- * there is the table it reads.
1728
- */
1729
- function cacheTableDdl(cache, home, plan) {
1730
- const database = rootDatabase(home, plan);
1731
- const schema = home.roles === false ? void 0 : home.schema;
1732
- const name = cache.table ?? cacheTable(cache.id);
1733
- const table = schema ? `${schema}.${name}` : name;
1734
- const created = cacheTableStatements({ table }).map((statement) => ({
1735
- id: cache.id,
1736
- describe: statement.describe,
1737
- database,
1738
- ...statement.exists ? { exists: statement.exists } : {},
1739
- create: statement.sql
1740
- }));
1741
- if (!schema) return created;
1742
- const runtime = localRole(home);
1743
- const owner = ownerRole(runtime);
1744
- const qualified = table.split(".").map((part) => quoteIdentifier(part)).join(".");
1745
- return [
1746
- ...created,
1747
- {
1748
- id: cache.id,
1749
- describe: `cache table ${table} is owned by ${owner}`,
1750
- database,
1751
- create: `ALTER TABLE ${qualified} OWNER TO ${quoteIdentifier(owner)}`
1752
- },
1753
- {
1754
- id: cache.id,
1755
- describe: `${runtime} may read and write ${table}`,
1756
- database,
1757
- create: `GRANT SELECT, INSERT, UPDATE, DELETE ON ${qualified} TO ${quoteIdentifier(runtime)}`
1758
- }
1759
- ];
1760
- }
1761
- /**
1762
- * The roles and schema for one database or tenant.
1763
- *
1764
- * Skipped entirely when the construct declared `roles: false` — the documented
1765
- * downgrade, where both URLs fall back to the cluster's master credential. It
1766
- * is a choice someone made rather than a default they got.
1767
- */
1768
- function rolesFor(resource, schema, plan, project) {
1769
- if (resource.roles === false) return [];
1770
- const runtime = localRole(resource);
1771
- const owner = ownerRole(runtime);
1772
- const reader = plan.resources.some((r) => r.kind === "database-reader" && r.of === resource.id) ? readerRole(runtime) : void 0;
1773
- return roleStatements({
1774
- runtime,
1775
- owner,
1776
- ...reader ? { reader } : {},
1777
- schema,
1778
- passwords: {
1779
- runtime: localRolePassword(project, plan, runtime),
1780
- owner: localRolePassword(project, plan, owner),
1781
- ...reader ? { reader: localRolePassword(project, plan, reader) } : {}
1782
- }
1783
- }).map((statement) => ({
1784
- id: resource.id,
1785
- describe: statement.describe,
1786
- database: rootDatabase(resource, plan),
1787
- ...statement.exists ? { exists: statement.exists } : {},
1788
- create: statement.sql
1789
- }));
1790
- }
1791
- /** The buckets a plan implies. */
1792
- function bucketNames(plan) {
1793
- return plan.resources.filter((r) => r.provisions && r.kind === "objects").map((r) => r.name);
1794
- }
1795
- /**
1796
- * Quote an identifier for use in DDL.
1797
- *
1798
- * Names reaching here are already canonical and stage-suffixed, so this is
1799
- * defence rather than sanitisation — but DDL cannot be parameterised, and an
1800
- * unquoted identifier is the one place a name could ever be more than a name.
1801
- */
1802
- function quoteIdentifier(name) {
1803
- return `"${name.replace(/"/g, "\"\"")}"`;
1804
- }
1805
- /**
1806
- * Apply the plan's Postgres statements.
1807
- *
1808
- * Each is checked before it is run, so this converges rather than erroring on a
1809
- * second pass.
1810
- */
1811
- async function applyPostgres(client, statements) {
1812
- const applied = [];
1813
- for (const statement of statements) {
1814
- if (!statement.exists) {
1815
- await client.query(statement.database, statement.create);
1816
- applied.push({
1817
- id: statement.id,
1818
- describe: statement.describe,
1819
- created: false
1820
- });
1821
- continue;
1822
- }
1823
- if ((await client.query(statement.database, statement.exists.sql, statement.exists.values)).length > 0) {
1824
- applied.push({
1825
- id: statement.id,
1826
- describe: statement.describe,
1827
- created: false
1828
- });
1829
- continue;
1830
- }
1831
- await client.query(statement.database, statement.create);
1832
- applied.push({
1833
- id: statement.id,
1834
- describe: statement.describe,
1835
- created: true
1836
- });
1837
- }
1838
- return applied;
1839
- }
1840
- /**
1841
- * What each bucket's open paths are, if anything serves it.
1842
- *
1843
- * Keyed by the *origin*, because that is where the policy lives: two servers
1844
- * over one bucket contribute to one policy, so the patterns are unioned rather
1845
- * than the last one winning.
1846
- */
1847
- function bucketPolicies(plan) {
1848
- const byBucket = /* @__PURE__ */ new Map();
1849
- for (const resource of plan.resources) {
1850
- if (resource.kind !== "file-server" || !resource.open?.length) continue;
1851
- const origin = plan.resources.find((r) => r.id === resource.of);
1852
- if (!origin) continue;
1853
- const patterns = byBucket.get(origin.name) ?? /* @__PURE__ */ new Set();
1854
- for (const pattern of resource.open) patterns.add(pattern);
1855
- byBucket.set(origin.name, patterns);
1856
- }
1857
- return [...byBucket].map(([bucket, open]) => ({
1858
- bucket,
1859
- open: [...open].sort()
1860
- })).sort((a, b) => a.bucket.localeCompare(b.bucket));
1861
- }
1862
- /**
1863
- * One bucket's open paths as an S3 bucket policy.
1864
- *
1865
- * Anonymous `s3:GetObject` on the named prefixes and nothing else — which is
1866
- * what "open" means everywhere: the server serves that path without a
1867
- * signature, and the bucket stays private for everything else.
1868
- *
1869
- * One fidelity note, stated rather than discovered: an S3 policy resource's `*`
1870
- * crosses `/`, so a single-star pattern is *wider* here than the construct's own
1871
- * runtime check, which stops at a segment boundary. The construct is the
1872
- * stricter of the two, so a key it refuses to serve unsigned is never one this
1873
- * policy was relied on to refuse — but a key fetched directly, bypassing the
1874
- * client, can be admitted by the policy where the client would have said no.
1875
- * Prefer `**` where crossing segments is what you meant.
1876
- */
1877
- function bucketPolicy(bucket, open) {
1878
- return JSON.stringify({
1879
- Version: "2012-10-17",
1880
- Statement: [{
1881
- Sid: "GkmOpenPaths",
1882
- Effect: "Allow",
1883
- Principal: { AWS: ["*"] },
1884
- Action: ["s3:GetObject"],
1885
- Resource: open.map((pattern) => `arn:aws:s3:::${bucket}/${pattern.replace(/\*\*/g, "*")}`)
1886
- }]
1887
- });
1888
- }
1889
- /**
1890
- * Apply each served bucket's open-path policy, skipping those already correct.
1891
- *
1892
- * Compared as parsed JSON rather than as text: the same policy re-serialised
1893
- * with different key order is the same policy, and rewriting it every reconcile
1894
- * would report a change on every start.
1895
- */
1896
- async function applyPolicies(client, policies) {
1897
- const applied = [];
1898
- for (const { bucket, open } of policies) {
1899
- const wanted = bucketPolicy(bucket, open);
1900
- const describe = `open paths on ${bucket}`;
1901
- if (equivalent(await client.policy(bucket), wanted)) {
1902
- applied.push({
1903
- id: `${bucket}:policy`,
1904
- describe,
1905
- created: false
1906
- });
1907
- continue;
1908
- }
1909
- await client.setPolicy(bucket, wanted);
1910
- applied.push({
1911
- id: `${bucket}:policy`,
1912
- describe,
1913
- created: true
1914
- });
1915
- }
1916
- return applied;
1917
- }
1918
- /** Whether two policy documents say the same thing. */
1919
- function equivalent(current, wanted) {
1920
- if (!current) return false;
1921
- try {
1922
- return JSON.stringify(JSON.parse(current)) === JSON.stringify(JSON.parse(wanted));
1923
- } catch {
1924
- return false;
1925
- }
1926
- }
1927
- /** Create every bucket the plan names, skipping those that exist. */
1928
- async function applyBuckets(client, buckets) {
1929
- const applied = [];
1930
- for (const bucket of buckets) {
1931
- if (await client.exists(bucket)) {
1932
- applied.push({
1933
- id: bucket,
1934
- describe: `bucket ${bucket}`,
1935
- created: false
1936
- });
1937
- continue;
1938
- }
1939
- await client.create(bucket);
1940
- applied.push({
1941
- id: bucket,
1942
- describe: `bucket ${bucket}`,
1943
- created: true
1944
- });
1945
- }
1946
- return applied;
1947
- }
1948
- //#endregion
1949
- //#region src/reconcile/state.ts
1950
- /**
1951
- * What reconcile records, and the hash that lets it do nothing.
1952
- *
1953
- * Reconciling on every `gkm dev` is only acceptable if the converged case is
1954
- * free, so the desired plan is hashed: matching hash plus healthy containers
1955
- * means there is nothing to do. Without that, the automatic reconcile the design
1956
- * asks for would tax every start.
1957
- *
1958
- * Almost nothing needs recording — roles are queried, migrations have their own
1959
- * table, containers are remembered by Docker. Only ports and this hash have no
1960
- * other owner.
1961
- */
1962
- const STATE_DIR = ".gkm/reconcile";
1963
- /**
1964
- * The hash of everything a reconcile would act on.
1965
- *
1966
- * Covers the compose document rather than the plan alone, because the plan is
1967
- * unchanged when only an image pin moves — and a changed image is exactly a
1968
- * container that must be recreated. `stringify` is stable here because
1969
- * `composeFor` sorts its containers, which is what makes the hash meaningful.
1970
- *
1971
- * Deliberately a plain function over serialisable input: the deployed target
1972
- * keys its provisioner invocation on the same idea, and the two must not be able
1973
- * to disagree about what counts as a change.
1974
- */
1975
- function planHash(plan, compose, generated = {}) {
1976
- return createHash("sha256").update(JSON.stringify({
1977
- stage: plan.stage,
1978
- plan,
1979
- compose,
1980
- generated
1981
- })).digest("hex");
1982
- }
1983
- /** Read the recorded state, or nothing if this stage has never reconciled. */
1984
- async function loadState(root, stage) {
1985
- try {
1986
- const raw = await readFile(statePath(root, stage), "utf-8");
1987
- const state = JSON.parse(raw);
1988
- return state.stage === stage ? state : void 0;
1989
- } catch {
1990
- return;
1991
- }
1992
- }
1993
- /** Record what was applied, so the next run can skip it. */
1994
- async function saveState(root, state) {
1995
- const path = statePath(root, state.stage);
1996
- await mkdir(dirname(path), { recursive: true });
1997
- await writeFile(path, `${JSON.stringify(state, null, 2)}\n`);
1998
- }
1999
- function statePath(root, stage) {
2000
- return join(root, STATE_DIR, `${stage}.json`);
2001
- }
2002
- //#endregion
2003
- //#region src/reconcile/index.ts
2004
- /**
2005
- * Reconcile — the one convergent function `gkm dev`, `gkm test`, and `gkm setup`
2006
- * all call.
2007
- *
2008
- * Three phases, and only this one has side effects: declaring is pure (`gkm
2009
- * build` and the dev watcher), running reads `<NAME>_URL` and provisions
2010
- * nothing. Reconcile computes the desired state, compares, and applies the
2011
- * difference — which is what makes "when does it run" answerable with
2012
- * *whenever, repeatedly*.
2013
- *
2014
- * It is safe to run automatically because its blast radius is entirely local:
2015
- * this project's containers, this project's `.gkm/`. Nothing it does can reach a
2016
- * cloud. The line is drawn at data, not at side effects — it allocates ports,
2017
- * writes compose, starts containers, and creates roles; it never seeds, resets,
2018
- * or drops.
2019
- *
2020
- * Docker is injected rather than imported so the rules above can be asserted
2021
- * without a daemon. The default implementation is the real one.
2022
- */
2023
- /**
2024
- * Where the generated compose file is written, relative to the project root.
2025
- *
2026
- * At the root, beside the project's own `docker-compose.yml`, because the two
2027
- * are one stack: this file is everything the constructs imply and is never
2028
- * edited, that one is anything they cannot express — an image pin, an extra
2029
- * service — and is merged over it, so it wins.
2030
- */
2031
- const COMPOSE_PATH = "docker-compose.constructs.yml";
2032
- /**
2033
- * The local edge's config, beside the compose file that mounts it.
2034
- *
2035
- * Relative in the compose volume, so it resolves against `.gkm/` wherever the
2036
- * project lives.
2037
- */
2038
- const CADDYFILE_PATH = ".gkm/Caddyfile";
2039
- /**
2040
- * Where one stage's routes live, imported by the file above.
2041
- *
2042
- * Per stage because one edge serves every stage, the same way one Postgres
2043
- * holds `orders` and `orders_test`. A single file would mean `gkm test`
2044
- * deleting the routes `gkm dev` is serving.
2045
- */
2046
- const caddySitesPath = (stage) => `.gkm/caddy-sites/${stage}.caddy`;
2047
- /**
2048
- * Where the local edge's root certificate is copied to.
2049
- *
2050
- * Exported so a process can be pointed at it without installing anything:
2051
- * `NODE_EXTRA_CA_CERTS` is the whole of the trust story for Node, and it needs
2052
- * no sudo. A browser is the case that still wants the root in the system store,
2053
- * which is a one-time `caddy trust` rather than something a reconcile should do
2054
- * on a developer's behalf.
2055
- */
2056
- const LOCAL_CA_PATH = ".gkm/caddy-root.crt";
2057
- /** Where Caddy keeps the root of the CA it generated. */
2058
- const CADDY_ROOT_IN_CONTAINER = "/data/caddy/pki/authorities/local/root.crt";
2059
- /**
2060
- * Converge the local target on what the manifest declares.
2061
- *
2062
- * Cheap when there is nothing to do: the hash is compared before the compose
2063
- * file is written or a container is touched, and a converged project pays one
2064
- * hash and one health check.
2065
- */
2066
- async function reconcile(options) {
2067
- const { root, project, manifest, stage, start = true, provision = true, docker = dockerCli, probe = isPortFree, sql = pgClient, buckets = bucketClient } = options;
2068
- const plan = planFor(manifest, stage, provisionOrder(manifest), {
2069
- localStage: options.localStage,
2070
- events: options.events,
2071
- cache: options.cache,
2072
- extraContainers: options.extraContainers,
2073
- ...options.edge === void 0 ? {} : { edge: options.edge }
2074
- });
2075
- const composePath = join(root, COMPOSE_PATH);
2076
- const observed = await observedPorts(docker, composePath, plan.containers);
2077
- const ports = await allocate(project, portKeys(plan.containers), {
2078
- ...options.saved,
2079
- ...observed
2080
- }, probe);
2081
- const compose = composeFor(plan, {
2082
- project,
2083
- ports,
2084
- ...options.apps ? { apps: options.apps(plan.containers) } : {}
2085
- });
2086
- const caddyfile = toCaddyfile(sitesFor(plan, project, options.addresses));
2087
- const hash = planHash(plan, compose, { caddyfile });
2088
- const addresses = addressesFor(plan.containers, ports);
2089
- const env = envFor(plan, {
2090
- ports,
2091
- project,
2092
- ...options.mailFrom ? { mailFrom: options.mailFrom } : {},
2093
- ...options.addresses ? { addresses: options.addresses } : {}
2094
- });
2095
- if (plan.containers.includes("caddy")) env.NODE_EXTRA_CA_CERTS = join(root, LOCAL_CA_PATH);
2096
- const result = {
2097
- stage,
2098
- plan,
2099
- compose,
2100
- ports,
2101
- addresses,
2102
- env,
2103
- provisioned: [],
2104
- hash,
2105
- changed: false
2106
- };
2107
- if ((await loadState(root, stage))?.hash === hash && existsSync(composePath) && (!start || await docker.healthy(composePath, plan.containers))) return result;
2108
- await write(composePath, toYaml(compose));
2109
- if (plan.containers.includes("caddy")) {
2110
- await write(join(root, CADDYFILE_PATH), caddyfileRoot());
2111
- await write(join(root, caddySitesPath(stage)), caddyfile);
2112
- }
2113
- if (start && plan.containers.length > 0) await docker.up(composePath, plan.containers);
2114
- if (start && plan.containers.includes("caddy")) await docker.reload(composePath, "caddy").catch(() => {});
2115
- if (start && plan.containers.includes("caddy")) await docker.copyOut(composePath, "caddy", CADDY_ROOT_IN_CONTAINER, join(root, LOCAL_CA_PATH)).catch(() => {});
2116
- const provisioned = start && provision ? await create(plan, ports, sql, buckets, project) : [];
2117
- await saveState(root, {
2118
- hash,
2119
- stage
2120
- });
2121
- return {
2122
- ...result,
2123
- provisioned,
2124
- changed: true
2125
- };
2126
- }
2127
- /**
2128
- * Create the databases, schemas, and buckets the plan names.
2129
- *
2130
- * Idempotent throughout, so this runs on every non-converged reconcile rather
2131
- * than being something to remember.
2132
- */
2133
- async function create(plan, ports, sql, buckets, project) {
2134
- const applied = [];
2135
- const postgresPort = ports[primaryPortKey("postgres")];
2136
- const statements = postgresStatements(plan, project);
2137
- if (postgresPort !== void 0 && statements.length > 0) applied.push(...await applyPostgres(sql(postgresPort), statements));
2138
- const minioPort = ports[primaryPortKey("minio")];
2139
- const names = bucketNames(plan);
2140
- const policies = bucketPolicies(plan);
2141
- if (minioPort !== void 0 && (names.length > 0 || policies.length > 0)) {
2142
- const client = buckets(minioPort);
2143
- if (names.length > 0) applied.push(...await applyBuckets(client, names));
2144
- if (policies.length > 0) applied.push(...await applyPolicies(client, policies));
2145
- }
2146
- return applied;
2147
- }
2148
- /**
2149
- * The host ports of containers already running.
2150
- *
2151
- * Keyed the same way allocation keys them, so the two merge without either
2152
- * knowing about the other.
2153
- */
2154
- async function observedPorts(docker, composePath, containers) {
2155
- const observed = {};
2156
- for (const container of containers) for (const port of portsOf(container)) {
2157
- const running = await docker.publishedPort(composePath, container, port.inside);
2158
- if (running !== void 0) observed[port.key] = running;
2159
- }
2160
- return observed;
2161
- }
2162
- /**
2163
- * Where each container can be reached on this machine.
2164
- *
2165
- * The primary port only — a container's console is for a human to open, not
2166
- * something an app connects to.
2167
- */
2168
- function addressesFor(containers, ports) {
2169
- const addresses = {};
2170
- for (const container of containers) {
2171
- const port = ports[primaryPortKey(container)];
2172
- if (port !== void 0) addresses[container] = `localhost:${port}`;
2173
- }
2174
- return addresses;
2175
- }
2176
- /** Write a file only when its content would change, so mtimes stay meaningful. */
2177
- async function write(path, content) {
2178
- try {
2179
- if (await readFile(path, "utf-8") === content) return;
2180
- } catch {}
2181
- await mkdir(dirname(path), { recursive: true });
2182
- await writeFile(path, content);
2183
- }
2184
- //#endregion
2185
- //#region src/reconcile/workspace.ts
2186
- /**
2187
- * Workspace config → reconcile.
2188
- *
2189
- * Nothing here is read from a `services:` block — there is none. Which
2190
- * containers exist comes from the manifest; which backend a cache or a broker
2191
- * resolves to comes from the deploy target; and an image pin is the project's
2192
- * own `docker-compose.yml`, merged over the generated file.
2193
- *
2194
- * Shared by `gkm setup`, `gkm dev`, and `gkm test` so all three converge on the
2195
- * same state, differing only in the stage they pass.
2196
- */
2197
- var workspace_exports = /* @__PURE__ */ __exportAll({
2198
- backendsOf: () => backendsOf,
2199
- constructGlobs: () => constructGlobs,
2200
- derivedContainers: () => derivedContainers,
2201
- reconcileWorkspace: () => reconcileWorkspace,
2202
- surfaceAddresses: () => surfaceAddresses,
2203
- usesConstructs: () => usesConstructs
2204
- });
2205
- /**
2206
- * Every constructs glob in the workspace, resolved against its app.
2207
- *
2208
- * Absolute because discovery globs from a single cwd while apps live in
2209
- * different directories.
2210
- */
2211
- function constructGlobs(workspace) {
2212
- return allConstructGlobs(workspace);
2213
- }
2214
- /** Whether any app has adopted the constructs glob. */
2215
- function usesConstructs(workspace) {
2216
- return constructGlobs(workspace).length > 0;
2217
- }
2218
- /** The backends a workspace's target implies, as the plan takes them. */
2219
- function backendsOf(workspace) {
2220
- const on = providerOf(workspace);
2221
- return {
2222
- events: eventsBackendFor(on),
2223
- cache: cacheBackendFor(on)
2224
- };
2225
- }
2226
- /**
2227
- * The containers a workspace's declarations imply, without reconciling.
2228
- *
2229
- * The same derivation `reconcileWorkspace` makes, available to callers that
2230
- * need to know *what would run* without starting anything or writing ports —
2231
- * `gkm setup` deciding which credentials to generate, `gkm docker` writing a
2232
- * compose file. Those used to each read a boolean per service out of config,
2233
- * which is how a container could exist because config asked for one rather than
2234
- * because something declared it.
2235
- */
2236
- async function derivedContainers(workspace, stage, manifest) {
2237
- const found = manifest ?? await discover({
2238
- patterns: constructGlobs(workspace),
2239
- cwd: workspace.root
2240
- });
2241
- return planFor(found, stage, provisionOrder(found), {
2242
- localStage: workspace.stages.local,
2243
- ...backendsOf(workspace)
2244
- }).containers;
2245
- }
2246
- /**
2247
- * Reconcile a workspace for one stage.
2248
- *
2249
- * Ports are loaded and saved around the call rather than inside it, so the loop
2250
- * stays a pure-ish function of its inputs and the store keeps its single owner.
2251
- */
2252
- async function reconcileWorkspace(workspace, options) {
2253
- const manifest = options.manifest ?? await discover({
2254
- patterns: constructGlobs(workspace),
2255
- cwd: workspace.root
2256
- });
2257
- const result = await reconcile({
2258
- root: workspace.root,
2259
- project: workspace.name,
2260
- manifest,
2261
- stage: options.stage,
2262
- localStage: workspace.stages.local,
2263
- ...backendsOf(workspace),
2264
- saved: await loadPortState(workspace.root),
2265
- addresses: surfaceAddresses(workspace, manifest),
2266
- apps: (containers) => appServices(workspace, manifest, containers),
2267
- ...options.start === void 0 ? {} : { start: options.start }
2268
- });
2269
- await savePortState(workspace.root, { ...result.ports });
2270
- return result;
2271
- }
2272
- /**
2273
- * Where each declared surface and site answers locally.
2274
- *
2275
- * The addresses come from the ports the workspace already assigns; which
2276
- * construct sits at which one comes from the manifest. That split is the point:
2277
- * this used to answer "who may call whom" by listing every app the workspace
2278
- * runs, which is a different question that happened to give the same answer in
2279
- * a single-repo workspace and no answer at all deployed. Now it answers only
2280
- * "where does this construct answer", and the graph answers the rest.
2281
- *
2282
- * A site is matched to its app by `path`, because that is the one thing a site
2283
- * declaration and a workspace app both name. Surfaces are matched to the
2284
- * backend app: every `rest-api` in a process answers on that process's port, so
2285
- * an app serving both its own API and an auth server publishes one address
2286
- * twice — which is exactly what it does at runtime.
2287
- */
2288
- function surfaceAddresses(workspace, manifest, at = (_app, port) => localAddress(port)) {
2289
- const addresses = {};
2290
- for (const [id, declaration] of Object.entries(manifest)) {
2291
- if (declaration.kind !== "rest-api" && declaration.kind !== "site") continue;
2292
- const host = appKey(id);
2293
- const port = workspace.apps[host]?.port;
2294
- if (port) addresses[id] = at(host, port);
2295
- }
2296
- return addresses;
2297
- }
2298
- /** Where a local process answers, given the port the workspace gave it. */
2299
- function localAddress(port) {
2300
- return `http://localhost:${port}`;
2301
- }
2302
- //#endregion
2303
- //#region src/credentials/index.ts
2304
- const logger = console;
2305
- /**
2306
- * Load environment files
2307
- * @internal Exported for testing
2308
- */
2309
- function loadEnvFiles(envConfig, cwd = process.cwd()) {
2310
- const loaded = [];
2311
- const missing = [];
2312
- const envFiles = envConfig ? Array.isArray(envConfig) ? envConfig : [envConfig] : [".env"];
2313
- for (const envFile of envFiles) {
2314
- const envPath = resolve(cwd, envFile);
2315
- if (existsSync(envPath)) {
2316
- config({
2317
- path: envPath,
2318
- override: true,
2319
- quiet: true
2320
- });
2321
- loaded.push(envFile);
2322
- } else if (envConfig) missing.push(envFile);
2323
- }
2324
- return {
2325
- loaded,
2326
- missing
2327
- };
2328
- }
2329
- /**
2330
- * Check if a port is available
2331
- * @internal Exported for testing
2332
- */
2333
- async function isPortAvailable(port) {
2334
- return new Promise((resolve) => {
2335
- const server = createServer();
2336
- server.once("error", (err) => {
2337
- if (err.code === "EADDRINUSE") resolve(false);
2338
- else resolve(false);
2339
- });
2340
- server.once("listening", () => {
2341
- server.close();
2342
- resolve(true);
2343
- });
2344
- server.listen(port);
2345
- });
2346
- }
2347
- /**
2348
- * Find an available port starting from the preferred port
2349
- * @internal Exported for testing
2350
- */
2351
- async function findAvailablePort(preferredPort, maxAttempts = 10) {
2352
- for (let i = 0; i < maxAttempts; i++) {
2353
- const port = preferredPort + i;
2354
- if (await isPortAvailable(port)) return port;
2355
- logger.log(`⚠️ Port ${port} is in use, trying ${port + 1}...`);
2356
- }
2357
- throw new Error(`Could not find an available port after trying ${maxAttempts} ports starting from ${preferredPort}`);
2358
- }
2359
- const PORT_STATE_PATH = ".gkm/ports.json";
2360
- /**
2361
- * Parse docker-compose.yml and extract all port mappings that use env var interpolation.
2362
- * Entries like `'${POSTGRES_HOST_PORT:-5432}:5432'` are captured.
2363
- * Fixed port mappings like `'5050:80'` are skipped.
2364
- * @internal Exported for testing
2365
- */
2366
- function parseComposePortMappings(composePath) {
2367
- if (!existsSync(composePath)) return [];
2368
- const content = readFileSync(composePath, "utf-8");
2369
- const compose = parse$1(content);
2370
- if (!compose?.services) return [];
2371
- const results = [];
2372
- for (const [serviceName, serviceConfig] of Object.entries(compose.services)) for (const portMapping of serviceConfig?.ports ?? []) {
2373
- const match = String(portMapping).match(/\$\{(\w+):-(\d+)\}:(\d+)/);
2374
- if (match?.[1] && match[2] && match[3]) results.push({
2375
- service: serviceName,
2376
- envVar: match[1],
2377
- defaultPort: Number(match[2]),
2378
- containerPort: Number(match[3])
2379
- });
2380
- }
2381
- return results;
2382
- }
2383
- /**
2384
- * Load saved port state from .gkm/ports.json.
2385
- * @internal Exported for testing
2386
- */
2387
- async function loadPortState(workspaceRoot) {
2388
- try {
2389
- const raw = await readFile(join(workspaceRoot, PORT_STATE_PATH), "utf-8");
2390
- return JSON.parse(raw);
2391
- } catch {
2392
- return {};
2393
- }
2394
- }
2395
- /**
2396
- * Save port state to .gkm/ports.json.
2397
- * @internal Exported for testing
2398
- */
2399
- async function savePortState(workspaceRoot, ports) {
2400
- const dir = join(workspaceRoot, ".gkm");
2401
- await mkdir(dir, { recursive: true });
2402
- await writeFile(join(workspaceRoot, PORT_STATE_PATH), `${JSON.stringify(ports, null, 2)}\n`);
2403
- }
2404
- /**
2405
- * Check if a project's own Docker container is running and return its host port.
2406
- * Uses `docker compose port` scoped to the project's compose file.
2407
- * @internal Exported for testing
2408
- */
2409
- function getContainerHostPort(workspaceRoot, service, containerPort) {
2410
- try {
2411
- const match = execSync(`docker compose port ${service} ${containerPort}`, {
2412
- cwd: workspaceRoot,
2413
- stdio: "pipe"
2414
- }).toString().trim().match(/:(\d+)$/);
2415
- return match ? Number(match[1]) : null;
2416
- } catch {
2417
- return null;
2418
- }
2419
- }
2420
- /**
2421
- * Resolve host ports for Docker services by parsing docker-compose.yml.
2422
- * Priority: running container → saved state → find available port.
2423
- * Persists resolved ports to .gkm/ports.json.
2424
- * @internal Exported for testing
2425
- */
2426
- async function resolveServicePorts(workspaceRoot) {
2427
- const mappings = parseComposePortMappings(join(workspaceRoot, "docker-compose.yml"));
2428
- if (mappings.length === 0) return {
2429
- dockerEnv: {},
2430
- ports: {},
2431
- mappings: []
2432
- };
2433
- const savedState = await loadPortState(workspaceRoot);
2434
- const dockerEnv = {};
2435
- const ports = {};
2436
- const assignedPorts = /* @__PURE__ */ new Set();
2437
- logger.log("\n🔌 Resolving service ports...");
2438
- for (const mapping of mappings) {
2439
- const containerPort = getContainerHostPort(workspaceRoot, mapping.service, mapping.containerPort);
2440
- if (containerPort !== null) {
2441
- ports[mapping.envVar] = containerPort;
2442
- dockerEnv[mapping.envVar] = String(containerPort);
2443
- assignedPorts.add(containerPort);
2444
- logger.log(` 🔄 ${mapping.service}:${mapping.containerPort}: reusing existing container on port ${containerPort}`);
2445
- continue;
2446
- }
2447
- const savedPort = savedState[mapping.envVar];
2448
- if (savedPort && !assignedPorts.has(savedPort) && await isPortAvailable(savedPort)) {
2449
- ports[mapping.envVar] = savedPort;
2450
- dockerEnv[mapping.envVar] = String(savedPort);
2451
- assignedPorts.add(savedPort);
2452
- logger.log(` 💾 ${mapping.service}:${mapping.containerPort}: using saved port ${savedPort}`);
2453
- continue;
2454
- }
2455
- let resolvedPort = await findAvailablePort(mapping.defaultPort);
2456
- while (assignedPorts.has(resolvedPort)) resolvedPort = await findAvailablePort(resolvedPort + 1);
2457
- ports[mapping.envVar] = resolvedPort;
2458
- dockerEnv[mapping.envVar] = String(resolvedPort);
2459
- assignedPorts.add(resolvedPort);
2460
- if (resolvedPort !== mapping.defaultPort) logger.log(` ⚡ ${mapping.service}:${mapping.containerPort}: port ${mapping.defaultPort} occupied, using port ${resolvedPort}`);
2461
- else logger.log(` ✅ ${mapping.service}:${mapping.containerPort}: using default port ${resolvedPort}`);
2462
- }
2463
- await savePortState(workspaceRoot, ports);
2464
- return {
2465
- dockerEnv,
2466
- ports,
2467
- mappings
2468
- };
2469
- }
2470
- /**
2471
- * Replace a port in a URL string.
2472
- * Handles both `hostname:port` and `localhost:port` patterns.
2473
- * @internal Exported for testing
2474
- */
2475
- function replacePortInUrl(url, oldPort, newPort) {
2476
- if (oldPort === newPort) return url;
2477
- let result = url.replace(new RegExp(`:${oldPort}(?=[/?#]|$)`, "g"), `:${newPort}`);
2478
- result = result.replace(new RegExp(`%3A${oldPort}(?=[%/?#&]|$)`, "gi"), `%3A${newPort}`);
2479
- return result;
2480
- }
2481
- /**
2482
- * Rewrite connection URLs and port vars in secrets with resolved ports.
2483
- * Uses the parsed compose mappings to determine which default ports to replace.
2484
- * Pure transform — does not modify secrets on disk.
2485
- * @internal Exported for testing
2486
- */
2487
- function rewriteUrlsWithPorts(secrets, resolvedPorts) {
2488
- const { ports, mappings } = resolvedPorts;
2489
- const result = { ...secrets };
2490
- const portReplacements = [];
2491
- const serviceNames = /* @__PURE__ */ new Set();
2492
- for (const mapping of mappings) {
2493
- serviceNames.add(mapping.service);
2494
- const resolved = ports[mapping.envVar];
2495
- if (resolved !== void 0) portReplacements.push({
2496
- defaultPort: mapping.defaultPort,
2497
- resolvedPort: resolved
2498
- });
2499
- }
2500
- for (const [key, value] of Object.entries(result)) {
2501
- if (!key.endsWith("_HOST")) continue;
2502
- if (serviceNames.has(value)) result[key] = "localhost";
2503
- }
2504
- for (const [key, value] of Object.entries(result)) {
2505
- if (!key.endsWith("_PORT")) continue;
2506
- for (const { defaultPort, resolvedPort } of portReplacements) if (value === String(defaultPort)) result[key] = String(resolvedPort);
2507
- }
2508
- for (const [key, value] of Object.entries(result)) {
2509
- if (!key.endsWith("_URL") && !key.endsWith("_ENDPOINT") && !key.endsWith("_CONNECTION_STRING") && key !== "DATABASE_URL") continue;
2510
- let rewritten = value;
2511
- for (const name of serviceNames) rewritten = rewritten.replace(new RegExp(`@${name}:`, "g"), "@localhost:");
2512
- for (const { defaultPort, resolvedPort } of portReplacements) rewritten = replacePortInUrl(rewritten, defaultPort, resolvedPort);
2513
- result[key] = rewritten;
2514
- }
2515
- return result;
2516
- }
2517
- /**
2518
- * Build the environment variables to pass to `docker compose up`.
2519
- * Merges process.env, secrets, and port mappings so that Docker Compose
2520
- * can interpolate variables like ${POSTGRES_USER} correctly.
2521
- * @internal Exported for testing
2522
- */
2523
- function buildDockerComposeEnv(secretsEnv, portEnv) {
2524
- return {
2525
- ...process.env,
2526
- ...secretsEnv,
2527
- ...portEnv
2528
- };
2529
- }
2530
- /**
2531
- * Parse all service names from a docker-compose.yml file.
2532
- * @internal Exported for testing
2533
- */
2534
- function parseComposeServiceNames(composePath) {
2535
- if (!existsSync(composePath)) return [];
2536
- const content = readFileSync(composePath, "utf-8");
2537
- const compose = parse$1(content);
2538
- return Object.keys(compose?.services ?? {});
2539
- }
2540
- /**
2541
- * Start docker-compose services for a single-app project (no workspace config).
2542
- * Starts all services defined in docker-compose.yml.
2543
- */
2544
- async function startComposeServices(cwd, portEnv, secretsEnv) {
2545
- const composeFile = join(cwd, "docker-compose.yml");
2546
- if (!existsSync(composeFile)) return;
2547
- const servicesToStart = parseComposeServiceNames(composeFile);
2548
- if (servicesToStart.length === 0) return;
2549
- logger.log(`🐳 Starting services: ${servicesToStart.join(", ")}`);
2550
- try {
2551
- execSync(`docker compose up -d ${servicesToStart.join(" ")}`, {
2552
- cwd,
2553
- stdio: "inherit",
2554
- env: buildDockerComposeEnv(secretsEnv, portEnv)
2555
- });
2556
- logger.log("✅ Services started");
2557
- } catch (error) {
2558
- logger.error("❌ Failed to start services:", error.message);
2559
- throw error;
2560
- }
2561
- }
2562
- /**
2563
- * Start docker-compose services for a workspace.
2564
- * Discovers all services from docker-compose.yml and starts everything
2565
- * except app services (which are managed by turbo).
2566
- * @internal Exported for testing
2567
- */
2568
- async function startWorkspaceServices(workspace, portEnv, secretsEnv) {
2569
- const composeFile = join(workspace.root, "docker-compose.yml");
2570
- if (!existsSync(composeFile)) return;
2571
- const allServices = parseComposeServiceNames(composeFile);
2572
- const appNames = new Set(Object.keys(workspace.apps));
2573
- const servicesToStart = allServices.filter((name) => !appNames.has(name));
2574
- if (servicesToStart.length === 0) return;
2575
- logger.log(`🐳 Starting services: ${servicesToStart.join(", ")}`);
2576
- try {
2577
- execSync(`docker compose up -d ${servicesToStart.join(" ")}`, {
2578
- cwd: workspace.root,
2579
- stdio: "inherit",
2580
- env: buildDockerComposeEnv(secretsEnv, portEnv)
2581
- });
2582
- logger.log("✅ Services started");
2583
- } catch (error) {
2584
- logger.error("❌ Failed to start services:", error.message);
2585
- throw error;
2586
- }
2587
- }
2588
- /**
2589
- * Load and flatten secrets for an app from encrypted storage.
2590
- * For workspace app: maps {APP}_DATABASE_URL → DATABASE_URL.
2591
- * @internal Exported for testing
2592
- */
2593
- async function loadSecretsForApp(secretsRoot, stage, appName) {
2594
- let secrets = {};
2595
- if (secretsExist(stage, secretsRoot)) {
2596
- const stageSecrets = await readStageSecrets(stage, secretsRoot);
2597
- if (stageSecrets) {
2598
- logger.log(`🔐 Loading secrets from stage: ${stage}`);
2599
- secrets = toEmbeddableSecrets(stageSecrets);
2600
- }
2601
- }
2602
- if (Object.keys(secrets).length === 0) return {};
2603
- if (!appName) return secrets;
2604
- const prefix = appName.toUpperCase();
2605
- const mapped = { ...secrets };
2606
- const appDbUrl = secrets[`${prefix}_DATABASE_URL`];
2607
- if (appDbUrl) mapped.DATABASE_URL = appDbUrl;
2608
- return mapped;
2609
- }
2610
- /**
2611
- * Walk up the directory tree to find the root containing .gkm/secrets/.
2612
- * @internal Exported for testing
2613
- */
2614
- function findSecretsRoot(startDir) {
2615
- let dir = startDir;
2616
- while (dir !== "/") {
2617
- if (existsSync(join(dir, ".gkm", "secrets"))) return dir;
2618
- const parent = dirname(dir);
2619
- if (parent === dir) break;
2620
- dir = parent;
2621
- }
2622
- return startDir;
2623
- }
2624
- /**
2625
- * Generate the credentials injection code snippet.
2626
- * This is the common logic used by both entry wrapper and exec preload.
2627
- * @internal
2628
- */
2629
- function generateCredentialsInjection(secretsJsonPath) {
2630
- return `import { existsSync, readFileSync } from 'node:fs';
2631
-
2632
- // Inject dev secrets via globalThis and process.env
2633
- // Using globalThis.__gkm_credentials__ avoids CJS/ESM interop issues where
2634
- // Object.assign on the Credentials export only mutates one module copy.
2635
- const secretsPath = '${secretsJsonPath}';
2636
- if (existsSync(secretsPath)) {
2637
- const secrets = JSON.parse(readFileSync(secretsPath, 'utf-8'));
2638
- globalThis.__gkm_credentials__ = secrets;
2639
- Object.assign(process.env, secrets);
2640
- }
2641
- `;
2642
- }
2643
- /**
2644
- * Create a preload script that injects secrets into Credentials.
2645
- * Used by `gkm exec` to inject secrets before running any command.
2646
- * @internal Exported for testing
2647
- */
2648
- async function createCredentialsPreload(preloadPath, secretsJsonPath) {
2649
- const content = `/**
2650
- * Credentials preload generated by 'gkm exec'
2651
- * This file is loaded via NODE_OPTIONS="--import <path>"
2652
- */
2653
- ${generateCredentialsInjection(secretsJsonPath)}`;
2654
- await writeFile(preloadPath, content);
2655
- }
2656
- /**
2657
- * Create a wrapper script that injects secrets before importing the entry file.
2658
- * @internal Exported for testing
2659
- */
2660
- async function createEntryWrapper(wrapperPath, entryPath, secretsJsonPath) {
2661
- const content = `#!/usr/bin/env node
2662
- /**
2663
- * Entry wrapper generated by 'gkm dev --entry'
2664
- */
2665
- ${secretsJsonPath ? `${generateCredentialsInjection(secretsJsonPath)}
2666
- ` : ""}// Import and run the user's entry file (dynamic import ensures secrets load first)
2667
- await import('${entryPath}');
2668
- `;
2669
- await writeFile(wrapperPath, content);
2670
- }
2671
- /**
2672
- * Prepare credentials for dev/exec/test modes.
2673
- * Loads workspace config, secrets, resolves Docker ports, rewrites URLs,
2674
- * injects PORT, dependency URLs, and writes credentials JSON.
2675
- *
2676
- * @param options.resolveDockerPorts - How to resolve Docker ports:
2677
- * - `'full'` (default): probe running containers, saved state, then find available ports. Used by dev/test.
2678
- * - `'readonly'`: check running containers and saved state only, never probe for new ports. Used by exec.
2679
- * @param options.stage - The stage whose secrets to load. Default: the project's `stages.local`.
2680
- * @param options.startDocker - Start Docker Compose services after port resolution. Default: false.
2681
- * @param options.secretsFileName - Custom secrets JSON filename. Default: 'dev-secrets-{appName}.json' or 'dev-secrets.json'.
2682
- * @internal Exported for testing
2683
- */
2684
- async function prepareEntryCredentials(options) {
2685
- const cwd = options.cwd ?? process.cwd();
2686
- const portMode = options.resolveDockerPorts ?? "full";
2687
- let workspaceAppPort;
2688
- let secretsRoot = cwd;
2689
- let appName;
2690
- let appInfo;
2691
- try {
2692
- appInfo = await loadWorkspaceAppInfo(cwd);
2693
- workspaceAppPort = appInfo.app.port;
2694
- secretsRoot = appInfo.workspaceRoot;
2695
- appName = appInfo.appName;
2696
- } catch {
2697
- secretsRoot = findSecretsRoot(cwd);
2698
- appName = getAppNameFromCwd(cwd) ?? void 0;
2699
- }
2700
- const resolvedPort = options.explicitPort ?? workspaceAppPort ?? 3e3;
2701
- const stage = options.stage ?? appInfo?.workspace.stages.local;
2702
- const credentials = stage ? await loadSecretsForApp(secretsRoot, stage, appName) : {};
2703
- credentials.PORT = String(resolvedPort);
2704
- const declaredKeys = [];
2705
- if (appInfo && usesConstructs(appInfo.workspace)) {
2706
- const { reconcileWorkspace } = await Promise.resolve().then(() => workspace_exports);
2707
- const reconciled = await reconcileWorkspace(appInfo.workspace, {
2708
- stage: options.reconcileStage ?? appInfo.workspace.stages.local,
2709
- start: options.startDocker ?? false
2710
- });
2711
- Object.assign(credentials, reconciled.env);
2712
- declaredKeys.push(...Object.keys(reconciled.env));
2713
- if (Object.keys(reconciled.env).length > 0) logger.log(`🔌 Resolved ${Object.keys(reconciled.env).length} declared URL(s)`);
2714
- } else {
2715
- const mappings = parseComposePortMappings(join(secretsRoot, "docker-compose.yml"));
2716
- if (mappings.length > 0) {
2717
- let resolvedPorts;
2718
- if (portMode === "full") resolvedPorts = await resolveServicePorts(secretsRoot);
2719
- else {
2720
- const savedPorts = await loadPortState(secretsRoot);
2721
- const ports = {};
2722
- for (const mapping of mappings) {
2723
- const containerPort = getContainerHostPort(secretsRoot, mapping.service, mapping.containerPort);
2724
- if (containerPort !== null) ports[mapping.envVar] = containerPort;
2725
- else {
2726
- const saved = savedPorts[mapping.envVar];
2727
- if (saved !== void 0) ports[mapping.envVar] = saved;
2728
- }
2729
- }
2730
- resolvedPorts = {
2731
- dockerEnv: {},
2732
- ports,
2733
- mappings
2734
- };
2735
- }
2736
- if (options.startDocker) {
2737
- if (appInfo) await startWorkspaceServices(appInfo.workspace, resolvedPorts.dockerEnv, credentials);
2738
- else await startComposeServices(secretsRoot, resolvedPorts.dockerEnv, credentials);
2739
- }
2740
- if (Object.keys(resolvedPorts.ports).length > 0) {
2741
- const rewritten = rewriteUrlsWithPorts(credentials, resolvedPorts);
2742
- Object.assign(credentials, rewritten);
2743
- logger.log(`🔌 Applied ${Object.keys(resolvedPorts.ports).length} port mapping(s)`);
2744
- }
2745
- }
2746
- }
2747
- if (appInfo?.appName) {
2748
- const depEnv = getDependencyEnvVars(appInfo.workspace, appInfo.appName);
2749
- Object.assign(credentials, depEnv);
2750
- }
2751
- if (!credentials.EVENT_PUBLISHER_CONNECTION_STRING && !credentials.EVENT_SUBSCRIBER_CONNECTION_STRING && credentials.PGBOSS_DB_USER) {
2752
- const pgbossUrl = generatePgBossUrl({
2753
- username: credentials.PGBOSS_DB_USER,
2754
- password: credentials.PGBOSS_DB_PASSWORD ?? "",
2755
- host: credentials.POSTGRES_HOST ?? "localhost",
2756
- port: Number(credentials.POSTGRES_PORT ?? "5432"),
2757
- database: credentials.POSTGRES_DB ?? "app"
2758
- });
2759
- credentials.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;
2760
- credentials.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;
2761
- }
2762
- const secretsDir = join(secretsRoot, ".gkm");
2763
- await mkdir(secretsDir, { recursive: true });
2764
- const secretsFileName = options.secretsFileName ?? (appName ? `dev-secrets-${appName}.json` : "dev-secrets.json");
2765
- const secretsJsonPath = join(secretsDir, secretsFileName);
2766
- await writeFile(secretsJsonPath, JSON.stringify(credentials, null, 2));
2767
- return {
2768
- credentials,
2769
- resolvedPort,
2770
- secretsJsonPath,
2771
- appName,
2772
- secretsRoot,
2773
- appInfo,
2774
- declaredKeys
2775
- };
2776
- }
2777
- //#endregion
2778
- export { storageBackendFor as C, providerOf as S, LOCAL_CA_PATH as _, loadEnvFiles as a, cacheBackendFor as b, resolveServicePorts as c, constructGlobs as d, derivedContainers as f, COMPOSE_PATH as g, workspace_exports as h, isPortAvailable as i, rewriteUrlsWithPorts as l, usesConstructs as m, createEntryWrapper as n, loadSecretsForApp as o, reconcileWorkspace as p, findAvailablePort as r, prepareEntryCredentials as s, createCredentialsPreload as t, startWorkspaceServices as u, applyPostgres as v, eventsBackendFor as x, resourceName as y };
2779
-
2780
- //# sourceMappingURL=credentials-BekkKtY_.mjs.map