@geekmidas/cli 10.0.0-alpha.18 → 10.0.0-alpha.181

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 (448) 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-DvufVJjQ.cjs +124 -0
  11. package/dist/LegacyStateStore-DvufVJjQ.cjs.map +1 -0
  12. package/dist/LegacyStateStore-p-_Z8ucw.mjs +124 -0
  13. package/dist/LegacyStateStore-p-_Z8ucw.mjs.map +1 -0
  14. package/dist/LocalStateStore-BKAi5XsN.mjs +167 -0
  15. package/dist/LocalStateStore-BKAi5XsN.mjs.map +1 -0
  16. package/dist/LocalStateStore-DLDD6udB.cjs +178 -0
  17. package/dist/LocalStateStore-DLDD6udB.cjs.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-C8thID2w.mjs +223 -0
  23. package/dist/S3StateStore-C8thID2w.mjs.map +1 -0
  24. package/dist/S3StateStore-J3FztlVC.cjs +222 -0
  25. package/dist/S3StateStore-J3FztlVC.cjs.map +1 -0
  26. package/dist/SSMStateStore-0TQsme40.mjs +205 -0
  27. package/dist/SSMStateStore-0TQsme40.mjs.map +1 -0
  28. package/dist/SSMStateStore-DhkkSF1D.cjs +204 -0
  29. package/dist/SSMStateStore-DhkkSF1D.cjs.map +1 -0
  30. package/dist/SubscriberGenerator-B3jHf26s.mjs +787 -0
  31. package/dist/SubscriberGenerator-B3jHf26s.mjs.map +1 -0
  32. package/dist/SubscriberGenerator-JhwVlWBS.cjs +852 -0
  33. package/dist/SubscriberGenerator-JhwVlWBS.cjs.map +1 -0
  34. package/dist/add-DWCzdPLz.mjs +711 -0
  35. package/dist/add-DWCzdPLz.mjs.map +1 -0
  36. package/dist/add-gs34ewLG.cjs +713 -0
  37. package/dist/add-gs34ewLG.cjs.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/apps-C27qrbEe.cjs +5174 -0
  43. package/dist/apps-C27qrbEe.cjs.map +1 -0
  44. package/dist/apps-D2oTQasd.mjs +4650 -0
  45. package/dist/apps-D2oTQasd.mjs.map +1 -0
  46. package/dist/aws-BXfiWNbi.cjs +108 -0
  47. package/dist/aws-BXfiWNbi.cjs.map +1 -0
  48. package/dist/aws-BjvSTTcE.mjs +97 -0
  49. package/dist/aws-BjvSTTcE.mjs.map +1 -0
  50. package/dist/awsStore-BYYCmXiq.mjs +121 -0
  51. package/dist/awsStore-BYYCmXiq.mjs.map +1 -0
  52. package/dist/awsStore-DKQUElJL.cjs +138 -0
  53. package/dist/awsStore-DKQUElJL.cjs.map +1 -0
  54. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  55. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  56. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  57. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  58. package/dist/backups/runner.cjs +519 -0
  59. package/dist/backups/runner.cjs.map +1 -0
  60. package/dist/backups/runner.d.cts +102 -0
  61. package/dist/backups/runner.d.cts.map +1 -0
  62. package/dist/backups/runner.d.mts +102 -0
  63. package/dist/backups/runner.d.mts.map +1 -0
  64. package/dist/backups/runner.mjs +506 -0
  65. package/dist/backups/runner.mjs.map +1 -0
  66. package/dist/{bundler-mwH7WOb1.mjs → bundler-CbT4y4H_.mjs} +68 -15
  67. package/dist/bundler-CbT4y4H_.mjs.map +1 -0
  68. package/dist/{bundler-mjqGAvu1.cjs → bundler-DGeOugof.cjs} +67 -14
  69. package/dist/bundler-DGeOugof.cjs.map +1 -0
  70. package/dist/cli-C-jUNT69.cjs +80 -0
  71. package/dist/cli-C-jUNT69.cjs.map +1 -0
  72. package/dist/cli-DKEJryS7.mjs +80 -0
  73. package/dist/cli-DKEJryS7.mjs.map +1 -0
  74. package/dist/clientTelemetry-BAwj6MOf.d.cts +10 -0
  75. package/dist/clientTelemetry-BAwj6MOf.d.cts.map +1 -0
  76. package/dist/clientTelemetry-CvamPJj_.d.mts +10 -0
  77. package/dist/clientTelemetry-CvamPJj_.d.mts.map +1 -0
  78. package/dist/compose-BpnSP2x7.mjs +2434 -0
  79. package/dist/compose-BpnSP2x7.mjs.map +1 -0
  80. package/dist/compose-DJAaJEqL.cjs +2925 -0
  81. package/dist/compose-DJAaJEqL.cjs.map +1 -0
  82. package/dist/compose-DmtR2f0l.cjs +3564 -0
  83. package/dist/compose-DmtR2f0l.cjs.map +1 -0
  84. package/dist/compose-Glqs13is.mjs +3451 -0
  85. package/dist/compose-Glqs13is.mjs.map +1 -0
  86. package/dist/config-BODxZemw.d.mts +291 -0
  87. package/dist/config-BODxZemw.d.mts.map +1 -0
  88. package/dist/config-C3U5HulX.d.cts +291 -0
  89. package/dist/config-C3U5HulX.d.cts.map +1 -0
  90. package/dist/config.cjs +457 -9
  91. package/dist/config.cjs.map +1 -0
  92. package/dist/config.d.cts +4 -117
  93. package/dist/config.d.mts +4 -117
  94. package/dist/config.mjs +441 -3
  95. package/dist/config.mjs.map +1 -0
  96. package/dist/credentialSchemas-D_85KW2k.mjs +236 -0
  97. package/dist/credentialSchemas-D_85KW2k.mjs.map +1 -0
  98. package/dist/credentialSchemas-DjK6xKMk.cjs +271 -0
  99. package/dist/credentialSchemas-DjK6xKMk.cjs.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-DUudiQWj.cjs +154 -0
  105. package/dist/dbTunnel-DUudiQWj.cjs.map +1 -0
  106. package/dist/dbTunnel-KgbAh2v1.mjs +154 -0
  107. package/dist/dbTunnel-KgbAh2v1.mjs.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 +211 -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 +144 -0
  119. package/dist/deploy/public.mjs.map +1 -0
  120. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  121. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  122. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  123. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  124. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  125. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  126. package/dist/deploy/sniffer-hooks.cjs +1 -1
  127. package/dist/deploy/sniffer-hooks.mjs +1 -1
  128. package/dist/deploy/sniffer-loader.cjs +2 -2
  129. package/dist/deploy/sniffer-loader.mjs +1 -1
  130. package/dist/deploy/sniffer-routes-worker.cjs +2 -2
  131. package/dist/deploy/sniffer-routes-worker.mjs +1 -1
  132. package/dist/deploy-UkAiPzTp.mjs +3838 -0
  133. package/dist/deploy-UkAiPzTp.mjs.map +1 -0
  134. package/dist/deploy-ycRCutW9.cjs +3894 -0
  135. package/dist/deploy-ycRCutW9.cjs.map +1 -0
  136. package/dist/destroy-Cq5Un0kf.mjs +789 -0
  137. package/dist/destroy-Cq5Un0kf.mjs.map +1 -0
  138. package/dist/destroy-DzRzQcAR.cjs +790 -0
  139. package/dist/destroy-DzRzQcAR.cjs.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/dns-7zc-Mc9k.cjs +2257 -0
  145. package/dist/dns-7zc-Mc9k.cjs.map +1 -0
  146. package/dist/dns-dl7WUWmB.mjs +1820 -0
  147. package/dist/dns-dl7WUWmB.mjs.map +1 -0
  148. package/dist/docker-BDqp9Pfn.cjs +1798 -0
  149. package/dist/docker-BDqp9Pfn.cjs.map +1 -0
  150. package/dist/docker-MjMWQSEN.mjs +1649 -0
  151. package/dist/docker-MjMWQSEN.mjs.map +1 -0
  152. package/dist/dokploy-B0xtYCzY.mjs +38 -0
  153. package/dist/dokploy-B0xtYCzY.mjs.map +1 -0
  154. package/dist/dokploy-D-pBRnSV.cjs +38 -0
  155. package/dist/dokploy-D-pBRnSV.cjs.map +1 -0
  156. package/dist/drivers-BQRb3KsL.mjs +294 -0
  157. package/dist/drivers-BQRb3KsL.mjs.map +1 -0
  158. package/dist/drivers-DP7__dJX.cjs +377 -0
  159. package/dist/drivers-DP7__dJX.cjs.map +1 -0
  160. package/dist/eas-9danFNrJ.mjs +334 -0
  161. package/dist/eas-9danFNrJ.mjs.map +1 -0
  162. package/dist/eas-BJRA27vb.cjs +337 -0
  163. package/dist/eas-BJRA27vb.cjs.map +1 -0
  164. package/dist/emit-C4KSXOeS.mjs +153 -0
  165. package/dist/emit-C4KSXOeS.mjs.map +1 -0
  166. package/dist/emit-DiW0kbue.cjs +164 -0
  167. package/dist/emit-DiW0kbue.cjs.map +1 -0
  168. package/dist/encryption-0IiNCA3O.cjs +90 -0
  169. package/dist/encryption-0IiNCA3O.cjs.map +1 -0
  170. package/dist/encryption-ZDhvgGvu.mjs +89 -0
  171. package/dist/encryption-ZDhvgGvu.mjs.map +1 -0
  172. package/dist/engine-Csnr6XDu.mjs +3217 -0
  173. package/dist/engine-Csnr6XDu.mjs.map +1 -0
  174. package/dist/engine-DpjIgsGn.cjs +3330 -0
  175. package/dist/engine-DpjIgsGn.cjs.map +1 -0
  176. package/dist/errors-C9uIyIDt.mjs +27 -0
  177. package/dist/errors-C9uIyIDt.mjs.map +1 -0
  178. package/dist/errors-D1x8duqI.cjs +38 -0
  179. package/dist/errors-D1x8duqI.cjs.map +1 -0
  180. package/dist/github-Dej8EWxH.mjs +986 -0
  181. package/dist/github-Dej8EWxH.mjs.map +1 -0
  182. package/dist/github-HHxVur1m.cjs +987 -0
  183. package/dist/github-HHxVur1m.cjs.map +1 -0
  184. package/dist/googlePlay-DNrD-67X.mjs +931 -0
  185. package/dist/googlePlay-DNrD-67X.mjs.map +1 -0
  186. package/dist/googlePlay-NK1zgJJm.cjs +931 -0
  187. package/dist/googlePlay-NK1zgJJm.cjs.map +1 -0
  188. package/dist/iam-BzFyFf7T.mjs +442 -0
  189. package/dist/iam-BzFyFf7T.mjs.map +1 -0
  190. package/dist/iam-WIoKnLBp.cjs +521 -0
  191. package/dist/iam-WIoKnLBp.cjs.map +1 -0
  192. package/dist/{index-RCUizGxL.d.cts → index-BKgOlfK2.d.mts} +38 -14
  193. package/dist/index-BKgOlfK2.d.mts.map +1 -0
  194. package/dist/{index-B4H4XF7A.d.mts → index-zPzigXh-.d.cts} +38 -14
  195. package/dist/index-zPzigXh-.d.cts.map +1 -0
  196. package/dist/index.cjs +14502 -12767
  197. package/dist/index.cjs.map +1 -1
  198. package/dist/index.mjs +15137 -13400
  199. package/dist/index.mjs.map +1 -1
  200. package/dist/local-BW_VIsx0.cjs +241 -0
  201. package/dist/local-BW_VIsx0.cjs.map +1 -0
  202. package/dist/local-CVp-4wDb.mjs +224 -0
  203. package/dist/local-CVp-4wDb.mjs.map +1 -0
  204. package/dist/migrate-B8fq5egU.cjs +272 -0
  205. package/dist/migrate-B8fq5egU.cjs.map +1 -0
  206. package/dist/migrate-C8yCZ5P3.mjs +181 -0
  207. package/dist/migrate-C8yCZ5P3.mjs.map +1 -0
  208. package/dist/migrate-CkSq2f7k.mjs +267 -0
  209. package/dist/migrate-CkSq2f7k.mjs.map +1 -0
  210. package/dist/migrate-FOc2erAl.cjs +181 -0
  211. package/dist/migrate-FOc2erAl.cjs.map +1 -0
  212. package/dist/next.cjs +59 -0
  213. package/dist/next.cjs.map +1 -0
  214. package/dist/next.d.cts +44 -0
  215. package/dist/next.d.cts.map +1 -0
  216. package/dist/next.d.mts +44 -0
  217. package/dist/next.d.mts.map +1 -0
  218. package/dist/next.mjs +58 -0
  219. package/dist/next.mjs.map +1 -0
  220. package/dist/notes--JQyDHim.cjs +510 -0
  221. package/dist/notes--JQyDHim.cjs.map +1 -0
  222. package/dist/notes-DXl9qERh.mjs +409 -0
  223. package/dist/notes-DXl9qERh.mjs.map +1 -0
  224. package/dist/openapi.cjs +213 -7
  225. package/dist/openapi.cjs.map +1 -0
  226. package/dist/openapi.d.cts +27 -8
  227. package/dist/openapi.d.cts.map +1 -1
  228. package/dist/openapi.d.mts +27 -8
  229. package/dist/openapi.d.mts.map +1 -1
  230. package/dist/openapi.mjs +208 -2
  231. package/dist/openapi.mjs.map +1 -0
  232. package/dist/projectBucket-CGpcWqyY.cjs +263 -0
  233. package/dist/projectBucket-CGpcWqyY.cjs.map +1 -0
  234. package/dist/projectBucket-TigJy25c.mjs +222 -0
  235. package/dist/projectBucket-TigJy25c.mjs.map +1 -0
  236. package/dist/provider-BvjDbsTR.mjs +46 -0
  237. package/dist/provider-BvjDbsTR.mjs.map +1 -0
  238. package/dist/provider-DLhgo-mB.cjs +57 -0
  239. package/dist/provider-DLhgo-mB.cjs.map +1 -0
  240. package/dist/publish-BPfW3DWi.mjs +123 -0
  241. package/dist/publish-BPfW3DWi.mjs.map +1 -0
  242. package/dist/publish-D4pC6_G0.cjs +124 -0
  243. package/dist/publish-D4pC6_G0.cjs.map +1 -0
  244. package/dist/ready-BcV28QoW.mjs +375 -0
  245. package/dist/ready-BcV28QoW.mjs.map +1 -0
  246. package/dist/ready-ByQvw4-W.cjs +404 -0
  247. package/dist/ready-ByQvw4-W.cjs.map +1 -0
  248. package/dist/reconcile/public.cjs +3 -5
  249. package/dist/reconcile/public.d.cts +33 -89
  250. package/dist/reconcile/public.d.cts.map +1 -1
  251. package/dist/reconcile/public.d.mts +33 -89
  252. package/dist/reconcile/public.d.mts.map +1 -1
  253. package/dist/reconcile/public.mjs +3 -3
  254. package/dist/reconcile--I7V4Klj.mjs +34 -0
  255. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  256. package/dist/reconcile-CuCQBa5-.cjs +34 -0
  257. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  258. package/dist/resolve-BmBR1vBr.cjs +316 -0
  259. package/dist/resolve-BmBR1vBr.cjs.map +1 -0
  260. package/dist/resolve-DA1kORng.mjs +263 -0
  261. package/dist/resolve-DA1kORng.mjs.map +1 -0
  262. package/dist/rollback-DlgQDX8m.mjs +136 -0
  263. package/dist/rollback-DlgQDX8m.mjs.map +1 -0
  264. package/dist/rollback-tsy4pyEp.cjs +165 -0
  265. package/dist/rollback-tsy4pyEp.cjs.map +1 -0
  266. package/dist/runtime-CaejlcZt.d.mts +82 -0
  267. package/dist/runtime-CaejlcZt.d.mts.map +1 -0
  268. package/dist/runtime-D3jD4Dvn.d.cts +82 -0
  269. package/dist/runtime-D3jD4Dvn.d.cts.map +1 -0
  270. package/dist/s3-BLEF-PQU.cjs +240 -0
  271. package/dist/s3-BLEF-PQU.cjs.map +1 -0
  272. package/dist/s3-DVYiOqWs.mjs +240 -0
  273. package/dist/s3-DVYiOqWs.mjs.map +1 -0
  274. package/dist/sandbox/config-worker.cjs +43 -0
  275. package/dist/sandbox/config-worker.cjs.map +1 -0
  276. package/dist/sandbox/config-worker.d.cts +1 -0
  277. package/dist/sandbox/config-worker.d.mts +1 -0
  278. package/dist/sandbox/config-worker.mjs +44 -0
  279. package/dist/sandbox/config-worker.mjs.map +1 -0
  280. package/dist/sandbox/credentials-worker.cjs +53 -0
  281. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  282. package/dist/sandbox/credentials-worker.d.cts +1 -0
  283. package/dist/sandbox/credentials-worker.d.mts +1 -0
  284. package/dist/sandbox/credentials-worker.mjs +54 -0
  285. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  286. package/dist/sandbox/discover-worker.cjs +47 -0
  287. package/dist/sandbox/discover-worker.cjs.map +1 -0
  288. package/dist/sandbox/discover-worker.d.cts +1 -0
  289. package/dist/sandbox/discover-worker.d.mts +1 -0
  290. package/dist/sandbox/discover-worker.mjs +48 -0
  291. package/dist/sandbox/discover-worker.mjs.map +1 -0
  292. package/dist/sandbox/migrate-worker.cjs +75 -0
  293. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  294. package/dist/sandbox/migrate-worker.d.cts +1 -0
  295. package/dist/sandbox/migrate-worker.d.mts +1 -0
  296. package/dist/sandbox/migrate-worker.mjs +76 -0
  297. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  298. package/dist/{workspace-CRD9YinV.cjs → schemas-BCwKKA42.mjs} +399 -1179
  299. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  300. package/dist/{workspace-Bu3xNCej.mjs → schemas-BQ_v0lEX.cjs} +487 -982
  301. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  302. package/dist/secretsManager-CjTo6CRq.mjs +113 -0
  303. package/dist/secretsManager-CjTo6CRq.mjs.map +1 -0
  304. package/dist/secretsManager-CvmBGjdM.cjs +124 -0
  305. package/dist/secretsManager-CvmBGjdM.cjs.map +1 -0
  306. package/dist/seeds-Bc3niNVb.cjs +382 -0
  307. package/dist/seeds-Bc3niNVb.cjs.map +1 -0
  308. package/dist/seeds-Ccn0Ru2T.mjs +299 -0
  309. package/dist/seeds-Ccn0Ru2T.mjs.map +1 -0
  310. package/dist/serverSetup-B_O65wLb.cjs +685 -0
  311. package/dist/serverSetup-B_O65wLb.cjs.map +1 -0
  312. package/dist/serverSetup-Dsy8drIb.mjs +685 -0
  313. package/dist/serverSetup-Dsy8drIb.mjs.map +1 -0
  314. package/dist/sniffer-Ckx4cr-o.cjs +1997 -0
  315. package/dist/sniffer-Ckx4cr-o.cjs.map +1 -0
  316. package/dist/sniffer-fBefNUuJ.mjs +1824 -0
  317. package/dist/sniffer-fBefNUuJ.mjs.map +1 -0
  318. package/dist/snsSubscriptions-BJ0LErGk.mjs +1010 -0
  319. package/dist/snsSubscriptions-BJ0LErGk.mjs.map +1 -0
  320. package/dist/snsSubscriptions-ChbFp-QP.cjs +1135 -0
  321. package/dist/snsSubscriptions-ChbFp-QP.cjs.map +1 -0
  322. package/dist/sst-BnuPeGyy.cjs +501 -0
  323. package/dist/sst-BnuPeGyy.cjs.map +1 -0
  324. package/dist/sst-Y7H_zaEZ.mjs +478 -0
  325. package/dist/sst-Y7H_zaEZ.mjs.map +1 -0
  326. package/dist/stack-BAipv5Js.cjs +1887 -0
  327. package/dist/stack-BAipv5Js.cjs.map +1 -0
  328. package/dist/stack-BHrGbsGA.mjs +1777 -0
  329. package/dist/stack-BHrGbsGA.mjs.map +1 -0
  330. package/dist/stage-BSZ9890H.mjs +303 -0
  331. package/dist/stage-BSZ9890H.mjs.map +1 -0
  332. package/dist/stage-D7vBtLXL.cjs +332 -0
  333. package/dist/stage-D7vBtLXL.cjs.map +1 -0
  334. package/dist/stages-BeSQQQ4z.cjs +190 -0
  335. package/dist/stages-BeSQQQ4z.cjs.map +1 -0
  336. package/dist/stages-DjFKQv08.mjs +190 -0
  337. package/dist/stages-DjFKQv08.mjs.map +1 -0
  338. package/dist/target/public.cjs +15 -0
  339. package/dist/target/public.d.cts +28 -0
  340. package/dist/target/public.d.cts.map +1 -0
  341. package/dist/target/public.d.mts +28 -0
  342. package/dist/target/public.d.mts.map +1 -0
  343. package/dist/target/public.mjs +4 -0
  344. package/dist/terminal-B7G-FtkD.cjs +85 -0
  345. package/dist/terminal-B7G-FtkD.cjs.map +1 -0
  346. package/dist/terminal-lp8RwHdX.mjs +85 -0
  347. package/dist/terminal-lp8RwHdX.mjs.map +1 -0
  348. package/dist/{types-7R81hu0i.d.mts → types-CLxsw-QY.d.cts} +2135 -428
  349. package/dist/types-CLxsw-QY.d.cts.map +1 -0
  350. package/dist/{types-N7c2O2m7.d.cts → types-wLlwkSib.d.mts} +2133 -428
  351. package/dist/types-wLlwkSib.d.mts.map +1 -0
  352. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  353. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  354. package/dist/utils-D_fxUqvU.mjs +156 -0
  355. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  356. package/dist/vitest.cjs +65 -0
  357. package/dist/vitest.cjs.map +1 -0
  358. package/dist/vitest.d.cts +29 -0
  359. package/dist/vitest.d.cts.map +1 -0
  360. package/dist/vitest.d.mts +29 -0
  361. package/dist/vitest.d.mts.map +1 -0
  362. package/dist/vitest.mjs +65 -0
  363. package/dist/vitest.mjs.map +1 -0
  364. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  365. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  366. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  367. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  368. package/dist/workspace/index.cjs +6 -2
  369. package/dist/workspace/index.d.cts +3 -3
  370. package/dist/workspace/index.d.mts +3 -3
  371. package/dist/workspace/index.mjs +2 -2
  372. package/dist/workspace-DJjhfAGf.mjs +3027 -0
  373. package/dist/workspace-DJjhfAGf.mjs.map +1 -0
  374. package/dist/workspace-wTLnc1Ef.cjs +3577 -0
  375. package/dist/workspace-wTLnc1Ef.cjs.map +1 -0
  376. package/package.json +76 -13
  377. package/dist/HostingerProvider-BY26bWwB.mjs +0 -243
  378. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  379. package/dist/HostingerProvider-BZFGYYVA.cjs +0 -243
  380. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  381. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  382. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  383. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  384. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  385. package/dist/Route53Provider-Cvj40A8I.mjs +0 -209
  386. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  387. package/dist/Route53Provider-DVILBsvV.cjs +0 -209
  388. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  389. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  390. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  391. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  392. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  393. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  394. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  395. package/dist/bundler-mjqGAvu1.cjs.map +0 -1
  396. package/dist/bundler-mwH7WOb1.mjs.map +0 -1
  397. package/dist/config-DSXI480r.cjs +0 -467
  398. package/dist/config-DSXI480r.cjs.map +0 -1
  399. package/dist/config-DdKkoUE1.mjs +0 -414
  400. package/dist/config-DdKkoUE1.mjs.map +0 -1
  401. package/dist/config.d.cts.map +0 -1
  402. package/dist/config.d.mts.map +0 -1
  403. package/dist/credentials-C6Pfn6GY.cjs +0 -2939
  404. package/dist/credentials-C6Pfn6GY.cjs.map +0 -1
  405. package/dist/credentials-lbv-j0Be.mjs +0 -2802
  406. package/dist/credentials-lbv-j0Be.mjs.map +0 -1
  407. package/dist/discover-BERGFg8v.cjs +0 -288
  408. package/dist/discover-BERGFg8v.cjs.map +0 -1
  409. package/dist/discover-CK-n3w6b.mjs +0 -244
  410. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  411. package/dist/emit-BdoPFjZf.cjs +0 -253
  412. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  413. package/dist/emit-Bzq7JsMP.mjs +0 -224
  414. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  415. package/dist/generator-LfZU7NlU.mjs +0 -247
  416. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  417. package/dist/generator-Wdfp0jCS.cjs +0 -282
  418. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  419. package/dist/github-DlIrXPee.mjs +0 -216
  420. package/dist/github-DlIrXPee.mjs.map +0 -1
  421. package/dist/github-n7N9yOff.cjs +0 -216
  422. package/dist/github-n7N9yOff.cjs.map +0 -1
  423. package/dist/index-B4H4XF7A.d.mts.map +0 -1
  424. package/dist/index-RCUizGxL.d.cts.map +0 -1
  425. package/dist/openapi-B8bu_OXN.cjs +0 -2038
  426. package/dist/openapi-B8bu_OXN.cjs.map +0 -1
  427. package/dist/openapi-DfjbhrsM.mjs +0 -1991
  428. package/dist/openapi-DfjbhrsM.mjs.map +0 -1
  429. package/dist/reconcile-Cq4cO83R.cjs +0 -136
  430. package/dist/reconcile-Cq4cO83R.cjs.map +0 -1
  431. package/dist/reconcile-fmoluZmZ.mjs +0 -113
  432. package/dist/reconcile-fmoluZmZ.mjs.map +0 -1
  433. package/dist/ssm-BKN1Cg4z.mjs +0 -60
  434. package/dist/ssm-BKN1Cg4z.mjs.map +0 -1
  435. package/dist/ssm-FxeSAt35.cjs +0 -60
  436. package/dist/ssm-FxeSAt35.cjs.map +0 -1
  437. package/dist/storage-DgypfSD6.cjs +0 -351
  438. package/dist/storage-DgypfSD6.cjs.map +0 -1
  439. package/dist/storage-TP0x118M.mjs +0 -304
  440. package/dist/storage-TP0x118M.mjs.map +0 -1
  441. package/dist/transfer-2aRVVJ6I.mjs +0 -122
  442. package/dist/transfer-2aRVVJ6I.mjs.map +0 -1
  443. package/dist/transfer-C3WZVmj_.cjs +0 -151
  444. package/dist/transfer-C3WZVmj_.cjs.map +0 -1
  445. package/dist/types-7R81hu0i.d.mts.map +0 -1
  446. package/dist/types-N7c2O2m7.d.cts.map +0 -1
  447. package/dist/workspace-Bu3xNCej.mjs.map +0 -1
  448. package/dist/workspace-CRD9YinV.cjs.map +0 -1
