@geekmidas/cli 10.0.0-alpha.19 → 10.0.0-alpha.190

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 (436) hide show
  1. package/README.md +323 -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-CBKH87_b.mjs +1043 -0
  7. package/dist/EndpointGenerator-CBKH87_b.mjs.map +1 -0
  8. package/dist/EndpointGenerator-iyA3HkOH.cjs +1102 -0
  9. package/dist/EndpointGenerator-iyA3HkOH.cjs.map +1 -0
  10. package/dist/LegacyStateStore-CWiswz6T.mjs +124 -0
  11. package/dist/LegacyStateStore-CWiswz6T.mjs.map +1 -0
  12. package/dist/LegacyStateStore-CuSe37fl.cjs +124 -0
  13. package/dist/LegacyStateStore-CuSe37fl.cjs.map +1 -0
  14. package/dist/LocalStateStore-BciJ_DF0.cjs +178 -0
  15. package/dist/LocalStateStore-BciJ_DF0.cjs.map +1 -0
  16. package/dist/LocalStateStore-CLHasLJI.mjs +167 -0
  17. package/dist/LocalStateStore-CLHasLJI.mjs.map +1 -0
  18. package/dist/OpenApiTsGenerator-CoVA3Ykv.mjs +534 -0
  19. package/dist/OpenApiTsGenerator-CoVA3Ykv.mjs.map +1 -0
  20. package/dist/OpenApiTsGenerator-vy-fOJgs.cjs +539 -0
  21. package/dist/OpenApiTsGenerator-vy-fOJgs.cjs.map +1 -0
  22. package/dist/S3StateStore-BHLRjoj3.cjs +222 -0
  23. package/dist/S3StateStore-BHLRjoj3.cjs.map +1 -0
  24. package/dist/S3StateStore-CTiv2_ON.mjs +223 -0
  25. package/dist/S3StateStore-CTiv2_ON.mjs.map +1 -0
  26. package/dist/SSMStateStore-BqT3MXXb.cjs +204 -0
  27. package/dist/SSMStateStore-BqT3MXXb.cjs.map +1 -0
  28. package/dist/SSMStateStore-D6qqaem2.mjs +205 -0
  29. package/dist/SSMStateStore-D6qqaem2.mjs.map +1 -0
  30. package/dist/SubscriberGenerator-Cfoz8uTY.mjs +787 -0
  31. package/dist/SubscriberGenerator-Cfoz8uTY.mjs.map +1 -0
  32. package/dist/SubscriberGenerator-CxzECrfj.cjs +852 -0
  33. package/dist/SubscriberGenerator-CxzECrfj.cjs.map +1 -0
  34. package/dist/add-B2OmIQzs.cjs +712 -0
  35. package/dist/add-B2OmIQzs.cjs.map +1 -0
  36. package/dist/add-CXwL549o.mjs +710 -0
  37. package/dist/add-CXwL549o.mjs.map +1 -0
  38. package/dist/appPorts-BoXMwolc.mjs +249 -0
  39. package/dist/appPorts-BoXMwolc.mjs.map +1 -0
  40. package/dist/appPorts-IW-OZmRi.cjs +296 -0
  41. package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
  42. package/dist/aws-BXfiWNbi.cjs +108 -0
  43. package/dist/aws-BXfiWNbi.cjs.map +1 -0
  44. package/dist/aws-BjvSTTcE.mjs +97 -0
  45. package/dist/aws-BjvSTTcE.mjs.map +1 -0
  46. package/dist/awsStore-BYYCmXiq.mjs +121 -0
  47. package/dist/awsStore-BYYCmXiq.mjs.map +1 -0
  48. package/dist/awsStore-DKQUElJL.cjs +138 -0
  49. package/dist/awsStore-DKQUElJL.cjs.map +1 -0
  50. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  51. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  52. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  53. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  54. package/dist/backups/runner.cjs +1007 -0
  55. package/dist/backups/runner.cjs.map +1 -0
  56. package/dist/backups/runner.d.cts +187 -0
  57. package/dist/backups/runner.d.cts.map +1 -0
  58. package/dist/backups/runner.d.mts +187 -0
  59. package/dist/backups/runner.d.mts.map +1 -0
  60. package/dist/backups/runner.mjs +984 -0
  61. package/dist/backups/runner.mjs.map +1 -0
  62. package/dist/{bundler-mwH7WOb1.mjs → bundler-CHXyJFsS.mjs} +68 -15
  63. package/dist/bundler-CHXyJFsS.mjs.map +1 -0
  64. package/dist/{bundler-mjqGAvu1.cjs → bundler-CLoVtcBi.cjs} +67 -14
  65. package/dist/bundler-CLoVtcBi.cjs.map +1 -0
  66. package/dist/cli-Bjua3PaZ.mjs +80 -0
  67. package/dist/cli-Bjua3PaZ.mjs.map +1 -0
  68. package/dist/cli-DiuUr1Am.cjs +80 -0
  69. package/dist/cli-DiuUr1Am.cjs.map +1 -0
  70. package/dist/clientTelemetry-DXuYNH-J.d.cts +10 -0
  71. package/dist/clientTelemetry-DXuYNH-J.d.cts.map +1 -0
  72. package/dist/clientTelemetry-eC8VQ6nB.d.mts +10 -0
  73. package/dist/clientTelemetry-eC8VQ6nB.d.mts.map +1 -0
  74. package/dist/compose-DUOETDhc.mjs +2855 -0
  75. package/dist/compose-DUOETDhc.mjs.map +1 -0
  76. package/dist/compose-gnNrY3NQ.cjs +2939 -0
  77. package/dist/compose-gnNrY3NQ.cjs.map +1 -0
  78. package/dist/config-1zirYXeO.d.mts +300 -0
  79. package/dist/config-1zirYXeO.d.mts.map +1 -0
  80. package/dist/config-rSlB-bXj.d.cts +300 -0
  81. package/dist/config-rSlB-bXj.d.cts.map +1 -0
  82. package/dist/config.cjs +462 -9
  83. package/dist/config.cjs.map +1 -0
  84. package/dist/config.d.cts +4 -117
  85. package/dist/config.d.mts +4 -117
  86. package/dist/config.mjs +446 -3
  87. package/dist/config.mjs.map +1 -0
  88. package/dist/credentialSchemas-D_85KW2k.mjs +236 -0
  89. package/dist/credentialSchemas-D_85KW2k.mjs.map +1 -0
  90. package/dist/credentialSchemas-DjK6xKMk.cjs +271 -0
  91. package/dist/credentialSchemas-DjK6xKMk.cjs.map +1 -0
  92. package/dist/credentials-BI52H1ad.cjs +2911 -0
  93. package/dist/credentials-BI52H1ad.cjs.map +1 -0
  94. package/dist/credentials-Cp09PIsc.cjs +1451 -0
  95. package/dist/credentials-Cp09PIsc.cjs.map +1 -0
  96. package/dist/credentials-DbjLhvix.mjs +1140 -0
  97. package/dist/credentials-DbjLhvix.mjs.map +1 -0
  98. package/dist/credentials-VLP_959f.mjs +2390 -0
  99. package/dist/credentials-VLP_959f.mjs.map +1 -0
  100. package/dist/databases-CV22HzrI.mjs +588 -0
  101. package/dist/databases-CV22HzrI.mjs.map +1 -0
  102. package/dist/databases-DwYYH2mX.cjs +703 -0
  103. package/dist/databases-DwYYH2mX.cjs.map +1 -0
  104. package/dist/dbTunnel-CLsqWr7o.mjs +153 -0
  105. package/dist/dbTunnel-CLsqWr7o.mjs.map +1 -0
  106. package/dist/dbTunnel-DQcdaaLi.cjs +153 -0
  107. package/dist/dbTunnel-DQcdaaLi.cjs.map +1 -0
  108. package/dist/define-BfrNaY82.mjs +106 -0
  109. package/dist/define-BfrNaY82.mjs.map +1 -0
  110. package/dist/define-zKgLY65H.cjs +153 -0
  111. package/dist/define-zKgLY65H.cjs.map +1 -0
  112. package/dist/deploy/public.cjs +210 -0
  113. package/dist/deploy/public.cjs.map +1 -0
  114. package/dist/deploy/public.d.cts +659 -0
  115. package/dist/deploy/public.d.cts.map +1 -0
  116. package/dist/deploy/public.d.mts +659 -0
  117. package/dist/deploy/public.d.mts.map +1 -0
  118. package/dist/deploy/public.mjs +143 -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 +1 -1
  132. package/dist/deploy-DhIy2Ftj.mjs +3854 -0
  133. package/dist/deploy-DhIy2Ftj.mjs.map +1 -0
  134. package/dist/deploy-DpQ_4Pu1.cjs +3910 -0
  135. package/dist/deploy-DpQ_4Pu1.cjs.map +1 -0
  136. package/dist/destroy-DmTDT6V7.cjs +791 -0
  137. package/dist/destroy-DmTDT6V7.cjs.map +1 -0
  138. package/dist/destroy-wV9yNLQV.mjs +790 -0
  139. package/dist/destroy-wV9yNLQV.mjs.map +1 -0
  140. package/dist/discover-Dfmn6HQ7.mjs +940 -0
  141. package/dist/discover-Dfmn6HQ7.mjs.map +1 -0
  142. package/dist/discover-OXczlq08.cjs +1085 -0
  143. package/dist/discover-OXczlq08.cjs.map +1 -0
  144. package/dist/dokploy-B61ww4Yb.cjs +38 -0
  145. package/dist/dokploy-B61ww4Yb.cjs.map +1 -0
  146. package/dist/dokploy-Jhl3sPd4.mjs +38 -0
  147. package/dist/dokploy-Jhl3sPd4.mjs.map +1 -0
  148. package/dist/drivers-BQRb3KsL.mjs +294 -0
  149. package/dist/drivers-BQRb3KsL.mjs.map +1 -0
  150. package/dist/drivers-DP7__dJX.cjs +377 -0
  151. package/dist/drivers-DP7__dJX.cjs.map +1 -0
  152. package/dist/eas-BmvO40xS.mjs +334 -0
  153. package/dist/eas-BmvO40xS.mjs.map +1 -0
  154. package/dist/eas-X09Gz8_E.cjs +337 -0
  155. package/dist/eas-X09Gz8_E.cjs.map +1 -0
  156. package/dist/emit-C4KSXOeS.mjs +153 -0
  157. package/dist/emit-C4KSXOeS.mjs.map +1 -0
  158. package/dist/emit-DiW0kbue.cjs +164 -0
  159. package/dist/emit-DiW0kbue.cjs.map +1 -0
  160. package/dist/encryption-BBIUewnL.cjs +90 -0
  161. package/dist/encryption-BBIUewnL.cjs.map +1 -0
  162. package/dist/encryption-BOmswIgE.mjs +89 -0
  163. package/dist/encryption-BOmswIgE.mjs.map +1 -0
  164. package/dist/engine-BhjhShKf.cjs +3333 -0
  165. package/dist/engine-BhjhShKf.cjs.map +1 -0
  166. package/dist/engine-DW2H3KNa.mjs +3220 -0
  167. package/dist/engine-DW2H3KNa.mjs.map +1 -0
  168. package/dist/errors-C9uIyIDt.mjs +27 -0
  169. package/dist/errors-C9uIyIDt.mjs.map +1 -0
  170. package/dist/errors-D1x8duqI.cjs +38 -0
  171. package/dist/errors-D1x8duqI.cjs.map +1 -0
  172. package/dist/github-Ptbigbrq.mjs +986 -0
  173. package/dist/github-Ptbigbrq.mjs.map +1 -0
  174. package/dist/github-xUtu4Ur7.cjs +987 -0
  175. package/dist/github-xUtu4Ur7.cjs.map +1 -0
  176. package/dist/googlePlay-B4xhz5xT.cjs +931 -0
  177. package/dist/googlePlay-B4xhz5xT.cjs.map +1 -0
  178. package/dist/googlePlay-C9rrwN5b.mjs +931 -0
  179. package/dist/googlePlay-C9rrwN5b.mjs.map +1 -0
  180. package/dist/iam-D7mXd6by.cjs +521 -0
  181. package/dist/iam-D7mXd6by.cjs.map +1 -0
  182. package/dist/iam-DNlbVN_l.mjs +442 -0
  183. package/dist/iam-DNlbVN_l.mjs.map +1 -0
  184. package/dist/{index-RCUizGxL.d.cts → index-B1gfXH5K.d.mts} +38 -14
  185. package/dist/index-B1gfXH5K.d.mts.map +1 -0
  186. package/dist/{index-B4H4XF7A.d.mts → index-CunkOPOu.d.cts} +38 -14
  187. package/dist/index-CunkOPOu.d.cts.map +1 -0
  188. package/dist/index.cjs +15566 -13457
  189. package/dist/index.cjs.map +1 -1
  190. package/dist/index.mjs +15249 -13138
  191. package/dist/index.mjs.map +1 -1
  192. package/dist/local-CvC-z86k.mjs +224 -0
  193. package/dist/local-CvC-z86k.mjs.map +1 -0
  194. package/dist/local-DAJrhvSC.cjs +241 -0
  195. package/dist/local-DAJrhvSC.cjs.map +1 -0
  196. package/dist/migrate-0-A4BOcd.cjs +272 -0
  197. package/dist/migrate-0-A4BOcd.cjs.map +1 -0
  198. package/dist/migrate-C_36JSwV.mjs +181 -0
  199. package/dist/migrate-C_36JSwV.mjs.map +1 -0
  200. package/dist/migrate-DHbXzZIJ.mjs +267 -0
  201. package/dist/migrate-DHbXzZIJ.mjs.map +1 -0
  202. package/dist/migrate-fGWfv2DV.cjs +181 -0
  203. package/dist/migrate-fGWfv2DV.cjs.map +1 -0
  204. package/dist/next.cjs +59 -0
  205. package/dist/next.cjs.map +1 -0
  206. package/dist/next.d.cts +44 -0
  207. package/dist/next.d.cts.map +1 -0
  208. package/dist/next.d.mts +44 -0
  209. package/dist/next.d.mts.map +1 -0
  210. package/dist/next.mjs +58 -0
  211. package/dist/next.mjs.map +1 -0
  212. package/dist/openapi.cjs +213 -7
  213. package/dist/openapi.cjs.map +1 -0
  214. package/dist/openapi.d.cts +27 -8
  215. package/dist/openapi.d.cts.map +1 -1
  216. package/dist/openapi.d.mts +27 -8
  217. package/dist/openapi.d.mts.map +1 -1
  218. package/dist/openapi.mjs +208 -2
  219. package/dist/openapi.mjs.map +1 -0
  220. package/dist/projectBucket-BAoFOQtA.cjs +263 -0
  221. package/dist/projectBucket-BAoFOQtA.cjs.map +1 -0
  222. package/dist/projectBucket-Dxub09V1.mjs +222 -0
  223. package/dist/projectBucket-Dxub09V1.mjs.map +1 -0
  224. package/dist/provider-BvjDbsTR.mjs +46 -0
  225. package/dist/provider-BvjDbsTR.mjs.map +1 -0
  226. package/dist/provider-DLhgo-mB.cjs +57 -0
  227. package/dist/provider-DLhgo-mB.cjs.map +1 -0
  228. package/dist/publish-BX8_zXaf.cjs +124 -0
  229. package/dist/publish-BX8_zXaf.cjs.map +1 -0
  230. package/dist/publish-DE_yBzlz.mjs +123 -0
  231. package/dist/publish-DE_yBzlz.mjs.map +1 -0
  232. package/dist/ready-DCvnFZnJ.cjs +404 -0
  233. package/dist/ready-DCvnFZnJ.cjs.map +1 -0
  234. package/dist/ready-sSPuiZ7N.mjs +375 -0
  235. package/dist/ready-sSPuiZ7N.mjs.map +1 -0
  236. package/dist/reconcile/public.cjs +3 -5
  237. package/dist/reconcile/public.d.cts +33 -89
  238. package/dist/reconcile/public.d.cts.map +1 -1
  239. package/dist/reconcile/public.d.mts +33 -89
  240. package/dist/reconcile/public.d.mts.map +1 -1
  241. package/dist/reconcile/public.mjs +3 -3
  242. package/dist/reconcile--I7V4Klj.mjs +34 -0
  243. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  244. package/dist/reconcile-CuCQBa5-.cjs +34 -0
  245. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  246. package/dist/resolve-CPB2jkB4.cjs +316 -0
  247. package/dist/resolve-CPB2jkB4.cjs.map +1 -0
  248. package/dist/resolve-DCPtP7-X.mjs +263 -0
  249. package/dist/resolve-DCPtP7-X.mjs.map +1 -0
  250. package/dist/rollback-sefKrjlE.mjs +137 -0
  251. package/dist/rollback-sefKrjlE.mjs.map +1 -0
  252. package/dist/rollback-ygh2qRWo.cjs +166 -0
  253. package/dist/rollback-ygh2qRWo.cjs.map +1 -0
  254. package/dist/runtime-BwiWhqkI.d.cts +82 -0
  255. package/dist/runtime-BwiWhqkI.d.cts.map +1 -0
  256. package/dist/runtime-Dx5F8-IL.d.mts +82 -0
  257. package/dist/runtime-Dx5F8-IL.d.mts.map +1 -0
  258. package/dist/s3-Bcvbg8io.cjs +240 -0
  259. package/dist/s3-Bcvbg8io.cjs.map +1 -0
  260. package/dist/s3-DK1ofU4f.mjs +240 -0
  261. package/dist/s3-DK1ofU4f.mjs.map +1 -0
  262. package/dist/sandbox/config-worker.cjs +43 -0
  263. package/dist/sandbox/config-worker.cjs.map +1 -0
  264. package/dist/sandbox/config-worker.d.cts +1 -0
  265. package/dist/sandbox/config-worker.d.mts +1 -0
  266. package/dist/sandbox/config-worker.mjs +44 -0
  267. package/dist/sandbox/config-worker.mjs.map +1 -0
  268. package/dist/sandbox/credentials-worker.cjs +53 -0
  269. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  270. package/dist/sandbox/credentials-worker.d.cts +1 -0
  271. package/dist/sandbox/credentials-worker.d.mts +1 -0
  272. package/dist/sandbox/credentials-worker.mjs +54 -0
  273. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  274. package/dist/sandbox/discover-worker.cjs +47 -0
  275. package/dist/sandbox/discover-worker.cjs.map +1 -0
  276. package/dist/sandbox/discover-worker.d.cts +1 -0
  277. package/dist/sandbox/discover-worker.d.mts +1 -0
  278. package/dist/sandbox/discover-worker.mjs +48 -0
  279. package/dist/sandbox/discover-worker.mjs.map +1 -0
  280. package/dist/sandbox/migrate-worker.cjs +75 -0
  281. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  282. package/dist/sandbox/migrate-worker.d.cts +1 -0
  283. package/dist/sandbox/migrate-worker.d.mts +1 -0
  284. package/dist/sandbox/migrate-worker.mjs +76 -0
  285. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  286. package/dist/{workspace-CRD9YinV.cjs → schemas-BCwKKA42.mjs} +399 -1179
  287. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  288. package/dist/{workspace-Bu3xNCej.mjs → schemas-BQ_v0lEX.cjs} +487 -982
  289. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  290. package/dist/secretsManager-CjTo6CRq.mjs +113 -0
  291. package/dist/secretsManager-CjTo6CRq.mjs.map +1 -0
  292. package/dist/secretsManager-CvmBGjdM.cjs +124 -0
  293. package/dist/secretsManager-CvmBGjdM.cjs.map +1 -0
  294. package/dist/seeds-Bc3niNVb.cjs +382 -0
  295. package/dist/seeds-Bc3niNVb.cjs.map +1 -0
  296. package/dist/seeds-Ccn0Ru2T.mjs +299 -0
  297. package/dist/seeds-Ccn0Ru2T.mjs.map +1 -0
  298. package/dist/serverSetup-ClU2iSeU.cjs +686 -0
  299. package/dist/serverSetup-ClU2iSeU.cjs.map +1 -0
  300. package/dist/serverSetup-D68Otrp0.mjs +686 -0
  301. package/dist/serverSetup-D68Otrp0.mjs.map +1 -0
  302. package/dist/sniffer-CFOmQQit.cjs +1997 -0
  303. package/dist/sniffer-CFOmQQit.cjs.map +1 -0
  304. package/dist/sniffer-CRF3eD_B.mjs +1824 -0
  305. package/dist/sniffer-CRF3eD_B.mjs.map +1 -0
  306. package/dist/snsSubscriptions-CwA6Ceg2.mjs +1024 -0
  307. package/dist/snsSubscriptions-CwA6Ceg2.mjs.map +1 -0
  308. package/dist/snsSubscriptions-S_CMCXqI.cjs +1149 -0
  309. package/dist/snsSubscriptions-S_CMCXqI.cjs.map +1 -0
  310. package/dist/sst-BgG7dJJu.cjs +514 -0
  311. package/dist/sst-BgG7dJJu.cjs.map +1 -0
  312. package/dist/sst-CDnHFO3U.mjs +491 -0
  313. package/dist/sst-CDnHFO3U.mjs.map +1 -0
  314. package/dist/stack-BXmLQf3K.mjs +10920 -0
  315. package/dist/stack-BXmLQf3K.mjs.map +1 -0
  316. package/dist/stack-BtnflNSa.cjs +11901 -0
  317. package/dist/stack-BtnflNSa.cjs.map +1 -0
  318. package/dist/stage-BbQidxxa.mjs +302 -0
  319. package/dist/stage-BbQidxxa.mjs.map +1 -0
  320. package/dist/stage-ssuPXLhP.cjs +331 -0
  321. package/dist/stage-ssuPXLhP.cjs.map +1 -0
  322. package/dist/stages-CQwD2QxS.cjs +190 -0
  323. package/dist/stages-CQwD2QxS.cjs.map +1 -0
  324. package/dist/stages-MA2sXnX4.mjs +190 -0
  325. package/dist/stages-MA2sXnX4.mjs.map +1 -0
  326. package/dist/target/public.cjs +15 -0
  327. package/dist/target/public.d.cts +28 -0
  328. package/dist/target/public.d.cts.map +1 -0
  329. package/dist/target/public.d.mts +28 -0
  330. package/dist/target/public.d.mts.map +1 -0
  331. package/dist/target/public.mjs +4 -0
  332. package/dist/terminal-BEGE1AEV.mjs +85 -0
  333. package/dist/terminal-BEGE1AEV.mjs.map +1 -0
  334. package/dist/terminal-BecJpgA3.cjs +85 -0
  335. package/dist/terminal-BecJpgA3.cjs.map +1 -0
  336. package/dist/{types-7R81hu0i.d.mts → types-BvokH0ya.d.cts} +2235 -459
  337. package/dist/types-BvokH0ya.d.cts.map +1 -0
  338. package/dist/{types-N7c2O2m7.d.cts → types-DmLnGeii.d.mts} +2233 -459
  339. package/dist/types-DmLnGeii.d.mts.map +1 -0
  340. package/dist/utils-CdKxD8Lt.mjs +156 -0
  341. package/dist/utils-CdKxD8Lt.mjs.map +1 -0
  342. package/dist/utils-DBqXbB8P.cjs +205 -0
  343. package/dist/utils-DBqXbB8P.cjs.map +1 -0
  344. package/dist/vitest.cjs +65 -0
  345. package/dist/vitest.cjs.map +1 -0
  346. package/dist/vitest.d.cts +29 -0
  347. package/dist/vitest.d.cts.map +1 -0
  348. package/dist/vitest.d.mts +29 -0
  349. package/dist/vitest.d.mts.map +1 -0
  350. package/dist/vitest.mjs +65 -0
  351. package/dist/vitest.mjs.map +1 -0
  352. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  353. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  354. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  355. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  356. package/dist/workspace/index.cjs +6 -2
  357. package/dist/workspace/index.d.cts +3 -3
  358. package/dist/workspace/index.d.mts +3 -3
  359. package/dist/workspace/index.mjs +2 -2
  360. package/dist/workspace-DEmfa9RO.cjs +3689 -0
  361. package/dist/workspace-DEmfa9RO.cjs.map +1 -0
  362. package/dist/workspace-RgU7TBgg.mjs +3133 -0
  363. package/dist/workspace-RgU7TBgg.mjs.map +1 -0
  364. package/package.json +76 -13
  365. package/dist/HostingerProvider-BY26bWwB.mjs +0 -243
  366. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  367. package/dist/HostingerProvider-BZFGYYVA.cjs +0 -243
  368. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  369. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  370. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  371. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  372. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  373. package/dist/Route53Provider-Cvj40A8I.mjs +0 -209
  374. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  375. package/dist/Route53Provider-DVILBsvV.cjs +0 -209
  376. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  377. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  378. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  379. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  380. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  381. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  382. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  383. package/dist/bundler-mjqGAvu1.cjs.map +0 -1
  384. package/dist/bundler-mwH7WOb1.mjs.map +0 -1
  385. package/dist/config-DSXI480r.cjs +0 -467
  386. package/dist/config-DSXI480r.cjs.map +0 -1
  387. package/dist/config-DdKkoUE1.mjs +0 -414
  388. package/dist/config-DdKkoUE1.mjs.map +0 -1
  389. package/dist/config.d.cts.map +0 -1
  390. package/dist/config.d.mts.map +0 -1
  391. package/dist/credentials-C6Pfn6GY.cjs +0 -2939
  392. package/dist/credentials-C6Pfn6GY.cjs.map +0 -1
  393. package/dist/credentials-lbv-j0Be.mjs +0 -2802
  394. package/dist/credentials-lbv-j0Be.mjs.map +0 -1
  395. package/dist/discover-BERGFg8v.cjs +0 -288
  396. package/dist/discover-BERGFg8v.cjs.map +0 -1
  397. package/dist/discover-CK-n3w6b.mjs +0 -244
  398. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  399. package/dist/emit-BdoPFjZf.cjs +0 -253
  400. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  401. package/dist/emit-Bzq7JsMP.mjs +0 -224
  402. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  403. package/dist/generator-LfZU7NlU.mjs +0 -247
  404. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  405. package/dist/generator-Wdfp0jCS.cjs +0 -282
  406. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  407. package/dist/github-BvfpvBcW.cjs +0 -216
  408. package/dist/github-BvfpvBcW.cjs.map +0 -1
  409. package/dist/github-DW3CP-4D.mjs +0 -216
  410. package/dist/github-DW3CP-4D.mjs.map +0 -1
  411. package/dist/index-B4H4XF7A.d.mts.map +0 -1
  412. package/dist/index-RCUizGxL.d.cts.map +0 -1
  413. package/dist/openapi-B8bu_OXN.cjs +0 -2038
  414. package/dist/openapi-B8bu_OXN.cjs.map +0 -1
  415. package/dist/openapi-DfjbhrsM.mjs +0 -1991
  416. package/dist/openapi-DfjbhrsM.mjs.map +0 -1
  417. package/dist/reconcile-gb1lz1Dk.mjs +0 -113
  418. package/dist/reconcile-gb1lz1Dk.mjs.map +0 -1
  419. package/dist/reconcile-hx_vBvux.cjs +0 -136
  420. package/dist/reconcile-hx_vBvux.cjs.map +0 -1
  421. package/dist/ssm-BKN1Cg4z.mjs +0 -60
  422. package/dist/ssm-BKN1Cg4z.mjs.map +0 -1
  423. package/dist/ssm-FxeSAt35.cjs +0 -60
  424. package/dist/ssm-FxeSAt35.cjs.map +0 -1
  425. package/dist/storage-DgypfSD6.cjs +0 -351
  426. package/dist/storage-DgypfSD6.cjs.map +0 -1
  427. package/dist/storage-TP0x118M.mjs +0 -304
  428. package/dist/storage-TP0x118M.mjs.map +0 -1
  429. package/dist/transfer-DjFZRgub.mjs +0 -122
  430. package/dist/transfer-DjFZRgub.mjs.map +0 -1
  431. package/dist/transfer-SeiSeKEF.cjs +0 -151
  432. package/dist/transfer-SeiSeKEF.cjs.map +0 -1
  433. package/dist/types-7R81hu0i.d.mts.map +0 -1
  434. package/dist/types-N7c2O2m7.d.cts.map +0 -1
  435. package/dist/workspace-Bu3xNCej.mjs.map +0 -1
  436. package/dist/workspace-CRD9YinV.cjs.map +0 -1
