@geekmidas/cli 10.0.0-alpha.92 → 10.0.0-alpha.94

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 (206) hide show
  1. package/dist/{GoDaddyProvider-BqYGk9XT.mjs → GoDaddyProvider-BRZUWD8z.mjs} +3 -3
  2. package/dist/{GoDaddyProvider-BqYGk9XT.mjs.map → GoDaddyProvider-BRZUWD8z.mjs.map} +1 -1
  3. package/dist/{GoDaddyProvider-CJwg2r_9.cjs → GoDaddyProvider-DzguxU_a.cjs} +3 -3
  4. package/dist/{GoDaddyProvider-CJwg2r_9.cjs.map → GoDaddyProvider-DzguxU_a.cjs.map} +1 -1
  5. package/dist/{HostingerProvider-1mqD6aG8.mjs → HostingerProvider-Cjh_2Ml6.mjs} +9 -4
  6. package/dist/{HostingerProvider-1mqD6aG8.mjs.map → HostingerProvider-Cjh_2Ml6.mjs.map} +1 -1
  7. package/dist/{HostingerProvider-C6t-PSNe.cjs → HostingerProvider-OdQmKXE3.cjs} +9 -4
  8. package/dist/HostingerProvider-OdQmKXE3.cjs.map +1 -0
  9. package/dist/LegacyStateStore-BQZb6-j2.mjs +124 -0
  10. package/dist/LegacyStateStore-BQZb6-j2.mjs.map +1 -0
  11. package/dist/LegacyStateStore-D50dgUPc.cjs +124 -0
  12. package/dist/LegacyStateStore-D50dgUPc.cjs.map +1 -0
  13. package/dist/{LocalStateStore-Y8XHdoCR.mjs → LocalStateStore-BSaS2535.mjs} +2 -2
  14. package/dist/{LocalStateStore-Y8XHdoCR.mjs.map → LocalStateStore-BSaS2535.mjs.map} +1 -1
  15. package/dist/{LocalStateStore-BMfseje2.cjs → LocalStateStore-EFBUjuMX.cjs} +8 -8
  16. package/dist/{LocalStateStore-BMfseje2.cjs.map → LocalStateStore-EFBUjuMX.cjs.map} +1 -1
  17. package/dist/{S3StateStore-BmMt2HhW.cjs → S3StateStore-C5mv8To3.cjs} +5 -5
  18. package/dist/{S3StateStore-BmMt2HhW.cjs.map → S3StateStore-C5mv8To3.cjs.map} +1 -1
  19. package/dist/{S3StateStore-BfoY4MvD.mjs → S3StateStore-CrFq4UZU.mjs} +2 -2
  20. package/dist/{S3StateStore-BfoY4MvD.mjs.map → S3StateStore-CrFq4UZU.mjs.map} +1 -1
  21. package/dist/{SSMStateStore-Bdyw_0Jj.mjs → SSMStateStore-D3Z6mZnA.mjs} +2 -2
  22. package/dist/{SSMStateStore-Bdyw_0Jj.mjs.map → SSMStateStore-D3Z6mZnA.mjs.map} +1 -1
  23. package/dist/{SSMStateStore-D9K62wM4.cjs → SSMStateStore-DuZCH7_v.cjs} +9 -9
  24. package/dist/{SSMStateStore-D9K62wM4.cjs.map → SSMStateStore-DuZCH7_v.cjs.map} +1 -1
  25. package/dist/{add-2Opn2VVE.mjs → add-C85isXFl.mjs} +4 -5
  26. package/dist/add-C85isXFl.mjs.map +1 -0
  27. package/dist/{add-oN0b18HN.cjs → add-DsVDdvon.cjs} +5 -6
  28. package/dist/add-DsVDdvon.cjs.map +1 -0
  29. package/dist/{bundler-CXQDrhzN.cjs → bundler-BEgUKc4j.cjs} +5 -5
  30. package/dist/{bundler-CXQDrhzN.cjs.map → bundler-BEgUKc4j.cjs.map} +1 -1
  31. package/dist/{bundler-C-AdesaG.mjs → bundler-BSHog8CH.mjs} +5 -5
  32. package/dist/{bundler-C-AdesaG.mjs.map → bundler-BSHog8CH.mjs.map} +1 -1
  33. package/dist/{cli-BjhaVObS.mjs → cli-BsFenyaf.mjs} +10 -6
  34. package/dist/cli-BsFenyaf.mjs.map +1 -0
  35. package/dist/{cli-BRZFYvdb.cjs → cli-BvBdv660.cjs} +9 -5
  36. package/dist/cli-BvBdv660.cjs.map +1 -0
  37. package/dist/compose-Cd09gW-n.cjs +1562 -0
  38. package/dist/compose-Cd09gW-n.cjs.map +1 -0
  39. package/dist/compose-D2RFYd_f.mjs +1515 -0
  40. package/dist/compose-D2RFYd_f.mjs.map +1 -0
  41. package/dist/{config-C9zx7KsX.d.cts → config-DvHNMoOp.d.cts} +4 -4
  42. package/dist/{config-BJo8Wggp.d.mts.map → config-DvHNMoOp.d.cts.map} +1 -1
  43. package/dist/{config-BJo8Wggp.d.mts → config-Ngesg4O8.d.mts} +4 -4
  44. package/dist/{config-C9zx7KsX.d.cts.map → config-Ngesg4O8.d.mts.map} +1 -1
  45. package/dist/config.cjs +1 -1
  46. package/dist/config.d.cts +3 -3
  47. package/dist/config.d.mts +3 -3
  48. package/dist/config.mjs +1 -1
  49. package/dist/{credentials-QBu7VgaQ.cjs → credentials-D7XJypNd.cjs} +9 -3
  50. package/dist/{credentials-QBu7VgaQ.cjs.map → credentials-D7XJypNd.cjs.map} +1 -1
  51. package/dist/{credentials-C4KII3PD.mjs → credentials-DpfnUvIR.mjs} +9 -3
  52. package/dist/{credentials-C4KII3PD.mjs.map → credentials-DpfnUvIR.mjs.map} +1 -1
  53. package/dist/deploy/public.cjs +13 -12
  54. package/dist/deploy/public.d.cts +25 -10
  55. package/dist/deploy/public.d.cts.map +1 -1
  56. package/dist/deploy/public.d.mts +25 -10
  57. package/dist/deploy/public.d.mts.map +1 -1
  58. package/dist/deploy/public.mjs +11 -11
  59. package/dist/{deploy-6ToUHJmM.cjs → deploy-C911Akkn.cjs} +125 -10
  60. package/dist/deploy-C911Akkn.cjs.map +1 -0
  61. package/dist/{deploy-yuJHlkY0.mjs → deploy-CeJ5D0xn.mjs} +124 -9
  62. package/dist/deploy-CeJ5D0xn.mjs.map +1 -0
  63. package/dist/{discover-G76EQ4vY.d.mts → discover-CTzOSGUF.d.cts} +2 -2
  64. package/dist/{discover-CRMhvHG9.d.cts.map → discover-CTzOSGUF.d.cts.map} +1 -1
  65. package/dist/{discover-CRMhvHG9.d.cts → discover-CihAtaoj.d.mts} +2 -2
  66. package/dist/{discover-G76EQ4vY.d.mts.map → discover-CihAtaoj.d.mts.map} +1 -1
  67. package/dist/{dokploy-Bvvfj2qe.cjs → dokploy-CV7GcobZ.cjs} +2 -2
  68. package/dist/{dokploy-Bvvfj2qe.cjs.map → dokploy-CV7GcobZ.cjs.map} +1 -1
  69. package/dist/{dokploy-BvbJ_A4Q.mjs → dokploy-D_aat2Xj.mjs} +2 -2
  70. package/dist/{dokploy-BvbJ_A4Q.mjs.map → dokploy-D_aat2Xj.mjs.map} +1 -1
  71. package/dist/{encryption-CgW167LO.cjs → encryption-DFcivJaO.cjs} +3 -3
  72. package/dist/{encryption-CgW167LO.cjs.map → encryption-DFcivJaO.cjs.map} +1 -1
  73. package/dist/{encryption-C9Jm9dfn.mjs → encryption-_4qKqtTx.mjs} +3 -3
  74. package/dist/{encryption-C9Jm9dfn.mjs.map → encryption-_4qKqtTx.mjs.map} +1 -1
  75. package/dist/{engine-Dj7ZKO8H.cjs → engine-Bv-LZpmj.cjs} +13 -11
  76. package/dist/engine-Bv-LZpmj.cjs.map +1 -0
  77. package/dist/{engine-C8Ye9MUm.mjs → engine-DPMHThkg.mjs} +11 -9
  78. package/dist/engine-DPMHThkg.mjs.map +1 -0
  79. package/dist/{github-BD051KZZ.cjs → github-Br42NMrW.cjs} +94 -6
  80. package/dist/github-Br42NMrW.cjs.map +1 -0
  81. package/dist/{github-B1k42hIt.mjs → github-xsDT19im.mjs} +94 -6
  82. package/dist/github-xsDT19im.mjs.map +1 -0
  83. package/dist/{index-D1pHwqkK.d.mts → index-BlpcClwM.d.mts} +2 -2
  84. package/dist/{index-B5uuwx-Y.d.cts.map → index-BlpcClwM.d.mts.map} +1 -1
  85. package/dist/{index-B5uuwx-Y.d.cts → index-CwLvFqtH.d.cts} +2 -2
  86. package/dist/{index-D1pHwqkK.d.mts.map → index-CwLvFqtH.d.cts.map} +1 -1
  87. package/dist/index.cjs +240 -250
  88. package/dist/index.cjs.map +1 -1
  89. package/dist/index.mjs +234 -243
  90. package/dist/index.mjs.map +1 -1
  91. package/dist/{local-Otp74ak0.mjs → local-B7Zv1NoA.mjs} +2 -2
  92. package/dist/{local-Otp74ak0.mjs.map → local-B7Zv1NoA.mjs.map} +1 -1
  93. package/dist/{local-B61kUh0w.cjs → local-OPC9BCZt.cjs} +2 -2
  94. package/dist/{local-B61kUh0w.cjs.map → local-OPC9BCZt.cjs.map} +1 -1
  95. package/dist/{migrate-IZsYyZ5F.mjs → migrate-B7evHv7O.mjs} +3 -3
  96. package/dist/{migrate-IZsYyZ5F.mjs.map → migrate-B7evHv7O.mjs.map} +1 -1
  97. package/dist/{migrate-D3VVsiHp.cjs → migrate-D5jUz20_.cjs} +3 -3
  98. package/dist/{migrate-D3VVsiHp.cjs.map → migrate-D5jUz20_.cjs.map} +1 -1
  99. package/dist/{migrate-BSbZ7-9n.mjs → migrate-DhvFPGLi.mjs} +4 -4
  100. package/dist/{migrate-BSbZ7-9n.mjs.map → migrate-DhvFPGLi.mjs.map} +1 -1
  101. package/dist/{migrate-f6JDjyCp.cjs → migrate-SkWJotn5.cjs} +3 -3
  102. package/dist/{migrate-f6JDjyCp.cjs.map → migrate-SkWJotn5.cjs.map} +1 -1
  103. package/dist/openapi.cjs +1 -1
  104. package/dist/openapi.d.cts +1 -1
  105. package/dist/openapi.d.mts +1 -1
  106. package/dist/openapi.mjs +1 -1
  107. package/dist/providers-BFeP_mYw.cjs +1098 -0
  108. package/dist/providers-BFeP_mYw.cjs.map +1 -0
  109. package/dist/providers-sTj-BG0S.mjs +1079 -0
  110. package/dist/providers-sTj-BG0S.mjs.map +1 -0
  111. package/dist/reconcile/public.d.cts +2 -2
  112. package/dist/reconcile/public.d.mts +2 -2
  113. package/dist/{reconcile-Dh1Jk7WE.mjs → reconcile--I7V4Klj.mjs} +2 -2
  114. package/dist/{reconcile-Dh1Jk7WE.mjs.map → reconcile--I7V4Klj.mjs.map} +1 -1
  115. package/dist/{resolve-DUp65SnJ.cjs → resolve-CFEOtRsl.cjs} +4 -4
  116. package/dist/{resolve-DUp65SnJ.cjs.map → resolve-CFEOtRsl.cjs.map} +1 -1
  117. package/dist/{resolve-Be4bF1w4.mjs → resolve-Dyd1S2wn.mjs} +4 -4
  118. package/dist/{resolve-Be4bF1w4.mjs.map → resolve-Dyd1S2wn.mjs.map} +1 -1
  119. package/dist/{rollback-DDHtd0GJ.cjs → rollback-D720SFhV.cjs} +11 -8
  120. package/dist/rollback-D720SFhV.cjs.map +1 -0
  121. package/dist/{rollback-D1d-fW0r.mjs → rollback-NroNbGC0.mjs} +10 -7
  122. package/dist/rollback-NroNbGC0.mjs.map +1 -0
  123. package/dist/{runtime-Es1V4e9M.d.mts → runtime-BRCq6dQ7.d.mts} +2 -2
  124. package/dist/{runtime-DDrHlYe5.d.cts.map → runtime-BRCq6dQ7.d.mts.map} +1 -1
  125. package/dist/{runtime-DDrHlYe5.d.cts → runtime-VktAo_8B.d.cts} +2 -2
  126. package/dist/{runtime-Es1V4e9M.d.mts.map → runtime-VktAo_8B.d.cts.map} +1 -1
  127. package/dist/{sandbox-MaxSeU92.d.cts → sandbox-D1gd0iDz.d.cts} +2 -2
  128. package/dist/{sandbox-C3WsTa5m.d.mts.map → sandbox-D1gd0iDz.d.cts.map} +1 -1
  129. package/dist/{sandbox-C3WsTa5m.d.mts → sandbox-zHnRLCj0.d.mts} +2 -2
  130. package/dist/{sandbox-MaxSeU92.d.cts.map → sandbox-zHnRLCj0.d.mts.map} +1 -1
  131. package/dist/secrets-CwLauUB_.mjs +36 -0
  132. package/dist/secrets-CwLauUB_.mjs.map +1 -0
  133. package/dist/secrets-DAvi_O9g.cjs +47 -0
  134. package/dist/secrets-DAvi_O9g.cjs.map +1 -0
  135. package/dist/{seeds-BKoJYsE7.cjs → seeds-BCg8X36S.cjs} +1732 -2300
  136. package/dist/seeds-BCg8X36S.cjs.map +1 -0
  137. package/dist/{seeds-CvGQJnPO.mjs → seeds-CTxTZa-R.mjs} +1637 -2270
  138. package/dist/seeds-CTxTZa-R.mjs.map +1 -0
  139. package/dist/{sniffer-Dq5BS98f.cjs → sniffer-C0z3NB2A.cjs} +572 -3
  140. package/dist/sniffer-C0z3NB2A.cjs.map +1 -0
  141. package/dist/{sniffer-BTtGAtm3.mjs → sniffer-DCcuzHz_.mjs} +496 -5
  142. package/dist/sniffer-DCcuzHz_.mjs.map +1 -0
  143. package/dist/{sst-CnKY-CSh.cjs → sst-DKNH243z.cjs} +3 -3
  144. package/dist/{sst-CnKY-CSh.cjs.map → sst-DKNH243z.cjs.map} +1 -1
  145. package/dist/{sst-BaRXp2Dd.mjs → sst-DRDSDwOk.mjs} +3 -3
  146. package/dist/{sst-BaRXp2Dd.mjs.map → sst-DRDSDwOk.mjs.map} +1 -1
  147. package/dist/stack-B3fPDTBg.cjs +1346 -0
  148. package/dist/stack-B3fPDTBg.cjs.map +1 -0
  149. package/dist/stack-NrdH5ngX.mjs +1239 -0
  150. package/dist/stack-NrdH5ngX.mjs.map +1 -0
  151. package/dist/{stages-BI8JvPzI.cjs → stages-CkqP1N4S.cjs} +16 -3
  152. package/dist/stages-CkqP1N4S.cjs.map +1 -0
  153. package/dist/{stages-DY-fQKmo.mjs → stages-veC4TcQe.mjs} +16 -3
  154. package/dist/stages-veC4TcQe.mjs.map +1 -0
  155. package/dist/target/public.cjs +1 -1
  156. package/dist/target/public.d.cts +2 -2
  157. package/dist/target/public.d.mts +2 -2
  158. package/dist/target/public.mjs +1 -1
  159. package/dist/{terminal-8XngdSTo.cjs → terminal-CkUYuAPd.cjs} +2 -2
  160. package/dist/{terminal-8XngdSTo.cjs.map → terminal-CkUYuAPd.cjs.map} +1 -1
  161. package/dist/{terminal-Dtd6BZX9.mjs → terminal-DAHs2Zko.mjs} +3 -3
  162. package/dist/{terminal-Dtd6BZX9.mjs.map → terminal-DAHs2Zko.mjs.map} +1 -1
  163. package/dist/{types-Bk9st2cd.d.cts → types-DMoaFrjg.d.mts} +108 -33
  164. package/dist/types-DMoaFrjg.d.mts.map +1 -0
  165. package/dist/{types-B3Gqs175.d.mts → types-DXyaSmqu.d.cts} +109 -32
  166. package/dist/types-DXyaSmqu.d.cts.map +1 -0
  167. package/dist/workspace/index.cjs +1 -1
  168. package/dist/workspace/index.d.cts +2 -2
  169. package/dist/workspace/index.d.mts +2 -2
  170. package/dist/workspace/index.mjs +1 -1
  171. package/dist/{workspace-Bzw7Zs82.mjs → workspace-DWK1PTXP.mjs} +4 -4
  172. package/dist/workspace-DWK1PTXP.mjs.map +1 -0
  173. package/dist/{workspace-CHOB2Xg3.cjs → workspace-cSyi5nb1.cjs} +4 -4
  174. package/dist/workspace-cSyi5nb1.cjs.map +1 -0
  175. package/package.json +15 -15
  176. package/dist/HostingerProvider-C6t-PSNe.cjs.map +0 -1
  177. package/dist/LegacyStateStore-CeEwayMB.cjs +0 -89
  178. package/dist/LegacyStateStore-CeEwayMB.cjs.map +0 -1
  179. package/dist/LegacyStateStore-DdJ1bCRV.mjs +0 -89
  180. package/dist/LegacyStateStore-DdJ1bCRV.mjs.map +0 -1
  181. package/dist/add-2Opn2VVE.mjs.map +0 -1
  182. package/dist/add-oN0b18HN.cjs.map +0 -1
  183. package/dist/cli-BRZFYvdb.cjs.map +0 -1
  184. package/dist/cli-BjhaVObS.mjs.map +0 -1
  185. package/dist/compose-CTdVeeVk.mjs +0 -3151
  186. package/dist/compose-CTdVeeVk.mjs.map +0 -1
  187. package/dist/compose-fnYmPk_c.cjs +0 -3276
  188. package/dist/compose-fnYmPk_c.cjs.map +0 -1
  189. package/dist/deploy-6ToUHJmM.cjs.map +0 -1
  190. package/dist/deploy-yuJHlkY0.mjs.map +0 -1
  191. package/dist/engine-C8Ye9MUm.mjs.map +0 -1
  192. package/dist/engine-Dj7ZKO8H.cjs.map +0 -1
  193. package/dist/github-B1k42hIt.mjs.map +0 -1
  194. package/dist/github-BD051KZZ.cjs.map +0 -1
  195. package/dist/rollback-D1d-fW0r.mjs.map +0 -1
  196. package/dist/rollback-DDHtd0GJ.cjs.map +0 -1
  197. package/dist/seeds-BKoJYsE7.cjs.map +0 -1
  198. package/dist/seeds-CvGQJnPO.mjs.map +0 -1
  199. package/dist/sniffer-BTtGAtm3.mjs.map +0 -1
  200. package/dist/sniffer-Dq5BS98f.cjs.map +0 -1
  201. package/dist/stages-BI8JvPzI.cjs.map +0 -1
  202. package/dist/stages-DY-fQKmo.mjs.map +0 -1
  203. package/dist/types-B3Gqs175.d.mts.map +0 -1
  204. package/dist/types-Bk9st2cd.d.cts.map +0 -1
  205. package/dist/workspace-Bzw7Zs82.mjs.map +0 -1
  206. package/dist/workspace-CHOB2Xg3.cjs.map +0 -1
