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

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 +13468 -12280
  189. package/dist/index.cjs.map +1 -1
  190. package/dist/index.mjs +13491 -12301
  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-BB9fibbQ.cjs +272 -0
  197. package/dist/migrate-BB9fibbQ.cjs.map +1 -0
  198. package/dist/migrate-BIl4kLb1.cjs +181 -0
  199. package/dist/migrate-BIl4kLb1.cjs.map +1 -0
  200. package/dist/migrate-BKAh880g.mjs +267 -0
  201. package/dist/migrate-BKAh880g.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
@@ -0,0 +1,3834 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
3
+ import { c as runOutput, s as run } from "./credentials-DpfnUvIR.mjs";
4
+ import { B as LOGS_PORT, I as otlpTelemetryEnv, L as resolveStageTelemetry, at as certificateFor, ft as SERVER_IPV4_KEY, ht as isReservedStageKey, it as ComposeTlsFileMissing, ot as proxyFor, z as telemetryEnv } from "./workspace-CjSfjfMK.mjs";
5
+ import { A as stackBackups, C as siteAuth, I as stageBackups, O as backupsRoleStatements, T as BACKUPS_SERVICE, a as subscriptionKey, c as HostNotPointingAtServer, f as requiredServerAddress, g as stageDns, h as stackHosts, i as recordedPushSubscriptions, k as backupsService, n as SUBSCRIPTION_TYPE, o as subscriptionResource, p as serverAddressHint, r as confirmPendingSubscriptions, s as topicConnection, t as PushSubscriptionsUnconfirmed, u as isLocalHost, v as systemLookup, w as sitePasswordKey } from "./snsSubscriptions-Bl3CChIH.mjs";
6
+ import { t as defineTarget } from "./define-6poNqm5O.mjs";
7
+ import { $ as ORIGIN_VERIFY_HEADER, $n as telemetryOf, An as postgresSuperuser, At as LEGACY_LOCAL_LOGIN, B as processorDockerfile, Bn as redisService, Ct as backendsOf, Dn as LOCAL_RABBITMQ_USER, Ft as composeFor, Gn as localRolePassword, H as workerDockerfile, Hn as stackRedis, L as appDockerfile, Ln as withGeneratedSecrets, Mt as bucketClient, N as stageProviderNotes, Nt as pgClient, On as loadLocalCredentials, Qt as initStageSecrets, Rn as REDIS_SERVICE, S as recordRelease, Sn as bucketPolicies, Un as withRedisPassword, V as processorNative, Vn as runsRedis, Wn as envFor, Xn as isTelemetryKey, Zn as scopeTelemetryEnv, _n as applyLifecycles, _r as withLogsPassword, _t as appEnvKeys, a as dnsResources, an as PROCESSOR_PORT, ar as DEFAULT_IMAGES, bn as applyPostgres, br as resolveHost, bt as processorEnvKeys, c as currentActor, cr as portKeys, d as DeployJournal, dr as primaryPortKey, dt as devServicesUsed, er as usesTelemetry, fn as publicBuildValues, ft as externalServices, gn as applyBuckets, gr as stackLogs, gt as suppliedOnly, hn as workerUnits, hr as logsService, ht as stageServiceDeclarations, in as imageLayout, ir as hostFor, it as validateImageRef, jt as ensurePostgresLogin, ln as findBuildRoot, mn as processorUnits, mr as logsAccess, n as reportDatabaseRuns, nr as watchedBuckets, nt as originSecretKey, o as forgetDnsResource, on as TURBO_VERSION, pr as LOGS_SERVICE, qn as planFor, r as reportPlannedSeeds, rn as composeBuildPaths, rr as EMULATOR_ACCESS_KEY_ID, rt as processorOriginHost, s as recordDnsChanges, sn as WORKER_PORT, t as DeploySeedsFailed, tr as minioWebhookEnv, v as createComposeState, vn as applyNotifications, vr as NoDomainForStage, wn as postgresStatements, wt as constructGlobs, xn as bucketLifecycles, xt as workerEnvKeys, yn as applyPolicies, yr as isMainFrontendApp, yt as networkEnv, z as ensureDockerignore, zn as STACK_CACHE } from "./seeds-CNPdk_2f.mjs";
8
+ import { t as appKey } from "./derive-Dew0QoGe.mjs";
9
+ import { i as installedFrom, s as DEFAULT_EVENTS } from "./drivers-CDjpjakg.mjs";
10
+ import { a as imageRef } from "./identity-CBXr4wNi.mjs";
11
+ import { i as discover } from "./discover-DOhYSKY_.mjs";
12
+ import { a as SNS_SUBSCRIPTIONS_KEY, o as objectsRoute, s as subscriberRoute } from "./SubscriberGenerator-0ruEmYXj.mjs";
13
+ import { f as plannedSeeds, o as SeedFailed, p as seedDatabases, u as migrateDatabases } from "./databases-Db48ZIXL.mjs";
14
+ import { dirname, join } from "node:path";
15
+ import { existsSync } from "node:fs";
16
+ import { chmod, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
17
+ import { hostname, userInfo } from "node:os";
18
+ import { spawn } from "node:child_process";
19
+ import { createConnection, createServer } from "node:net";
20
+ import { createHash } from "node:crypto";
21
+ import { CLIENT_IP_HEADER, provideKey, provisionOrder } from "@geekmidas/manifest";
22
+ import { stringify } from "yaml";
23
+ import { request } from "node:https";
24
+ //#region src/compose/docker.ts
25
+ /**
26
+ * The Docker operations `gkm compose` needs, behind an interface.
27
+ *
28
+ * Small on purpose, like reconcile's: the rules about *when* each runs — the
29
+ * registry is asked before anything is pulled, nothing is started for a tag
30
+ * that is missing — are asserted against a fake, and this file is only the
31
+ * wiring to the real CLI.
32
+ *
33
+ * Every call is an argument array. Image refs, tags and paths come from the
34
+ * workspace, and none of them reaches a shell.
35
+ */
36
+ /** `output` as `spawn` reads it. */
37
+ const STDIO = {
38
+ inherit: "inherit",
39
+ stderr: [
40
+ "ignore",
41
+ 2,
42
+ 2
43
+ ],
44
+ ignore: "ignore"
45
+ };
46
+ /**
47
+ * The environment a docker command for `engine` runs with: this process's,
48
+ * with `DOCKER_HOST` pointing at the stack's engine when it is a server's.
49
+ */
50
+ function engineEnv(engine, extra = {}) {
51
+ if (!engine.host && Object.keys(extra).length === 0) return void 0;
52
+ return {
53
+ ...process.env,
54
+ ...extra,
55
+ ...engine.host ? { DOCKER_HOST: engine.host } : {}
56
+ };
57
+ }
58
+ /** How a stack's docker commands run: where it is, where output goes. */
59
+ function runOptions(stack, extra) {
60
+ const env = engineEnv(stack, extra);
61
+ return {
62
+ cwd: stack.cwd,
63
+ stdio: STDIO[stack.output ?? "inherit"],
64
+ ...env ? { env } : {},
65
+ ...stack.signal ? { signal: stack.signal } : {}
66
+ };
67
+ }
68
+ /** The network compose puts a project's services on. */
69
+ function projectNetwork(project) {
70
+ return `${project}_default`;
71
+ }
72
+ /**
73
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
74
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
75
+ */
76
+ function publishedPorts(column) {
77
+ const ports = /* @__PURE__ */ new Set();
78
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
79
+ const first = Number(match[1]);
80
+ const last = match[2] ? Number(match[2]) : first;
81
+ for (let port = first; port <= last; port++) ports.add(port);
82
+ }
83
+ return [...ports];
84
+ }
85
+ /**
86
+ * The host port a `docker ps` Ports column publishes for `inside`:
87
+ * `127.0.0.1:54321->5432/tcp` is 54321.
88
+ */
89
+ function publishedPort(column, inside) {
90
+ const match = new RegExp(`(?:[\\d.]+|\\[[^\\]]*\\]):(\\d+)->${inside}/tcp`).exec(column);
91
+ return match ? Number(match[1]) : void 0;
92
+ }
93
+ /** Each line `docker ps` printed, as the containers holding `port`. */
94
+ function portHolders(output, port) {
95
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
96
+ container,
97
+ ...project ? { project } : {},
98
+ ...service ? { service } : {}
99
+ }));
100
+ }
101
+ /** How long a stack has to pass its health checks. */
102
+ const WAIT_TIMEOUT_S = 180;
103
+ /** `docker` itself failed, before it could say anything about a service. */
104
+ var DockerUnreachable = class extends GkmError {
105
+ engine;
106
+ stderr;
107
+ constructor(engine, stderr) {
108
+ super(`Could not ask Docker on ${engine} which ports its services publish (docker said: ${stderr.trim() || "nothing"}). Check that \`DOCKER_HOST=${engine} docker ps\` works from here.`);
109
+ this.engine = engine;
110
+ this.stderr = stderr;
111
+ this.name = "DockerUnreachable";
112
+ }
113
+ };
114
+ /** `docker compose port` printed nothing a port can be read from. */
115
+ var ServicePortUnknown = class extends GkmError {
116
+ service;
117
+ inside;
118
+ output;
119
+ constructor(service, inside, output) {
120
+ super(`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || "nothing"}). Is it running? \`docker compose ps\` shows the stack.`);
121
+ this.service = service;
122
+ this.inside = inside;
123
+ this.output = output;
124
+ this.name = "ServicePortUnknown";
125
+ }
126
+ };
127
+ /**
128
+ * Whether `ref` names a registry on this machine's loopback — which the
129
+ * daemon pulls from and pushes to over plain HTTP by default, and `docker
130
+ * manifest inspect` reaches only when told `--insecure` (without it, a local
131
+ * registry's image is reported as no such manifest).
132
+ */
133
+ function isLoopbackRegistry(ref) {
134
+ const first = ref.split("/")[0];
135
+ if (!ref.includes("/") || !/[.:]|^localhost$/.test(first)) return false;
136
+ const host = first.replace(/:\d+$/, "");
137
+ return host === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(host);
138
+ }
139
+ /** `docker push` finished without saying what digest the registry stored. */
140
+ var PushDigestUnknown = class extends GkmError {
141
+ ref;
142
+ output;
143
+ constructor(ref, output) {
144
+ super(`Pushed ${ref}, but docker did not say which digest the registry stored (it said: ${output.trim().split("\n").slice(-3).join(" / ") || "nothing"}). Check the push with \`docker buildx imagetools inspect ${ref}\`.`);
145
+ this.ref = ref;
146
+ this.output = output;
147
+ this.name = "PushDigestUnknown";
148
+ }
149
+ };
150
+ /** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */
151
+ function pushedDigest(output) {
152
+ return [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)].at(-1)?.[1];
153
+ }
154
+ function compose(stack, args) {
155
+ return [
156
+ "compose",
157
+ "-p",
158
+ stack.project,
159
+ "-f",
160
+ stack.file,
161
+ ...(stack.overrides ?? []).flatMap((file) => ["-f", file]),
162
+ ...args
163
+ ];
164
+ }
165
+ /** Run a program and keep everything it said, whatever it exits with. */
166
+ function capture(command, args, options = {}) {
167
+ const { timeoutMs = 6e4 } = options;
168
+ return new Promise((resolve, reject) => {
169
+ const child = spawn(command, [...args], {
170
+ stdio: [
171
+ options.input === void 0 ? "ignore" : "pipe",
172
+ "pipe",
173
+ "pipe"
174
+ ],
175
+ shell: false,
176
+ ...options.env ? { env: options.env } : {}
177
+ });
178
+ if (options.input !== void 0) child.stdin?.end(options.input);
179
+ let stdout = "";
180
+ let stderr = "";
181
+ child.stdout?.on("data", (chunk) => {
182
+ stdout += chunk.toString();
183
+ });
184
+ child.stderr?.on("data", (chunk) => {
185
+ stderr += chunk.toString();
186
+ });
187
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
188
+ timer.unref?.();
189
+ child.on("error", (error) => {
190
+ clearTimeout(timer);
191
+ reject(error);
192
+ });
193
+ child.on("close", (code) => {
194
+ clearTimeout(timer);
195
+ resolve({
196
+ code,
197
+ stdout,
198
+ stderr
199
+ });
200
+ });
201
+ });
202
+ }
203
+ /**
204
+ * Whether a failed `docker manifest inspect` means the tag is not there, as
205
+ * opposed to the registry not answering.
206
+ *
207
+ * Read off the message because that is all the CLI gives. Anything not
208
+ * recognisably "no such tag" is treated as the registry being unreachable:
209
+ * a registry that refused credentials must not be reported as a tag that was
210
+ * never pushed, or the fix offered would be the wrong one.
211
+ */
212
+ function isMissingManifest(output) {
213
+ return /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(output);
214
+ }
215
+ const dockerCompose = {
216
+ async lookup(ref) {
217
+ const { code, stdout, stderr } = await capture("docker", [
218
+ "manifest",
219
+ "inspect",
220
+ ...isLoopbackRegistry(ref) ? ["--insecure"] : [],
221
+ ref
222
+ ]);
223
+ if (code === 0) return {
224
+ ref,
225
+ status: "found"
226
+ };
227
+ const output = `${stderr}\n${stdout}`.trim();
228
+ return isMissingManifest(output) ? {
229
+ ref,
230
+ status: "missing"
231
+ } : {
232
+ ref,
233
+ status: "unreachable",
234
+ detail: output
235
+ };
236
+ },
237
+ async build(stack, services) {
238
+ await run("docker", compose(stack, ["build", ...services]), runOptions(stack, {
239
+ ...process.env,
240
+ DOCKER_BUILDKIT: "1"
241
+ }));
242
+ },
243
+ async pull(stack, services) {
244
+ await run("docker", compose(stack, ["pull", ...services]), runOptions(stack));
245
+ },
246
+ async up(stack, services) {
247
+ await run("docker", compose(stack, [
248
+ "up",
249
+ "-d",
250
+ "--wait",
251
+ `--wait-timeout=${WAIT_TIMEOUT_S}`,
252
+ ...services ? [] : ["--remove-orphans"],
253
+ ...services ?? []
254
+ ]), runOptions(stack));
255
+ },
256
+ async down(stack) {
257
+ await run("docker", compose(stack, ["down"]), runOptions(stack));
258
+ },
259
+ async port(stack, service, inside) {
260
+ const env = engineEnv(stack);
261
+ const output = await runOutput("docker", compose(stack, [
262
+ "port",
263
+ service,
264
+ String(inside)
265
+ ]), {
266
+ cwd: stack.cwd,
267
+ ...env ? { env } : {},
268
+ ...stack.signal ? { signal: stack.signal } : {}
269
+ });
270
+ const port = Number(output.trim().split(":").pop());
271
+ if (!Number.isInteger(port) || port <= 0) throw new ServicePortUnknown(service, inside, output);
272
+ return port;
273
+ },
274
+ async health(stack, service) {
275
+ const env = engineEnv(stack);
276
+ const { code, stdout } = await capture("docker", compose(stack, [
277
+ "ps",
278
+ "--format",
279
+ "{{.Health}}",
280
+ service
281
+ ]), env ? { env } : {});
282
+ if (code !== 0) return void 0;
283
+ return stdout.trim().split("\n")[0] || void 0;
284
+ },
285
+ async copyOut(stack, service, from, to) {
286
+ await mkdir(dirname(to), { recursive: true });
287
+ await run("docker", compose(stack, [
288
+ "cp",
289
+ `${service}:${from}`,
290
+ to
291
+ ]), runOptions(stack));
292
+ },
293
+ async push(stack, ref) {
294
+ const output = await runOutput("docker", ["push", ref], {
295
+ cwd: stack.cwd,
296
+ ...stack.signal ? { signal: stack.signal } : {}
297
+ });
298
+ const digest = pushedDigest(output);
299
+ if (!digest) throw new PushDigestUnknown(ref, output);
300
+ return digest;
301
+ },
302
+ async digest(engine, ref) {
303
+ const env = engineEnv(engine);
304
+ const { code, stdout } = await capture("docker", [
305
+ "image",
306
+ "inspect",
307
+ "--format={{json .RepoDigests}} {{.Id}}",
308
+ ref
309
+ ], env ? { env } : {});
310
+ if (code !== 0) return void 0;
311
+ const [json = "[]", id] = stdout.trim().split(" ");
312
+ const repository = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
313
+ try {
314
+ const digests = JSON.parse(json);
315
+ const match = Array.isArray(digests) ? digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`)) : void 0;
316
+ if (match) return match.slice(repository.length + 1);
317
+ } catch {}
318
+ return id || void 0;
319
+ },
320
+ async ensureNetwork(engine, name) {
321
+ const env = engineEnv(engine);
322
+ const options = env ? { env } : {};
323
+ const { code } = await capture("docker", [
324
+ "network",
325
+ "inspect",
326
+ name
327
+ ], options);
328
+ if (code === 0) return;
329
+ const created = await capture("docker", [
330
+ "network",
331
+ "create",
332
+ name
333
+ ], options);
334
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
335
+ },
336
+ async publishers(engine, port) {
337
+ const env = engineEnv(engine);
338
+ const { stdout } = await capture("docker", [
339
+ "ps",
340
+ "--format",
341
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
342
+ ], env ? { env } : {});
343
+ return portHolders(stdout, port);
344
+ },
345
+ async exec(stack, service, command, input) {
346
+ const env = engineEnv(stack);
347
+ const options = env ? { env } : {};
348
+ const { stdout: ids } = await capture("docker", [
349
+ "ps",
350
+ "-q",
351
+ "--filter",
352
+ `label=com.docker.compose.project=${stack.project}`,
353
+ "--filter",
354
+ `label=com.docker.compose.service=${service}`
355
+ ], options);
356
+ const container = ids.trim().split("\n")[0];
357
+ if (!container) return {
358
+ code: null,
359
+ stdout: "",
360
+ stderr: `${service} is not running`
361
+ };
362
+ return capture("docker", [
363
+ "exec",
364
+ ...input === void 0 ? [] : ["-i"],
365
+ container,
366
+ ...command
367
+ ], {
368
+ ...options,
369
+ ...input === void 0 ? {} : { input }
370
+ });
371
+ },
372
+ async container(engine, project, service) {
373
+ const env = engineEnv(engine);
374
+ const { stdout } = await capture("docker", [
375
+ "ps",
376
+ "--filter",
377
+ `label=com.docker.compose.project=${project}`,
378
+ "--filter",
379
+ `label=com.docker.compose.service=${service}`,
380
+ "--format",
381
+ "{{.ID}} {{.Image}}"
382
+ ], env ? { env } : {});
383
+ const [id, image] = stdout.trim().split("\n")[0]?.split(" ") ?? [];
384
+ return id && image ? {
385
+ id,
386
+ image
387
+ } : void 0;
388
+ },
389
+ async published(engine, project, service, inside) {
390
+ const env = engineEnv(engine);
391
+ const { code, stdout, stderr } = await capture("docker", [
392
+ "ps",
393
+ "--filter",
394
+ `label=com.docker.compose.project=${project}`,
395
+ "--filter",
396
+ `label=com.docker.compose.service=${service}`,
397
+ "--format",
398
+ "{{.Ports}}"
399
+ ], env ? { env } : {});
400
+ if (code !== 0) throw new DockerUnreachable(engine.host ?? "this machine", stderr);
401
+ return publishedPort(stdout, inside);
402
+ },
403
+ runOnce(engine, options) {
404
+ return dockerExit([
405
+ "run",
406
+ "--rm",
407
+ ...options.stdin ? ["-i"] : [],
408
+ "--network",
409
+ options.network,
410
+ ...Object.keys(options.env ?? {}).flatMap((name) => ["-e", name]),
411
+ "--entrypoint",
412
+ "",
413
+ options.image,
414
+ ...options.command
415
+ ], {
416
+ env: engineEnv(engine, { ...options.env }) ?? process.env,
417
+ ...options.stdin ? { stdin: options.stdin } : {},
418
+ ...options.output ? { output: options.output } : {}
419
+ });
420
+ }
421
+ };
422
+ /** Spawn `docker`, its output where `output` says; resolve with the exit code. */
423
+ function dockerExit(args, options = {}) {
424
+ const output = STDIO[options.output ?? "inherit"];
425
+ const out = Array.isArray(output) ? output : [
426
+ output,
427
+ output,
428
+ output
429
+ ];
430
+ return new Promise((resolve, reject) => {
431
+ const child = spawn("docker", [...args], {
432
+ stdio: [
433
+ options.stdin ? "pipe" : "ignore",
434
+ out[1],
435
+ out[2]
436
+ ],
437
+ env: options.env ?? process.env,
438
+ shell: false
439
+ });
440
+ if (options.stdin && child.stdin) {
441
+ options.stdin.on("error", (error) => child.stdin?.destroy(error));
442
+ child.stdin.on("error", () => {});
443
+ options.stdin.pipe(child.stdin);
444
+ }
445
+ child.on("error", reject);
446
+ child.on("close", (code) => resolve(code ?? 1));
447
+ });
448
+ }
449
+ /** `docker network create` failed. */
450
+ var NetworkCreateFailed = class extends GkmError {
451
+ network;
452
+ output;
453
+ constructor(network, output) {
454
+ super(`Could not create the Docker network '${network}' (docker said: ${output.trim() || "nothing"}). Create it by hand with \`docker network create ${network}\` and run again.`);
455
+ this.network = network;
456
+ this.output = output;
457
+ this.name = "NetworkCreateFailed";
458
+ }
459
+ };
460
+ //#endregion
461
+ //#region src/compose/server.ts
462
+ /**
463
+ * Where a deployed compose stage runs: its server, reached over SSH.
464
+ *
465
+ * gkm never runs on the server. It runs where the deploy is started — a CI
466
+ * runner, a developer's machine — and drives the server's Docker engine over
467
+ * SSH (`DOCKER_HOST=ssh://user@host`), so the server holds Docker, an SSH
468
+ * login and nothing else: no gkm, no checkout, no cloud credentials.
469
+ *
470
+ * ```ts
471
+ * deploy: { compose: { server: { production: { user: 'deploy' } } } }
472
+ * ```
473
+ *
474
+ * The host is the stage's `GKM_SERVER_IPV4` secret — the address its DNS
475
+ * records already point at — unless `host` names another. The local stage is
476
+ * never given one: it runs on this machine's Docker.
477
+ *
478
+ * What the deploy needs from inside the server — Postgres and MinIO, published
479
+ * on the server's loopback alone — it reaches through an SSH tunnel on the same
480
+ * login, so neither is ever published publicly.
481
+ */
482
+ /** A deployed compose stage with nowhere to run. */
483
+ var ComposeServerMissing = class extends GkmError {
484
+ stage;
485
+ missing;
486
+ constructor(stage, missing) {
487
+ super(missing === "config" ? `'${stage}' is a deployed stage, and gkm deploys it to its server's Docker over SSH — it never starts a deployed stage on this machine's Docker. Name the login in gkm.config.ts: deploy: { compose: { server: { ${stage}: { user: 'deploy' } } } } — the host is the stage's ${SERVER_IPV4_KEY} secret (gkm secrets:set ${SERVER_IPV4_KEY} '<ip>' --stage ${stage}), or set host there too.` : `deploy.compose.server.${stage} names no host, and '${stage}' has no ${SERVER_IPV4_KEY} secret to default to. Set it: gkm secrets:set ${SERVER_IPV4_KEY} '<ip>' --stage ${stage} — or set deploy.compose.server.${stage}.host.`);
488
+ this.stage = stage;
489
+ this.missing = missing;
490
+ this.name = "ComposeServerMissing";
491
+ }
492
+ };
493
+ /** SSH to the stage's server failed before anything was changed there. */
494
+ var ComposeServerUnreachable = class extends GkmError {
495
+ target;
496
+ stderr;
497
+ constructor(target, stderr) {
498
+ super(`Could not reach Docker on ${target} over SSH (ssh said: ${stderr.trim() || "nothing"}). Check that \`ssh ${target} docker version\` works from here: the host key in ~/.ssh/known_hosts, the key in your agent or ~/.ssh/config, and the user in the server's docker group.`);
499
+ this.target = target;
500
+ this.stderr = stderr;
501
+ this.name = "ComposeServerUnreachable";
502
+ }
503
+ };
504
+ /** An SSH tunnel to a port on the server's loopback did not open. */
505
+ var ComposeTunnelFailed = class extends GkmError {
506
+ target;
507
+ remotePort;
508
+ stderr;
509
+ constructor(target, remotePort, stderr) {
510
+ super(`Could not open an SSH tunnel to 127.0.0.1:${remotePort} on ${target} (ssh said: ${stderr.trim() || "nothing"}). The server's sshd must allow TCP forwarding for the deploy user (AllowTcpForwarding yes, the default, or local), and its key in ~/.ssh/authorized_keys must too: a key installed with \`restrict\` refuses forwarding unless it also says \`port-forwarding\` (\`restrict,port-forwarding ssh-ed25519 …\`).`);
511
+ this.target = target;
512
+ this.remotePort = remotePort;
513
+ this.stderr = stderr;
514
+ this.name = "ComposeTunnelFailed";
515
+ }
516
+ };
517
+ /**
518
+ * The stage's server: its login from `deploy.compose.server.<stage>`, its
519
+ * host from there or the stage's `GKM_SERVER_IPV4`. Undefined for the local
520
+ * stage, which runs on this machine.
521
+ *
522
+ * @throws {ComposeServerMissing} for a deployed stage with no login or host
523
+ */
524
+ function composeServer(options) {
525
+ const { stage } = options;
526
+ if (options.local) return void 0;
527
+ const config = options.config?.[stage];
528
+ if (!config) throw new ComposeServerMissing(stage, "config");
529
+ const host = config.host ?? options.custom?.["GKM_SERVER_IPV4"]?.trim();
530
+ if (!host) throw new ComposeServerMissing(stage, "host");
531
+ return {
532
+ user: config.user,
533
+ host,
534
+ port: config.port ?? 22
535
+ };
536
+ }
537
+ /** `user@host`, as a person types it after `ssh`. */
538
+ function sshTarget(server) {
539
+ return `${server.user}@${server.host}`;
540
+ }
541
+ /** The server's Docker engine, as `DOCKER_HOST` names it. */
542
+ function dockerHost(server) {
543
+ const host = server.host.includes(":") ? `[${server.host}]` : server.host;
544
+ return `ssh://${server.user}@${host}${server.port === 22 ? "" : `:${server.port}`}`;
545
+ }
546
+ /** The arguments every `ssh` gkm runs starts with: no prompt, ever. */
547
+ function sshArgs(server) {
548
+ return [
549
+ "-o",
550
+ "BatchMode=yes",
551
+ "-o",
552
+ "ConnectTimeout=20",
553
+ "-p",
554
+ String(server.port),
555
+ sshTarget(server)
556
+ ];
557
+ }
558
+ async function freeLocalPort() {
559
+ const server = createServer();
560
+ await new Promise((resolve, reject) => {
561
+ server.once("error", reject);
562
+ server.listen(0, "127.0.0.1", resolve);
563
+ });
564
+ const address = server.address();
565
+ await new Promise((resolve) => server.close(resolve));
566
+ if (!address || typeof address === "string") return 0;
567
+ return address.port;
568
+ }
569
+ function connects(port) {
570
+ return new Promise((resolve) => {
571
+ const socket = createConnection({
572
+ host: "127.0.0.1",
573
+ port
574
+ });
575
+ socket.once("connect", () => {
576
+ socket.destroy();
577
+ resolve(true);
578
+ });
579
+ socket.once("error", () => resolve(false));
580
+ });
581
+ }
582
+ /** The real one: the system's `ssh`, with the user's keys and known hosts. */
583
+ const sshAccess = {
584
+ check(server) {
585
+ return new Promise((resolve, reject) => {
586
+ const child = spawn("ssh", [
587
+ ...sshArgs(server),
588
+ "docker",
589
+ "version",
590
+ "--format",
591
+ "{{.Server.Version}}"
592
+ ], { stdio: [
593
+ "ignore",
594
+ "ignore",
595
+ "pipe"
596
+ ] });
597
+ let stderr = "";
598
+ child.stderr.on("data", (chunk) => {
599
+ stderr += chunk.toString();
600
+ });
601
+ child.on("error", (error) => reject(new ComposeServerUnreachable(sshTarget(server), error.message)));
602
+ child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeServerUnreachable(sshTarget(server), stderr)));
603
+ });
604
+ },
605
+ async tunnel(server, remotePort) {
606
+ const port = await freeLocalPort();
607
+ const child = spawn("ssh", [
608
+ "-N",
609
+ "-o",
610
+ "ExitOnForwardFailure=yes",
611
+ "-o",
612
+ "ControlPath=none",
613
+ "-L",
614
+ `127.0.0.1:${port}:127.0.0.1:${remotePort}`,
615
+ ...sshArgs(server)
616
+ ], { stdio: [
617
+ "ignore",
618
+ "ignore",
619
+ "pipe"
620
+ ] });
621
+ let stderr = "";
622
+ let exited = false;
623
+ child.stderr.on("data", (chunk) => {
624
+ stderr += chunk.toString();
625
+ });
626
+ child.on("exit", () => {
627
+ exited = true;
628
+ });
629
+ child.on("error", (error) => {
630
+ exited = true;
631
+ stderr += error.message;
632
+ });
633
+ const close = async () => {
634
+ if (exited) return;
635
+ const gone = new Promise((resolve) => child.once("exit", resolve));
636
+ child.kill("SIGTERM");
637
+ await gone;
638
+ };
639
+ for (let attempt = 0; attempt < 150; attempt++) {
640
+ if (exited) break;
641
+ if (await connects(port)) return {
642
+ port,
643
+ close
644
+ };
645
+ await new Promise((resolve) => setTimeout(resolve, 200));
646
+ }
647
+ await close();
648
+ throw new ComposeTunnelFailed(sshTarget(server), remotePort, stderr);
649
+ }
650
+ };
651
+ //#endregion
652
+ //#region src/compose/routes.ts
653
+ /** A route with handlers and a check that would have to hold for each of them. */
654
+ var EdgeRouteConflict = class extends Error {
655
+ route;
656
+ constructor(route) {
657
+ super(`The edge route '${route}' sends some paths to other upstreams and also restricts who or what it answers. The two are not combined: give the restricted paths a host of their own.`);
658
+ this.route = route;
659
+ this.name = "EdgeRouteConflict";
660
+ }
661
+ };
662
+ /** @throws {EdgeRouteConflict} */
663
+ function assertRouteRenderable(route) {
664
+ if (route.handlers?.length && (route.allow || route.paths || route.prefixes || route.requireHeader)) throw new EdgeRouteConflict(route.name);
665
+ }
666
+ /** File descriptors a process holding sockets may open. */
667
+ const NOFILE = {
668
+ soft: 1048576,
669
+ hard: 1048576
670
+ };
671
+ /**
672
+ * What the edge runs with: a descriptor per socket, twice — the client's and
673
+ * the upstream's — and every local port for those upstream connections. One
674
+ * edge address to one upstream has only the ephemeral range to open
675
+ * connections from, ~28k by Linux's default; widened, ~64k per replica.
676
+ */
677
+ const EDGE_LIMITS = {
678
+ sysctls: { "net.ipv4.ip_local_port_range": "1024 65535" },
679
+ ulimits: { nofile: NOFILE }
680
+ };
681
+ //#endregion
682
+ //#region src/compose/caddyfile.ts
683
+ /**
684
+ * The stack's own edge, rendered for Caddy: one site block per route.
685
+ *
686
+ * Deployed, each host is the stage's real domain and Caddy gets it a
687
+ * certificate from Let's Encrypt on first request — the same automatic HTTPS
688
+ * it does anywhere, with nothing to configure but the name — or serves the
689
+ * stage's own certificate (`deploy.compose.tls`). Locally the hosts are
690
+ * `*.localhost` and the certificates come from Caddy's own CA, as the `gkm
691
+ * dev` edge does, so a local stack is `https://` like a deployed one.
692
+ *
693
+ * Pure: the routes are data (`routes.ts`), and rendering them is one string.
694
+ */
695
+ /** Where Caddy reads a stage's own certificate, inside its container. */
696
+ const CADDY_TLS_DIR = "/etc/caddy/tls";
697
+ /** An upstream on the stack's own network: its service name. */
698
+ function address({ service, port }) {
699
+ return `${service}:${port}`;
700
+ }
701
+ /** The Caddyfile for a stack's edge. */
702
+ function edgeCaddyfile(routes, options) {
703
+ const { tls } = options;
704
+ const global = tls.kind === "internal" ? `{
705
+ # No ACME and no public DNS: the CA is Caddy's own and the names resolve
706
+ # to this machine.
707
+ local_certs
708
+ auto_https disable_redirects
709
+ }` : options.email ? `{
710
+ email ${options.email}
711
+ }` : "";
712
+ const certificate = tls.kind === "internal" ? `
713
+ tls internal
714
+ ` : tls.kind === "files" ? `
715
+ tls ${tls.certFile} ${tls.keyFile}
716
+ ` : "";
717
+ const blocks = routes.map((route) => siteBlock(route, certificate));
718
+ return `${HEADER}${global ? `${global}\n\n` : ""}${blocks.join("\n\n")}\n`;
719
+ }
720
+ /** One route's site block. */
721
+ function siteBlock(route, certificate) {
722
+ assertRouteRenderable(route);
723
+ const { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;
724
+ const allowed = [...paths ?? [], ...(prefixes ?? []).map((prefix) => `${prefix}*`)];
725
+ const checks = `${allow ? `
726
+ # Only these addresses — the peer Caddy sees, never a header a client
727
+ # could set. Everything else is refused before it reaches the upstream.
728
+ @denied not remote_ip ${allow.join(" ")}
729
+ respond @denied 403
730
+ ` : ""}${requireHeader ? `
731
+ # Only what the CDN sends: it adds this header to every request, and this
732
+ # host would be reached around the CDN otherwise.
733
+ @forged not header ${requireHeader.name} "${requireHeader.value}"
734
+ respond @forged 403
735
+ ` : ""}${auth ? `
736
+ # The stage's login, asked for before anything reaches the upstream.
737
+ basic_auth {
738
+ ${auth.user} ${auth.hash}
739
+ }
740
+ ` : ""}${allowed.length ? `
741
+ # Only these paths answer. Everything else on this host is refused before
742
+ # it reaches the upstream.
743
+ @elsewhere not path ${allowed.join(" ")}
744
+ respond @elsewhere 404
745
+ ` : ""}`;
746
+ const proxy = proxyBlock(route);
747
+ const body = handlers?.length ? `${handlers.map((handler, index) => `
748
+ # Answered by another service: ${handler.name}.
749
+ @handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(" ")}
750
+ handle @handler${index} {
751
+ reverse_proxy ${handler.upstreams.map(address).join(" ")}
752
+ }
753
+ `).join("")}
754
+ handle {${proxy.replace(/\n/g, "\n ")}
755
+ }` : proxy;
756
+ return `https://${host} {${certificate}
757
+ # gkm's own header, which only a service of this stack may send: the auth
758
+ # server rate-limits by the client address it carries.
759
+ request_header -${CLIENT_IP_HEADER}
760
+ ${checks}${body}
761
+ }`;
762
+ }
763
+ /** Where a route's requests go, when no handler took them. */
764
+ function proxyBlock({ upstreams, prefix, streaming }) {
765
+ return prefix ? `
766
+ # A bucket, served at a host of its own: the bucket is a prefix on MinIO,
767
+ # which routes and signs on the Host header — so it is sent the upstream's.
768
+ reverse_proxy ${upstreams.map(address).join(" ")} {
769
+ rewrite ${prefix}{uri}
770
+ header_up Host {upstream_hostport}
771
+ }` : `
772
+ # Host and X-Forwarded-* are passed through as Caddy does by default, so
773
+ # an app builds redirects, cookies and links on the address a caller used.
774
+ reverse_proxy ${upstreams.map(address).join(" ")}${streaming ? ` {
775
+ # Never buffer: a streamed response — server-sent events, a Next.js
776
+ # RSC payload — reaches the client as each chunk is written.
777
+ flush_interval -1
778
+ }` : ""}`;
779
+ }
780
+ const HEADER = `# Generated by gkm compose from the construct manifest — do not edit.
781
+ #
782
+ # One host per API and site, each in front of its own container, one per
783
+ # file server in front of the stack's MinIO — its processors' paths sent to
784
+ # their own service — one per worker SNS pushes to and per processor unit a
785
+ # CDN reaches, answering only those paths, and — when its logs are served
786
+ # publicly — one for OpenObserve, to the addresses it allows. A site the
787
+ # stage puts behind a password asks for its login first.
788
+ `;
789
+ //#endregion
790
+ //#region src/compose/images.ts
791
+ /**
792
+ * Which image each app runs — and, for a tag, whether every one exists.
793
+ *
794
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
795
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
796
+ * image is asked of the registry before anything is pulled or the running
797
+ * stack is touched, and one missing image stops the whole run naming every
798
+ * one that is missing. Nor is a missing image quietly built instead — a build
799
+ * of whatever is checked out here is not the release the tag names.
800
+ */
801
+ /**
802
+ * The tag a site's image carries for a release.
803
+ *
804
+ * A site's public URLs are inlined when it is built, so one bundle serves one
805
+ * stage: `v1.4.0-production` and `v1.4.0-staging` are two images of the same
806
+ * commit. A backend reads its URLs at runtime, so one image serves every stage
807
+ * and its tag is the release's alone.
808
+ */
809
+ function siteTag(tag, stage) {
810
+ return `${tag}-${stage}`;
811
+ }
812
+ /** Images a tag names that the registry does not have. */
813
+ var ImageTagNotFound = class extends GkmError {
814
+ tag;
815
+ refs;
816
+ constructor(tag, refs) {
817
+ super(`The registry has no image for ${refs.length === 1 ? "this app" : `${refs.length} apps`} at '${tag}':\n` + refs.map((ref) => ` - ${ref}`).join("\n") + `\nNothing was pulled or started. Push '${tag}' for every app from CI, pick a tag that exists, or run without --tag to build from this checkout.`);
818
+ this.tag = tag;
819
+ this.refs = refs;
820
+ this.name = "ImageTagNotFound";
821
+ }
822
+ };
823
+ /** The registry did not answer, or did not let this machine in. */
824
+ var RegistryUnreachable = class extends GkmError {
825
+ ref;
826
+ detail;
827
+ constructor(ref, detail) {
828
+ super(`Could not ask the registry about ${ref}: ${detail || "no answer"}\nNothing was pulled or started. Check the registry is reachable and that this machine is logged in to it (\`docker login <registry>\`).`);
829
+ this.ref = ref;
830
+ this.detail = detail;
831
+ this.name = "RegistryUnreachable";
832
+ }
833
+ };
834
+ /**
835
+ * Assert every image exists, before anything else happens.
836
+ *
837
+ * Asked all at once and reported all at once: a release missing two images is
838
+ * one problem with two names, and finding the second only after fixing the
839
+ * first is a slower way to learn the same thing.
840
+ *
841
+ * @throws {RegistryUnreachable} when the registry cannot say
842
+ * @throws {ImageTagNotFound} listing every missing image
843
+ */
844
+ async function assertImagesExist(docker, tag, images) {
845
+ const lookups = await Promise.all(images.map((image) => docker.lookup(image.ref)));
846
+ const unreachable = lookups.find((lookup) => lookup.status === "unreachable");
847
+ if (unreachable?.status === "unreachable") throw new RegistryUnreachable(unreachable.ref, unreachable.detail);
848
+ const missing = lookups.filter((lookup) => lookup.status === "missing").map((lookup) => lookup.ref);
849
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
850
+ }
851
+ /**
852
+ * A push or a pull with no `deploy.registry` to push to or pull from.
853
+ *
854
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
855
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
856
+ * from, somebody else's account. It is never a fallback.
857
+ */
858
+ var RegistryRequired = class extends GkmError {
859
+ operation;
860
+ ref;
861
+ constructor(operation, ref) {
862
+ super(`${operation === "push" ? "Pushing" : "Pulling"} images needs a registry, and gkm.config.ts sets no deploy.registry: '${ref}' would be ${operation === "push" ? "pushed to" : "pulled from"} Docker Hub. Set deploy.registry (e.g. registry: 'ghcr.io/acme') in gkm.config.ts.` + (operation === "pull" ? " To run images built here instead, pass --build." : ""));
863
+ this.operation = operation;
864
+ this.ref = ref;
865
+ this.name = "RegistryRequired";
866
+ }
867
+ };
868
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
869
+ function pinnedRef(ref, digest) {
870
+ return `${ref.split("@")[0]}@${digest}`;
871
+ }
872
+ /** A digests file with no entry for an app the stack runs. */
873
+ var ImageDigestMissing = class extends GkmError {
874
+ file;
875
+ apps;
876
+ constructor(file, apps) {
877
+ super(`${file} pins no digest for ${apps.join(", ")}. Use the file the same release's \`gkm compose --build --push --digests-file\` wrote, or run without --digests-file to pull by tag.`);
878
+ this.file = file;
879
+ this.apps = apps;
880
+ this.name = "ImageDigestMissing";
881
+ }
882
+ };
883
+ /** A digests file entry that is not this app's image. */
884
+ var ImageDigestMismatch = class extends GkmError {
885
+ app;
886
+ expected;
887
+ found;
888
+ constructor(app, expected, found) {
889
+ super(`The digests file pins '${app}' to ${found}, but this release runs ${expected}. It was written for another registry, project, stage or tag; use the file this stage's push of this tag wrote.`);
890
+ this.app = app;
891
+ this.expected = expected;
892
+ this.found = found;
893
+ this.name = "ImageDigestMismatch";
894
+ }
895
+ };
896
+ /** A digests file that is not a JSON object of app to pinned ref. */
897
+ var ImageDigestsInvalid = class extends GkmError {
898
+ file;
899
+ detail;
900
+ constructor(file, detail) {
901
+ super(`${file} is not a digests file (${detail}). It should be the JSON object \`gkm compose --build --push --digests-file\` writes: { "api": "<registry>/<image>:<tag>@sha256:…" }.`);
902
+ this.file = file;
903
+ this.detail = detail;
904
+ this.name = "ImageDigestsInvalid";
905
+ }
906
+ };
907
+ /** Parse a digests file's content, checking its shape. */
908
+ function parseDigests(file, content) {
909
+ let parsed;
910
+ try {
911
+ parsed = JSON.parse(content);
912
+ } catch (error) {
913
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
914
+ }
915
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
916
+ for (const [app, value] of Object.entries(parsed)) if (typeof value !== "string" || !/@sha256:[0-9a-f]{64}$/.test(value)) throw new ImageDigestsInvalid(file, `'${app}' is not an <image>:<tag>@sha256:… ref`);
917
+ return parsed;
918
+ }
919
+ /**
920
+ * Each image pinned to the digest the file names for it.
921
+ *
922
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
923
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
924
+ */
925
+ function pinImages(file, digests, images) {
926
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
927
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
928
+ return images.map((image) => {
929
+ const pinned = digests[image.app];
930
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
931
+ return {
932
+ ...image,
933
+ ref: pinned
934
+ };
935
+ });
936
+ }
937
+ //#endregion
938
+ //#region src/compose/traefik.ts
939
+ /**
940
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
941
+ * with, and what one stack registers with it.
942
+ *
943
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
944
+ * HTTPS. It is configured through its file provider alone: each stack writes
945
+ * one file — its routers, services and middlewares, every name prefixed with
946
+ * its compose project — into a directory the edge watches, and removes it
947
+ * when it stops. There is no Docker socket: the edge never learns what runs
948
+ * on the server except from those files.
949
+ *
950
+ * The edge and the stacks meet on one external Docker network. Only a
951
+ * stack's public services join it, each under an alias prefixed with its
952
+ * project (`<project>-api`), because the network is shared: a bare service
953
+ * name there would be answered by every stack's `api`.
954
+ *
955
+ * Pure: the documents are data, and the edge's side effects are `edge.ts`'s.
956
+ */
957
+ /**
958
+ * The image, pinned: the edge is every stack's way in, so a new version is a
959
+ * change to this line, not whatever `latest` is on the day a server starts.
960
+ */
961
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
962
+ /** The edge's compose project, one per server. */
963
+ const EDGE_PROJECT = "gkm-edge";
964
+ /** The external network the edge and every stack's public services share. */
965
+ const EDGE_NETWORK = "gkm-edge";
966
+ /** The edge's compose service. */
967
+ const EDGE_SERVICE = "traefik";
968
+ /** Inside the edge's container: what it watches, and where certificates are. */
969
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
970
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
971
+ /** The certificate resolver every deployed route without its own certificate uses. */
972
+ const ACME_RESOLVER = "letsencrypt";
973
+ /** The internal entrypoint the edge's health check asks; never published. */
974
+ const PING_PORT = 8082;
975
+ /** A stack's service, as the edge — and the stack itself — reach it. */
976
+ function edgeAlias(project, service) {
977
+ return `${project}-${service}`;
978
+ }
979
+ /** A stack's certificate, as the edge's container reads it. */
980
+ function edgeCertificatePaths(project) {
981
+ return {
982
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
983
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
984
+ };
985
+ }
986
+ /**
987
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
988
+ * the directory it watches. No API and no dashboard — nothing about the edge
989
+ * is reachable but the routes stacks register.
990
+ */
991
+ function traefikStatic(ports) {
992
+ return {
993
+ global: {
994
+ checkNewVersion: false,
995
+ sendAnonymousUsage: false
996
+ },
997
+ entryPoints: {
998
+ web: {
999
+ address: ":80",
1000
+ http: { redirections: { entryPoint: {
1001
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
1002
+ scheme: "https",
1003
+ permanent: true
1004
+ } } }
1005
+ },
1006
+ websecure: { address: ":443" },
1007
+ ping: { address: `:${PING_PORT}` }
1008
+ },
1009
+ ping: { entryPoint: "ping" },
1010
+ providers: { file: {
1011
+ directory: EDGE_DYNAMIC_DIR,
1012
+ watch: true
1013
+ } },
1014
+ certificatesResolvers: { [ACME_RESOLVER]: { acme: {
1015
+ storage: "/acme/acme.json",
1016
+ httpChallenge: { entryPoint: "web" }
1017
+ } } },
1018
+ log: { level: "INFO" }
1019
+ };
1020
+ }
1021
+ /** The edge's compose document. */
1022
+ function edgeCompose(options) {
1023
+ const { ports } = options;
1024
+ return {
1025
+ name: EDGE_PROJECT,
1026
+ services: { [EDGE_SERVICE]: {
1027
+ image: TRAEFIK_IMAGE,
1028
+ restart: "unless-stopped",
1029
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
1030
+ configs: [{
1031
+ source: "traefik",
1032
+ target: "/etc/traefik/traefik.yml"
1033
+ }],
1034
+ volumes: [
1035
+ `dynamic:${EDGE_DYNAMIC_DIR}`,
1036
+ `certs:${EDGE_CERTS_DIR}`,
1037
+ "acme:/acme"
1038
+ ],
1039
+ labels: { "dev.geekmidas.edge.config": createHash("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
1040
+ networks: ["edge"],
1041
+ ...EDGE_LIMITS,
1042
+ healthcheck: {
1043
+ test: [
1044
+ "CMD",
1045
+ "traefik",
1046
+ "healthcheck",
1047
+ "--ping"
1048
+ ],
1049
+ interval: "10s",
1050
+ timeout: "5s",
1051
+ retries: 5
1052
+ },
1053
+ logging: options.logging
1054
+ } },
1055
+ configs: { traefik: { content: options.staticConfig } },
1056
+ volumes: {
1057
+ acme: {},
1058
+ dynamic: {},
1059
+ certs: {}
1060
+ },
1061
+ networks: { edge: {
1062
+ name: EDGE_NETWORK,
1063
+ external: true
1064
+ } }
1065
+ };
1066
+ }
1067
+ /** A stack's dynamic configuration, as an object. */
1068
+ function traefikDynamic(routes, options) {
1069
+ const { project, tls } = options;
1070
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
1071
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
1072
+ const routers = {};
1073
+ const services = {};
1074
+ const middlewares = {};
1075
+ const strip = `${project}-strip-gkm-headers`;
1076
+ if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [CLIENT_IP_HEADER]: "" } } };
1077
+ for (const route of routes) {
1078
+ const chain = [strip];
1079
+ if (route.allow) {
1080
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
1081
+ chain.push(name(route, "allow"));
1082
+ }
1083
+ if (route.auth) {
1084
+ middlewares[name(route, "auth")] = { basicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] } };
1085
+ chain.push(name(route, "auth"));
1086
+ }
1087
+ if (route.prefix) {
1088
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
1089
+ chain.push(name(route, "prefix"));
1090
+ }
1091
+ assertRouteRenderable(route);
1092
+ const allowed = [...(route.paths ?? []).map((path) => `Path(\`${path}\`)`), ...(route.prefixes ?? []).map((prefix) => `PathPrefix(\`${prefix}\`)`)];
1093
+ const paths = allowed.length ? ` && (${allowed.join(" || ")})` : "";
1094
+ const header = route.requireHeader ? ` && Header(\`${route.requireHeader.name}\`, \`${route.requireHeader.value}\`)` : "";
1095
+ for (const handler of route.handlers ?? []) {
1096
+ const handlerName = name(route, handler.name);
1097
+ routers[handlerName] = {
1098
+ rule: `Host(\`${route.host}\`) && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
1099
+ priority: 1e4,
1100
+ entryPoints: ["websecure"],
1101
+ service: handlerName,
1102
+ middlewares: [strip],
1103
+ tls: tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {}
1104
+ };
1105
+ services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
1106
+ }
1107
+ routers[name(route)] = {
1108
+ rule: `Host(\`${route.host}\`)${paths}${header}`,
1109
+ entryPoints: ["websecure"],
1110
+ service: name(route),
1111
+ middlewares: chain,
1112
+ tls: tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {}
1113
+ };
1114
+ services[name(route)] = { loadBalancer: {
1115
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
1116
+ ...route.prefix ? { passHostHeader: false } : {},
1117
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
1118
+ ...route.health ? { healthCheck: {
1119
+ path: route.health,
1120
+ interval: "5s",
1121
+ timeout: "3s"
1122
+ } } : {}
1123
+ } };
1124
+ }
1125
+ return {
1126
+ http: {
1127
+ routers,
1128
+ services,
1129
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
1130
+ },
1131
+ ...tls.kind === "files" ? { tls: { certificates: [{
1132
+ certFile: tls.certFile,
1133
+ keyFile: tls.keyFile
1134
+ }] } } : {}
1135
+ };
1136
+ }
1137
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
1138
+ function traefikDynamicFile(routes, options) {
1139
+ return `# Generated by gkm compose for ${options.project} — do not edit.
1140
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
1141
+ # one is removed by gkm compose --down.
1142
+ ${yaml(traefikDynamic(routes, options))}`;
1143
+ }
1144
+ /** The edge's static configuration file. */
1145
+ function traefikStaticFile(ports) {
1146
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1147
+ ${yaml(traefikStatic(ports))}`;
1148
+ }
1149
+ /** The edge's compose file. */
1150
+ function edgeComposeFile(options) {
1151
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1152
+ #
1153
+ # Started by the first stack that runs with proxy: 'traefik', and left
1154
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
1155
+ #
1156
+ # docker compose -p ${EDGE_PROJECT} down
1157
+ ${yaml(edgeCompose(options))}`;
1158
+ }
1159
+ function yaml(value) {
1160
+ return stringify(value, {
1161
+ lineWidth: 0,
1162
+ aliasDuplicateObjects: false
1163
+ });
1164
+ }
1165
+ //#endregion
1166
+ //#region src/compose/stack.ts
1167
+ /**
1168
+ * The stack a workspace runs as for one stage — pure.
1169
+ *
1170
+ * Everything `gkm compose` writes is decided here, as data: the compose file,
1171
+ * the Caddyfile, one env file per backend, and the image each app runs. The
1172
+ * command around it reads the workspace, asks the registry, writes the files
1173
+ * and starts Docker; none of those decide anything, so all of it can be
1174
+ * asserted without a daemon.
1175
+ *
1176
+ * The values come from the same derivations every other target uses. The
1177
+ * plan is reconcile's `planFor`, the keys an app reads are `appEnvKeys`, and
1178
+ * every URL is `envFor`'s — asked twice, once with each app at its public
1179
+ * address and once on the compose network, because a browser and a sibling
1180
+ * service reach the same API by different names.
1181
+ */
1182
+ /** Where a stack's files are written, relative to the workspace root. */
1183
+ function stackDir(stage) {
1184
+ return `.gkm/compose/${stage}`;
1185
+ }
1186
+ /**
1187
+ * The compose project a stage's stack runs as.
1188
+ *
1189
+ * The deploy identity's scope, so two workspaces with one name in different
1190
+ * namespaces never share containers or volumes — and the stage, so a
1191
+ * machine can run two stages side by side.
1192
+ */
1193
+ function composeProject(identity) {
1194
+ return `${identity.scope}-${identity.stage}`;
1195
+ }
1196
+ /** The ports the edge is published on, and the variables that move them. */
1197
+ const EDGE_PORT_ENV = {
1198
+ https: "GKM_COMPOSE_HTTPS_PORT",
1199
+ http: "GKM_COMPOSE_HTTP_PORT"
1200
+ };
1201
+ /**
1202
+ * The variable that moves the local stage's OpenObserve off its loopback
1203
+ * port, 5080 — which the local stage takes from nowhere else, since it
1204
+ * ignores `deploy.telemetry`. Another stack, or another tool, may hold 5080.
1205
+ */
1206
+ const LOGS_PORT_ENV = "GKM_COMPOSE_LOGS_PORT";
1207
+ /**
1208
+ * Containers this target does not run.
1209
+ *
1210
+ * The AWS emulator never applies: a stack is a server target, whose events
1211
+ * are pg-boss. Reconcile's Caddy fronts `gkm dev`'s host processes; the stack
1212
+ * brings its own edge.
1213
+ *
1214
+ * MinIO and Mailpit run on the local stage always, and on a deployed stage
1215
+ * only where `--allow-dev-services` allowed them and its secrets configure no
1216
+ * real bucket or mail server — see `devServices.ts`.
1217
+ */
1218
+ const NOT_RUN = {
1219
+ localstack: true,
1220
+ caddy: true
1221
+ };
1222
+ /** The kinds a deployed stage takes from its secrets, or a dev service. */
1223
+ const SERVICE_KINDS = {
1224
+ email: "email",
1225
+ objects: "objects",
1226
+ "file-server": "file-server"
1227
+ };
1228
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
1229
+ const MINIO_REGION = "us-east-1";
1230
+ /** The S3 client's credentials, read beside a bucket's URL when it has them. */
1231
+ const STORAGE_KEYS = [
1232
+ "AWS_ACCESS_KEY_ID",
1233
+ "AWS_SECRET_ACCESS_KEY",
1234
+ "AWS_REGION"
1235
+ ];
1236
+ /**
1237
+ * Every service's Docker logs, rotated. The json-file driver keeps a
1238
+ * container's output in one file that grows until the disk is full — on a
1239
+ * small server, in weeks. Three files of 10 MB each per container is enough
1240
+ * to see what happened and never fills anything. A project's own override
1241
+ * file that sets `logging` wins over it.
1242
+ */
1243
+ const LOG_ROTATION = {
1244
+ driver: "json-file",
1245
+ options: {
1246
+ "max-size": "10m",
1247
+ "max-file": "3"
1248
+ }
1249
+ };
1250
+ /** A CDN serves the bucket, and the secret it sends the processors is not in the stage. */
1251
+ var ProcessorOriginSecretMissing = class extends GkmError {
1252
+ fileServer;
1253
+ key;
1254
+ stage;
1255
+ constructor(fileServer, key, stage) {
1256
+ super(`'${fileServer}' has processors, and its bucket is not the stack's MinIO, so they are reached through the CDN in front of it — which sends ${key}, and stage '${stage}' has none. It is written by the deploy that creates the CDN (\`deploy.objects.${stage}\` on s3, cdn on): run gkm deploy --stage ${stage}.`);
1257
+ this.fileServer = fileServer;
1258
+ this.key = key;
1259
+ this.stage = stage;
1260
+ this.name = "ProcessorOriginSecretMissing";
1261
+ }
1262
+ };
1263
+ /**
1264
+ * The stack with Caddy's files inline: its Caddyfile and, where the stage has
1265
+ * one, its own certificate — `configs` with their `content`, which compose
1266
+ * copies into the container through the engine's API. Nothing is mounted from
1267
+ * a path, so the stack runs the same on a server's engine, over SSH, as on
1268
+ * this machine's. Their hash is a label: a changed file is a changed service,
1269
+ * which `up` recreates (compose does not, for a config's content alone).
1270
+ */
1271
+ function withCaddyConfigs(compose, files) {
1272
+ const caddy = compose.services.caddy;
1273
+ if (!caddy) return compose;
1274
+ const configs = {
1275
+ caddyfile: { content: files.caddyfile },
1276
+ ...files.tls ? {
1277
+ "tls-cert": { content: files.tls.cert },
1278
+ "tls-key": { content: files.tls.key }
1279
+ } : {}
1280
+ };
1281
+ const hash = createHash("sha256");
1282
+ for (const [name, { content }] of Object.entries(configs)) hash.update(`${name}\0${content}\0`);
1283
+ return {
1284
+ ...compose,
1285
+ services: {
1286
+ ...compose.services,
1287
+ caddy: {
1288
+ ...caddy,
1289
+ configs: [{
1290
+ source: "caddyfile",
1291
+ target: "/etc/caddy/Caddyfile"
1292
+ }, ...files.tls ? [{
1293
+ source: "tls-cert",
1294
+ target: `${CADDY_TLS_DIR}/cert.pem`
1295
+ }, {
1296
+ source: "tls-key",
1297
+ target: `${CADDY_TLS_DIR}/key.pem`,
1298
+ mode: 256
1299
+ }] : []],
1300
+ labels: {
1301
+ ...caddy.labels,
1302
+ "dev.geekmidas.caddy.config": hash.digest("hex").slice(0, 16)
1303
+ }
1304
+ }
1305
+ },
1306
+ configs: {
1307
+ ...compose.configs,
1308
+ ...configs
1309
+ }
1310
+ };
1311
+ }
1312
+ /** The local stage's stack, without the logins `gkm dev` generates. */
1313
+ var LocalCredentialsMissing = class extends GkmError {
1314
+ stage;
1315
+ constructor(stage) {
1316
+ super(`The local stage '${stage}' runs with this machine's generated logins, and none were passed. Load them with loadLocalCredentials(workspace) and pass them as localCredentials.`);
1317
+ this.stage = stage;
1318
+ this.name = "LocalCredentialsMissing";
1319
+ }
1320
+ };
1321
+ /**
1322
+ * A deployed stage's container logins, derived from its seed like its role
1323
+ * passwords — so every deploy of the stage computes the same ones, and no one
1324
+ * reading the repo can.
1325
+ */
1326
+ function derivedCredentials(project, plan, seed) {
1327
+ const derive = (purpose) => localRolePassword(project, plan, purpose, seed);
1328
+ return {
1329
+ postgres: {
1330
+ user: postgresSuperuser(project),
1331
+ password: derive("master")
1332
+ },
1333
+ minio: {
1334
+ user: `${project}-minio`,
1335
+ password: derive("minio")
1336
+ },
1337
+ rabbitmq: {
1338
+ user: LOCAL_RABBITMQ_USER,
1339
+ password: derive("rabbitmq")
1340
+ },
1341
+ redis: { password: derive("redis") },
1342
+ cacheToken: derive("cache-token"),
1343
+ emulator: {
1344
+ accessKeyId: EMULATOR_ACCESS_KEY_ID,
1345
+ secretAccessKey: derive("emulator")
1346
+ },
1347
+ logs: {
1348
+ email: `admin@${project}`,
1349
+ password: derive("logs")
1350
+ }
1351
+ };
1352
+ }
1353
+ /** A value only the stage's secrets can hold, and they do not. */
1354
+ var StageSecretMissing = class extends GkmError {
1355
+ app;
1356
+ key;
1357
+ stage;
1358
+ constructor(app, key, stage) {
1359
+ super(`'${app}' reads ${key}, and the stage '${stage}' has none. Nothing in the stack can derive it; set it in the stage's secrets: gkm secrets:set ${key} '…' --stage ${stage}`);
1360
+ this.app = app;
1361
+ this.key = key;
1362
+ this.stage = stage;
1363
+ this.name = "StageSecretMissing";
1364
+ }
1365
+ };
1366
+ /** A deployed stage's secrets with no seed to derive its passwords from. */
1367
+ var StageSeedMissing = class extends GkmError {
1368
+ stage;
1369
+ constructor(stage) {
1370
+ super(`The stage '${stage}' has no seed in its secrets, and a deployed stage's database passwords are derived from it. Run gkm compose --stage ${stage} without --dry-run once, or gkm deploy, to generate it.`);
1371
+ this.stage = stage;
1372
+ this.name = "StageSeedMissing";
1373
+ }
1374
+ };
1375
+ /** A workspace with no API and no site to run. */
1376
+ var NothingToCompose = class extends GkmError {
1377
+ root;
1378
+ constructor(root) {
1379
+ super(`${root} declares no RestApi, no site and no Worker with work to do, so a stack would run nothing. Mobile apps ship through their own toolchain.`);
1380
+ this.root = root;
1381
+ this.name = "NothingToCompose";
1382
+ }
1383
+ };
1384
+ /** A value that cannot be written to an env file a line at a time. */
1385
+ var EnvValueMultiline = class extends GkmError {
1386
+ app;
1387
+ key;
1388
+ constructor(app, key) {
1389
+ super(`${key} for '${app}' spans more than one line, and an env file holds one value per line. Store it on one line — base64, or JSON — and decode it where it is read.`);
1390
+ this.app = app;
1391
+ this.key = key;
1392
+ this.name = "EnvValueMultiline";
1393
+ }
1394
+ };
1395
+ /** The services a stack's apps wait on and the edge waits on in turn. */
1396
+ const HEALTHY = { condition: "service_healthy" };
1397
+ /**
1398
+ * An app's health check: its own server, asked on 127.0.0.1 — not
1399
+ * `localhost`, which resolves to `::1` first in an Alpine container while a
1400
+ * server may listen on IPv4 alone.
1401
+ */
1402
+ function probe(port, path) {
1403
+ return {
1404
+ test: [
1405
+ "CMD",
1406
+ "wget",
1407
+ "-q",
1408
+ "-O",
1409
+ "/dev/null",
1410
+ `http://127.0.0.1:${port}${path}`
1411
+ ],
1412
+ interval: "5s",
1413
+ timeout: "3s",
1414
+ retries: 20,
1415
+ start_period: "10s"
1416
+ };
1417
+ }
1418
+ /**
1419
+ * What a stage's stack provisions: reconcile's plan, with a server target's
1420
+ * backends whatever `deploy.default` says — the stack is one machine running
1421
+ * containers, so events are pg-boss beside the declared database, and every
1422
+ * cache, one declared from that database included, is in the stack's own
1423
+ * Redis.
1424
+ */
1425
+ function stackPlan(workspace, manifest, stage) {
1426
+ return planFor(manifest, stage, provisionOrder(manifest), {
1427
+ localStage: workspace.stages.local,
1428
+ events: DEFAULT_EVENTS.server,
1429
+ cache: STACK_CACHE,
1430
+ edge: false
1431
+ });
1432
+ }
1433
+ /** The stack for one stage. */
1434
+ function composeStack(input) {
1435
+ const { workspace, manifest, stage, identity } = input;
1436
+ const local = stage === workspace.stages.local;
1437
+ const project = composeProject(identity);
1438
+ const custom = input.secrets?.custom ?? {};
1439
+ const https = input.ports?.https ?? 443;
1440
+ const http = input.ports?.http ?? 80;
1441
+ const proxy = proxyFor(workspace.deploy?.compose, stage, local);
1442
+ const certificate = local ? void 0 : certificateFor(workspace.deploy?.compose, stage, workspace.root);
1443
+ const plan = stackPlan(workspace, manifest, stage);
1444
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1445
+ if (local && !input.localCredentials) throw new LocalCredentialsMissing(stage);
1446
+ const seed = local ? input.localCredentials.seed : input.secrets?.seed;
1447
+ if (!seed) throw new StageSeedMissing(stage);
1448
+ const containers = local ? input.localCredentials : derivedCredentials(workspace.name, plan, seed);
1449
+ const credential = {
1450
+ containers: {
1451
+ ...containers,
1452
+ minio: {
1453
+ user: custom.AWS_ACCESS_KEY_ID ?? containers.minio.user,
1454
+ password: custom.AWS_SECRET_ACCESS_KEY ?? containers.minio.password
1455
+ }
1456
+ },
1457
+ seed
1458
+ };
1459
+ const apps = stackApps(workspace, manifest, plan, {
1460
+ local,
1461
+ stage,
1462
+ https,
1463
+ identity,
1464
+ images: input.images
1465
+ });
1466
+ const workers = stackWorkers(workerUnits(workspace, manifest, input.background ?? {}), {
1467
+ stage,
1468
+ identity,
1469
+ images: input.images
1470
+ });
1471
+ const processors = stackProcessors(processorUnits(workspace, manifest), {
1472
+ manifest,
1473
+ stage,
1474
+ identity,
1475
+ images: input.images
1476
+ });
1477
+ if (apps.length === 0 && workers.length === 0 && processors.length === 0) throw new NothingToCompose(workspace.root);
1478
+ const owners = /* @__PURE__ */ new Map();
1479
+ for (const resource of plan.resources) {
1480
+ owners.set(resource.envKey, resource);
1481
+ if (resource.kind === "email") {
1482
+ owners.set(provideKey(resource.id, "from"), resource);
1483
+ owners.set(provideKey(resource.id, "inboxUrl"), resource);
1484
+ }
1485
+ if (resource.kind === "external-api") owners.set(provideKey(resource.id, "credentials"), resource);
1486
+ if (resource.kind === "websocket-api") owners.set(provideKey(resource.id, "publisherConnectionString"), resource);
1487
+ }
1488
+ const domain = workspace.domains?.[stage];
1489
+ const telemetry = resolveStageTelemetry({
1490
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1491
+ stage,
1492
+ local,
1493
+ target: "compose",
1494
+ runtime: "server",
1495
+ selfHosted: true,
1496
+ used: usesTelemetry(manifest)
1497
+ });
1498
+ const logsBase = telemetry?.provider === "self-hosted" ? stackLogs({
1499
+ config: local && input.ports?.logs ? {
1500
+ ...telemetry.selfHosted,
1501
+ port: input.ports.logs
1502
+ } : telemetry.selfHosted,
1503
+ stage,
1504
+ local,
1505
+ project: workspace.name,
1506
+ ...domain ? { domain } : {},
1507
+ custom,
1508
+ https,
1509
+ ...local ? { localLogin: input.localCredentials.logs } : {}
1510
+ }) : void 0;
1511
+ const services = local ? {
1512
+ missing: [],
1513
+ minio: plan.resources.filter((r) => r.kind === "objects").map((r) => r.id),
1514
+ mailpit: plan.resources.filter((r) => r.kind === "email").map((r) => r.id)
1515
+ } : externalServices({
1516
+ stage,
1517
+ declarations: stageServiceDeclarations({
1518
+ manifest,
1519
+ ...input.runnables ? { runnables: input.runnables } : {}
1520
+ }),
1521
+ supplied: custom,
1522
+ allow: input.allowDevServices === true,
1523
+ ...domain ? { domain } : {},
1524
+ providers: stageProviderNotes(workspace, stage)
1525
+ });
1526
+ const redis = stackRedis({
1527
+ plan,
1528
+ stage,
1529
+ local,
1530
+ custom,
1531
+ ...local ? { localPassword: input.localCredentials.redis.password } : {}
1532
+ });
1533
+ const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== LOGS_SERVICE).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logsBase ? [LOGS_SERVICE] : []].sort();
1534
+ const storage = infra.includes("minio") ? (() => {
1535
+ const buckets = services.minio.map((id) => byId.get(id)?.name).filter((name) => Boolean(name)).sort();
1536
+ return {
1537
+ ...credential.containers.minio,
1538
+ buckets,
1539
+ policies: bucketPolicies(plan).filter((p) => buckets.includes(p.bucket)),
1540
+ objects: services.minio.map((id) => ({
1541
+ id,
1542
+ name: byId.get(id)?.name
1543
+ })).filter((b) => Boolean(b.name)).sort((a, b) => a.name.localeCompare(b.name)),
1544
+ webhooks: [],
1545
+ lifecycles: bucketLifecycles(plan).filter((l) => buckets.includes(l.bucket))
1546
+ };
1547
+ })() : void 0;
1548
+ const bucketEventKeys = /* @__PURE__ */ new Map();
1549
+ for (const resource of plan.resources) {
1550
+ if (resource.kind !== "objects") continue;
1551
+ bucketEventKeys.set(provideKey(resource.id, "eventsConnectionString"), resource.id);
1552
+ bucketEventKeys.set(provideKey(resource.id, "eventsToken"), resource.id);
1553
+ }
1554
+ const fileServers = /* @__PURE__ */ new Map();
1555
+ if (storage) for (const resource of plan.resources) {
1556
+ if (resource.kind !== "file-server" || !resource.of) continue;
1557
+ if (!services.minio.includes(resource.of)) continue;
1558
+ if (custom[resource.envKey] !== void 0) continue;
1559
+ const bucket = byId.get(resource.of);
1560
+ if (!bucket) continue;
1561
+ let host;
1562
+ if (local) host = hostFor(resource, workspace.name);
1563
+ else {
1564
+ if (!domain) throw new NoDomainForStage(stage);
1565
+ host = `${resource.subdomain ?? appKey(resource.id)}.${domain}`;
1566
+ }
1567
+ fileServers.set(resource.id, {
1568
+ url: `https://${host}${local && https !== 443 ? `:${https}` : ""}`,
1569
+ route: {
1570
+ name: `files-${appKey(resource.id)}`,
1571
+ host,
1572
+ upstreams: [{
1573
+ service: "minio",
1574
+ port: 9e3
1575
+ }],
1576
+ streaming: false,
1577
+ prefix: `/${bucket.name}`
1578
+ }
1579
+ });
1580
+ }
1581
+ const edgeServices = new Set(proxy === "traefik" ? [
1582
+ ...apps.flatMap(replicaNames),
1583
+ ...fileServers.size > 0 ? ["minio"] : [],
1584
+ ...logsBase?.host && logsBase.public ? [LOGS_SERVICE] : []
1585
+ ] : []);
1586
+ const hostOf = (service) => edgeServices.has(service) ? edgeAlias(project, service) : service;
1587
+ const logs = logsBase && {
1588
+ ...logsBase,
1589
+ appEnv: {
1590
+ ...logsBase.appEnv,
1591
+ OTEL_EXPORTER_OTLP_ENDPOINT: logsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(`//openobserve:`, `//${hostOf("openobserve")}:`)
1592
+ }
1593
+ };
1594
+ const derivation = {
1595
+ project: workspace.name,
1596
+ credentials: credential.containers,
1597
+ seed: credential.seed,
1598
+ ...!local && domain ? { mailFrom: `noreply@${domain}` } : {},
1599
+ relayedBuckets: [...watchedBuckets(manifest, input.subscribers ?? {}).keys()].filter((bucket) => services.minio.includes(bucket))
1600
+ };
1601
+ const outside = networkEnv(plan, {
1602
+ ...derivation,
1603
+ addresses: Object.fromEntries(apps.map((app) => [app.id, app.url]))
1604
+ }, hostOf);
1605
+ const inside = networkEnv(plan, {
1606
+ ...derivation,
1607
+ addresses: Object.fromEntries(apps.map((app) => [app.id, `${app.kind === "websocket-api" ? "ws" : "http"}://${hostOf(app.name)}:${app.port}`]))
1608
+ }, hostOf);
1609
+ const surfaceUrls = new Map(plan.resources.filter((r) => r.kind === "rest-api" || r.kind === "websocket-api" || r.kind === "site").map((r) => [r.envKey, r.id]));
1610
+ const appById = new Map(apps.map((app) => [app.id, app]));
1611
+ /**
1612
+ * What a key resolves to for one app, from the stage's secrets where only
1613
+ * they can hold it, and the derivations otherwise.
1614
+ */
1615
+ const valueFor = (app, key, owner) => {
1616
+ if (isReservedStageKey(key)) return void 0;
1617
+ const watching = bucketEventKeys.get(key);
1618
+ if (watching) {
1619
+ if (custom[key] !== void 0) return custom[key];
1620
+ return services.minio.includes(watching) ? outside[key] : void 0;
1621
+ }
1622
+ if (!local && owner?.kind === "email" && key.endsWith("_INBOX_URL")) return;
1623
+ if (owner && SERVICE_KINDS[owner.kind]) {
1624
+ if (custom[key] !== void 0) return custom[key];
1625
+ if (owner.kind === "file-server") return fileServers.get(owner.id)?.url;
1626
+ return outside[key];
1627
+ }
1628
+ if (owner && suppliedOnly(owner.kind, owner.id, key, local)) {
1629
+ const value = custom[key];
1630
+ if (value === void 0) throw new StageSecretMissing(app.name, key, stage);
1631
+ return value;
1632
+ }
1633
+ if (custom[key] !== void 0) return custom[key];
1634
+ if (owner?.kind === "cache") return redis?.urls[key];
1635
+ if (owner?.kind === "websocket-api" && key === provideKey(owner.id, "publisherConnectionString")) return redis?.urls[key];
1636
+ const surface = surfaceUrls.get(key);
1637
+ if ((app.kind === "rest-api" || app.kind === "websocket-api") && surface && surface !== app.id) return inside[key];
1638
+ return outside[key];
1639
+ };
1640
+ const telemetryValues = logs ? telemetryEnv({
1641
+ endpoint: logs.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT,
1642
+ headers: logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS
1643
+ }, telemetry?.sampleRate ?? 1) : telemetry?.provider === "otlp" ? otlpTelemetryEnv(telemetry) : void 0;
1644
+ /** Each key one backend process reads, resolved for this stage. */
1645
+ const valuesFor = (app, keys) => {
1646
+ const values = {};
1647
+ for (const key of [...keys].sort()) {
1648
+ if (isTelemetryKey(key)) continue;
1649
+ const owner = owners.get(key) ?? storageOwner(key, plan);
1650
+ if (STORAGE_KEYS.includes(key)) {
1651
+ const value = custom[key] ?? storageValue(key, storage);
1652
+ if (value !== void 0) values[key] = value;
1653
+ continue;
1654
+ }
1655
+ const value = valueFor(app, key, owner);
1656
+ if (value !== void 0) values[key] = value;
1657
+ }
1658
+ return values;
1659
+ };
1660
+ for (const app of apps) {
1661
+ if (app.kind === "site") {
1662
+ const site = manifest[app.id];
1663
+ if (site?.kind !== "site") continue;
1664
+ const args = publicBuildValues(site, manifest, (key) => valueFor(app, key, owners.get(key)), custom);
1665
+ if (app.build && Object.keys(args).length > 0) app.build.args = args;
1666
+ continue;
1667
+ }
1668
+ if (input.buildOnly) continue;
1669
+ const keys = appEnvKeys(manifest, app.name, input.runnables) ?? /* @__PURE__ */ new Set();
1670
+ const values = valuesFor(app, keys);
1671
+ const trusted = provideKey(app.id, "trustedOrigins");
1672
+ if (keys.has(trusted)) {
1673
+ const internal = (byId.get(app.id)?.callers ?? []).map((caller) => appById.get(caller)).filter((caller) => caller?.kind === "rest-api" || caller?.kind === "websocket-api").map((caller) => `http://${hostOf(caller.name)}:${caller.port}`);
1674
+ const origins = [...(values[trusted] ?? "").split(",").filter(Boolean), ...internal];
1675
+ values[trusted] = [...new Set(origins)].join(",");
1676
+ }
1677
+ app.env = {
1678
+ ...scopeTelemetryEnv(values, {
1679
+ uses: telemetryOf(manifest, app.id) !== void 0,
1680
+ serviceName: app.name,
1681
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1682
+ }),
1683
+ NODE_ENV: "production",
1684
+ PORT: String(app.port),
1685
+ STAGE: stage
1686
+ };
1687
+ for (const [key, value] of Object.entries(app.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(app.name, key);
1688
+ }
1689
+ const mobileApps = [];
1690
+ for (const declaration of Object.values(manifest)) {
1691
+ if (declaration.kind !== "mobile-app") continue;
1692
+ const app = {
1693
+ name: appKey(declaration.id),
1694
+ id: declaration.id,
1695
+ kind: "site"
1696
+ };
1697
+ mobileApps.push({
1698
+ name: app.name,
1699
+ id: app.id,
1700
+ values: publicBuildValues(declaration, manifest, (key) => valueFor(app, key, owners.get(key)), custom)
1701
+ });
1702
+ }
1703
+ for (const worker of input.buildOnly ? [] : workers) {
1704
+ const keys = workerEnvKeys(manifest, worker.id, input.runnables) ?? /* @__PURE__ */ new Set();
1705
+ const resolved = valuesFor({
1706
+ name: worker.name,
1707
+ id: worker.id,
1708
+ kind: "rest-api"
1709
+ }, keys);
1710
+ const push = local ? void 0 : workerPush(worker, input.subscribers?.[worker.id] ?? [], resolved, {
1711
+ stage,
1712
+ ...domain ? { domain } : {}
1713
+ });
1714
+ if (push) {
1715
+ worker.push = push;
1716
+ if (proxy === "traefik") edgeServices.add(worker.name);
1717
+ }
1718
+ worker.env = {
1719
+ ...scopeTelemetryEnv(resolved, {
1720
+ uses: telemetryOf(manifest, worker.id) !== void 0,
1721
+ serviceName: worker.name,
1722
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1723
+ }),
1724
+ ...push && !input.recordingSubscriptions ? { [SNS_SUBSCRIPTIONS_KEY]: recordedSubscriptions(worker, push, input.pushSubscriptions?.[worker.id]) } : {},
1725
+ NODE_ENV: "production",
1726
+ PORT: String(worker.port),
1727
+ STAGE: stage
1728
+ };
1729
+ for (const [key, value] of Object.entries(worker.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);
1730
+ }
1731
+ for (const unit of processors) {
1732
+ const served = fileServers.get(unit.id);
1733
+ if (served) served.route = {
1734
+ ...served.route,
1735
+ handlers: [{
1736
+ name: unit.name,
1737
+ prefixes: unit.prefixes,
1738
+ upstreams: [{
1739
+ service: unit.name,
1740
+ port: unit.port
1741
+ }]
1742
+ }]
1743
+ };
1744
+ else if (!local && !input.buildOnly) {
1745
+ if (!domain) throw new NoDomainForStage(stage);
1746
+ const key = originSecretKey(unit.id);
1747
+ const secret = custom[key];
1748
+ if (!secret) throw new ProcessorOriginSecretMissing(unit.id, key, stage);
1749
+ unit.origin = {
1750
+ host: processorOriginHost(unit.id, domain),
1751
+ secret
1752
+ };
1753
+ }
1754
+ if (proxy === "traefik" && (served || unit.origin)) edgeServices.add(unit.name);
1755
+ if (input.buildOnly) continue;
1756
+ const keys = processorEnvKeys(manifest, unit.id, input.runnables) ?? /* @__PURE__ */ new Set();
1757
+ unit.env = {
1758
+ ...scopeTelemetryEnv(valuesFor({
1759
+ name: unit.name,
1760
+ id: unit.id,
1761
+ kind: "rest-api"
1762
+ }, keys), {
1763
+ uses: telemetryOf(manifest, unit.id) !== void 0,
1764
+ serviceName: unit.name,
1765
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1766
+ }),
1767
+ NODE_ENV: "production",
1768
+ PORT: String(unit.port),
1769
+ STAGE: stage
1770
+ };
1771
+ for (const [key, value] of Object.entries(unit.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(unit.name, key);
1772
+ }
1773
+ if (storage && !input.buildOnly) {
1774
+ const watched = watchedBuckets(manifest, input.subscribers ?? {});
1775
+ for (const [bucket, workerId] of watched) {
1776
+ if (!services.minio.includes(bucket)) continue;
1777
+ const worker = workers.find((w) => w.id === workerId);
1778
+ const relay = worker?.env?.[provideKey(bucket, "eventsConnectionString")];
1779
+ const token = worker?.env?.[provideKey(bucket, "eventsToken")];
1780
+ if (!worker || !relay || relay.startsWith("sns:") || !token) continue;
1781
+ storage.webhooks.push({
1782
+ bucket,
1783
+ endpoint: `http://${hostOf(worker.name)}:${worker.port}${objectsRoute(bucket)}`,
1784
+ token
1785
+ });
1786
+ }
1787
+ }
1788
+ const deployedTls = certificate ? {
1789
+ kind: "files",
1790
+ ...proxy === "caddy" ? {
1791
+ certFile: `${CADDY_TLS_DIR}/cert.pem`,
1792
+ keyFile: `${CADDY_TLS_DIR}/key.pem`
1793
+ } : edgeCertificatePaths(project)
1794
+ } : { kind: "acme" };
1795
+ const tls = local ? { kind: "internal" } : deployedTls;
1796
+ const backupsChoice = input.buildOnly ? void 0 : stageBackups(workspace, manifest, stage);
1797
+ const backups = backupsChoice?.mode === "on" && infra.includes("postgres") ? stackBackups({
1798
+ workspace,
1799
+ stage,
1800
+ project,
1801
+ plan,
1802
+ backups: backupsChoice.backups,
1803
+ custom,
1804
+ seed,
1805
+ superuser: credential.containers.postgres,
1806
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1807
+ }) : void 0;
1808
+ const layout = input.layout ?? defaultLayout(workspace.root);
1809
+ const compose = stackFile({
1810
+ project,
1811
+ plan,
1812
+ infra,
1813
+ apps,
1814
+ workers,
1815
+ processors,
1816
+ credentials: credential.containers,
1817
+ ...storage ? { storage } : {},
1818
+ ...logs ? { logs } : {},
1819
+ ...redis ? { redis } : {},
1820
+ ...backups ? { backups } : {},
1821
+ https,
1822
+ http,
1823
+ composeDir: join(workspace.root, stackDir(stage)),
1824
+ buildRoot: layout.buildRoot,
1825
+ workspaceRoot: workspace.root,
1826
+ envFiles: !input.buildOnly,
1827
+ proxy,
1828
+ edge: new Map([...edgeServices].map((service) => [service, hostOf(service)]))
1829
+ });
1830
+ if (!local) for (const app of apps) {
1831
+ const site = manifest[app.id];
1832
+ if (site?.kind !== "site") continue;
1833
+ const key = sitePasswordKey(manifest, site, stage);
1834
+ if (key) app.auth = siteAuth(stage, key, custom);
1835
+ }
1836
+ const routes = [
1837
+ ...apps.map((app) => ({
1838
+ name: app.name,
1839
+ host: app.host,
1840
+ upstreams: replicaNames(app).map((service) => ({
1841
+ service,
1842
+ port: app.port
1843
+ })),
1844
+ streaming: true,
1845
+ ...app.auth ? { auth: {
1846
+ user: app.auth.user,
1847
+ hash: app.auth.hash
1848
+ } } : {},
1849
+ health: app.kind === "site" ? "/" : "/health"
1850
+ })),
1851
+ ...[...fileServers.values()].map(({ route }) => route),
1852
+ ...processors.flatMap(({ name, port, prefixes, origin }) => origin ? [{
1853
+ name,
1854
+ host: origin.host,
1855
+ upstreams: [{
1856
+ service: name,
1857
+ port
1858
+ }],
1859
+ streaming: false,
1860
+ prefixes,
1861
+ requireHeader: {
1862
+ name: ORIGIN_VERIFY_HEADER,
1863
+ value: origin.secret
1864
+ },
1865
+ health: "/health"
1866
+ }] : []),
1867
+ ...workers.flatMap(({ name, port, push }) => push ? [{
1868
+ name,
1869
+ host: push.host,
1870
+ upstreams: [{
1871
+ service: name,
1872
+ port
1873
+ }],
1874
+ streaming: false,
1875
+ paths: push.paths,
1876
+ health: "/health"
1877
+ }] : []),
1878
+ ...logs?.host && logs.public ? [{
1879
+ name: LOGS_SERVICE,
1880
+ host: logs.host,
1881
+ upstreams: [{
1882
+ service: LOGS_SERVICE,
1883
+ port: LOGS_PORT
1884
+ }],
1885
+ streaming: true,
1886
+ allow: logs.public.allow
1887
+ }] : []
1888
+ ];
1889
+ assertHostsUnique(routes);
1890
+ const dockerfiles = {};
1891
+ for (const app of apps) {
1892
+ if (!app.build) continue;
1893
+ dockerfiles[app.build.dockerfile] = appDockerfile(app.name, workspace.apps[app.name], {
1894
+ layout,
1895
+ workspaceRoot: workspace.root,
1896
+ apps: workspace.apps,
1897
+ manifest,
1898
+ cache: STACK_CACHE,
1899
+ workspace,
1900
+ stage,
1901
+ ...app.kind === "site" && app.build.args ? { publicUrlArgs: Object.keys(app.build.args) } : {}
1902
+ });
1903
+ }
1904
+ for (const worker of workers) {
1905
+ if (!worker.build) continue;
1906
+ dockerfiles[worker.build.dockerfile] = workerDockerfile({
1907
+ id: worker.id,
1908
+ name: worker.name,
1909
+ app: worker.host
1910
+ }, workspace.apps[worker.host], {
1911
+ layout,
1912
+ workspaceRoot: workspace.root,
1913
+ cache: STACK_CACHE
1914
+ });
1915
+ }
1916
+ for (const unit of processors) {
1917
+ if (!unit.build) continue;
1918
+ dockerfiles[unit.build.dockerfile] = processorDockerfile({
1919
+ id: unit.id,
1920
+ name: unit.name,
1921
+ app: unit.host
1922
+ }, workspace.apps[unit.host], {
1923
+ layout,
1924
+ workspaceRoot: workspace.root,
1925
+ native: unit.native,
1926
+ cache: STACK_CACHE
1927
+ });
1928
+ }
1929
+ return {
1930
+ project,
1931
+ stage,
1932
+ local,
1933
+ apps,
1934
+ workers,
1935
+ processors,
1936
+ mobileApps,
1937
+ infra,
1938
+ compose,
1939
+ proxy,
1940
+ routes,
1941
+ ...proxy === "caddy" ? { caddyfile: edgeCaddyfile(routes, { tls }) } : { traefik: traefikDynamicFile(routes, {
1942
+ project,
1943
+ tls: deployedTls
1944
+ }) },
1945
+ ...certificate ? { tls: certificate } : {},
1946
+ dockerfiles,
1947
+ plan,
1948
+ credential,
1949
+ ...storage ? { storage } : {},
1950
+ devServices: local ? [] : devServicesUsed(services),
1951
+ ...logs ? { logs } : {},
1952
+ ...telemetry ? { telemetry } : {},
1953
+ ...redis ? { redis } : {},
1954
+ ...backups ? { backups } : {}
1955
+ };
1956
+ }
1957
+ /** The stack's MinIO's value for one of the S3 client's keys. */
1958
+ function storageValue(key, storage) {
1959
+ if (!storage) return void 0;
1960
+ if (key === "AWS_ACCESS_KEY_ID") return storage.user;
1961
+ if (key === "AWS_SECRET_ACCESS_KEY") return storage.password;
1962
+ if (key === "AWS_REGION") return MINIO_REGION;
1963
+ }
1964
+ /** Which bucket an S3 credential key belongs to — the first one declared. */
1965
+ function storageOwner(key, plan) {
1966
+ if (!STORAGE_KEYS.includes(key)) return void 0;
1967
+ return plan.resources.find((r) => r.kind === "objects");
1968
+ }
1969
+ /** The apps a stack runs: every API and every site, at its stage address. */
1970
+ function stackApps(workspace, manifest, plan, options) {
1971
+ const apps = [];
1972
+ const resources = new Map(plan.resources.map((r) => [r.id, r]));
1973
+ for (const [id, declaration] of Object.entries(manifest)) {
1974
+ if (declaration.kind !== "rest-api" && declaration.kind !== "websocket-api" && declaration.kind !== "site") continue;
1975
+ const name = appKey(id);
1976
+ const app = workspace.apps[name];
1977
+ const resource = resources.get(id);
1978
+ if (!app || !resource || !app.port) continue;
1979
+ const host = hostOf(name, app, workspace, resource, options);
1980
+ const tag = declaration.kind === "site" ? siteTag(options.images.tag, options.stage) : options.images.tag;
1981
+ const ref = validateImageRef(imageRef(options.identity, name, options.images.registry, tag));
1982
+ apps.push({
1983
+ app: name,
1984
+ name,
1985
+ id,
1986
+ kind: declaration.kind,
1987
+ replicas: declaration.kind === "websocket-api" ? declaration.replicas ?? 1 : 1,
1988
+ path: app.path,
1989
+ port: app.port,
1990
+ host,
1991
+ url: `${declaration.kind === "websocket-api" ? "wss" : "https"}://${host}${options.local && options.https !== 443 ? `:${options.https}` : ""}`,
1992
+ ref,
1993
+ tag,
1994
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${name}` } } : {}
1995
+ });
1996
+ }
1997
+ return apps.sort((a, b) => a.name.localeCompare(b.name));
1998
+ }
1999
+ /**
2000
+ * Where SNS pushes to a worker on a deployed stage, or nothing when it pushes
2001
+ * to none of its subscribers.
2002
+ *
2003
+ * A subscriber is pushed to when the connection string its deliveries come
2004
+ * from — its topic's, or its bucket's events — as this stage resolved it for
2005
+ * the worker, is an SNS one — the same test the worker's own
2006
+ * startup makes, so the edge exposes a route exactly when the worker mounts
2007
+ * it. Each such route, and nothing else the worker serves, answers on
2008
+ * `<worker>.<domain>`.
2009
+ */
2010
+ function workerPush(worker, subscribers, env, options) {
2011
+ const pushed = subscribers.filter(({ connectionKey }) => env[connectionKey]?.startsWith("sns:")).filter((subscriber, index, all) => all.findIndex((s) => s.name === subscriber.name) === index).sort((a, b) => a.name.localeCompare(b.name));
2012
+ if (pushed.length === 0) return void 0;
2013
+ if (!options.domain) throw new NoDomainForStage(options.stage);
2014
+ const host = `${worker.name}.${options.domain}`;
2015
+ const url = `https://${host}`;
2016
+ return {
2017
+ host,
2018
+ url,
2019
+ paths: pushed.map(({ name }) => subscriberRoute(name)),
2020
+ subscribers: pushed.map(({ name, connectionKey, events }) => ({
2021
+ name,
2022
+ connectionKey,
2023
+ endpoint: `${url}${subscriberRoute(name)}`,
2024
+ ...events ? { events } : {}
2025
+ }))
2026
+ };
2027
+ }
2028
+ /** A pushed subscriber the deploy recorded no SNS subscription for. */
2029
+ var PushSubscriptionMissing = class extends GkmError {
2030
+ worker;
2031
+ subscriber;
2032
+ constructor(worker, subscriber) {
2033
+ super(`SNS pushes to '${subscriber}' on the worker '${worker}', and the deploy recorded no subscription for it, so the worker would mount no route and SNS would deliver nowhere. Deploy the stage, which subscribes each pushed subscriber and records its ARN.`);
2034
+ this.worker = worker;
2035
+ this.subscriber = subscriber;
2036
+ this.name = "PushSubscriptionMissing";
2037
+ }
2038
+ };
2039
+ /**
2040
+ * The worker's `GKM_SNS_SUBSCRIPTIONS`: each pushed subscriber's recorded
2041
+ * subscription ARN, and nothing for a subscriber it does not run.
2042
+ *
2043
+ * @throws {PushSubscriptionMissing} when one has none
2044
+ */
2045
+ function recordedSubscriptions(worker, push, recorded = {}) {
2046
+ const arns = {};
2047
+ for (const { name } of push.subscribers) {
2048
+ const arn = recorded[name];
2049
+ if (!arn) throw new PushSubscriptionMissing(worker.name, name);
2050
+ arns[name] = arn;
2051
+ }
2052
+ return JSON.stringify(arns);
2053
+ }
2054
+ /** Two constructs the edge would answer on one host. */
2055
+ var EdgeHostTaken = class extends GkmError {
2056
+ host;
2057
+ first;
2058
+ second;
2059
+ constructor(host, first, second) {
2060
+ super(`'${first}' and '${second}' would both answer on ${host}, and the edge can send a host to only one of them. Give one a subdomain of its own, or rename it.`);
2061
+ this.host = host;
2062
+ this.first = first;
2063
+ this.second = second;
2064
+ this.name = "EdgeHostTaken";
2065
+ }
2066
+ };
2067
+ /** Refuse a stack where one host would be routed to two services. */
2068
+ function assertHostsUnique(routes) {
2069
+ const claimed = /* @__PURE__ */ new Map();
2070
+ for (const { host, name } of routes) {
2071
+ const first = claimed.get(host);
2072
+ if (first !== void 0) throw new EdgeHostTaken(host, first, name);
2073
+ claimed.set(host, name);
2074
+ }
2075
+ }
2076
+ /** Each processor unit's image, and where it is built from. */
2077
+ function stackProcessors(units, options) {
2078
+ return units.map((unit) => {
2079
+ const server = options.manifest[unit.id];
2080
+ const processors = server?.kind === "file-server" ? server.processors ?? [] : [];
2081
+ return {
2082
+ app: unit.name,
2083
+ name: unit.name,
2084
+ id: unit.id,
2085
+ host: unit.app,
2086
+ port: PROCESSOR_PORT,
2087
+ prefixes: [...new Set(processors.map((p) => p.prefix))].sort(),
2088
+ native: processorNative(options.manifest, unit.id),
2089
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
2090
+ tag: options.images.tag,
2091
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
2092
+ };
2093
+ });
2094
+ }
2095
+ /** Each worker's image, and where it is built from. */
2096
+ function stackWorkers(units, options) {
2097
+ return units.map((unit) => ({
2098
+ app: unit.name,
2099
+ name: unit.name,
2100
+ id: unit.id,
2101
+ host: unit.app,
2102
+ port: WORKER_PORT,
2103
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
2104
+ tag: options.images.tag,
2105
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
2106
+ }));
2107
+ }
2108
+ /**
2109
+ * The host an app answers on for a stage: the `gkm dev` edge's
2110
+ * `*.localhost` names for the local stage, and the stage's domain — by the
2111
+ * same rule a deploy follows — for any other.
2112
+ */
2113
+ function hostOf(name, app, workspace, resource, options) {
2114
+ if (options.local) return hostFor(resource, workspace.name);
2115
+ return resolveHost(name, app, options.stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
2116
+ }
2117
+ /** An app's compose services, one per replica: `api`, `api-2`, `api-3`. */
2118
+ function replicaNames(app) {
2119
+ return [app.name, ...Array.from({ length: app.replicas - 1 }, (_, i) => `${app.name}-${i + 2}`)];
2120
+ }
2121
+ /** The compose document: the infrastructure, the apps, and the edge. */
2122
+ function stackFile(options) {
2123
+ const { project, plan, apps } = options;
2124
+ const infra = options.infra.filter((name) => name !== LOGS_SERVICE);
2125
+ const derived = composeFor({
2126
+ ...plan,
2127
+ containers: [...infra]
2128
+ }, {
2129
+ project,
2130
+ ports: Object.fromEntries(portKeys(infra, plan.fakes).map((key) => [key, 0])),
2131
+ credentials: options.credentials
2132
+ });
2133
+ const services = {};
2134
+ const volumes = {
2135
+ ...derived.volumes,
2136
+ ...options.proxy === "caddy" ? {
2137
+ "caddy-data": {},
2138
+ "caddy-config": {}
2139
+ } : {},
2140
+ ...options.logs ? { "openobserve-data": {} } : {}
2141
+ };
2142
+ for (const name of infra) {
2143
+ const { ports: _ports, depends_on, profiles: _profiles, ...service } = derived.services[name];
2144
+ services[name] = {
2145
+ ...service,
2146
+ ...depends_on?.length ? { depends_on: Object.fromEntries(depends_on.map((dep) => [dep, HEALTHY])) } : {}
2147
+ };
2148
+ }
2149
+ const postgres = services.postgres;
2150
+ if (postgres) postgres.ports = ["127.0.0.1::5432"];
2151
+ const minio = services.minio;
2152
+ if (minio && options.storage) {
2153
+ minio.environment = {
2154
+ ...minio.environment,
2155
+ MINIO_ROOT_USER: options.storage.user,
2156
+ MINIO_ROOT_PASSWORD: options.storage.password,
2157
+ ...minioWebhookEnv(options.storage.webhooks)
2158
+ };
2159
+ minio.ports = ["127.0.0.1::9000"];
2160
+ }
2161
+ if (services["redis"] && options.redis) services[REDIS_SERVICE] = redisService(options.redis);
2162
+ if (options.logs) services[LOGS_SERVICE] = logsService(options.logs);
2163
+ if (options.backups) services[BACKUPS_SERVICE] = backupsService(options.backups, options.envFiles);
2164
+ for (const app of apps) {
2165
+ const definition = {
2166
+ image: app.ref,
2167
+ ...app.build ? { build: {
2168
+ ...composeBuildPaths({
2169
+ composeDir: options.composeDir,
2170
+ buildRoot: options.buildRoot,
2171
+ workspaceRoot: options.workspaceRoot,
2172
+ dockerfile: app.build.dockerfile
2173
+ }),
2174
+ ...app.build.args ? { args: app.build.args } : {}
2175
+ } } : {},
2176
+ restart: "unless-stopped",
2177
+ ...app.kind !== "site" ? {
2178
+ env_file: [{
2179
+ path: `./${app.name}.env`,
2180
+ format: "raw"
2181
+ }],
2182
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {}
2183
+ } : {},
2184
+ healthcheck: probe(app.port, app.kind === "site" ? "/" : "/health"),
2185
+ ...app.kind === "websocket-api" ? { ulimits: { nofile: NOFILE } } : {}
2186
+ };
2187
+ for (const name of replicaNames(app)) services[name] = { ...definition };
2188
+ }
2189
+ for (const worker of [...options.workers, ...options.processors]) services[worker.name] = {
2190
+ image: worker.ref,
2191
+ ...worker.build ? { build: composeBuildPaths({
2192
+ composeDir: options.composeDir,
2193
+ buildRoot: options.buildRoot,
2194
+ workspaceRoot: options.workspaceRoot,
2195
+ dockerfile: worker.build.dockerfile
2196
+ }) } : {},
2197
+ restart: "unless-stopped",
2198
+ env_file: [{
2199
+ path: `./${worker.name}.env`,
2200
+ format: "raw"
2201
+ }],
2202
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
2203
+ healthcheck: probe(worker.port, "/health")
2204
+ };
2205
+ if (options.proxy === "caddy") services.caddy = {
2206
+ image: DEFAULT_IMAGES.caddy,
2207
+ restart: "unless-stopped",
2208
+ ports: [`${options.https}:443`, `${options.http}:80`],
2209
+ volumes: ["caddy-data:/data", "caddy-config:/config"],
2210
+ ...EDGE_LIMITS,
2211
+ depends_on: Object.fromEntries([
2212
+ ...apps.flatMap(replicaNames),
2213
+ ...options.workers.filter((w) => w.push).map((w) => w.name),
2214
+ ...options.processors.map((p) => p.name)
2215
+ ].map((name) => [name, HEALTHY])),
2216
+ healthcheck: {
2217
+ test: [
2218
+ "CMD",
2219
+ "caddy",
2220
+ "version"
2221
+ ],
2222
+ interval: "10s",
2223
+ timeout: "5s",
2224
+ retries: 5
2225
+ }
2226
+ };
2227
+ for (const [service, alias] of options.edge) {
2228
+ const definition = services[service];
2229
+ if (!definition) continue;
2230
+ definition.networks = {
2231
+ default: { aliases: [alias] },
2232
+ edge: { aliases: [alias] }
2233
+ };
2234
+ }
2235
+ for (const service of Object.values(services)) {
2236
+ if (!options.envFiles) delete service.env_file;
2237
+ service.logging = {
2238
+ driver: LOG_ROTATION.driver,
2239
+ options: { ...LOG_ROTATION.options }
2240
+ };
2241
+ }
2242
+ return {
2243
+ name: project,
2244
+ services,
2245
+ volumes,
2246
+ ...options.edge.size > 0 ? { networks: { edge: {
2247
+ name: EDGE_NETWORK,
2248
+ external: true
2249
+ } } } : {}
2250
+ };
2251
+ }
2252
+ /**
2253
+ * A build without a layout: the workspace is the build root, with pnpm.
2254
+ * What a caller that never looked at the filesystem gets.
2255
+ */
2256
+ function defaultLayout(root) {
2257
+ return {
2258
+ buildRoot: root,
2259
+ gkmRoot: ".",
2260
+ tools: {
2261
+ packageManager: "pnpm",
2262
+ turboVersion: TURBO_VERSION,
2263
+ monorepo: true
2264
+ },
2265
+ gkmPaths: ["gkm.config.*"]
2266
+ };
2267
+ }
2268
+ /** Render an app's env file: one `KEY=value` per line, read raw by compose. */
2269
+ function envFile(env) {
2270
+ return `${Object.entries(env).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n")}\n`;
2271
+ }
2272
+ //#endregion
2273
+ //#region src/compose/edge.ts
2274
+ /**
2275
+ * The server's shared Traefik edge, in Docker: started when a stack needs it,
2276
+ * and each stack's routes written to — and removed from — the directory it
2277
+ * watches.
2278
+ *
2279
+ * Everything goes through the server's Docker engine, never its filesystem:
2280
+ * the edge's static configuration is handed to it inline, and the directories
2281
+ * it watches are volumes each stack writes into with `docker exec`. So the
2282
+ * deploy runs anywhere that reaches the engine — a CI runner over SSH — and
2283
+ * nothing it writes depends on a path on that machine.
2284
+ *
2285
+ * gkm-edge (compose project)
2286
+ * traefik.yml its static configuration (inline config)
2287
+ * dynamic/<project>.yml one per stack: routers, services, middlewares
2288
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
2289
+ */
2290
+ /** The edge's compose project, as docker is asked about it. */
2291
+ function edgeRef(file, options = {}) {
2292
+ return {
2293
+ project: EDGE_PROJECT,
2294
+ file,
2295
+ cwd: dirname(file),
2296
+ ...options
2297
+ };
2298
+ }
2299
+ /** Writing to or removing from the edge's volumes failed. */
2300
+ var EdgeWriteFailed = class extends GkmError {
2301
+ path;
2302
+ output;
2303
+ constructor(path, output) {
2304
+ super(`Could not write ${path} in the shared edge (${EDGE_PROJECT}): ${output.trim() || "it is not running"}. Check it with \`docker compose -p ${EDGE_PROJECT} ps\` on the server, and run gkm compose again.`);
2305
+ this.path = path;
2306
+ this.output = output;
2307
+ this.name = "EdgeWriteFailed";
2308
+ }
2309
+ };
2310
+ /**
2311
+ * Something other than the proxy a stack is set to holds the edge's ports.
2312
+ *
2313
+ * With `proxy: 'traefik'`, the stack's own Caddy — still running from before
2314
+ * the switch — or any other container; with `proxy: 'caddy'`, the shared
2315
+ * edge, or another stack's Caddy. Refused before anything is started, so the
2316
+ * stack is never left half on one proxy and half on the other.
2317
+ */
2318
+ var ComposeProxyClash = class extends GkmError {
2319
+ project;
2320
+ proxy;
2321
+ port;
2322
+ holder;
2323
+ constructor(project, proxy, port, holder) {
2324
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
2325
+ const fix = proxy === "traefik" ? holder.project === project && holder.service === "caddy" ? `That is this stack's own Caddy, from before it was switched to proxy: 'traefik'. Move it once: stop it (docker compose -p ${project} stop caddy), then run gkm compose again — the shared edge takes 80/443 and the stack registers with it.` : `The shared edge needs ports 80 and 443. Stop ${holder.container}${holder.project ? ` (docker compose -p ${holder.project} down, or its own gkm compose --down)` : ""}, or move the edge with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.` : holder.project === "gkm-edge" ? `That is the server's shared Traefik edge, which other stacks register with. Set deploy.compose.proxy to 'traefik' for this stage so the stack registers with it too, or stop the edge once nothing uses it (docker compose -p ${EDGE_PROJECT} down).` : `Stop ${holder.container}, or publish this stack's Caddy elsewhere with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.`;
2326
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
2327
+ this.project = project;
2328
+ this.proxy = proxy;
2329
+ this.port = port;
2330
+ this.holder = holder;
2331
+ this.name = "ComposeProxyClash";
2332
+ }
2333
+ };
2334
+ /**
2335
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
2336
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
2337
+ */
2338
+ async function assertEdgePorts(docker, options) {
2339
+ const { project, proxy, ports } = options;
2340
+ for (const port of [ports.https, ports.http]) for (const holder of await docker.publishers(options.engine, port)) if (!(proxy === "traefik" ? holder.project === "gkm-edge" : holder.project === project && holder.service === "caddy")) throw new ComposeProxyClash(project, proxy, port, holder);
2341
+ }
2342
+ /**
2343
+ * Write a file into the edge's running container whole or not at all: a
2344
+ * temporary name, then a rename. Not `.yml`: the edge reads only `.yml`,
2345
+ * `.yaml` and `.toml` files, so it never sees one half written.
2346
+ */
2347
+ async function put(docker, edge, path, content, mode = "644") {
2348
+ const result = await docker.exec(edge, EDGE_SERVICE, [
2349
+ "sh",
2350
+ "-c",
2351
+ "set -e; t=\"$1.tmp\"; cat > \"$t\"; chmod \"$2\" \"$t\"; mv \"$t\" \"$1\"",
2352
+ "sh",
2353
+ path,
2354
+ mode
2355
+ ], content);
2356
+ if (result.code !== 0) throw new EdgeWriteFailed(path, `${result.stderr}${result.stdout}`);
2357
+ }
2358
+ /** Remove files from the edge's container; whether the first was there. */
2359
+ async function remove(docker, edge, paths) {
2360
+ return (await docker.exec(edge, EDGE_SERVICE, [
2361
+ "sh",
2362
+ "-c",
2363
+ "e=1; [ -f \"$1\" ] && e=0; rm -f \"$@\"; exit $e",
2364
+ "sh",
2365
+ ...paths
2366
+ ])).code === 0;
2367
+ }
2368
+ /**
2369
+ * The edge, up: its network and its container — started when it is not
2370
+ * running, and recreated when its configuration changed. Idempotent: on a
2371
+ * server where it already runs as configured, `up` changes nothing. Its
2372
+ * compose file is written to `file`, on this machine: compose reads it here.
2373
+ */
2374
+ async function ensureEdge(docker, options) {
2375
+ const { file, ports } = options;
2376
+ const content = edgeComposeFile({
2377
+ ports,
2378
+ staticConfig: traefikStaticFile(ports),
2379
+ logging: options.logging
2380
+ });
2381
+ await mkdir(dirname(file), { recursive: true });
2382
+ if (await readFile(file, "utf-8").catch(() => void 0) !== content) await writeFile(file, content);
2383
+ const ref = edgeRef(file, {
2384
+ ...options.host ? { host: options.host } : {},
2385
+ ...options.output ? { output: options.output } : {},
2386
+ ...options.signal ? { signal: options.signal } : {}
2387
+ });
2388
+ await docker.ensureNetwork(ref, EDGE_NETWORK);
2389
+ await docker.up(ref, [EDGE_SERVICE]);
2390
+ return [file];
2391
+ }
2392
+ /** A stack's routes, inside the edge's container. */
2393
+ function routesPath(project) {
2394
+ return `${EDGE_DYNAMIC_DIR}/${project}.yml`;
2395
+ }
2396
+ function certificatePaths(project) {
2397
+ return [`${EDGE_CERTS_DIR}/${project}.crt`, `${EDGE_CERTS_DIR}/${project}.key`];
2398
+ }
2399
+ /**
2400
+ * Register a stack with the edge: its certificate first, where it has one,
2401
+ * so the routes that need it never load without it — then its routes, in one
2402
+ * rename the edge picks up whole. The certificate is read here and written
2403
+ * through the engine. The paths written, inside the edge.
2404
+ */
2405
+ async function writeEdgeRoutes(docker, edge, project, routes, certificate) {
2406
+ const written = [];
2407
+ const [crt, key] = certificatePaths(project);
2408
+ if (certificate) {
2409
+ await put(docker, edge, crt, await readFile(certificate.certFile, "utf-8"));
2410
+ await put(docker, edge, key, await readFile(certificate.keyFile, "utf-8"), "600");
2411
+ written.push(crt, key);
2412
+ } else await remove(docker, edge, [crt, key]);
2413
+ await put(docker, edge, routesPath(project), routes);
2414
+ written.push(routesPath(project));
2415
+ return written;
2416
+ }
2417
+ /** What a stack's file holds for the moment between emptying and removal. */
2418
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
2419
+ /**
2420
+ * Unregister a stack: its routes, then its certificate. Whether there was
2421
+ * anything to remove — false, too, when the edge is not running.
2422
+ */
2423
+ async function removeEdgeRoutes(docker, edge, project) {
2424
+ const file = routesPath(project);
2425
+ if ((await docker.exec(edge, "traefik", [
2426
+ "test",
2427
+ "-f",
2428
+ file
2429
+ ])).code !== 0) return false;
2430
+ await put(docker, edge, file, UNREGISTERED);
2431
+ await remove(docker, edge, [file, ...certificatePaths(project)]);
2432
+ return true;
2433
+ }
2434
+ //#endregion
2435
+ //#region src/compose/secrets.ts
2436
+ function deployedStackSecrets(workspace, stage, stored, manifest) {
2437
+ const withSeed = withGeneratedSecrets(stored ?? initStageSecrets(stage), manifest);
2438
+ const withLogs = resolveStageTelemetry({
2439
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
2440
+ stage,
2441
+ local: false,
2442
+ target: "compose",
2443
+ runtime: "server",
2444
+ selfHosted: true,
2445
+ used: usesTelemetry(manifest)
2446
+ })?.provider === "self-hosted" ? withLogsPassword(withSeed.secrets) : {
2447
+ secrets: withSeed.secrets,
2448
+ generated: []
2449
+ };
2450
+ const withRedis = runsRedis(manifest, withLogs.secrets.custom ?? {}) ? withRedisPassword(withLogs.secrets) : {
2451
+ secrets: withLogs.secrets,
2452
+ generated: []
2453
+ };
2454
+ return {
2455
+ secrets: withRedis.secrets,
2456
+ generated: [
2457
+ ...withSeed.generated,
2458
+ ...withLogs.generated,
2459
+ ...withRedis.generated
2460
+ ]
2461
+ };
2462
+ }
2463
+ //#endregion
2464
+ //#region src/target/compose/health.ts
2465
+ /**
2466
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
2467
+ * the way a browser reaches it.
2468
+ *
2469
+ * `docker compose up --wait` already knows each container passed its own
2470
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
2471
+ * the stack is reachable: whether the edge routes the host to the app, and
2472
+ * whether the certificate it presents is one a client accepts. So the check
2473
+ * goes through the edge, by hostname, and verifies the certificate.
2474
+ */
2475
+ /** A request that got no answer in time. */
2476
+ var HealthRequestTimedOut = class extends GkmError {
2477
+ url;
2478
+ timeoutMs;
2479
+ constructor(url, timeoutMs) {
2480
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
2481
+ this.url = url;
2482
+ this.timeoutMs = timeoutMs;
2483
+ this.name = "HealthRequestTimedOut";
2484
+ }
2485
+ };
2486
+ /** The real probe: one HTTPS GET, the certificate verified. */
2487
+ const httpsProbe = ({ url, ca, connectTo, connectPort, authorization, timeoutMs, signal }) => {
2488
+ const target = new URL(url);
2489
+ return new Promise((resolve, reject) => {
2490
+ const req = request({
2491
+ host: connectTo ?? target.hostname,
2492
+ port: connectPort ?? (target.port || 443),
2493
+ servername: target.hostname,
2494
+ path: `${target.pathname}${target.search}`,
2495
+ method: "GET",
2496
+ headers: {
2497
+ host: target.host,
2498
+ ...authorization ? { authorization } : {}
2499
+ },
2500
+ ...ca ? { ca } : {},
2501
+ ...signal ? { signal } : {},
2502
+ timeout: timeoutMs
2503
+ }, (res) => {
2504
+ res.resume();
2505
+ res.on("end", () => resolve(res.statusCode ?? 0));
2506
+ res.on("error", reject);
2507
+ });
2508
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
2509
+ req.on("error", reject);
2510
+ req.end();
2511
+ });
2512
+ };
2513
+ /** Whether a status means the app answered as it should. */
2514
+ function isHealthy(status) {
2515
+ return status >= 200 && status < 400;
2516
+ }
2517
+ /** Apps that did not answer through the edge. */
2518
+ var ComposeAppsUnhealthy = class extends GkmError {
2519
+ project;
2520
+ apps;
2521
+ proxy;
2522
+ constructor(project, apps, proxy = "caddy") {
2523
+ const names = apps.map((a) => a.app).join(" ");
2524
+ super(`${project} started, but ${apps.length === 1 ? "this app does" : "these apps do"} not answer through ${proxy === "caddy" ? "Caddy" : "the shared Traefik edge"}:\n` + apps.map(({ url, last }) => ` - ${url}: ${last}`).join("\n") + (proxy === "caddy" ? `\nSee why with \`docker compose -p ${project} logs caddy ${names}\`.` : `\nSee why with \`docker compose -p gkm-edge logs traefik\` and \`docker compose -p ${project} logs ${names}\`.`));
2525
+ this.project = project;
2526
+ this.apps = apps;
2527
+ this.proxy = proxy;
2528
+ this.name = "ComposeAppsUnhealthy";
2529
+ }
2530
+ };
2531
+ //#endregion
2532
+ //#region src/target/compose/topicSubscriptions.ts
2533
+ /**
2534
+ * Every topic subscriber the stack pushes to: a subscriber whose connection
2535
+ * key is a topic's publisher string — a bucket's events key is not — and
2536
+ * whose value on this stage is an SNS one.
2537
+ */
2538
+ function topicPushes(stack, manifest) {
2539
+ const topicKeys = new Set(Object.values(manifest).filter((declaration) => declaration.kind === "topic").map((topic) => provideKey(topic.id, "publisherConnectionString")));
2540
+ const pushes = [];
2541
+ for (const worker of stack.workers) for (const subscriber of worker.push?.subscribers ?? []) {
2542
+ if (!topicKeys.has(subscriber.connectionKey)) continue;
2543
+ const connectionString = worker.env?.[subscriber.connectionKey];
2544
+ if (!connectionString?.startsWith("sns:")) continue;
2545
+ pushes.push({
2546
+ worker: worker.id,
2547
+ name: subscriber.name,
2548
+ endpoint: subscriber.endpoint,
2549
+ connectionKey: subscriber.connectionKey,
2550
+ connectionString,
2551
+ ...subscriber.events ? { events: subscriber.events } : {}
2552
+ });
2553
+ }
2554
+ return pushes;
2555
+ }
2556
+ /** The subscriptions recorded for hand-set topics: those with a key. */
2557
+ function recordedTopicSubscriptions(resources) {
2558
+ return Object.values(resources ?? {}).filter((record) => record.type === "sns-subscription" && typeof record.data?.connectionKey === "string");
2559
+ }
2560
+ /**
2561
+ * Converge each hand-set topic's subscriptions on the subscribers pushed to:
2562
+ * subscribe, bring filters up to date, unsubscribe a route on the worker's
2563
+ * host no subscriber wants any more — and record each ARN, forgetting what
2564
+ * was removed.
2565
+ *
2566
+ * @returns each worker's subscriptions, by export — what it is handed
2567
+ */
2568
+ async function ensureTopicSubscriptions(input) {
2569
+ const { snsUrl, reconcileHttpSubscriptions } = await import("@geekmidas/events/sns");
2570
+ const groups = /* @__PURE__ */ new Map();
2571
+ const group = (topicArn, host, connectionKey) => {
2572
+ const id = `${topicArn}|${host}`;
2573
+ const found = groups.get(id);
2574
+ if (found) return found;
2575
+ const created = {
2576
+ topicArn,
2577
+ host,
2578
+ connectionKey,
2579
+ pushes: [],
2580
+ recorded: []
2581
+ };
2582
+ groups.set(id, created);
2583
+ return created;
2584
+ };
2585
+ for (const push of input.pushes) {
2586
+ const { topicArn } = snsUrl.parse(push.connectionString);
2587
+ const into = group(topicArn, new URL(push.endpoint).host, push.connectionKey);
2588
+ into.connectionString = push.connectionString;
2589
+ into.pushes.push(push);
2590
+ }
2591
+ for (const record of recordedTopicSubscriptions(input.recorded)) group(String(record.data?.topicArn), new URL(String(record.data?.endpoint)).host, String(record.data?.connectionKey)).recorded.push(record);
2592
+ const wanted = new Set(input.pushes.map(({ worker, name }) => subscriptionKey(worker, name)));
2593
+ const arns = {};
2594
+ for (const { topicArn, host, connectionKey, ...members } of groups.values()) {
2595
+ const stale = members.recorded.filter((r) => !wanted.has(r.key));
2596
+ const named = members.connectionString ?? input.secrets[connectionKey];
2597
+ if (!named?.startsWith("sns:")) {
2598
+ for (const record of stale) {
2599
+ input.log(` – forgot ${record.data?.endpoint}: '${connectionKey}' no longer names an SNS topic to unsubscribe it from`);
2600
+ await input.forget(record.key);
2601
+ }
2602
+ continue;
2603
+ }
2604
+ const address = new URL(named);
2605
+ address.searchParams.set("topicArn", topicArn);
2606
+ const connection = await topicConnection({
2607
+ connectionKey,
2608
+ connectionString: address.toString(),
2609
+ stage: input.stage,
2610
+ env: input.env
2611
+ });
2612
+ const result = await reconcileHttpSubscriptions(connection, {
2613
+ endpoints: members.pushes.map((push) => ({
2614
+ name: push.name,
2615
+ endpoint: push.endpoint,
2616
+ ...push.events ? { events: push.events } : {}
2617
+ })),
2618
+ ownedHost: host
2619
+ });
2620
+ await connection.close();
2621
+ for (const push of members.pushes) {
2622
+ const arn = result.subscriptions[push.name];
2623
+ const key = subscriptionKey(push.worker, push.name);
2624
+ if (input.recorded?.[key]?.id !== arn) input.log(` ✓ '${push.name}' subscribed to ${topicArn.split(":").pop()} at ${push.endpoint}`);
2625
+ await input.record(subscriptionResource({
2626
+ worker: push.worker,
2627
+ name: push.name,
2628
+ topicArn,
2629
+ endpoint: push.endpoint,
2630
+ connectionKey: push.connectionKey,
2631
+ pending: result.pending.includes(push.name),
2632
+ ...push.events ? { events: push.events } : {}
2633
+ }, arn));
2634
+ arns[push.worker] = {
2635
+ ...arns[push.worker],
2636
+ [push.name]: arn
2637
+ };
2638
+ }
2639
+ for (const arn of result.removed) input.log(` – unsubscribed ${arn}: no subscriber wants it any more`);
2640
+ for (const record of stale) await input.forget(record.key);
2641
+ }
2642
+ return arns;
2643
+ }
2644
+ //#endregion
2645
+ //#region src/target/compose/phases.ts
2646
+ /**
2647
+ * The compose target's phases: a stage as one Docker Compose stack behind
2648
+ * Caddy — the local stage on this machine's Docker, a deployed stage on its
2649
+ * server's, driven over SSH (`compose/server.ts`) from wherever the deploy
2650
+ * runs.
2651
+ *
2652
+ * The order is the point of this file, and the rules it keeps are these:
2653
+ *
2654
+ * - A tag is checked before anything happens (`validate`). Every app's image
2655
+ * is asked of the registry first; one missing image stops the run naming
2656
+ * them all, and nothing is written, pulled or started.
2657
+ * - The databases exist before the apps do (`provision`). Postgres comes up
2658
+ * alone, its databases, roles and grants are created, its migrations
2659
+ * applied and its seeds run from this machine — through an SSH tunnel to a
2660
+ * server's loopback — and only then do the apps
2661
+ * start — so an app
2662
+ * never boots against a schema that is not there yet.
2663
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
2664
+ * was released under and the digest it resolved to are written to the
2665
+ * stage's state, so "what is this stage running" has an exact answer.
2666
+ * - What was started answers (`verify`): each app is asked through Caddy,
2667
+ * over HTTPS, with the certificate verified.
2668
+ *
2669
+ * Every image is built inside Docker from a pruned slice of the build root —
2670
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
2671
+ * machine before `docker compose build`.
2672
+ *
2673
+ * Docker, the registry, Postgres and the health probe are
2674
+ * injected, so the rules are asserted without a daemon; the defaults are the
2675
+ * real ones.
2676
+ */
2677
+ /** `--push` without `--build`: there is nothing built here to push. */
2678
+ var ComposePushNeedsBuild = class extends GkmError {
2679
+ constructor() {
2680
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
2681
+ this.name = "ComposePushNeedsBuild";
2682
+ }
2683
+ };
2684
+ /** Digests to run by, on a run that pulls nothing. */
2685
+ var ComposePinNeedsPull = class extends GkmError {
2686
+ constructor() {
2687
+ super("--digests-file pins the images a release pulls, so it needs --tag (or --pull) — or, with --build --push, it is where the pushed digests are written.");
2688
+ this.name = "ComposePinNeedsPull";
2689
+ }
2690
+ };
2691
+ /** A port variable that does not hold a port. */
2692
+ var EdgePortInvalid = class extends GkmError {
2693
+ variable;
2694
+ value;
2695
+ constructor(variable, value) {
2696
+ super(`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`);
2697
+ this.variable = variable;
2698
+ this.value = value;
2699
+ this.name = "EdgePortInvalid";
2700
+ }
2701
+ };
2702
+ /** A build with no commit to tag its images with. */
2703
+ var NoGitRevision = class extends GkmError {
2704
+ root;
2705
+ constructor(root) {
2706
+ super(`Images built here are tagged with the commit they were built from, and ${root} is not in a git repository with a commit. Commit, or pass --tag to name the images yourself.`);
2707
+ this.root = root;
2708
+ this.name = "NoGitRevision";
2709
+ }
2710
+ };
2711
+ /**
2712
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
2713
+ * at the workspace root. What the generated file cannot know — a port bound
2714
+ * to a tailnet address, another log driver — goes there, and is never
2715
+ * overwritten.
2716
+ */
2717
+ function stackOverrideFile(root, stage) {
2718
+ return join(root, `docker-compose.${stage}.yml`);
2719
+ }
2720
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
2721
+ async function gitRevision(root) {
2722
+ let sha;
2723
+ try {
2724
+ sha = (await runOutput("git", [
2725
+ "rev-parse",
2726
+ "--short",
2727
+ "HEAD"
2728
+ ], { cwd: root })).trim();
2729
+ } catch {
2730
+ throw new NoGitRevision(root);
2731
+ }
2732
+ if (!sha) throw new NoGitRevision(root);
2733
+ return (await runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
2734
+ }
2735
+ /** The edge's ports, from the environment — 443 and 80 when unset. */
2736
+ function edgePorts(env = process.env) {
2737
+ const read = (variable, fallback) => {
2738
+ const value = env[variable];
2739
+ if (value === void 0 || value === "") return fallback;
2740
+ const port = Number(value);
2741
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new EdgePortInvalid(variable, value);
2742
+ return port;
2743
+ };
2744
+ const logs = env["GKM_COMPOSE_LOGS_PORT"] ? read(LOGS_PORT_ENV, 0) : void 0;
2745
+ return {
2746
+ https: read(EDGE_PORT_ENV.https, 443),
2747
+ http: read(EDGE_PORT_ENV.http, 80),
2748
+ ...logs ? { logs } : {}
2749
+ };
2750
+ }
2751
+ /**
2752
+ * The real ones. Each app is asked for three minutes before it counts as
2753
+ * down: a deployed stage's first ACME certificate can take that long.
2754
+ */
2755
+ const defaultDeps = {
2756
+ docker: dockerCompose,
2757
+ revision: gitRevision,
2758
+ sql: pgClient,
2759
+ buckets: bucketClient,
2760
+ logins: ensurePostgresLogin,
2761
+ migrate: migrateDatabases,
2762
+ seed: seedDatabases,
2763
+ probe: httpsProbe,
2764
+ healthAttempts: 90,
2765
+ healthIntervalMs: 2e3,
2766
+ env: process.env,
2767
+ lookup: systemLookup,
2768
+ server: sshAccess
2769
+ };
2770
+ /**
2771
+ * The stack the stage would run, and — for a tag — the registry's word that
2772
+ * every image it names exists. Nothing is written: a missing image stops the
2773
+ * run here, before a file, a secret or a container is touched.
2774
+ */
2775
+ async function validateCompose(ctx, deps, options = {}) {
2776
+ const { workspace, stage, identity, tag } = ctx;
2777
+ const root = workspace.root;
2778
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
2779
+ const push = options.push === true;
2780
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
2781
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
2782
+ const registry = workspace.deploy?.registry;
2783
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, tag));
2784
+ const runnables = {};
2785
+ const background = {};
2786
+ const subscribers = {};
2787
+ const manifest = await discover({
2788
+ patterns: constructGlobs(workspace),
2789
+ cwd: root,
2790
+ runnables,
2791
+ background,
2792
+ subscribers
2793
+ });
2794
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
2795
+ const recorded = push ? void 0 : await ctx.state.read(stage);
2796
+ const layout = mode === "build" ? imageLayout(workspace) : void 0;
2797
+ const input = {
2798
+ workspace,
2799
+ manifest,
2800
+ runnables,
2801
+ background,
2802
+ subscribers,
2803
+ stage,
2804
+ identity,
2805
+ images: {
2806
+ mode,
2807
+ tag,
2808
+ ...registry ? { registry } : {}
2809
+ },
2810
+ secrets,
2811
+ ...stage === workspace.stages.local ? { localCredentials: (await loadLocalCredentials(workspace)).credentials } : {},
2812
+ allowDevServices: ctx.allowDevServices,
2813
+ ports: edgePorts(deps.env),
2814
+ ...layout ? { layout } : {},
2815
+ ...push ? { buildOnly: true } : {}
2816
+ };
2817
+ const recordedArns = recordedPushSubscriptions(recorded?.resources);
2818
+ const planned = push ? void 0 : composeStack({
2819
+ ...input,
2820
+ recordingSubscriptions: true
2821
+ });
2822
+ const pushes = planned ? topicPushes(planned, manifest) : [];
2823
+ const topics = planned && (pushes.length > 0 || recordedTopicSubscriptions(recorded?.resources).length > 0) ? {
2824
+ pushes,
2825
+ recorded: recorded?.resources
2826
+ } : void 0;
2827
+ const composed = topics && planned ? planned : composeStack({
2828
+ ...input,
2829
+ pushSubscriptions: recordedArns
2830
+ });
2831
+ if (mode === "build") assertRedisClient(workspace, composed, manifest, runnables);
2832
+ const pinned = (unpinned) => options.pin ? withPinnedImages(unpinned, options.pin.file, options.pin.digests) : unpinned;
2833
+ const stack = pinned(composed);
2834
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, tag, [
2835
+ ...stack.apps,
2836
+ ...stack.workers,
2837
+ ...stack.processors
2838
+ ]);
2839
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
2840
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
2841
+ ctx.secrets.mask(stack.logs.password);
2842
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
2843
+ }
2844
+ if (!push && !stack.local) requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
2845
+ const server = push ? void 0 : composeServer({
2846
+ stage,
2847
+ local: stack.local,
2848
+ config: workspace.deploy?.compose?.server,
2849
+ custom: secrets?.custom
2850
+ });
2851
+ const dir = join(root, stackDir(stage));
2852
+ const override = stackOverrideFile(root, stage);
2853
+ const overrides = existsSync(override) ? [override] : [];
2854
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
2855
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
2856
+ const { ref, tag, digest } = releases.current;
2857
+ return [name, {
2858
+ ref,
2859
+ ...tag ? { tag } : {},
2860
+ ...digest ? { digest } : {}
2861
+ }];
2862
+ }));
2863
+ return {
2864
+ mode,
2865
+ push,
2866
+ stack,
2867
+ ...topics ? { topicSubscriptions: {
2868
+ ...topics,
2869
+ restack: (arns) => {
2870
+ const merged = { ...recordedArns };
2871
+ for (const [worker, own] of Object.entries(arns)) merged[worker] = {
2872
+ ...merged[worker],
2873
+ ...own
2874
+ };
2875
+ return pinned(composeStack({
2876
+ ...input,
2877
+ pushSubscriptions: merged
2878
+ }));
2879
+ }
2880
+ } } : {},
2881
+ ...server ? { server } : {},
2882
+ dir,
2883
+ ref: {
2884
+ project: composeProject(identity),
2885
+ file: join(dir, "docker-compose.yml"),
2886
+ ...overrides.length > 0 ? { overrides } : {},
2887
+ cwd: root,
2888
+ ...server ? { host: dockerHost(server) } : {},
2889
+ output: ctx.childOutput,
2890
+ signal: ctx.signal
2891
+ },
2892
+ secrets,
2893
+ generated,
2894
+ previous,
2895
+ files: [],
2896
+ images: {},
2897
+ changes: []
2898
+ };
2899
+ }
2900
+ /**
2901
+ * What only a compose deploy checks before it changes anything, once the
2902
+ * stage's own keys are: the stage's own certificate is there, and every
2903
+ * public host points at the stage's server — its records written where a
2904
+ * provider holds them, then confirmed — before Caddy or Traefik ask Let's
2905
+ * Encrypt for a certificate it could not issue. A build-only run never asks.
2906
+ */
2907
+ async function readyCompose(ctx, run, deps) {
2908
+ const { stack } = run;
2909
+ if (stack.tls) {
2910
+ for (const file of [stack.tls.certFile, stack.tls.keyFile]) if (!existsSync(file)) throw new ComposeTlsFileMissing(ctx.stage, file);
2911
+ }
2912
+ if (stack.local) return;
2913
+ if (run.server && !ctx.dryRun && !run.push) await deps.server.check(run.server);
2914
+ const prune = await stageHostsDns(ctx, deps, stackHosts(stack).filter((host) => !isLocalHost(host)), run.secrets?.custom);
2915
+ if (prune) run.pruneDns = prune;
2916
+ }
2917
+ /** A stack whose caches are in Redis, built for an app that has no client. */
2918
+ var RedisClientMissing = class extends GkmError {
2919
+ apps;
2920
+ constructor(apps) {
2921
+ super(`The stack keeps every cache in Redis, and ${apps.join(", ")} ${apps.length === 1 ? "does" : "do"} not depend on ioredis, the client the generated server reaches it with. Add it to the workspace: pnpm add ioredis`);
2922
+ this.apps = apps;
2923
+ this.name = "RedisClientMissing";
2924
+ }
2925
+ };
2926
+ /**
2927
+ * Every backend and worker image whose process reaches a cache can resolve
2928
+ * `ioredis` — listed by its app or a directory above it, the way Node and
2929
+ * the image's install find it. A process that reaches no cache registers no
2930
+ * cache driver, so it needs no client.
2931
+ */
2932
+ function assertRedisClient(workspace, stack, manifest, runnables) {
2933
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
2934
+ const cacheKeys = Object.values(manifest).filter((d) => d.kind === "cache").flatMap((d) => d.provides ?? []);
2935
+ const reachesCache = (keys) => cacheKeys.some((key) => keys?.has(key));
2936
+ const missing = [.../* @__PURE__ */ new Set([...stack.apps.filter((app) => (app.kind === "rest-api" || app.kind === "websocket-api") && reachesCache(appEnvKeys(manifest, app.name, runnables))).map((a) => a.name), ...stack.workers.filter((worker) => reachesCache(workerEnvKeys(manifest, worker.id, runnables))).map((worker) => worker.host)])].filter((name) => {
2937
+ const app = workspace.apps[name];
2938
+ return app && !installedFrom(join(workspace.root, app.path), "ioredis");
2939
+ }).sort();
2940
+ if (missing.length > 0) throw new RedisClientMissing(missing);
2941
+ }
2942
+ /**
2943
+ * The deploy's DNS step, for a deployed stage: its server's address — required
2944
+ * where it serves a real domain — then its own hosts written through each
2945
+ * domain's provider in `dns` where they differ, read back from it, and
2946
+ * recorded in the stage's state; hosts no provider writes resolved with the
2947
+ * system resolver. A dry run prints the plan and writes nothing, and warns
2948
+ * rather than stops. Returns the prune of the records gkm wrote for hosts the
2949
+ * stage no longer serves — which a dry run prints there and then.
2950
+ *
2951
+ * @throws {ServerAddressMissing} when the stage has a domain and no address
2952
+ * @throws {ServerAddressInvalid} for a value that is not an address
2953
+ * @throws {HostNotPointingAtServer} when a host is not the server
2954
+ */
2955
+ async function stageHostsDns(ctx, deps, hosts, custom) {
2956
+ const { workspace, stage } = ctx;
2957
+ const server = requiredServerAddress(stage, workspace.domains?.[stage], custom);
2958
+ if (hosts.length === 0) return;
2959
+ if (ctx.skipDns) {
2960
+ ctx.logger.info("🌐 DNS skipped (--skip-dns): no record is written or checked");
2961
+ return;
2962
+ }
2963
+ if (!server) {
2964
+ ctx.logger.info(`🌐 DNS skipped: no ${SERVER_IPV4_KEY} in '${stage}''s secrets — ${serverAddressHint(stage)}`);
2965
+ return;
2966
+ }
2967
+ const log = (line) => ctx.logger.info(line);
2968
+ if (workspace.dns) log(`🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${ctx.dryRun ? " (dry run — nothing is written)" : ""}`);
2969
+ try {
2970
+ const stored = await ctx.state.read(stage);
2971
+ const result = await stageDns({
2972
+ stage,
2973
+ hosts,
2974
+ server,
2975
+ dns: workspace.dns,
2976
+ recorded: dnsResources(stored?.resources ?? {}),
2977
+ credentials: ctx.credentials,
2978
+ log,
2979
+ lookup: deps.lookup ?? systemLookup,
2980
+ ...ctx.dryRun ? { dryRun: true } : {},
2981
+ ...deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}
2982
+ });
2983
+ if (!ctx.dryRun) {
2984
+ const journal = await DeployJournal.open(ctx.state, stage, () => createComposeState(stage));
2985
+ const providers = new Map(result.plan.domains.map((d) => [d.domain, d.provider]));
2986
+ await recordDnsChanges(journal, result.changes, (domain) => providers.get(domain));
2987
+ }
2988
+ const parts = [result.confirmed.length > 0 ? `${result.confirmed.length} host${result.confirmed.length === 1 ? "" : "s"} confirmed by the DNS provider` : "", result.resolved.length > 0 ? `${result.resolved.length} host${result.resolved.length === 1 ? "" : "s"} resolve${result.resolved.length === 1 ? "s" : ""} to ${server.ipv4}` : ""].filter(Boolean);
2989
+ if (parts.length > 0) log(`🌐 ${parts.join(", ")}`);
2990
+ if (ctx.dryRun) {
2991
+ await result.prune();
2992
+ return;
2993
+ }
2994
+ return result.recorded.stale.length > 0 ? result.prune : void 0;
2995
+ } catch (error) {
2996
+ if (ctx.dryRun && error instanceof HostNotPointingAtServer) {
2997
+ ctx.logger.warn(`⚠ ${error.message}`);
2998
+ return;
2999
+ }
3000
+ throw error;
3001
+ }
3002
+ }
3003
+ /**
3004
+ * The records gkm wrote for hosts the stage no longer serves, deleted once it
3005
+ * answers on its new ones — and forgotten from its state, deleted or not:
3006
+ * none is gkm's to manage any more.
3007
+ */
3008
+ async function pruneStageDns(ctx, run) {
3009
+ if (!run.pruneDns) return;
3010
+ const pruned = await run.pruneDns();
3011
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
3012
+ for (const { record } of pruned) await forgetDnsResource(journal, record);
3013
+ const deleted = pruned.filter((p) => p.action === "delete").length;
3014
+ if (deleted > 0) ctx.logger.info(`🌐 ${deleted} record${deleted === 1 ? "" : "s"} deleted`);
3015
+ }
3016
+ /**
3017
+ * The stage's secrets — and, for a deployed stage, everything it generates
3018
+ * once: its seed, and each declared secret and keyring. Kept only once the
3019
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
3020
+ * leaves the stage's secrets as it found them.
3021
+ */
3022
+ async function stageSecrets(ctx, manifest) {
3023
+ const stored = await ctx.secrets.read();
3024
+ if (ctx.stage === ctx.workspace.stages.local) return {
3025
+ secrets: stored,
3026
+ generated: []
3027
+ };
3028
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
3029
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
3030
+ for (const [key, value] of Object.entries(secrets.custom ?? {})) if (!isReservedStageKey(key)) ctx.secrets.mask(value);
3031
+ return {
3032
+ secrets,
3033
+ generated
3034
+ };
3035
+ }
3036
+ /**
3037
+ * The stack with each app's and worker's image pinned to the digest the file
3038
+ * names: the refs it is checked, pulled and recorded by, and the image each
3039
+ * compose service runs.
3040
+ */
3041
+ function withPinnedImages(stack, file, digests) {
3042
+ const apps = pinImages(file, digests, stack.apps);
3043
+ const workers = pinImages(file, digests, stack.workers);
3044
+ const processors = pinImages(file, digests, stack.processors);
3045
+ const services = { ...stack.compose.services };
3046
+ for (const image of [
3047
+ ...apps,
3048
+ ...workers,
3049
+ ...processors
3050
+ ]) services[image.name] = {
3051
+ ...services[image.name],
3052
+ image: image.ref
3053
+ };
3054
+ return {
3055
+ ...stack,
3056
+ apps,
3057
+ workers,
3058
+ processors,
3059
+ compose: {
3060
+ ...stack.compose,
3061
+ services
3062
+ }
3063
+ };
3064
+ }
3065
+ /**
3066
+ * A dry run: the stack's files, written so they can be read, and what a real
3067
+ * run would do — no image is built or pulled, no container touched, nothing
3068
+ * recorded and no secret kept.
3069
+ */
3070
+ async function planCompose(ctx, run) {
3071
+ if (run.generated.length > 0) ctx.logger.info(`🔑 "${ctx.stage}" has no ${run.generated.join(", ")} yet; this dry run used values it did not keep.`);
3072
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack);
3073
+ printPlan(ctx, run);
3074
+ if (!run.push && run.stack.infra.includes("postgres")) reportPlannedSeeds((await plannedSeeds({
3075
+ root: ctx.workspace.root,
3076
+ manifest: ctx.manifest
3077
+ })).map(({ target, seeds }) => ({
3078
+ folder: target.seeds,
3079
+ seeds
3080
+ })), (line) => ctx.logger.info(line));
3081
+ const planned = (change) => {
3082
+ run.changes.push(change);
3083
+ ctx.emit({
3084
+ type: "resource.planned",
3085
+ ...change
3086
+ });
3087
+ };
3088
+ for (const service of run.push ? [] : run.stack.infra) planned({
3089
+ key: `service:${service}`,
3090
+ resourceType: "service",
3091
+ action: "ensure"
3092
+ });
3093
+ for (const app of run.stack.apps) {
3094
+ planned({
3095
+ key: `image:${app.name}`,
3096
+ resourceType: "image",
3097
+ action: run.mode === "build" ? "build" : "reuse",
3098
+ id: app.ref
3099
+ });
3100
+ if (run.push) continue;
3101
+ planned({
3102
+ key: `service:${app.name}`,
3103
+ resourceType: "service",
3104
+ action: run.previous[app.name] ? "reuse" : "create"
3105
+ });
3106
+ }
3107
+ for (const worker of [...run.stack.workers, ...run.stack.processors]) {
3108
+ planned({
3109
+ key: `image:${worker.name}`,
3110
+ resourceType: "image",
3111
+ action: run.mode === "build" ? "build" : "reuse",
3112
+ id: worker.ref
3113
+ });
3114
+ if (run.push) continue;
3115
+ planned({
3116
+ key: `service:${worker.name}`,
3117
+ resourceType: "service",
3118
+ action: run.previous[worker.name] ? "reuse" : "create"
3119
+ });
3120
+ }
3121
+ for (const push of run.topicSubscriptions?.pushes ?? []) {
3122
+ const key = subscriptionKey(push.worker, push.name);
3123
+ const id = run.topicSubscriptions?.recorded?.[key]?.id;
3124
+ planned({
3125
+ key,
3126
+ resourceType: SUBSCRIPTION_TYPE,
3127
+ action: id ? "reuse" : "create",
3128
+ ...id ? { id } : {}
3129
+ });
3130
+ }
3131
+ if (!run.push) planned({
3132
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
3133
+ resourceType: "service",
3134
+ action: "ensure"
3135
+ });
3136
+ }
3137
+ /**
3138
+ * What the apps run on: the stage's generated secrets kept, the stack's files
3139
+ * written, its infrastructure started, and its databases, roles, grants and
3140
+ * migrations applied.
3141
+ */
3142
+ async function provisionCompose(ctx, run, deps) {
3143
+ const { ref } = run;
3144
+ if (run.push) return;
3145
+ if (run.generated.length > 0 && run.secrets) {
3146
+ await ctx.secrets.write(run.secrets);
3147
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
3148
+ }
3149
+ const ports = edgePorts(deps.env);
3150
+ await assertEdgePorts(deps.docker, {
3151
+ project: run.stack.project,
3152
+ proxy: run.stack.proxy,
3153
+ ports,
3154
+ engine: ref
3155
+ });
3156
+ if (run.topicSubscriptions) await subscribeTopics(ctx, run, deps);
3157
+ const { stack } = run;
3158
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
3159
+ printPlan(ctx, run);
3160
+ if (stack.proxy === "traefik") {
3161
+ ctx.logger.info(`\n🌐 Starting the shared edge (${EDGE_PROJECT})…`);
3162
+ run.files.push(...await ensureEdge(deps.docker, {
3163
+ file: edgeFile(run),
3164
+ ports,
3165
+ ...ref.host ? { host: ref.host } : {},
3166
+ logging: {
3167
+ driver: LOG_ROTATION.driver,
3168
+ options: { ...LOG_ROTATION.options }
3169
+ },
3170
+ ...ref.output ? { output: ref.output } : {},
3171
+ ...ref.signal ? { signal: ref.signal } : {}
3172
+ }));
3173
+ applied(ctx, run, {
3174
+ key: `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
3175
+ resourceType: "service",
3176
+ action: "ensure",
3177
+ id: `${EDGE_PROJECT}/${EDGE_SERVICE}`,
3178
+ via: "found"
3179
+ });
3180
+ }
3181
+ if (stack.infra.length > 0) {
3182
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
3183
+ await deps.docker.up(ref, stack.infra);
3184
+ for (const service of stack.infra) applied(ctx, run, {
3185
+ key: `service:${service}`,
3186
+ resourceType: "service",
3187
+ action: "ensure",
3188
+ id: `${stack.project}/${service}`,
3189
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
3190
+ });
3191
+ }
3192
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
3193
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
3194
+ }
3195
+ /**
3196
+ * Subscribe each topic subscriber SNS pushes to — for a topic the stage set
3197
+ * to SNS by hand — record the ARNs, and compose the stack again with them,
3198
+ * before a file is written.
3199
+ */
3200
+ async function subscribeTopics(ctx, run, deps) {
3201
+ const { pushes, recorded, restack } = run.topicSubscriptions;
3202
+ if (pushes.length > 0) ctx.logger.info("\n📮 SNS subscriptions for the stage's own topics");
3203
+ run.stack = restack(await ensureTopicSubscriptions({
3204
+ pushes,
3205
+ recorded,
3206
+ secrets: run.secrets?.custom ?? {},
3207
+ stage: ctx.stage,
3208
+ env: deps.env,
3209
+ record: async (resource) => {
3210
+ await ctx.state.putResource(ctx.stage, resource);
3211
+ applied(ctx, run, {
3212
+ key: resource.key,
3213
+ resourceType: SUBSCRIPTION_TYPE,
3214
+ action: "ensure",
3215
+ id: resource.id,
3216
+ via: recorded?.[resource.key]?.id === resource.id ? "recorded" : "created"
3217
+ });
3218
+ },
3219
+ forget: async (key) => {
3220
+ await ctx.state.deleteResource(ctx.stage, key);
3221
+ },
3222
+ log: (line) => ctx.logger.info(line)
3223
+ }));
3224
+ }
3225
+ /**
3226
+ * Create each bucket the stack's MinIO serves, and the open paths of each
3227
+ * one a file server fronts — from this machine, on MinIO's loopback port,
3228
+ * the way `gkm dev` creates them.
3229
+ */
3230
+ async function prepareBuckets(ctx, run, deps) {
3231
+ const storage = run.stack.storage;
3232
+ if (storage.buckets.length === 0) return;
3233
+ const tunnel = await reach(run, deps, "minio", 9e3);
3234
+ let done;
3235
+ try {
3236
+ const client = deps.buckets(tunnel.port, storage);
3237
+ done = [
3238
+ ...await applyBuckets(client, storage.buckets),
3239
+ ...await applyPolicies(client, storage.policies),
3240
+ ...await applyLifecycles(client, storage.lifecycles),
3241
+ ...await applyNotifications(client, storage.objects, new Set(storage.webhooks.map((hook) => hook.bucket)))
3242
+ ];
3243
+ } finally {
3244
+ await tunnel.close();
3245
+ }
3246
+ const created = done.filter((entry) => entry.created).length;
3247
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
3248
+ }
3249
+ /**
3250
+ * Create what the plan names in the stack's Postgres, migrate it, then run
3251
+ * its seeds — every one, every time, as each construct's owner.
3252
+ */
3253
+ async function prepareDatabases(ctx, run, deps) {
3254
+ const tunnel = await reach(run, deps, "postgres", 5432);
3255
+ try {
3256
+ await migrateAndSeed(ctx, run, deps, tunnel.port);
3257
+ } finally {
3258
+ await tunnel.close();
3259
+ }
3260
+ }
3261
+ /**
3262
+ * A port a stack's service publishes on its engine's loopback, reachable
3263
+ * from this machine: the published port itself on the local stage, and on a
3264
+ * server an SSH tunnel to it over the deploy's own login — so Postgres and
3265
+ * MinIO are never published beyond the server's loopback.
3266
+ *
3267
+ * Migrations and seeds run here, in this process, with the project's own
3268
+ * Kysely — the way `gkm migrate` runs them — through that port. No image
3269
+ * needs to carry them, and nothing is run on the server but the stack.
3270
+ */
3271
+ async function reach(run, deps, service, inside) {
3272
+ const published = await deps.docker.port(run.ref, service, inside);
3273
+ if (!run.server) return {
3274
+ port: published,
3275
+ close: async () => {}
3276
+ };
3277
+ return deps.server.tunnel(run.server, published);
3278
+ }
3279
+ async function migrateAndSeed(ctx, run, deps, port) {
3280
+ const { stack } = run;
3281
+ const workspace = ctx.workspace;
3282
+ const superuser = stack.credential.containers.postgres;
3283
+ const login = await deps.logins({
3284
+ port,
3285
+ login: superuser,
3286
+ legacy: [{
3287
+ user: LEGACY_LOCAL_LOGIN.user,
3288
+ password: superuser.password
3289
+ }, ...stack.local ? [LEGACY_LOCAL_LOGIN] : []]
3290
+ });
3291
+ if (login.notice) ctx.logger.info(login.notice);
3292
+ const statements = [...postgresStatements(stack.plan, workspace.name, stack.credential.seed), ...stack.backups ? backupsRoleStatements(stack.backups) : []];
3293
+ if (statements.length > 0) {
3294
+ ctx.logger.info("🗄️ Creating databases, roles and grants…");
3295
+ await applyPostgres(deps.sql(port, login.login), statements);
3296
+ }
3297
+ const sources = {};
3298
+ const manifest = await discover({
3299
+ patterns: constructGlobs(workspace),
3300
+ cwd: workspace.root,
3301
+ sources
3302
+ });
3303
+ const env = envFor(stack.plan, {
3304
+ ports: { [primaryPortKey("postgres")]: port },
3305
+ project: workspace.name,
3306
+ credentials: {
3307
+ ...stack.credential.containers,
3308
+ postgres: login.login
3309
+ },
3310
+ seed: stack.credential.seed
3311
+ });
3312
+ const options = {
3313
+ root: workspace.root,
3314
+ manifest,
3315
+ sources,
3316
+ env
3317
+ };
3318
+ const runs = await deps.migrate(options);
3319
+ const seeds = await deps.seed({
3320
+ ...options,
3321
+ stage: ctx.stage,
3322
+ backends: backendsOf(workspace)
3323
+ }).catch((error) => {
3324
+ if (error instanceof SeedFailed) throw new DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
3325
+ throw error;
3326
+ });
3327
+ reportDatabaseRuns(runs.map(({ target, applied }) => ({
3328
+ construct: target.id,
3329
+ folder: target.migrations,
3330
+ applied
3331
+ })), seeds.map(({ target, seeded }) => ({
3332
+ construct: target.id,
3333
+ folder: target.seeds,
3334
+ seeded
3335
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
3336
+ }
3337
+ /**
3338
+ * Each app's image: built from this checkout — inside Docker, every one of
3339
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
3340
+ * live changes.
3341
+ */
3342
+ async function buildCompose(ctx, run, deps) {
3343
+ const { stack, ref } = run;
3344
+ const images = [
3345
+ ...stack.apps,
3346
+ ...stack.workers,
3347
+ ...stack.processors
3348
+ ];
3349
+ const apps = images.map((image) => image.app);
3350
+ if (run.push) {
3351
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
3352
+ printPlan(ctx, run);
3353
+ }
3354
+ if (run.mode === "build") {
3355
+ ctx.logger.info("\n🐳 Building images…");
3356
+ await deps.docker.build(ref, apps);
3357
+ } else {
3358
+ ctx.logger.info(`\n🐳 Pulling ${ctx.tag}…`);
3359
+ await deps.docker.pull(ref, apps);
3360
+ }
3361
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
3362
+ for (const image of images) {
3363
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(ref, image.ref);
3364
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
3365
+ run.images[image.app] = {
3366
+ ref: image.ref,
3367
+ tag: image.tag,
3368
+ ...digest ? { digest } : {}
3369
+ };
3370
+ ctx.emit({
3371
+ type: "artifact.built",
3372
+ app: image.app,
3373
+ imageRef: image.ref,
3374
+ ...digest ? { digest } : {}
3375
+ });
3376
+ run.changes.push({
3377
+ key: `image:${image.app}`,
3378
+ resourceType: "image",
3379
+ action: run.mode === "build" ? "build" : "reuse",
3380
+ id: digest ?? image.ref
3381
+ });
3382
+ }
3383
+ }
3384
+ /**
3385
+ * The whole stack up — anything it no longer defines removed — and each
3386
+ * app's image recorded in the stage's state.
3387
+ */
3388
+ async function releaseCompose(ctx, run, deps) {
3389
+ const { stack, ref } = run;
3390
+ if (run.push) return;
3391
+ ctx.logger.info("\n🚀 Starting the stack…");
3392
+ await deps.docker.up(ref);
3393
+ const edge = edgeRef(edgeFile(run), {
3394
+ ...ref.host ? { host: ref.host } : {},
3395
+ ...ref.output ? { output: ref.output } : {}
3396
+ });
3397
+ if (stack.proxy === "traefik" && stack.traefik) {
3398
+ const written = await writeEdgeRoutes(deps.docker, edge, stack.project, stack.traefik, stack.tls);
3399
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${EDGE_PROJECT}: ${written.at(-1)}`);
3400
+ } else if (!stack.local) await removeEdgeRoutes(deps.docker, edge, stack.project);
3401
+ if (stack.local) await deps.docker.copyOut(ref, "caddy", "/data/caddy/pki/authorities/local/root.crt", caFile(run)).catch(() => {});
3402
+ await recordImages(ctx, run);
3403
+ for (const app of stack.apps) {
3404
+ const image = run.images[app.name];
3405
+ applied(ctx, run, {
3406
+ key: `service:${app.name}`,
3407
+ resourceType: "service",
3408
+ action: "ensure",
3409
+ id: `${stack.project}/${app.name}`,
3410
+ via: run.previous[app.name] ? "recorded" : "created"
3411
+ });
3412
+ ctx.emit({
3413
+ type: "app.deployed",
3414
+ app: app.name,
3415
+ applicationId: `${stack.project}/${app.name}`,
3416
+ imageRef: image?.ref ?? app.ref,
3417
+ url: app.url
3418
+ });
3419
+ }
3420
+ for (const worker of [...stack.workers, ...stack.processors]) applied(ctx, run, {
3421
+ key: `service:${worker.name}`,
3422
+ resourceType: "service",
3423
+ action: "ensure",
3424
+ id: `${stack.project}/${worker.name}`,
3425
+ via: run.previous[worker.name] ? "recorded" : "created"
3426
+ });
3427
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
3428
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url}${app.auth ? ` 🔒 user: ${app.auth.user}, password: gkm secrets:show --stage ${ctx.stage} --reveal → ${app.auth.key}` : ""}`);
3429
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
3430
+ for (const unit of stack.processors) ctx.logger.info(` ${unit.name.padEnd(12)} processors of ${unit.id}`);
3431
+ if (stack.local) ctx.logger.info(`\n🔐 Certificates are from Caddy's local CA: NODE_EXTRA_CA_CERTS=${join(stackDir(ctx.stage), "caddy-root.crt")}`);
3432
+ }
3433
+ /**
3434
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
3435
+ * records: the ref it runs, the tag it was released under, and the digest
3436
+ * the tag resolved to.
3437
+ */
3438
+ async function recordImages(ctx, run) {
3439
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
3440
+ const by = currentActor();
3441
+ for (const app of [
3442
+ ...run.stack.apps,
3443
+ ...run.stack.workers,
3444
+ ...run.stack.processors
3445
+ ]) {
3446
+ const image = run.images[app.app] ?? {
3447
+ ref: app.ref,
3448
+ tag: app.tag
3449
+ };
3450
+ recordRelease(journal.state, app.app, image, by);
3451
+ }
3452
+ journal.state.identity = ctx.identity.key;
3453
+ await journal.save();
3454
+ }
3455
+ /**
3456
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
3457
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
3458
+ * its certificates are Caddy's internal CA's, so the CA `release` copied out
3459
+ * is the one trusted and the request goes to 127.0.0.1.
3460
+ */
3461
+ async function verifyCompose(ctx, run, deps) {
3462
+ const { stack } = run;
3463
+ if (run.push) return;
3464
+ const ca = stack.local ? await readFile(caFile(run), "utf-8").catch(() => void 0) : void 0;
3465
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
3466
+ const edge = stack.local ? { connectTo: "127.0.0.1" } : run.server ? {
3467
+ connectTo: run.server.host,
3468
+ connectPort: edgePorts(deps.env).https
3469
+ } : void 0;
3470
+ const results = await Promise.all(stack.apps.map((app) => checkApp(ctx, app, deps, {
3471
+ ca,
3472
+ edge
3473
+ })));
3474
+ results.push(...await Promise.all([...stack.workers, ...stack.processors].map((worker) => checkContainer(ctx, run, deps, worker.name))));
3475
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, LOGS_SERVICE));
3476
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
3477
+ app,
3478
+ url,
3479
+ last
3480
+ }));
3481
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
3482
+ await pruneStageDns(ctx, run);
3483
+ await confirmSubscriptions(ctx, run, deps);
3484
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local, run.server);
3485
+ }
3486
+ /**
3487
+ * The SNS subscriptions the stage's providers made before the workers were
3488
+ * up: each still pending is subscribed again, so SNS resends its
3489
+ * confirmation to a worker now there to answer it, and waited on. One still
3490
+ * pending after that is said, not failed on — every app is healthy, and
3491
+ * rolling them back would not confirm it.
3492
+ */
3493
+ async function confirmSubscriptions(ctx, run, deps) {
3494
+ const stored = await ctx.state.read(ctx.stage);
3495
+ const left = await (deps.confirmSubscriptions ?? confirmPendingSubscriptions)({
3496
+ workspace: ctx.workspace,
3497
+ stage: ctx.stage,
3498
+ secrets: run.secrets?.custom ?? {},
3499
+ resources: stored?.resources,
3500
+ env: deps.env,
3501
+ log: (line) => ctx.logger.info(line),
3502
+ record: async (record) => {
3503
+ const { updatedAt: _, updatedBy: __, ...input } = record;
3504
+ await ctx.state.putResource(ctx.stage, input);
3505
+ }
3506
+ });
3507
+ if (left.length > 0) ctx.logger.warn(`⚠ ${new PushSubscriptionsUnconfirmed(left).message}`);
3508
+ }
3509
+ /**
3510
+ * A container's own health check, as Docker reports it: a worker's, which
3511
+ * has no route through the edge, and OpenObserve's — by default it has no
3512
+ * host there, and served publicly it answers only the addresses it allows,
3513
+ * which need not include this one.
3514
+ */
3515
+ async function checkContainer(ctx, run, deps, service) {
3516
+ const url = `docker:${service}`;
3517
+ let last = "not asked";
3518
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
3519
+ ctx.signal.throwIfAborted();
3520
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
3521
+ last = health ?? "not running";
3522
+ const healthy = health === "healthy";
3523
+ ctx.emit({
3524
+ type: "health.checked",
3525
+ app: service,
3526
+ url,
3527
+ healthy,
3528
+ attempt
3529
+ });
3530
+ if (healthy) {
3531
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
3532
+ return {
3533
+ app: service,
3534
+ url,
3535
+ last,
3536
+ healthy
3537
+ };
3538
+ }
3539
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
3540
+ }
3541
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
3542
+ return {
3543
+ app: service,
3544
+ url,
3545
+ last,
3546
+ healthy: false
3547
+ };
3548
+ }
3549
+ /** A login, as the `Authorization` header that carries it. */
3550
+ function basicAuthorization(auth) {
3551
+ return `Basic ${Buffer.from(`${auth.user}:${auth.password}`).toString("base64")}`;
3552
+ }
3553
+ /** How to open the logs, printed — and as an event, for a headless caller. */
3554
+ function reportLogs(ctx, logs, local, server) {
3555
+ const lines = logsAccess(logs, {
3556
+ stage: ctx.stage,
3557
+ local,
3558
+ user: server?.user ?? currentUser(),
3559
+ hostname: server?.host ?? hostname(),
3560
+ ...server ? { known: true } : {}
3561
+ });
3562
+ ctx.logger.info(`\n${lines.join("\n")}`);
3563
+ ctx.emit({
3564
+ type: "logs.ready",
3565
+ service: LOGS_SERVICE,
3566
+ access: logs.public ? "public" : "tunnel",
3567
+ url: logs.url,
3568
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
3569
+ email: logs.email
3570
+ });
3571
+ }
3572
+ /** This machine's user — a guess at who would SSH in. */
3573
+ function currentUser() {
3574
+ try {
3575
+ return userInfo().username;
3576
+ } catch {
3577
+ return process.env.USER ?? "user";
3578
+ }
3579
+ }
3580
+ async function checkApp(ctx, app, deps, options) {
3581
+ const url = `${app.url.replace(/^ws/, "http")}${app.kind === "site" ? "/" : "/health"}`;
3582
+ let last = "not asked";
3583
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
3584
+ ctx.signal.throwIfAborted();
3585
+ let status;
3586
+ try {
3587
+ status = await deps.probe({
3588
+ url,
3589
+ ...options.ca ? { ca: options.ca } : {},
3590
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
3591
+ ...options.edge,
3592
+ timeoutMs: 1e4,
3593
+ signal: ctx.signal
3594
+ });
3595
+ last = `HTTP ${status}`;
3596
+ } catch (error) {
3597
+ last = error instanceof Error ? error.message : String(error);
3598
+ }
3599
+ const healthy = status !== void 0 && isHealthy(status);
3600
+ ctx.emit({
3601
+ type: "health.checked",
3602
+ app: app.name,
3603
+ url,
3604
+ healthy,
3605
+ ...status !== void 0 ? { status } : {},
3606
+ attempt
3607
+ });
3608
+ if (healthy) {
3609
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
3610
+ return {
3611
+ app: app.name,
3612
+ url,
3613
+ last,
3614
+ healthy
3615
+ };
3616
+ }
3617
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
3618
+ }
3619
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
3620
+ return {
3621
+ app: app.name,
3622
+ url,
3623
+ last,
3624
+ healthy: false
3625
+ };
3626
+ }
3627
+ function composeResult(ctx, run) {
3628
+ const apps = [...run.stack.apps.map((app) => {
3629
+ const image = run.images[app.name];
3630
+ return {
3631
+ appName: app.name,
3632
+ type: app.kind === "site" ? "web" : "backend",
3633
+ success: !ctx.dryRun,
3634
+ applicationId: `${run.stack.project}/${app.name}`,
3635
+ imageRef: image?.ref ?? app.ref,
3636
+ ...image?.digest ? { digest: image.digest } : {},
3637
+ url: app.url
3638
+ };
3639
+ }), ...[...run.stack.workers, ...run.stack.processors].map((worker) => {
3640
+ const image = run.images[worker.name];
3641
+ return {
3642
+ appName: worker.name,
3643
+ type: "backend",
3644
+ success: !ctx.dryRun,
3645
+ applicationId: `${run.stack.project}/${worker.name}`,
3646
+ imageRef: image?.ref ?? worker.ref,
3647
+ ...image?.digest ? { digest: image.digest } : {}
3648
+ };
3649
+ })];
3650
+ return {
3651
+ apps,
3652
+ projectId: run.stack.project,
3653
+ successCount: ctx.dryRun ? 0 : apps.length,
3654
+ failedCount: 0,
3655
+ stage: ctx.stage,
3656
+ identity: ctx.identity.key,
3657
+ tag: ctx.tag,
3658
+ dryRun: ctx.dryRun,
3659
+ environmentId: "",
3660
+ skipped: [...ctx.skipped],
3661
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
3662
+ changes: run.changes
3663
+ };
3664
+ }
3665
+ function caFile(run) {
3666
+ return join(run.dir, "caddy-root.crt");
3667
+ }
3668
+ /** The shared edge's compose file, as this machine hands it to compose. */
3669
+ function edgeFile(run) {
3670
+ return join(run.dir, `${EDGE_PROJECT}.yml`);
3671
+ }
3672
+ function applied(ctx, run, change) {
3673
+ const { via, ...rest } = change;
3674
+ run.changes.push(rest);
3675
+ ctx.emit({
3676
+ type: "resource.applied",
3677
+ ...rest,
3678
+ via
3679
+ });
3680
+ }
3681
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
3682
+ async function writeStack(root, dir, stack) {
3683
+ await mkdir(dir, {
3684
+ recursive: true,
3685
+ mode: 448
3686
+ });
3687
+ await chmod(dir, 448);
3688
+ const files = [];
3689
+ const write = async (path, content, mode = 420) => {
3690
+ await mkdir(dirname(path), { recursive: true });
3691
+ await writeFile(path, content, { mode });
3692
+ await chmod(path, mode);
3693
+ files.push(path);
3694
+ };
3695
+ const tls = stack.proxy === "caddy" && stack.tls ? {
3696
+ cert: await readFile(stack.tls.certFile, "utf-8"),
3697
+ key: await readFile(stack.tls.keyFile, "utf-8")
3698
+ } : void 0;
3699
+ const compose = stack.caddyfile !== void 0 ? withCaddyConfigs(stack.compose, {
3700
+ caddyfile: stack.caddyfile,
3701
+ ...tls ? { tls } : {}
3702
+ }) : stack.compose;
3703
+ await write(join(dir, "docker-compose.yml"), composeYaml(stack, compose), tls ? 384 : 420);
3704
+ if (stack.caddyfile !== void 0) {
3705
+ await write(join(dir, "Caddyfile"), stack.caddyfile);
3706
+ await rm(join(dir, "traefik.yml"), { force: true });
3707
+ } else await rm(join(dir, "Caddyfile"), { force: true });
3708
+ if (stack.traefik !== void 0) await write(join(dir, "traefik.yml"), stack.traefik);
3709
+ await rm(join(dir, "tls"), {
3710
+ recursive: true,
3711
+ force: true
3712
+ });
3713
+ for (const app of [
3714
+ ...stack.apps,
3715
+ ...stack.workers,
3716
+ ...stack.processors
3717
+ ]) if (app.env) await write(join(dir, `${app.name}.env`), envFile(app.env), 384);
3718
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write(join(dir, `${LOGS_SERVICE}.env`), envFile(stack.logs.env), 384);
3719
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write(join(dir, `${REDIS_SERVICE}.env`), envFile(stack.redis.env), 384);
3720
+ if (stack.backups) {
3721
+ for (const [name, content] of Object.entries(stack.backups.files)) await write(join(dir, BACKUPS_SERVICE, name), content);
3722
+ if (stack.compose.services["backups"]?.env_file) await write(join(dir, `${BACKUPS_SERVICE}.env`), envFile(stack.backups.env), 384);
3723
+ } else {
3724
+ await rm(join(dir, BACKUPS_SERVICE), {
3725
+ recursive: true,
3726
+ force: true
3727
+ });
3728
+ await rm(join(dir, `${BACKUPS_SERVICE}.env`), { force: true });
3729
+ }
3730
+ for (const entry of await readdir(dir)) if (entry.endsWith(".credentials")) await rm(join(dir, entry));
3731
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write(join(root, path), content);
3732
+ await ensureDockerignore(findBuildRoot(root));
3733
+ return files;
3734
+ }
3735
+ function composeYaml(stack, compose) {
3736
+ const stage = ` --stage ${stack.stage}`;
3737
+ return `# Generated by gkm compose from the construct manifest — do not edit.
3738
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${EDGE_PROJECT})`}, and its workers.
3739
+ # Each backend and worker reads exactly the keys in its own env file beside
3740
+ # this one.
3741
+ #
3742
+ # gkm compose${stage} start or update it
3743
+ # gkm compose${stage} --down stop it
3744
+ ${stringify(compose, {
3745
+ lineWidth: 0,
3746
+ aliasDuplicateObjects: false
3747
+ })}`;
3748
+ }
3749
+ function printPlan(ctx, run) {
3750
+ const { stack, mode, files } = run;
3751
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
3752
+ if (run.server) ctx.logger.info(` → ${sshTarget(run.server)} (docker over ssh)`);
3753
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
3754
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
3755
+ for (const unit of stack.processors) ctx.logger.info(` ${unit.name.padEnd(12)} ${`processors of ${unit.id}`.padEnd(40)} ${mode} ${unit.ref}`);
3756
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
3757
+ if (stack.backups) ctx.logger.info(` ${BACKUPS_SERVICE.padEnd(12)} ${stack.backups.databases.map((d) => d.file).join(", ")} — ${stack.backups.backups.describe}, to ${stack.backups.prefix}/`);
3758
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${stackDir(stack.stage)}/`);
3759
+ }
3760
+ //#endregion
3761
+ //#region src/target/compose/index.ts
3762
+ /**
3763
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
3764
+ * Caddy — the local stage on the machine that runs the deploy, a deployed
3765
+ * stage on its server's Docker engine, over SSH (`deploy.compose.server`).
3766
+ *
3767
+ * ```bash
3768
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
3769
+ * gkm deploy --target compose --stage production # built from here
3770
+ * gkm deploy --target compose --stage development # the local stage
3771
+ * ```
3772
+ *
3773
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
3774
+ * looked up in the registry — `ImageTagNotFound` before anything changes
3775
+ * - `ready`: a deploy's own checks, after the stage's keys are — the stage's
3776
+ * certificate, its server's address, and every public host's DNS
3777
+ * - `plan`: the stack's files and what a run would create or reuse
3778
+ * - `provision`: generated secrets kept, files written, infrastructure up,
3779
+ * databases, roles, grants and migrations
3780
+ * - `build`: each backend bundled on the host and every image built — or, for
3781
+ * a tag, pulled
3782
+ * - `release`: `up --wait --remove-orphans`, and each app's image, tag and
3783
+ * digest in the stage's state
3784
+ * - `verify`: each app asked through Caddy over HTTPS
3785
+ *
3786
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
3787
+ * every image and pushes it to `deploy.registry`, and does nothing else: no
3788
+ * readiness check runs, so a stage whose keys the deploy has yet to write
3789
+ * still builds.
3790
+ *
3791
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
3792
+ * `--down`), run through the same `deploy()`.
3793
+ */
3794
+ var compose_exports = /* @__PURE__ */ __exportAll({ composeTarget: () => composeTarget });
3795
+ /** The compose target, with its Docker, bundler and probe as given. */
3796
+ function composeTarget(options = {}) {
3797
+ const { mode, push, pin, report, ...given } = options;
3798
+ const deps = {
3799
+ ...defaultDeps,
3800
+ ...given
3801
+ };
3802
+ return defineTarget({
3803
+ name: "compose",
3804
+ runtime: "server",
3805
+ capabilities: {
3806
+ rollback: false,
3807
+ migrations: "target",
3808
+ images: true,
3809
+ localStage: true,
3810
+ selfHostedTelemetry: true
3811
+ },
3812
+ credentials: [],
3813
+ tag: ({ cwd }) => deps.revision(cwd),
3814
+ validate: (ctx) => validateCompose(ctx, deps, {
3815
+ ...mode ? { mode } : {},
3816
+ ...push ? { push } : {},
3817
+ ...pin ? { pin } : {}
3818
+ }),
3819
+ ready: (ctx, run) => readyCompose(ctx, run, deps),
3820
+ plan: (ctx, run) => planCompose(ctx, run),
3821
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
3822
+ build: (ctx, run) => buildCompose(ctx, run, deps),
3823
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
3824
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
3825
+ result: (ctx, run) => {
3826
+ report?.(run);
3827
+ return composeResult(ctx, run);
3828
+ }
3829
+ });
3830
+ }
3831
+ //#endregion
3832
+ export { dockerCompose as C, sshTarget as S, parseDigests as _, edgePorts as a, dockerHost as b, edgeRef as c, composeStack as d, derivedCredentials as f, edgeAlias as g, EDGE_PROJECT as h, ComposePushNeedsBuild as i, removeEdgeRoutes as l, stackPlan as m, compose_exports as n, stackOverrideFile as o, stackDir as p, ComposePinNeedsPull as r, deployedStackSecrets as s, composeTarget as t, composeProject as u, pinnedRef as v, projectNetwork as w, sshAccess as x, composeServer as y };
3833
+
3834
+ //# sourceMappingURL=compose-CnanpQBB.mjs.map