@@ -0,0 +1,3564 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-D1x8duqI.cjs");
3
+ const require_dns = require("./dns-7zc-Mc9k.cjs");
4
+ const require_workspace = require("./workspace-wTLnc1Ef.cjs");
5
+ const require_apps = require("./apps-C27qrbEe.cjs");
6
+ const require_define = require("./define-zKgLY65H.cjs");
7
+ const require_compose = require("./compose-DJAaJEqL.cjs");
8
+ const require_drivers = require("./drivers-DP7__dJX.cjs");
9
+ const require_discover = require("./discover-OXczlq08.cjs");
10
+ const require_stack = require("./stack-BAipv5Js.cjs");
11
+ const require_docker = require("./docker-BDqp9Pfn.cjs");
12
+ const require_snsSubscriptions = require("./snsSubscriptions-ChbFp-QP.cjs");
13
+ const require_seeds = require("./seeds-Bc3niNVb.cjs");
14
+ const require_databases = require("./databases-DwYYH2mX.cjs");
15
+ let node_path = require("node:path");
16
+ let node_fs = require("node:fs");
17
+ let node_fs_promises = require("node:fs/promises");
18
+ let node_os = require("node:os");
19
+ let node_child_process = require("node:child_process");
20
+ let node_net = require("node:net");
21
+ let node_crypto = require("node:crypto");
22
+ let _geekmidas_edge_certificates_local = require("@geekmidas/edge/certificates/local");
23
+ let _geekmidas_edge_proxy_traefik = require("@geekmidas/edge/proxy/traefik");
24
+ let _geekmidas_manifest = require("@geekmidas/manifest");
25
+ let yaml = require("yaml");
26
+ let node_http = require("node:http");
27
+ let node_https = require("node:https");
28
+ //#region src/compose/docker.ts
29
+ /**
30
+ * The Docker operations `gkm compose` needs, behind an interface.
31
+ *
32
+ * Small on purpose, like reconcile's: the rules about *when* each runs — the
33
+ * registry is asked before anything is pulled, nothing is started for a tag
34
+ * that is missing — are asserted against a fake, and this file is only the
35
+ * wiring to the real CLI.
36
+ *
37
+ * Every call is an argument array. Image refs, tags and paths come from the
38
+ * workspace, and none of them reaches a shell.
39
+ */
40
+ /** `output` as `spawn` reads it. */
41
+ const STDIO = {
42
+ inherit: "inherit",
43
+ stderr: [
44
+ "ignore",
45
+ 2,
46
+ 2
47
+ ],
48
+ ignore: "ignore"
49
+ };
50
+ /**
51
+ * The environment a docker command for `engine` runs with: this process's,
52
+ * with `DOCKER_HOST` pointing at the stack's engine when it is a server's.
53
+ */
54
+ function engineEnv(engine, extra = {}) {
55
+ if (!engine.host && Object.keys(extra).length === 0) return void 0;
56
+ return {
57
+ ...process.env,
58
+ ...extra,
59
+ ...engine.host ? { DOCKER_HOST: engine.host } : {}
60
+ };
61
+ }
62
+ /** How a stack's docker commands run: where it is, where output goes. */
63
+ function runOptions(stack, extra) {
64
+ const env = engineEnv(stack, extra);
65
+ return {
66
+ cwd: stack.cwd,
67
+ stdio: STDIO[stack.output ?? "inherit"],
68
+ ...env ? { env } : {},
69
+ ...stack.signal ? { signal: stack.signal } : {}
70
+ };
71
+ }
72
+ /** The network compose puts a project's services on. */
73
+ function projectNetwork(project) {
74
+ return `${project}_default`;
75
+ }
76
+ /**
77
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
78
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
79
+ */
80
+ function publishedPorts(column) {
81
+ const ports = /* @__PURE__ */ new Set();
82
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
83
+ const first = Number(match[1]);
84
+ const last = match[2] ? Number(match[2]) : first;
85
+ for (let port = first; port <= last; port++) ports.add(port);
86
+ }
87
+ return [...ports];
88
+ }
89
+ /**
90
+ * The host port a `docker ps` Ports column publishes for `inside`:
91
+ * `127.0.0.1:54321->5432/tcp` is 54321.
92
+ */
93
+ function publishedPort(column, inside) {
94
+ const match = new RegExp(`(?:[\\d.]+|\\[[^\\]]*\\]):(\\d+)->${inside}/tcp`).exec(column);
95
+ return match ? Number(match[1]) : void 0;
96
+ }
97
+ /** Each line `docker ps` printed, as the containers holding `port`. */
98
+ function portHolders(output, port) {
99
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
100
+ container,
101
+ ...project ? { project } : {},
102
+ ...service ? { service } : {}
103
+ }));
104
+ }
105
+ /** How long a stack has to pass its health checks. */
106
+ const WAIT_TIMEOUT_S = 180;
107
+ /** `docker` itself failed, before it could say anything about a service. */
108
+ var DockerUnreachable = class extends require_errors.GkmError {
109
+ engine;
110
+ stderr;
111
+ constructor(engine, stderr) {
112
+ super(`Could not ask Docker on ${engine} which ports its services publish (docker said: ${stderr.trim() || "nothing"}). Check that \`DOCKER_HOST=${engine} docker ps\` works from here.`);
113
+ this.engine = engine;
114
+ this.stderr = stderr;
115
+ this.name = "DockerUnreachable";
116
+ }
117
+ };
118
+ /** `docker compose port` printed nothing a port can be read from. */
119
+ var ServicePortUnknown = class extends require_errors.GkmError {
120
+ service;
121
+ inside;
122
+ output;
123
+ constructor(service, inside, output) {
124
+ super(`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || "nothing"}). Is it running? \`docker compose ps\` shows the stack.`);
125
+ this.service = service;
126
+ this.inside = inside;
127
+ this.output = output;
128
+ this.name = "ServicePortUnknown";
129
+ }
130
+ };
131
+ /**
132
+ * Whether `ref` names a registry on this machine's loopback — which the
133
+ * daemon pulls from and pushes to over plain HTTP by default, and `docker
134
+ * manifest inspect` reaches only when told `--insecure` (without it, a local
135
+ * registry's image is reported as no such manifest).
136
+ */
137
+ function isLoopbackRegistry(ref) {
138
+ const first = ref.split("/")[0];
139
+ if (!ref.includes("/") || !/[.:]|^localhost$/.test(first)) return false;
140
+ const host = first.replace(/:\d+$/, "");
141
+ return host === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(host);
142
+ }
143
+ /** `docker push` finished without saying what digest the registry stored. */
144
+ var PushDigestUnknown = class extends require_errors.GkmError {
145
+ ref;
146
+ output;
147
+ constructor(ref, output) {
148
+ super(`Pushed ${ref}, but docker did not say which digest the registry stored (it said: ${output.trim().split("\n").slice(-3).join(" / ") || "nothing"}). Check the push with \`docker buildx imagetools inspect ${ref}\`.`);
149
+ this.ref = ref;
150
+ this.output = output;
151
+ this.name = "PushDigestUnknown";
152
+ }
153
+ };
154
+ /** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */
155
+ function pushedDigest(output) {
156
+ return [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)].at(-1)?.[1];
157
+ }
158
+ function compose(stack, args) {
159
+ return [
160
+ "compose",
161
+ "-p",
162
+ stack.project,
163
+ "-f",
164
+ stack.file,
165
+ ...(stack.overrides ?? []).flatMap((file) => ["-f", file]),
166
+ ...args
167
+ ];
168
+ }
169
+ /** Run a program and keep everything it said, whatever it exits with. */
170
+ function capture(command, args, options = {}) {
171
+ const { timeoutMs = 6e4 } = options;
172
+ return new Promise((resolve, reject) => {
173
+ const child = (0, node_child_process.spawn)(command, [...args], {
174
+ stdio: [
175
+ options.input === void 0 ? "ignore" : "pipe",
176
+ "pipe",
177
+ "pipe"
178
+ ],
179
+ shell: false,
180
+ ...options.env ? { env: options.env } : {}
181
+ });
182
+ if (options.input !== void 0) child.stdin?.end(options.input);
183
+ let stdout = "";
184
+ let stderr = "";
185
+ child.stdout?.on("data", (chunk) => {
186
+ stdout += chunk.toString();
187
+ });
188
+ child.stderr?.on("data", (chunk) => {
189
+ stderr += chunk.toString();
190
+ });
191
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
192
+ timer.unref?.();
193
+ child.on("error", (error) => {
194
+ clearTimeout(timer);
195
+ reject(error);
196
+ });
197
+ child.on("close", (code) => {
198
+ clearTimeout(timer);
199
+ resolve({
200
+ code,
201
+ stdout,
202
+ stderr
203
+ });
204
+ });
205
+ });
206
+ }
207
+ /**
208
+ * Whether a failed `docker manifest inspect` means the tag is not there, as
209
+ * opposed to the registry not answering.
210
+ *
211
+ * Read off the message because that is all the CLI gives. Anything not
212
+ * recognisably "no such tag" is treated as the registry being unreachable:
213
+ * a registry that refused credentials must not be reported as a tag that was
214
+ * never pushed, or the fix offered would be the wrong one.
215
+ */
216
+ function isMissingManifest(output) {
217
+ return /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(output);
218
+ }
219
+ const dockerCompose = {
220
+ async lookup(ref) {
221
+ const { code, stdout, stderr } = await capture("docker", [
222
+ "manifest",
223
+ "inspect",
224
+ ...isLoopbackRegistry(ref) ? ["--insecure"] : [],
225
+ ref
226
+ ]);
227
+ if (code === 0) return {
228
+ ref,
229
+ status: "found"
230
+ };
231
+ const output = `${stderr}\n${stdout}`.trim();
232
+ return isMissingManifest(output) ? {
233
+ ref,
234
+ status: "missing"
235
+ } : {
236
+ ref,
237
+ status: "unreachable",
238
+ detail: output
239
+ };
240
+ },
241
+ async build(stack, services) {
242
+ await require_dns.run("docker", compose(stack, ["build", ...services]), runOptions(stack, {
243
+ ...process.env,
244
+ DOCKER_BUILDKIT: "1"
245
+ }));
246
+ },
247
+ async pull(stack, services) {
248
+ await require_dns.run("docker", compose(stack, ["pull", ...services]), runOptions(stack));
249
+ },
250
+ async up(stack, services) {
251
+ await require_dns.run("docker", compose(stack, [
252
+ "up",
253
+ "-d",
254
+ "--wait",
255
+ `--wait-timeout=${WAIT_TIMEOUT_S}`,
256
+ ...services ? [] : ["--remove-orphans"],
257
+ ...services ?? []
258
+ ]), runOptions(stack));
259
+ },
260
+ async down(stack, options) {
261
+ const args = ["down", ...options?.volumes ? ["--volumes"] : []];
262
+ await require_dns.run("docker", (0, node_fs.existsSync)(stack.file) ? compose(stack, args) : [
263
+ "compose",
264
+ "-p",
265
+ stack.project,
266
+ ...args
267
+ ], runOptions(stack));
268
+ },
269
+ async port(stack, service, inside) {
270
+ const env = engineEnv(stack);
271
+ const output = await require_dns.runOutput("docker", compose(stack, [
272
+ "port",
273
+ service,
274
+ String(inside)
275
+ ]), {
276
+ cwd: stack.cwd,
277
+ ...env ? { env } : {},
278
+ ...stack.signal ? { signal: stack.signal } : {}
279
+ });
280
+ const port = Number(output.trim().split(":").pop());
281
+ if (!Number.isInteger(port) || port <= 0) throw new ServicePortUnknown(service, inside, output);
282
+ return port;
283
+ },
284
+ async health(stack, service) {
285
+ const env = engineEnv(stack);
286
+ const { code, stdout } = await capture("docker", compose(stack, [
287
+ "ps",
288
+ "--format",
289
+ "{{.Health}}",
290
+ service
291
+ ]), env ? { env } : {});
292
+ if (code !== 0) return void 0;
293
+ return stdout.trim().split("\n")[0] || void 0;
294
+ },
295
+ async push(stack, ref) {
296
+ const output = await require_dns.runOutput("docker", ["push", ref], {
297
+ cwd: stack.cwd,
298
+ ...stack.signal ? { signal: stack.signal } : {}
299
+ });
300
+ const digest = pushedDigest(output);
301
+ if (!digest) throw new PushDigestUnknown(ref, output);
302
+ return digest;
303
+ },
304
+ async digest(engine, ref) {
305
+ const env = engineEnv(engine);
306
+ const { code, stdout } = await capture("docker", [
307
+ "image",
308
+ "inspect",
309
+ "--format={{json .RepoDigests}} {{.Id}}",
310
+ ref
311
+ ], env ? { env } : {});
312
+ if (code !== 0) return void 0;
313
+ const [json = "[]", id] = stdout.trim().split(" ");
314
+ const repository = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
315
+ try {
316
+ const digests = JSON.parse(json);
317
+ const match = Array.isArray(digests) ? digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`)) : void 0;
318
+ if (match) return match.slice(repository.length + 1);
319
+ } catch {}
320
+ return id || void 0;
321
+ },
322
+ async ensureNetwork(engine, name) {
323
+ const env = engineEnv(engine);
324
+ const options = env ? { env } : {};
325
+ const { code } = await capture("docker", [
326
+ "network",
327
+ "inspect",
328
+ name
329
+ ], options);
330
+ if (code === 0) return;
331
+ const created = await capture("docker", [
332
+ "network",
333
+ "create",
334
+ name
335
+ ], options);
336
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
337
+ },
338
+ async publishers(engine, port) {
339
+ const env = engineEnv(engine);
340
+ const { stdout } = await capture("docker", [
341
+ "ps",
342
+ "--format",
343
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
344
+ ], env ? { env } : {});
345
+ return portHolders(stdout, port);
346
+ },
347
+ async exec(stack, service, command, input) {
348
+ const env = engineEnv(stack);
349
+ const options = env ? { env } : {};
350
+ const { stdout: ids } = await capture("docker", [
351
+ "ps",
352
+ "-q",
353
+ "--filter",
354
+ `label=com.docker.compose.project=${stack.project}`,
355
+ "--filter",
356
+ `label=com.docker.compose.service=${service}`
357
+ ], options);
358
+ const container = ids.trim().split("\n")[0];
359
+ if (!container) return {
360
+ code: null,
361
+ stdout: "",
362
+ stderr: `${service} is not running`
363
+ };
364
+ return capture("docker", [
365
+ "exec",
366
+ ...input === void 0 ? [] : ["-i"],
367
+ container,
368
+ ...command
369
+ ], {
370
+ ...options,
371
+ ...input === void 0 ? {} : { input }
372
+ });
373
+ },
374
+ async container(engine, project, service) {
375
+ const env = engineEnv(engine);
376
+ const { stdout } = await capture("docker", [
377
+ "ps",
378
+ "--filter",
379
+ `label=com.docker.compose.project=${project}`,
380
+ "--filter",
381
+ `label=com.docker.compose.service=${service}`,
382
+ "--format",
383
+ "{{.ID}} {{.Image}}"
384
+ ], env ? { env } : {});
385
+ const [id, image] = stdout.trim().split("\n")[0]?.split(" ") ?? [];
386
+ return id && image ? {
387
+ id,
388
+ image
389
+ } : void 0;
390
+ },
391
+ async published(engine, project, service, inside) {
392
+ const env = engineEnv(engine);
393
+ const { code, stdout, stderr } = await capture("docker", [
394
+ "ps",
395
+ "--filter",
396
+ `label=com.docker.compose.project=${project}`,
397
+ "--filter",
398
+ `label=com.docker.compose.service=${service}`,
399
+ "--format",
400
+ "{{.Ports}}"
401
+ ], env ? { env } : {});
402
+ if (code !== 0) throw new DockerUnreachable(engine.host ?? "this machine", stderr);
403
+ return publishedPort(stdout, inside);
404
+ },
405
+ async stop(engine, project, keep) {
406
+ const env = engineEnv(engine);
407
+ const options = env ? { env } : {};
408
+ const listed = await capture("docker", [
409
+ "ps",
410
+ "--filter",
411
+ `label=com.docker.compose.project=${project}`,
412
+ "--format",
413
+ "{{.ID}} {{.Label \"com.docker.compose.service\"}}"
414
+ ], options);
415
+ if (listed.code !== 0) throw new DockerUnreachable(engine.host ?? "this machine", listed.stderr);
416
+ const ids = listed.stdout.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, service = ""]) => !keep.includes(service)).map(([id = ""]) => id).filter(Boolean);
417
+ if (ids.length === 0) return [];
418
+ const stopped = await capture("docker", ["stop", ...ids], {
419
+ ...options,
420
+ timeoutMs: 12e4
421
+ });
422
+ if (stopped.code !== 0) throw new ContainersNotStopped(project, ids, stopped.stderr);
423
+ return ids;
424
+ },
425
+ async start(engine, ids) {
426
+ if (ids.length === 0) return;
427
+ const env = engineEnv(engine);
428
+ const started = await capture("docker", ["start", ...ids], {
429
+ ...env ? { env } : {},
430
+ timeoutMs: 12e4
431
+ });
432
+ if (started.code !== 0) throw new ContainersNotStarted(ids, started.stderr);
433
+ },
434
+ async remove(engine, project, service) {
435
+ const env = engineEnv(engine);
436
+ const options = env ? { env } : {};
437
+ const listed = await capture("docker", [
438
+ "ps",
439
+ "--all",
440
+ "--filter",
441
+ `label=com.docker.compose.project=${project}`,
442
+ "--filter",
443
+ `label=com.docker.compose.service=${service}`,
444
+ "--format",
445
+ "{{.ID}}"
446
+ ], options);
447
+ if (listed.code !== 0) throw new DockerUnreachable(engine.host ?? "this machine", listed.stderr);
448
+ const ids = listed.stdout.split("\n").filter(Boolean);
449
+ if (ids.length === 0) return [];
450
+ const removed = await capture("docker", [
451
+ "rm",
452
+ "--force",
453
+ ...ids
454
+ ], {
455
+ ...options,
456
+ timeoutMs: 12e4
457
+ });
458
+ if (removed.code !== 0) throw new ContainersNotRemoved(project, service, ids, removed.stderr);
459
+ return ids;
460
+ },
461
+ runOnce(engine, options) {
462
+ return dockerExit([
463
+ "run",
464
+ "--rm",
465
+ ...options.stdin ? ["-i"] : [],
466
+ "--network",
467
+ options.network,
468
+ ...Object.keys(options.env ?? {}).flatMap((name) => ["-e", name]),
469
+ "--entrypoint",
470
+ "",
471
+ options.image,
472
+ ...options.command
473
+ ], {
474
+ env: engineEnv(engine, { ...options.env }) ?? process.env,
475
+ ...options.stdin ? { stdin: options.stdin } : {},
476
+ ...options.output ? { output: options.output } : {}
477
+ });
478
+ }
479
+ };
480
+ /** Spawn `docker`, its output where `output` says; resolve with the exit code. */
481
+ function dockerExit(args, options = {}) {
482
+ const output = STDIO[options.output ?? "inherit"];
483
+ const out = Array.isArray(output) ? output : [
484
+ output,
485
+ output,
486
+ output
487
+ ];
488
+ return new Promise((resolve, reject) => {
489
+ const child = (0, node_child_process.spawn)("docker", [...args], {
490
+ stdio: [
491
+ options.stdin ? "pipe" : "ignore",
492
+ out[1],
493
+ out[2]
494
+ ],
495
+ env: options.env ?? process.env,
496
+ shell: false
497
+ });
498
+ let stdinFailed;
499
+ if (options.stdin && child.stdin) {
500
+ options.stdin.on("error", (error) => {
501
+ stdinFailed = error;
502
+ child.stdin?.destroy(error);
503
+ });
504
+ child.stdin.on("error", () => {});
505
+ options.stdin.pipe(child.stdin);
506
+ }
507
+ child.on("error", reject);
508
+ child.on("close", (code) => {
509
+ if (stdinFailed) reject(new StdinNotDelivered(stdinFailed));
510
+ else resolve(code ?? 1);
511
+ });
512
+ });
513
+ }
514
+ /** What a command run with {@link dockerExit} read from stdin failed partway. */
515
+ var StdinNotDelivered = class extends require_errors.GkmError {
516
+ reason;
517
+ constructor(reason) {
518
+ super(`The input to docker stopped before its end (${reason.message}), so the command only read part of it. Run it again.`);
519
+ this.reason = reason;
520
+ this.name = "StdinNotDelivered";
521
+ }
522
+ };
523
+ /** `docker stop` failed for some of a project's containers. */
524
+ var ContainersNotStopped = class extends require_errors.GkmError {
525
+ project;
526
+ ids;
527
+ output;
528
+ constructor(project, ids, output) {
529
+ super(`Could not stop ${project}'s containers ${ids.join(", ")} (docker said: ${output.trim() || "nothing"}). Check \`docker ps\` on the stage's server.`);
530
+ this.project = project;
531
+ this.ids = ids;
532
+ this.output = output;
533
+ this.name = "ContainersNotStopped";
534
+ }
535
+ };
536
+ /** `docker start` failed for containers that were stopped. */
537
+ var ContainersNotStarted = class extends require_errors.GkmError {
538
+ ids;
539
+ output;
540
+ constructor(ids, output) {
541
+ super(`Could not start the containers ${ids.join(", ")} again (docker said: ${output.trim() || "nothing"}). Start them on the stage's server with \`docker start ${ids.join(" ")}\`, or deploy the stage.`);
542
+ this.ids = ids;
543
+ this.output = output;
544
+ this.name = "ContainersNotStarted";
545
+ }
546
+ };
547
+ /** `docker rm` failed for a service's containers. */
548
+ var ContainersNotRemoved = class extends require_errors.GkmError {
549
+ project;
550
+ service;
551
+ ids;
552
+ output;
553
+ constructor(project, service, ids, output) {
554
+ super(`Could not remove ${project}'s ${service} containers ${ids.join(", ")} (docker said: ${output.trim() || "nothing"}). Remove them on the stage's server with \`docker rm --force ${ids.join(" ")}\`, and deploy again.`);
555
+ this.project = project;
556
+ this.service = service;
557
+ this.ids = ids;
558
+ this.output = output;
559
+ this.name = "ContainersNotRemoved";
560
+ }
561
+ };
562
+ /** `docker network create` failed. */
563
+ var NetworkCreateFailed = class extends require_errors.GkmError {
564
+ network;
565
+ output;
566
+ constructor(network, output) {
567
+ super(`Could not create the Docker network '${network}' (docker said: ${output.trim() || "nothing"}). Create it by hand with \`docker network create ${network}\` and run again.`);
568
+ this.network = network;
569
+ this.output = output;
570
+ this.name = "NetworkCreateFailed";
571
+ }
572
+ };
573
+ //#endregion
574
+ //#region src/compose/server.ts
575
+ /**
576
+ * Where a deployed compose stage runs: its server, reached over SSH.
577
+ *
578
+ * gkm never runs on the server. It runs where the deploy is started — a CI
579
+ * runner, a developer's machine — and drives the server's Docker engine over
580
+ * SSH (`DOCKER_HOST=ssh://user@host`), so the server holds Docker, an SSH
581
+ * login and nothing else: no gkm, no checkout, no cloud credentials.
582
+ *
583
+ * ```ts
584
+ * deploy: { compose: { server: { production: { user: 'deploy' } } } }
585
+ * ```
586
+ *
587
+ * The host is the stage's `GKM_SERVER_IPV4` secret — the address its DNS
588
+ * records already point at — unless `host` names another. The local stage is
589
+ * never given one: it runs on this machine's Docker.
590
+ *
591
+ * What the deploy needs from inside the server — Postgres and MinIO, published
592
+ * on the server's loopback alone — it reaches through an SSH tunnel on the same
593
+ * login, so neither is ever published publicly.
594
+ */
595
+ /** A deployed compose stage with nowhere to run. */
596
+ var ComposeServerMissing = class extends require_errors.GkmError {
597
+ stage;
598
+ missing;
599
+ constructor(stage, missing) {
600
+ 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.`);
601
+ this.stage = stage;
602
+ this.missing = missing;
603
+ this.name = "ComposeServerMissing";
604
+ }
605
+ };
606
+ /** SSH to the stage's server failed before anything was changed there. */
607
+ var ComposeServerUnreachable = class extends require_errors.GkmError {
608
+ target;
609
+ stderr;
610
+ constructor(target, stderr) {
611
+ 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.`);
612
+ this.target = target;
613
+ this.stderr = stderr;
614
+ this.name = "ComposeServerUnreachable";
615
+ }
616
+ };
617
+ /** An SSH tunnel to a port on the server's loopback did not open. */
618
+ var ComposeTunnelFailed = class extends require_errors.GkmError {
619
+ target;
620
+ remotePort;
621
+ stderr;
622
+ constructor(target, remotePort, stderr) {
623
+ 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 …\`).`);
624
+ this.target = target;
625
+ this.remotePort = remotePort;
626
+ this.stderr = stderr;
627
+ this.name = "ComposeTunnelFailed";
628
+ }
629
+ };
630
+ /**
631
+ * The stage's server: its login from `deploy.compose.server.<stage>`, its
632
+ * host from there or the stage's `GKM_SERVER_IPV4`. Undefined for the local
633
+ * stage, which runs on this machine.
634
+ *
635
+ * @throws {ComposeServerMissing} for a deployed stage with no login or host
636
+ */
637
+ function composeServer(options) {
638
+ const { stage } = options;
639
+ if (options.local) return void 0;
640
+ const config = options.config?.[stage];
641
+ if (!config) throw new ComposeServerMissing(stage, "config");
642
+ const host = config.host ?? options.custom?.["GKM_SERVER_IPV4"]?.trim();
643
+ if (!host) throw new ComposeServerMissing(stage, "host");
644
+ return {
645
+ user: config.user,
646
+ host,
647
+ port: config.port ?? 22
648
+ };
649
+ }
650
+ /** `user@host`, as a person types it after `ssh`. */
651
+ function sshTarget(server) {
652
+ return `${server.user}@${server.host}`;
653
+ }
654
+ /** The server's Docker engine, as `DOCKER_HOST` names it. */
655
+ function dockerHost(server) {
656
+ const host = server.host.includes(":") ? `[${server.host}]` : server.host;
657
+ return `ssh://${server.user}@${host}${server.port === 22 ? "" : `:${server.port}`}`;
658
+ }
659
+ /** The arguments every `ssh` gkm runs starts with: no prompt, ever. */
660
+ function sshArgs(server) {
661
+ return [
662
+ "-o",
663
+ "BatchMode=yes",
664
+ "-o",
665
+ "ConnectTimeout=20",
666
+ "-p",
667
+ String(server.port),
668
+ sshTarget(server)
669
+ ];
670
+ }
671
+ async function freeLocalPort() {
672
+ const server = (0, node_net.createServer)();
673
+ await new Promise((resolve, reject) => {
674
+ server.once("error", reject);
675
+ server.listen(0, "127.0.0.1", resolve);
676
+ });
677
+ const address = server.address();
678
+ await new Promise((resolve) => server.close(resolve));
679
+ if (!address || typeof address === "string") return 0;
680
+ return address.port;
681
+ }
682
+ function connects(port) {
683
+ return new Promise((resolve) => {
684
+ const socket = (0, node_net.createConnection)({
685
+ host: "127.0.0.1",
686
+ port
687
+ });
688
+ socket.once("connect", () => {
689
+ socket.destroy();
690
+ resolve(true);
691
+ });
692
+ socket.once("error", () => resolve(false));
693
+ });
694
+ }
695
+ /** The real one: the system's `ssh`, with the user's keys and known hosts. */
696
+ const sshAccess = {
697
+ check(server) {
698
+ return new Promise((resolve, reject) => {
699
+ const child = (0, node_child_process.spawn)("ssh", [
700
+ ...sshArgs(server),
701
+ "docker",
702
+ "version",
703
+ "--format",
704
+ "{{.Server.Version}}"
705
+ ], { stdio: [
706
+ "ignore",
707
+ "ignore",
708
+ "pipe"
709
+ ] });
710
+ let stderr = "";
711
+ child.stderr.on("data", (chunk) => {
712
+ stderr += chunk.toString();
713
+ });
714
+ child.on("error", (error) => reject(new ComposeServerUnreachable(sshTarget(server), error.message)));
715
+ child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeServerUnreachable(sshTarget(server), stderr)));
716
+ });
717
+ },
718
+ async tunnel(server, remotePort) {
719
+ const port = await freeLocalPort();
720
+ const child = (0, node_child_process.spawn)("ssh", [
721
+ "-N",
722
+ "-o",
723
+ "ExitOnForwardFailure=yes",
724
+ "-o",
725
+ "ControlPath=none",
726
+ "-L",
727
+ `127.0.0.1:${port}:127.0.0.1:${remotePort}`,
728
+ ...sshArgs(server)
729
+ ], { stdio: [
730
+ "ignore",
731
+ "ignore",
732
+ "pipe"
733
+ ] });
734
+ let stderr = "";
735
+ let exited = false;
736
+ child.stderr.on("data", (chunk) => {
737
+ stderr += chunk.toString();
738
+ });
739
+ child.on("exit", () => {
740
+ exited = true;
741
+ });
742
+ child.on("error", (error) => {
743
+ exited = true;
744
+ stderr += error.message;
745
+ });
746
+ const close = async () => {
747
+ if (exited) return;
748
+ const gone = new Promise((resolve) => child.once("exit", resolve));
749
+ child.kill("SIGTERM");
750
+ await gone;
751
+ };
752
+ for (let attempt = 0; attempt < 150; attempt++) {
753
+ if (exited) break;
754
+ if (await connects(port)) return {
755
+ port,
756
+ close
757
+ };
758
+ await new Promise((resolve) => setTimeout(resolve, 200));
759
+ }
760
+ await close();
761
+ throw new ComposeTunnelFailed(sshTarget(server), remotePort, stderr);
762
+ }
763
+ };
764
+ //#endregion
765
+ //#region src/compose/edge.ts
766
+ /**
767
+ * The server's shared Traefik edge, in Docker: started when a stack needs it,
768
+ * and each stack's routes written to — and removed from — the directory it
769
+ * watches.
770
+ *
771
+ * Everything goes through the server's Docker engine, never its filesystem:
772
+ * the edge's static configuration is handed to it inline, and the directories
773
+ * it watches are volumes each stack writes into with `docker exec`. So the
774
+ * deploy runs anywhere that reaches the engine — a CI runner over SSH — and
775
+ * nothing it writes depends on a path on that machine.
776
+ *
777
+ * gkm-edge (compose project — `GKM_EDGE_PROJECT` renames it)
778
+ * traefik.yml its static configuration (inline config)
779
+ * dynamic/<project>.yml one per stack: routers, services, middlewares
780
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
781
+ */
782
+ /** The edge's compose project, as docker is asked about it. */
783
+ function edgeRef(file, options = {}) {
784
+ return {
785
+ project: _geekmidas_edge_proxy_traefik.EDGE_PROJECT,
786
+ file,
787
+ cwd: (0, node_path.dirname)(file),
788
+ ...options
789
+ };
790
+ }
791
+ /** Writing to or removing from the edge's volumes failed. */
792
+ var EdgeWriteFailed = class extends require_errors.GkmError {
793
+ path;
794
+ output;
795
+ constructor(path, output) {
796
+ super(`Could not write ${path} in the shared edge (${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}): ${output.trim() || "it is not running"}. Check it with \`docker compose -p ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} ps\` on the server, and run gkm compose again.`);
797
+ this.path = path;
798
+ this.output = output;
799
+ this.name = "EdgeWriteFailed";
800
+ }
801
+ };
802
+ /**
803
+ * Something other than the proxy a stack is set to holds the edge's ports.
804
+ *
805
+ * With `proxy: 'traefik'`, any container but the shared edge and the stack's
806
+ * own Caddy, which the deploy moves (see {@link assertEdgePorts}); with
807
+ * `proxy: 'caddy'`, the shared edge, or another stack's Caddy. Refused before
808
+ * anything is started, so the stack is never left half on one proxy and half
809
+ * on the other.
810
+ */
811
+ var ComposeProxyClash = class extends require_errors.GkmError {
812
+ project;
813
+ proxy;
814
+ port;
815
+ holder;
816
+ constructor(project, proxy, port, holder) {
817
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
818
+ const fix = proxy === "traefik" ? `The shared edge needs ports 80 and 443. Stop ${holder.container}${holder.project ? ` (docker compose -p ${holder.project} down, or its own gkm compose --down)` : ""}, or move the edge with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.` : holder.project === _geekmidas_edge_proxy_traefik.EDGE_PROJECT ? `That is the server's shared Traefik edge, which other stacks register with. Set deploy.compose.proxy to 'traefik' for this stage so the stack registers with it too, or stop the edge once nothing uses it (docker compose -p ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} down).` : `Stop ${holder.container}, or publish this stack's Caddy elsewhere with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.`;
819
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
820
+ this.project = project;
821
+ this.proxy = proxy;
822
+ this.port = port;
823
+ this.holder = holder;
824
+ this.name = "ComposeProxyClash";
825
+ }
826
+ };
827
+ /**
828
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
829
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
830
+ *
831
+ * One holder is not refused: with `'traefik'`, the stack's own Caddy, still
832
+ * running from before the stage was switched. It is this stack's to move and
833
+ * no other's, so it is returned for the deploy to remove just before the edge
834
+ * takes the ports — the moment's downtime the switch costs. Undefined when
835
+ * there is nothing to move.
836
+ */
837
+ async function assertEdgePorts(docker, options) {
838
+ const { project, proxy, ports } = options;
839
+ const ownCaddy = (holder) => holder.project === project && holder.service === "caddy";
840
+ let move;
841
+ for (const port of [ports.https, ports.http]) for (const holder of await docker.publishers(options.engine, port)) {
842
+ if (proxy === "traefik" && ownCaddy(holder)) {
843
+ move = holder;
844
+ continue;
845
+ }
846
+ if (!(proxy === "traefik" ? holder.project === _geekmidas_edge_proxy_traefik.EDGE_PROJECT : ownCaddy(holder))) throw new ComposeProxyClash(project, proxy, port, holder);
847
+ }
848
+ return move;
849
+ }
850
+ /**
851
+ * Write a file into the edge's running container whole or not at all: a
852
+ * temporary name, then a rename. Not `.yml`: the edge reads only `.yml`,
853
+ * `.yaml` and `.toml` files, so it never sees one half written.
854
+ */
855
+ async function put(docker, edge, path, content, mode = "644") {
856
+ const result = await docker.exec(edge, _geekmidas_edge_proxy_traefik.EDGE_SERVICE, [
857
+ "sh",
858
+ "-c",
859
+ "set -e; t=\"$1.tmp\"; cat > \"$t\"; chmod \"$2\" \"$t\"; mv \"$t\" \"$1\"",
860
+ "sh",
861
+ path,
862
+ mode
863
+ ], content);
864
+ if (result.code !== 0) throw new EdgeWriteFailed(path, `${result.stderr}${result.stdout}`);
865
+ }
866
+ /** Remove files from the edge's container; whether the first was there. */
867
+ async function remove(docker, edge, paths) {
868
+ return (await docker.exec(edge, _geekmidas_edge_proxy_traefik.EDGE_SERVICE, [
869
+ "sh",
870
+ "-c",
871
+ "e=1; [ -f \"$1\" ] && e=0; rm -f \"$@\"; exit $e",
872
+ "sh",
873
+ ...paths
874
+ ])).code === 0;
875
+ }
876
+ /**
877
+ * The edge, up: its network and its container — started when it is not
878
+ * running, and recreated when its configuration changed. Idempotent: on a
879
+ * server where it already runs as configured, `up` changes nothing. Its
880
+ * compose file is written to `file`, on this machine: compose reads it here.
881
+ */
882
+ async function ensureEdge(docker, options) {
883
+ const { file, ports } = options;
884
+ const staticConfig = (0, _geekmidas_edge_proxy_traefik.traefikStaticFile)(ports);
885
+ const content = (0, _geekmidas_edge_proxy_traefik.edgeComposeFile)({
886
+ ports,
887
+ staticConfig,
888
+ logging: options.logging
889
+ });
890
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(file), { recursive: true });
891
+ if (await (0, node_fs_promises.readFile)(file, "utf-8").catch(() => void 0) !== content) await (0, node_fs_promises.writeFile)(file, content);
892
+ const ref = edgeRef(file, {
893
+ ...options.host ? { host: options.host } : {},
894
+ ...options.output ? { output: options.output } : {},
895
+ ...options.signal ? { signal: options.signal } : {}
896
+ });
897
+ await docker.ensureNetwork(ref, _geekmidas_edge_proxy_traefik.EDGE_NETWORK);
898
+ await docker.up(ref, [_geekmidas_edge_proxy_traefik.EDGE_SERVICE]);
899
+ return [file];
900
+ }
901
+ /** A file inside the edge's running container, or undefined where there is none. */
902
+ async function readEdgeFile(docker, edge, path) {
903
+ const result = await docker.exec(edge, _geekmidas_edge_proxy_traefik.EDGE_SERVICE, ["cat", path]);
904
+ return result.code === 0 ? result.stdout : void 0;
905
+ }
906
+ /** A file written into the edge's running container, whole, readable by it alone. */
907
+ async function writeEdgeSecret(docker, edge, path, content) {
908
+ await put(docker, edge, path, content, "600");
909
+ }
910
+ /**
911
+ * The edge restarted — what it reads once and keeps, a key among them, read
912
+ * again — and waited on until it is healthy. Its own restart policy brings
913
+ * it back; `up` waits for it.
914
+ */
915
+ async function restartEdge(docker, edge) {
916
+ await docker.exec(edge, _geekmidas_edge_proxy_traefik.EDGE_SERVICE, ["kill", "1"]);
917
+ await docker.up(edge, [_geekmidas_edge_proxy_traefik.EDGE_SERVICE]);
918
+ }
919
+ /** A stack's routes, inside the edge's container. */
920
+ function routesPath(project) {
921
+ return `${_geekmidas_edge_proxy_traefik.EDGE_DYNAMIC_DIR}/${project}.yml`;
922
+ }
923
+ /**
924
+ * A host this stack routes is already routed through the shared edge by
925
+ * another project: two routers for one host, and which stack serves it — and
926
+ * which gets its certificate — would be the edge's choice.
927
+ */
928
+ var EdgeHostClaimed = class extends require_errors.GkmError {
929
+ host;
930
+ owner;
931
+ project;
932
+ edge;
933
+ constructor(host, owner, project, edge = _geekmidas_edge_proxy_traefik.EDGE_PROJECT) {
934
+ super(`${project} routes ${host}, and ${owner} already routes it through the shared edge (${edge}) on this server. A host is served by one stack only. Give ${project} another domain, or take ${owner} off the edge first: gkm compose --stage <stage> --down in its workspace (or remove ${routesPath(owner)} from the edge).`);
935
+ this.host = host;
936
+ this.owner = owner;
937
+ this.project = project;
938
+ this.edge = edge;
939
+ this.name = "EdgeHostClaimed";
940
+ }
941
+ };
942
+ /**
943
+ * Every other stack's claims on the edge, by project: each `dynamic/*.yml`
944
+ * but this project's, read through the engine. None where the edge is not
945
+ * running — nothing is routed through it.
946
+ */
947
+ async function edgeClaimsByProject(docker, edge, project) {
948
+ const claimed = /* @__PURE__ */ new Map();
949
+ const listed = await docker.exec(edge, _geekmidas_edge_proxy_traefik.EDGE_SERVICE, [
950
+ "ls",
951
+ "-1",
952
+ _geekmidas_edge_proxy_traefik.EDGE_DYNAMIC_DIR
953
+ ]);
954
+ if (listed.code !== 0) return claimed;
955
+ for (const name of listed.stdout.split("\n").map((line) => line.trim())) {
956
+ if (!name.endsWith(".yml")) continue;
957
+ const owner = name.slice(0, -4);
958
+ if (!owner || owner === project) continue;
959
+ const file = await readEdgeFile(docker, edge, routesPath(owner));
960
+ if (file === void 0) continue;
961
+ const claims = (0, _geekmidas_edge_proxy_traefik.readEdgeClaims)(file);
962
+ if (claims.length > 0) claimed.set(owner, claims);
963
+ }
964
+ return claimed;
965
+ }
966
+ /**
967
+ * Refuse a stack's routes when a host in them is routed through the edge by
968
+ * another project — checked before a deploy changes anything, and again
969
+ * before its routes are written. Its own file, from its last deploy, is
970
+ * replaced, never a clash.
971
+ */
972
+ async function assertEdgeHostsFree(docker, edge, project, routes) {
973
+ const mine = (0, _geekmidas_edge_proxy_traefik.readEdgeClaims)(routes);
974
+ if (mine.length === 0) return;
975
+ const others = await edgeClaimsByProject(docker, edge, project);
976
+ for (const [owner, theirs] of [...others].sort(([a], [b]) => a.localeCompare(b))) for (const claim of mine) for (const other of theirs) {
977
+ const host = (0, _geekmidas_edge_proxy_traefik.claimsOverlap)(claim, other);
978
+ if (host !== void 0) throw new EdgeHostClaimed(host, owner, project, edge.project);
979
+ }
980
+ }
981
+ function certificatePaths(project) {
982
+ return [`${_geekmidas_edge_proxy_traefik.EDGE_CERTS_DIR}/${project}.crt`, `${_geekmidas_edge_proxy_traefik.EDGE_CERTS_DIR}/${project}.key`];
983
+ }
984
+ /**
985
+ * Register a stack with the edge — refused, before anything is written, when
986
+ * another project routes one of its hosts: its certificate first, where it has one,
987
+ * so the routes that need it never load without it — then its routes, in one
988
+ * rename the edge picks up whole. The certificate — the stage's own, or the
989
+ * one gkm's local CA issued the local stage — is PEM read on this machine and
990
+ * written through the engine. The paths written, inside the edge.
991
+ */
992
+ async function writeEdgeRoutes(docker, edge, project, routes, certificate) {
993
+ await assertEdgeHostsFree(docker, edge, project, routes);
994
+ const written = [];
995
+ const [crt, key] = certificatePaths(project);
996
+ if (certificate) {
997
+ await put(docker, edge, crt, certificate.cert);
998
+ await put(docker, edge, key, certificate.key, "600");
999
+ written.push(crt, key);
1000
+ } else await remove(docker, edge, [crt, key]);
1001
+ await put(docker, edge, routesPath(project), routes);
1002
+ written.push(routesPath(project));
1003
+ return written;
1004
+ }
1005
+ /** What a stack's file holds for the moment between emptying and removal. */
1006
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
1007
+ /**
1008
+ * Unregister a stack: its routes, then its certificate. Whether there was
1009
+ * anything to remove — false, too, when the edge is not running.
1010
+ */
1011
+ async function removeEdgeRoutes(docker, edge, project) {
1012
+ const file = routesPath(project);
1013
+ if ((await docker.exec(edge, _geekmidas_edge_proxy_traefik.EDGE_SERVICE, [
1014
+ "test",
1015
+ "-f",
1016
+ file
1017
+ ])).code !== 0) return false;
1018
+ await put(docker, edge, file, UNREGISTERED);
1019
+ await remove(docker, edge, [file, ...certificatePaths(project)]);
1020
+ return true;
1021
+ }
1022
+ //#endregion
1023
+ //#region src/compose/acmeDns.ts
1024
+ /**
1025
+ * The key the server's shared Traefik edge answers Let's Encrypt's DNS
1026
+ * challenge with, for a stage with a wildcard site.
1027
+ *
1028
+ * A wildcard certificate is issued only over the DNS challenge: the edge
1029
+ * proves it holds `<domain>` by writing a TXT record at
1030
+ * `_acme-challenge.<domain>`. So it needs a key that can write that record —
1031
+ * and nothing else, because it lives on the server.
1032
+ *
1033
+ * - **The user**: one per server, under `/gkm/`, tagged with the server it
1034
+ * is for. One that exists without that tag is someone else's, and is
1035
+ * refused rather than taken over.
1036
+ * - **Its policies**: one per stack on the server, named for its compose
1037
+ * project, allowing `ChangeResourceRecordSets` on the stage's hosted zone
1038
+ * for TXT records named `_acme-challenge.<domain>` alone — plus what
1039
+ * finding the zone and waiting for the change take, which read and write
1040
+ * nothing. Put back on every deploy.
1041
+ * - **Its key**: written into the edge's container, never into the stage's
1042
+ * secrets or onto the machine running the deploy. Issued when the edge
1043
+ * has none, or holds one IAM no longer knows — and then the edge is
1044
+ * restarted, since it keeps the key it first read.
1045
+ */
1046
+ /** Where gkm's IAM users live. */
1047
+ const USER_PATH = "/gkm/";
1048
+ /** The tag a server's edge user is found by. */
1049
+ const TAG_EDGE = "gkm:edge";
1050
+ /** The edge user's name for a server: stable, and safe for IAM. */
1051
+ function edgeAcmeUser(server) {
1052
+ return `gkm-edge-acme-${(0, node_crypto.createHash)("sha256").update(server).digest("hex").slice(0, 12)}`;
1053
+ }
1054
+ /**
1055
+ * What one stage's wildcard certificate needs: its challenge record written
1056
+ * in its zone, the change waited on, and the zone found by name — which is
1057
+ * how the edge's ACME client finds it.
1058
+ */
1059
+ function acmeDnsPolicy(zoneId, domain) {
1060
+ return JSON.stringify({
1061
+ Version: "2012-10-17",
1062
+ Statement: [
1063
+ {
1064
+ Effect: "Allow",
1065
+ Action: "route53:ChangeResourceRecordSets",
1066
+ Resource: `arn:aws:route53:::hostedzone/${zoneId}`,
1067
+ Condition: { "ForAllValues:StringEquals": {
1068
+ "route53:ChangeResourceRecordSetsNormalizedRecordNames": [`_acme-challenge.${domain.toLowerCase()}`],
1069
+ "route53:ChangeResourceRecordSetsRecordTypes": ["TXT"]
1070
+ } }
1071
+ },
1072
+ {
1073
+ Effect: "Allow",
1074
+ Action: "route53:ListResourceRecordSets",
1075
+ Resource: `arn:aws:route53:::hostedzone/${zoneId}`
1076
+ },
1077
+ {
1078
+ Effect: "Allow",
1079
+ Action: "route53:GetChange",
1080
+ Resource: "arn:aws:route53:::change/*"
1081
+ },
1082
+ {
1083
+ Effect: "Allow",
1084
+ Action: "route53:ListHostedZonesByName",
1085
+ Resource: "*"
1086
+ }
1087
+ ]
1088
+ });
1089
+ }
1090
+ /** An IAM user by the edge user's name that gkm did not create for this server. */
1091
+ var EdgeAcmeUserNotOwned = class extends require_errors.GkmError {
1092
+ user;
1093
+ server;
1094
+ constructor(user, server) {
1095
+ super(`The IAM user ${user} exists but is not tagged ${TAG_EDGE}=${server}, so gkm will not take it over to write the shared edge's DNS challenge records. Delete it, or tag it ${TAG_EDGE}=${server} if it is the one gkm created for this server.`);
1096
+ this.user = user;
1097
+ this.server = server;
1098
+ this.name = "EdgeAcmeUserNotOwned";
1099
+ }
1100
+ };
1101
+ /** A wildcard site's domain with no Route 53 hosted zone to answer it in. */
1102
+ var AcmeHostedZoneMissing = class extends require_errors.GkmError {
1103
+ domain;
1104
+ constructor(domain) {
1105
+ super(`No Route 53 hosted zone holds ${domain}, so the shared edge cannot answer the DNS challenge for its wildcard certificate. Create the zone, or set hostedZoneId in its dns entry.`);
1106
+ this.domain = domain;
1107
+ this.name = "AcmeHostedZoneMissing";
1108
+ }
1109
+ };
1110
+ /**
1111
+ * The edge's key for `domain`'s challenge record: its user, this stack's
1112
+ * policy on it, and a key in the edge that IAM knows.
1113
+ *
1114
+ * @throws {EdgeAcmeUserNotOwned} when the user is someone else's
1115
+ * @throws {AcmeHostedZoneMissing} when no hosted zone holds the domain
1116
+ */
1117
+ async function ensureEdgeAcmeKey(docker, options) {
1118
+ const { clients, edge, server, project, domain } = options;
1119
+ const log = options.log ?? ((line) => console.log(line));
1120
+ const IAM = await import("@aws-sdk/client-iam");
1121
+ const user = edgeAcmeUser(server);
1122
+ const zoneId = options.hostedZoneId ?? await hostedZoneId(clients.route53, options.zone);
1123
+ if (!zoneId) throw new AcmeHostedZoneMissing(domain);
1124
+ if (options.dryRun) {
1125
+ log(`🔑 Would let ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} write _acme-challenge.${domain} TXT records in ${zoneId}, as IAM user ${user} (dry run — nothing is written)`);
1126
+ return {
1127
+ user,
1128
+ zoneId,
1129
+ issued: false
1130
+ };
1131
+ }
1132
+ if (!(await clients.iam.send(new IAM.GetUserCommand({ UserName: user })).catch((error) => {
1133
+ if (error?.name === "NoSuchEntity" || error?.name === "NoSuchEntityException") return;
1134
+ throw error;
1135
+ }))?.User) await clients.iam.send(new IAM.CreateUserCommand({
1136
+ UserName: user,
1137
+ Path: USER_PATH,
1138
+ Tags: [{
1139
+ Key: TAG_EDGE,
1140
+ Value: server
1141
+ }]
1142
+ }));
1143
+ else {
1144
+ const { Tags = [] } = await clients.iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
1145
+ if (!Tags.some((t) => t.Key === "gkm:edge" && t.Value === server)) throw new EdgeAcmeUserNotOwned(user, server);
1146
+ }
1147
+ await clients.iam.send(new IAM.PutUserPolicyCommand({
1148
+ UserName: user,
1149
+ PolicyName: project,
1150
+ PolicyDocument: acmeDnsPolicy(zoneId, domain)
1151
+ }));
1152
+ log(`🔑 ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} may write _acme-challenge.${domain} TXT records in ${zoneId}, and nothing else there, as IAM user ${user}`);
1153
+ const written = await readEdgeFile(docker, edge, _geekmidas_edge_proxy_traefik.EDGE_AWS_CREDENTIALS);
1154
+ const held = written?.match(/aws_access_key_id\s*=\s*(\S+)/)?.[1];
1155
+ const { AccessKeyMetadata = [] } = await clients.iam.send(new IAM.ListAccessKeysCommand({ UserName: user }));
1156
+ if (held && AccessKeyMetadata.some((k) => k.AccessKeyId === held)) return {
1157
+ user,
1158
+ zoneId,
1159
+ issued: false
1160
+ };
1161
+ for (const key of AccessKeyMetadata) {
1162
+ if (!key.AccessKeyId) continue;
1163
+ await clients.iam.send(new IAM.DeleteAccessKeyCommand({
1164
+ UserName: user,
1165
+ AccessKeyId: key.AccessKeyId
1166
+ }));
1167
+ }
1168
+ const { AccessKey } = await clients.iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }));
1169
+ await writeEdgeSecret(docker, edge, _geekmidas_edge_proxy_traefik.EDGE_AWS_CREDENTIALS, `# Written by gkm compose — the key ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} answers DNS challenges with.
1170
+ [default]
1171
+ aws_access_key_id = ${AccessKey?.AccessKeyId}
1172
+ aws_secret_access_key = ${AccessKey?.SecretAccessKey}
1173
+ `);
1174
+ log(`🔑 Wrote a new key for ${user} to ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT} (${_geekmidas_edge_proxy_traefik.EDGE_AWS_CREDENTIALS})`);
1175
+ if (written !== void 0) await restartEdge(docker, edge);
1176
+ return {
1177
+ user,
1178
+ zoneId,
1179
+ issued: true
1180
+ };
1181
+ }
1182
+ /** The id of the hosted zone named exactly `zone`, if there is one. */
1183
+ async function hostedZoneId(route53, zone) {
1184
+ const { ListHostedZonesByNameCommand } = await import("@aws-sdk/client-route-53");
1185
+ const name = zone.endsWith(".") ? zone : `${zone}.`;
1186
+ const { HostedZones = [] } = await route53.send(new ListHostedZonesByNameCommand({
1187
+ DNSName: name,
1188
+ MaxItems: 1
1189
+ }));
1190
+ return HostedZones.find((z) => z.Name === name)?.Id?.replace("/hostedzone/", "");
1191
+ }
1192
+ //#endregion
1193
+ //#region src/compose/images.ts
1194
+ /**
1195
+ * Which image each app runs — and, for a tag, whether every one exists.
1196
+ *
1197
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
1198
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
1199
+ * image is asked of the registry before anything is pulled or the running
1200
+ * stack is touched, and one missing image stops the whole run naming every
1201
+ * one that is missing. Nor is a missing image quietly built instead — a build
1202
+ * of whatever is checked out here is not the release the tag names.
1203
+ */
1204
+ /** Images a tag names that the registry does not have. */
1205
+ var ImageTagNotFound = class extends require_errors.GkmError {
1206
+ tag;
1207
+ refs;
1208
+ constructor(tag, refs) {
1209
+ 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.`);
1210
+ this.tag = tag;
1211
+ this.refs = refs;
1212
+ this.name = "ImageTagNotFound";
1213
+ }
1214
+ };
1215
+ /** The registry did not answer, or did not let this machine in. */
1216
+ var RegistryUnreachable = class extends require_errors.GkmError {
1217
+ ref;
1218
+ detail;
1219
+ constructor(ref, detail) {
1220
+ 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>\`).`);
1221
+ this.ref = ref;
1222
+ this.detail = detail;
1223
+ this.name = "RegistryUnreachable";
1224
+ }
1225
+ };
1226
+ /**
1227
+ * A pinned image whose digest the registry would not give, while its tag it
1228
+ * would: the tag now names another image than the one the release pinned.
1229
+ *
1230
+ * Not a login problem — the registry answered for the tag. The tag was pushed
1231
+ * again (by another build of it), and the pinned image is gone, or cannot be
1232
+ * read, by its digest.
1233
+ */
1234
+ var PinnedImageMoved = class extends require_errors.GkmError {
1235
+ ref;
1236
+ detail;
1237
+ constructor(ref, detail) {
1238
+ const [tagged, digest] = ref.split("@");
1239
+ 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.`);
1240
+ this.ref = ref;
1241
+ this.detail = detail;
1242
+ this.name = "PinnedImageMoved";
1243
+ }
1244
+ };
1245
+ /**
1246
+ * The ref an image is asked of the registry by: a pinned one by its digest
1247
+ * alone (`<image>@sha256:…`), so a tag moved since the push cannot change the
1248
+ * answer; any other by its tag.
1249
+ */
1250
+ function lookupRef(ref) {
1251
+ const [tagged, digest] = ref.split("@");
1252
+ if (!digest) return ref;
1253
+ return `${tagged.replace(/:[\w][\w.-]*$/, "")}@${digest}`;
1254
+ }
1255
+ /**
1256
+ * Assert every image exists, before anything else happens.
1257
+ *
1258
+ * Asked all at once and reported all at once: a release missing two images is
1259
+ * one problem with two names, and finding the second only after fixing the
1260
+ * first is a slower way to learn the same thing.
1261
+ *
1262
+ * A pinned image is asked for by its digest. When the registry will not give
1263
+ * it, its tag is asked too: a tag that answers means the registry is reachable
1264
+ * and the tag names another image, and that is what is reported.
1265
+ *
1266
+ * @throws {PinnedImageMoved} when a pinned digest fails and its tag answers
1267
+ * @throws {RegistryUnreachable} when the registry cannot say
1268
+ * @throws {ImageTagNotFound} listing every missing image
1269
+ */
1270
+ async function assertImagesExist(docker, tag, images) {
1271
+ const lookups = await Promise.all(images.map(async (image) => ({
1272
+ image,
1273
+ lookup: await docker.lookup(lookupRef(image.ref))
1274
+ })));
1275
+ for (const { image, lookup } of lookups) {
1276
+ if (lookup.status === "found" || !image.ref.includes("@")) continue;
1277
+ if ((await docker.lookup(image.ref.split("@")[0])).status === "found") throw new PinnedImageMoved(image.ref, lookup.status === "unreachable" ? lookup.detail : "");
1278
+ }
1279
+ for (const { lookup } of lookups) if (lookup.status === "unreachable") throw new RegistryUnreachable(lookup.ref, lookup.detail);
1280
+ const missing = lookups.filter(({ lookup }) => lookup.status === "missing").map(({ image }) => image.ref);
1281
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
1282
+ }
1283
+ /**
1284
+ * A push or a pull with no `deploy.registry` to push to or pull from.
1285
+ *
1286
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
1287
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
1288
+ * from, somebody else's account. It is never a fallback.
1289
+ */
1290
+ var RegistryRequired = class extends require_errors.GkmError {
1291
+ operation;
1292
+ ref;
1293
+ constructor(operation, ref) {
1294
+ 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." : ""));
1295
+ this.operation = operation;
1296
+ this.ref = ref;
1297
+ this.name = "RegistryRequired";
1298
+ }
1299
+ };
1300
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
1301
+ function pinnedRef(ref, digest) {
1302
+ return `${ref.split("@")[0]}@${digest}`;
1303
+ }
1304
+ /** A digests file with no entry for an app the stack runs. */
1305
+ var ImageDigestMissing = class extends require_errors.GkmError {
1306
+ file;
1307
+ apps;
1308
+ constructor(file, apps) {
1309
+ 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.`);
1310
+ this.file = file;
1311
+ this.apps = apps;
1312
+ this.name = "ImageDigestMissing";
1313
+ }
1314
+ };
1315
+ /** A digests file entry that is not this app's image. */
1316
+ var ImageDigestMismatch = class extends require_errors.GkmError {
1317
+ app;
1318
+ expected;
1319
+ found;
1320
+ constructor(app, expected, found) {
1321
+ 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.`);
1322
+ this.app = app;
1323
+ this.expected = expected;
1324
+ this.found = found;
1325
+ this.name = "ImageDigestMismatch";
1326
+ }
1327
+ };
1328
+ /** A digests file that is not a JSON object of app to pinned ref. */
1329
+ var ImageDigestsInvalid = class extends require_errors.GkmError {
1330
+ file;
1331
+ detail;
1332
+ constructor(file, detail) {
1333
+ 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:…" }.`);
1334
+ this.file = file;
1335
+ this.detail = detail;
1336
+ this.name = "ImageDigestsInvalid";
1337
+ }
1338
+ };
1339
+ /** Parse a digests file's content, checking its shape. */
1340
+ function parseDigests(file, content) {
1341
+ let parsed;
1342
+ try {
1343
+ parsed = JSON.parse(content);
1344
+ } catch (error) {
1345
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
1346
+ }
1347
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
1348
+ 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`);
1349
+ return parsed;
1350
+ }
1351
+ /**
1352
+ * Each image pinned to the digest the file names for it.
1353
+ *
1354
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
1355
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
1356
+ */
1357
+ function pinImages(file, digests, images) {
1358
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
1359
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
1360
+ return images.map((image) => {
1361
+ const pinned = digests[image.app];
1362
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
1363
+ return {
1364
+ ...image,
1365
+ ref: pinned
1366
+ };
1367
+ });
1368
+ }
1369
+ //#endregion
1370
+ //#region src/compose/secrets.ts
1371
+ function deployedStackSecrets(workspace, stage, stored, manifest) {
1372
+ const withSeed = require_compose.withGeneratedSecrets(stored ?? require_dns.initStageSecrets(stage), manifest);
1373
+ const withLogs = require_workspace.resolveStageTelemetry({
1374
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1375
+ stage,
1376
+ local: false,
1377
+ target: "compose",
1378
+ runtime: "server",
1379
+ selfHosted: true,
1380
+ used: require_compose.usesTelemetry(manifest)
1381
+ })?.provider === "self-hosted" ? require_compose.withLogsLogin(withSeed.secrets, workspace.domains?.[stage]) : {
1382
+ secrets: withSeed.secrets,
1383
+ generated: []
1384
+ };
1385
+ const withRedis = require_compose.runsRedis(manifest, withLogs.secrets.custom ?? {}) ? require_compose.withRedisPassword(withLogs.secrets) : {
1386
+ secrets: withLogs.secrets,
1387
+ generated: []
1388
+ };
1389
+ return {
1390
+ secrets: withRedis.secrets,
1391
+ generated: [
1392
+ ...withSeed.generated,
1393
+ ...withLogs.generated,
1394
+ ...withRedis.generated
1395
+ ]
1396
+ };
1397
+ }
1398
+ //#endregion
1399
+ //#region src/target/compose/health.ts
1400
+ /**
1401
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
1402
+ * the way a browser reaches it.
1403
+ *
1404
+ * `docker compose up --wait` already knows each container passed its own
1405
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
1406
+ * the stack is reachable: whether the edge routes the host to the app, and
1407
+ * whether the certificate it presents is one a client accepts. So the check
1408
+ * goes through the edge, by hostname, and verifies the certificate.
1409
+ */
1410
+ /** A request that got no answer in time. */
1411
+ var HealthRequestTimedOut = class extends require_errors.GkmError {
1412
+ url;
1413
+ timeoutMs;
1414
+ constructor(url, timeoutMs) {
1415
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
1416
+ this.url = url;
1417
+ this.timeoutMs = timeoutMs;
1418
+ this.name = "HealthRequestTimedOut";
1419
+ }
1420
+ };
1421
+ /** The most of a body read — a sitemap may be 50 MB, and none needs to be. */
1422
+ const EDGE_BODY_LIMIT = 10485760;
1423
+ /** A body larger than {@link EDGE_BODY_LIMIT}. */
1424
+ var EdgeResponseTooLarge = class extends require_errors.GkmError {
1425
+ url;
1426
+ limit;
1427
+ constructor(url, limit) {
1428
+ super(`${url} answered with more than ${limit} bytes, which is more than gkm reads. Split it — a sitemap index can list several sitemaps.`);
1429
+ this.url = url;
1430
+ this.limit = limit;
1431
+ this.name = "EdgeResponseTooLarge";
1432
+ }
1433
+ };
1434
+ /**
1435
+ * The real request: one GET to the edge — over HTTPS, the certificate
1436
+ * verified, for an `https:` URL, and plain HTTP for an `http:` one — with
1437
+ * the URL's host as SNI and `Host` wherever it connects.
1438
+ */
1439
+ const edgeFetch = ({ url, ca, connectTo, connectPort, authorization, timeoutMs, signal, read, headers }) => {
1440
+ const target = new URL(url);
1441
+ const secure = target.protocol === "https:";
1442
+ const request = secure ? node_https.request : node_http.request;
1443
+ return new Promise((resolve, reject) => {
1444
+ const req = request({
1445
+ host: connectTo ?? target.hostname,
1446
+ port: connectPort ?? (target.port || (secure ? 443 : 80)),
1447
+ ...secure ? { servername: target.hostname } : {},
1448
+ path: `${target.pathname}${target.search}`,
1449
+ method: "GET",
1450
+ headers: {
1451
+ ...headers,
1452
+ host: target.host,
1453
+ ...authorization ? { authorization } : {}
1454
+ },
1455
+ ...secure && ca ? { ca } : {},
1456
+ ...signal ? { signal } : {},
1457
+ timeout: timeoutMs
1458
+ }, (res) => {
1459
+ const answered = {
1460
+ status: res.statusCode ?? 0,
1461
+ headers: res.headers
1462
+ };
1463
+ if (!read) {
1464
+ res.resume();
1465
+ res.on("end", () => resolve({
1466
+ ...answered,
1467
+ body: ""
1468
+ }));
1469
+ res.on("error", reject);
1470
+ return;
1471
+ }
1472
+ const chunks = [];
1473
+ let size = 0;
1474
+ res.on("data", (chunk) => {
1475
+ size += chunk.length;
1476
+ if (size > 10485760) {
1477
+ req.destroy(new EdgeResponseTooLarge(url, EDGE_BODY_LIMIT));
1478
+ return;
1479
+ }
1480
+ chunks.push(chunk);
1481
+ });
1482
+ res.on("end", () => resolve({
1483
+ ...answered,
1484
+ body: Buffer.concat(chunks).toString("utf-8")
1485
+ }));
1486
+ res.on("error", reject);
1487
+ });
1488
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
1489
+ req.on("error", reject);
1490
+ req.end();
1491
+ });
1492
+ };
1493
+ /** The real probe: one GET through the edge, answered by its status. */
1494
+ const httpsProbe = (request) => edgeFetch(request).then(({ status }) => status);
1495
+ /** Whether a status means the app answered as it should. */
1496
+ function isHealthy(status) {
1497
+ return status >= 200 && status < 400;
1498
+ }
1499
+ /**
1500
+ * Apps that are not healthy. `via` says which check said so:
1501
+ * - `edge`: verify asked each app through the edge, by its host, and it did
1502
+ * not answer as it should (a worker, with no route, by its container's
1503
+ * health);
1504
+ * - `docker`: `up --wait` failed, and these containers' own health checks
1505
+ * had not passed — the rest of the stack was released and routed first.
1506
+ * One class either way, so a caller matches one failure: apps not healthy.
1507
+ */
1508
+ var ComposeAppsUnhealthy = class extends require_errors.GkmError {
1509
+ project;
1510
+ apps;
1511
+ proxy;
1512
+ via;
1513
+ constructor(project, apps, proxy = "caddy", via = "edge") {
1514
+ const names = apps.map((a) => a.app).join(" ");
1515
+ 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}\`.`));
1516
+ this.project = project;
1517
+ this.apps = apps;
1518
+ this.proxy = proxy;
1519
+ this.via = via;
1520
+ this.name = "ComposeAppsUnhealthy";
1521
+ }
1522
+ };
1523
+ //#endregion
1524
+ //#region src/target/compose/topicSubscriptions.ts
1525
+ /**
1526
+ * Every topic subscriber the stack pushes to: a subscriber whose connection
1527
+ * key is a topic's publisher string — a bucket's events key is not — and
1528
+ * whose value on this stage is an SNS one.
1529
+ */
1530
+ function topicPushes(stack, manifest) {
1531
+ const topicKeys = new Set(Object.values(manifest).filter((declaration) => declaration.kind === "topic").map((topic) => (0, _geekmidas_manifest.providedKeyFor)(topic.id, topic.kind, "publisherConnectionString")));
1532
+ const pushes = [];
1533
+ for (const worker of stack.workers) for (const subscriber of worker.push?.subscribers ?? []) {
1534
+ if (!topicKeys.has(subscriber.connectionKey)) continue;
1535
+ const connectionString = worker.env?.[subscriber.connectionKey];
1536
+ if (!connectionString?.startsWith("sns:")) continue;
1537
+ pushes.push({
1538
+ worker: worker.id,
1539
+ name: subscriber.name,
1540
+ endpoint: subscriber.endpoint,
1541
+ connectionKey: subscriber.connectionKey,
1542
+ connectionString,
1543
+ ...subscriber.events ? { events: subscriber.events } : {}
1544
+ });
1545
+ }
1546
+ return pushes;
1547
+ }
1548
+ /** The subscriptions recorded for hand-set topics: those with a key. */
1549
+ function recordedTopicSubscriptions(resources) {
1550
+ return Object.values(resources ?? {}).filter((record) => record.type === "sns-subscription" && typeof record.data?.connectionKey === "string");
1551
+ }
1552
+ /**
1553
+ * Converge each hand-set topic's subscriptions on the subscribers pushed to:
1554
+ * subscribe, bring filters up to date, unsubscribe a route on the worker's
1555
+ * host no subscriber wants any more — and record each ARN, forgetting what
1556
+ * was removed.
1557
+ *
1558
+ * @returns each worker's subscriptions, by export — what it is handed
1559
+ */
1560
+ async function ensureTopicSubscriptions(input) {
1561
+ const { snsUrl, reconcileHttpSubscriptions } = await import("@geekmidas/events/sns");
1562
+ const groups = /* @__PURE__ */ new Map();
1563
+ const group = (topicArn, host, connectionKey) => {
1564
+ const id = `${topicArn}|${host}`;
1565
+ const found = groups.get(id);
1566
+ if (found) return found;
1567
+ const created = {
1568
+ topicArn,
1569
+ host,
1570
+ connectionKey,
1571
+ pushes: [],
1572
+ recorded: []
1573
+ };
1574
+ groups.set(id, created);
1575
+ return created;
1576
+ };
1577
+ for (const push of input.pushes) {
1578
+ const { topicArn } = snsUrl.parse(push.connectionString);
1579
+ const into = group(topicArn, new URL(push.endpoint).host, push.connectionKey);
1580
+ into.connectionString = push.connectionString;
1581
+ into.pushes.push(push);
1582
+ }
1583
+ 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);
1584
+ const provisioned = require_snsSubscriptions.provisionedTopics(input.recorded);
1585
+ const wanted = new Set(input.pushes.map(({ worker, name }) => require_snsSubscriptions.subscriptionKey(worker, name)));
1586
+ const arns = {};
1587
+ for (const { topicArn, host, connectionKey, ...members } of groups.values()) {
1588
+ const stale = members.recorded.filter((r) => !wanted.has(r.key));
1589
+ const named = members.connectionString ?? input.secrets[connectionKey];
1590
+ if (!named?.startsWith("sns:")) {
1591
+ for (const record of stale) {
1592
+ input.log(` – forgot ${record.data?.endpoint}: '${connectionKey}' no longer names an SNS topic to unsubscribe it from`);
1593
+ await input.forget(record.key);
1594
+ }
1595
+ continue;
1596
+ }
1597
+ const address = new URL(named);
1598
+ address.searchParams.set("topicArn", topicArn);
1599
+ const connection = await require_snsSubscriptions.topicConnection({
1600
+ connectionKey,
1601
+ connectionString: address.toString(),
1602
+ stage: input.stage,
1603
+ env: input.env,
1604
+ provisioned: provisioned.has(topicArn)
1605
+ });
1606
+ const result = await reconcileHttpSubscriptions(connection, {
1607
+ endpoints: members.pushes.map((push) => ({
1608
+ name: push.name,
1609
+ endpoint: push.endpoint,
1610
+ ...push.events ? { events: push.events } : {}
1611
+ })),
1612
+ ownedHost: host
1613
+ });
1614
+ await connection.close();
1615
+ for (const push of members.pushes) {
1616
+ const arn = result.subscriptions[push.name];
1617
+ const key = require_snsSubscriptions.subscriptionKey(push.worker, push.name);
1618
+ if (input.recorded?.[key]?.id !== arn) input.log(` ✓ '${push.name}' subscribed to ${topicArn.split(":").pop()} at ${push.endpoint}`);
1619
+ await input.record(require_snsSubscriptions.subscriptionResource({
1620
+ worker: push.worker,
1621
+ name: push.name,
1622
+ topicArn,
1623
+ endpoint: push.endpoint,
1624
+ connectionKey: push.connectionKey,
1625
+ pending: result.pending.includes(push.name),
1626
+ ...push.events ? { events: push.events } : {}
1627
+ }, arn));
1628
+ arns[push.worker] = {
1629
+ ...arns[push.worker],
1630
+ [push.name]: arn
1631
+ };
1632
+ }
1633
+ for (const arn of result.removed) input.log(` – unsubscribed ${arn}: no subscriber wants it any more`);
1634
+ for (const record of stale) await input.forget(record.key);
1635
+ }
1636
+ return arns;
1637
+ }
1638
+ /**
1639
+ * How long one page has to answer: a first render fetches from the site's
1640
+ * APIs, so it is given longer than a health check is.
1641
+ */
1642
+ const WARMUP_TIMEOUT_MS = 3e4;
1643
+ /**
1644
+ * Next's on-demand revalidation header: a request carrying the build's
1645
+ * preview-mode id is rendered afresh whatever the page's cache says.
1646
+ */
1647
+ const NEXT_REVALIDATE_HEADER = "x-prerender-revalidate";
1648
+ /**
1649
+ * What Next answered a request from: `HIT` and `STALE` are a cached copy —
1650
+ * on a fresh deploy, the build's — and the request rendered nothing.
1651
+ */
1652
+ const NEXT_CACHE_HEADER = "x-nextjs-cache";
1653
+ const FROM_CACHE = /* @__PURE__ */ new Set(["HIT", "STALE"]);
1654
+ /**
1655
+ * Asks the site for its `/sitemap.xml` — a sitemap index's sitemaps followed
1656
+ * one level — then for `/` and every page it lists, up to `maxUrls` pages in
1657
+ * all, `concurrency` at a time. The sitemap comes first so that, rendered
1658
+ * again with `headers`, it lists what the deployed APIs hold. Only pages on
1659
+ * the site's own origin are asked: a sitemap may list another's, which this
1660
+ * deploy did not start.
1661
+ */
1662
+ async function warmSite(options) {
1663
+ const { fetch, edge = {}, maxUrls = 500, concurrency = 4, timeoutMs = WARMUP_TIMEOUT_MS, headers } = options;
1664
+ const origin = new URL(options.url).origin;
1665
+ const result = {
1666
+ warmed: [],
1667
+ cached: [],
1668
+ warnings: [],
1669
+ leftOut: 0
1670
+ };
1671
+ /** One GET; a failure is a warning, and `undefined`. */
1672
+ const get = async (url, read) => {
1673
+ try {
1674
+ const response = await fetch({
1675
+ url,
1676
+ ...edge,
1677
+ ...headers ? { headers } : {},
1678
+ timeoutMs,
1679
+ read
1680
+ });
1681
+ const cache = response.headers?.[NEXT_CACHE_HEADER];
1682
+ if (typeof cache === "string" && FROM_CACHE.has(cache.toUpperCase())) result.cached.push(url);
1683
+ return response;
1684
+ } catch (error) {
1685
+ if (edge.signal?.aborted) throw error;
1686
+ result.warnings.push({
1687
+ url,
1688
+ reason: error instanceof HealthRequestTimedOut ? `no answer within ${error.timeoutMs}ms` : error instanceof Error ? error.message : String(error)
1689
+ });
1690
+ return;
1691
+ }
1692
+ };
1693
+ const warm = async (url) => {
1694
+ const response = await get(url, false);
1695
+ if (!response) return;
1696
+ if (isHealthy(response.status)) result.warmed.push(url);
1697
+ else result.warnings.push({
1698
+ url,
1699
+ reason: `HTTP ${response.status}`
1700
+ });
1701
+ };
1702
+ /** A sitemap's `<loc>`s, or none where it has none — or did not answer. */
1703
+ const sitemap = async (url) => {
1704
+ const response = await get(url, true);
1705
+ if (!response) return void 0;
1706
+ if (response.status >= 400 && response.status < 500) return void 0;
1707
+ if (!isHealthy(response.status)) {
1708
+ result.warnings.push({
1709
+ url,
1710
+ reason: `HTTP ${response.status}`
1711
+ });
1712
+ return;
1713
+ }
1714
+ return readSitemap(response.body);
1715
+ };
1716
+ const root = `${origin}/`;
1717
+ const pages = /* @__PURE__ */ new Set([root]);
1718
+ const sameOrigin = (loc) => {
1719
+ if (!URL.canParse(loc, root)) return void 0;
1720
+ const url = new URL(loc, root);
1721
+ url.hash = "";
1722
+ return url.origin === origin ? url.href : void 0;
1723
+ };
1724
+ const list = (locs) => {
1725
+ for (const loc of locs) {
1726
+ const url = sameOrigin(loc);
1727
+ if (url) pages.add(url);
1728
+ }
1729
+ };
1730
+ const top = await sitemap(`${origin}/sitemap.xml`);
1731
+ if (top?.kind === "index") {
1732
+ const read = await pool([...new Set(top.locs.map(sameOrigin).filter((u) => u !== void 0))], concurrency, sitemap);
1733
+ for (const child of read) if (child?.kind === "urlset") list(child.locs);
1734
+ } else if (top) list(top.locs);
1735
+ await warm(root);
1736
+ const listed = [...pages].slice(1);
1737
+ const room = Math.max(0, maxUrls - 1);
1738
+ result.leftOut = Math.max(0, listed.length - room);
1739
+ await pool(listed.slice(0, room), concurrency, warm);
1740
+ return result;
1741
+ }
1742
+ /**
1743
+ * Prints the preview-mode id of the prerender manifest at `argv[1]`, and
1744
+ * nothing else of it: the manifest's signing and encryption keys never leave
1745
+ * the container. Exit 3 when the manifest has no id.
1746
+ */
1747
+ const PRINT_PREVIEW_MODE_ID = [
1748
+ "let m;",
1749
+ "try { m = JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8')); }",
1750
+ "catch (e) { process.stderr.write(String(e && e.message)); process.exit(2); }",
1751
+ "const id = m && m.preview && m.preview.previewModeId;",
1752
+ "if (typeof id !== 'string' || id === '') process.exit(3);",
1753
+ "process.stdout.write(id);"
1754
+ ].join(" ");
1755
+ /**
1756
+ * The preview-mode id of a running Next site, from the prerender manifest
1757
+ * of its image — `manifest`, a path inside the container — by running the
1758
+ * image's own `node` in it through `exec` (`docker exec`, on whichever
1759
+ * engine runs the stack). Never read from this machine's disk: the image
1760
+ * that runs is the one whose id counts.
1761
+ *
1762
+ * The id is a secret of the site's: it is returned to the warm-up and
1763
+ * nowhere else — never logged, never written.
1764
+ */
1765
+ async function nextPreviewModeId(exec, manifest) {
1766
+ const { code, stdout, stderr } = await exec([
1767
+ "node",
1768
+ "-e",
1769
+ PRINT_PREVIEW_MODE_ID,
1770
+ manifest
1771
+ ]);
1772
+ if (code === 0 && stdout) return { id: stdout };
1773
+ if (code === 3 || code === 0) return { reason: `${manifest} has no preview.previewModeId, which this version of Next may not write` };
1774
+ const said = stderr.trim().split("\n")[0];
1775
+ if (code === null) return { reason: said || "its container is not running" };
1776
+ return { reason: `could not read ${manifest} in its container (${said || `exit ${code}`})` };
1777
+ }
1778
+ /**
1779
+ * Reads a sitemap (sitemaps.org): each entry's `<loc>`, entity-decoded or
1780
+ * from CDATA. Only an unprefixed `<loc>` is an entry's — an `<image:loc>` is
1781
+ * an image on a page, not a page.
1782
+ */
1783
+ function readSitemap(xml) {
1784
+ const kind = /<(?:[\w-]+:)?sitemapindex[\s>]/.test(xml) ? "index" : "urlset";
1785
+ const locs = [];
1786
+ for (const match of xml.matchAll(/<loc>\s*(?:<!\[CDATA\[([\s\S]*?)\]\]>|([\s\S]*?))\s*<\/loc>/g)) {
1787
+ const loc = match[1] ?? decodeEntities(match[2] ?? "");
1788
+ if (loc.trim()) locs.push(loc.trim());
1789
+ }
1790
+ return {
1791
+ kind,
1792
+ locs
1793
+ };
1794
+ }
1795
+ const ENTITIES = {
1796
+ amp: "&",
1797
+ lt: "<",
1798
+ gt: ">",
1799
+ quot: "\"",
1800
+ apos: "'"
1801
+ };
1802
+ function decodeEntities(text) {
1803
+ return text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (whole, entity) => {
1804
+ if (entity[0] === "#") {
1805
+ const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
1806
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
1807
+ }
1808
+ return ENTITIES[entity.toLowerCase()] ?? whole;
1809
+ });
1810
+ }
1811
+ /** Each item through `run`, at most `size` at once, results in order. */
1812
+ async function pool(items, size, run) {
1813
+ const results = new Array(items.length);
1814
+ let next = 0;
1815
+ const worker = async () => {
1816
+ while (next < items.length) {
1817
+ const index = next++;
1818
+ results[index] = await run(items[index]);
1819
+ }
1820
+ };
1821
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker));
1822
+ return results;
1823
+ }
1824
+ //#endregion
1825
+ //#region src/target/compose/phases.ts
1826
+ /**
1827
+ * The compose target's phases: a stage as one Docker Compose stack behind
1828
+ * Caddy — the local stage on this machine's Docker, a deployed stage on its
1829
+ * server's, driven over SSH (`compose/server.ts`) from wherever the deploy
1830
+ * runs.
1831
+ *
1832
+ * The order is the point of this file, and the rules it keeps are these:
1833
+ *
1834
+ * - A tag is checked before anything happens (`validate`). Every app's image
1835
+ * is asked of the registry first; one missing image stops the run naming
1836
+ * them all, and nothing is written, pulled or started.
1837
+ * - The databases exist before the apps do (`provision`). Postgres comes up
1838
+ * alone, its databases, roles and grants are created, its migrations
1839
+ * applied and its seeds run from this machine — through an SSH tunnel to a
1840
+ * server's loopback — and only then do the apps
1841
+ * start — so an app
1842
+ * never boots against a schema that is not there yet.
1843
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
1844
+ * was released under and the digest it resolved to are written to the
1845
+ * stage's state, so "what is this stage running" has an exact answer.
1846
+ * - What was started answers (`verify`): each app is asked through Caddy,
1847
+ * over HTTPS, with the certificate verified. Then each server-rendered site
1848
+ * is warmed (`warmup.ts`): a page that fails to warm is said, never failed.
1849
+ *
1850
+ * Every image is built inside Docker from a pruned slice of the build root —
1851
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
1852
+ * machine before `docker compose build`.
1853
+ *
1854
+ * Docker, the registry, Postgres and the health probe are
1855
+ * injected, so the rules are asserted without a daemon; the defaults are the
1856
+ * real ones.
1857
+ */
1858
+ /** `--push` without `--build`: there is nothing built here to push. */
1859
+ var ComposePushNeedsBuild = class extends require_errors.GkmError {
1860
+ constructor() {
1861
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
1862
+ this.name = "ComposePushNeedsBuild";
1863
+ }
1864
+ };
1865
+ /** Digests to run by, on a run that pulls nothing. */
1866
+ var ComposePinNeedsPull = class extends require_errors.GkmError {
1867
+ constructor() {
1868
+ 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.");
1869
+ this.name = "ComposePinNeedsPull";
1870
+ }
1871
+ };
1872
+ /** A port variable that does not hold a port. */
1873
+ var EdgePortInvalid = class extends require_errors.GkmError {
1874
+ variable;
1875
+ value;
1876
+ constructor(variable, value) {
1877
+ super(`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`);
1878
+ this.variable = variable;
1879
+ this.value = value;
1880
+ this.name = "EdgePortInvalid";
1881
+ }
1882
+ };
1883
+ /**
1884
+ * A site that pre-renders against its stage (`prerender: 'stage'`) whose
1885
+ * APIs do not answer, so it is not built: pages built without their data
1886
+ * would ship, and nothing at runtime could fill them.
1887
+ */
1888
+ var SitePrerenderApisDown = class extends require_errors.GkmError {
1889
+ site;
1890
+ apis;
1891
+ via;
1892
+ constructor(site, apis, via) {
1893
+ const lines = apis.map(({ app, url, last }) => via === "docker" ? ` - ${app}: Docker reports it ${last}` : ` - ${url}: ${last}`).join("\n");
1894
+ 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."));
1895
+ this.site = site;
1896
+ this.apis = apis;
1897
+ this.via = via;
1898
+ this.name = "SitePrerenderApisDown";
1899
+ }
1900
+ };
1901
+ /** A build with no commit to tag its images with. */
1902
+ var NoGitRevision = class extends require_errors.GkmError {
1903
+ root;
1904
+ constructor(root) {
1905
+ 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.`);
1906
+ this.root = root;
1907
+ this.name = "NoGitRevision";
1908
+ }
1909
+ };
1910
+ /**
1911
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
1912
+ * at the workspace root. What the generated file cannot know — a port bound
1913
+ * to a tailnet address, another log driver — goes there, and is never
1914
+ * overwritten.
1915
+ */
1916
+ function stackOverrideFile(root, stage) {
1917
+ return (0, node_path.join)(root, `docker-compose.${stage}.yml`);
1918
+ }
1919
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
1920
+ async function gitRevision(root) {
1921
+ let sha;
1922
+ try {
1923
+ sha = (await require_dns.runOutput("git", [
1924
+ "rev-parse",
1925
+ "--short",
1926
+ "HEAD"
1927
+ ], { cwd: root })).trim();
1928
+ } catch {
1929
+ throw new NoGitRevision(root);
1930
+ }
1931
+ if (!sha) throw new NoGitRevision(root);
1932
+ return (await require_dns.runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
1933
+ }
1934
+ /** The edge's ports, from the environment — 443 and 80 when unset. */
1935
+ function edgePorts(env = process.env) {
1936
+ const read = (variable, fallback) => {
1937
+ const value = env[variable];
1938
+ if (value === void 0 || value === "") return fallback;
1939
+ const port = Number(value);
1940
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new EdgePortInvalid(variable, value);
1941
+ return port;
1942
+ };
1943
+ const logs = env["GKM_COMPOSE_LOGS_PORT"] ? read(require_stack.LOGS_PORT_ENV, 0) : void 0;
1944
+ return {
1945
+ https: read(require_stack.EDGE_PORT_ENV.https, 443),
1946
+ http: read(require_stack.EDGE_PORT_ENV.http, 80),
1947
+ ...logs ? { logs } : {}
1948
+ };
1949
+ }
1950
+ /**
1951
+ * The real ones. Each app is asked for three minutes before it counts as
1952
+ * down: a deployed stage's first ACME certificate can take that long.
1953
+ */
1954
+ const defaultDeps = {
1955
+ docker: dockerCompose,
1956
+ revision: gitRevision,
1957
+ sql: require_apps.pgClient,
1958
+ buckets: require_apps.bucketClient,
1959
+ logins: require_apps.ensurePostgresLogin,
1960
+ migrate: require_databases.migrateDatabases,
1961
+ seed: require_databases.seedDatabases,
1962
+ probe: httpsProbe,
1963
+ fetch: edgeFetch,
1964
+ healthAttempts: 90,
1965
+ healthIntervalMs: 2e3,
1966
+ env: process.env,
1967
+ lookup: require_snsSubscriptions.systemLookup,
1968
+ server: sshAccess
1969
+ };
1970
+ /**
1971
+ * The stack the stage would run, and — for a tag — the registry's word that
1972
+ * every image it names exists. Nothing is written: a missing image stops the
1973
+ * run here, before a file, a secret or a container is touched.
1974
+ */
1975
+ async function validateCompose(ctx, deps, options = {}) {
1976
+ const { workspace, stage, identity, tag } = ctx;
1977
+ const root = workspace.root;
1978
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
1979
+ const push = options.push === true;
1980
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
1981
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
1982
+ const registry = workspace.deploy?.registry;
1983
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", require_dns.imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, require_dns.stageTag(tag, stage)));
1984
+ const background = {};
1985
+ const subscribers = {};
1986
+ const manifest = await require_discover.discover({
1987
+ patterns: require_apps.constructGlobs(workspace),
1988
+ cwd: root,
1989
+ background,
1990
+ subscribers
1991
+ });
1992
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
1993
+ const recorded = push ? void 0 : await ctx.state.read(stage);
1994
+ const layout = mode === "build" ? require_apps.imageLayout(workspace) : void 0;
1995
+ const input = {
1996
+ workspace,
1997
+ manifest,
1998
+ background,
1999
+ subscribers,
2000
+ stage,
2001
+ identity,
2002
+ images: {
2003
+ mode,
2004
+ tag,
2005
+ ...registry ? { registry } : {}
2006
+ },
2007
+ secrets,
2008
+ ...stage === workspace.stages.local ? { localCredentials: (await require_compose.loadLocalCredentials(workspace)).credentials } : {},
2009
+ allowDevServices: ctx.allowDevServices,
2010
+ ports: edgePorts(deps.env),
2011
+ ...layout ? { layout } : {},
2012
+ ...push ? { buildOnly: true } : {},
2013
+ ...mode === "build" ? { prerenderRun: (/* @__PURE__ */ new Date()).toISOString() } : {}
2014
+ };
2015
+ const recordedArns = require_snsSubscriptions.recordedPushSubscriptions(recorded?.resources);
2016
+ const planned = push ? void 0 : require_stack.composeStack({
2017
+ ...input,
2018
+ recordingSubscriptions: true
2019
+ });
2020
+ const pushes = planned ? topicPushes(planned, manifest) : [];
2021
+ const topics = planned && (pushes.length > 0 || recordedTopicSubscriptions(recorded?.resources).length > 0) ? {
2022
+ pushes,
2023
+ recorded: recorded?.resources
2024
+ } : void 0;
2025
+ const composed = topics && planned ? planned : require_stack.composeStack({
2026
+ ...input,
2027
+ pushSubscriptions: recordedArns
2028
+ });
2029
+ if (mode === "build") assertRedisClient(workspace, composed, manifest);
2030
+ const pinned = (unpinned) => options.pin ? withPinnedImages(unpinned, options.pin.file, options.pin.digests) : unpinned;
2031
+ const stack = pinned(composed);
2032
+ for (const warning of stack.warnings) ctx.logger.warn(`⚠ ${warning}`);
2033
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, require_dns.stageTag(tag, stage), [
2034
+ ...stack.apps,
2035
+ ...stack.workers,
2036
+ ...stack.processors
2037
+ ]);
2038
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
2039
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
2040
+ ctx.secrets.mask(stack.logs.password);
2041
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
2042
+ }
2043
+ if (!push && !stack.local) require_snsSubscriptions.requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
2044
+ const server = push ? void 0 : composeServer({
2045
+ stage,
2046
+ local: stack.local,
2047
+ config: workspace.deploy?.compose?.server,
2048
+ custom: secrets?.custom
2049
+ });
2050
+ const dir = (0, node_path.join)(root, require_stack.stackDir(stage));
2051
+ const override = stackOverrideFile(root, stage);
2052
+ const overrides = (0, node_fs.existsSync)(override) ? [override] : [];
2053
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
2054
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
2055
+ const { ref, tag, digest } = releases.current;
2056
+ return [name, {
2057
+ ref,
2058
+ ...tag ? { tag } : {},
2059
+ ...digest ? { digest } : {}
2060
+ }];
2061
+ }));
2062
+ return {
2063
+ mode,
2064
+ push,
2065
+ stack,
2066
+ ...topics ? { topicSubscriptions: {
2067
+ ...topics,
2068
+ restack: (arns) => {
2069
+ const merged = { ...recordedArns };
2070
+ for (const [worker, own] of Object.entries(arns)) merged[worker] = {
2071
+ ...merged[worker],
2072
+ ...own
2073
+ };
2074
+ return pinned(require_stack.composeStack({
2075
+ ...input,
2076
+ pushSubscriptions: merged
2077
+ }));
2078
+ }
2079
+ } } : {},
2080
+ ...server ? { server } : {},
2081
+ dir,
2082
+ ref: {
2083
+ project: require_stack.composeProject(identity),
2084
+ file: (0, node_path.join)(dir, "docker-compose.yml"),
2085
+ ...overrides.length > 0 ? { overrides } : {},
2086
+ cwd: root,
2087
+ ...server ? { host: dockerHost(server) } : {},
2088
+ output: ctx.childOutput,
2089
+ signal: ctx.signal
2090
+ },
2091
+ secrets,
2092
+ generated,
2093
+ previous,
2094
+ files: [],
2095
+ images: {},
2096
+ changes: []
2097
+ };
2098
+ }
2099
+ /**
2100
+ * What only a compose deploy checks before it changes anything, once the
2101
+ * stage's own keys are: the stage's own certificate is there, and every
2102
+ * public host points at the stage's server — its records written where a
2103
+ * provider holds them, then confirmed — before Caddy or Traefik ask Let's
2104
+ * Encrypt for a certificate it could not issue. A build-only run never asks.
2105
+ */
2106
+ async function readyCompose(ctx, run, deps) {
2107
+ const { stack } = run;
2108
+ if (stack.tls) {
2109
+ const { certFile, keyFile, caFile } = stack.tls;
2110
+ for (const file of [
2111
+ certFile,
2112
+ keyFile,
2113
+ ...caFile ? [caFile] : []
2114
+ ]) if (!(0, node_fs.existsSync)(file)) throw new require_workspace.ComposeTlsFileMissing(ctx.stage, file);
2115
+ }
2116
+ if (stack.local) {
2117
+ await edgeHostsFree(ctx, run, deps);
2118
+ return;
2119
+ }
2120
+ if (run.server && !ctx.dryRun && !run.push) await deps.server.check(run.server);
2121
+ await edgeHostsFree(ctx, run, deps);
2122
+ await logsPortOnServer(ctx, run, deps);
2123
+ const prune = await stageHostsDns(ctx, deps, require_snsSubscriptions.stackHosts(stack).filter((host) => !require_snsSubscriptions.isLocalHost(host)), run.secrets?.custom, stack.wildcard?.host);
2124
+ if (prune) run.pruneDns = prune;
2125
+ }
2126
+ /**
2127
+ * No host the stack routes through the shared edge is routed there by another
2128
+ * project — asked of the edge on the stage's engine before a record, a
2129
+ * secret, an image or a container is touched, so a clash fails the deploy
2130
+ * with nothing changed. Asked again as the routes are written
2131
+ * (`writeEdgeRoutes`), for an edge that was not running yet.
2132
+ */
2133
+ async function edgeHostsFree(ctx, run, deps) {
2134
+ const { stack, ref } = run;
2135
+ if (ctx.dryRun || run.push) return;
2136
+ if (stack.proxy !== "traefik" || !stack.traefik) return;
2137
+ await assertEdgeHostsFree(deps.docker, edgeRef(edgeFile(run), {
2138
+ ...ref.host ? { host: ref.host } : {},
2139
+ ...ref.output ? { output: ref.output } : {}
2140
+ }), stack.project, stack.traefik);
2141
+ }
2142
+ /** How many ports past the first a stage's OpenObserve is tried on. */
2143
+ const LOGS_PORT_TRIES = 100;
2144
+ /**
2145
+ * The loopback port the stack's OpenObserve is published on, settled against
2146
+ * what every other stack on the server publishes — before anything is
2147
+ * written, so two stages on one machine cannot both take `5080` and fail at
2148
+ * `up`.
2149
+ *
2150
+ * - A port the stage named is refused when another project holds it.
2151
+ * - Otherwise the stack keeps the port it already publishes, or takes the
2152
+ * first from the default up that no other project holds — and the stack,
2153
+ * its tunnel line included, is moved onto it.
2154
+ *
2155
+ * Asked of the server's engine, so not on a dry run, a push, or the local
2156
+ * stage; nor for a log UI served through the edge, which publishes nothing.
2157
+ *
2158
+ * @throws {LogsPortTaken}
2159
+ */
2160
+ async function logsPortOnServer(ctx, run, deps) {
2161
+ const logs = run.stack.logs;
2162
+ if (!logs || logs.public || run.stack.local) return;
2163
+ if (ctx.dryRun || run.push || !run.server) return;
2164
+ const engine = run.ref.host ? { host: run.ref.host } : {};
2165
+ const project = run.ref.project;
2166
+ const holder = async (port) => {
2167
+ const others = (await deps.docker.publishers(engine, port)).filter((held) => held.project !== project);
2168
+ return others[0] && (others[0].project ?? others[0].container);
2169
+ };
2170
+ if (logs.portSet) {
2171
+ const taken = await holder(logs.port);
2172
+ if (taken) throw new require_compose.LogsPortTaken(ctx.stage, logs.port, taken, true);
2173
+ return;
2174
+ }
2175
+ const kept = await deps.docker.published(engine, project, require_compose.LOGS_SERVICE, require_workspace.LOGS_PORT);
2176
+ let port = kept;
2177
+ if (port === void 0) {
2178
+ let taken;
2179
+ for (let next = logs.port; next < logs.port + LOGS_PORT_TRIES; next++) {
2180
+ taken = await holder(next);
2181
+ if (!taken) {
2182
+ port = next;
2183
+ break;
2184
+ }
2185
+ }
2186
+ if (port === void 0) throw new require_compose.LogsPortTaken(ctx.stage, logs.port, taken ?? "", false);
2187
+ }
2188
+ if (port !== logs.port) {
2189
+ 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`);
2190
+ run.stack = require_stack.withLogsPort(run.stack, port);
2191
+ }
2192
+ }
2193
+ /** A stack whose caches are in Redis, built for an app that has no client. */
2194
+ var RedisClientMissing = class extends require_errors.GkmError {
2195
+ apps;
2196
+ constructor(apps) {
2197
+ 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`);
2198
+ this.apps = apps;
2199
+ this.name = "RedisClientMissing";
2200
+ }
2201
+ };
2202
+ /**
2203
+ * Every backend and worker image whose process reaches a cache can resolve
2204
+ * `ioredis` — listed by its app or a directory above it, the way Node and
2205
+ * the image's install find it. A process that reaches no cache registers no
2206
+ * cache driver, so it needs no client.
2207
+ */
2208
+ function assertRedisClient(workspace, stack, manifest) {
2209
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
2210
+ const cacheKeys = Object.values(manifest).filter((d) => d.kind === "cache").flatMap((d) => d.provides ?? []);
2211
+ const reachesCache = (keys) => cacheKeys.some((key) => keys?.has(key));
2212
+ const missing = [.../* @__PURE__ */ new Set([...stack.apps.filter((app) => (app.kind === "rest-api" || app.kind === "websocket-api") && reachesCache(require_apps.appEnvKeys(manifest, app.name))).map((a) => a.name), ...stack.workers.filter((worker) => reachesCache(require_apps.workerEnvKeys(manifest, worker.id))).map((worker) => worker.host)])].filter((name) => {
2213
+ const app = workspace.apps[name];
2214
+ return app && !require_drivers.installedFrom((0, node_path.join)(workspace.root, app.path), "ioredis");
2215
+ }).sort();
2216
+ if (missing.length > 0) throw new RedisClientMissing(missing);
2217
+ }
2218
+ /**
2219
+ * The deploy's DNS step, for a deployed stage: its server's address — required
2220
+ * where it serves a real domain — then its own hosts written through each
2221
+ * domain's provider in `dns` where they differ, read back from it, and
2222
+ * recorded in the stage's state; hosts no provider writes resolved with the
2223
+ * system resolver. A dry run prints the plan and writes nothing, and warns
2224
+ * rather than stops. Returns the prune of the records gkm wrote for hosts the
2225
+ * stage no longer serves — which a dry run prints there and then.
2226
+ *
2227
+ * @throws {ServerAddressMissing} when the stage has a domain and no address
2228
+ * @throws {ServerAddressInvalid} for a value that is not an address
2229
+ * @throws {HostNotPointingAtServer} when a host is not the server
2230
+ */
2231
+ /**
2232
+ * The records the stack's DNS step weighs against its plan: every one gkm
2233
+ * wrote for the stage's hosts, and each a provider asked for on an earlier
2234
+ * deploy and not on this one — which the plan does not have either, so it is
2235
+ * pruned once the stack answers. One a provider asked for this run is not
2236
+ * the stack's to prune; nor is any provider's, when the providers did not
2237
+ * run.
2238
+ */
2239
+ function recordedForStack(recorded, providerDns) {
2240
+ const asked = new Set(providerDns ?? []);
2241
+ return recorded.filter((record) => record.source !== "provider" || providerDns !== void 0 && !asked.has(require_seeds.dnsResourceKey(record.fqdn, record.type)));
2242
+ }
2243
+ async function stageHostsDns(ctx, deps, hosts, custom, wildcard) {
2244
+ const { workspace, stage } = ctx;
2245
+ const server = require_snsSubscriptions.requiredServerAddress(stage, workspace.domains?.[stage], custom);
2246
+ if (hosts.length === 0) return;
2247
+ if (ctx.skipDns) {
2248
+ ctx.logger.info("🌐 DNS skipped (--skip-dns): no record is written or checked");
2249
+ return;
2250
+ }
2251
+ if (!server) {
2252
+ ctx.logger.info(`🌐 DNS skipped: no ${require_workspace.SERVER_IPV4_KEY} in '${stage}''s secrets — ${require_snsSubscriptions.serverAddressHint(stage)}`);
2253
+ return;
2254
+ }
2255
+ const log = (line) => ctx.logger.info(line);
2256
+ if (workspace.dns) log(`🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${ctx.dryRun ? " (dry run — nothing is written)" : ""}`);
2257
+ try {
2258
+ const stored = await ctx.state.read(stage);
2259
+ const result = await require_snsSubscriptions.stageDns({
2260
+ stage,
2261
+ hosts,
2262
+ server,
2263
+ dns: workspace.dns,
2264
+ recorded: recordedForStack(require_seeds.dnsResources(stored?.resources ?? {}), ctx.providerDns),
2265
+ ...wildcard ? { wildcard } : {},
2266
+ credentials: ctx.credentials,
2267
+ log,
2268
+ lookup: deps.lookup ?? require_snsSubscriptions.systemLookup,
2269
+ ...ctx.dryRun ? { dryRun: true } : {},
2270
+ ...deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}
2271
+ });
2272
+ if (!ctx.dryRun) {
2273
+ const journal = await require_seeds.DeployJournal.open(ctx.state, stage, () => require_dns.createComposeState(stage));
2274
+ const providers = new Map(result.plan.domains.map((d) => [d.domain, d.provider]));
2275
+ await require_seeds.recordDnsChanges(journal, result.changes, (domain) => providers.get(domain));
2276
+ }
2277
+ 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);
2278
+ if (parts.length > 0) log(`🌐 ${parts.join(", ")}`);
2279
+ if (ctx.dryRun) {
2280
+ await result.prune();
2281
+ return;
2282
+ }
2283
+ return result.recorded.stale.length > 0 ? result.prune : void 0;
2284
+ } catch (error) {
2285
+ if (ctx.dryRun && error instanceof require_snsSubscriptions.HostNotPointingAtServer) {
2286
+ ctx.logger.warn(`⚠ ${error.message}`);
2287
+ return;
2288
+ }
2289
+ throw error;
2290
+ }
2291
+ }
2292
+ /**
2293
+ * The records gkm wrote for hosts the stage no longer serves, deleted once it
2294
+ * answers on its new ones — and forgotten from its state, deleted or not:
2295
+ * none is gkm's to manage any more.
2296
+ */
2297
+ async function pruneStageDns(ctx, run) {
2298
+ if (!run.pruneDns) return;
2299
+ const pruned = await run.pruneDns();
2300
+ const journal = await require_seeds.DeployJournal.open(ctx.state, ctx.stage, () => require_dns.createComposeState(ctx.stage));
2301
+ for (const { record } of pruned) await require_seeds.forgetDnsResource(journal, record);
2302
+ const deleted = pruned.filter((p) => p.action === "delete").length;
2303
+ if (deleted > 0) ctx.logger.info(`🌐 ${deleted} record${deleted === 1 ? "" : "s"} deleted`);
2304
+ }
2305
+ /**
2306
+ * The stage's secrets — and, for a deployed stage, everything it generates
2307
+ * once: its seed, and each declared secret and keyring. Kept only once the
2308
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
2309
+ * leaves the stage's secrets as it found them.
2310
+ */
2311
+ async function stageSecrets(ctx, manifest) {
2312
+ const stored = await ctx.secrets.read();
2313
+ if (ctx.stage === ctx.workspace.stages.local) return {
2314
+ secrets: stored,
2315
+ generated: []
2316
+ };
2317
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
2318
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
2319
+ for (const [key, value] of Object.entries(secrets.custom ?? {})) if (!require_workspace.isReservedStageKey(key) && key !== "ZO_ROOT_USER_EMAIL") ctx.secrets.mask(value);
2320
+ return {
2321
+ secrets,
2322
+ generated
2323
+ };
2324
+ }
2325
+ /**
2326
+ * The stack with each app's and worker's image pinned to the digest the file
2327
+ * names: the refs it is checked, pulled and recorded by, and the image each
2328
+ * compose service runs.
2329
+ */
2330
+ function withPinnedImages(stack, file, digests) {
2331
+ const apps = pinImages(file, digests, stack.apps);
2332
+ const workers = pinImages(file, digests, stack.workers);
2333
+ const processors = pinImages(file, digests, stack.processors);
2334
+ const services = { ...stack.compose.services };
2335
+ for (const image of [
2336
+ ...apps,
2337
+ ...workers,
2338
+ ...processors
2339
+ ]) services[image.name] = {
2340
+ ...services[image.name],
2341
+ image: image.ref
2342
+ };
2343
+ return {
2344
+ ...stack,
2345
+ apps,
2346
+ workers,
2347
+ processors,
2348
+ compose: {
2349
+ ...stack.compose,
2350
+ services
2351
+ }
2352
+ };
2353
+ }
2354
+ /**
2355
+ * A dry run: the stack's files, written so they can be read, and what a real
2356
+ * run would do — no image is built or pulled, no container touched, nothing
2357
+ * recorded and no secret kept.
2358
+ */
2359
+ async function planCompose(ctx, run) {
2360
+ 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.`);
2361
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack);
2362
+ printPlan(ctx, run);
2363
+ if (!run.push && run.stack.infra.includes("postgres")) require_seeds.reportPlannedSeeds((await require_databases.plannedSeeds({
2364
+ root: ctx.workspace.root,
2365
+ manifest: ctx.manifest
2366
+ })).map(({ target, seeds }) => ({
2367
+ folder: target.seeds,
2368
+ seeds
2369
+ })), (line) => ctx.logger.info(line));
2370
+ const planned = (change) => {
2371
+ run.changes.push(change);
2372
+ ctx.emit({
2373
+ type: "resource.planned",
2374
+ ...change
2375
+ });
2376
+ };
2377
+ for (const service of run.push ? [] : run.stack.infra) planned({
2378
+ key: `service:${service}`,
2379
+ resourceType: "service",
2380
+ action: "ensure"
2381
+ });
2382
+ for (const app of run.stack.apps) {
2383
+ planned({
2384
+ key: `image:${app.name}`,
2385
+ resourceType: "image",
2386
+ action: run.mode === "build" ? "build" : "reuse",
2387
+ id: app.ref
2388
+ });
2389
+ if (run.push) continue;
2390
+ planned({
2391
+ key: `service:${app.name}`,
2392
+ resourceType: "service",
2393
+ action: run.previous[app.name] ? "reuse" : "create"
2394
+ });
2395
+ }
2396
+ for (const worker of [...run.stack.workers, ...run.stack.processors]) {
2397
+ planned({
2398
+ key: `image:${worker.name}`,
2399
+ resourceType: "image",
2400
+ action: run.mode === "build" ? "build" : "reuse",
2401
+ id: worker.ref
2402
+ });
2403
+ if (run.push) continue;
2404
+ planned({
2405
+ key: `service:${worker.name}`,
2406
+ resourceType: "service",
2407
+ action: run.previous[worker.name] ? "reuse" : "create"
2408
+ });
2409
+ }
2410
+ for (const push of run.topicSubscriptions?.pushes ?? []) {
2411
+ const key = require_snsSubscriptions.subscriptionKey(push.worker, push.name);
2412
+ const id = run.topicSubscriptions?.recorded?.[key]?.id;
2413
+ planned({
2414
+ key,
2415
+ resourceType: require_snsSubscriptions.SUBSCRIPTION_TYPE,
2416
+ action: id ? "reuse" : "create",
2417
+ ...id ? { id } : {}
2418
+ });
2419
+ }
2420
+ if (!run.push) planned({
2421
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}/${_geekmidas_edge_proxy_traefik.EDGE_SERVICE}`,
2422
+ resourceType: "service",
2423
+ action: "ensure"
2424
+ });
2425
+ }
2426
+ /**
2427
+ * The shared edge's key for the stage's wildcard certificate: the DNS
2428
+ * challenge's record, and nothing else, through the stage domain's Route 53
2429
+ * entry — before the stack's routes ask for the certificate.
2430
+ */
2431
+ async function edgeAcmeKey(ctx, run, deps) {
2432
+ const { workspace, stage } = ctx;
2433
+ const domain = workspace.domains?.[stage];
2434
+ const dns = workspace.dns ? require_dns.normalizeDnsConfig(workspace.dns) : {};
2435
+ const zone = domain ? require_dns.findRootDomain(domain, dns) : null;
2436
+ const config = zone ? dns[zone] : void 0;
2437
+ if (!domain || !zone || config?.provider !== "route53") return;
2438
+ const route53 = config;
2439
+ const server = require_snsSubscriptions.requiredServerAddress(stage, domain, run.secrets?.custom)?.ipv4 ?? run.server?.host ?? "local";
2440
+ const clients = await (deps.acmeClients ?? defaultAcmeClients)(route53);
2441
+ await ensureEdgeAcmeKey(deps.docker, {
2442
+ clients,
2443
+ edge: edgeRef(edgeFile(run), {
2444
+ ...run.ref.host ? { host: run.ref.host } : {},
2445
+ ...run.ref.output ? { output: run.ref.output } : {}
2446
+ }),
2447
+ server,
2448
+ project: run.stack.project,
2449
+ domain,
2450
+ zone,
2451
+ ...route53.hostedZoneId ? { hostedZoneId: route53.hostedZoneId } : {},
2452
+ ...ctx.dryRun ? { dryRun: true } : {},
2453
+ log: (line) => ctx.logger.info(line)
2454
+ });
2455
+ }
2456
+ /** IAM and Route 53 through the AWS SDK's own chain, or the entry's profile. */
2457
+ async function defaultAcmeClients(config) {
2458
+ const [{ IAMClient }, { Route53Client }, { fromIni }] = await Promise.all([
2459
+ import("@aws-sdk/client-iam"),
2460
+ import("@aws-sdk/client-route-53"),
2461
+ import("@aws-sdk/credential-providers")
2462
+ ]);
2463
+ const options = {
2464
+ region: config.region ?? "us-east-1",
2465
+ ...config.profile ? { credentials: fromIni({ profile: config.profile }) } : {}
2466
+ };
2467
+ return {
2468
+ iam: new IAMClient(options),
2469
+ route53: new Route53Client(options)
2470
+ };
2471
+ }
2472
+ /**
2473
+ * What the apps run on: the stage's generated secrets kept, the stack's files
2474
+ * written, its infrastructure started, and its databases, roles, grants and
2475
+ * migrations applied.
2476
+ */
2477
+ async function provisionCompose(ctx, run, deps) {
2478
+ const { ref } = run;
2479
+ if (run.push) return;
2480
+ if (run.generated.length > 0 && run.secrets) {
2481
+ await ctx.secrets.write(run.secrets);
2482
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
2483
+ }
2484
+ const ports = edgePorts(deps.env);
2485
+ const ownCaddy = await assertEdgePorts(deps.docker, {
2486
+ project: run.stack.project,
2487
+ proxy: run.stack.proxy,
2488
+ ports,
2489
+ engine: ref
2490
+ });
2491
+ if (run.topicSubscriptions) await subscribeTopics(ctx, run, deps);
2492
+ const { stack } = run;
2493
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
2494
+ printPlan(ctx, run);
2495
+ if (stack.proxy === "traefik") {
2496
+ if (ownCaddy) {
2497
+ 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.`);
2498
+ await deps.docker.remove(ref, stack.project, "caddy");
2499
+ }
2500
+ ctx.logger.info(`\n🌐 Starting the shared edge (${_geekmidas_edge_proxy_traefik.EDGE_PROJECT})…`);
2501
+ run.files.push(...await ensureEdge(deps.docker, {
2502
+ file: edgeFile(run),
2503
+ ports,
2504
+ ...ref.host ? { host: ref.host } : {},
2505
+ logging: {
2506
+ driver: require_stack.LOG_ROTATION.driver,
2507
+ options: { ...require_stack.LOG_ROTATION.options }
2508
+ },
2509
+ ...ref.output ? { output: ref.output } : {},
2510
+ ...ref.signal ? { signal: ref.signal } : {}
2511
+ }));
2512
+ applied(ctx, run, {
2513
+ key: `service:${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}/${_geekmidas_edge_proxy_traefik.EDGE_SERVICE}`,
2514
+ resourceType: "service",
2515
+ action: "ensure",
2516
+ id: `${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}/${_geekmidas_edge_proxy_traefik.EDGE_SERVICE}`,
2517
+ via: "found"
2518
+ });
2519
+ if (stack.wildcard?.tls === "dns") await edgeAcmeKey(ctx, run, deps);
2520
+ }
2521
+ if (stack.infra.length > 0) {
2522
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
2523
+ await deps.docker.up(ref, stack.infra);
2524
+ for (const service of stack.infra) applied(ctx, run, {
2525
+ key: `service:${service}`,
2526
+ resourceType: "service",
2527
+ action: "ensure",
2528
+ id: `${stack.project}/${service}`,
2529
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
2530
+ });
2531
+ }
2532
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
2533
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
2534
+ }
2535
+ /**
2536
+ * Subscribe each topic subscriber SNS pushes to — for a topic the stage set
2537
+ * to SNS by hand — record the ARNs, and compose the stack again with them,
2538
+ * before a file is written.
2539
+ */
2540
+ async function subscribeTopics(ctx, run, deps) {
2541
+ const { pushes, recorded, restack } = run.topicSubscriptions;
2542
+ if (pushes.length > 0) ctx.logger.info("\n📮 SNS subscriptions for the stage's own topics");
2543
+ run.stack = restack(await ensureTopicSubscriptions({
2544
+ pushes,
2545
+ recorded,
2546
+ secrets: run.secrets?.custom ?? {},
2547
+ stage: ctx.stage,
2548
+ env: deps.env,
2549
+ record: async (resource) => {
2550
+ await ctx.state.putResource(ctx.stage, resource);
2551
+ applied(ctx, run, {
2552
+ key: resource.key,
2553
+ resourceType: require_snsSubscriptions.SUBSCRIPTION_TYPE,
2554
+ action: "ensure",
2555
+ id: resource.id,
2556
+ via: recorded?.[resource.key]?.id === resource.id ? "recorded" : "created"
2557
+ });
2558
+ },
2559
+ forget: async (key) => {
2560
+ await ctx.state.deleteResource(ctx.stage, key);
2561
+ },
2562
+ log: (line) => ctx.logger.info(line)
2563
+ }));
2564
+ }
2565
+ /**
2566
+ * Create each bucket the stack's MinIO serves, and the open paths of each
2567
+ * one a file server fronts — from this machine, on MinIO's loopback port,
2568
+ * the way `gkm dev` creates them.
2569
+ */
2570
+ async function prepareBuckets(ctx, run, deps) {
2571
+ const storage = run.stack.storage;
2572
+ if (storage.buckets.length === 0) return;
2573
+ const tunnel = await reach(run, deps, "minio", require_stack.LOOPBACK_SERVICES.minio);
2574
+ let done;
2575
+ try {
2576
+ const client = deps.buckets(tunnel.port, storage);
2577
+ done = [
2578
+ ...await require_apps.applyBuckets(client, storage.buckets),
2579
+ ...await require_apps.applyPolicies(client, storage.policies),
2580
+ ...await require_apps.applyLifecycles(client, storage.lifecycles),
2581
+ ...await require_apps.applyNotifications(client, storage.objects, new Set(storage.webhooks.map((hook) => hook.bucket)))
2582
+ ];
2583
+ } finally {
2584
+ await tunnel.close();
2585
+ }
2586
+ const created = done.filter((entry) => entry.created).length;
2587
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
2588
+ }
2589
+ /**
2590
+ * Create what the plan names in the stack's Postgres, migrate it, then run
2591
+ * its seeds — every one, every time, as each construct's owner.
2592
+ *
2593
+ * Every service the stack publishes on its loopback is reached, not only
2594
+ * Postgres: a seed runs project code, and project code that uploads a file
2595
+ * reaches the stack's MinIO as well.
2596
+ */
2597
+ async function prepareDatabases(ctx, run, deps) {
2598
+ const tunnels = [];
2599
+ try {
2600
+ const ports = {};
2601
+ for (const [service, inside] of Object.entries(require_stack.LOOPBACK_SERVICES)) {
2602
+ if (!run.stack.infra.includes(service)) continue;
2603
+ const tunnel = await reach(run, deps, service, inside);
2604
+ tunnels.push(tunnel);
2605
+ ports[require_compose.primaryPortKey(service)] = tunnel.port;
2606
+ }
2607
+ await migrateAndSeed(ctx, run, deps, ports);
2608
+ } finally {
2609
+ await Promise.all(tunnels.map((tunnel) => tunnel.close()));
2610
+ }
2611
+ }
2612
+ /**
2613
+ * A port a stack's service publishes on its engine's loopback, reachable
2614
+ * from this machine: the published port itself on the local stage, and on a
2615
+ * server an SSH tunnel to it over the deploy's own login — so Postgres and
2616
+ * MinIO are never published beyond the server's loopback.
2617
+ *
2618
+ * Migrations and seeds run here, in this process, with the project's own
2619
+ * Kysely — the way `gkm migrate` runs them — through that port. No image
2620
+ * needs to carry them, and nothing is run on the server but the stack.
2621
+ */
2622
+ async function reach(run, deps, service, inside) {
2623
+ const published = await deps.docker.port(run.ref, service, inside);
2624
+ if (!run.server) return {
2625
+ port: published,
2626
+ close: async () => {}
2627
+ };
2628
+ return deps.server.tunnel(run.server, published);
2629
+ }
2630
+ async function migrateAndSeed(ctx, run, deps, ports) {
2631
+ const { stack } = run;
2632
+ const workspace = ctx.workspace;
2633
+ const port = ports[require_compose.primaryPortKey("postgres")];
2634
+ const superuser = stack.credential.containers.postgres;
2635
+ const login = await deps.logins({
2636
+ port,
2637
+ login: superuser,
2638
+ legacy: [{
2639
+ user: require_apps.LEGACY_LOCAL_LOGIN.user,
2640
+ password: superuser.password
2641
+ }, ...stack.local ? [require_apps.LEGACY_LOCAL_LOGIN] : []]
2642
+ });
2643
+ if (login.notice) ctx.logger.info(login.notice);
2644
+ const statements = [...require_apps.postgresStatements(stack.plan, workspace.name, stack.credential.seed), ...stack.backups ? require_apps.backupsRoleStatements(stack.backups) : []];
2645
+ if (statements.length > 0) {
2646
+ ctx.logger.info("🗄️ Creating databases, roles and grants…");
2647
+ await require_apps.applyPostgres(deps.sql(port, login.login), statements);
2648
+ }
2649
+ const sources = {};
2650
+ const manifest = await require_discover.discover({
2651
+ patterns: require_apps.constructGlobs(workspace),
2652
+ cwd: workspace.root,
2653
+ sources
2654
+ });
2655
+ const custom = run.secrets?.custom ?? {};
2656
+ const resolved = require_apps.envFor(stack.plan, {
2657
+ ...stack.resolution,
2658
+ ports,
2659
+ credentials: {
2660
+ ...stack.resolution.credentials,
2661
+ postgres: login.login
2662
+ }
2663
+ });
2664
+ const env = require_apps.stageEnv(run.secrets ? require_dns.toEmbeddableSecrets(run.secrets) : {}, Object.fromEntries(Object.entries(resolved).filter(([key]) => custom[key] === void 0)));
2665
+ const options = {
2666
+ root: workspace.root,
2667
+ manifest,
2668
+ sources,
2669
+ env
2670
+ };
2671
+ const runs = await deps.migrate(options);
2672
+ const seeds = await deps.seed({
2673
+ ...options,
2674
+ stage: ctx.stage,
2675
+ backends: require_apps.backendsOf(workspace)
2676
+ }).catch((error) => {
2677
+ if (error instanceof require_databases.SeedFailed) throw new require_seeds.DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
2678
+ throw error;
2679
+ });
2680
+ require_seeds.reportDatabaseRuns(runs.map(({ target, applied }) => ({
2681
+ construct: target.id,
2682
+ folder: target.migrations,
2683
+ applied
2684
+ })), seeds.map(({ target, seeded }) => ({
2685
+ construct: target.id,
2686
+ folder: target.seeds,
2687
+ seeded
2688
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
2689
+ }
2690
+ /**
2691
+ * Each app's image: built from this checkout — inside Docker, every one of
2692
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
2693
+ * live changes.
2694
+ */
2695
+ async function buildCompose(ctx, run, deps) {
2696
+ const { stack, ref } = run;
2697
+ const images = [
2698
+ ...stack.apps,
2699
+ ...stack.workers,
2700
+ ...stack.processors
2701
+ ];
2702
+ const apps = images.map((image) => image.app);
2703
+ if (run.push) {
2704
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
2705
+ printPlan(ctx, run);
2706
+ }
2707
+ const prerendered = prerenderedHere(run);
2708
+ if (run.push) await stageAnswers(ctx, run, deps, prerendered);
2709
+ const held = new Set(run.push ? [] : prerendered.map(({ app }) => app));
2710
+ const now = images.filter((image) => !held.has(image.app));
2711
+ if (run.mode === "build") {
2712
+ ctx.logger.info("\n🐳 Building images…");
2713
+ await deps.docker.build(ref, now.map((image) => image.app));
2714
+ } else {
2715
+ ctx.logger.info(`\n🐳 Pulling ${require_dns.stageTag(ctx.tag, ctx.stage)}…`);
2716
+ await deps.docker.pull(ref, apps);
2717
+ }
2718
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
2719
+ await recordBuilt(ctx, run, deps, now);
2720
+ }
2721
+ /**
2722
+ * Each image's tag as it resolved — the registry's digest for a pushed or
2723
+ * pulled image, or, for one built here and never pushed, its content id —
2724
+ * in the run, and said.
2725
+ */
2726
+ async function recordBuilt(ctx, run, deps, images) {
2727
+ const { ref } = run;
2728
+ for (const image of images) {
2729
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(ref, image.ref);
2730
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
2731
+ run.images[image.app] = {
2732
+ ref: image.ref,
2733
+ tag: image.tag,
2734
+ ...digest ? { digest } : {}
2735
+ };
2736
+ ctx.emit({
2737
+ type: "artifact.built",
2738
+ app: image.app,
2739
+ imageRef: image.ref,
2740
+ ...digest ? { digest } : {}
2741
+ });
2742
+ run.changes.push({
2743
+ key: `image:${image.app}`,
2744
+ resourceType: "image",
2745
+ action: run.mode === "build" ? "build" : "reuse",
2746
+ id: digest ?? image.ref
2747
+ });
2748
+ }
2749
+ }
2750
+ /**
2751
+ * The whole stack up — anything it no longer defines removed — and each
2752
+ * app's image recorded in the stage's state.
2753
+ */
2754
+ async function releaseCompose(ctx, run, deps) {
2755
+ const { stack, ref } = run;
2756
+ if (run.push) return;
2757
+ const edge = edgeRef(edgeFile(run), {
2758
+ ...ref.host ? { host: ref.host } : {},
2759
+ ...ref.output ? { output: ref.output } : {}
2760
+ });
2761
+ if (stack.proxy === "traefik" && stack.traefik) {
2762
+ const written = await writeEdgeRoutes(deps.docker, edge, stack.project, stack.traefik, await edgeCertificate(run.dir, stack));
2763
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}: ${written.at(-1)}`);
2764
+ } else if (!stack.local || (0, node_fs.existsSync)(edgeFile(run))) await removeEdgeRoutes(deps.docker, edge, stack.project);
2765
+ const prerendered = prerenderedHere(run);
2766
+ if (prerendered.length > 0) await buildAgainstStage(ctx, run, deps, prerendered);
2767
+ ctx.logger.info("\n🚀 Starting the stack…");
2768
+ const down = await deps.docker.up(ref).then(() => [], (error) => unhealthyAfterUp(ctx, run, deps, error));
2769
+ const isDown = new Set(down.map(({ app }) => app));
2770
+ await recordImages(ctx, run);
2771
+ for (const app of stack.apps) {
2772
+ if (isDown.has(app.name)) continue;
2773
+ const image = run.images[app.name];
2774
+ applied(ctx, run, {
2775
+ key: `service:${app.name}`,
2776
+ resourceType: "service",
2777
+ action: "ensure",
2778
+ id: `${stack.project}/${app.name}`,
2779
+ via: run.previous[app.name] ? "recorded" : "created"
2780
+ });
2781
+ ctx.emit({
2782
+ type: "app.deployed",
2783
+ app: app.name,
2784
+ applicationId: `${stack.project}/${app.name}`,
2785
+ imageRef: image?.ref ?? app.ref,
2786
+ url: app.url
2787
+ });
2788
+ }
2789
+ for (const worker of [...stack.workers, ...stack.processors]) {
2790
+ if (isDown.has(worker.name)) continue;
2791
+ applied(ctx, run, {
2792
+ key: `service:${worker.name}`,
2793
+ resourceType: "service",
2794
+ action: "ensure",
2795
+ id: `${stack.project}/${worker.name}`,
2796
+ via: run.previous[worker.name] ? "recorded" : "created"
2797
+ });
2798
+ }
2799
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
2800
+ for (const app of stack.apps) {
2801
+ if (isDown.has(app.name)) continue;
2802
+ 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}` : ""}`);
2803
+ }
2804
+ if (stack.mailInbox) ctx.logger.info(` ${"mail".padEnd(12)} ${stack.mailInbox.url} (inbox)`);
2805
+ for (const worker of stack.workers) {
2806
+ if (isDown.has(worker.name)) continue;
2807
+ ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
2808
+ }
2809
+ for (const unit of stack.processors) {
2810
+ if (isDown.has(unit.name)) continue;
2811
+ ctx.logger.info(` ${unit.name.padEnd(12)} processors of ${unit.id}`);
2812
+ }
2813
+ 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}`);
2814
+ 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.`);
2815
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy, "docker");
2816
+ }
2817
+ /**
2818
+ * After `up --wait` failed: each app's and worker's service that is not
2819
+ * healthy once its health settles — waited on while it is still starting,
2820
+ * as `--wait` stops at the first that is not. None means the failure was not
2821
+ * health's, and it is thrown as it was.
2822
+ */
2823
+ async function unhealthyAfterUp(ctx, run, deps, error, except = /* @__PURE__ */ new Set()) {
2824
+ const { stack } = run;
2825
+ const services = [
2826
+ ...stack.apps.flatMap(require_stack.replicaNames),
2827
+ ...stack.workers.map((worker) => worker.name),
2828
+ ...stack.processors.map((unit) => unit.name)
2829
+ ].filter((service) => !except.has(service));
2830
+ const down = (await Promise.all(services.map(async (service) => {
2831
+ let last;
2832
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2833
+ ctx.signal.throwIfAborted();
2834
+ last = await deps.docker.health(run.ref, service).catch(() => void 0);
2835
+ if (last !== "starting") break;
2836
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2837
+ }
2838
+ return {
2839
+ app: service,
2840
+ url: `docker:${service}`,
2841
+ last
2842
+ };
2843
+ }))).filter(({ last }) => last !== "healthy").map(({ app, url, last }) => ({
2844
+ app,
2845
+ url,
2846
+ last: last ?? "not running"
2847
+ }));
2848
+ if (down.length === 0) throw error;
2849
+ ctx.logger.warn(`\n⚠️ ${down.map(({ app }) => app).join(", ")} did not turn healthy; the rest of the stack is released and routed.`);
2850
+ return down;
2851
+ }
2852
+ /**
2853
+ * Where a check through the edge connects: this machine for the local stage,
2854
+ * a deployed stage's server on its published port — or, for a push, which
2855
+ * has no server, wherever the host resolves.
2856
+ */
2857
+ function edgeTarget(run, deps) {
2858
+ if (run.stack.local) return { connectTo: "127.0.0.1" };
2859
+ if (run.server) return {
2860
+ connectTo: run.server.host,
2861
+ connectPort: edgePorts(deps.env).https
2862
+ };
2863
+ }
2864
+ /**
2865
+ * The sites this run builds against their stage's running APIs
2866
+ * (`prerender: 'stage'`). None for a run that pulls: a pulled image was built
2867
+ * against the stage when it was pushed.
2868
+ */
2869
+ function prerenderedHere(run) {
2870
+ if (run.mode !== "build") return [];
2871
+ return run.stack.apps.filter((app) => app.prerender && app.build);
2872
+ }
2873
+ /**
2874
+ * A site that pre-renders against its stage, built once its APIs answer:
2875
+ * every service of the stack started but those sites — `up --wait`, so each
2876
+ * is healthy by its own check — then each API the site depends on asked
2877
+ * through the edge, as a browser reaches it, and only then the site built.
2878
+ * The full `up` that follows starts it.
2879
+ */
2880
+ async function buildAgainstStage(ctx, run, deps, sites) {
2881
+ const { stack, ref } = run;
2882
+ const held = new Set(sites.flatMap(require_stack.replicaNames));
2883
+ const services = Object.keys(stack.compose.services).filter((service) => !held.has(service));
2884
+ ctx.logger.info(`\n🚀 Starting the stack, but ${listNames(sites)}, built once its APIs answer…`);
2885
+ const down = await deps.docker.up(ref, services).then(() => [], (error) => unhealthyAfterUp(ctx, run, deps, error, held));
2886
+ for (const site of sites) {
2887
+ const against = new Set(site.prerender?.against);
2888
+ const blocking = down.filter(({ app }) => against.has(app));
2889
+ if (blocking.length > 0) throw new SitePrerenderApisDown(site.name, blocking, "docker");
2890
+ }
2891
+ await stageAnswers(ctx, run, deps, sites);
2892
+ ctx.logger.info(`\n🐳 Building ${listNames(sites)} against the stage's APIs…`);
2893
+ await deps.docker.build(ref, sites.map((site) => site.app));
2894
+ await recordBuilt(ctx, run, deps, sites);
2895
+ }
2896
+ /** `web` — or `docs and web`. */
2897
+ function listNames(apps) {
2898
+ const names = apps.map(({ name }) => name);
2899
+ return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0] ?? "";
2900
+ }
2901
+ /**
2902
+ * Each API a site pre-rendered against its stage depends on, asked through
2903
+ * the edge as `verify` asks it — the address the site's build fetches from.
2904
+ * Any that does not answer fails the run before the site is built: a build
2905
+ * that cannot reach them bakes in pages without their data.
2906
+ */
2907
+ async function stageAnswers(ctx, run, deps, sites) {
2908
+ const { stack } = run;
2909
+ const names = new Set(sites.flatMap((site) => site.prerender?.against ?? []));
2910
+ const apps = stack.apps.filter((app) => names.has(app.name));
2911
+ if (apps.length === 0) return;
2912
+ ctx.logger.info(`\n🩺 Checking the APIs ${listNames(sites)} ${sites.length > 1 ? "pre-render" : "pre-renders"} from…`);
2913
+ const ca = await verifyAuthority(stack);
2914
+ const edge = edgeTarget(run, deps);
2915
+ const results = await Promise.all(apps.map((app) => app.id === stack.wildcard?.site && !run.push ? checkContainer(ctx, run, deps, app.name) : checkApp(ctx, app, deps, {
2916
+ ca,
2917
+ edge
2918
+ })));
2919
+ const down = new Map(results.filter((r) => !r.healthy).map((r) => [r.app, r]));
2920
+ for (const site of sites) {
2921
+ const blocking = (site.prerender?.against ?? []).flatMap((name) => {
2922
+ const result = down.get(name);
2923
+ return result ? [result] : [];
2924
+ });
2925
+ if (blocking.length > 0) throw new SitePrerenderApisDown(site.name, blocking, run.push ? "push" : "edge");
2926
+ }
2927
+ }
2928
+ /**
2929
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
2930
+ * records: the ref it runs, the tag it was released under, and the digest
2931
+ * the tag resolved to.
2932
+ */
2933
+ async function recordImages(ctx, run) {
2934
+ const journal = await require_seeds.DeployJournal.open(ctx.state, ctx.stage, () => require_dns.createComposeState(ctx.stage));
2935
+ const by = require_seeds.currentActor();
2936
+ for (const app of [
2937
+ ...run.stack.apps,
2938
+ ...run.stack.workers,
2939
+ ...run.stack.processors
2940
+ ]) {
2941
+ const image = run.images[app.app] ?? {
2942
+ ref: app.ref,
2943
+ tag: app.tag
2944
+ };
2945
+ require_dns.recordRelease(journal.state, app.app, image, by);
2946
+ }
2947
+ journal.state.identity = ctx.identity.key;
2948
+ await journal.save();
2949
+ }
2950
+ /**
2951
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
2952
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
2953
+ * its certificate is from gkm's local CA, so that root is the one trusted and
2954
+ * the request goes to 127.0.0.1.
2955
+ */
2956
+ async function verifyCompose(ctx, run, deps) {
2957
+ const { stack } = run;
2958
+ if (run.push) return;
2959
+ const ca = await verifyAuthority(stack);
2960
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
2961
+ const edge = edgeTarget(run, deps);
2962
+ const results = await Promise.all(stack.apps.map((app) => app.id === stack.wildcard?.site ? checkContainer(ctx, run, deps, app.name) : checkApp(ctx, app, deps, {
2963
+ ca,
2964
+ edge
2965
+ })));
2966
+ results.push(...await Promise.all([...stack.workers, ...stack.processors].map((worker) => checkContainer(ctx, run, deps, worker.name))));
2967
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, require_compose.LOGS_SERVICE));
2968
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
2969
+ app,
2970
+ url,
2971
+ last
2972
+ }));
2973
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
2974
+ await pruneStageDns(ctx, run);
2975
+ await confirmSubscriptions(ctx, run, deps);
2976
+ await warmSites(ctx, run, deps, {
2977
+ ca,
2978
+ edge
2979
+ });
2980
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local, run.server);
2981
+ }
2982
+ /**
2983
+ * Each server-rendered site (`next`, `tanstack`) asked for its sitemap, its
2984
+ * `/` and every page the sitemap lists, through the edge as `checkApp` asks
2985
+ * it — see `warmup.ts`. Its image was built with no API reachable, so each
2986
+ * page renders on its first request: this is that request, made before any
2987
+ * visitor's. A Next site is asked with its on-demand revalidation header,
2988
+ * so a page its build cached (empty) is rendered again from the deployed
2989
+ * APIs rather than served from that cache.
2990
+ *
2991
+ * Only ever said, never failed on: every app is already healthy, and a page
2992
+ * that did not warm renders on the next request for it.
2993
+ */
2994
+ async function warmSites(ctx, run, deps, options) {
2995
+ const { stack } = run;
2996
+ const sites = stack.apps.filter((app) => app.kind === "site" && (app.variant === "next" || app.variant === "tanstack"));
2997
+ if (sites.length === 0) return;
2998
+ ctx.logger.info("\n🔥 Warming each server-rendered site…");
2999
+ for (const app of sites) {
3000
+ if (app.id === stack.wildcard?.site) {
3001
+ ctx.logger.info(` – ${app.name.padEnd(12)} serves every subdomain: there is no one host to warm, so it is skipped`);
3002
+ continue;
3003
+ }
3004
+ try {
3005
+ const headers = app.variant === "next" ? await forceRender(ctx, run, deps, app) : {};
3006
+ const { warmed, cached, warnings, leftOut } = await warmSite({
3007
+ url: app.url,
3008
+ fetch: deps.fetch ?? edgeFetch,
3009
+ headers,
3010
+ edge: {
3011
+ ...options.ca ? { ca: options.ca } : {},
3012
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
3013
+ ...options.edge,
3014
+ signal: ctx.signal
3015
+ }
3016
+ });
3017
+ const said = `warmed ${warmed.length} page(s)${cached.length > 0 ? `, ${cached.length} served from the build cache` : ""}${warnings.length > 0 ? `, ${warnings.length} warning(s)` : ""}`;
3018
+ if (warnings.length === 0) ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${said}${cached.length > 0 ? `: ${listed(cached)}` : ""}`);
3019
+ else {
3020
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} ${said}:`);
3021
+ for (const { url, reason } of warnings) ctx.logger.warn(` ${url}: ${reason}`);
3022
+ if (cached.length > 0) ctx.logger.warn(` served from the build cache: ${listed(cached)}`);
3023
+ }
3024
+ if (leftOut > 0) ctx.logger.info(` ${leftOut} more page(s) in its sitemap were not asked: at most 500 are warmed per site`);
3025
+ } catch (error) {
3026
+ if (ctx.signal.aborted) throw error;
3027
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} not warmed: ${error instanceof Error ? error.message : String(error)}`);
3028
+ }
3029
+ }
3030
+ }
3031
+ /** The most pages a summary names; the rest are counted. */
3032
+ const LISTED_PAGES = 10;
3033
+ /** Pages by path, `/about`, the first {@link LISTED_PAGES} of them. */
3034
+ function listed(urls) {
3035
+ const paths = urls.map((url) => {
3036
+ const { pathname, search } = new URL(url);
3037
+ return `${pathname}${search}`;
3038
+ });
3039
+ const shown = paths.slice(0, LISTED_PAGES).join(", ");
3040
+ return paths.length > LISTED_PAGES ? `${shown} and ${paths.length - LISTED_PAGES} more` : shown;
3041
+ }
3042
+ /**
3043
+ * The header that has a Next site render each warmed page whatever its
3044
+ * cache says: `x-prerender-revalidate` with the preview-mode id of the image
3045
+ * running — read in its container, through the stack's Docker engine, at
3046
+ * the path the generated Dockerfile puts the standalone output at. Where the
3047
+ * id cannot be read, said once, and the site is warmed with plain requests.
3048
+ */
3049
+ async function forceRender(ctx, run, deps, app) {
3050
+ let reason;
3051
+ try {
3052
+ const root = ctx.workspace.root;
3053
+ const gkmRoot = (0, node_path.relative)(require_apps.findBuildRoot(root), root) || ".";
3054
+ const lookup = await nextPreviewModeId((command) => deps.docker.exec(run.ref, app.name, command), require_apps.nextPrerenderManifest(require_apps.fromBuildRoot({ gkmRoot }, app.path)));
3055
+ if ("id" in lookup) return { [NEXT_REVALIDATE_HEADER]: lookup.id };
3056
+ reason = lookup.reason;
3057
+ } catch (error) {
3058
+ if (ctx.signal.aborted) throw error;
3059
+ reason = error instanceof Error ? error.message : String(error);
3060
+ }
3061
+ 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.`);
3062
+ return {};
3063
+ }
3064
+ /**
3065
+ * The SNS subscriptions the stage's providers made before the workers were
3066
+ * up: each still pending is subscribed again, so SNS resends its
3067
+ * confirmation to a worker now there to answer it, and waited on. One still
3068
+ * pending after that is said, not failed on — every app is healthy, and
3069
+ * rolling them back would not confirm it.
3070
+ */
3071
+ async function confirmSubscriptions(ctx, run, deps) {
3072
+ const stored = await ctx.state.read(ctx.stage);
3073
+ const left = await (deps.confirmSubscriptions ?? require_snsSubscriptions.confirmPendingSubscriptions)({
3074
+ workspace: ctx.workspace,
3075
+ stage: ctx.stage,
3076
+ secrets: run.secrets?.custom ?? {},
3077
+ resources: stored?.resources,
3078
+ env: deps.env,
3079
+ log: (line) => ctx.logger.info(line),
3080
+ record: async (record) => {
3081
+ const { updatedAt: _, updatedBy: __, ...input } = record;
3082
+ await ctx.state.putResource(ctx.stage, input);
3083
+ }
3084
+ });
3085
+ if (left.length > 0) ctx.logger.warn(`⚠ ${new require_snsSubscriptions.PushSubscriptionsUnconfirmed(left).message}`);
3086
+ }
3087
+ /**
3088
+ * A container's own health check, as Docker reports it: a worker's, which
3089
+ * has no route through the edge, and OpenObserve's — by default it has no
3090
+ * host there, and served publicly it answers only the addresses it allows,
3091
+ * which need not include this one.
3092
+ */
3093
+ async function checkContainer(ctx, run, deps, service) {
3094
+ const url = `docker:${service}`;
3095
+ let last = "not asked";
3096
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
3097
+ ctx.signal.throwIfAborted();
3098
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
3099
+ last = health ?? "not running";
3100
+ const healthy = health === "healthy";
3101
+ ctx.emit({
3102
+ type: "health.checked",
3103
+ app: service,
3104
+ url,
3105
+ healthy,
3106
+ attempt
3107
+ });
3108
+ if (healthy) {
3109
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
3110
+ return {
3111
+ app: service,
3112
+ url,
3113
+ last,
3114
+ healthy
3115
+ };
3116
+ }
3117
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
3118
+ }
3119
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
3120
+ return {
3121
+ app: service,
3122
+ url,
3123
+ last,
3124
+ healthy: false
3125
+ };
3126
+ }
3127
+ /** A login, as the `Authorization` header that carries it. */
3128
+ function basicAuthorization(auth) {
3129
+ return `Basic ${Buffer.from(`${auth.user}:${auth.password}`).toString("base64")}`;
3130
+ }
3131
+ /** How to open the logs, printed — and as an event, for a headless caller. */
3132
+ function reportLogs(ctx, logs, local, server) {
3133
+ const lines = require_compose.logsAccess(logs, {
3134
+ stage: ctx.stage,
3135
+ local,
3136
+ user: server?.user ?? currentUser(),
3137
+ hostname: server?.host ?? (0, node_os.hostname)(),
3138
+ ...server ? { known: true } : {}
3139
+ });
3140
+ ctx.logger.info(`\n${lines.join("\n")}`);
3141
+ ctx.emit({
3142
+ type: "logs.ready",
3143
+ service: require_compose.LOGS_SERVICE,
3144
+ access: logs.public ? "public" : "tunnel",
3145
+ url: logs.url,
3146
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
3147
+ email: logs.email
3148
+ });
3149
+ }
3150
+ /** This machine's user — a guess at who would SSH in. */
3151
+ function currentUser() {
3152
+ try {
3153
+ return (0, node_os.userInfo)().username;
3154
+ } catch {
3155
+ return process.env.USER ?? "user";
3156
+ }
3157
+ }
3158
+ async function checkApp(ctx, app, deps, options) {
3159
+ const url = `${app.url.replace(/^ws/, "http")}${app.kind === "site" ? "/" : "/health"}`;
3160
+ let last = "not asked";
3161
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
3162
+ ctx.signal.throwIfAborted();
3163
+ let status;
3164
+ try {
3165
+ status = await deps.probe({
3166
+ url,
3167
+ ...options.ca ? { ca: options.ca } : {},
3168
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
3169
+ ...options.edge,
3170
+ timeoutMs: 1e4,
3171
+ signal: ctx.signal
3172
+ });
3173
+ last = `HTTP ${status}`;
3174
+ } catch (error) {
3175
+ last = error instanceof Error ? error.message : String(error);
3176
+ }
3177
+ const healthy = status !== void 0 && isHealthy(status);
3178
+ ctx.emit({
3179
+ type: "health.checked",
3180
+ app: app.name,
3181
+ url,
3182
+ healthy,
3183
+ ...status !== void 0 ? { status } : {},
3184
+ attempt
3185
+ });
3186
+ if (healthy) {
3187
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
3188
+ return {
3189
+ app: app.name,
3190
+ url,
3191
+ last,
3192
+ healthy
3193
+ };
3194
+ }
3195
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
3196
+ }
3197
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
3198
+ return {
3199
+ app: app.name,
3200
+ url,
3201
+ last,
3202
+ healthy: false
3203
+ };
3204
+ }
3205
+ function composeResult(ctx, run) {
3206
+ const apps = [...run.stack.apps.map((app) => {
3207
+ const image = run.images[app.name];
3208
+ return {
3209
+ appName: app.name,
3210
+ type: app.kind === "site" ? "web" : "backend",
3211
+ success: !ctx.dryRun,
3212
+ applicationId: `${run.stack.project}/${app.name}`,
3213
+ imageRef: image?.ref ?? app.ref,
3214
+ ...image?.digest ? { digest: image.digest } : {},
3215
+ url: app.url
3216
+ };
3217
+ }), ...[...run.stack.workers, ...run.stack.processors].map((worker) => {
3218
+ const image = run.images[worker.name];
3219
+ return {
3220
+ appName: worker.name,
3221
+ type: "backend",
3222
+ success: !ctx.dryRun,
3223
+ applicationId: `${run.stack.project}/${worker.name}`,
3224
+ imageRef: image?.ref ?? worker.ref,
3225
+ ...image?.digest ? { digest: image.digest } : {}
3226
+ };
3227
+ })];
3228
+ return {
3229
+ apps,
3230
+ projectId: run.stack.project,
3231
+ successCount: ctx.dryRun ? 0 : apps.length,
3232
+ failedCount: 0,
3233
+ stage: ctx.stage,
3234
+ identity: ctx.identity.key,
3235
+ tag: require_dns.stageTag(ctx.tag, ctx.stage),
3236
+ dryRun: ctx.dryRun,
3237
+ environmentId: "",
3238
+ skipped: [...ctx.skipped],
3239
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
3240
+ changes: run.changes
3241
+ };
3242
+ }
3243
+ /** The shared edge's compose file, as this machine hands it to compose. */
3244
+ function edgeFile(run) {
3245
+ return (0, node_path.join)(run.dir, `${_geekmidas_edge_proxy_traefik.EDGE_PROJECT}.yml`);
3246
+ }
3247
+ function applied(ctx, run, change) {
3248
+ const { via, ...rest } = change;
3249
+ run.changes.push(rest);
3250
+ ctx.emit({
3251
+ type: "resource.applied",
3252
+ ...rest,
3253
+ via
3254
+ });
3255
+ }
3256
+ /**
3257
+ * The root the check after a start trusts, PEM: gkm's on the local stage that
3258
+ * set no certificate of its own, and otherwise the one the stage's own names
3259
+ * (`deploy.compose.tls.<stage>.caFile`). Undefined — Node's own roots, and
3260
+ * `NODE_EXTRA_CA_CERTS` — for a certificate that names none: a public CA's.
3261
+ */
3262
+ async function verifyAuthority(stack) {
3263
+ if (stack.authority) return (await (0, _geekmidas_edge_certificates_local.readLocalAuthority)(stack.authority)).cert;
3264
+ if (stack.tls?.caFile) return (0, node_fs_promises.readFile)(stack.tls.caFile, "utf-8");
3265
+ }
3266
+ /**
3267
+ * The certificate the stack's proxy serves, PEM: the stage's own where it set
3268
+ * one, the one gkm's local CA issued the local stage otherwise, and none — a
3269
+ * deployed stage's comes from Let's Encrypt — when neither.
3270
+ */
3271
+ async function edgeCertificate(dir, stack) {
3272
+ if (stack.tls) return {
3273
+ cert: await (0, node_fs_promises.readFile)(stack.tls.certFile, "utf-8"),
3274
+ key: await (0, node_fs_promises.readFile)(stack.tls.keyFile, "utf-8")
3275
+ };
3276
+ if (stack.authority) return localEdgeCertificate(dir, stack, stack.authority);
3277
+ }
3278
+ /** Where the local stage's edge certificate is kept, between runs. */
3279
+ const LOCAL_EDGE_CERTIFICATE = "local-edge.pem";
3280
+ /**
3281
+ * The local stage's edge certificate, from gkm's local CA: the one kept in
3282
+ * the stack's directory while it still covers every host, so an unchanged
3283
+ * stack does not recreate its Caddy for a new certificate each run.
3284
+ */
3285
+ async function localEdgeCertificate(dir, stack, authority) {
3286
+ 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));
3287
+ return {
3288
+ cert,
3289
+ key
3290
+ };
3291
+ }
3292
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
3293
+ async function writeStack(root, dir, stack) {
3294
+ await (0, node_fs_promises.mkdir)(dir, {
3295
+ recursive: true,
3296
+ mode: 448
3297
+ });
3298
+ await (0, node_fs_promises.chmod)(dir, 448);
3299
+ const files = [];
3300
+ const write = async (path, content, mode = 420) => {
3301
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
3302
+ await (0, node_fs_promises.writeFile)(path, content, { mode });
3303
+ await (0, node_fs_promises.chmod)(path, mode);
3304
+ files.push(path);
3305
+ };
3306
+ const issued = await edgeCertificate(dir, stack);
3307
+ const tls = stack.proxy === "caddy" ? issued : void 0;
3308
+ const compose = stack.caddyfile !== void 0 ? require_stack.withCaddyConfigs(stack.compose, {
3309
+ caddyfile: stack.caddyfile,
3310
+ ...tls ? { tls } : {}
3311
+ }) : stack.compose;
3312
+ await write((0, node_path.join)(dir, "docker-compose.yml"), composeYaml(stack, compose), tls ? 384 : 420);
3313
+ if (stack.caddyfile !== void 0) {
3314
+ await write((0, node_path.join)(dir, "Caddyfile"), stack.caddyfile);
3315
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, "traefik.yml"), { force: true });
3316
+ } else await (0, node_fs_promises.rm)((0, node_path.join)(dir, "Caddyfile"), { force: true });
3317
+ if (stack.traefik !== void 0) await write((0, node_path.join)(dir, "traefik.yml"), stack.traefik);
3318
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, "tls"), {
3319
+ recursive: true,
3320
+ force: true
3321
+ });
3322
+ for (const app of [
3323
+ ...stack.apps,
3324
+ ...stack.workers,
3325
+ ...stack.processors
3326
+ ]) if (app.env) await write((0, node_path.join)(dir, `${app.name}.env`), require_stack.envFile(app.env), 384);
3327
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write((0, node_path.join)(dir, `${require_compose.LOGS_SERVICE}.env`), require_stack.envFile(stack.logs.env), 384);
3328
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write((0, node_path.join)(dir, `${require_compose.REDIS_SERVICE}.env`), require_stack.envFile(stack.redis.env), 384);
3329
+ if (stack.backups) {
3330
+ for (const [name, content] of Object.entries(stack.backups.files)) await write((0, node_path.join)(dir, require_apps.BACKUPS_SERVICE, name), content);
3331
+ if (stack.compose.services["backups"]?.env_file) await write((0, node_path.join)(dir, `${require_apps.BACKUPS_SERVICE}.env`), require_stack.envFile(stack.backups.env), 384);
3332
+ } else {
3333
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, require_apps.BACKUPS_SERVICE), {
3334
+ recursive: true,
3335
+ force: true
3336
+ });
3337
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, `${require_apps.BACKUPS_SERVICE}.env`), { force: true });
3338
+ }
3339
+ 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));
3340
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write((0, node_path.join)(root, path), content);
3341
+ await require_docker.ensureDockerignore(require_apps.findBuildRoot(root));
3342
+ return files;
3343
+ }
3344
+ function composeYaml(stack, compose) {
3345
+ const stage = ` --stage ${stack.stage}`;
3346
+ return `# Generated by gkm compose from the construct manifest — do not edit.
3347
+ # 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.
3348
+ # Each backend and worker reads exactly the keys in its own env file beside
3349
+ # this one.
3350
+ #
3351
+ # gkm compose${stage} start or update it
3352
+ # gkm compose${stage} --down stop it
3353
+ ${(0, yaml.stringify)(compose, {
3354
+ lineWidth: 0,
3355
+ aliasDuplicateObjects: false
3356
+ })}`;
3357
+ }
3358
+ function printPlan(ctx, run) {
3359
+ const { stack, mode, files } = run;
3360
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
3361
+ if (run.server) ctx.logger.info(` → ${sshTarget(run.server)} (docker over ssh)`);
3362
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
3363
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
3364
+ for (const unit of stack.processors) ctx.logger.info(` ${unit.name.padEnd(12)} ${`processors of ${unit.id}`.padEnd(40)} ${mode} ${unit.ref}`);
3365
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
3366
+ if (stack.backups) ctx.logger.info(` ${require_apps.BACKUPS_SERVICE.padEnd(12)} ${stack.backups.databases.map((d) => d.file).join(", ")} — ${stack.backups.backups.describe}, to ${stack.backups.prefix}/`);
3367
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${require_stack.stackDir(stack.stage)}/`);
3368
+ }
3369
+ //#endregion
3370
+ //#region src/target/compose/index.ts
3371
+ /**
3372
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
3373
+ * Caddy — the local stage on the machine that runs the deploy, a deployed
3374
+ * stage on its server's Docker engine, over SSH (`deploy.compose.server`).
3375
+ *
3376
+ * ```bash
3377
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
3378
+ * gkm deploy --target compose --stage production # built from here
3379
+ * gkm deploy --target compose --stage development # the local stage
3380
+ * ```
3381
+ *
3382
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
3383
+ * looked up in the registry — `ImageTagNotFound` before anything changes
3384
+ * - `ready`: a deploy's own checks, after the stage's keys are — the stage's
3385
+ * certificate, its server's address, and every public host's DNS
3386
+ * - `plan`: the stack's files and what a run would create or reuse
3387
+ * - `provision`: generated secrets kept, files written, infrastructure up,
3388
+ * databases, roles, grants and migrations
3389
+ * - `build`: each backend bundled on the host and every image built — or, for
3390
+ * a tag, pulled. A site that pre-renders against its stage
3391
+ * (`prerender: 'stage'`) is held back, but for a push, which first asks the
3392
+ * running stage's APIs and builds it against them
3393
+ * - `release`: the stack's routes on the shared edge; a held-back site built
3394
+ * once the rest of the stack is up and its APIs answer through the edge;
3395
+ * then `up --wait
3396
+ * --remove-orphans`, and each app's image, tag and digest in the stage's
3397
+ * state — an app that never turns healthy fails it only once the rest is
3398
+ * released and routed
3399
+ * - `verify`: each app asked through Caddy over HTTPS, then each
3400
+ * server-rendered site warmed — its `/` and its sitemap's pages asked, a
3401
+ * failure only warned of
3402
+ *
3403
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
3404
+ * every image and pushes it to `deploy.registry`, and does nothing else: no
3405
+ * readiness check runs, so a stage whose keys the deploy has yet to write
3406
+ * still builds.
3407
+ *
3408
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
3409
+ * `--down`), run through the same `deploy()`.
3410
+ */
3411
+ var compose_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ composeTarget: () => composeTarget });
3412
+ /** The compose target, with its Docker, bundler and probe as given. */
3413
+ function composeTarget(options = {}) {
3414
+ const { mode, push, pin, report, ...given } = options;
3415
+ const deps = {
3416
+ ...defaultDeps,
3417
+ ...given
3418
+ };
3419
+ return require_define.defineTarget({
3420
+ name: "compose",
3421
+ runtime: "server",
3422
+ capabilities: {
3423
+ rollback: false,
3424
+ migrations: "target",
3425
+ images: true,
3426
+ localStage: true,
3427
+ selfHostedTelemetry: true
3428
+ },
3429
+ credentials: [],
3430
+ tag: ({ cwd }) => deps.revision(cwd),
3431
+ validate: (ctx) => validateCompose(ctx, deps, {
3432
+ ...mode ? { mode } : {},
3433
+ ...push ? { push } : {},
3434
+ ...pin ? { pin } : {}
3435
+ }),
3436
+ ready: (ctx, run) => readyCompose(ctx, run, deps),
3437
+ plan: (ctx, run) => planCompose(ctx, run),
3438
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
3439
+ build: (ctx, run) => buildCompose(ctx, run, deps),
3440
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
3441
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
3442
+ result: (ctx, run) => {
3443
+ report?.(run);
3444
+ return composeResult(ctx, run);
3445
+ }
3446
+ });
3447
+ }
3448
+ //#endregion
3449
+ Object.defineProperty(exports, "ComposePinNeedsPull", {
3450
+ enumerable: true,
3451
+ get: function() {
3452
+ return ComposePinNeedsPull;
3453
+ }
3454
+ });
3455
+ Object.defineProperty(exports, "ComposePushNeedsBuild", {
3456
+ enumerable: true,
3457
+ get: function() {
3458
+ return ComposePushNeedsBuild;
3459
+ }
3460
+ });
3461
+ Object.defineProperty(exports, "ContainersNotStarted", {
3462
+ enumerable: true,
3463
+ get: function() {
3464
+ return ContainersNotStarted;
3465
+ }
3466
+ });
3467
+ Object.defineProperty(exports, "ContainersNotStopped", {
3468
+ enumerable: true,
3469
+ get: function() {
3470
+ return ContainersNotStopped;
3471
+ }
3472
+ });
3473
+ Object.defineProperty(exports, "composeServer", {
3474
+ enumerable: true,
3475
+ get: function() {
3476
+ return composeServer;
3477
+ }
3478
+ });
3479
+ Object.defineProperty(exports, "composeTarget", {
3480
+ enumerable: true,
3481
+ get: function() {
3482
+ return composeTarget;
3483
+ }
3484
+ });
3485
+ Object.defineProperty(exports, "compose_exports", {
3486
+ enumerable: true,
3487
+ get: function() {
3488
+ return compose_exports;
3489
+ }
3490
+ });
3491
+ Object.defineProperty(exports, "deployedStackSecrets", {
3492
+ enumerable: true,
3493
+ get: function() {
3494
+ return deployedStackSecrets;
3495
+ }
3496
+ });
3497
+ Object.defineProperty(exports, "dockerCompose", {
3498
+ enumerable: true,
3499
+ get: function() {
3500
+ return dockerCompose;
3501
+ }
3502
+ });
3503
+ Object.defineProperty(exports, "dockerHost", {
3504
+ enumerable: true,
3505
+ get: function() {
3506
+ return dockerHost;
3507
+ }
3508
+ });
3509
+ Object.defineProperty(exports, "edgePorts", {
3510
+ enumerable: true,
3511
+ get: function() {
3512
+ return edgePorts;
3513
+ }
3514
+ });
3515
+ Object.defineProperty(exports, "edgeRef", {
3516
+ enumerable: true,
3517
+ get: function() {
3518
+ return edgeRef;
3519
+ }
3520
+ });
3521
+ Object.defineProperty(exports, "parseDigests", {
3522
+ enumerable: true,
3523
+ get: function() {
3524
+ return parseDigests;
3525
+ }
3526
+ });
3527
+ Object.defineProperty(exports, "pinnedRef", {
3528
+ enumerable: true,
3529
+ get: function() {
3530
+ return pinnedRef;
3531
+ }
3532
+ });
3533
+ Object.defineProperty(exports, "projectNetwork", {
3534
+ enumerable: true,
3535
+ get: function() {
3536
+ return projectNetwork;
3537
+ }
3538
+ });
3539
+ Object.defineProperty(exports, "removeEdgeRoutes", {
3540
+ enumerable: true,
3541
+ get: function() {
3542
+ return removeEdgeRoutes;
3543
+ }
3544
+ });
3545
+ Object.defineProperty(exports, "sshAccess", {
3546
+ enumerable: true,
3547
+ get: function() {
3548
+ return sshAccess;
3549
+ }
3550
+ });
3551
+ Object.defineProperty(exports, "sshTarget", {
3552
+ enumerable: true,
3553
+ get: function() {
3554
+ return sshTarget;
3555
+ }
3556
+ });
3557
+ Object.defineProperty(exports, "stackOverrideFile", {
3558
+ enumerable: true,
3559
+ get: function() {
3560
+ return stackOverrideFile;
3561
+ }
3562
+ });
3563
+
3564
+ //# sourceMappingURL=compose-DmtR2f0l.cjs.map