@geekmidas/cli 10.0.0-alpha.14 → 10.0.0-alpha.140

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