@geekmidas/cli 10.0.0-alpha.16 → 10.0.0-alpha.161

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