@@ -0,0 +1,2939 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-D1x8duqI.cjs");
3
+ const require_credentials = require("./credentials-Cp09PIsc.cjs");
4
+ const require_stack = require("./stack-BtnflNSa.cjs");
5
+ const require_workspace = require("./workspace-DEmfa9RO.cjs");
6
+ const require_define = require("./define-zKgLY65H.cjs");
7
+ const require_credentials$1 = require("./credentials-BI52H1ad.cjs");
8
+ const require_drivers = require("./drivers-DP7__dJX.cjs");
9
+ const require_discover = require("./discover-OXczlq08.cjs");
10
+ const require_snsSubscriptions = require("./snsSubscriptions-S_CMCXqI.cjs");
11
+ const require_seeds = require("./seeds-Bc3niNVb.cjs");
12
+ const require_databases = require("./databases-DwYYH2mX.cjs");
13
+ let node_path = require("node:path");
14
+ let _geekmidas_edge = require("@geekmidas/edge");
15
+ let node_fs = require("node:fs");
16
+ let node_fs_promises = require("node:fs/promises");
17
+ let node_os = require("node:os");
18
+ let node_child_process = require("node:child_process");
19
+ let node_net = require("node:net");
20
+ let node_crypto = require("node:crypto");
21
+ let _geekmidas_edge_certificates_local = require("@geekmidas/edge/certificates/local");
22
+ let _geekmidas_edge_proxy_traefik = require("@geekmidas/edge/proxy/traefik");
23
+ let _geekmidas_manifest = require("@geekmidas/manifest");
24
+ let yaml = require("yaml");
25
+ let node_http = require("node:http");
26
+ let node_forge = require("node-forge");
27
+ node_forge = require_rolldown_runtime.__toESM(node_forge, 1);
28
+ let node_https = require("node:https");
29
+ //#region src/compose/server.ts
30
+ /**
31
+ * Where a deployed compose stage runs: its server, reached over SSH.
32
+ *
33
+ * gkm never runs on the server. It runs where the deploy is started — a CI
34
+ * runner, a developer's machine — and drives the server's Docker engine over
35
+ * SSH (`DOCKER_HOST=ssh://user@host`), so the server holds Docker, an SSH
36
+ * login and nothing else: no gkm, no checkout, no cloud credentials.
37
+ *
38
+ * ```ts
39
+ * deploy: { compose: { server: { production: { user: 'deploy' } } } }
40
+ * ```
41
+ *
42
+ * The host is the stage's `GKM_SERVER_IPV4` secret — the address its DNS
43
+ * records already point at — unless `host` names another. The local stage is
44
+ * never given one: it runs on this machine's Docker.
45
+ *
46
+ * What the deploy needs from inside the server — Postgres and MinIO, published
47
+ * on the server's loopback alone — it reaches through an SSH tunnel on the same
48
+ * login, so neither is ever published publicly.
49
+ */
50
+ /** A deployed compose stage with nowhere to run. */
51
+ var ComposeServerMissing = class extends require_errors.GkmError {
52
+ stage;
53
+ missing;
54
+ constructor(stage, missing) {
55
+ 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 ${require_workspace.SERVER_IPV4_KEY} secret (gkm secrets:set ${require_workspace.SERVER_IPV4_KEY} '<ip>' --stage ${stage}), or set host there too.` : `deploy.compose.server.${stage} names no host, and '${stage}' has no ${require_workspace.SERVER_IPV4_KEY} secret to default to. Set it: gkm secrets:set ${require_workspace.SERVER_IPV4_KEY} '<ip>' --stage ${stage} — or set deploy.compose.server.${stage}.host.`);
56
+ this.stage = stage;
57
+ this.missing = missing;
58
+ this.name = "ComposeServerMissing";
59
+ }
60
+ };
61
+ /** SSH to the stage's server failed before anything was changed there. */
62
+ var ComposeServerUnreachable = class extends require_errors.GkmError {
63
+ target;
64
+ stderr;
65
+ constructor(target, stderr) {
66
+ 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.`);
67
+ this.target = target;
68
+ this.stderr = stderr;
69
+ this.name = "ComposeServerUnreachable";
70
+ }
71
+ };
72
+ /** An SSH tunnel to a port on the server's loopback did not open. */
73
+ var ComposeTunnelFailed = class extends require_errors.GkmError {
74
+ target;
75
+ remotePort;
76
+ stderr;
77
+ constructor(target, remotePort, stderr) {
78
+ 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 …\`).`);
79
+ this.target = target;
80
+ this.remotePort = remotePort;
81
+ this.stderr = stderr;
82
+ this.name = "ComposeTunnelFailed";
83
+ }
84
+ };
85
+ /**
86
+ * The stage's server: its login from `deploy.compose.server.<stage>`, its
87
+ * host from there or the stage's `GKM_SERVER_IPV4`. Undefined for the local
88
+ * stage, which runs on this machine.
89
+ *
90
+ * @throws {ComposeServerMissing} for a deployed stage with no login or host
91
+ */
92
+ function composeServer(options) {
93
+ const { stage } = options;
94
+ if (options.local) return void 0;
95
+ const config = options.config?.[stage];
96
+ if (!config) throw new ComposeServerMissing(stage, "config");
97
+ const host = config.host ?? options.custom?.["GKM_SERVER_IPV4"]?.trim();
98
+ if (!host) throw new ComposeServerMissing(stage, "host");
99
+ return {
100
+ user: config.user,
101
+ host,
102
+ port: config.port ?? 22
103
+ };
104
+ }
105
+ /** `user@host`, as a person types it after `ssh`. */
106
+ function sshTarget(server) {
107
+ return `${server.user}@${server.host}`;
108
+ }
109
+ /** The server's Docker engine, as `DOCKER_HOST` names it. */
110
+ function dockerHost(server) {
111
+ const host = server.host.includes(":") ? `[${server.host}]` : server.host;
112
+ return `ssh://${server.user}@${host}${server.port === 22 ? "" : `:${server.port}`}`;
113
+ }
114
+ /** The arguments every `ssh` gkm runs starts with: no prompt, ever. */
115
+ function sshArgs(server) {
116
+ return [
117
+ "-o",
118
+ "BatchMode=yes",
119
+ "-o",
120
+ "ConnectTimeout=20",
121
+ "-p",
122
+ String(server.port),
123
+ sshTarget(server)
124
+ ];
125
+ }
126
+ async function freeLocalPort() {
127
+ const server = (0, node_net.createServer)();
128
+ await new Promise((resolve, reject) => {
129
+ server.once("error", reject);
130
+ server.listen(0, "127.0.0.1", resolve);
131
+ });
132
+ const address = server.address();
133
+ await new Promise((resolve) => server.close(resolve));
134
+ if (!address || typeof address === "string") return 0;
135
+ return address.port;
136
+ }
137
+ function connects(port) {
138
+ return new Promise((resolve) => {
139
+ const socket = (0, node_net.createConnection)({
140
+ host: "127.0.0.1",
141
+ port
142
+ });
143
+ socket.once("connect", () => {
144
+ socket.destroy();
145
+ resolve(true);
146
+ });
147
+ socket.once("error", () => resolve(false));
148
+ });
149
+ }
150
+ /** The real one: the system's `ssh`, with the user's keys and known hosts. */
151
+ const sshAccess = {
152
+ check(server) {
153
+ return new Promise((resolve, reject) => {
154
+ const child = (0, node_child_process.spawn)("ssh", [
155
+ ...sshArgs(server),
156
+ "docker",
157
+ "version",
158
+ "--format",
159
+ "{{.Server.Version}}"
160
+ ], { stdio: [
161
+ "ignore",
162
+ "ignore",
163
+ "pipe"
164
+ ] });
165
+ let stderr = "";
166
+ child.stderr.on("data", (chunk) => {
167
+ stderr += chunk.toString();
168
+ });
169
+ child.on("error", (error) => reject(new ComposeServerUnreachable(sshTarget(server), error.message)));
170
+ child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeServerUnreachable(sshTarget(server), stderr)));
171
+ });
172
+ },
173
+ async tunnel(server, remotePort) {
174
+ const port = await freeLocalPort();
175
+ const child = (0, node_child_process.spawn)("ssh", [
176
+ "-N",
177
+ "-o",
178
+ "ExitOnForwardFailure=yes",
179
+ "-o",
180
+ "ControlPath=none",
181
+ "-L",
182
+ `127.0.0.1:${port}:127.0.0.1:${remotePort}`,
183
+ ...sshArgs(server)
184
+ ], { stdio: [
185
+ "ignore",
186
+ "ignore",
187
+ "pipe"
188
+ ] });
189
+ let stderr = "";
190
+ let exited = false;
191
+ child.stderr.on("data", (chunk) => {
192
+ stderr += chunk.toString();
193
+ });
194
+ child.on("exit", () => {
195
+ exited = true;
196
+ });
197
+ child.on("error", (error) => {
198
+ exited = true;
199
+ stderr += error.message;
200
+ });
201
+ const close = async () => {
202
+ if (exited) return;
203
+ const gone = new Promise((resolve) => child.once("exit", resolve));
204
+ child.kill("SIGTERM");
205
+ await gone;
206
+ };
207
+ for (let attempt = 0; attempt < 150; attempt++) {
208
+ if (exited) break;
209
+ if (await connects(port)) return {
210
+ port,
211
+ close
212
+ };
213
+ await new Promise((resolve) => setTimeout(resolve, 200));
214
+ }
215
+ await close();
216
+ throw new ComposeTunnelFailed(sshTarget(server), remotePort, stderr);
217
+ }
218
+ };
219
+ //#endregion
220
+ //#region src/compose/images.ts
221
+ /**
222
+ * Which image each app runs — and, for a tag, whether every one exists.
223
+ *
224
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
225
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
226
+ * image is asked of the registry before anything is pulled or the running
227
+ * stack is touched, and one missing image stops the whole run naming every
228
+ * one that is missing. Nor is a missing image quietly built instead — a build
229
+ * of whatever is checked out here is not the release the tag names.
230
+ */
231
+ /** Images a tag names that the registry does not have. */
232
+ var ImageTagNotFound = class extends require_errors.GkmError {
233
+ tag;
234
+ refs;
235
+ constructor(tag, refs) {
236
+ 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.`);
237
+ this.tag = tag;
238
+ this.refs = refs;
239
+ this.name = "ImageTagNotFound";
240
+ }
241
+ };
242
+ /** The registry did not answer, or did not let this machine in. */
243
+ var RegistryUnreachable = class extends require_errors.GkmError {
244
+ ref;
245
+ detail;
246
+ constructor(ref, detail) {
247
+ 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>\`).`);
248
+ this.ref = ref;
249
+ this.detail = detail;
250
+ this.name = "RegistryUnreachable";
251
+ }
252
+ };
253
+ /**
254
+ * A pinned image whose digest the registry would not give, while its tag it
255
+ * would: the tag now names another image than the one the release pinned.
256
+ *
257
+ * Not a login problem — the registry answered for the tag. The tag was pushed
258
+ * again (by another build of it), and the pinned image is gone, or cannot be
259
+ * read, by its digest.
260
+ */
261
+ var PinnedImageMoved = class extends require_errors.GkmError {
262
+ ref;
263
+ detail;
264
+ constructor(ref, detail) {
265
+ const [tagged, digest] = ref.split("@");
266
+ super(`${tagged} is in the registry, but it resolves to a different image than the pinned ${digest}, and the registry would not give that digest${detail ? `: ${detail}` : ""}\nNothing was pulled or started. The tag was pushed again after this release's push; deploy with the digests file of a push whose images are still in the registry, or push this release again.`);
267
+ this.ref = ref;
268
+ this.detail = detail;
269
+ this.name = "PinnedImageMoved";
270
+ }
271
+ };
272
+ /**
273
+ * The ref an image is asked of the registry by: a pinned one by its digest
274
+ * alone (`<image>@sha256:…`), so a tag moved since the push cannot change the
275
+ * answer; any other by its tag.
276
+ */
277
+ function lookupRef(ref) {
278
+ const [tagged, digest] = ref.split("@");
279
+ if (!digest) return ref;
280
+ return `${tagged.replace(/:[\w][\w.-]*$/, "")}@${digest}`;
281
+ }
282
+ /**
283
+ * Assert every image exists, before anything else happens.
284
+ *
285
+ * Asked all at once and reported all at once: a release missing two images is
286
+ * one problem with two names, and finding the second only after fixing the
287
+ * first is a slower way to learn the same thing.
288
+ *
289
+ * A pinned image is asked for by its digest. When the registry will not give
290
+ * it, its tag is asked too: a tag that answers means the registry is reachable
291
+ * and the tag names another image, and that is what is reported.
292
+ *
293
+ * @throws {PinnedImageMoved} when a pinned digest fails and its tag answers
294
+ * @throws {RegistryUnreachable} when the registry cannot say
295
+ * @throws {ImageTagNotFound} listing every missing image
296
+ */
297
+ async function assertImagesExist(docker, tag, images) {
298
+ const lookups = await Promise.all(images.map(async (image) => ({
299
+ image,
300
+ lookup: await docker.lookup(lookupRef(image.ref))
301
+ })));
302
+ for (const { image, lookup } of lookups) {
303
+ if (lookup.status === "found" || !image.ref.includes("@")) continue;
304
+ if ((await docker.lookup(image.ref.split("@")[0])).status === "found") throw new PinnedImageMoved(image.ref, lookup.status === "unreachable" ? lookup.detail : "");
305
+ }
306
+ for (const { lookup } of lookups) if (lookup.status === "unreachable") throw new RegistryUnreachable(lookup.ref, lookup.detail);
307
+ const missing = lookups.filter(({ lookup }) => lookup.status === "missing").map(({ image }) => image.ref);
308
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
309
+ }
310
+ /**
311
+ * A push or a pull with no `deploy.registry` to push to or pull from.
312
+ *
313
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
314
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
315
+ * from, somebody else's account. It is never a fallback.
316
+ */
317
+ var RegistryRequired = class extends require_errors.GkmError {
318
+ operation;
319
+ ref;
320
+ constructor(operation, ref) {
321
+ 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." : ""));
322
+ this.operation = operation;
323
+ this.ref = ref;
324
+ this.name = "RegistryRequired";
325
+ }
326
+ };
327
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
328
+ function pinnedRef(ref, digest) {
329
+ return `${ref.split("@")[0]}@${digest}`;
330
+ }
331
+ /** A digests file with no entry for an app the stack runs. */
332
+ var ImageDigestMissing = class extends require_errors.GkmError {
333
+ file;
334
+ apps;
335
+ constructor(file, apps) {
336
+ 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.`);
337
+ this.file = file;
338
+ this.apps = apps;
339
+ this.name = "ImageDigestMissing";
340
+ }
341
+ };
342
+ /** A digests file entry that is not this app's image. */
343
+ var ImageDigestMismatch = class extends require_errors.GkmError {
344
+ app;
345
+ expected;
346
+ found;
347
+ constructor(app, expected, found) {
348
+ 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.`);
349
+ this.app = app;
350
+ this.expected = expected;
351
+ this.found = found;
352
+ this.name = "ImageDigestMismatch";
353
+ }
354
+ };
355
+ /** A digests file that is not a JSON object of app to pinned ref. */
356
+ var ImageDigestsInvalid = class extends require_errors.GkmError {
357
+ file;
358
+ detail;
359
+ constructor(file, detail) {
360
+ 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:…" }.`);
361
+ this.file = file;
362
+ this.detail = detail;
363
+ this.name = "ImageDigestsInvalid";
364
+ }
365
+ };
366
+ /** Parse a digests file's content, checking its shape. */
367
+ function parseDigests(file, content) {
368
+ let parsed;
369
+ try {
370
+ parsed = JSON.parse(content);
371
+ } catch (error) {
372
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
373
+ }
374
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
375
+ 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`);
376
+ return parsed;
377
+ }
378
+ /**
379
+ * Each image pinned to the digest the file names for it.
380
+ *
381
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
382
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
383
+ */
384
+ function pinImages(file, digests, images) {
385
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
386
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
387
+ return images.map((image) => {
388
+ const pinned = digests[image.app];
389
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
390
+ return {
391
+ ...image,
392
+ ref: pinned
393
+ };
394
+ });
395
+ }
396
+ //#endregion
397
+ //#region src/compose/originCertificate.ts
398
+ /**
399
+ * The origin certificate a CDN issues for the hosts it answers — what the
400
+ * server shows the CDN when it connects (`deploy.cdn.<stage>.certificate`,
401
+ * `'origin'` by default).
402
+ *
403
+ * A host behind Cloudflare's proxy resolves to Cloudflare, so Let's
404
+ * Encrypt's HTTP challenge no longer reliably reaches the server. Cloudflare
405
+ * issues certificates for its own origins instead: trusted by its proxy and
406
+ * by nothing else, valid up to 15 years, for whatever hosts the request
407
+ * names. So the deploy:
408
+ *
409
+ * - **makes the key here**, on the machine that runs the deploy, and sends
410
+ * Cloudflare's Origin CA only a signing request — the key is never sent;
411
+ * - **asks for exactly the hosts the CDN answers**, never a wildcard it did
412
+ * not declare: the edge is shared, and a certificate is served for every
413
+ * name it covers;
414
+ * - **keeps both in the stage's secrets**, under keys gkm reserves for the
415
+ * server (`GKM_SERVER_*`, never handed to an app), so every later deploy
416
+ * reuses them — and the server holds no Cloudflare token;
417
+ * - **asks again** only when the hosts it is for change, its key no longer
418
+ * matches, or it is within {@link ORIGIN_RENEW_BEFORE_DAYS} of expiring.
419
+ *
420
+ * The token is the deploy's own (`CLOUDFLARE_API_TOKEN`), which then needs
421
+ * `Zone → SSL and Certificates → Edit` beside its DNS permissions.
422
+ */
423
+ /** The stage secret holding the origin certificate, PEM. */
424
+ const ORIGIN_CERT_KEY = "GKM_SERVER_ORIGIN_CERT";
425
+ /** The stage secret holding its private key, PEM. */
426
+ const ORIGIN_KEY_KEY = "GKM_SERVER_ORIGIN_KEY";
427
+ /** What is asked for: the Origin CA's longest, 15 years. */
428
+ const ORIGIN_VALIDITY_DAYS = 5475;
429
+ /** The names a certificate covers, lowercase: its DNS subject alternative names. */
430
+ function certificateHosts(cert) {
431
+ return new Set((cert.subjectAltName ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry.startsWith("DNS:")).map((entry) => entry.slice(4).toLowerCase()));
432
+ }
433
+ /**
434
+ * What is wrong with a kept certificate for `hosts` at `now`, or `undefined`
435
+ * when it serves them: it covers each by name, its key is its own, and it
436
+ * is not about to expire.
437
+ */
438
+ function originCertificateProblem(kept, hosts, now = /* @__PURE__ */ new Date()) {
439
+ if (!kept?.cert || !kept.key) return "missing";
440
+ let cert;
441
+ try {
442
+ cert = new node_crypto.X509Certificate(kept.cert);
443
+ if (!cert.checkPrivateKey((0, node_crypto.createPrivateKey)(kept.key))) return "key";
444
+ } catch {
445
+ return "unreadable";
446
+ }
447
+ const covered = certificateHosts(cert);
448
+ if (!hosts.every((host) => covered.has(host.toLowerCase()))) return "hosts";
449
+ const renewAt = new Date(cert.validTo).getTime() - 2592e6;
450
+ if (now.getTime() >= renewAt) return "expiring";
451
+ }
452
+ /**
453
+ * A new private key and a signing request for `hosts` — RSA, which every
454
+ * proxy serves. The key stays here; only the request is sent.
455
+ */
456
+ function originSigningRequest(hosts) {
457
+ const { privateKey, publicKey } = (0, node_crypto.generateKeyPairSync)("rsa", { modulusLength: 2048 });
458
+ const key = privateKey.export({
459
+ type: "pkcs8",
460
+ format: "pem"
461
+ }).toString();
462
+ const csr = node_forge.default.pki.createCertificationRequest();
463
+ csr.publicKey = node_forge.default.pki.publicKeyFromPem(publicKey.export({
464
+ type: "spki",
465
+ format: "pem"
466
+ }).toString());
467
+ csr.setSubject([{
468
+ name: "commonName",
469
+ value: hosts[0]
470
+ }]);
471
+ csr.setAttributes([{
472
+ name: "extensionRequest",
473
+ extensions: [{
474
+ name: "subjectAltName",
475
+ altNames: hosts.map((value) => ({
476
+ type: 2,
477
+ value
478
+ }))
479
+ }]
480
+ }]);
481
+ csr.sign(node_forge.default.pki.privateKeyFromPem(key), node_forge.default.md.sha256.create());
482
+ return {
483
+ csr: node_forge.default.pki.certificationRequestToPem(csr),
484
+ key
485
+ };
486
+ }
487
+ const REASONS = {
488
+ missing: "there is none yet",
489
+ unreadable: "the one kept cannot be read",
490
+ key: "the one kept does not match its key",
491
+ hosts: "the hosts it is for changed",
492
+ expiring: `the one kept expires within 30 days`
493
+ };
494
+ /**
495
+ * The stage's origin certificate for `hosts`: the one kept, while it serves
496
+ * them, and otherwise a new one from Cloudflare's Origin CA, kept before it
497
+ * is returned. A dry run issues nothing, and says it would.
498
+ *
499
+ * @throws {MissingCredential} when one must be issued and there is no token
500
+ */
501
+ async function ensureOriginCertificate(input) {
502
+ const log = input.log ?? ((line) => console.log(line));
503
+ const hosts = [...new Set(input.hosts.map((h) => h.toLowerCase()))].sort();
504
+ const kept = {
505
+ cert: input.custom?.[ORIGIN_CERT_KEY],
506
+ key: input.custom?.[ORIGIN_KEY_KEY]
507
+ };
508
+ const problem = originCertificateProblem(kept, hosts, input.now);
509
+ if (!problem) return kept;
510
+ const why = REASONS[problem];
511
+ if (input.dryRun) {
512
+ log(` 🔐 would have Cloudflare issue an origin certificate for ${hosts.join(", ")} — ${why}`);
513
+ return problem === "expiring" || problem === "hosts" ? kept : void 0;
514
+ }
515
+ const credential = await input.credentials.get({ kind: "cloudflare" });
516
+ if (!credential?.token) throw new require_credentials.MissingCredential("cloudflare", `${input.stage}'s origin certificate`);
517
+ log(` 🔐 Cloudflare issues an origin certificate for ${hosts.join(", ")} — ${why}`);
518
+ const issuer = await (input.issuer ?? cloudflareIssuer)(credential.token);
519
+ const { csr, key } = originSigningRequest(hosts);
520
+ const { certificate } = await issuer.createOriginCertificate(input.zone, {
521
+ csr,
522
+ hostnames: hosts,
523
+ days: ORIGIN_VALIDITY_DAYS,
524
+ type: "origin-rsa"
525
+ });
526
+ const issued = {
527
+ cert: certificate,
528
+ key
529
+ };
530
+ await input.keep({
531
+ [ORIGIN_CERT_KEY]: issued.cert,
532
+ [ORIGIN_KEY_KEY]: key
533
+ });
534
+ return issued;
535
+ }
536
+ /** Cloudflare's own Origin CA, through the deploy's token. */
537
+ async function cloudflareIssuer(token) {
538
+ const { CloudflareApi } = await import("@geekmidas/edge/dns/cloudflare");
539
+ return new CloudflareApi({ credential: { token } });
540
+ }
541
+ //#endregion
542
+ //#region src/compose/secrets.ts
543
+ function deployedStackSecrets(workspace, stage, stored, manifest) {
544
+ const withSeed = require_credentials$1.withGeneratedSecrets(stored ?? require_credentials.initStageSecrets(stage), manifest);
545
+ const withLogs = require_workspace.resolveStageTelemetry({
546
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
547
+ stage,
548
+ local: false,
549
+ target: "compose",
550
+ runtime: "server",
551
+ selfHosted: true,
552
+ used: require_credentials$1.usesTelemetry(manifest)
553
+ })?.provider === "self-hosted" ? require_credentials$1.withLogsLogin(withSeed.secrets, workspace.domains?.[stage]) : {
554
+ secrets: withSeed.secrets,
555
+ generated: []
556
+ };
557
+ const withRedis = require_credentials$1.runsRedis(manifest, withLogs.secrets.custom ?? {}) ? require_credentials$1.withRedisPassword(withLogs.secrets) : {
558
+ secrets: withLogs.secrets,
559
+ generated: []
560
+ };
561
+ return {
562
+ secrets: withRedis.secrets,
563
+ generated: [
564
+ ...withSeed.generated,
565
+ ...withLogs.generated,
566
+ ...withRedis.generated
567
+ ]
568
+ };
569
+ }
570
+ //#endregion
571
+ //#region src/target/compose/health.ts
572
+ /**
573
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
574
+ * the way a browser reaches it.
575
+ *
576
+ * `docker compose up --wait` already knows each container passed its own
577
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
578
+ * the stack is reachable: whether the edge routes the host to the app, and
579
+ * whether the certificate it presents is one a client accepts. So the check
580
+ * goes through the edge, by hostname, and verifies the certificate.
581
+ */
582
+ /** A request that got no answer in time. */
583
+ var HealthRequestTimedOut = class extends require_errors.GkmError {
584
+ url;
585
+ timeoutMs;
586
+ constructor(url, timeoutMs) {
587
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
588
+ this.url = url;
589
+ this.timeoutMs = timeoutMs;
590
+ this.name = "HealthRequestTimedOut";
591
+ }
592
+ };
593
+ /** The most of a body read — a sitemap may be 50 MB, and none needs to be. */
594
+ const EDGE_BODY_LIMIT = 10485760;
595
+ /** A body larger than {@link EDGE_BODY_LIMIT}. */
596
+ var EdgeResponseTooLarge = class extends require_errors.GkmError {
597
+ url;
598
+ limit;
599
+ constructor(url, limit) {
600
+ super(`${url} answered with more than ${limit} bytes, which is more than gkm reads. Split it — a sitemap index can list several sitemaps.`);
601
+ this.url = url;
602
+ this.limit = limit;
603
+ this.name = "EdgeResponseTooLarge";
604
+ }
605
+ };
606
+ /**
607
+ * The real request: one GET to the edge — over HTTPS, the certificate
608
+ * verified, for an `https:` URL, and plain HTTP for an `http:` one — with
609
+ * the URL's host as SNI and `Host` wherever it connects.
610
+ */
611
+ const edgeFetch = ({ url, ca, connectTo, connectPort, authorization, timeoutMs, signal, read, headers }) => {
612
+ const target = new URL(url);
613
+ const secure = target.protocol === "https:";
614
+ const request = secure ? node_https.request : node_http.request;
615
+ return new Promise((resolve, reject) => {
616
+ const req = request({
617
+ host: connectTo ?? target.hostname,
618
+ port: connectPort ?? (target.port || (secure ? 443 : 80)),
619
+ ...secure ? { servername: target.hostname } : {},
620
+ path: `${target.pathname}${target.search}`,
621
+ method: "GET",
622
+ headers: {
623
+ ...headers,
624
+ host: target.host,
625
+ ...authorization ? { authorization } : {}
626
+ },
627
+ ...secure && ca ? { ca } : {},
628
+ ...signal ? { signal } : {},
629
+ timeout: timeoutMs
630
+ }, (res) => {
631
+ const answered = {
632
+ status: res.statusCode ?? 0,
633
+ headers: res.headers
634
+ };
635
+ if (!read) {
636
+ res.resume();
637
+ res.on("end", () => resolve({
638
+ ...answered,
639
+ body: ""
640
+ }));
641
+ res.on("error", reject);
642
+ return;
643
+ }
644
+ const chunks = [];
645
+ let size = 0;
646
+ res.on("data", (chunk) => {
647
+ size += chunk.length;
648
+ if (size > 10485760) {
649
+ req.destroy(new EdgeResponseTooLarge(url, EDGE_BODY_LIMIT));
650
+ return;
651
+ }
652
+ chunks.push(chunk);
653
+ });
654
+ res.on("end", () => resolve({
655
+ ...answered,
656
+ body: Buffer.concat(chunks).toString("utf-8")
657
+ }));
658
+ res.on("error", reject);
659
+ });
660
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
661
+ req.on("error", reject);
662
+ req.end();
663
+ });
664
+ };
665
+ /** The real probe: one GET through the edge, answered by its status. */
666
+ const httpsProbe = (request) => edgeFetch(request).then(({ status }) => status);
667
+ /** Whether a status means the app answered as it should. */
668
+ function isHealthy(status) {
669
+ return status >= 200 && status < 400;
670
+ }
671
+ /**
672
+ * Apps that are not healthy. `via` says which check said so:
673
+ * - `edge`: verify asked each app through the edge, by its host, and it did
674
+ * not answer as it should (a worker, with no route, by its container's
675
+ * health);
676
+ * - `docker`: `up --wait` failed, and these containers' own health checks
677
+ * had not passed — the rest of the stack was released and routed first.
678
+ * One class either way, so a caller matches one failure: apps not healthy.
679
+ */
680
+ var ComposeAppsUnhealthy = class extends require_errors.GkmError {
681
+ project;
682
+ apps;
683
+ proxy;
684
+ via;
685
+ constructor(project, apps, proxy = "caddy", via = "edge") {
686
+ const names = apps.map((a) => a.app).join(" ");
687
+ super(via === "docker" ? `${project} started, but ${apps.length === 1 ? "this container's health check has" : "these containers' health checks have"} not passed. The rest of the stack is up and routed:\n` + apps.map(({ app, last }) => ` - ${app}: Docker reports it ${last}`).join("\n") + `\nSee why with \`docker compose -p ${project} ps ${names}\` and \`docker compose -p ${project} logs ${names}\`, fix the app, and deploy again.` : `${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 ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} logs traefik\` and \`docker compose -p ${project} logs ${names}\`.`));
688
+ this.project = project;
689
+ this.apps = apps;
690
+ this.proxy = proxy;
691
+ this.via = via;
692
+ this.name = "ComposeAppsUnhealthy";
693
+ }
694
+ };
695
+ //#endregion
696
+ //#region src/target/compose/startupCheck.ts
697
+ /**
698
+ * The startup check (`gkm compose --stage <stage> --build --check`): every
699
+ * image the build produced, started before anything is pushed.
700
+ *
701
+ * A bundle that builds, typechecks and passes every test can still fail to
702
+ * start — a package that finds its own files at runtime, inlined into the
703
+ * bundle and so not in the image's `node_modules`. Tests run from source,
704
+ * where `node_modules` is, so the first place that shows is the server.
705
+ *
706
+ * So the images are started here, on the machine that built them, with a
707
+ * deployed stage's real secrets — never fakes, which would prove only that
708
+ * the image starts against the fakes — and the backing services the stack
709
+ * declares (Postgres, Redis, …) started beside them, migrated. Each app,
710
+ * worker and processor must pass its own health check, or the check fails
711
+ * naming it, with its last log lines, and nothing is pushed.
712
+ *
713
+ * The stage is one that is not protected: a check runs on every pull request,
714
+ * and a protected stage's secrets are not handed to one.
715
+ */
716
+ /** The compose project a stage's check runs as, never the stage's own. */
717
+ function checkProject(project) {
718
+ return `${project}-check`;
719
+ }
720
+ /** `--check` with no build: there is nothing built here to start. */
721
+ var StartupCheckNeedsBuild = class extends require_errors.GkmError {
722
+ constructor() {
723
+ super("--check starts the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --check.");
724
+ this.name = "StartupCheckNeedsBuild";
725
+ }
726
+ };
727
+ /** `--check` of a stage that is not deployed: it has no real secrets. */
728
+ var StartupCheckNeedsDeployedStage = class extends require_errors.GkmError {
729
+ stage;
730
+ deployed;
731
+ constructor(stage, deployed) {
732
+ super(`'${stage}' is not a deployed stage, and a startup check runs with a deployed stage's real secrets. Check one of the deployed stages that is not protected: ${deployed.join(", ") || "(none is declared)"}.`);
733
+ this.stage = stage;
734
+ this.deployed = deployed;
735
+ this.name = "StartupCheckNeedsDeployedStage";
736
+ }
737
+ };
738
+ /** `--check` of a protected stage, whose secrets a check is never given. */
739
+ var StartupCheckStageProtected = class extends require_errors.GkmError {
740
+ stage;
741
+ checkable;
742
+ constructor(stage, checkable) {
743
+ super(`'${stage}' is protected (stages.protected), and a startup check is never given a protected stage's secrets: it runs on every pull request. ` + (checkable.length > 0 ? `Check ${checkable.map((s) => `'${s}'`).join(" or ")} instead.` : "Declare a deployed stage that is not protected, and check that."));
744
+ this.stage = stage;
745
+ this.checkable = checkable;
746
+ this.name = "StartupCheckStageProtected";
747
+ }
748
+ };
749
+ /** Images that did not start: each one, what Docker said, and its logs. */
750
+ var StartupCheckFailed = class extends require_errors.GkmError {
751
+ stage;
752
+ apps;
753
+ constructor(stage, apps) {
754
+ const one = apps.length === 1;
755
+ super(`${one ? "This image" : "These images"} did not start with '${stage}''s secrets, so nothing was pushed:\n` + apps.map(({ app, last, logs }) => ` - ${app}: Docker reports it ${last}` + (logs ? `. Its last lines:\n${logs.split("\n").map((line) => ` ${line}`).join("\n")}` : ", and it logged nothing.")).join("\n") + `\nA package that reads its own files at runtime is bundled without them: run the image with \`gkm compose --stage ${stage} --build --check\` until ${one ? "it starts" : "they start"}.`);
756
+ this.stage = stage;
757
+ this.apps = apps;
758
+ this.name = "StartupCheckFailed";
759
+ }
760
+ };
761
+ /**
762
+ * Refuse a check gkm cannot run honestly: one that builds nothing, of a stage
763
+ * with no real secrets, or of a protected stage.
764
+ */
765
+ function assertCheckable(workspace, stage, mode) {
766
+ if (mode !== "build") throw new StartupCheckNeedsBuild();
767
+ const { deployed, protected: kept = [] } = workspace.stages;
768
+ const checkable = deployed.filter((name) => !kept.includes(name));
769
+ if (!deployed.includes(stage)) throw new StartupCheckNeedsDeployedStage(stage, checkable);
770
+ if (kept.includes(stage)) throw new StartupCheckStageProtected(stage, checkable);
771
+ }
772
+ //#endregion
773
+ //#region src/target/compose/topicSubscriptions.ts
774
+ /**
775
+ * Every topic subscriber the stack pushes to: a subscriber whose connection
776
+ * key is a topic's publisher string — a bucket's events key is not — and
777
+ * whose value on this stage is an SNS one.
778
+ */
779
+ function topicPushes(stack, manifest) {
780
+ const topicKeys = new Set(Object.values(manifest).filter((declaration) => declaration.kind === "topic").map((topic) => (0, _geekmidas_manifest.providedKeyFor)(topic.id, topic.kind, "publisherConnectionString")));
781
+ const pushes = [];
782
+ for (const worker of stack.workers) for (const subscriber of worker.push?.subscribers ?? []) {
783
+ if (!topicKeys.has(subscriber.connectionKey)) continue;
784
+ const connectionString = worker.env?.[subscriber.connectionKey];
785
+ if (!connectionString?.startsWith("sns:")) continue;
786
+ pushes.push({
787
+ worker: worker.id,
788
+ name: subscriber.name,
789
+ endpoint: subscriber.endpoint,
790
+ connectionKey: subscriber.connectionKey,
791
+ connectionString,
792
+ ...subscriber.events ? { events: subscriber.events } : {}
793
+ });
794
+ }
795
+ return pushes;
796
+ }
797
+ /** The subscriptions recorded for hand-set topics: those with a key. */
798
+ function recordedTopicSubscriptions(resources) {
799
+ return Object.values(resources ?? {}).filter((record) => record.type === "sns-subscription" && typeof record.data?.connectionKey === "string");
800
+ }
801
+ /**
802
+ * Converge each hand-set topic's subscriptions on the subscribers pushed to:
803
+ * subscribe, bring filters up to date, unsubscribe a route on the worker's
804
+ * host no subscriber wants any more — and record each ARN, forgetting what
805
+ * was removed.
806
+ *
807
+ * @returns each worker's subscriptions, by export — what it is handed
808
+ */
809
+ async function ensureTopicSubscriptions(input) {
810
+ const { snsUrl, reconcileHttpSubscriptions } = await import("@geekmidas/events/sns");
811
+ const groups = /* @__PURE__ */ new Map();
812
+ const group = (topicArn, host, connectionKey) => {
813
+ const id = `${topicArn}|${host}`;
814
+ const found = groups.get(id);
815
+ if (found) return found;
816
+ const created = {
817
+ topicArn,
818
+ host,
819
+ connectionKey,
820
+ pushes: [],
821
+ recorded: []
822
+ };
823
+ groups.set(id, created);
824
+ return created;
825
+ };
826
+ for (const push of input.pushes) {
827
+ const { topicArn } = snsUrl.parse(push.connectionString);
828
+ const into = group(topicArn, new URL(push.endpoint).host, push.connectionKey);
829
+ into.connectionString = push.connectionString;
830
+ into.pushes.push(push);
831
+ }
832
+ 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);
833
+ const provisioned = require_snsSubscriptions.provisionedTopics(input.recorded);
834
+ const wanted = new Set(input.pushes.map(({ worker, name }) => require_snsSubscriptions.subscriptionKey(worker, name)));
835
+ const arns = {};
836
+ for (const { topicArn, host, connectionKey, ...members } of groups.values()) {
837
+ const stale = members.recorded.filter((r) => !wanted.has(r.key));
838
+ const named = members.connectionString ?? input.secrets[connectionKey];
839
+ if (!named?.startsWith("sns:")) {
840
+ for (const record of stale) {
841
+ input.log(` – forgot ${record.data?.endpoint}: '${connectionKey}' no longer names an SNS topic to unsubscribe it from`);
842
+ await input.forget(record.key);
843
+ }
844
+ continue;
845
+ }
846
+ const address = new URL(named);
847
+ address.searchParams.set("topicArn", topicArn);
848
+ const connection = await require_snsSubscriptions.topicConnection({
849
+ connectionKey,
850
+ connectionString: address.toString(),
851
+ stage: input.stage,
852
+ env: input.env,
853
+ provisioned: provisioned.has(topicArn)
854
+ });
855
+ const result = await reconcileHttpSubscriptions(connection, {
856
+ endpoints: members.pushes.map((push) => ({
857
+ name: push.name,
858
+ endpoint: push.endpoint,
859
+ ...push.events ? { events: push.events } : {}
860
+ })),
861
+ ownedHost: host
862
+ });
863
+ await connection.close();
864
+ for (const push of members.pushes) {
865
+ const arn = result.subscriptions[push.name];
866
+ const key = require_snsSubscriptions.subscriptionKey(push.worker, push.name);
867
+ if (input.recorded?.[key]?.id !== arn) input.log(` ✓ '${push.name}' subscribed to ${topicArn.split(":").pop()} at ${push.endpoint}`);
868
+ await input.record(require_snsSubscriptions.subscriptionResource({
869
+ worker: push.worker,
870
+ name: push.name,
871
+ topicArn,
872
+ endpoint: push.endpoint,
873
+ connectionKey: push.connectionKey,
874
+ pending: result.pending.includes(push.name),
875
+ ...push.events ? { events: push.events } : {}
876
+ }, arn));
877
+ arns[push.worker] = {
878
+ ...arns[push.worker],
879
+ [push.name]: arn
880
+ };
881
+ }
882
+ for (const arn of result.removed) input.log(` – unsubscribed ${arn}: no subscriber wants it any more`);
883
+ for (const record of stale) await input.forget(record.key);
884
+ }
885
+ return arns;
886
+ }
887
+ /**
888
+ * How long one page has to answer: a first render fetches from the site's
889
+ * APIs, so it is given longer than a health check is.
890
+ */
891
+ const WARMUP_TIMEOUT_MS = 3e4;
892
+ /**
893
+ * Next's on-demand revalidation header: a request carrying the build's
894
+ * preview-mode id is rendered afresh whatever the page's cache says.
895
+ */
896
+ const NEXT_REVALIDATE_HEADER = "x-prerender-revalidate";
897
+ /**
898
+ * What Next answered a request from: `HIT` and `STALE` are a cached copy —
899
+ * on a fresh deploy, the build's — and the request rendered nothing.
900
+ */
901
+ const NEXT_CACHE_HEADER = "x-nextjs-cache";
902
+ const FROM_CACHE = /* @__PURE__ */ new Set(["HIT", "STALE"]);
903
+ /**
904
+ * Asks the site for its `/sitemap.xml` — a sitemap index's sitemaps followed
905
+ * one level — then for `/` and every page it lists, up to `maxUrls` pages in
906
+ * all, `concurrency` at a time. The sitemap comes first so that, rendered
907
+ * again with `headers`, it lists what the deployed APIs hold. Only pages on
908
+ * the site's own origin are asked: a sitemap may list another's, which this
909
+ * deploy did not start.
910
+ */
911
+ async function warmSite(options) {
912
+ const { fetch, edge = {}, maxUrls = 500, concurrency = 4, timeoutMs = WARMUP_TIMEOUT_MS, headers } = options;
913
+ const origin = new URL(options.url).origin;
914
+ const result = {
915
+ warmed: [],
916
+ cached: [],
917
+ warnings: [],
918
+ leftOut: 0
919
+ };
920
+ /** One GET; a failure is a warning, and `undefined`. */
921
+ const get = async (url, read) => {
922
+ try {
923
+ const response = await fetch({
924
+ url,
925
+ ...edge,
926
+ ...headers ? { headers } : {},
927
+ timeoutMs,
928
+ read
929
+ });
930
+ const cache = response.headers?.[NEXT_CACHE_HEADER];
931
+ if (typeof cache === "string" && FROM_CACHE.has(cache.toUpperCase())) result.cached.push(url);
932
+ return response;
933
+ } catch (error) {
934
+ if (edge.signal?.aborted) throw error;
935
+ result.warnings.push({
936
+ url,
937
+ reason: error instanceof HealthRequestTimedOut ? `no answer within ${error.timeoutMs}ms` : error instanceof Error ? error.message : String(error)
938
+ });
939
+ return;
940
+ }
941
+ };
942
+ const warm = async (url) => {
943
+ const response = await get(url, false);
944
+ if (!response) return;
945
+ if (isHealthy(response.status)) result.warmed.push(url);
946
+ else result.warnings.push({
947
+ url,
948
+ reason: `HTTP ${response.status}`
949
+ });
950
+ };
951
+ /** A sitemap's `<loc>`s, or none where it has none — or did not answer. */
952
+ const sitemap = async (url) => {
953
+ const response = await get(url, true);
954
+ if (!response) return void 0;
955
+ if (response.status >= 400 && response.status < 500) return void 0;
956
+ if (!isHealthy(response.status)) {
957
+ result.warnings.push({
958
+ url,
959
+ reason: `HTTP ${response.status}`
960
+ });
961
+ return;
962
+ }
963
+ return readSitemap(response.body);
964
+ };
965
+ const root = `${origin}/`;
966
+ const pages = /* @__PURE__ */ new Set([root]);
967
+ const sameOrigin = (loc) => {
968
+ if (!URL.canParse(loc, root)) return void 0;
969
+ const url = new URL(loc, root);
970
+ url.hash = "";
971
+ return url.origin === origin ? url.href : void 0;
972
+ };
973
+ const list = (locs) => {
974
+ for (const loc of locs) {
975
+ const url = sameOrigin(loc);
976
+ if (url) pages.add(url);
977
+ }
978
+ };
979
+ const top = await sitemap(`${origin}/sitemap.xml`);
980
+ if (top?.kind === "index") {
981
+ const read = await pool([...new Set(top.locs.map(sameOrigin).filter((u) => u !== void 0))], concurrency, sitemap);
982
+ for (const child of read) if (child?.kind === "urlset") list(child.locs);
983
+ } else if (top) list(top.locs);
984
+ await warm(root);
985
+ const listed = [...pages].slice(1);
986
+ const room = Math.max(0, maxUrls - 1);
987
+ result.leftOut = Math.max(0, listed.length - room);
988
+ await pool(listed.slice(0, room), concurrency, warm);
989
+ return result;
990
+ }
991
+ /**
992
+ * Prints the preview-mode id of the prerender manifest at `argv[1]`, and
993
+ * nothing else of it: the manifest's signing and encryption keys never leave
994
+ * the container. Exit 3 when the manifest has no id.
995
+ */
996
+ const PRINT_PREVIEW_MODE_ID = [
997
+ "let m;",
998
+ "try { m = JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8')); }",
999
+ "catch (e) { process.stderr.write(String(e && e.message)); process.exit(2); }",
1000
+ "const id = m && m.preview && m.preview.previewModeId;",
1001
+ "if (typeof id !== 'string' || id === '') process.exit(3);",
1002
+ "process.stdout.write(id);"
1003
+ ].join(" ");
1004
+ /**
1005
+ * The preview-mode id of a running Next site, from the prerender manifest
1006
+ * of its image — `manifest`, a path inside the container — by running the
1007
+ * image's own `node` in it through `exec` (`docker exec`, on whichever
1008
+ * engine runs the stack). Never read from this machine's disk: the image
1009
+ * that runs is the one whose id counts.
1010
+ *
1011
+ * The id is a secret of the site's: it is returned to the warm-up and
1012
+ * nowhere else — never logged, never written.
1013
+ */
1014
+ async function nextPreviewModeId(exec, manifest) {
1015
+ const { code, stdout, stderr } = await exec([
1016
+ "node",
1017
+ "-e",
1018
+ PRINT_PREVIEW_MODE_ID,
1019
+ manifest
1020
+ ]);
1021
+ if (code === 0 && stdout) return { id: stdout };
1022
+ if (code === 3 || code === 0) return { reason: `${manifest} has no preview.previewModeId, which this version of Next may not write` };
1023
+ const said = stderr.trim().split("\n")[0];
1024
+ if (code === null) return { reason: said || "its container is not running" };
1025
+ return { reason: `could not read ${manifest} in its container (${said || `exit ${code}`})` };
1026
+ }
1027
+ /**
1028
+ * Reads a sitemap (sitemaps.org): each entry's `<loc>`, entity-decoded or
1029
+ * from CDATA. Only an unprefixed `<loc>` is an entry's — an `<image:loc>` is
1030
+ * an image on a page, not a page.
1031
+ */
1032
+ function readSitemap(xml) {
1033
+ const kind = /<(?:[\w-]+:)?sitemapindex[\s>]/.test(xml) ? "index" : "urlset";
1034
+ const locs = [];
1035
+ for (const match of xml.matchAll(/<loc>\s*(?:<!\[CDATA\[([\s\S]*?)\]\]>|([\s\S]*?))\s*<\/loc>/g)) {
1036
+ const loc = match[1] ?? decodeEntities(match[2] ?? "");
1037
+ if (loc.trim()) locs.push(loc.trim());
1038
+ }
1039
+ return {
1040
+ kind,
1041
+ locs
1042
+ };
1043
+ }
1044
+ const ENTITIES = {
1045
+ amp: "&",
1046
+ lt: "<",
1047
+ gt: ">",
1048
+ quot: "\"",
1049
+ apos: "'"
1050
+ };
1051
+ function decodeEntities(text) {
1052
+ return text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (whole, entity) => {
1053
+ if (entity[0] === "#") {
1054
+ const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
1055
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
1056
+ }
1057
+ return ENTITIES[entity.toLowerCase()] ?? whole;
1058
+ });
1059
+ }
1060
+ /** Each item through `run`, at most `size` at once, results in order. */
1061
+ async function pool(items, size, run) {
1062
+ const results = new Array(items.length);
1063
+ let next = 0;
1064
+ const worker = async () => {
1065
+ while (next < items.length) {
1066
+ const index = next++;
1067
+ results[index] = await run(items[index]);
1068
+ }
1069
+ };
1070
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker));
1071
+ return results;
1072
+ }
1073
+ //#endregion
1074
+ //#region src/target/compose/phases.ts
1075
+ /**
1076
+ * The compose target's phases: a stage as one Docker Compose stack behind
1077
+ * Caddy — the local stage on this machine's Docker, a deployed stage on its
1078
+ * server's, driven over SSH (`compose/server.ts`) from wherever the deploy
1079
+ * runs.
1080
+ *
1081
+ * The order is the point of this file, and the rules it keeps are these:
1082
+ *
1083
+ * - A tag is checked before anything happens (`validate`). Every app's image
1084
+ * is asked of the registry first; one missing image stops the run naming
1085
+ * them all, and nothing is written, pulled or started.
1086
+ * - The databases exist before the apps do (`provision`). Postgres comes up
1087
+ * alone, its databases, roles and grants are created, its migrations
1088
+ * applied and its seeds run from this machine — through an SSH tunnel to a
1089
+ * server's loopback — and only then do the apps
1090
+ * start — so an app
1091
+ * never boots against a schema that is not there yet.
1092
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
1093
+ * was released under and the digest it resolved to are written to the
1094
+ * stage's state, so "what is this stage running" has an exact answer.
1095
+ * - What was started answers (`verify`): each app is asked through Caddy,
1096
+ * over HTTPS, with the certificate verified. Then each server-rendered site
1097
+ * is warmed (`warmup.ts`): a page that fails to warm is said, never failed.
1098
+ *
1099
+ * Every image is built inside Docker from a pruned slice of the build root —
1100
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
1101
+ * machine before `docker compose build`.
1102
+ *
1103
+ * Docker, the registry, Postgres and the health probe are
1104
+ * injected, so the rules are asserted without a daemon; the defaults are the
1105
+ * real ones.
1106
+ */
1107
+ /** `--push` without `--build`: there is nothing built here to push. */
1108
+ var ComposePushNeedsBuild = class extends require_errors.GkmError {
1109
+ constructor() {
1110
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
1111
+ this.name = "ComposePushNeedsBuild";
1112
+ }
1113
+ };
1114
+ /** Digests to run by, on a run that pulls nothing. */
1115
+ var ComposePinNeedsPull = class extends require_errors.GkmError {
1116
+ constructor() {
1117
+ 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.");
1118
+ this.name = "ComposePinNeedsPull";
1119
+ }
1120
+ };
1121
+ /**
1122
+ * A site that pre-renders against its stage (`prerender: 'stage'`) whose
1123
+ * APIs do not answer, so it is not built: pages built without their data
1124
+ * would ship, and nothing at runtime could fill them.
1125
+ */
1126
+ var SitePrerenderApisDown = class extends require_errors.GkmError {
1127
+ site;
1128
+ apis;
1129
+ via;
1130
+ constructor(site, apis, via) {
1131
+ const lines = apis.map(({ app, url, last }) => via === "docker" ? ` - ${app}: Docker reports it ${last}` : ` - ${url}: ${last}`).join("\n");
1132
+ super(`'${site}' pre-renders from its stage's APIs (prerender: 'stage'), and ${apis.length === 1 ? "this one does" : "these do"} not answer, so it was not built:\n${lines}\n` + (via === "push" ? "An image pushed for it is built against the stage as it runs now: deploy the stage first, then build and push the site." : "Fix the API and deploy again."));
1133
+ this.site = site;
1134
+ this.apis = apis;
1135
+ this.via = via;
1136
+ this.name = "SitePrerenderApisDown";
1137
+ }
1138
+ };
1139
+ /** A build with no commit to tag its images with. */
1140
+ var NoGitRevision = class extends require_errors.GkmError {
1141
+ root;
1142
+ constructor(root) {
1143
+ 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.`);
1144
+ this.root = root;
1145
+ this.name = "NoGitRevision";
1146
+ }
1147
+ };
1148
+ /**
1149
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
1150
+ * at the workspace root. What the generated file cannot know — a port bound
1151
+ * to a tailnet address, another log driver — goes there, and is never
1152
+ * overwritten.
1153
+ */
1154
+ function stackOverrideFile(root, stage) {
1155
+ return (0, node_path.join)(root, `docker-compose.${stage}.yml`);
1156
+ }
1157
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
1158
+ async function gitRevision(root) {
1159
+ let sha;
1160
+ try {
1161
+ sha = (await require_stack.runOutput("git", [
1162
+ "rev-parse",
1163
+ "--short",
1164
+ "HEAD"
1165
+ ], { cwd: root })).trim();
1166
+ } catch {
1167
+ throw new NoGitRevision(root);
1168
+ }
1169
+ if (!sha) throw new NoGitRevision(root);
1170
+ return (await require_stack.runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
1171
+ }
1172
+ /**
1173
+ * The real ones. Each app is asked for three minutes before it counts as
1174
+ * down: a deployed stage's first ACME certificate can take that long.
1175
+ */
1176
+ const defaultDeps = {
1177
+ docker: require_stack.dockerCompose,
1178
+ revision: gitRevision,
1179
+ sql: require_stack.pgClient,
1180
+ buckets: require_stack.bucketClient,
1181
+ logins: require_stack.ensurePostgresLogin,
1182
+ migrate: require_databases.migrateDatabases,
1183
+ seed: require_databases.seedDatabases,
1184
+ probe: httpsProbe,
1185
+ fetch: edgeFetch,
1186
+ healthAttempts: 90,
1187
+ healthIntervalMs: 2e3,
1188
+ env: process.env,
1189
+ lookup: require_snsSubscriptions.systemLookup,
1190
+ server: sshAccess
1191
+ };
1192
+ /**
1193
+ * The stack the stage would run, and — for a tag — the registry's word that
1194
+ * every image it names exists. Nothing is written: a missing image stops the
1195
+ * run here, before a file, a secret or a container is touched.
1196
+ */
1197
+ async function validateCompose(ctx, deps, options = {}) {
1198
+ const { workspace, stage, identity, tag } = ctx;
1199
+ const root = workspace.root;
1200
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
1201
+ const push = options.push === true;
1202
+ const check = options.check === true;
1203
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
1204
+ if (check) assertCheckable(workspace, stage, mode);
1205
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
1206
+ const registry = workspace.deploy?.registry;
1207
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", require_credentials.imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, require_credentials.stageTag(tag, stage)));
1208
+ const background = {};
1209
+ const subscribers = {};
1210
+ const manifest = await require_discover.discover({
1211
+ patterns: require_stack.constructGlobs(workspace),
1212
+ cwd: root,
1213
+ background,
1214
+ subscribers
1215
+ });
1216
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
1217
+ const recorded = push || check ? void 0 : await ctx.state.read(stage);
1218
+ const layout = mode === "build" ? require_stack.imageLayout(workspace) : void 0;
1219
+ const input = {
1220
+ workspace,
1221
+ manifest,
1222
+ background,
1223
+ subscribers,
1224
+ stage,
1225
+ identity,
1226
+ images: {
1227
+ mode,
1228
+ tag,
1229
+ ...registry ? { registry } : {}
1230
+ },
1231
+ secrets,
1232
+ ...stage === workspace.stages.local ? { localCredentials: (await require_credentials$1.loadLocalCredentials(workspace)).credentials } : {},
1233
+ allowDevServices: ctx.allowDevServices,
1234
+ ports: require_stack.edgePorts(deps.env),
1235
+ ...layout ? { layout } : {},
1236
+ ...push && !check ? { buildOnly: true } : {},
1237
+ ...mode === "build" ? { prerenderRun: (/* @__PURE__ */ new Date()).toISOString() } : {}
1238
+ };
1239
+ const recordedArns = require_snsSubscriptions.recordedPushSubscriptions(recorded?.resources);
1240
+ const planned = push || check ? void 0 : require_stack.composeStack({
1241
+ ...input,
1242
+ recordingSubscriptions: true
1243
+ });
1244
+ const pushes = planned ? topicPushes(planned, manifest) : [];
1245
+ const topics = planned && (pushes.length > 0 || recordedTopicSubscriptions(recorded?.resources).length > 0) ? {
1246
+ pushes,
1247
+ recorded: recorded?.resources
1248
+ } : void 0;
1249
+ const composed = topics && planned ? planned : require_stack.composeStack({
1250
+ ...input,
1251
+ pushSubscriptions: recordedArns
1252
+ });
1253
+ if (mode === "build") assertRedisClient(workspace, composed, manifest);
1254
+ const pinned = (unpinned) => options.pin ? withPinnedImages(unpinned, options.pin.file, options.pin.digests) : unpinned;
1255
+ const stack = pinned(composed);
1256
+ for (const warning of stack.warnings) ctx.logger.warn(`⚠ ${warning}`);
1257
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, require_credentials.stageTag(tag, stage), [
1258
+ ...stack.apps,
1259
+ ...stack.workers,
1260
+ ...stack.processors
1261
+ ]);
1262
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
1263
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
1264
+ ctx.secrets.mask(stack.logs.password);
1265
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
1266
+ }
1267
+ if (!push && !check && !stack.local) {
1268
+ require_snsSubscriptions.requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
1269
+ if (stack.proxy === "traefik" && dnsChallenged(stack)) {
1270
+ const zone = require_stack.acmeDnsZone(workspace, stage);
1271
+ if (zone) require_stack.acmeDnsSecrets(zone, stage, secrets?.custom);
1272
+ }
1273
+ }
1274
+ const server = push || check ? void 0 : composeServer({
1275
+ stage,
1276
+ local: stack.local,
1277
+ config: workspace.deploy?.compose?.server,
1278
+ custom: secrets?.custom
1279
+ });
1280
+ const dir = (0, node_path.join)(root, require_stack.stackDir(stage));
1281
+ const override = stackOverrideFile(root, stage);
1282
+ const overrides = (0, node_fs.existsSync)(override) ? [override] : [];
1283
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
1284
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
1285
+ const { ref, tag, digest } = releases.current;
1286
+ return [name, {
1287
+ ref,
1288
+ ...tag ? { tag } : {},
1289
+ ...digest ? { digest } : {}
1290
+ }];
1291
+ }));
1292
+ return {
1293
+ mode,
1294
+ push,
1295
+ check,
1296
+ stack,
1297
+ ...topics ? { topicSubscriptions: {
1298
+ ...topics,
1299
+ restack: (arns) => {
1300
+ const merged = { ...recordedArns };
1301
+ for (const [worker, own] of Object.entries(arns)) merged[worker] = {
1302
+ ...merged[worker],
1303
+ ...own
1304
+ };
1305
+ return pinned(require_stack.composeStack({
1306
+ ...input,
1307
+ pushSubscriptions: merged
1308
+ }));
1309
+ }
1310
+ } } : {},
1311
+ ...server ? { server } : {},
1312
+ dir,
1313
+ ref: {
1314
+ project: check ? checkProject(require_stack.composeProject(identity)) : require_stack.composeProject(identity),
1315
+ file: (0, node_path.join)(dir, "docker-compose.yml"),
1316
+ ...overrides.length > 0 ? { overrides } : {},
1317
+ cwd: root,
1318
+ ...server ? { host: dockerHost(server) } : {},
1319
+ output: ctx.childOutput,
1320
+ signal: ctx.signal
1321
+ },
1322
+ secrets,
1323
+ generated,
1324
+ previous,
1325
+ files: [],
1326
+ images: {},
1327
+ changes: []
1328
+ };
1329
+ }
1330
+ /**
1331
+ * What only a compose deploy checks before it changes anything, once the
1332
+ * stage's own keys are: the stage's own certificate is there, and every
1333
+ * public host points at the stage's server — its records written where a
1334
+ * provider holds them, then confirmed — before Caddy or Traefik ask Let's
1335
+ * Encrypt for a certificate it could not issue. A build-only run never asks.
1336
+ */
1337
+ async function readyCompose(ctx, run, deps) {
1338
+ const { stack } = run;
1339
+ if (stack.tls) {
1340
+ const { certFile, keyFile, caFile } = stack.tls;
1341
+ for (const file of [
1342
+ certFile,
1343
+ keyFile,
1344
+ ...caFile ? [caFile] : []
1345
+ ]) if (!(0, node_fs.existsSync)(file)) throw new require_workspace.ComposeTlsFileMissing(ctx.stage, file);
1346
+ }
1347
+ if (stack.cdn?.certificate === "origin" && !buildsOnly(run)) {
1348
+ const issued = await ensureOriginCertificate({
1349
+ stage: ctx.stage,
1350
+ zone: stack.cdn.zone,
1351
+ hosts: stack.cdn.hosts,
1352
+ custom: run.secrets?.custom,
1353
+ credentials: ctx.credentials,
1354
+ keep: (values) => keepStageSecrets(ctx, run, values),
1355
+ ...ctx.dryRun ? { dryRun: true } : {},
1356
+ log: (line) => ctx.logger.info(line),
1357
+ ...deps.originIssuer ? { issuer: deps.originIssuer } : {}
1358
+ });
1359
+ if (issued) {
1360
+ ctx.secrets.mask(issued.key);
1361
+ run.originCertificate = issued;
1362
+ }
1363
+ }
1364
+ if (stack.local) {
1365
+ await edgeHostsFree(ctx, run, deps);
1366
+ return;
1367
+ }
1368
+ if (run.server && !ctx.dryRun && !run.push) await deps.server.check(run.server);
1369
+ await edgeHostsFree(ctx, run, deps);
1370
+ await logsPortOnServer(ctx, run, deps);
1371
+ const prune = await stageHostsDns(ctx, deps, require_snsSubscriptions.stackHosts(stack).filter((host) => !require_snsSubscriptions.isLocalHost(host)), run.secrets?.custom, stack.wildcard?.host, stack.cdn?.hosts);
1372
+ if (prune) run.pruneDns = prune;
1373
+ }
1374
+ /**
1375
+ * No host the stack routes through the shared edge is routed there by another
1376
+ * project — asked of the edge on the stage's engine before a record, a
1377
+ * secret, an image or a container is touched, so a clash fails the deploy
1378
+ * with nothing changed. Asked again as the routes are written
1379
+ * (`writeEdgeRoutes`), for an edge that was not running yet.
1380
+ */
1381
+ async function edgeHostsFree(ctx, run, deps) {
1382
+ const { stack, ref } = run;
1383
+ if (ctx.dryRun || run.push) return;
1384
+ if (stack.proxy !== "traefik" || !stack.traefik) return;
1385
+ await require_stack.assertEdgeHostsFree(deps.docker, require_stack.edgeRef(edgeFile(run), {
1386
+ ...ref.host ? { host: ref.host } : {},
1387
+ ...ref.output ? { output: ref.output } : {}
1388
+ }), stack.project, stack.traefik);
1389
+ }
1390
+ /** How many ports past the first a stage's OpenObserve is tried on. */
1391
+ const LOGS_PORT_TRIES = 100;
1392
+ /**
1393
+ * The loopback port the stack's OpenObserve is published on, settled against
1394
+ * what every other stack on the server publishes — before anything is
1395
+ * written, so two stages on one machine cannot both take `5080` and fail at
1396
+ * `up`.
1397
+ *
1398
+ * - A port the stage named is refused when another project holds it.
1399
+ * - Otherwise the stack keeps the port it already publishes, or takes the
1400
+ * first from the default up that no other project holds — and the stack,
1401
+ * its tunnel line included, is moved onto it.
1402
+ *
1403
+ * Asked of the server's engine, so not on a dry run, a push, or the local
1404
+ * stage; nor for a log UI served through the edge, which publishes nothing.
1405
+ *
1406
+ * @throws {LogsPortTaken}
1407
+ */
1408
+ async function logsPortOnServer(ctx, run, deps) {
1409
+ const logs = run.stack.logs;
1410
+ if (!logs || logs.public || run.stack.local) return;
1411
+ if (ctx.dryRun || run.push || !run.server) return;
1412
+ const engine = run.ref.host ? { host: run.ref.host } : {};
1413
+ const project = run.ref.project;
1414
+ const holder = async (port) => {
1415
+ const others = (await deps.docker.publishers(engine, port)).filter((held) => held.project !== project);
1416
+ return others[0] && (others[0].project ?? others[0].container);
1417
+ };
1418
+ if (logs.portSet) {
1419
+ const taken = await holder(logs.port);
1420
+ if (taken) throw new require_credentials$1.LogsPortTaken(ctx.stage, logs.port, taken, true);
1421
+ return;
1422
+ }
1423
+ const kept = await deps.docker.published(engine, project, require_credentials$1.LOGS_SERVICE, require_workspace.LOGS_PORT);
1424
+ let port = kept;
1425
+ if (port === void 0) {
1426
+ let taken;
1427
+ for (let next = logs.port; next < logs.port + LOGS_PORT_TRIES; next++) {
1428
+ taken = await holder(next);
1429
+ if (!taken) {
1430
+ port = next;
1431
+ break;
1432
+ }
1433
+ }
1434
+ if (port === void 0) throw new require_credentials$1.LogsPortTaken(ctx.stage, logs.port, taken ?? "", false);
1435
+ }
1436
+ if (port !== logs.port) {
1437
+ ctx.logger.info(kept === void 0 ? `📜 OpenObserve: ${logs.port} is another stack's on this server, so "${ctx.stage}" publishes ${port}` : `📜 OpenObserve: "${ctx.stage}" keeps ${port}, the port it already publishes`);
1438
+ run.stack = require_stack.withLogsPort(run.stack, port);
1439
+ }
1440
+ }
1441
+ /** A stack whose caches are in Redis, built for an app that has no client. */
1442
+ var RedisClientMissing = class extends require_errors.GkmError {
1443
+ apps;
1444
+ constructor(apps) {
1445
+ 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`);
1446
+ this.apps = apps;
1447
+ this.name = "RedisClientMissing";
1448
+ }
1449
+ };
1450
+ /**
1451
+ * Every backend and worker image whose process reaches a cache can resolve
1452
+ * `ioredis` — listed by its app or a directory above it, the way Node and
1453
+ * the image's install find it. A process that reaches no cache registers no
1454
+ * cache driver, so it needs no client.
1455
+ */
1456
+ function assertRedisClient(workspace, stack, manifest) {
1457
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
1458
+ const cacheKeys = Object.values(manifest).filter((d) => d.kind === "cache").flatMap((d) => d.provides ?? []);
1459
+ const reachesCache = (keys) => cacheKeys.some((key) => keys?.has(key));
1460
+ const missing = [.../* @__PURE__ */ new Set([...stack.apps.filter((app) => (app.kind === "rest-api" || app.kind === "websocket-api") && reachesCache(require_stack.appEnvKeys(manifest, app.name))).map((a) => a.name), ...stack.workers.filter((worker) => reachesCache(require_stack.workerEnvKeys(manifest, worker.id))).map((worker) => worker.host)])].filter((name) => {
1461
+ const app = workspace.apps[name];
1462
+ return app && !require_drivers.installedFrom((0, node_path.join)(workspace.root, app.path), "ioredis");
1463
+ }).sort();
1464
+ if (missing.length > 0) throw new RedisClientMissing(missing);
1465
+ }
1466
+ /**
1467
+ * The deploy's DNS step, for a deployed stage: its server's address — required
1468
+ * where it serves a real domain — then its own hosts written through each
1469
+ * domain's provider in `dns` where they differ, read back from it, and
1470
+ * recorded in the stage's state; hosts no provider writes resolved with the
1471
+ * system resolver. A dry run prints the plan and writes nothing, and warns
1472
+ * rather than stops. Returns the prune of the records gkm wrote for hosts the
1473
+ * stage no longer serves — which a dry run prints there and then.
1474
+ *
1475
+ * @throws {ServerAddressMissing} when the stage has a domain and no address
1476
+ * @throws {ServerAddressInvalid} for a value that is not an address
1477
+ * @throws {HostNotPointingAtServer} when a host is not the server
1478
+ */
1479
+ /**
1480
+ * The records the stack's DNS step weighs against its plan: every one gkm
1481
+ * wrote for the stage's hosts, and each a provider asked for on an earlier
1482
+ * deploy and not on this one — which the plan does not have either, so it is
1483
+ * pruned once the stack answers. One a provider asked for this run is not
1484
+ * the stack's to prune; nor is any provider's, when the providers did not
1485
+ * run.
1486
+ */
1487
+ function recordedForStack(recorded, providerDns) {
1488
+ const asked = new Set(providerDns ?? []);
1489
+ return recorded.filter((record) => record.source !== "provider" || providerDns !== void 0 && !asked.has(require_seeds.dnsResourceKey(record.fqdn, record.type)));
1490
+ }
1491
+ async function stageHostsDns(ctx, deps, hosts, custom, wildcard, proxied) {
1492
+ const { workspace, stage } = ctx;
1493
+ const server = require_snsSubscriptions.requiredServerAddress(stage, workspace.domains?.[stage], custom);
1494
+ if (hosts.length === 0) return;
1495
+ if (ctx.skipDns) {
1496
+ ctx.logger.info("🌐 DNS skipped (--skip-dns): no record is written or checked");
1497
+ return;
1498
+ }
1499
+ if (!server) {
1500
+ ctx.logger.info(`🌐 DNS skipped: no ${require_workspace.SERVER_IPV4_KEY} in '${stage}''s secrets — ${require_snsSubscriptions.serverAddressHint(stage)}`);
1501
+ return;
1502
+ }
1503
+ const log = (line) => ctx.logger.info(line);
1504
+ if (workspace.dns) log(`🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${ctx.dryRun ? " (dry run — nothing is written)" : ""}`);
1505
+ try {
1506
+ const stored = await ctx.state.read(stage);
1507
+ const result = await require_snsSubscriptions.stageDns({
1508
+ stage,
1509
+ hosts,
1510
+ server,
1511
+ dns: workspace.dns,
1512
+ recorded: recordedForStack(require_seeds.dnsResources(stored?.resources ?? {}), ctx.providerDns),
1513
+ ...wildcard ? { wildcard } : {},
1514
+ ...proxied?.length ? { proxied } : {},
1515
+ credentials: ctx.credentials,
1516
+ log,
1517
+ lookup: deps.lookup ?? require_snsSubscriptions.systemLookup,
1518
+ ...ctx.dryRun ? { dryRun: true } : {},
1519
+ ...deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}
1520
+ });
1521
+ if (!ctx.dryRun) {
1522
+ const journal = await require_seeds.DeployJournal.open(ctx.state, stage, () => require_stack.createComposeState(stage));
1523
+ const providers = new Map(result.plan.domains.map((d) => [d.domain, d.provider]));
1524
+ await require_seeds.recordDnsChanges(journal, result.changes, (domain) => providers.get(domain));
1525
+ }
1526
+ 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);
1527
+ if (parts.length > 0) log(`🌐 ${parts.join(", ")}`);
1528
+ if (ctx.dryRun) {
1529
+ await result.prune();
1530
+ return;
1531
+ }
1532
+ return result.recorded.stale.length > 0 ? result.prune : void 0;
1533
+ } catch (error) {
1534
+ if (ctx.dryRun && error instanceof require_snsSubscriptions.HostNotPointingAtServer) {
1535
+ ctx.logger.warn(`⚠ ${error.message}`);
1536
+ return;
1537
+ }
1538
+ throw error;
1539
+ }
1540
+ }
1541
+ /**
1542
+ * The records gkm wrote for hosts the stage no longer serves, deleted once it
1543
+ * answers on its new ones — and forgotten from its state, deleted or not:
1544
+ * none is gkm's to manage any more.
1545
+ */
1546
+ async function pruneStageDns(ctx, run) {
1547
+ if (!run.pruneDns) return;
1548
+ const pruned = await run.pruneDns();
1549
+ const journal = await require_seeds.DeployJournal.open(ctx.state, ctx.stage, () => require_stack.createComposeState(ctx.stage));
1550
+ for (const { record } of pruned) await require_seeds.forgetDnsResource(journal, record);
1551
+ const deleted = pruned.filter((p) => p.action === "delete").length;
1552
+ if (deleted > 0) ctx.logger.info(`🌐 ${deleted} record${deleted === 1 ? "" : "s"} deleted`);
1553
+ }
1554
+ /**
1555
+ * The stage's secrets — and, for a deployed stage, everything it generates
1556
+ * once: its seed, and each declared secret and keyring. Kept only once the
1557
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
1558
+ * leaves the stage's secrets as it found them.
1559
+ */
1560
+ async function stageSecrets(ctx, manifest) {
1561
+ const stored = await ctx.secrets.read();
1562
+ if (ctx.stage === ctx.workspace.stages.local) return {
1563
+ secrets: stored,
1564
+ generated: []
1565
+ };
1566
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
1567
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
1568
+ for (const [key, value] of Object.entries(secrets.custom ?? {})) if (!require_workspace.isReservedStageKey(key) && key !== "ZO_ROOT_USER_EMAIL") ctx.secrets.mask(value);
1569
+ return {
1570
+ secrets,
1571
+ generated
1572
+ };
1573
+ }
1574
+ /**
1575
+ * The stack with each app's and worker's image pinned to the digest the file
1576
+ * names: the refs it is checked, pulled and recorded by, and the image each
1577
+ * compose service runs.
1578
+ */
1579
+ function withPinnedImages(stack, file, digests) {
1580
+ const apps = pinImages(file, digests, stack.apps);
1581
+ const workers = pinImages(file, digests, stack.workers);
1582
+ const processors = pinImages(file, digests, stack.processors);
1583
+ const services = { ...stack.compose.services };
1584
+ for (const image of [
1585
+ ...apps,
1586
+ ...workers,
1587
+ ...processors
1588
+ ]) services[image.name] = {
1589
+ ...services[image.name],
1590
+ image: image.ref
1591
+ };
1592
+ return {
1593
+ ...stack,
1594
+ apps,
1595
+ workers,
1596
+ processors,
1597
+ compose: {
1598
+ ...stack.compose,
1599
+ services
1600
+ }
1601
+ };
1602
+ }
1603
+ /**
1604
+ * A dry run: the stack's files, written so they can be read, and what a real
1605
+ * run would do — no image is built or pulled, no container touched, nothing
1606
+ * recorded and no secret kept.
1607
+ */
1608
+ async function planCompose(ctx, run) {
1609
+ 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.`);
1610
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack, run.originCertificate);
1611
+ printPlan(ctx, run);
1612
+ if (!run.push && run.stack.infra.includes("postgres")) require_seeds.reportPlannedSeeds((await require_databases.plannedSeeds({
1613
+ root: ctx.workspace.root,
1614
+ manifest: ctx.manifest
1615
+ })).map(({ target, seeds }) => ({
1616
+ folder: target.seeds,
1617
+ seeds
1618
+ })), (line) => ctx.logger.info(line));
1619
+ const planned = (change) => {
1620
+ run.changes.push(change);
1621
+ ctx.emit({
1622
+ type: "resource.planned",
1623
+ ...change
1624
+ });
1625
+ };
1626
+ for (const service of run.push ? [] : run.stack.infra) planned({
1627
+ key: `service:${service}`,
1628
+ resourceType: "service",
1629
+ action: "ensure"
1630
+ });
1631
+ for (const app of run.stack.apps) {
1632
+ planned({
1633
+ key: `image:${app.name}`,
1634
+ resourceType: "image",
1635
+ action: run.mode === "build" ? "build" : "reuse",
1636
+ id: app.ref
1637
+ });
1638
+ if (run.push) continue;
1639
+ planned({
1640
+ key: `service:${app.name}`,
1641
+ resourceType: "service",
1642
+ action: run.previous[app.name] ? "reuse" : "create"
1643
+ });
1644
+ }
1645
+ for (const worker of [...run.stack.workers, ...run.stack.processors]) {
1646
+ planned({
1647
+ key: `image:${worker.name}`,
1648
+ resourceType: "image",
1649
+ action: run.mode === "build" ? "build" : "reuse",
1650
+ id: worker.ref
1651
+ });
1652
+ if (run.push) continue;
1653
+ planned({
1654
+ key: `service:${worker.name}`,
1655
+ resourceType: "service",
1656
+ action: run.previous[worker.name] ? "reuse" : "create"
1657
+ });
1658
+ }
1659
+ for (const push of run.topicSubscriptions?.pushes ?? []) {
1660
+ const key = require_snsSubscriptions.subscriptionKey(push.worker, push.name);
1661
+ const id = run.topicSubscriptions?.recorded?.[key]?.id;
1662
+ planned({
1663
+ key,
1664
+ resourceType: require_snsSubscriptions.SUBSCRIPTION_TYPE,
1665
+ action: id ? "reuse" : "create",
1666
+ ...id ? { id } : {}
1667
+ });
1668
+ }
1669
+ if (!run.push) planned({
1670
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}/${_geekmidas_edge_proxy_traefik.EDGE_SERVICE}`,
1671
+ resourceType: "service",
1672
+ action: "ensure"
1673
+ });
1674
+ }
1675
+ /**
1676
+ * Keys written into the stage's secrets now, on top of what the store holds
1677
+ * — not at the end of the run, so a value the CDN hands over once is kept
1678
+ * the moment it exists — and into the run's copy, so a later write of it
1679
+ * keeps them too.
1680
+ */
1681
+ async function keepStageSecrets(ctx, run, values) {
1682
+ const stored = await ctx.secrets.read() ?? run.secrets;
1683
+ if (!stored) throw new StageSecretsMissingForKeep(ctx.stage);
1684
+ await ctx.secrets.write({
1685
+ ...stored,
1686
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1687
+ custom: {
1688
+ ...stored.custom,
1689
+ ...values
1690
+ }
1691
+ });
1692
+ if (run.secrets) run.secrets = {
1693
+ ...run.secrets,
1694
+ custom: {
1695
+ ...run.secrets.custom,
1696
+ ...values
1697
+ }
1698
+ };
1699
+ }
1700
+ /** A deployed stage with no secrets to keep a value in. */
1701
+ var StageSecretsMissingForKeep = class extends require_errors.GkmError {
1702
+ stage;
1703
+ constructor(stage) {
1704
+ super(`'${stage}' has no secrets yet to keep its CDN's origin certificate in. Set them up first: gkm secrets:init --stage ${stage}.`);
1705
+ this.stage = stage;
1706
+ this.name = "StageSecretsMissingForKeep";
1707
+ }
1708
+ };
1709
+ /**
1710
+ * Whether the shared edge gets any of the stack's certificates over the DNS
1711
+ * challenge: a wildcard site's, or the hosts a CDN answers.
1712
+ */
1713
+ function dnsChallenged(stack) {
1714
+ return stack.wildcard?.tls === "dns" || stack.cdn?.certificate === "dns";
1715
+ }
1716
+ /**
1717
+ * The shared edge's key for the stage's wildcard certificate, through the
1718
+ * DNS provider holding the stage's domain — before the stack's routes ask
1719
+ * for the certificate. Route 53's is issued through IAM, allowed the DNS
1720
+ * challenge's record and nothing else; every other provider's is the
1721
+ * stage's own secrets, written into the edge.
1722
+ */
1723
+ async function edgeAcmeKey(ctx, run, deps) {
1724
+ const { workspace, stage } = ctx;
1725
+ const zone = require_stack.acmeDnsZone(workspace, stage);
1726
+ if (!zone) return;
1727
+ const edge = require_stack.edgeRef(edgeFile(run), {
1728
+ ...run.ref.host ? { host: run.ref.host } : {},
1729
+ ...run.ref.output ? { output: run.ref.output } : {}
1730
+ });
1731
+ const log = (line) => ctx.logger.info(line);
1732
+ if (zone.provider !== "route53") {
1733
+ await require_stack.ensureEdgeDnsSecrets(deps.docker, {
1734
+ edge,
1735
+ zone,
1736
+ stage,
1737
+ custom: run.secrets?.custom,
1738
+ ...ctx.dryRun ? { dryRun: true } : {},
1739
+ log
1740
+ });
1741
+ return;
1742
+ }
1743
+ const { domain } = zone;
1744
+ const route53 = zone.config;
1745
+ const server = require_snsSubscriptions.requiredServerAddress(stage, domain, run.secrets?.custom)?.ipv4 ?? run.server?.host ?? "local";
1746
+ const clients = await (deps.acmeClients ?? defaultAcmeClients)(route53);
1747
+ await require_stack.ensureEdgeAcmeKey(deps.docker, {
1748
+ clients,
1749
+ edge,
1750
+ server,
1751
+ project: run.stack.project,
1752
+ domain,
1753
+ zone: zone.zone,
1754
+ ...route53.hostedZoneId ? { hostedZoneId: route53.hostedZoneId } : {},
1755
+ ...ctx.dryRun ? { dryRun: true } : {},
1756
+ log
1757
+ });
1758
+ }
1759
+ /** IAM and Route 53 through the AWS SDK's own chain, or the entry's profile. */
1760
+ async function defaultAcmeClients(config) {
1761
+ const [{ IAMClient }, { Route53Client }, { fromIni }] = await Promise.all([
1762
+ import("@aws-sdk/client-iam"),
1763
+ import("@aws-sdk/client-route-53"),
1764
+ import("@aws-sdk/credential-providers")
1765
+ ]);
1766
+ const options = {
1767
+ region: config.region ?? "us-east-1",
1768
+ ...config.profile ? { credentials: fromIni({ profile: config.profile }) } : {}
1769
+ };
1770
+ return {
1771
+ iam: new IAMClient(options),
1772
+ route53: new Route53Client(options)
1773
+ };
1774
+ }
1775
+ /**
1776
+ * What the apps run on: the stage's generated secrets kept, the stack's files
1777
+ * written, its infrastructure started, and its databases, roles, grants and
1778
+ * migrations applied.
1779
+ */
1780
+ async function provisionCompose(ctx, run, deps) {
1781
+ const { ref } = run;
1782
+ if (run.push) return;
1783
+ if (run.generated.length > 0 && run.secrets) {
1784
+ await ctx.secrets.write(run.secrets);
1785
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
1786
+ }
1787
+ const ports = require_stack.edgePorts(deps.env);
1788
+ const ownCaddy = await require_stack.assertEdgePorts(deps.docker, {
1789
+ project: run.stack.project,
1790
+ proxy: run.stack.proxy,
1791
+ ports,
1792
+ engine: ref
1793
+ });
1794
+ if (run.topicSubscriptions) await subscribeTopics(ctx, run, deps);
1795
+ const { stack } = run;
1796
+ run.files = await writeStack(ctx.cwd, run.dir, stack, run.originCertificate);
1797
+ printPlan(ctx, run);
1798
+ if (stack.proxy === "traefik") {
1799
+ if (ownCaddy) {
1800
+ ctx.logger.warn(`\n↪ Moving ${stack.project} from its own Caddy to the shared edge: removing ${ownCaddy.container}. Its hosts are offline until the edge is up and the stack is registered with it.`);
1801
+ await deps.docker.remove(ref, stack.project, "caddy");
1802
+ }
1803
+ ctx.logger.info(`\n🌐 Starting the shared edge (${_geekmidas_edge_proxy_traefik.EDGE_PROJECT})…`);
1804
+ run.files.push(...await require_stack.ensureEdge(deps.docker, {
1805
+ file: edgeFile(run),
1806
+ ports,
1807
+ ...ref.host ? { host: ref.host } : {},
1808
+ logging: {
1809
+ driver: require_stack.LOG_ROTATION.driver,
1810
+ options: { ...require_stack.LOG_ROTATION.options }
1811
+ },
1812
+ ...ref.output ? { output: ref.output } : {},
1813
+ ...ref.signal ? { signal: ref.signal } : {}
1814
+ }));
1815
+ applied(ctx, run, {
1816
+ key: `service:${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}/${_geekmidas_edge_proxy_traefik.EDGE_SERVICE}`,
1817
+ resourceType: "service",
1818
+ action: "ensure",
1819
+ id: `${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}/${_geekmidas_edge_proxy_traefik.EDGE_SERVICE}`,
1820
+ via: "found"
1821
+ });
1822
+ if (dnsChallenged(stack)) await edgeAcmeKey(ctx, run, deps);
1823
+ }
1824
+ if (stack.infra.length > 0) {
1825
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
1826
+ await deps.docker.up(ref, stack.infra);
1827
+ for (const service of stack.infra) applied(ctx, run, {
1828
+ key: `service:${service}`,
1829
+ resourceType: "service",
1830
+ action: "ensure",
1831
+ id: `${stack.project}/${service}`,
1832
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
1833
+ });
1834
+ }
1835
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
1836
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
1837
+ }
1838
+ /**
1839
+ * Subscribe each topic subscriber SNS pushes to — for a topic the stage set
1840
+ * to SNS by hand — record the ARNs, and compose the stack again with them,
1841
+ * before a file is written.
1842
+ */
1843
+ async function subscribeTopics(ctx, run, deps) {
1844
+ const { pushes, recorded, restack } = run.topicSubscriptions;
1845
+ if (pushes.length > 0) ctx.logger.info("\n📮 SNS subscriptions for the stage's own topics");
1846
+ run.stack = restack(await ensureTopicSubscriptions({
1847
+ pushes,
1848
+ recorded,
1849
+ secrets: run.secrets?.custom ?? {},
1850
+ stage: ctx.stage,
1851
+ env: deps.env,
1852
+ record: async (resource) => {
1853
+ await ctx.state.putResource(ctx.stage, resource);
1854
+ applied(ctx, run, {
1855
+ key: resource.key,
1856
+ resourceType: require_snsSubscriptions.SUBSCRIPTION_TYPE,
1857
+ action: "ensure",
1858
+ id: resource.id,
1859
+ via: recorded?.[resource.key]?.id === resource.id ? "recorded" : "created"
1860
+ });
1861
+ },
1862
+ forget: async (key) => {
1863
+ await ctx.state.deleteResource(ctx.stage, key);
1864
+ },
1865
+ log: (line) => ctx.logger.info(line)
1866
+ }));
1867
+ }
1868
+ /**
1869
+ * Create each bucket the stack's MinIO serves, and the open paths of each
1870
+ * one a file server fronts — from this machine, on MinIO's loopback port,
1871
+ * the way `gkm dev` creates them.
1872
+ */
1873
+ async function prepareBuckets(ctx, run, deps) {
1874
+ const storage = run.stack.storage;
1875
+ if (storage.buckets.length === 0) return;
1876
+ const tunnel = await reach(run, deps, "minio", require_stack.LOOPBACK_SERVICES.minio);
1877
+ let done;
1878
+ try {
1879
+ const client = deps.buckets(tunnel.port, storage);
1880
+ done = [
1881
+ ...await require_stack.applyBuckets(client, storage.buckets),
1882
+ ...await require_stack.applyPolicies(client, storage.policies),
1883
+ ...await require_stack.applyLifecycles(client, storage.lifecycles),
1884
+ ...await require_stack.applyNotifications(client, storage.objects, new Set(storage.webhooks.map((hook) => hook.bucket)))
1885
+ ];
1886
+ } finally {
1887
+ await tunnel.close();
1888
+ }
1889
+ const created = done.filter((entry) => entry.created).length;
1890
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
1891
+ }
1892
+ /**
1893
+ * Create what the plan names in the stack's Postgres, migrate it, then run
1894
+ * its seeds — every one, every time, as each construct's owner.
1895
+ *
1896
+ * Every service the stack publishes on its loopback is reached, not only
1897
+ * Postgres: a seed runs project code, and project code that uploads a file
1898
+ * reaches the stack's MinIO as well.
1899
+ */
1900
+ async function prepareDatabases(ctx, run, deps) {
1901
+ await reachLoopback(run, deps, (ports) => migrateAndSeed(ctx, run, deps, ports));
1902
+ }
1903
+ /**
1904
+ * Every service the stack publishes on its loopback, reached from this
1905
+ * machine for as long as `body` runs — each by its port key.
1906
+ */
1907
+ async function reachLoopback(run, deps, body) {
1908
+ const tunnels = [];
1909
+ try {
1910
+ const ports = {};
1911
+ for (const [service, inside] of Object.entries(require_stack.LOOPBACK_SERVICES)) {
1912
+ if (!run.stack.infra.includes(service)) continue;
1913
+ const tunnel = await reach(run, deps, service, inside);
1914
+ tunnels.push(tunnel);
1915
+ ports[require_credentials$1.primaryPortKey(service)] = tunnel.port;
1916
+ }
1917
+ await body(ports);
1918
+ } finally {
1919
+ await Promise.all(tunnels.map((tunnel) => tunnel.close()));
1920
+ }
1921
+ }
1922
+ /**
1923
+ * A port a stack's service publishes on its engine's loopback, reachable
1924
+ * from this machine: the published port itself on the local stage, and on a
1925
+ * server an SSH tunnel to it over the deploy's own login — so Postgres and
1926
+ * MinIO are never published beyond the server's loopback.
1927
+ *
1928
+ * Migrations and seeds run here, in this process, with the project's own
1929
+ * Kysely — the way `gkm migrate` runs them — through that port. No image
1930
+ * needs to carry them, and nothing is run on the server but the stack.
1931
+ */
1932
+ async function reach(run, deps, service, inside) {
1933
+ const published = await deps.docker.port(run.ref, service, inside);
1934
+ if (!run.server) return {
1935
+ port: published,
1936
+ close: async () => {}
1937
+ };
1938
+ return deps.server.tunnel(run.server, published);
1939
+ }
1940
+ async function migrateAndSeed(ctx, run, deps, ports, seeds = true) {
1941
+ const { stack } = run;
1942
+ const workspace = ctx.workspace;
1943
+ const port = ports[require_credentials$1.primaryPortKey("postgres")];
1944
+ const superuser = stack.credential.containers.postgres;
1945
+ const login = await deps.logins({
1946
+ port,
1947
+ login: superuser,
1948
+ legacy: [{
1949
+ user: require_stack.LEGACY_LOCAL_LOGIN.user,
1950
+ password: superuser.password
1951
+ }, ...stack.local ? [require_stack.LEGACY_LOCAL_LOGIN] : []]
1952
+ });
1953
+ if (login.notice) ctx.logger.info(login.notice);
1954
+ const statements = [...require_stack.postgresStatements(stack.plan, workspace.name, stack.credential.seed), ...stack.backups ? require_stack.backupsRoleStatements(stack.backups) : []];
1955
+ if (statements.length > 0) {
1956
+ const created = (await require_stack.applyPostgres(deps.sql(port, login.login), statements)).filter((entry) => entry.created);
1957
+ ctx.logger.info(created.length > 0 ? `🗄️ Created ${created.map((entry) => entry.describe).join(", ")}` : "🗄️ Databases and roles already in place");
1958
+ }
1959
+ const sources = {};
1960
+ const manifest = await require_discover.discover({
1961
+ patterns: require_stack.constructGlobs(workspace),
1962
+ cwd: workspace.root,
1963
+ sources
1964
+ });
1965
+ const custom = run.secrets?.custom ?? {};
1966
+ const resolved = require_stack.envFor(stack.plan, {
1967
+ ...stack.resolution,
1968
+ ports,
1969
+ credentials: {
1970
+ ...stack.resolution.credentials,
1971
+ postgres: login.login
1972
+ }
1973
+ });
1974
+ const env = require_stack.stageEnv(run.secrets ? require_credentials.toEmbeddableSecrets(run.secrets) : {}, Object.fromEntries(Object.entries(resolved).filter(([key]) => custom[key] === void 0)));
1975
+ const options = {
1976
+ root: workspace.root,
1977
+ manifest,
1978
+ sources,
1979
+ env
1980
+ };
1981
+ const runs = await deps.migrate(options);
1982
+ const seeded = !seeds ? [] : await deps.seed({
1983
+ ...options,
1984
+ stage: ctx.stage,
1985
+ backends: require_stack.backendsOf(workspace)
1986
+ }).catch((error) => {
1987
+ if (error instanceof require_databases.SeedFailed) throw new require_seeds.DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
1988
+ throw error;
1989
+ });
1990
+ require_seeds.reportDatabaseRuns(runs.map(({ target, applied }) => ({
1991
+ construct: target.id,
1992
+ folder: target.migrations,
1993
+ applied
1994
+ })), seeded.map(({ target, seeded }) => ({
1995
+ construct: target.id,
1996
+ folder: target.seeds,
1997
+ seeded
1998
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
1999
+ }
2000
+ /**
2001
+ * Each app's image: built from this checkout — inside Docker, every one of
2002
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
2003
+ * live changes.
2004
+ */
2005
+ async function buildCompose(ctx, run, deps) {
2006
+ const { stack, ref } = run;
2007
+ const images = [
2008
+ ...stack.apps,
2009
+ ...stack.workers,
2010
+ ...stack.processors
2011
+ ];
2012
+ const apps = images.map((image) => image.app);
2013
+ if (buildsOnly(run)) {
2014
+ run.files = await writeStack(ctx.cwd, run.dir, stack, run.originCertificate);
2015
+ printPlan(ctx, run);
2016
+ }
2017
+ const prerendered = prerenderedHere(run);
2018
+ if (buildsOnly(run)) await stageAnswers(ctx, run, deps, prerendered);
2019
+ const held = new Set(buildsOnly(run) ? [] : prerendered.map(({ app }) => app));
2020
+ const now = images.filter((image) => !held.has(image.app));
2021
+ if (run.mode === "build") {
2022
+ ctx.logger.info("\n🐳 Building images…");
2023
+ await deps.docker.build(ref, now.map((image) => image.app));
2024
+ } else {
2025
+ ctx.logger.info(`\n🐳 Pulling ${require_credentials.stageTag(ctx.tag, ctx.stage)}…`);
2026
+ await deps.docker.pull(ref, apps);
2027
+ }
2028
+ if (run.check) await startupCheck(ctx, run, deps);
2029
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
2030
+ await recordBuilt(ctx, run, deps, now);
2031
+ }
2032
+ /**
2033
+ * Whether the run only builds — to push, or to check — so nothing is
2034
+ * provisioned, released or recorded, and no stage's server is reached.
2035
+ */
2036
+ function buildsOnly(run) {
2037
+ return run.push || run.check;
2038
+ }
2039
+ /**
2040
+ * Each image's tag as it resolved — the registry's digest for a pushed or
2041
+ * pulled image, or, for one built here and never pushed, its content id —
2042
+ * in the run, and said.
2043
+ */
2044
+ async function recordBuilt(ctx, run, deps, images) {
2045
+ const { ref } = run;
2046
+ for (const image of images) {
2047
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(ref, image.ref);
2048
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
2049
+ run.images[image.app] = {
2050
+ ref: image.ref,
2051
+ tag: image.tag,
2052
+ ...digest ? { digest } : {}
2053
+ };
2054
+ ctx.emit({
2055
+ type: "artifact.built",
2056
+ app: image.app,
2057
+ imageRef: image.ref,
2058
+ ...digest ? { digest } : {}
2059
+ });
2060
+ run.changes.push({
2061
+ key: `image:${image.app}`,
2062
+ resourceType: "image",
2063
+ action: run.mode === "build" ? "build" : "reuse",
2064
+ id: digest ?? image.ref
2065
+ });
2066
+ }
2067
+ }
2068
+ /**
2069
+ * The whole stack up — anything it no longer defines removed — and each
2070
+ * app's image recorded in the stage's state.
2071
+ */
2072
+ async function releaseCompose(ctx, run, deps) {
2073
+ const { stack, ref } = run;
2074
+ if (run.push) return;
2075
+ const edge = require_stack.edgeRef(edgeFile(run), {
2076
+ ...ref.host ? { host: ref.host } : {},
2077
+ ...ref.output ? { output: ref.output } : {}
2078
+ });
2079
+ if (stack.proxy === "traefik" && stack.traefik) {
2080
+ const written = await require_stack.writeEdgeRoutes(deps.docker, edge, stack.project, stack.traefik, await edgeCertificate(run.dir, stack), run.originCertificate);
2081
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}: ${written.at(-1)}`);
2082
+ } else if (!stack.local || (0, node_fs.existsSync)(edgeFile(run))) await require_stack.removeEdgeRoutes(deps.docker, edge, stack.project);
2083
+ const prerendered = prerenderedHere(run);
2084
+ if (prerendered.length > 0) await buildAgainstStage(ctx, run, deps, prerendered);
2085
+ ctx.logger.info("\n🚀 Starting the stack…");
2086
+ const down = await deps.docker.up(ref).then(() => [], (error) => unhealthyAfterUp(ctx, run, deps, error));
2087
+ const isDown = new Set(down.map(({ app }) => app));
2088
+ await recordImages(ctx, run);
2089
+ for (const app of stack.apps) {
2090
+ if (isDown.has(app.name)) continue;
2091
+ const image = run.images[app.name];
2092
+ applied(ctx, run, {
2093
+ key: `service:${app.name}`,
2094
+ resourceType: "service",
2095
+ action: "ensure",
2096
+ id: `${stack.project}/${app.name}`,
2097
+ via: run.previous[app.name] ? "recorded" : "created"
2098
+ });
2099
+ ctx.emit({
2100
+ type: "app.deployed",
2101
+ app: app.name,
2102
+ applicationId: `${stack.project}/${app.name}`,
2103
+ imageRef: image?.ref ?? app.ref,
2104
+ url: app.url
2105
+ });
2106
+ }
2107
+ for (const worker of [...stack.workers, ...stack.processors]) {
2108
+ if (isDown.has(worker.name)) continue;
2109
+ applied(ctx, run, {
2110
+ key: `service:${worker.name}`,
2111
+ resourceType: "service",
2112
+ action: "ensure",
2113
+ id: `${stack.project}/${worker.name}`,
2114
+ via: run.previous[worker.name] ? "recorded" : "created"
2115
+ });
2116
+ }
2117
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
2118
+ for (const app of stack.apps) {
2119
+ if (isDown.has(app.name)) continue;
2120
+ 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}` : ""}`);
2121
+ }
2122
+ if (stack.mailInbox) ctx.logger.info(` ${"mail".padEnd(12)} ${stack.mailInbox.url} (inbox)`);
2123
+ for (const worker of stack.workers) {
2124
+ if (isDown.has(worker.name)) continue;
2125
+ ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
2126
+ }
2127
+ for (const unit of stack.processors) {
2128
+ if (isDown.has(unit.name)) continue;
2129
+ ctx.logger.info(` ${unit.name.padEnd(12)} processors of ${unit.id}`);
2130
+ }
2131
+ if (stack.authority) ctx.logger.info(`\n🔐 Certificates are from gkm's local CA ("gkm trust" trusts it here): NODE_EXTRA_CA_CERTS=${stack.authority.certFile}`);
2132
+ else if (stack.local && stack.tls) ctx.logger.info(stack.tls.caFile ? `\n🔐 Certificates are the stage's own (deploy.compose.tls), from the CA in ${stack.tls.caFile}: NODE_EXTRA_CA_CERTS=${stack.tls.caFile}` : `\n🔐 Certificates are the stage's own (deploy.compose.tls): ${stack.tls.certFile}. Set its caFile to the root it chains to, so gkm and the stack's containers trust it.`);
2133
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy, "docker");
2134
+ }
2135
+ /**
2136
+ * After `up --wait` failed: each app's and worker's service that is not
2137
+ * healthy once its health settles — waited on while it is still starting,
2138
+ * as `--wait` stops at the first that is not. None means the failure was not
2139
+ * health's, and it is thrown as it was.
2140
+ */
2141
+ async function unhealthyAfterUp(ctx, run, deps, error, except = /* @__PURE__ */ new Set()) {
2142
+ const down = await notHealthy(ctx, run, deps, imageServices(run.stack).filter((service) => !except.has(service)));
2143
+ if (down.length === 0) throw error;
2144
+ ctx.logger.warn(`\n⚠️ ${down.map(({ app }) => app).join(", ")} did not turn healthy; the rest of the stack is released and routed.`);
2145
+ return down;
2146
+ }
2147
+ /** Every service of the stack that runs one of its images: apps, workers, processors. */
2148
+ function imageServices(stack) {
2149
+ return [
2150
+ ...stack.apps.flatMap(require_stack.replicaNames),
2151
+ ...stack.workers.map((worker) => worker.name),
2152
+ ...stack.processors.map((unit) => unit.name)
2153
+ ];
2154
+ }
2155
+ /**
2156
+ * Each of `services` that is not healthy once its health settles — waited on
2157
+ * while it is still starting, as `--wait` stops at the first that is not.
2158
+ */
2159
+ async function notHealthy(ctx, run, deps, services) {
2160
+ return (await Promise.all(services.map(async (service) => {
2161
+ let last;
2162
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2163
+ ctx.signal.throwIfAborted();
2164
+ last = await deps.docker.health(run.ref, service).catch(() => void 0);
2165
+ if (last !== "starting") break;
2166
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2167
+ }
2168
+ return {
2169
+ app: service,
2170
+ url: `docker:${service}`,
2171
+ last
2172
+ };
2173
+ }))).filter(({ last }) => last !== "healthy").map(({ app, url, last }) => ({
2174
+ app,
2175
+ url,
2176
+ last: last ?? "not running"
2177
+ }));
2178
+ }
2179
+ /**
2180
+ * The startup check (`--check`, see `startupCheck.ts`): every image built
2181
+ * here started on this machine, as its own compose project, with the stage's
2182
+ * secrets and the stack's backing services — migrated, not seeded — and
2183
+ * each one healthy by its own check. One that is not fails the run, named,
2184
+ * with its last log lines. The project is removed, volumes and all, however
2185
+ * it ends.
2186
+ */
2187
+ async function startupCheck(ctx, run, deps) {
2188
+ const { stack, ref } = run;
2189
+ const services = imageServices(stack);
2190
+ ctx.logger.info(`\n🩺 Starting ${services.length} image(s) with ${ctx.stage}'s secrets, before anything is pushed…`);
2191
+ try {
2192
+ for (const network of Object.values(stack.compose.networks ?? {})) if (network.external) await deps.docker.ensureNetwork(ref, network.name);
2193
+ if (stack.infra.length > 0) {
2194
+ ctx.logger.info(`🗄️ Starting ${stack.infra.join(", ")}…`);
2195
+ await deps.docker.up(ref, stack.infra);
2196
+ }
2197
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
2198
+ if (stack.infra.includes("postgres")) await reachLoopback(run, deps, (ports) => migrateAndSeed(ctx, run, deps, ports, false));
2199
+ const down = await deps.docker.up(ref, services).then(() => [], async (error) => {
2200
+ const found = await notHealthy(ctx, run, deps, services);
2201
+ if (found.length === 0) throw error;
2202
+ return found;
2203
+ });
2204
+ if (down.length > 0) {
2205
+ const failed = await Promise.all(down.map(async ({ app, last }) => ({
2206
+ app,
2207
+ last,
2208
+ logs: await deps.docker.logs(ref, app, 50).catch(() => "")
2209
+ })));
2210
+ throw new StartupCheckFailed(ctx.stage, failed);
2211
+ }
2212
+ } finally {
2213
+ await deps.docker.down(ref, { volumes: true }).catch((error) => {
2214
+ ctx.logger.warn(`⚠️ Could not remove the check's stack (${ref.project}): ${error instanceof Error ? error.message : String(error)}. Remove it with \`docker compose -p ${ref.project} down --volumes\`.`);
2215
+ });
2216
+ }
2217
+ ctx.logger.info(`✅ Every image started with ${ctx.stage}'s secrets and passed its health check.`);
2218
+ }
2219
+ /**
2220
+ * Where a check through the edge connects: this machine for the local stage,
2221
+ * a deployed stage's server on its published port — or, for a push, which
2222
+ * has no server, wherever the host resolves.
2223
+ */
2224
+ function edgeTarget(run, deps) {
2225
+ if (run.stack.local) return { connectTo: "127.0.0.1" };
2226
+ if (run.server) return {
2227
+ connectTo: run.server.host,
2228
+ connectPort: require_stack.edgePorts(deps.env).https
2229
+ };
2230
+ }
2231
+ /**
2232
+ * The sites this run builds against their stage's running APIs
2233
+ * (`prerender: 'stage'`). None for a run that pulls: a pulled image was built
2234
+ * against the stage when it was pushed.
2235
+ */
2236
+ function prerenderedHere(run) {
2237
+ if (run.mode !== "build") return [];
2238
+ return run.stack.apps.filter((app) => app.prerender && app.build);
2239
+ }
2240
+ /**
2241
+ * A site that pre-renders against its stage, built once its APIs answer:
2242
+ * every service of the stack started but those sites — `up --wait`, so each
2243
+ * is healthy by its own check — then each API the site depends on asked
2244
+ * through the edge, as a browser reaches it, and only then the site built.
2245
+ * The full `up` that follows starts it.
2246
+ */
2247
+ async function buildAgainstStage(ctx, run, deps, sites) {
2248
+ const { stack, ref } = run;
2249
+ const held = new Set(sites.flatMap(require_stack.replicaNames));
2250
+ const services = Object.keys(stack.compose.services).filter((service) => !held.has(service));
2251
+ ctx.logger.info(`\n🚀 Starting the stack, but ${listNames(sites)}, built once its APIs answer…`);
2252
+ const down = await deps.docker.up(ref, services).then(() => [], (error) => unhealthyAfterUp(ctx, run, deps, error, held));
2253
+ for (const site of sites) {
2254
+ const against = new Set(site.prerender?.against);
2255
+ const blocking = down.filter(({ app }) => against.has(app));
2256
+ if (blocking.length > 0) throw new SitePrerenderApisDown(site.name, blocking, "docker");
2257
+ }
2258
+ await stageAnswers(ctx, run, deps, sites);
2259
+ ctx.logger.info(`\n🐳 Building ${listNames(sites)} against the stage's APIs…`);
2260
+ await deps.docker.build(ref, sites.map((site) => site.app));
2261
+ await recordBuilt(ctx, run, deps, sites);
2262
+ }
2263
+ /** `web` — or `docs and web`. */
2264
+ function listNames(apps) {
2265
+ const names = apps.map(({ name }) => name);
2266
+ return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0] ?? "";
2267
+ }
2268
+ /**
2269
+ * Each API a site pre-rendered against its stage depends on, asked through
2270
+ * the edge as `verify` asks it — the address the site's build fetches from.
2271
+ * Any that does not answer fails the run before the site is built: a build
2272
+ * that cannot reach them bakes in pages without their data.
2273
+ */
2274
+ async function stageAnswers(ctx, run, deps, sites) {
2275
+ const { stack } = run;
2276
+ const names = new Set(sites.flatMap((site) => site.prerender?.against ?? []));
2277
+ const apps = stack.apps.filter((app) => names.has(app.name));
2278
+ if (apps.length === 0) return;
2279
+ ctx.logger.info(`\n🩺 Checking the APIs ${listNames(sites)} ${sites.length > 1 ? "pre-render" : "pre-renders"} from…`);
2280
+ const ca = await verifyAuthority(stack);
2281
+ const edge = edgeTarget(run, deps);
2282
+ const results = await Promise.all(apps.map((app) => app.id === stack.wildcard?.site && !buildsOnly(run) ? checkContainer(ctx, run, deps, app.name) : checkApp(ctx, app, deps, {
2283
+ ca,
2284
+ edge
2285
+ })));
2286
+ const down = new Map(results.filter((r) => !r.healthy).map((r) => [r.app, r]));
2287
+ for (const site of sites) {
2288
+ const blocking = (site.prerender?.against ?? []).flatMap((name) => {
2289
+ const result = down.get(name);
2290
+ return result ? [result] : [];
2291
+ });
2292
+ if (blocking.length > 0) throw new SitePrerenderApisDown(site.name, blocking, buildsOnly(run) ? "push" : "edge");
2293
+ }
2294
+ }
2295
+ /**
2296
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
2297
+ * records: the ref it runs, the tag it was released under, and the digest
2298
+ * the tag resolved to.
2299
+ */
2300
+ async function recordImages(ctx, run) {
2301
+ const journal = await require_seeds.DeployJournal.open(ctx.state, ctx.stage, () => require_stack.createComposeState(ctx.stage));
2302
+ const by = require_seeds.currentActor();
2303
+ for (const app of [
2304
+ ...run.stack.apps,
2305
+ ...run.stack.workers,
2306
+ ...run.stack.processors
2307
+ ]) {
2308
+ const image = run.images[app.app] ?? {
2309
+ ref: app.ref,
2310
+ tag: app.tag
2311
+ };
2312
+ require_stack.recordRelease(journal.state, app.app, image, by);
2313
+ }
2314
+ journal.state.identity = ctx.identity.key;
2315
+ await journal.save();
2316
+ }
2317
+ /**
2318
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
2319
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
2320
+ * its certificate is from gkm's local CA, so that root is the one trusted and
2321
+ * the request goes to 127.0.0.1.
2322
+ */
2323
+ async function verifyCompose(ctx, run, deps) {
2324
+ const { stack } = run;
2325
+ if (run.push) return;
2326
+ const ca = await verifyAuthority(stack);
2327
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
2328
+ const edge = edgeTarget(run, deps);
2329
+ const results = await Promise.all(stack.apps.map((app) => app.id === stack.wildcard?.site ? checkContainer(ctx, run, deps, app.name) : checkApp(ctx, app, deps, {
2330
+ ca,
2331
+ edge
2332
+ })));
2333
+ results.push(...await Promise.all([...stack.workers, ...stack.processors].map((worker) => checkContainer(ctx, run, deps, worker.name))));
2334
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, require_credentials$1.LOGS_SERVICE));
2335
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
2336
+ app,
2337
+ url,
2338
+ last
2339
+ }));
2340
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
2341
+ await pruneStageDns(ctx, run);
2342
+ await confirmSubscriptions(ctx, run, deps);
2343
+ await warmSites(ctx, run, deps, {
2344
+ ca,
2345
+ edge
2346
+ });
2347
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local, run.server);
2348
+ }
2349
+ /**
2350
+ * Each server-rendered site (`next`, `tanstack`) asked for its sitemap, its
2351
+ * `/` and every page the sitemap lists, through the edge as `checkApp` asks
2352
+ * it — see `warmup.ts`. Its image was built with no API reachable, so each
2353
+ * page renders on its first request: this is that request, made before any
2354
+ * visitor's. A Next site is asked with its on-demand revalidation header,
2355
+ * so a page its build cached (empty) is rendered again from the deployed
2356
+ * APIs rather than served from that cache.
2357
+ *
2358
+ * Only ever said, never failed on: every app is already healthy, and a page
2359
+ * that did not warm renders on the next request for it.
2360
+ */
2361
+ async function warmSites(ctx, run, deps, options) {
2362
+ const { stack } = run;
2363
+ const sites = stack.apps.filter((app) => app.kind === "site" && (app.variant === "next" || app.variant === "tanstack"));
2364
+ if (sites.length === 0) return;
2365
+ ctx.logger.info("\n🔥 Warming each server-rendered site…");
2366
+ for (const app of sites) {
2367
+ if (app.id === stack.wildcard?.site) {
2368
+ ctx.logger.info(` – ${app.name.padEnd(12)} serves every subdomain: there is no one host to warm, so it is skipped`);
2369
+ continue;
2370
+ }
2371
+ try {
2372
+ const headers = app.variant === "next" ? await forceRender(ctx, run, deps, app) : {};
2373
+ const { warmed, cached, warnings, leftOut } = await warmSite({
2374
+ url: app.url,
2375
+ fetch: deps.fetch ?? edgeFetch,
2376
+ headers,
2377
+ edge: {
2378
+ ...options.ca ? { ca: options.ca } : {},
2379
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
2380
+ ...options.edge,
2381
+ signal: ctx.signal
2382
+ }
2383
+ });
2384
+ const said = `warmed ${warmed.length} page(s)${cached.length > 0 ? `, ${cached.length} served from the build cache` : ""}${warnings.length > 0 ? `, ${warnings.length} warning(s)` : ""}`;
2385
+ if (warnings.length === 0) ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${said}${cached.length > 0 ? `: ${listed(cached)}` : ""}`);
2386
+ else {
2387
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} ${said}:`);
2388
+ for (const { url, reason } of warnings) ctx.logger.warn(` ${url}: ${reason}`);
2389
+ if (cached.length > 0) ctx.logger.warn(` served from the build cache: ${listed(cached)}`);
2390
+ }
2391
+ if (leftOut > 0) ctx.logger.info(` ${leftOut} more page(s) in its sitemap were not asked: at most 500 are warmed per site`);
2392
+ } catch (error) {
2393
+ if (ctx.signal.aborted) throw error;
2394
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} not warmed: ${error instanceof Error ? error.message : String(error)}`);
2395
+ }
2396
+ }
2397
+ }
2398
+ /** The most pages a summary names; the rest are counted. */
2399
+ const LISTED_PAGES = 10;
2400
+ /** Pages by path, `/about`, the first {@link LISTED_PAGES} of them. */
2401
+ function listed(urls) {
2402
+ const paths = urls.map((url) => {
2403
+ const { pathname, search } = new URL(url);
2404
+ return `${pathname}${search}`;
2405
+ });
2406
+ const shown = paths.slice(0, LISTED_PAGES).join(", ");
2407
+ return paths.length > LISTED_PAGES ? `${shown} and ${paths.length - LISTED_PAGES} more` : shown;
2408
+ }
2409
+ /**
2410
+ * The header that has a Next site render each warmed page whatever its
2411
+ * cache says: `x-prerender-revalidate` with the preview-mode id of the image
2412
+ * running — read in its container, through the stack's Docker engine, at
2413
+ * the path the generated Dockerfile puts the standalone output at. Where the
2414
+ * id cannot be read, said once, and the site is warmed with plain requests.
2415
+ */
2416
+ async function forceRender(ctx, run, deps, app) {
2417
+ let reason;
2418
+ try {
2419
+ const root = ctx.workspace.root;
2420
+ const gkmRoot = (0, node_path.relative)(require_stack.findBuildRoot(root), root) || ".";
2421
+ const lookup = await nextPreviewModeId((command) => deps.docker.exec(run.ref, app.name, command), require_stack.nextPrerenderManifest(require_stack.fromBuildRoot({ gkmRoot }, app.path)));
2422
+ if ("id" in lookup) return { [NEXT_REVALIDATE_HEADER]: lookup.id };
2423
+ reason = lookup.reason;
2424
+ } catch (error) {
2425
+ if (ctx.signal.aborted) throw error;
2426
+ reason = error instanceof Error ? error.message : String(error);
2427
+ }
2428
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} can't force ISR pages to render: ${reason}. Warming with plain requests; a page Next cached at build is served from that cache until its revalidate window ends.`);
2429
+ return {};
2430
+ }
2431
+ /**
2432
+ * The SNS subscriptions the stage's providers made before the workers were
2433
+ * up: each still pending is subscribed again, so SNS resends its
2434
+ * confirmation to a worker now there to answer it, and waited on. One still
2435
+ * pending after that is said, not failed on — every app is healthy, and
2436
+ * rolling them back would not confirm it.
2437
+ */
2438
+ async function confirmSubscriptions(ctx, run, deps) {
2439
+ const stored = await ctx.state.read(ctx.stage);
2440
+ const left = await (deps.confirmSubscriptions ?? require_snsSubscriptions.confirmPendingSubscriptions)({
2441
+ workspace: ctx.workspace,
2442
+ stage: ctx.stage,
2443
+ secrets: run.secrets?.custom ?? {},
2444
+ resources: stored?.resources,
2445
+ env: deps.env,
2446
+ log: (line) => ctx.logger.info(line),
2447
+ record: async (record) => {
2448
+ const { updatedAt: _, updatedBy: __, ...input } = record;
2449
+ await ctx.state.putResource(ctx.stage, input);
2450
+ }
2451
+ });
2452
+ if (left.length > 0) ctx.logger.warn(`⚠ ${new require_snsSubscriptions.PushSubscriptionsUnconfirmed(left).message}`);
2453
+ }
2454
+ /**
2455
+ * A container's own health check, as Docker reports it: a worker's, which
2456
+ * has no route through the edge, and OpenObserve's — by default it has no
2457
+ * host there, and served publicly it answers only the addresses it allows,
2458
+ * which need not include this one.
2459
+ */
2460
+ async function checkContainer(ctx, run, deps, service) {
2461
+ const url = `docker:${service}`;
2462
+ let last = "not asked";
2463
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2464
+ ctx.signal.throwIfAborted();
2465
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
2466
+ last = health ?? "not running";
2467
+ const healthy = health === "healthy";
2468
+ ctx.emit({
2469
+ type: "health.checked",
2470
+ app: service,
2471
+ url,
2472
+ healthy,
2473
+ attempt
2474
+ });
2475
+ if (healthy) {
2476
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
2477
+ return {
2478
+ app: service,
2479
+ url,
2480
+ last,
2481
+ healthy
2482
+ };
2483
+ }
2484
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2485
+ }
2486
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
2487
+ return {
2488
+ app: service,
2489
+ url,
2490
+ last,
2491
+ healthy: false
2492
+ };
2493
+ }
2494
+ /** A login, as the `Authorization` header that carries it. */
2495
+ function basicAuthorization(auth) {
2496
+ return `Basic ${Buffer.from(`${auth.user}:${auth.password}`).toString("base64")}`;
2497
+ }
2498
+ /** How to open the logs, printed — and as an event, for a headless caller. */
2499
+ function reportLogs(ctx, logs, local, server) {
2500
+ const lines = require_credentials$1.logsAccess(logs, {
2501
+ stage: ctx.stage,
2502
+ local,
2503
+ user: server?.user ?? currentUser(),
2504
+ hostname: server?.host ?? (0, node_os.hostname)(),
2505
+ ...server ? { known: true } : {}
2506
+ });
2507
+ ctx.logger.info(`\n${lines.join("\n")}`);
2508
+ ctx.emit({
2509
+ type: "logs.ready",
2510
+ service: require_credentials$1.LOGS_SERVICE,
2511
+ access: logs.public ? "public" : "tunnel",
2512
+ url: logs.url,
2513
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
2514
+ email: logs.email
2515
+ });
2516
+ }
2517
+ /** This machine's user — a guess at who would SSH in. */
2518
+ function currentUser() {
2519
+ try {
2520
+ return (0, node_os.userInfo)().username;
2521
+ } catch {
2522
+ return process.env.USER ?? "user";
2523
+ }
2524
+ }
2525
+ async function checkApp(ctx, app, deps, options) {
2526
+ const url = `${app.url.replace(/^ws/, "http")}${app.kind === "site" ? "/" : "/health"}`;
2527
+ let last = "not asked";
2528
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2529
+ ctx.signal.throwIfAborted();
2530
+ let status;
2531
+ try {
2532
+ status = await deps.probe({
2533
+ url,
2534
+ ...options.ca ? { ca: options.ca } : {},
2535
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
2536
+ ...options.edge,
2537
+ timeoutMs: 1e4,
2538
+ signal: ctx.signal
2539
+ });
2540
+ last = `HTTP ${status}`;
2541
+ } catch (error) {
2542
+ last = error instanceof Error ? error.message : String(error);
2543
+ }
2544
+ const healthy = status !== void 0 && isHealthy(status);
2545
+ ctx.emit({
2546
+ type: "health.checked",
2547
+ app: app.name,
2548
+ url,
2549
+ healthy,
2550
+ ...status !== void 0 ? { status } : {},
2551
+ attempt
2552
+ });
2553
+ if (healthy) {
2554
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
2555
+ return {
2556
+ app: app.name,
2557
+ url,
2558
+ last,
2559
+ healthy
2560
+ };
2561
+ }
2562
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2563
+ }
2564
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
2565
+ return {
2566
+ app: app.name,
2567
+ url,
2568
+ last,
2569
+ healthy: false
2570
+ };
2571
+ }
2572
+ function composeResult(ctx, run) {
2573
+ const apps = [...run.stack.apps.map((app) => {
2574
+ const image = run.images[app.name];
2575
+ return {
2576
+ appName: app.name,
2577
+ type: app.kind === "site" ? "web" : "backend",
2578
+ success: !ctx.dryRun,
2579
+ applicationId: `${run.stack.project}/${app.name}`,
2580
+ imageRef: image?.ref ?? app.ref,
2581
+ ...image?.digest ? { digest: image.digest } : {},
2582
+ url: app.url
2583
+ };
2584
+ }), ...[...run.stack.workers, ...run.stack.processors].map((worker) => {
2585
+ const image = run.images[worker.name];
2586
+ return {
2587
+ appName: worker.name,
2588
+ type: "backend",
2589
+ success: !ctx.dryRun,
2590
+ applicationId: `${run.stack.project}/${worker.name}`,
2591
+ imageRef: image?.ref ?? worker.ref,
2592
+ ...image?.digest ? { digest: image.digest } : {}
2593
+ };
2594
+ })];
2595
+ return {
2596
+ apps,
2597
+ projectId: run.stack.project,
2598
+ successCount: ctx.dryRun ? 0 : apps.length,
2599
+ failedCount: 0,
2600
+ stage: ctx.stage,
2601
+ identity: ctx.identity.key,
2602
+ tag: require_credentials.stageTag(ctx.tag, ctx.stage),
2603
+ dryRun: ctx.dryRun,
2604
+ environmentId: "",
2605
+ skipped: [...ctx.skipped],
2606
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
2607
+ changes: run.changes
2608
+ };
2609
+ }
2610
+ /** The shared edge's compose file, as this machine hands it to compose. */
2611
+ function edgeFile(run) {
2612
+ return (0, node_path.join)(run.dir, `${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}.yml`);
2613
+ }
2614
+ function applied(ctx, run, change) {
2615
+ const { via, ...rest } = change;
2616
+ run.changes.push(rest);
2617
+ ctx.emit({
2618
+ type: "resource.applied",
2619
+ ...rest,
2620
+ via
2621
+ });
2622
+ }
2623
+ /**
2624
+ * The root the check after a start trusts, PEM: gkm's on the local stage that
2625
+ * set no certificate of its own, and otherwise the one the stage's own names
2626
+ * (`deploy.compose.tls.<stage>.caFile`). Undefined — Node's own roots, and
2627
+ * `NODE_EXTRA_CA_CERTS` — for a certificate that names none: a public CA's.
2628
+ */
2629
+ async function verifyAuthority(stack) {
2630
+ if (stack.authority) return (await (0, _geekmidas_edge_certificates_local.readLocalAuthority)(stack.authority)).cert;
2631
+ if (stack.tls?.caFile) return (0, node_fs_promises.readFile)(stack.tls.caFile, "utf-8");
2632
+ }
2633
+ /**
2634
+ * The certificate the stack's proxy serves, PEM: the stage's own where it set
2635
+ * one, the one gkm's local CA issued the local stage otherwise, and none — a
2636
+ * deployed stage's comes from Let's Encrypt — when neither.
2637
+ */
2638
+ async function edgeCertificate(dir, stack) {
2639
+ if (stack.tls) return {
2640
+ cert: await (0, node_fs_promises.readFile)(stack.tls.certFile, "utf-8"),
2641
+ key: await (0, node_fs_promises.readFile)(stack.tls.keyFile, "utf-8")
2642
+ };
2643
+ if (stack.authority) return localEdgeCertificate(dir, stack, stack.authority);
2644
+ }
2645
+ /** Where the local stage's edge certificate is kept, between runs. */
2646
+ const LOCAL_EDGE_CERTIFICATE = "local-edge.pem";
2647
+ /**
2648
+ * The local stage's edge certificate, from gkm's local CA: the one kept in
2649
+ * the stack's directory while it still covers every host, so an unchanged
2650
+ * stack does not recreate its Caddy for a new certificate each run.
2651
+ */
2652
+ async function localEdgeCertificate(dir, stack, authority) {
2653
+ const { cert, key } = await (0, _geekmidas_edge_certificates_local.ensureLocalCertificate)(await (0, _geekmidas_edge_certificates_local.ensureLocalAuthority)(authority), (0, _geekmidas_edge_certificates_local.localCertificateNames)(stack.resolution.project ?? "", require_snsSubscriptions.stackHosts(stack)), (0, node_path.join)(dir, LOCAL_EDGE_CERTIFICATE));
2654
+ return {
2655
+ cert,
2656
+ key
2657
+ };
2658
+ }
2659
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
2660
+ async function writeStack(root, dir, stack, origin) {
2661
+ await (0, node_fs_promises.mkdir)(dir, {
2662
+ recursive: true,
2663
+ mode: 448
2664
+ });
2665
+ await (0, node_fs_promises.chmod)(dir, 448);
2666
+ const files = [];
2667
+ const write = async (path, content, mode = 420) => {
2668
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
2669
+ await (0, node_fs_promises.writeFile)(path, content, { mode });
2670
+ await (0, node_fs_promises.chmod)(path, mode);
2671
+ files.push(path);
2672
+ };
2673
+ const issued = await edgeCertificate(dir, stack);
2674
+ const tls = stack.proxy === "caddy" ? issued : void 0;
2675
+ const originTls = stack.proxy === "caddy" ? origin : void 0;
2676
+ const compose = stack.caddyfile !== void 0 ? require_stack.withCaddyConfigs(stack.compose, {
2677
+ caddyfile: stack.caddyfile,
2678
+ ...tls ? { tls } : {},
2679
+ ...originTls ? { origin: originTls } : {}
2680
+ }) : stack.compose;
2681
+ await write((0, node_path.join)(dir, "docker-compose.yml"), composeYaml(stack, compose), tls || originTls ? 384 : 420);
2682
+ if (stack.caddyfile !== void 0) {
2683
+ await write((0, node_path.join)(dir, "Caddyfile"), stack.caddyfile);
2684
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, "traefik.yml"), { force: true });
2685
+ } else await (0, node_fs_promises.rm)((0, node_path.join)(dir, "Caddyfile"), { force: true });
2686
+ if (stack.traefik !== void 0) await write((0, node_path.join)(dir, "traefik.yml"), stack.traefik);
2687
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, "tls"), {
2688
+ recursive: true,
2689
+ force: true
2690
+ });
2691
+ for (const app of [
2692
+ ...stack.apps,
2693
+ ...stack.workers,
2694
+ ...stack.processors
2695
+ ]) if (app.env) await write((0, node_path.join)(dir, `${app.name}.env`), require_stack.envFile(app.env), 384);
2696
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write((0, node_path.join)(dir, `${require_credentials$1.LOGS_SERVICE}.env`), require_stack.envFile(stack.logs.env), 384);
2697
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write((0, node_path.join)(dir, `${require_credentials$1.REDIS_SERVICE}.env`), require_stack.envFile(stack.redis.env), 384);
2698
+ if (stack.backups) {
2699
+ for (const [name, content] of Object.entries(stack.backups.files)) await write((0, node_path.join)(dir, require_stack.BACKUPS_SERVICE, name), content);
2700
+ if (stack.compose.services["backups"]?.env_file) await write((0, node_path.join)(dir, `${require_stack.BACKUPS_SERVICE}.env`), require_stack.envFile(stack.backups.env), 384);
2701
+ } else {
2702
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, require_stack.BACKUPS_SERVICE), {
2703
+ recursive: true,
2704
+ force: true
2705
+ });
2706
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, `${require_stack.BACKUPS_SERVICE}.env`), { force: true });
2707
+ }
2708
+ const pitr = stack.backups?.pitr;
2709
+ if (pitr) {
2710
+ for (const [name, content] of Object.entries(pitr.postgres.files)) await write((0, node_path.join)(dir, require_stack.POSTGRES_SERVICE, name), content);
2711
+ if (stack.compose.services["postgres"]?.env_file) await write((0, node_path.join)(dir, `${require_stack.POSTGRES_SERVICE}.env`), require_stack.envFile(pitr.postgres.env), 384);
2712
+ } else {
2713
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, require_stack.POSTGRES_SERVICE), {
2714
+ recursive: true,
2715
+ force: true
2716
+ });
2717
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, `${require_stack.POSTGRES_SERVICE}.env`), { force: true });
2718
+ }
2719
+ for (const entry of await (0, node_fs_promises.readdir)(dir)) if (entry.endsWith(".credentials")) await (0, node_fs_promises.rm)((0, node_path.join)(dir, entry));
2720
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write((0, node_path.join)(root, path), content);
2721
+ await require_stack.ensureDockerignore(require_stack.findBuildRoot(root));
2722
+ return files;
2723
+ }
2724
+ function composeYaml(stack, compose) {
2725
+ const stage = ` --stage ${stack.stage}`;
2726
+ return `# Generated by gkm compose from the construct manifest — do not edit.
2727
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${_geekmidas_edge_proxy_traefik.EDGE_PROJECT})`}, and its workers.
2728
+ # Each backend and worker reads exactly the keys in its own env file beside
2729
+ # this one.
2730
+ #
2731
+ # gkm compose${stage} start or update it
2732
+ # gkm compose${stage} --down stop it
2733
+ ${(0, yaml.stringify)(composeLiterals(compose), {
2734
+ lineWidth: 0,
2735
+ aliasDuplicateObjects: false
2736
+ })}`;
2737
+ }
2738
+ /**
2739
+ * The stack with each inline config's content escaped for compose, which
2740
+ * would otherwise read every `$` in it — a bcrypt hash's in the Caddyfile — as
2741
+ * a variable. Done here, where the file is written, so no inline file escapes
2742
+ * it: the stack itself holds each file as the container is to read it.
2743
+ */
2744
+ function composeLiterals(compose) {
2745
+ if (!compose.configs) return compose;
2746
+ return {
2747
+ ...compose,
2748
+ configs: Object.fromEntries(Object.entries(compose.configs).map(([name, { content }]) => [name, { content: (0, _geekmidas_edge.composeLiteral)(content) }]))
2749
+ };
2750
+ }
2751
+ function printPlan(ctx, run) {
2752
+ const { stack, mode, files } = run;
2753
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
2754
+ if (run.server) ctx.logger.info(` → ${sshTarget(run.server)} (docker over ssh)`);
2755
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
2756
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
2757
+ for (const unit of stack.processors) ctx.logger.info(` ${unit.name.padEnd(12)} ${`processors of ${unit.id}`.padEnd(40)} ${mode} ${unit.ref}`);
2758
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
2759
+ if (stack.backups) {
2760
+ ctx.logger.info(` ${require_stack.BACKUPS_SERVICE.padEnd(12)} ${stack.backups.databases.map((d) => d.file).join(", ")} — ${stack.backups.backups.describe}, to ${stack.backups.prefix}/`);
2761
+ if (stack.backups.pitr) ctx.logger.info(` ${"".padEnd(12)} ${stack.backups.pitr.pitr.describe}, to ${stack.backups.pitr.prefix}/`);
2762
+ }
2763
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${require_stack.stackDir(stack.stage)}/`);
2764
+ }
2765
+ //#endregion
2766
+ //#region src/target/compose/index.ts
2767
+ /**
2768
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
2769
+ * Caddy — the local stage on the machine that runs the deploy, a deployed
2770
+ * stage on its server's Docker engine, over SSH (`deploy.compose.server`).
2771
+ *
2772
+ * ```bash
2773
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
2774
+ * gkm deploy --target compose --stage production # built from here
2775
+ * gkm deploy --target compose --stage development # the local stage
2776
+ * ```
2777
+ *
2778
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
2779
+ * looked up in the registry — `ImageTagNotFound` before anything changes
2780
+ * - `ready`: a deploy's own checks, after the stage's keys are — the stage's
2781
+ * certificate, its server's address, and every public host's DNS
2782
+ * - `plan`: the stack's files and what a run would create or reuse
2783
+ * - `provision`: generated secrets kept, files written, infrastructure up,
2784
+ * databases, roles, grants and migrations
2785
+ * - `build`: each backend bundled on the host and every image built — or, for
2786
+ * a tag, pulled. A site that pre-renders against its stage
2787
+ * (`prerender: 'stage'`) is held back, but for a push, which first asks the
2788
+ * running stage's APIs and builds it against them
2789
+ * - `release`: the stack's routes on the shared edge; a held-back site built
2790
+ * once the rest of the stack is up and its APIs answer through the edge;
2791
+ * then `up --wait
2792
+ * --remove-orphans`, and each app's image, tag and digest in the stage's
2793
+ * state — an app that never turns healthy fails it only once the rest is
2794
+ * released and routed
2795
+ * - `verify`: each app asked through Caddy over HTTPS, then each
2796
+ * server-rendered site warmed — its `/` and its sitemap's pages asked, a
2797
+ * failure only warned of
2798
+ *
2799
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
2800
+ * every image and pushes it to `deploy.registry`, and does nothing else: no
2801
+ * readiness check runs, so a stage whose keys the deploy has yet to write
2802
+ * still builds.
2803
+ *
2804
+ * With `check` (`gkm compose --build --check`), also run with `buildOnly`,
2805
+ * every image built is started on this machine with the stage's secrets and
2806
+ * the stack's backing services, and must turn healthy before any is pushed
2807
+ * — see `startupCheck.ts`.
2808
+ *
2809
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
2810
+ * `--down`), run through the same `deploy()`.
2811
+ */
2812
+ var compose_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
2813
+ CHECK_LOG_LINES: () => 50,
2814
+ composeTarget: () => composeTarget
2815
+ });
2816
+ /** The compose target, with its Docker, bundler and probe as given. */
2817
+ function composeTarget(options = {}) {
2818
+ const { mode, push, check, pin, report, ...given } = options;
2819
+ const deps = {
2820
+ ...defaultDeps,
2821
+ ...given
2822
+ };
2823
+ return require_define.defineTarget({
2824
+ name: "compose",
2825
+ runtime: "server",
2826
+ capabilities: {
2827
+ rollback: false,
2828
+ migrations: "target",
2829
+ images: true,
2830
+ localStage: true,
2831
+ selfHostedTelemetry: true
2832
+ },
2833
+ credentials: [],
2834
+ tag: ({ cwd }) => deps.revision(cwd),
2835
+ validate: (ctx) => validateCompose(ctx, deps, {
2836
+ ...mode ? { mode } : {},
2837
+ ...push ? { push } : {},
2838
+ ...check ? { check } : {},
2839
+ ...pin ? { pin } : {}
2840
+ }),
2841
+ ready: (ctx, run) => readyCompose(ctx, run, deps),
2842
+ plan: (ctx, run) => planCompose(ctx, run),
2843
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
2844
+ build: (ctx, run) => buildCompose(ctx, run, deps),
2845
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
2846
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
2847
+ result: (ctx, run) => {
2848
+ report?.(run);
2849
+ return composeResult(ctx, run);
2850
+ }
2851
+ });
2852
+ }
2853
+ //#endregion
2854
+ Object.defineProperty(exports, "ComposePinNeedsPull", {
2855
+ enumerable: true,
2856
+ get: function() {
2857
+ return ComposePinNeedsPull;
2858
+ }
2859
+ });
2860
+ Object.defineProperty(exports, "ComposePushNeedsBuild", {
2861
+ enumerable: true,
2862
+ get: function() {
2863
+ return ComposePushNeedsBuild;
2864
+ }
2865
+ });
2866
+ Object.defineProperty(exports, "StartupCheckNeedsBuild", {
2867
+ enumerable: true,
2868
+ get: function() {
2869
+ return StartupCheckNeedsBuild;
2870
+ }
2871
+ });
2872
+ Object.defineProperty(exports, "assertCheckable", {
2873
+ enumerable: true,
2874
+ get: function() {
2875
+ return assertCheckable;
2876
+ }
2877
+ });
2878
+ Object.defineProperty(exports, "composeServer", {
2879
+ enumerable: true,
2880
+ get: function() {
2881
+ return composeServer;
2882
+ }
2883
+ });
2884
+ Object.defineProperty(exports, "composeTarget", {
2885
+ enumerable: true,
2886
+ get: function() {
2887
+ return composeTarget;
2888
+ }
2889
+ });
2890
+ Object.defineProperty(exports, "compose_exports", {
2891
+ enumerable: true,
2892
+ get: function() {
2893
+ return compose_exports;
2894
+ }
2895
+ });
2896
+ Object.defineProperty(exports, "deployedStackSecrets", {
2897
+ enumerable: true,
2898
+ get: function() {
2899
+ return deployedStackSecrets;
2900
+ }
2901
+ });
2902
+ Object.defineProperty(exports, "dockerHost", {
2903
+ enumerable: true,
2904
+ get: function() {
2905
+ return dockerHost;
2906
+ }
2907
+ });
2908
+ Object.defineProperty(exports, "parseDigests", {
2909
+ enumerable: true,
2910
+ get: function() {
2911
+ return parseDigests;
2912
+ }
2913
+ });
2914
+ Object.defineProperty(exports, "pinnedRef", {
2915
+ enumerable: true,
2916
+ get: function() {
2917
+ return pinnedRef;
2918
+ }
2919
+ });
2920
+ Object.defineProperty(exports, "sshAccess", {
2921
+ enumerable: true,
2922
+ get: function() {
2923
+ return sshAccess;
2924
+ }
2925
+ });
2926
+ Object.defineProperty(exports, "sshTarget", {
2927
+ enumerable: true,
2928
+ get: function() {
2929
+ return sshTarget;
2930
+ }
2931
+ });
2932
+ Object.defineProperty(exports, "stackOverrideFile", {
2933
+ enumerable: true,
2934
+ get: function() {
2935
+ return stackOverrideFile;
2936
+ }
2937
+ });
2938
+
2939
+ //# sourceMappingURL=compose-gnNrY3NQ.cjs.map