@@ -0,0 +1,1515 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
3
+ import { c as runOutput, s as run, x as gkmHome } from "./credentials-DpfnUvIR.mjs";
4
+ import { r as discover } from "./discover-qjFapetL.mjs";
5
+ import { it as SERVER_IPV4_KEY, tt as ComposeTlsFileMissing } from "./workspace-DWK1PTXP.mjs";
6
+ import { t as defineTarget } from "./define-6poNqm5O.mjs";
7
+ import { $ as systemLookup, $n as imageRef, Bt as applyPolicies, Dt as loadLocalCredentials, G as HostNotPointingAtServer, J as requiredServerAddress, Jt as bucketClient, Kt as LEGACY_LOCAL_LOGIN, Mn as primaryPortKey, St as constructGlobs, Vt as applyPostgres, Wt as postgresStatements, X as stackHosts, Y as serverAddressHint, Yt as pgClient, Z as stageDns, dr as logsAccess, en as envFor, g as currentActor, h as recordDnsChanges, i as assertNoStaleSecrets, jt as REDIS_SERVICE, k as reportDevServices, l as ensureDockerignore, n as reportDatabaseRuns, q as isLocalHost, qt as ensurePostgresLogin, r as reportPlannedSeeds, rn as imageLayout, rt as createComposeState, sn as findBuildRoot, st as recordRelease, t as DeploySeedsFailed, ur as LOGS_SERVICE, zt as applyBuckets } from "./seeds-CTxTZa-R.mjs";
8
+ import { i as installedFrom } from "./drivers-CTaWrA_L.mjs";
9
+ import { n as verifyStageProviders, r as DeployJournal } from "./providers-sTj-BG0S.mjs";
10
+ import { _ as edgeComposeFile, a as composeStack, f as pinImages, g as EDGE_SERVICE, h as EDGE_PROJECT, i as composeProject, l as RegistryRequired, m as EDGE_NETWORK, n as LOGS_PORT_ENV, o as envFile, r as LOG_ROTATION, s as stackDir, t as EDGE_PORT_ENV, u as assertImagesExist, v as traefikStaticFile } from "./stack-NrdH5ngX.mjs";
11
+ import { t as deployedStackSecrets } from "./secrets-CwLauUB_.mjs";
12
+ import { f as plannedSeeds, o as SeedFailed, p as seedDatabases, u as migrateDatabases } from "./databases-BeGP5eDh.mjs";
13
+ import { n as assertStageCredentials } from "./credentialSchemas-BJFvfkaz.mjs";
14
+ import { dirname, join } from "node:path";
15
+ import { existsSync } from "node:fs";
16
+ import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
17
+ import { hostname, userInfo } from "node:os";
18
+ import { spawn } from "node:child_process";
19
+ import { stringify } from "yaml";
20
+ import { request } from "node:https";
21
+ //#region src/compose/docker.ts
22
+ /**
23
+ * The Docker operations `gkm compose` needs, behind an interface.
24
+ *
25
+ * Small on purpose, like reconcile's: the rules about *when* each runs — the
26
+ * registry is asked before anything is pulled, nothing is started for a tag
27
+ * that is missing — are asserted against a fake, and this file is only the
28
+ * wiring to the real CLI.
29
+ *
30
+ * Every call is an argument array. Image refs, tags and paths come from the
31
+ * workspace, and none of them reaches a shell.
32
+ */
33
+ /** `output` as `spawn` reads it. */
34
+ const STDIO = {
35
+ inherit: "inherit",
36
+ stderr: [
37
+ "ignore",
38
+ 2,
39
+ 2
40
+ ],
41
+ ignore: "ignore"
42
+ };
43
+ /** How a stack's docker commands run: where it is, where output goes. */
44
+ function runOptions(stack, env) {
45
+ return {
46
+ cwd: stack.cwd,
47
+ stdio: STDIO[stack.output ?? "inherit"],
48
+ ...env ? { env } : {},
49
+ ...stack.signal ? { signal: stack.signal } : {}
50
+ };
51
+ }
52
+ /**
53
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
54
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
55
+ */
56
+ function publishedPorts(column) {
57
+ const ports = /* @__PURE__ */ new Set();
58
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
59
+ const first = Number(match[1]);
60
+ const last = match[2] ? Number(match[2]) : first;
61
+ for (let port = first; port <= last; port++) ports.add(port);
62
+ }
63
+ return [...ports];
64
+ }
65
+ /** Each line `docker ps` printed, as the containers holding `port`. */
66
+ function portHolders(output, port) {
67
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
68
+ container,
69
+ ...project ? { project } : {},
70
+ ...service ? { service } : {}
71
+ }));
72
+ }
73
+ /** How long a stack has to pass its health checks. */
74
+ const WAIT_TIMEOUT_S = 180;
75
+ /** `docker compose port` printed nothing a port can be read from. */
76
+ var ServicePortUnknown = class extends GkmError {
77
+ service;
78
+ inside;
79
+ output;
80
+ constructor(service, inside, output) {
81
+ super(`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || "nothing"}). Is it running? \`docker compose ps\` shows the stack.`);
82
+ this.service = service;
83
+ this.inside = inside;
84
+ this.output = output;
85
+ this.name = "ServicePortUnknown";
86
+ }
87
+ };
88
+ /**
89
+ * Whether `ref` names a registry on this machine's loopback — which the
90
+ * daemon pulls from and pushes to over plain HTTP by default, and `docker
91
+ * manifest inspect` reaches only when told `--insecure` (without it, a local
92
+ * registry's image is reported as no such manifest).
93
+ */
94
+ function isLoopbackRegistry(ref) {
95
+ const first = ref.split("/")[0];
96
+ if (!ref.includes("/") || !/[.:]|^localhost$/.test(first)) return false;
97
+ const host = first.replace(/:\d+$/, "");
98
+ return host === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(host);
99
+ }
100
+ /** `docker push` finished without saying what digest the registry stored. */
101
+ var PushDigestUnknown = class extends GkmError {
102
+ ref;
103
+ output;
104
+ constructor(ref, output) {
105
+ 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}\`.`);
106
+ this.ref = ref;
107
+ this.output = output;
108
+ this.name = "PushDigestUnknown";
109
+ }
110
+ };
111
+ /** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */
112
+ function pushedDigest(output) {
113
+ return [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)].at(-1)?.[1];
114
+ }
115
+ function compose(stack, args) {
116
+ return [
117
+ "compose",
118
+ "-p",
119
+ stack.project,
120
+ "-f",
121
+ stack.file,
122
+ ...(stack.overrides ?? []).flatMap((file) => ["-f", file]),
123
+ ...args
124
+ ];
125
+ }
126
+ /** Run a program and keep everything it said, whatever it exits with. */
127
+ function capture(command, args, timeoutMs = 6e4) {
128
+ return new Promise((resolve, reject) => {
129
+ const child = spawn(command, [...args], {
130
+ stdio: [
131
+ "ignore",
132
+ "pipe",
133
+ "pipe"
134
+ ],
135
+ shell: false
136
+ });
137
+ let stdout = "";
138
+ let stderr = "";
139
+ child.stdout.on("data", (chunk) => {
140
+ stdout += chunk.toString();
141
+ });
142
+ child.stderr.on("data", (chunk) => {
143
+ stderr += chunk.toString();
144
+ });
145
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
146
+ timer.unref?.();
147
+ child.on("error", (error) => {
148
+ clearTimeout(timer);
149
+ reject(error);
150
+ });
151
+ child.on("close", (code) => {
152
+ clearTimeout(timer);
153
+ resolve({
154
+ code,
155
+ stdout,
156
+ stderr
157
+ });
158
+ });
159
+ });
160
+ }
161
+ /**
162
+ * Whether a failed `docker manifest inspect` means the tag is not there, as
163
+ * opposed to the registry not answering.
164
+ *
165
+ * Read off the message because that is all the CLI gives. Anything not
166
+ * recognisably "no such tag" is treated as the registry being unreachable:
167
+ * a registry that refused credentials must not be reported as a tag that was
168
+ * never pushed, or the fix offered would be the wrong one.
169
+ */
170
+ function isMissingManifest(output) {
171
+ return /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(output);
172
+ }
173
+ const dockerCompose = {
174
+ async lookup(ref) {
175
+ const { code, stdout, stderr } = await capture("docker", [
176
+ "manifest",
177
+ "inspect",
178
+ ...isLoopbackRegistry(ref) ? ["--insecure"] : [],
179
+ ref
180
+ ]);
181
+ if (code === 0) return {
182
+ ref,
183
+ status: "found"
184
+ };
185
+ const output = `${stderr}\n${stdout}`.trim();
186
+ return isMissingManifest(output) ? {
187
+ ref,
188
+ status: "missing"
189
+ } : {
190
+ ref,
191
+ status: "unreachable",
192
+ detail: output
193
+ };
194
+ },
195
+ async build(stack, services) {
196
+ await run("docker", compose(stack, ["build", ...services]), runOptions(stack, {
197
+ ...process.env,
198
+ DOCKER_BUILDKIT: "1"
199
+ }));
200
+ },
201
+ async pull(stack, services) {
202
+ await run("docker", compose(stack, ["pull", ...services]), runOptions(stack));
203
+ },
204
+ async up(stack, services) {
205
+ await run("docker", compose(stack, [
206
+ "up",
207
+ "-d",
208
+ "--wait",
209
+ `--wait-timeout=${WAIT_TIMEOUT_S}`,
210
+ ...services ? [] : ["--remove-orphans"],
211
+ ...services ?? []
212
+ ]), runOptions(stack));
213
+ },
214
+ async down(stack) {
215
+ await run("docker", compose(stack, ["down"]), runOptions(stack));
216
+ },
217
+ async port(stack, service, inside) {
218
+ const output = await runOutput("docker", compose(stack, [
219
+ "port",
220
+ service,
221
+ String(inside)
222
+ ]), {
223
+ cwd: stack.cwd,
224
+ ...stack.signal ? { signal: stack.signal } : {}
225
+ });
226
+ const port = Number(output.trim().split(":").pop());
227
+ if (!Number.isInteger(port) || port <= 0) throw new ServicePortUnknown(service, inside, output);
228
+ return port;
229
+ },
230
+ async health(stack, service) {
231
+ const { code, stdout } = await capture("docker", [...compose(stack, [
232
+ "ps",
233
+ "--format",
234
+ "{{.Health}}",
235
+ service
236
+ ])]);
237
+ if (code !== 0) return void 0;
238
+ return stdout.trim().split("\n")[0] || void 0;
239
+ },
240
+ async copyOut(stack, service, from, to) {
241
+ await mkdir(dirname(to), { recursive: true });
242
+ await run("docker", compose(stack, [
243
+ "cp",
244
+ `${service}:${from}`,
245
+ to
246
+ ]), runOptions(stack));
247
+ },
248
+ async push(stack, ref) {
249
+ const output = await runOutput("docker", ["push", ref], {
250
+ cwd: stack.cwd,
251
+ ...stack.signal ? { signal: stack.signal } : {}
252
+ });
253
+ const digest = pushedDigest(output);
254
+ if (!digest) throw new PushDigestUnknown(ref, output);
255
+ return digest;
256
+ },
257
+ async digest(ref) {
258
+ const { code, stdout } = await capture("docker", [
259
+ "image",
260
+ "inspect",
261
+ "--format={{json .RepoDigests}} {{.Id}}",
262
+ ref
263
+ ]);
264
+ if (code !== 0) return void 0;
265
+ const [json = "[]", id] = stdout.trim().split(" ");
266
+ const repository = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
267
+ try {
268
+ const digests = JSON.parse(json);
269
+ const match = Array.isArray(digests) ? digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`)) : void 0;
270
+ if (match) return match.slice(repository.length + 1);
271
+ } catch {}
272
+ return id || void 0;
273
+ },
274
+ async ensureNetwork(name) {
275
+ const { code } = await capture("docker", [
276
+ "network",
277
+ "inspect",
278
+ name
279
+ ]);
280
+ if (code === 0) return;
281
+ const created = await capture("docker", [
282
+ "network",
283
+ "create",
284
+ name
285
+ ]);
286
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
287
+ },
288
+ async publishers(port) {
289
+ const { stdout } = await capture("docker", [
290
+ "ps",
291
+ "--format",
292
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
293
+ ]);
294
+ return portHolders(stdout, port);
295
+ }
296
+ };
297
+ /** `docker network create` failed. */
298
+ var NetworkCreateFailed = class extends Error {
299
+ network;
300
+ output;
301
+ constructor(network, output) {
302
+ 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.`);
303
+ this.network = network;
304
+ this.output = output;
305
+ this.name = "NetworkCreateFailed";
306
+ }
307
+ };
308
+ //#endregion
309
+ //#region src/compose/edge.ts
310
+ /**
311
+ * The server's shared Traefik edge, on disk and in Docker: started when a
312
+ * stack needs it, and each stack's routes written to — and removed from —
313
+ * the directory it watches.
314
+ *
315
+ * The edge lives in the deploy user's gkm home (`$GKM_HOME/edge`, else
316
+ * `~/.gkm/edge`): the user who runs `gkm compose` owns it, so nothing needs
317
+ * root, and it sits beside the stage keys that same user already keeps.
318
+ *
319
+ * ~/.gkm/edge/
320
+ * docker-compose.yml the edge's compose project (gkm-edge)
321
+ * traefik.yml its static configuration
322
+ * dynamic/<project>.yml one per stack: its routers, services, middlewares
323
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
324
+ */
325
+ /** The edge's directory on this machine. */
326
+ function edgeDir(env = process.env) {
327
+ return join(gkmHome(env), "edge");
328
+ }
329
+ /** The edge's compose project, as docker is asked about it. */
330
+ function edgeRef(dir, options = {}) {
331
+ return {
332
+ project: EDGE_PROJECT,
333
+ file: join(dir, "docker-compose.yml"),
334
+ cwd: dir,
335
+ ...options
336
+ };
337
+ }
338
+ /**
339
+ * Something other than the proxy a stack is set to holds the edge's ports.
340
+ *
341
+ * With `proxy: 'traefik'`, the stack's own Caddy — still running from before
342
+ * the switch — or any other container; with `proxy: 'caddy'`, the shared
343
+ * edge, or another stack's Caddy. Refused before anything is started, so the
344
+ * stack is never left half on one proxy and half on the other.
345
+ */
346
+ var ComposeProxyClash = class extends GkmError {
347
+ project;
348
+ proxy;
349
+ port;
350
+ holder;
351
+ constructor(project, proxy, port, holder) {
352
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
353
+ const fix = proxy === "traefik" ? holder.project === project && holder.service === "caddy" ? `That is this stack's own Caddy, from before it was switched to proxy: 'traefik'. Move it once: stop it (docker compose -p ${project} stop caddy), then run gkm compose again — the shared edge takes 80/443 and the stack registers with it.` : `The shared edge needs ports 80 and 443. Stop ${holder.container}${holder.project ? ` (docker compose -p ${holder.project} down, or its own gkm compose --down)` : ""}, or move the edge with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.` : holder.project === "gkm-edge" ? `That is the server's shared Traefik edge, which other stacks register with. Set deploy.compose.proxy to 'traefik' for this stage so the stack registers with it too, or stop the edge once nothing uses it (docker compose -p ${EDGE_PROJECT} down).` : `Stop ${holder.container}, or publish this stack's Caddy elsewhere with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.`;
354
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
355
+ this.project = project;
356
+ this.proxy = proxy;
357
+ this.port = port;
358
+ this.holder = holder;
359
+ this.name = "ComposeProxyClash";
360
+ }
361
+ };
362
+ /**
363
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
364
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
365
+ */
366
+ async function assertEdgePorts(docker, options) {
367
+ const { project, proxy, ports } = options;
368
+ for (const port of [ports.https, ports.http]) for (const holder of await docker.publishers(port)) if (!(proxy === "traefik" ? holder.project === "gkm-edge" : holder.project === project && holder.service === "caddy")) throw new ComposeProxyClash(project, proxy, port, holder);
369
+ }
370
+ /** Write a file whole or not at all: a temporary file, then a rename. */
371
+ async function writeAtomic(path, content, mode = 420) {
372
+ const temporary = `${path}.${process.pid}.tmp`;
373
+ await writeFile(temporary, content, { mode });
374
+ await chmod(temporary, mode);
375
+ await rename(temporary, path);
376
+ }
377
+ /** Write a file only when its content changed; whether it did. */
378
+ async function writeIfChanged(path, content) {
379
+ if (await readFile(path, "utf-8").catch(() => void 0) === content) return false;
380
+ await writeAtomic(path, content);
381
+ return true;
382
+ }
383
+ /**
384
+ * The edge, up: its network, its files, and its container — started when it
385
+ * is not running, and recreated when its configuration changed. Idempotent:
386
+ * on a server where it already runs as configured, `up` changes nothing.
387
+ */
388
+ async function ensureEdge(docker, options) {
389
+ const { dir, ports } = options;
390
+ await mkdir(join(dir, "dynamic"), { recursive: true });
391
+ await mkdir(join(dir, "certs"), {
392
+ recursive: true,
393
+ mode: 448
394
+ });
395
+ const staticConfig = traefikStaticFile(ports);
396
+ await writeIfChanged(join(dir, "traefik.yml"), staticConfig);
397
+ await writeIfChanged(join(dir, "docker-compose.yml"), edgeComposeFile({
398
+ dir,
399
+ ports,
400
+ staticConfig,
401
+ logging: options.logging
402
+ }));
403
+ await docker.ensureNetwork(EDGE_NETWORK);
404
+ await docker.up(edgeRef(dir, {
405
+ ...options.output ? { output: options.output } : {},
406
+ ...options.signal ? { signal: options.signal } : {}
407
+ }), [EDGE_SERVICE]);
408
+ return [join(dir, "traefik.yml"), join(dir, "docker-compose.yml")];
409
+ }
410
+ /** A stack's file in the edge's directory. */
411
+ function routesFile(dir, project) {
412
+ return join(dir, "dynamic", `${project}.yml`);
413
+ }
414
+ /**
415
+ * Register a stack with the edge: its certificate first, where it has one,
416
+ * so the routes that need it never load without it — then its routes, in one
417
+ * rename the edge picks up whole.
418
+ */
419
+ async function writeEdgeRoutes(dir, project, routes, certificate) {
420
+ const files = [];
421
+ if (certificate) {
422
+ const certs = join(dir, "certs");
423
+ await mkdir(certs, {
424
+ recursive: true,
425
+ mode: 448
426
+ });
427
+ const crt = join(certs, `${project}.crt`);
428
+ const key = join(certs, `${project}.key`);
429
+ await copyFile(certificate.certFile, `${crt}.tmp`);
430
+ await rename(`${crt}.tmp`, crt);
431
+ await copyFile(certificate.keyFile, `${key}.tmp`);
432
+ await chmod(`${key}.tmp`, 384);
433
+ await rename(`${key}.tmp`, key);
434
+ files.push(crt, key);
435
+ } else await removeCertificate(dir, project);
436
+ await mkdir(join(dir, "dynamic"), { recursive: true });
437
+ const file = routesFile(dir, project);
438
+ await writeAtomic(file, routes);
439
+ files.push(file);
440
+ return files;
441
+ }
442
+ /** What a stack's file holds for the moment between emptying and removal. */
443
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
444
+ async function removeCertificate(dir, project) {
445
+ for (const ext of ["crt", "key"]) await rm(join(dir, "certs", `${project}.${ext}`), { force: true });
446
+ }
447
+ /**
448
+ * Unregister a stack: its routes, then its certificate. Whether there was
449
+ * anything to remove.
450
+ */
451
+ async function removeEdgeRoutes(dir, project) {
452
+ const file = routesFile(dir, project);
453
+ const existed = existsSync(file);
454
+ if (existed) await writeAtomic(file, UNREGISTERED);
455
+ await rm(file, { force: true });
456
+ await removeCertificate(dir, project);
457
+ return existed;
458
+ }
459
+ //#endregion
460
+ //#region src/target/compose/health.ts
461
+ /**
462
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
463
+ * the way a browser reaches it.
464
+ *
465
+ * `docker compose up --wait` already knows each container passed its own
466
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
467
+ * the stack is reachable: whether the edge routes the host to the app, and
468
+ * whether the certificate it presents is one a client accepts. So the check
469
+ * goes through the edge, by hostname, and verifies the certificate.
470
+ */
471
+ /** A request that got no answer in time. */
472
+ var HealthRequestTimedOut = class extends GkmError {
473
+ url;
474
+ timeoutMs;
475
+ constructor(url, timeoutMs) {
476
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
477
+ this.url = url;
478
+ this.timeoutMs = timeoutMs;
479
+ this.name = "HealthRequestTimedOut";
480
+ }
481
+ };
482
+ /** The real probe: one HTTPS GET, the certificate verified. */
483
+ const httpsProbe = ({ url, ca, connectTo, connectPort, timeoutMs, signal }) => {
484
+ const target = new URL(url);
485
+ return new Promise((resolve, reject) => {
486
+ const req = request({
487
+ host: connectTo ?? target.hostname,
488
+ port: connectPort ?? (target.port || 443),
489
+ servername: target.hostname,
490
+ path: `${target.pathname}${target.search}`,
491
+ method: "GET",
492
+ headers: { host: target.host },
493
+ ...ca ? { ca } : {},
494
+ ...signal ? { signal } : {},
495
+ timeout: timeoutMs
496
+ }, (res) => {
497
+ res.resume();
498
+ res.on("end", () => resolve(res.statusCode ?? 0));
499
+ res.on("error", reject);
500
+ });
501
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
502
+ req.on("error", reject);
503
+ req.end();
504
+ });
505
+ };
506
+ /** Whether a status means the app answered as it should. */
507
+ function isHealthy(status) {
508
+ return status >= 200 && status < 400;
509
+ }
510
+ /** Apps that did not answer through the edge. */
511
+ var ComposeAppsUnhealthy = class extends GkmError {
512
+ project;
513
+ apps;
514
+ proxy;
515
+ constructor(project, apps, proxy = "caddy") {
516
+ const names = apps.map((a) => a.app).join(" ");
517
+ super(`${project} started, but ${apps.length === 1 ? "this app does" : "these apps do"} not answer through ${proxy === "caddy" ? "Caddy" : "the shared Traefik edge"}:\n` + apps.map(({ url, last }) => ` - ${url}: ${last}`).join("\n") + (proxy === "caddy" ? `\nSee why with \`docker compose -p ${project} logs caddy ${names}\`.` : `\nSee why with \`docker compose -p gkm-edge logs traefik\` and \`docker compose -p ${project} logs ${names}\`.`));
518
+ this.project = project;
519
+ this.apps = apps;
520
+ this.proxy = proxy;
521
+ this.name = "ComposeAppsUnhealthy";
522
+ }
523
+ };
524
+ //#endregion
525
+ //#region src/target/compose/phases.ts
526
+ /**
527
+ * The compose target's phases: a stage as one Docker Compose stack behind
528
+ * Caddy, on the machine the deploy runs on.
529
+ *
530
+ * The order is the point of this file, and the rules it keeps are these:
531
+ *
532
+ * - A tag is checked before anything happens (`validate`). Every app's image
533
+ * is asked of the registry first; one missing image stops the run naming
534
+ * them all, and nothing is written, pulled or started.
535
+ * - The databases exist before the apps do (`provision`). Postgres comes up
536
+ * alone, its databases, roles and grants are created, its migrations
537
+ * applied and its seeds run from this machine, and only then do the apps
538
+ * start — so an app
539
+ * never boots against a schema that is not there yet.
540
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
541
+ * was released under and the digest it resolved to are written to the
542
+ * stage's state, so "what is this stage running" has an exact answer.
543
+ * - What was started answers (`verify`): each app is asked through Caddy,
544
+ * over HTTPS, with the certificate verified.
545
+ *
546
+ * Every image is built inside Docker from a pruned slice of the build root —
547
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
548
+ * machine before `docker compose build`.
549
+ *
550
+ * Docker, the registry, Postgres and the health probe are
551
+ * injected, so the rules are asserted without a daemon; the defaults are the
552
+ * real ones.
553
+ */
554
+ /** `--push` without `--build`: there is nothing built here to push. */
555
+ var ComposePushNeedsBuild = class extends GkmError {
556
+ constructor() {
557
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
558
+ this.name = "ComposePushNeedsBuild";
559
+ }
560
+ };
561
+ /** Digests to run by, on a run that pulls nothing. */
562
+ var ComposePinNeedsPull = class extends GkmError {
563
+ constructor() {
564
+ 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.");
565
+ this.name = "ComposePinNeedsPull";
566
+ }
567
+ };
568
+ /** A port variable that does not hold a port. */
569
+ var EdgePortInvalid = class extends GkmError {
570
+ variable;
571
+ value;
572
+ constructor(variable, value) {
573
+ super(`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`);
574
+ this.variable = variable;
575
+ this.value = value;
576
+ this.name = "EdgePortInvalid";
577
+ }
578
+ };
579
+ /** A build with no commit to tag its images with. */
580
+ var NoGitRevision = class extends GkmError {
581
+ root;
582
+ constructor(root) {
583
+ 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.`);
584
+ this.root = root;
585
+ this.name = "NoGitRevision";
586
+ }
587
+ };
588
+ /**
589
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
590
+ * at the workspace root. What the generated file cannot know — a port bound
591
+ * to a tailnet address, another log driver — goes there, and is never
592
+ * overwritten.
593
+ */
594
+ function stackOverrideFile(root, stage) {
595
+ return join(root, `docker-compose.${stage}.yml`);
596
+ }
597
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
598
+ async function gitRevision(root) {
599
+ let sha;
600
+ try {
601
+ sha = (await runOutput("git", [
602
+ "rev-parse",
603
+ "--short",
604
+ "HEAD"
605
+ ], { cwd: root })).trim();
606
+ } catch {
607
+ throw new NoGitRevision(root);
608
+ }
609
+ if (!sha) throw new NoGitRevision(root);
610
+ return (await runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
611
+ }
612
+ /** The edge's ports, from the environment — 443 and 80 when unset. */
613
+ function edgePorts(env = process.env) {
614
+ const read = (variable, fallback) => {
615
+ const value = env[variable];
616
+ if (value === void 0 || value === "") return fallback;
617
+ const port = Number(value);
618
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new EdgePortInvalid(variable, value);
619
+ return port;
620
+ };
621
+ const logs = env["GKM_COMPOSE_LOGS_PORT"] ? read(LOGS_PORT_ENV, 0) : void 0;
622
+ return {
623
+ https: read(EDGE_PORT_ENV.https, 443),
624
+ http: read(EDGE_PORT_ENV.http, 80),
625
+ ...logs ? { logs } : {}
626
+ };
627
+ }
628
+ /**
629
+ * The real ones. Each app is asked for three minutes before it counts as
630
+ * down: a deployed stage's first ACME certificate can take that long.
631
+ */
632
+ const defaultDeps = {
633
+ docker: dockerCompose,
634
+ revision: gitRevision,
635
+ sql: pgClient,
636
+ buckets: bucketClient,
637
+ logins: ensurePostgresLogin,
638
+ migrate: migrateDatabases,
639
+ seed: seedDatabases,
640
+ probe: httpsProbe,
641
+ healthAttempts: 90,
642
+ healthIntervalMs: 2e3,
643
+ env: process.env,
644
+ lookup: systemLookup
645
+ };
646
+ /**
647
+ * The stack the stage would run, and — for a tag — the registry's word that
648
+ * every image it names exists. Nothing is written: a missing image stops the
649
+ * run here, before a file, a secret or a container is touched.
650
+ */
651
+ async function validateCompose(ctx, deps, options = {}) {
652
+ const { workspace, stage, identity, tag } = ctx;
653
+ const root = workspace.root;
654
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
655
+ const push = options.push === true;
656
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
657
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
658
+ const registry = workspace.deploy?.registry;
659
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, tag));
660
+ const runnables = {};
661
+ const background = {};
662
+ const manifest = await discover({
663
+ patterns: constructGlobs(workspace),
664
+ cwd: root,
665
+ runnables,
666
+ background
667
+ });
668
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
669
+ const server = push || stage === workspace.stages.local ? void 0 : requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
670
+ if (!push) {
671
+ assertNoStaleSecrets({
672
+ manifest,
673
+ stage,
674
+ supplied: secrets?.custom ?? {}
675
+ });
676
+ await assertStageCredentials({
677
+ root,
678
+ patterns: constructGlobs(workspace),
679
+ manifest,
680
+ stage,
681
+ supplied: secrets?.custom ?? {}
682
+ });
683
+ }
684
+ const layout = mode === "build" ? imageLayout(workspace) : void 0;
685
+ const composed = composeStack({
686
+ workspace,
687
+ manifest,
688
+ runnables,
689
+ background,
690
+ stage,
691
+ identity,
692
+ images: {
693
+ mode,
694
+ tag,
695
+ ...registry ? { registry } : {}
696
+ },
697
+ secrets,
698
+ ...stage === workspace.stages.local ? { localCredentials: (await loadLocalCredentials(workspace)).credentials } : {},
699
+ allowDevServices: ctx.allowDevServices,
700
+ ports: edgePorts(deps.env),
701
+ ...layout ? { layout } : {},
702
+ ...push ? { buildOnly: true } : {}
703
+ });
704
+ reportDevServices(ctx, composed.devServices);
705
+ if (!push && stage !== workspace.stages.local) {
706
+ const verified = await verifyStageProviders({
707
+ workspace,
708
+ manifest,
709
+ stage,
710
+ secrets: secrets?.custom ?? {}
711
+ });
712
+ for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
713
+ }
714
+ if (mode === "build") assertRedisClient(workspace, composed);
715
+ const stack = options.pin ? withPinnedImages(composed, options.pin.file, options.pin.digests) : composed;
716
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, tag, [...stack.apps, ...stack.workers]);
717
+ if (stack.tls && !push) {
718
+ for (const file of [stack.tls.certFile, stack.tls.keyFile]) if (!existsSync(file)) throw new ComposeTlsFileMissing(stage, file);
719
+ }
720
+ if (!push && !stack.local) await deployDns(ctx, deps, stackHosts(stack).filter((host) => !isLocalHost(host)), server);
721
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
722
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
723
+ ctx.secrets.mask(stack.logs.password);
724
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
725
+ }
726
+ const dir = join(root, stackDir(stage));
727
+ const override = stackOverrideFile(root, stage);
728
+ const overrides = existsSync(override) ? [override] : [];
729
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
730
+ const recorded = push ? void 0 : await ctx.state.read(stage);
731
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
732
+ const { ref, tag, digest } = releases.current;
733
+ return [name, {
734
+ ref,
735
+ ...tag ? { tag } : {},
736
+ ...digest ? { digest } : {}
737
+ }];
738
+ }));
739
+ return {
740
+ mode,
741
+ push,
742
+ stack,
743
+ dir,
744
+ ref: {
745
+ project: composeProject(identity),
746
+ file: join(dir, "docker-compose.yml"),
747
+ ...overrides.length > 0 ? { overrides } : {},
748
+ cwd: root,
749
+ output: ctx.childOutput,
750
+ signal: ctx.signal
751
+ },
752
+ secrets,
753
+ generated,
754
+ previous,
755
+ files: [],
756
+ images: {},
757
+ changes: []
758
+ };
759
+ }
760
+ /** A stack whose caches are in Redis, built for an app that has no client. */
761
+ var RedisClientMissing = class extends GkmError {
762
+ apps;
763
+ constructor(apps) {
764
+ 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`);
765
+ this.apps = apps;
766
+ this.name = "RedisClientMissing";
767
+ }
768
+ };
769
+ /**
770
+ * Every backend and worker image built for a stack with a cache can resolve
771
+ * `ioredis` — listed by its app or a directory above it, the way Node and
772
+ * the image's install find it.
773
+ */
774
+ function assertRedisClient(workspace, stack) {
775
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
776
+ const missing = [.../* @__PURE__ */ new Set([...stack.apps.filter((app) => app.kind === "rest-api").map((a) => a.name), ...stack.workers.map((worker) => worker.host)])].filter((name) => {
777
+ const app = workspace.apps[name];
778
+ return app && !installedFrom(join(workspace.root, app.path), "ioredis");
779
+ }).sort();
780
+ if (missing.length > 0) throw new RedisClientMissing(missing);
781
+ }
782
+ /**
783
+ * The stage's secrets — and, for a deployed stage, everything it generates
784
+ * once: its seed, and each declared secret and keyring. Kept only once the
785
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
786
+ * leaves the stage's secrets as it found them.
787
+ */
788
+ /**
789
+ * The deploy's DNS step: the stage's own hosts written through each domain's
790
+ * provider in `dns` where they differ, read back from it, and recorded in the
791
+ * stage's state; hosts no provider writes resolved with the system resolver.
792
+ * A dry run prints the plan and writes nothing, and warns rather than stops.
793
+ */
794
+ async function deployDns(ctx, deps, hosts, server) {
795
+ const { workspace, stage } = ctx;
796
+ if (hosts.length === 0) return;
797
+ if (ctx.skipDns) {
798
+ ctx.logger.info("🌐 DNS skipped (--skip-dns): no record is written or checked");
799
+ return;
800
+ }
801
+ if (ctx.skipResources) {
802
+ ctx.logger.info("🌐 DNS skipped (--skip-resources): the --resources-only run wrote and confirmed the records");
803
+ return;
804
+ }
805
+ if (!server) {
806
+ ctx.logger.info(`🌐 DNS skipped: no ${SERVER_IPV4_KEY} in '${stage}''s secrets — ${serverAddressHint(stage)}`);
807
+ return;
808
+ }
809
+ const log = (line) => ctx.logger.info(line);
810
+ if (workspace.dns) log(`🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${ctx.dryRun ? " (dry run — nothing is written)" : ""}`);
811
+ try {
812
+ const result = await stageDns({
813
+ stage,
814
+ hosts,
815
+ server,
816
+ dns: workspace.dns,
817
+ credentials: ctx.credentials,
818
+ log,
819
+ lookup: deps.lookup ?? systemLookup,
820
+ ...ctx.dryRun ? { dryRun: true } : {},
821
+ ...deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}
822
+ });
823
+ if (!ctx.dryRun) {
824
+ const journal = await DeployJournal.open(ctx.state, stage, () => createComposeState(stage));
825
+ const providers = new Map(result.plan.domains.map((d) => [d.domain, d.provider]));
826
+ await recordDnsChanges(journal, result.changes, (domain) => providers.get(domain));
827
+ }
828
+ 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);
829
+ if (parts.length > 0) log(`🌐 ${parts.join(", ")}`);
830
+ } catch (error) {
831
+ if (ctx.dryRun && error instanceof HostNotPointingAtServer) {
832
+ ctx.logger.warn(`⚠ ${error.message}`);
833
+ return;
834
+ }
835
+ throw error;
836
+ }
837
+ }
838
+ /**
839
+ * `--resources-only`: the stage's DNS records, from the hosts its stack would
840
+ * serve — composed in memory, nothing written, no image asked for. What a CI
841
+ * runner runs with the DNS provider's token, so the server never holds it.
842
+ */
843
+ async function resourcesCompose(ctx, deps) {
844
+ const { workspace, stage } = ctx;
845
+ if (stage === workspace.stages.local) return;
846
+ const stored = await ctx.secrets.read();
847
+ const server = requiredServerAddress(stage, workspace.domains?.[stage], stored?.custom);
848
+ const { composeStageHosts } = await import("./seeds-CTxTZa-R.mjs").then((n) => n.W);
849
+ await deployDns(ctx, deps, (await composeStageHosts({
850
+ workspace,
851
+ stage,
852
+ stored,
853
+ manifest: ctx.manifest,
854
+ runnables: ctx.runnables ?? {},
855
+ background: ctx.background ?? {}
856
+ })).filter((host) => !isLocalHost(host)), server);
857
+ }
858
+ async function stageSecrets(ctx, manifest) {
859
+ const stored = await ctx.secrets.read();
860
+ if (ctx.stage === ctx.workspace.stages.local) return {
861
+ secrets: stored,
862
+ generated: []
863
+ };
864
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
865
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
866
+ for (const value of Object.values(secrets.custom ?? {})) ctx.secrets.mask(value);
867
+ return {
868
+ secrets,
869
+ generated
870
+ };
871
+ }
872
+ /**
873
+ * The stack with each app's and worker's image pinned to the digest the file
874
+ * names: the refs it is checked, pulled and recorded by, and the image each
875
+ * compose service runs.
876
+ */
877
+ function withPinnedImages(stack, file, digests) {
878
+ const apps = pinImages(file, digests, stack.apps);
879
+ const workers = pinImages(file, digests, stack.workers);
880
+ const services = { ...stack.compose.services };
881
+ for (const image of [...apps, ...workers]) services[image.name] = {
882
+ ...services[image.name],
883
+ image: image.ref
884
+ };
885
+ return {
886
+ ...stack,
887
+ apps,
888
+ workers,
889
+ compose: {
890
+ ...stack.compose,
891
+ services
892
+ }
893
+ };
894
+ }
895
+ /**
896
+ * A dry run: the stack's files, written so they can be read, and what a real
897
+ * run would do — no image is built or pulled, no container touched, nothing
898
+ * recorded and no secret kept.
899
+ */
900
+ async function planCompose(ctx, run) {
901
+ 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.`);
902
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack);
903
+ printPlan(ctx, run);
904
+ if (!run.push && run.stack.infra.includes("postgres")) reportPlannedSeeds((await plannedSeeds({
905
+ root: ctx.workspace.root,
906
+ manifest: ctx.manifest
907
+ })).map(({ target, seeds }) => ({
908
+ folder: target.seeds,
909
+ seeds
910
+ })), (line) => ctx.logger.info(line));
911
+ const planned = (change) => {
912
+ run.changes.push(change);
913
+ ctx.emit({
914
+ type: "resource.planned",
915
+ ...change
916
+ });
917
+ };
918
+ for (const service of run.push ? [] : run.stack.infra) planned({
919
+ key: `service:${service}`,
920
+ resourceType: "service",
921
+ action: "ensure"
922
+ });
923
+ for (const app of run.stack.apps) {
924
+ planned({
925
+ key: `image:${app.name}`,
926
+ resourceType: "image",
927
+ action: run.mode === "build" ? "build" : "reuse",
928
+ id: app.ref
929
+ });
930
+ if (run.push) continue;
931
+ planned({
932
+ key: `service:${app.name}`,
933
+ resourceType: "service",
934
+ action: run.previous[app.name] ? "reuse" : "create"
935
+ });
936
+ }
937
+ for (const worker of run.stack.workers) {
938
+ planned({
939
+ key: `image:${worker.name}`,
940
+ resourceType: "image",
941
+ action: run.mode === "build" ? "build" : "reuse",
942
+ id: worker.ref
943
+ });
944
+ if (run.push) continue;
945
+ planned({
946
+ key: `service:${worker.name}`,
947
+ resourceType: "service",
948
+ action: run.previous[worker.name] ? "reuse" : "create"
949
+ });
950
+ }
951
+ if (!run.push) planned({
952
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
953
+ resourceType: "service",
954
+ action: "ensure"
955
+ });
956
+ }
957
+ /**
958
+ * What the apps run on: the stage's generated secrets kept, the stack's files
959
+ * written, its infrastructure started, and its databases, roles, grants and
960
+ * migrations applied.
961
+ */
962
+ async function provisionCompose(ctx, run, deps) {
963
+ const { stack, ref } = run;
964
+ if (run.push) return;
965
+ if (run.generated.length > 0 && run.secrets) {
966
+ await ctx.secrets.write(run.secrets);
967
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
968
+ }
969
+ const ports = edgePorts(deps.env);
970
+ await assertEdgePorts(deps.docker, {
971
+ project: stack.project,
972
+ proxy: stack.proxy,
973
+ ports
974
+ });
975
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
976
+ printPlan(ctx, run);
977
+ if (stack.proxy === "traefik") {
978
+ const dir = edgeDir(deps.env);
979
+ ctx.logger.info(`\n🌐 Starting the shared edge (${EDGE_PROJECT}) from ${dir}…`);
980
+ run.files.push(...await ensureEdge(deps.docker, {
981
+ dir,
982
+ ports,
983
+ logging: {
984
+ driver: LOG_ROTATION.driver,
985
+ options: { ...LOG_ROTATION.options }
986
+ },
987
+ ...ref.output ? { output: ref.output } : {},
988
+ ...ref.signal ? { signal: ref.signal } : {}
989
+ }));
990
+ applied(ctx, run, {
991
+ key: `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
992
+ resourceType: "service",
993
+ action: "ensure",
994
+ id: `${EDGE_PROJECT}/${EDGE_SERVICE}`,
995
+ via: "found"
996
+ });
997
+ }
998
+ if (stack.infra.length > 0) {
999
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
1000
+ await deps.docker.up(ref, stack.infra);
1001
+ for (const service of stack.infra) applied(ctx, run, {
1002
+ key: `service:${service}`,
1003
+ resourceType: "service",
1004
+ action: "ensure",
1005
+ id: `${stack.project}/${service}`,
1006
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
1007
+ });
1008
+ }
1009
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
1010
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
1011
+ }
1012
+ /**
1013
+ * Create each bucket the stack's MinIO serves, and the open paths of each
1014
+ * one a file server fronts — from this machine, on MinIO's loopback port,
1015
+ * the way `gkm dev` creates them.
1016
+ */
1017
+ async function prepareBuckets(ctx, run, deps) {
1018
+ const storage = run.stack.storage;
1019
+ if (storage.buckets.length === 0) return;
1020
+ const port = await deps.docker.port(run.ref, "minio", 9e3);
1021
+ const client = deps.buckets(port, storage);
1022
+ const created = [...await applyBuckets(client, storage.buckets), ...await applyPolicies(client, storage.policies)].filter((entry) => entry.created).length;
1023
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
1024
+ }
1025
+ /**
1026
+ * Create what the plan names in the stack's Postgres, migrate it, then run
1027
+ * its seeds — every one, every time, as each construct's owner.
1028
+ */
1029
+ async function prepareDatabases(ctx, run, deps) {
1030
+ const { stack } = run;
1031
+ const workspace = ctx.workspace;
1032
+ const port = await deps.docker.port(run.ref, "postgres", 5432);
1033
+ const superuser = stack.credential.containers.postgres;
1034
+ const login = await deps.logins({
1035
+ port,
1036
+ login: superuser,
1037
+ legacy: [{
1038
+ user: LEGACY_LOCAL_LOGIN.user,
1039
+ password: superuser.password
1040
+ }, ...stack.local ? [LEGACY_LOCAL_LOGIN] : []]
1041
+ });
1042
+ if (login.notice) ctx.logger.info(login.notice);
1043
+ const statements = postgresStatements(stack.plan, workspace.name, stack.credential.seed);
1044
+ if (statements.length > 0) {
1045
+ ctx.logger.info("🗄️ Creating databases, roles and grants…");
1046
+ await applyPostgres(deps.sql(port, login.login), statements);
1047
+ }
1048
+ const sources = {};
1049
+ const manifest = await discover({
1050
+ patterns: constructGlobs(workspace),
1051
+ cwd: workspace.root,
1052
+ sources
1053
+ });
1054
+ const env = envFor(stack.plan, {
1055
+ ports: { [primaryPortKey("postgres")]: port },
1056
+ project: workspace.name,
1057
+ credentials: {
1058
+ ...stack.credential.containers,
1059
+ postgres: login.login
1060
+ },
1061
+ seed: stack.credential.seed
1062
+ });
1063
+ const options = {
1064
+ root: workspace.root,
1065
+ manifest,
1066
+ sources,
1067
+ env
1068
+ };
1069
+ const runs = await deps.migrate(options);
1070
+ const seeds = await deps.seed({
1071
+ ...options,
1072
+ stage: ctx.stage
1073
+ }).catch((error) => {
1074
+ if (error instanceof SeedFailed) throw new DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
1075
+ throw error;
1076
+ });
1077
+ reportDatabaseRuns(runs.map(({ target, applied }) => ({
1078
+ construct: target.id,
1079
+ folder: target.migrations,
1080
+ applied
1081
+ })), seeds.map(({ target, seeded }) => ({
1082
+ construct: target.id,
1083
+ folder: target.seeds,
1084
+ seeded
1085
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
1086
+ }
1087
+ /**
1088
+ * Each app's image: built from this checkout — inside Docker, every one of
1089
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
1090
+ * live changes.
1091
+ */
1092
+ async function buildCompose(ctx, run, deps) {
1093
+ const { stack, ref } = run;
1094
+ const images = [...stack.apps, ...stack.workers];
1095
+ const apps = images.map((image) => image.app);
1096
+ if (run.push) {
1097
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
1098
+ printPlan(ctx, run);
1099
+ }
1100
+ if (run.mode === "build") {
1101
+ ctx.logger.info("\n🐳 Building images…");
1102
+ await deps.docker.build(ref, apps);
1103
+ } else {
1104
+ ctx.logger.info(`\n🐳 Pulling ${ctx.tag}…`);
1105
+ await deps.docker.pull(ref, apps);
1106
+ }
1107
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
1108
+ for (const image of images) {
1109
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(image.ref);
1110
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
1111
+ run.images[image.app] = {
1112
+ ref: image.ref,
1113
+ tag: image.tag,
1114
+ ...digest ? { digest } : {}
1115
+ };
1116
+ ctx.emit({
1117
+ type: "artifact.built",
1118
+ app: image.app,
1119
+ imageRef: image.ref,
1120
+ ...digest ? { digest } : {}
1121
+ });
1122
+ run.changes.push({
1123
+ key: `image:${image.app}`,
1124
+ resourceType: "image",
1125
+ action: run.mode === "build" ? "build" : "reuse",
1126
+ id: digest ?? image.ref
1127
+ });
1128
+ }
1129
+ }
1130
+ /**
1131
+ * The whole stack up — anything it no longer defines removed — and each
1132
+ * app's image recorded in the stage's state.
1133
+ */
1134
+ async function releaseCompose(ctx, run, deps) {
1135
+ const { stack, ref } = run;
1136
+ if (run.push) return;
1137
+ ctx.logger.info("\n🚀 Starting the stack…");
1138
+ await deps.docker.up(ref);
1139
+ const edge = edgeDir(deps.env);
1140
+ if (stack.proxy === "traefik" && stack.traefik) {
1141
+ const written = await writeEdgeRoutes(edge, stack.project, stack.traefik, stack.tls);
1142
+ run.files.push(...written);
1143
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${EDGE_PROJECT}: ${written.at(-1)}`);
1144
+ } else await removeEdgeRoutes(edge, stack.project);
1145
+ if (stack.local) await deps.docker.copyOut(ref, "caddy", "/data/caddy/pki/authorities/local/root.crt", caFile(run)).catch(() => {});
1146
+ await recordImages(ctx, run);
1147
+ for (const app of stack.apps) {
1148
+ const image = run.images[app.name];
1149
+ applied(ctx, run, {
1150
+ key: `service:${app.name}`,
1151
+ resourceType: "service",
1152
+ action: "ensure",
1153
+ id: `${stack.project}/${app.name}`,
1154
+ via: run.previous[app.name] ? "recorded" : "created"
1155
+ });
1156
+ ctx.emit({
1157
+ type: "app.deployed",
1158
+ app: app.name,
1159
+ applicationId: `${stack.project}/${app.name}`,
1160
+ imageRef: image?.ref ?? app.ref,
1161
+ url: app.url
1162
+ });
1163
+ }
1164
+ for (const worker of stack.workers) applied(ctx, run, {
1165
+ key: `service:${worker.name}`,
1166
+ resourceType: "service",
1167
+ action: "ensure",
1168
+ id: `${stack.project}/${worker.name}`,
1169
+ via: run.previous[worker.name] ? "recorded" : "created"
1170
+ });
1171
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
1172
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url}`);
1173
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
1174
+ if (stack.local) ctx.logger.info(`\n🔐 Certificates are from Caddy's local CA: NODE_EXTRA_CA_CERTS=${join(stackDir(ctx.stage), "caddy-root.crt")}`);
1175
+ }
1176
+ /**
1177
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
1178
+ * records: the ref it runs, the tag it was released under, and the digest
1179
+ * the tag resolved to.
1180
+ */
1181
+ async function recordImages(ctx, run) {
1182
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
1183
+ const by = currentActor();
1184
+ for (const app of [...run.stack.apps, ...run.stack.workers]) {
1185
+ const image = run.images[app.app] ?? {
1186
+ ref: app.ref,
1187
+ tag: app.tag
1188
+ };
1189
+ recordRelease(journal.state, app.app, image, by);
1190
+ }
1191
+ journal.state.identity = ctx.identity.key;
1192
+ await journal.save();
1193
+ }
1194
+ /**
1195
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
1196
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
1197
+ * its certificates are Caddy's internal CA's, so the CA `release` copied out
1198
+ * is the one trusted and the request goes to 127.0.0.1.
1199
+ */
1200
+ async function verifyCompose(ctx, run, deps) {
1201
+ const { stack } = run;
1202
+ if (run.push) return;
1203
+ const ca = stack.local ? await readFile(caFile(run), "utf-8").catch(() => void 0) : void 0;
1204
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
1205
+ const edge = stack.local || stack.proxy === "traefik" ? {
1206
+ connectTo: "127.0.0.1",
1207
+ ...stack.local ? {} : { connectPort: edgePorts(deps.env).https }
1208
+ } : void 0;
1209
+ const results = await Promise.all(stack.apps.map((app) => checkApp(ctx, app, deps, {
1210
+ ca,
1211
+ edge
1212
+ })));
1213
+ results.push(...await Promise.all(stack.workers.map((worker) => checkContainer(ctx, run, deps, worker.name))));
1214
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, LOGS_SERVICE));
1215
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
1216
+ app,
1217
+ url,
1218
+ last
1219
+ }));
1220
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
1221
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local);
1222
+ }
1223
+ /**
1224
+ * A container's own health check, as Docker reports it: a worker's, which
1225
+ * has no route through the edge, and OpenObserve's — by default it has no
1226
+ * host there, and served publicly it answers only the addresses it allows,
1227
+ * which need not include this one.
1228
+ */
1229
+ async function checkContainer(ctx, run, deps, service) {
1230
+ const url = `docker:${service}`;
1231
+ let last = "not asked";
1232
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
1233
+ ctx.signal.throwIfAborted();
1234
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
1235
+ last = health ?? "not running";
1236
+ const healthy = health === "healthy";
1237
+ ctx.emit({
1238
+ type: "health.checked",
1239
+ app: service,
1240
+ url,
1241
+ healthy,
1242
+ attempt
1243
+ });
1244
+ if (healthy) {
1245
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
1246
+ return {
1247
+ app: service,
1248
+ url,
1249
+ last,
1250
+ healthy
1251
+ };
1252
+ }
1253
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
1254
+ }
1255
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
1256
+ return {
1257
+ app: service,
1258
+ url,
1259
+ last,
1260
+ healthy: false
1261
+ };
1262
+ }
1263
+ /** How to open the logs, printed — and as an event, for a headless caller. */
1264
+ function reportLogs(ctx, logs, local) {
1265
+ const lines = logsAccess(logs, {
1266
+ stage: ctx.stage,
1267
+ local,
1268
+ user: currentUser(),
1269
+ hostname: hostname()
1270
+ });
1271
+ ctx.logger.info(`\n${lines.join("\n")}`);
1272
+ ctx.emit({
1273
+ type: "logs.ready",
1274
+ service: LOGS_SERVICE,
1275
+ access: logs.public ? "public" : "tunnel",
1276
+ url: logs.url,
1277
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
1278
+ email: logs.email
1279
+ });
1280
+ }
1281
+ /** This machine's user — a guess at who would SSH in. */
1282
+ function currentUser() {
1283
+ try {
1284
+ return userInfo().username;
1285
+ } catch {
1286
+ return process.env.USER ?? "user";
1287
+ }
1288
+ }
1289
+ async function checkApp(ctx, app, deps, options) {
1290
+ const url = `${app.url}${app.kind === "site" ? "/" : "/health"}`;
1291
+ let last = "not asked";
1292
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
1293
+ ctx.signal.throwIfAborted();
1294
+ let status;
1295
+ try {
1296
+ status = await deps.probe({
1297
+ url,
1298
+ ...options.ca ? { ca: options.ca } : {},
1299
+ ...options.edge,
1300
+ timeoutMs: 1e4,
1301
+ signal: ctx.signal
1302
+ });
1303
+ last = `HTTP ${status}`;
1304
+ } catch (error) {
1305
+ last = error instanceof Error ? error.message : String(error);
1306
+ }
1307
+ const healthy = status !== void 0 && isHealthy(status);
1308
+ ctx.emit({
1309
+ type: "health.checked",
1310
+ app: app.name,
1311
+ url,
1312
+ healthy,
1313
+ ...status !== void 0 ? { status } : {},
1314
+ attempt
1315
+ });
1316
+ if (healthy) {
1317
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
1318
+ return {
1319
+ app: app.name,
1320
+ url,
1321
+ last,
1322
+ healthy
1323
+ };
1324
+ }
1325
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
1326
+ }
1327
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
1328
+ return {
1329
+ app: app.name,
1330
+ url,
1331
+ last,
1332
+ healthy: false
1333
+ };
1334
+ }
1335
+ function composeResult(ctx, run) {
1336
+ const apps = [...run.stack.apps.map((app) => {
1337
+ const image = run.images[app.name];
1338
+ return {
1339
+ appName: app.name,
1340
+ type: app.kind === "site" ? "web" : "backend",
1341
+ success: !ctx.dryRun,
1342
+ applicationId: `${run.stack.project}/${app.name}`,
1343
+ imageRef: image?.ref ?? app.ref,
1344
+ ...image?.digest ? { digest: image.digest } : {},
1345
+ url: app.url
1346
+ };
1347
+ }), ...run.stack.workers.map((worker) => {
1348
+ const image = run.images[worker.name];
1349
+ return {
1350
+ appName: worker.name,
1351
+ type: "backend",
1352
+ success: !ctx.dryRun,
1353
+ applicationId: `${run.stack.project}/${worker.name}`,
1354
+ imageRef: image?.ref ?? worker.ref,
1355
+ ...image?.digest ? { digest: image.digest } : {}
1356
+ };
1357
+ })];
1358
+ return {
1359
+ apps,
1360
+ projectId: run.stack.project,
1361
+ successCount: ctx.dryRun ? 0 : apps.length,
1362
+ failedCount: 0,
1363
+ stage: ctx.stage,
1364
+ identity: ctx.identity.key,
1365
+ tag: ctx.tag,
1366
+ dryRun: ctx.dryRun,
1367
+ environmentId: "",
1368
+ skipped: [...ctx.skipped],
1369
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
1370
+ changes: run.changes
1371
+ };
1372
+ }
1373
+ function caFile(run) {
1374
+ return join(run.dir, "caddy-root.crt");
1375
+ }
1376
+ function applied(ctx, run, change) {
1377
+ const { via, ...rest } = change;
1378
+ run.changes.push(rest);
1379
+ ctx.emit({
1380
+ type: "resource.applied",
1381
+ ...rest,
1382
+ via
1383
+ });
1384
+ }
1385
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
1386
+ async function writeStack(root, dir, stack) {
1387
+ await mkdir(dir, {
1388
+ recursive: true,
1389
+ mode: 448
1390
+ });
1391
+ await chmod(dir, 448);
1392
+ const files = [];
1393
+ const write = async (path, content, mode = 420) => {
1394
+ await mkdir(dirname(path), { recursive: true });
1395
+ await writeFile(path, content, { mode });
1396
+ await chmod(path, mode);
1397
+ files.push(path);
1398
+ };
1399
+ await write(join(dir, "docker-compose.yml"), composeYaml(stack));
1400
+ if (stack.caddyfile !== void 0) {
1401
+ await write(join(dir, "Caddyfile"), stack.caddyfile);
1402
+ await rm(join(dir, "traefik.yml"), { force: true });
1403
+ } else await rm(join(dir, "Caddyfile"), { force: true });
1404
+ if (stack.traefik !== void 0) await write(join(dir, "traefik.yml"), stack.traefik);
1405
+ if (stack.proxy === "caddy" && stack.tls) {
1406
+ await mkdir(join(dir, "tls"), {
1407
+ recursive: true,
1408
+ mode: 448
1409
+ });
1410
+ await write(join(dir, "tls", "cert.pem"), await readFile(stack.tls.certFile, "utf-8"));
1411
+ await write(join(dir, "tls", "key.pem"), await readFile(stack.tls.keyFile, "utf-8"), 384);
1412
+ } else await rm(join(dir, "tls"), {
1413
+ recursive: true,
1414
+ force: true
1415
+ });
1416
+ for (const app of [...stack.apps, ...stack.workers]) if (app.env) await write(join(dir, `${app.name}.env`), envFile(app.env), 384);
1417
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write(join(dir, `${LOGS_SERVICE}.env`), envFile(stack.logs.env), 384);
1418
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write(join(dir, `${REDIS_SERVICE}.env`), envFile(stack.redis.env), 384);
1419
+ for (const entry of await readdir(dir)) if (entry.endsWith(".credentials")) await rm(join(dir, entry));
1420
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write(join(root, path), content);
1421
+ await ensureDockerignore(findBuildRoot(root));
1422
+ return files;
1423
+ }
1424
+ function composeYaml(stack) {
1425
+ const stage = ` --stage ${stack.stage}`;
1426
+ return `# Generated by gkm compose from the construct manifest — do not edit.
1427
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${EDGE_PROJECT})`}, and its workers.
1428
+ # Each backend and worker reads exactly the keys in its own env file beside
1429
+ # this one.
1430
+ #
1431
+ # gkm compose${stage} start or update it
1432
+ # gkm compose${stage} --down stop it
1433
+ ${stringify(stack.compose, {
1434
+ lineWidth: 0,
1435
+ aliasDuplicateObjects: false
1436
+ })}`;
1437
+ }
1438
+ function printPlan(ctx, run) {
1439
+ const { stack, mode, files } = run;
1440
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
1441
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
1442
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
1443
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
1444
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${stackDir(stack.stage)}/`);
1445
+ }
1446
+ //#endregion
1447
+ //#region src/target/compose/index.ts
1448
+ /**
1449
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
1450
+ * Caddy, on the machine that runs the deploy.
1451
+ *
1452
+ * ```bash
1453
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
1454
+ * gkm deploy --target compose --stage production # built from here
1455
+ * gkm deploy --target compose --stage development # the local stage
1456
+ * ```
1457
+ *
1458
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
1459
+ * looked up in the registry — `ImageTagNotFound` before anything changes
1460
+ * - `plan`: the stack's files and what a run would create or reuse
1461
+ * - `provision`: generated secrets kept, files written, infrastructure up,
1462
+ * databases, roles, grants and migrations
1463
+ * - `build`: each backend bundled on the host and every image built — or, for
1464
+ * a tag, pulled
1465
+ * - `release`: `up --wait --remove-orphans`, and each app's image, tag and
1466
+ * digest in the stage's state
1467
+ * - `verify`: each app asked through Caddy over HTTPS
1468
+ *
1469
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
1470
+ * every image and pushes it to `deploy.registry`, and does nothing else.
1471
+ *
1472
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
1473
+ * `--down`), run through the same `deploy()`.
1474
+ */
1475
+ var compose_exports = /* @__PURE__ */ __exportAll({ composeTarget: () => composeTarget });
1476
+ /** The compose target, with its Docker, bundler and probe as given. */
1477
+ function composeTarget(options = {}) {
1478
+ const { mode, push, pin, report, ...given } = options;
1479
+ const deps = {
1480
+ ...defaultDeps,
1481
+ ...given
1482
+ };
1483
+ return defineTarget({
1484
+ name: "compose",
1485
+ runtime: "server",
1486
+ capabilities: {
1487
+ rollback: false,
1488
+ migrations: "target",
1489
+ images: true,
1490
+ localStage: true,
1491
+ selfHostedTelemetry: true
1492
+ },
1493
+ credentials: [],
1494
+ tag: ({ cwd }) => deps.revision(cwd),
1495
+ validate: (ctx) => validateCompose(ctx, deps, {
1496
+ ...mode ? { mode } : {},
1497
+ ...push ? { push } : {},
1498
+ ...pin ? { pin } : {}
1499
+ }),
1500
+ plan: (ctx, run) => planCompose(ctx, run),
1501
+ resources: (ctx) => resourcesCompose(ctx, deps),
1502
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
1503
+ build: (ctx, run) => buildCompose(ctx, run, deps),
1504
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
1505
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
1506
+ result: (ctx, run) => {
1507
+ report?.(run);
1508
+ return composeResult(ctx, run);
1509
+ }
1510
+ });
1511
+ }
1512
+ //#endregion
1513
+ export { stackOverrideFile as a, dockerCompose as c, ComposePushNeedsBuild as i, compose_exports as n, edgeDir as o, ComposePinNeedsPull as r, removeEdgeRoutes as s, composeTarget as t };
1514
+
1515
+ //# sourceMappingURL=compose-D2RFYd_f.mjs.map