@geekmidas/cli 10.0.0-alpha.15 → 10.0.0-alpha.151

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 (438) hide show
  1. package/README.md +313 -380
  2. package/bin/adjacent-tsconfig.mjs +46 -8
  3. package/bin/gkm.mjs +11 -3
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/EndpointGenerator-CusLH-9S.mjs +1037 -0
  7. package/dist/EndpointGenerator-CusLH-9S.mjs.map +1 -0
  8. package/dist/EndpointGenerator-DyLMYClE.cjs +1096 -0
  9. package/dist/EndpointGenerator-DyLMYClE.cjs.map +1 -0
  10. package/dist/GoDaddyProvider-BZYq0-nV.cjs +412 -0
  11. package/dist/GoDaddyProvider-BZYq0-nV.cjs.map +1 -0
  12. package/dist/GoDaddyProvider-D-8GW8cP.mjs +412 -0
  13. package/dist/GoDaddyProvider-D-8GW8cP.mjs.map +1 -0
  14. package/dist/{HostingerProvider-BZFGYYVA.cjs → HostingerProvider-BxRR2ibx.cjs} +23 -9
  15. package/dist/HostingerProvider-BxRR2ibx.cjs.map +1 -0
  16. package/dist/{HostingerProvider-BY26bWwB.mjs → HostingerProvider-C-C4aiKF.mjs} +23 -9
  17. package/dist/HostingerProvider-C-C4aiKF.mjs.map +1 -0
  18. package/dist/LegacyStateStore-BFkNiBxC.mjs +124 -0
  19. package/dist/LegacyStateStore-BFkNiBxC.mjs.map +1 -0
  20. package/dist/LegacyStateStore-DYaamZqR.cjs +124 -0
  21. package/dist/LegacyStateStore-DYaamZqR.cjs.map +1 -0
  22. package/dist/LocalStateStore-7pP4naiB.mjs +167 -0
  23. package/dist/LocalStateStore-7pP4naiB.mjs.map +1 -0
  24. package/dist/LocalStateStore-C0JSjyCg.cjs +178 -0
  25. package/dist/LocalStateStore-C0JSjyCg.cjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-BTMuu1WS.mjs +534 -0
  27. package/dist/OpenApiTsGenerator-BTMuu1WS.mjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-CI-tceXV.cjs +539 -0
  29. package/dist/OpenApiTsGenerator-CI-tceXV.cjs.map +1 -0
  30. package/dist/{Route53Provider-Cvj40A8I.mjs → Route53Provider-Di_SD9CF.mjs} +3 -3
  31. package/dist/Route53Provider-Di_SD9CF.mjs.map +1 -0
  32. package/dist/{Route53Provider-DVILBsvV.cjs → Route53Provider-emLuQHVw.cjs} +3 -3
  33. package/dist/Route53Provider-emLuQHVw.cjs.map +1 -0
  34. package/dist/S3StateStore-BnmbFco-.cjs +222 -0
  35. package/dist/S3StateStore-BnmbFco-.cjs.map +1 -0
  36. package/dist/S3StateStore-Dzyuiy3V.mjs +223 -0
  37. package/dist/S3StateStore-Dzyuiy3V.mjs.map +1 -0
  38. package/dist/SSMStateStore-BLbjoEFc.cjs +204 -0
  39. package/dist/SSMStateStore-BLbjoEFc.cjs.map +1 -0
  40. package/dist/SSMStateStore-BcNH7efc.mjs +205 -0
  41. package/dist/SSMStateStore-BcNH7efc.mjs.map +1 -0
  42. package/dist/SubscriberGenerator-BNJyPmXJ.cjs +848 -0
  43. package/dist/SubscriberGenerator-BNJyPmXJ.cjs.map +1 -0
  44. package/dist/SubscriberGenerator-CzPrixYu.mjs +783 -0
  45. package/dist/SubscriberGenerator-CzPrixYu.mjs.map +1 -0
  46. package/dist/add-SHsas9Yu.mjs +711 -0
  47. package/dist/add-SHsas9Yu.mjs.map +1 -0
  48. package/dist/add-moAE6nV4.cjs +713 -0
  49. package/dist/add-moAE6nV4.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-BOgA6AcI.mjs +5534 -0
  55. package/dist/apps-BOgA6AcI.mjs.map +1 -0
  56. package/dist/apps-DkxHjd59.cjs +6148 -0
  57. package/dist/apps-DkxHjd59.cjs.map +1 -0
  58. package/dist/aws-8QQ8n-t6.mjs +89 -0
  59. package/dist/aws-8QQ8n-t6.mjs.map +1 -0
  60. package/dist/aws-DY9NqQIT.cjs +100 -0
  61. package/dist/aws-DY9NqQIT.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-D0spRLb-.cjs} +59 -14
  79. package/dist/bundler-D0spRLb-.cjs.map +1 -0
  80. package/dist/{bundler-BodTL4kf.mjs → bundler-Dy-Dfchf.mjs} +59 -14
  81. package/dist/bundler-Dy-Dfchf.mjs.map +1 -0
  82. package/dist/cli-BmCyUTZf.cjs +71 -0
  83. package/dist/cli-BmCyUTZf.cjs.map +1 -0
  84. package/dist/cli-BpT_gg4n.mjs +71 -0
  85. package/dist/cli-BpT_gg4n.mjs.map +1 -0
  86. package/dist/compose-0HkjQywT.cjs +3046 -0
  87. package/dist/compose-0HkjQywT.cjs.map +1 -0
  88. package/dist/compose-B3OOowfE.mjs +1560 -0
  89. package/dist/compose-B3OOowfE.mjs.map +1 -0
  90. package/dist/compose-BIXEPrGA.mjs +2957 -0
  91. package/dist/compose-BIXEPrGA.mjs.map +1 -0
  92. package/dist/compose-BP8OeV7P.cjs +1919 -0
  93. package/dist/compose-BP8OeV7P.cjs.map +1 -0
  94. package/dist/config-BLrAd7Of.mjs +659 -0
  95. package/dist/config-BLrAd7Of.mjs.map +1 -0
  96. package/dist/config-CRk2vdSp.d.mts +268 -0
  97. package/dist/config-CRk2vdSp.d.mts.map +1 -0
  98. package/dist/config-juUyBlb1.cjs +772 -0
  99. package/dist/config-juUyBlb1.cjs.map +1 -0
  100. package/dist/config-oBgsbLip.d.cts +268 -0
  101. package/dist/config-oBgsbLip.d.cts.map +1 -0
  102. package/dist/config.cjs +11 -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-B6ZwGsy-.cjs +2272 -0
  111. package/dist/credentials-B6ZwGsy-.cjs.map +1 -0
  112. package/dist/credentials-DRfP9aG7.mjs +1817 -0
  113. package/dist/credentials-DRfP9aG7.mjs.map +1 -0
  114. package/dist/databases-DawSdqBI.cjs +703 -0
  115. package/dist/databases-DawSdqBI.cjs.map +1 -0
  116. package/dist/databases-mzSUFBTw.mjs +588 -0
  117. package/dist/databases-mzSUFBTw.mjs.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 +647 -0
  125. package/dist/deploy/public.d.cts.map +1 -0
  126. package/dist/deploy/public.d.mts +647 -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-BgOujGGL.mjs +3836 -0
  143. package/dist/deploy-BgOujGGL.mjs.map +1 -0
  144. package/dist/deploy-ciuNiVqo.cjs +3892 -0
  145. package/dist/deploy-ciuNiVqo.cjs.map +1 -0
  146. package/dist/discover-CRywE7yc.cjs +1085 -0
  147. package/dist/discover-CRywE7yc.cjs.map +1 -0
  148. package/dist/discover-DbDrCQ8h.mjs +940 -0
  149. package/dist/discover-DbDrCQ8h.mjs.map +1 -0
  150. package/dist/docker-74kvq2jQ.cjs +1514 -0
  151. package/dist/docker-74kvq2jQ.cjs.map +1 -0
  152. package/dist/docker-CXYz3W2U.mjs +1407 -0
  153. package/dist/docker-CXYz3W2U.mjs.map +1 -0
  154. package/dist/dokploy-CrxDMut1.cjs +38 -0
  155. package/dist/dokploy-CrxDMut1.cjs.map +1 -0
  156. package/dist/dokploy-tNy6ZU64.mjs +38 -0
  157. package/dist/dokploy-tNy6ZU64.mjs.map +1 -0
  158. package/dist/drivers-aM87NQJi.cjs +224 -0
  159. package/dist/drivers-aM87NQJi.cjs.map +1 -0
  160. package/dist/drivers-uxLBq3e3.mjs +195 -0
  161. package/dist/drivers-uxLBq3e3.mjs.map +1 -0
  162. package/dist/eas-B3yv_XVz.mjs +334 -0
  163. package/dist/eas-B3yv_XVz.mjs.map +1 -0
  164. package/dist/eas-CiORdzk0.cjs +337 -0
  165. package/dist/eas-CiORdzk0.cjs.map +1 -0
  166. package/dist/emit-Bj6XSivk.mjs +136 -0
  167. package/dist/emit-Bj6XSivk.mjs.map +1 -0
  168. package/dist/emit-CDC__ubE.cjs +147 -0
  169. package/dist/emit-CDC__ubE.cjs.map +1 -0
  170. package/dist/encryption-Birkm2_E.mjs +89 -0
  171. package/dist/encryption-Birkm2_E.mjs.map +1 -0
  172. package/dist/encryption-drgYmkGP.cjs +90 -0
  173. package/dist/encryption-drgYmkGP.cjs.map +1 -0
  174. package/dist/engine-CW78Wt8x.mjs +3217 -0
  175. package/dist/engine-CW78Wt8x.mjs.map +1 -0
  176. package/dist/engine-CfLaQ0bJ.cjs +3330 -0
  177. package/dist/engine-CfLaQ0bJ.cjs.map +1 -0
  178. package/dist/errors-D8Gwp5kU.mjs +23 -0
  179. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  180. package/dist/errors-DMC4Umsb.cjs +34 -0
  181. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  182. package/dist/github-BfLlBWB5.cjs +901 -0
  183. package/dist/github-BfLlBWB5.cjs.map +1 -0
  184. package/dist/github-DphkHybE.mjs +900 -0
  185. package/dist/github-DphkHybE.mjs.map +1 -0
  186. package/dist/googlePlay-BWDhYvH_.cjs +931 -0
  187. package/dist/googlePlay-BWDhYvH_.cjs.map +1 -0
  188. package/dist/googlePlay-CjzqTF8t.mjs +931 -0
  189. package/dist/googlePlay-CjzqTF8t.mjs.map +1 -0
  190. package/dist/{index-D-iAVHx-.d.cts → index-B35vTdAW.d.cts} +39 -15
  191. package/dist/index-B35vTdAW.d.cts.map +1 -0
  192. package/dist/{index-Cd-qeOam.d.mts → index-Dv1Zj86i.d.mts} +39 -15
  193. package/dist/index-Dv1Zj86i.d.mts.map +1 -0
  194. package/dist/index.cjs +13594 -12347
  195. package/dist/index.cjs.map +1 -1
  196. package/dist/index.mjs +13541 -12292
  197. package/dist/index.mjs.map +1 -1
  198. package/dist/local-Bt9jPziD.cjs +241 -0
  199. package/dist/local-Bt9jPziD.cjs.map +1 -0
  200. package/dist/local-DBtepRK5.mjs +224 -0
  201. package/dist/local-DBtepRK5.mjs.map +1 -0
  202. package/dist/migrate-2YESt4v9.mjs +267 -0
  203. package/dist/migrate-2YESt4v9.mjs.map +1 -0
  204. package/dist/migrate-B-_cASJt.cjs +272 -0
  205. package/dist/migrate-B-_cASJt.cjs.map +1 -0
  206. package/dist/migrate-BUhe0BuA.cjs +181 -0
  207. package/dist/migrate-BUhe0BuA.cjs.map +1 -0
  208. package/dist/migrate-Dp_Y2XGi.mjs +181 -0
  209. package/dist/migrate-Dp_Y2XGi.mjs.map +1 -0
  210. package/dist/notes-DHN4qThL.mjs +399 -0
  211. package/dist/notes-DHN4qThL.mjs.map +1 -0
  212. package/dist/notes-DUq6Bx1I.cjs +500 -0
  213. package/dist/notes-DUq6Bx1I.cjs.map +1 -0
  214. package/dist/openapi.cjs +213 -7
  215. package/dist/openapi.cjs.map +1 -0
  216. package/dist/openapi.d.cts +32 -8
  217. package/dist/openapi.d.cts.map +1 -1
  218. package/dist/openapi.d.mts +32 -8
  219. package/dist/openapi.d.mts.map +1 -1
  220. package/dist/openapi.mjs +208 -2
  221. package/dist/openapi.mjs.map +1 -0
  222. package/dist/projectBucket-CxsutB3D.cjs +263 -0
  223. package/dist/projectBucket-CxsutB3D.cjs.map +1 -0
  224. package/dist/projectBucket-DzLZlleB.mjs +222 -0
  225. package/dist/projectBucket-DzLZlleB.mjs.map +1 -0
  226. package/dist/provider-BqpjG9QM.cjs +57 -0
  227. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  228. package/dist/provider-CEOKk8NS.mjs +46 -0
  229. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  230. package/dist/publish-BVal0GFd.mjs +123 -0
  231. package/dist/publish-BVal0GFd.mjs.map +1 -0
  232. package/dist/publish-DmTJhVe8.cjs +124 -0
  233. package/dist/publish-DmTJhVe8.cjs.map +1 -0
  234. package/dist/ready-BNh3zsSn.cjs +404 -0
  235. package/dist/ready-BNh3zsSn.cjs.map +1 -0
  236. package/dist/ready-g25dcGzK.mjs +375 -0
  237. package/dist/ready-g25dcGzK.mjs.map +1 -0
  238. package/dist/reconcile/public.cjs +3 -5
  239. package/dist/reconcile/public.d.cts +31 -89
  240. package/dist/reconcile/public.d.cts.map +1 -1
  241. package/dist/reconcile/public.d.mts +31 -89
  242. package/dist/reconcile/public.d.mts.map +1 -1
  243. package/dist/reconcile/public.mjs +3 -3
  244. package/dist/{reconcile-DhQ00DpU.mjs → reconcile--I7V4Klj.mjs} +2 -2
  245. package/dist/{reconcile-DhQ00DpU.mjs.map → reconcile--I7V4Klj.mjs.map} +1 -1
  246. package/dist/{reconcile-Dd2iyILf.cjs → reconcile-CuCQBa5-.cjs} +3 -3
  247. package/dist/{reconcile-Dd2iyILf.cjs.map → reconcile-CuCQBa5-.cjs.map} +1 -1
  248. package/dist/resolve-BwTJI8K7.cjs +316 -0
  249. package/dist/resolve-BwTJI8K7.cjs.map +1 -0
  250. package/dist/resolve-UBq26cZc.mjs +263 -0
  251. package/dist/resolve-UBq26cZc.mjs.map +1 -0
  252. package/dist/rollback-BFKex9TO.cjs +165 -0
  253. package/dist/rollback-BFKex9TO.cjs.map +1 -0
  254. package/dist/rollback-DiOcLTRc.mjs +136 -0
  255. package/dist/rollback-DiOcLTRc.mjs.map +1 -0
  256. package/dist/runtime-CFvcLEJW.d.cts +82 -0
  257. package/dist/runtime-CFvcLEJW.d.cts.map +1 -0
  258. package/dist/runtime-dwsH6ddo.d.mts +82 -0
  259. package/dist/runtime-dwsH6ddo.d.mts.map +1 -0
  260. package/dist/s3-BgG_xW-D.cjs +215 -0
  261. package/dist/s3-BgG_xW-D.cjs.map +1 -0
  262. package/dist/s3-CkrerKdA.mjs +215 -0
  263. package/dist/s3-CkrerKdA.mjs.map +1 -0
  264. package/dist/sandbox/config-worker.cjs +43 -0
  265. package/dist/sandbox/config-worker.cjs.map +1 -0
  266. package/dist/sandbox/config-worker.d.cts +1 -0
  267. package/dist/sandbox/config-worker.d.mts +1 -0
  268. package/dist/sandbox/config-worker.mjs +44 -0
  269. package/dist/sandbox/config-worker.mjs.map +1 -0
  270. package/dist/sandbox/credentials-worker.cjs +53 -0
  271. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  272. package/dist/sandbox/credentials-worker.d.cts +1 -0
  273. package/dist/sandbox/credentials-worker.d.mts +1 -0
  274. package/dist/sandbox/credentials-worker.mjs +54 -0
  275. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  276. package/dist/sandbox/discover-worker.cjs +47 -0
  277. package/dist/sandbox/discover-worker.cjs.map +1 -0
  278. package/dist/sandbox/discover-worker.d.cts +1 -0
  279. package/dist/sandbox/discover-worker.d.mts +1 -0
  280. package/dist/sandbox/discover-worker.mjs +48 -0
  281. package/dist/sandbox/discover-worker.mjs.map +1 -0
  282. package/dist/sandbox/migrate-worker.cjs +75 -0
  283. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  284. package/dist/sandbox/migrate-worker.d.cts +1 -0
  285. package/dist/sandbox/migrate-worker.d.mts +1 -0
  286. package/dist/sandbox/migrate-worker.mjs +76 -0
  287. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  288. package/dist/{workspace-mFpI_ky_.cjs → schemas-BCwKKA42.mjs} +399 -1162
  289. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  290. package/dist/{workspace-CgwmXEtc.mjs → schemas-BQ_v0lEX.cjs} +487 -971
  291. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  292. package/dist/secretsManager-CQORubp9.mjs +97 -0
  293. package/dist/secretsManager-CQORubp9.mjs.map +1 -0
  294. package/dist/secretsManager-RAGcEDX1.cjs +108 -0
  295. package/dist/secretsManager-RAGcEDX1.cjs.map +1 -0
  296. package/dist/seeds-B3xvUAQf.cjs +363 -0
  297. package/dist/seeds-B3xvUAQf.cjs.map +1 -0
  298. package/dist/seeds-BCC8vAXR.mjs +298 -0
  299. package/dist/seeds-BCC8vAXR.mjs.map +1 -0
  300. package/dist/serverSetup-CUBu8_Mk.cjs +652 -0
  301. package/dist/serverSetup-CUBu8_Mk.cjs.map +1 -0
  302. package/dist/serverSetup-eh9MUdSN.mjs +652 -0
  303. package/dist/serverSetup-eh9MUdSN.mjs.map +1 -0
  304. package/dist/sniffer-CNTnUmhc.mjs +1824 -0
  305. package/dist/sniffer-CNTnUmhc.mjs.map +1 -0
  306. package/dist/sniffer-CaoQH_kk.cjs +1997 -0
  307. package/dist/sniffer-CaoQH_kk.cjs.map +1 -0
  308. package/dist/snsSubscriptions-DiqwM9Ms.cjs +1173 -0
  309. package/dist/snsSubscriptions-DiqwM9Ms.cjs.map +1 -0
  310. package/dist/snsSubscriptions-zOIIswN0.mjs +1048 -0
  311. package/dist/snsSubscriptions-zOIIswN0.mjs.map +1 -0
  312. package/dist/sst-D6Dvhr6H.mjs +462 -0
  313. package/dist/sst-D6Dvhr6H.mjs.map +1 -0
  314. package/dist/sst-DECRMgjv.cjs +485 -0
  315. package/dist/sst-DECRMgjv.cjs.map +1 -0
  316. package/dist/stack-BZG5HoVN.mjs +2206 -0
  317. package/dist/stack-BZG5HoVN.mjs.map +1 -0
  318. package/dist/stack-CLk9WojF.cjs +2381 -0
  319. package/dist/stack-CLk9WojF.cjs.map +1 -0
  320. package/dist/stage-Cl0DPJ7w.cjs +313 -0
  321. package/dist/stage-Cl0DPJ7w.cjs.map +1 -0
  322. package/dist/stage-DiLPb89O.mjs +302 -0
  323. package/dist/stage-DiLPb89O.mjs.map +1 -0
  324. package/dist/stages-Bs1THSy7.cjs +190 -0
  325. package/dist/stages-Bs1THSy7.cjs.map +1 -0
  326. package/dist/stages-_xCG4Ymu.mjs +190 -0
  327. package/dist/stages-_xCG4Ymu.mjs.map +1 -0
  328. package/dist/target/public.cjs +15 -0
  329. package/dist/target/public.d.cts +28 -0
  330. package/dist/target/public.d.cts.map +1 -0
  331. package/dist/target/public.d.mts +28 -0
  332. package/dist/target/public.d.mts.map +1 -0
  333. package/dist/target/public.mjs +4 -0
  334. package/dist/terminal-XQE106CG.cjs +85 -0
  335. package/dist/terminal-XQE106CG.cjs.map +1 -0
  336. package/dist/terminal-jGj9TtMQ.mjs +85 -0
  337. package/dist/terminal-jGj9TtMQ.mjs.map +1 -0
  338. package/dist/types-Bl_CwZC9.cjs +90 -0
  339. package/dist/types-Bl_CwZC9.cjs.map +1 -0
  340. package/dist/{types-BGo5TaNE.d.mts → types-Dk--xVOT.d.cts} +2234 -439
  341. package/dist/types-Dk--xVOT.d.cts.map +1 -0
  342. package/dist/{types-C5ZNpUad.d.cts → types-DwQYpd_0.d.mts} +2232 -439
  343. package/dist/types-DwQYpd_0.d.mts.map +1 -0
  344. package/dist/types-Y1NfWlyG.mjs +61 -0
  345. package/dist/types-Y1NfWlyG.mjs.map +1 -0
  346. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  347. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  348. package/dist/utils-D_fxUqvU.mjs +156 -0
  349. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  350. package/dist/vitest.cjs +65 -0
  351. package/dist/vitest.cjs.map +1 -0
  352. package/dist/vitest.d.cts +29 -0
  353. package/dist/vitest.d.cts.map +1 -0
  354. package/dist/vitest.d.mts +29 -0
  355. package/dist/vitest.d.mts.map +1 -0
  356. package/dist/vitest.mjs +65 -0
  357. package/dist/vitest.mjs.map +1 -0
  358. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  359. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  360. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  361. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  362. package/dist/workspace/index.cjs +6 -2
  363. package/dist/workspace/index.d.cts +3 -3
  364. package/dist/workspace/index.d.mts +3 -3
  365. package/dist/workspace/index.mjs +2 -2
  366. package/dist/workspace-1szcahj9.cjs +2916 -0
  367. package/dist/workspace-1szcahj9.cjs.map +1 -0
  368. package/dist/workspace-DFGsrjGD.mjs +2480 -0
  369. package/dist/workspace-DFGsrjGD.mjs.map +1 -0
  370. package/package.json +66 -14
  371. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  372. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  373. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  374. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  375. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  376. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  377. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  378. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  379. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  380. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  381. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  382. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  383. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  384. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  385. package/dist/bundler-BeNDZdHQ.cjs.map +0 -1
  386. package/dist/bundler-BodTL4kf.mjs.map +0 -1
  387. package/dist/config-Q1rvKHvw.cjs +0 -467
  388. package/dist/config-Q1rvKHvw.cjs.map +0 -1
  389. package/dist/config-pqGD3hF9.mjs +0 -414
  390. package/dist/config-pqGD3hF9.mjs.map +0 -1
  391. package/dist/config.d.cts.map +0 -1
  392. package/dist/config.d.mts.map +0 -1
  393. package/dist/credentials-BekkKtY_.mjs +0 -2780
  394. package/dist/credentials-BekkKtY_.mjs.map +0 -1
  395. package/dist/credentials-Q6F0uqJq.cjs +0 -2917
  396. package/dist/credentials-Q6F0uqJq.cjs.map +0 -1
  397. package/dist/discover-BERGFg8v.cjs +0 -288
  398. package/dist/discover-BERGFg8v.cjs.map +0 -1
  399. package/dist/discover-CK-n3w6b.mjs +0 -244
  400. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  401. package/dist/emit-BdoPFjZf.cjs +0 -253
  402. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  403. package/dist/emit-Bzq7JsMP.mjs +0 -224
  404. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  405. package/dist/fullstack-secrets-BET8gqwK.mjs +0 -81
  406. package/dist/fullstack-secrets-BET8gqwK.mjs.map +0 -1
  407. package/dist/fullstack-secrets-DXsWO-5m.cjs +0 -92
  408. package/dist/fullstack-secrets-DXsWO-5m.cjs.map +0 -1
  409. package/dist/generator-LfZU7NlU.mjs +0 -247
  410. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  411. package/dist/generator-Wdfp0jCS.cjs +0 -282
  412. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  413. package/dist/github-BfflNPVe.cjs +0 -203
  414. package/dist/github-BfflNPVe.cjs.map +0 -1
  415. package/dist/github-CRwnxKmD.mjs +0 -203
  416. package/dist/github-CRwnxKmD.mjs.map +0 -1
  417. package/dist/index-Cd-qeOam.d.mts.map +0 -1
  418. package/dist/index-D-iAVHx-.d.cts.map +0 -1
  419. package/dist/keystore-B4PRlbgE.mjs +0 -81
  420. package/dist/keystore-B4PRlbgE.mjs.map +0 -1
  421. package/dist/keystore-DgGRj2Yy.cjs +0 -98
  422. package/dist/keystore-DgGRj2Yy.cjs.map +0 -1
  423. package/dist/openapi-Dcbme-Us.cjs +0 -2038
  424. package/dist/openapi-Dcbme-Us.cjs.map +0 -1
  425. package/dist/openapi-vy4JzhUv.mjs +0 -1991
  426. package/dist/openapi-vy4JzhUv.mjs.map +0 -1
  427. package/dist/storage-C-30BD1e.cjs +0 -272
  428. package/dist/storage-C-30BD1e.cjs.map +0 -1
  429. package/dist/storage-P_b3w7uj.mjs +0 -231
  430. package/dist/storage-P_b3w7uj.mjs.map +0 -1
  431. package/dist/sync-B3xxXtJT.mjs +0 -88
  432. package/dist/sync-B3xxXtJT.mjs.map +0 -1
  433. package/dist/sync-D7uTIIEi.cjs +0 -111
  434. package/dist/sync-D7uTIIEi.cjs.map +0 -1
  435. package/dist/types-BGo5TaNE.d.mts.map +0 -1
  436. package/dist/types-C5ZNpUad.d.cts.map +0 -1
  437. package/dist/workspace-CgwmXEtc.mjs.map +0 -1
  438. package/dist/workspace-mFpI_ky_.cjs.map +0 -1
@@ -0,0 +1,2206 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { Q as imageRef, a as findRootDomain, o as normalizeDnsConfig } from "./credentials-DRfP9aG7.mjs";
3
+ import { B as LOGS_PORT, I as otlpTelemetryEnv, L as resolveStageTelemetry, lt as certificateFor, ut as proxyFor, yt as isReservedStageKey, z as telemetryEnv } from "./workspace-DFGsrjGD.mjs";
4
+ import { $ as OFFLINE_BUILD_ADDRESS, A as originSecretKey, Bt as hostFor, D as ORIGIN_VERIFY_HEADER, Et as localRolePassword, I as PROCESSOR_PORT, It as telemetryOf, L as TURBO_VERSION, Lt as usesTelemetry, Mt as isTelemetryKey, N as composeBuildPaths, Nt as scopeTelemetryEnv, R as WORKER_PORT, Rt as LOCAL_TLD, a as networkEnv, bt as bucketPolicies, ct as BACKUPS_SERVICE, et as offlineBuildHosts, ft as backupsService, j as processorOriginHost, kt as planFor, nt as runsServer, ot as processorUnits, pt as stackBackups, qt as stageBackups, s as processEnvKeys, st as workerUnits, tt as publicBuildValues, w as localAuthorityPaths, yt as bucketLifecycles, zt as clientIpRule } from "./apps-BOgA6AcI.mjs";
5
+ import { A as minioWebhookEnv, C as redisService, M as watchedBuckets, N as EMULATOR_ACCESS_KEY_ID, Q as logsService, R as DEFAULT_IMAGES, S as STACK_CACHE, T as stackRedis, V as portKeys, X as LOGS_SERVICE, at as resolveHost, et as stackLogs, g as postgresSuperuser, it as isMainFrontendApp, n as composeFor, nt as NoDomainForStage, p as LOCAL_RABBITMQ_USER, x as REDIS_SERVICE } from "./compose-B3OOowfE.mjs";
6
+ import { a as SNS_SUBSCRIPTIONS_KEY, c as INBOX_RELAY_TOKEN_KEY, d as inboxWebhookUrl, o as objectsRoute, s as subscriberRoute, u as inboxRelayWorker } from "./SubscriberGenerator-CzPrixYu.mjs";
7
+ import { g as appKey } from "./config-BLrAd7Of.mjs";
8
+ import { n as DEFAULT_EVENTS } from "./types-Y1NfWlyG.mjs";
9
+ import { _ as suppliedOnly, f as devServicesUsed, g as stageServiceDeclarations, i as stageProviderNotes, p as externalServices } from "./notes-DHN4qThL.mjs";
10
+ import { o as processorDockerfile, r as appDockerfile, s as workerDockerfile, v as validateImageRef } from "./docker-CXYz3W2U.mjs";
11
+ import { join } from "node:path";
12
+ import { createHash } from "node:crypto";
13
+ import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER, EDGE_TOKEN_KEY, WILDCARD_SUBDOMAIN, isWildcardSite, provideKey, provisionOrder } from "@geekmidas/manifest";
14
+ import { parse as parse$1, stringify } from "yaml";
15
+ import bcrypt from "bcryptjs";
16
+ //#region src/compose/routes.ts
17
+ /** A route with handlers and a check that would have to hold for each of them. */
18
+ var EdgeRouteConflict = class extends Error {
19
+ route;
20
+ constructor(route) {
21
+ super(`The edge route '${route}' sends some paths to other upstreams and also restricts who or what it answers. The two are not combined: give the restricted paths a host of their own.`);
22
+ this.route = route;
23
+ this.name = "EdgeRouteConflict";
24
+ }
25
+ };
26
+ /** @throws {EdgeRouteConflict} */
27
+ function assertRouteRenderable(route) {
28
+ if (route.handlers?.length && (route.allow || route.paths || route.prefixes || route.requireHeader)) throw new EdgeRouteConflict(route.name);
29
+ }
30
+ /** File descriptors a process holding sockets may open. */
31
+ const NOFILE = {
32
+ soft: 1048576,
33
+ hard: 1048576
34
+ };
35
+ /**
36
+ * What the edge runs with: a descriptor per socket, twice — the client's and
37
+ * the upstream's — and every local port for those upstream connections. One
38
+ * edge address to one upstream has only the ephemeral range to open
39
+ * connections from, ~28k by Linux's default; widened, ~64k per replica.
40
+ */
41
+ const EDGE_LIMITS = {
42
+ sysctls: { "net.ipv4.ip_local_port_range": "1024 65535" },
43
+ ulimits: { nofile: NOFILE }
44
+ };
45
+ //#endregion
46
+ //#region src/compose/caddyfile.ts
47
+ /**
48
+ * The stack's own edge, rendered for Caddy: one site block per route.
49
+ *
50
+ * Deployed, each host is the stage's real domain and Caddy gets it a
51
+ * certificate from Let's Encrypt on first request — the same automatic HTTPS
52
+ * it does anywhere, with nothing to configure but the name — or serves the
53
+ * stage's own certificate (`deploy.compose.tls`). Locally the hosts are
54
+ * `*.localhost` and the certificate is the one gkm's local authority issued,
55
+ * as the `gkm dev` edge's is, so a local stack is `https://` like a deployed
56
+ * one.
57
+ *
58
+ * Pure: the routes are data (`routes.ts`), and rendering them is one string.
59
+ */
60
+ /** Where Caddy reads a stage's own certificate, inside its container. */
61
+ const CADDY_TLS_DIR = "/etc/caddy/tls";
62
+ /** An upstream on the stack's own network: its service name. */
63
+ function address({ service, port }) {
64
+ return `${service}:${port}`;
65
+ }
66
+ /** The Caddyfile for a stack's edge. */
67
+ function edgeCaddyfile(routes, options) {
68
+ const { tls } = options;
69
+ const ask = routes.find((route) => route.wildcard?.tls.kind === "on-demand")?.wildcard?.tls;
70
+ const onDemand = ask?.kind === "on-demand" ? `
71
+ on_demand_tls {
72
+ ask ${ask.ask}
73
+ }` : "";
74
+ const settings = `${options.email ? `\n\temail ${options.email}` : ""}${options.redirects === false ? "\n auto_https disable_redirects" : ""}${onDemand}`;
75
+ const global = settings ? `{${settings}\n}` : "";
76
+ const certificate = tls.kind === "files" ? `
77
+ tls ${tls.certFile} ${tls.keyFile}
78
+ ` : "";
79
+ const blocks = [...routes.filter((route) => !route.wildcard), ...routes.filter((route) => route.wildcard)].map((route) => siteBlock(route, options.edgeToken, route.wildcard?.tls.kind === "on-demand" ? `
80
+ tls {
81
+ on_demand
82
+ }
83
+ ` : certificate));
84
+ return `${HEADER}${global ? `${global}\n\n` : ""}${blocks.join("\n\n")}\n`;
85
+ }
86
+ /** One route's site block. */
87
+ function siteBlock(route, edgeToken, certificate) {
88
+ assertRouteRenderable(route);
89
+ const { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;
90
+ const allowed = [...paths ?? [], ...(prefixes ?? []).map((prefix) => `${prefix}*`)];
91
+ const except = route.wildcard?.except ?? [];
92
+ const checks = `${except.length ? `
93
+ # Labels no tenant may take, although nothing in this stack answers them.
94
+ @protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(" ")}
95
+ respond @protected 404
96
+ ` : ""}${allow ? `
97
+ # Only these addresses — the peer Caddy sees, never a header a client
98
+ # could set. Everything else is refused before it reaches the upstream.
99
+ @denied not remote_ip ${allow.join(" ")}
100
+ respond @denied 403
101
+ ` : ""}${requireHeader ? `
102
+ # Only what the CDN sends: it adds this header to every request, and this
103
+ # host would be reached around the CDN otherwise.
104
+ @forged not header ${requireHeader.name} "${requireHeader.value}"
105
+ respond @forged 403
106
+ ` : ""}${auth ? `
107
+ # The stage's login, asked for before anything reaches the upstream.
108
+ basic_auth {
109
+ ${auth.user} ${auth.hash}
110
+ }
111
+ ` : ""}${allowed.length ? `
112
+ # Only these paths answer. Everything else on this host is refused before
113
+ # it reaches the upstream.
114
+ @elsewhere not path ${allowed.join(" ")}
115
+ respond @elsewhere 404
116
+ ` : ""}`;
117
+ const proxy = proxyBlock(route);
118
+ const body = handlers?.length ? `${handlers.map((handler, index) => `
119
+ # Answered by another service: ${handler.name}.
120
+ @handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(" ")}
121
+ handle @handler${index} {
122
+ reverse_proxy ${handler.upstreams.map(address).join(" ")}
123
+ }
124
+ `).join("")}
125
+ handle {${proxy.replace(/\n/g, "\n ")}
126
+ }` : proxy;
127
+ return `https://${host} {${certificate}${clientIpRule(edgeToken)}
128
+ ${checks}${body}
129
+ }`;
130
+ }
131
+ /** Where a route's requests go, when no handler took them. */
132
+ function proxyBlock(route) {
133
+ const { upstreams, prefix, streaming } = route;
134
+ const health = healthCheck(route);
135
+ return prefix ? `
136
+ # A bucket, served at a host of its own: the bucket is a prefix on MinIO,
137
+ # which routes and signs on the Host header — so it is sent the upstream's.
138
+ reverse_proxy ${upstreams.map(address).join(" ")} {
139
+ rewrite ${prefix}{uri}
140
+ header_up Host {upstream_hostport}${health}
141
+ }` : `
142
+ # Host and X-Forwarded-* are passed through as Caddy does by default, so
143
+ # an app builds redirects, cookies and links on the address a caller used.
144
+ reverse_proxy ${upstreams.map(address).join(" ")}${streaming || health ? ` {${streaming ? `
145
+ # Never buffer: a streamed response — server-sent events, a Next.js
146
+ # RSC payload — reaches the client as each chunk is written.
147
+ flush_interval -1` : ""}${health}
148
+ }` : ""}`;
149
+ }
150
+ /**
151
+ * Caddy's own check of each upstream, as the Traefik edge's
152
+ * `loadBalancer.healthCheck`: one that stops answering is taken out of
153
+ * rotation until it does again. Caddy starts once its apps have — not once
154
+ * they are healthy — so this is what keeps a request from an upstream that
155
+ * is not up, and a route to an app with none up answers an error (503)
156
+ * rather than going missing.
157
+ */
158
+ function healthCheck({ health }) {
159
+ return health ? `
160
+ # Each upstream asked on its own: one that stops answering is out of
161
+ # rotation until it answers again.
162
+ health_uri ${health}
163
+ health_interval 5s
164
+ health_timeout 3s` : "";
165
+ }
166
+ const HEADER = `# Generated by gkm compose from the construct manifest — do not edit.
167
+ #
168
+ # One host per API and site, each in front of its own container, one per
169
+ # file server in front of the stack's MinIO — its processors' paths sent to
170
+ # their own service — one per worker SNS pushes to and per processor unit a
171
+ # CDN reaches, answering only those paths, and — when its logs are served
172
+ # publicly — one for OpenObserve, to the addresses it allows. A site the
173
+ # stage puts behind a password asks for its login first.
174
+ `;
175
+ //#endregion
176
+ //#region src/compose/images.ts
177
+ /**
178
+ * Which image each app runs — and, for a tag, whether every one exists.
179
+ *
180
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
181
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
182
+ * image is asked of the registry before anything is pulled or the running
183
+ * stack is touched, and one missing image stops the whole run naming every
184
+ * one that is missing. Nor is a missing image quietly built instead — a build
185
+ * of whatever is checked out here is not the release the tag names.
186
+ */
187
+ /**
188
+ * The tag a site's image carries for a release.
189
+ *
190
+ * A site's public URLs are inlined when it is built, so one bundle serves one
191
+ * stage: `v1.4.0-production` and `v1.4.0-staging` are two images of the same
192
+ * commit. A backend reads its URLs at runtime, so one image serves every stage
193
+ * and its tag is the release's alone.
194
+ */
195
+ function siteTag(tag, stage) {
196
+ return `${tag}-${stage}`;
197
+ }
198
+ /** Images a tag names that the registry does not have. */
199
+ var ImageTagNotFound = class extends GkmError {
200
+ tag;
201
+ refs;
202
+ constructor(tag, refs) {
203
+ super(`The registry has no image for ${refs.length === 1 ? "this app" : `${refs.length} apps`} at '${tag}':\n` + refs.map((ref) => ` - ${ref}`).join("\n") + `\nNothing was pulled or started. Push '${tag}' for every app from CI, pick a tag that exists, or run without --tag to build from this checkout.`);
204
+ this.tag = tag;
205
+ this.refs = refs;
206
+ this.name = "ImageTagNotFound";
207
+ }
208
+ };
209
+ /** The registry did not answer, or did not let this machine in. */
210
+ var RegistryUnreachable = class extends GkmError {
211
+ ref;
212
+ detail;
213
+ constructor(ref, detail) {
214
+ super(`Could not ask the registry about ${ref}: ${detail || "no answer"}\nNothing was pulled or started. Check the registry is reachable and that this machine is logged in to it (\`docker login <registry>\`).`);
215
+ this.ref = ref;
216
+ this.detail = detail;
217
+ this.name = "RegistryUnreachable";
218
+ }
219
+ };
220
+ /**
221
+ * Assert every image exists, before anything else happens.
222
+ *
223
+ * Asked all at once and reported all at once: a release missing two images is
224
+ * one problem with two names, and finding the second only after fixing the
225
+ * first is a slower way to learn the same thing.
226
+ *
227
+ * @throws {RegistryUnreachable} when the registry cannot say
228
+ * @throws {ImageTagNotFound} listing every missing image
229
+ */
230
+ async function assertImagesExist(docker, tag, images) {
231
+ const lookups = await Promise.all(images.map((image) => docker.lookup(image.ref)));
232
+ const unreachable = lookups.find((lookup) => lookup.status === "unreachable");
233
+ if (unreachable?.status === "unreachable") throw new RegistryUnreachable(unreachable.ref, unreachable.detail);
234
+ const missing = lookups.filter((lookup) => lookup.status === "missing").map((lookup) => lookup.ref);
235
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
236
+ }
237
+ /**
238
+ * A push or a pull with no `deploy.registry` to push to or pull from.
239
+ *
240
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
241
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
242
+ * from, somebody else's account. It is never a fallback.
243
+ */
244
+ var RegistryRequired = class extends GkmError {
245
+ operation;
246
+ ref;
247
+ constructor(operation, ref) {
248
+ super(`${operation === "push" ? "Pushing" : "Pulling"} images needs a registry, and gkm.config.ts sets no deploy.registry: '${ref}' would be ${operation === "push" ? "pushed to" : "pulled from"} Docker Hub. Set deploy.registry (e.g. registry: 'ghcr.io/acme') in gkm.config.ts.` + (operation === "pull" ? " To run images built here instead, pass --build." : ""));
249
+ this.operation = operation;
250
+ this.ref = ref;
251
+ this.name = "RegistryRequired";
252
+ }
253
+ };
254
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
255
+ function pinnedRef(ref, digest) {
256
+ return `${ref.split("@")[0]}@${digest}`;
257
+ }
258
+ /** A digests file with no entry for an app the stack runs. */
259
+ var ImageDigestMissing = class extends GkmError {
260
+ file;
261
+ apps;
262
+ constructor(file, apps) {
263
+ super(`${file} pins no digest for ${apps.join(", ")}. Use the file the same release's \`gkm compose --build --push --digests-file\` wrote, or run without --digests-file to pull by tag.`);
264
+ this.file = file;
265
+ this.apps = apps;
266
+ this.name = "ImageDigestMissing";
267
+ }
268
+ };
269
+ /** A digests file entry that is not this app's image. */
270
+ var ImageDigestMismatch = class extends GkmError {
271
+ app;
272
+ expected;
273
+ found;
274
+ constructor(app, expected, found) {
275
+ super(`The digests file pins '${app}' to ${found}, but this release runs ${expected}. It was written for another registry, project, stage or tag; use the file this stage's push of this tag wrote.`);
276
+ this.app = app;
277
+ this.expected = expected;
278
+ this.found = found;
279
+ this.name = "ImageDigestMismatch";
280
+ }
281
+ };
282
+ /** A digests file that is not a JSON object of app to pinned ref. */
283
+ var ImageDigestsInvalid = class extends GkmError {
284
+ file;
285
+ detail;
286
+ constructor(file, detail) {
287
+ super(`${file} is not a digests file (${detail}). It should be the JSON object \`gkm compose --build --push --digests-file\` writes: { "api": "<registry>/<image>:<tag>@sha256:…" }.`);
288
+ this.file = file;
289
+ this.detail = detail;
290
+ this.name = "ImageDigestsInvalid";
291
+ }
292
+ };
293
+ /** Parse a digests file's content, checking its shape. */
294
+ function parseDigests(file, content) {
295
+ let parsed;
296
+ try {
297
+ parsed = JSON.parse(content);
298
+ } catch (error) {
299
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
300
+ }
301
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
302
+ for (const [app, value] of Object.entries(parsed)) if (typeof value !== "string" || !/@sha256:[0-9a-f]{64}$/.test(value)) throw new ImageDigestsInvalid(file, `'${app}' is not an <image>:<tag>@sha256:… ref`);
303
+ return parsed;
304
+ }
305
+ /**
306
+ * Each image pinned to the digest the file names for it.
307
+ *
308
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
309
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
310
+ */
311
+ function pinImages(file, digests, images) {
312
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
313
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
314
+ return images.map((image) => {
315
+ const pinned = digests[image.app];
316
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
317
+ return {
318
+ ...image,
319
+ ref: pinned
320
+ };
321
+ });
322
+ }
323
+ //#endregion
324
+ //#region src/compose/sitePassword.ts
325
+ /**
326
+ * A site served behind a password on some deployed stages — a `StaticSite`'s
327
+ * `password`, naming a `RandomPassword` — so a staging build is not public
328
+ * while it is being tried.
329
+ *
330
+ * The edge asks for it with HTTP basic auth, before a request reaches the
331
+ * site: the browser prompts, and nothing of the site loads until the stage's
332
+ * login is given. The user is the stage's name; the password is the
333
+ * `RandomPassword`'s value on the stage, generated and kept like any other.
334
+ * Only its bcrypt hash reaches the edge's config.
335
+ *
336
+ * Pure.
337
+ */
338
+ /** A site's `password` names a `RandomPassword` the manifest does not hold. */
339
+ var SitePasswordNotDeclared = class extends GkmError {
340
+ site;
341
+ secret;
342
+ constructor(site, secret) {
343
+ super(`'${site}' is served behind the password '${secret}', and no RandomPassword '${secret}' was found. Export it from a constructs file, as any construct is: export const ${secret[0].toLowerCase()}${secret.slice(1)} = new RandomPassword('${secret}');`);
344
+ this.site = site;
345
+ this.secret = secret;
346
+ this.name = "SitePasswordNotDeclared";
347
+ }
348
+ };
349
+ /** A site's `password` names a stage the workspace does not deploy. */
350
+ var UnknownPasswordStage = class extends GkmError {
351
+ site;
352
+ stage;
353
+ deployed;
354
+ constructor(site, stage, deployed) {
355
+ super(`'${site}' is served behind a password on '${stage}', which is not one of the workspace's deployed stages (${deployed.map((s) => `'${s}'`).join(", ")}). Name one of them in its password's stages.`);
356
+ this.site = site;
357
+ this.stage = stage;
358
+ this.deployed = deployed;
359
+ this.name = "UnknownPasswordStage";
360
+ }
361
+ };
362
+ /** A site behind a password, with none in the stage's secrets. */
363
+ var SitePasswordMissing = class extends GkmError {
364
+ stage;
365
+ key;
366
+ constructor(stage, key) {
367
+ super(`A site of '${stage}' is served behind a password, and the stage has no ${key} in its secrets. Run gkm compose --stage ${stage} once to generate it, or set one: gkm secrets:set ${key} '…' --stage ${stage}`);
368
+ this.stage = stage;
369
+ this.key = key;
370
+ this.name = "SitePasswordMissing";
371
+ }
372
+ };
373
+ /**
374
+ * A site behind a password on a stage it deploys through a target that cannot
375
+ * ask for a login. Refused rather than ignored: ignored, the site would be
376
+ * public while its construct says it is not.
377
+ */
378
+ var SitePasswordNeedsCompose = class extends GkmError {
379
+ site;
380
+ stage;
381
+ target;
382
+ constructor(site, stage, target) {
383
+ super(`'${site}' is served behind a password on '${stage}', and it deploys through '${target}', which cannot ask for one yet — only compose does. Remove ${stage} from its password's stages, or deploy it with compose.`);
384
+ this.site = site;
385
+ this.stage = stage;
386
+ this.target = target;
387
+ this.name = "SitePasswordNeedsCompose";
388
+ }
389
+ };
390
+ /**
391
+ * The `RandomPassword` a site is served behind on `stage`, by its key —
392
+ * `SITE_PASSWORD` — or `undefined` where the stage asks for none.
393
+ *
394
+ * @throws {SitePasswordNotDeclared} where the password is not in the manifest
395
+ */
396
+ function sitePasswordKey(manifest, site, stage) {
397
+ const password = site.password;
398
+ if (!password?.stages.includes(stage)) return void 0;
399
+ const secret = manifest[password.secret];
400
+ const key = secret?.kind === "secret" ? secret.provides?.[0] : void 0;
401
+ if (!key) throw new SitePasswordNotDeclared(site.id, password.secret);
402
+ return key;
403
+ }
404
+ /**
405
+ * Before anything is deployed: every site behind a password names a deployed
406
+ * stage and a declared `RandomPassword`, and one of `apps` behind it on
407
+ * `stage` deploys through compose.
408
+ *
409
+ * @throws {UnknownPasswordStage}, {SitePasswordNotDeclared},
410
+ * {SitePasswordNeedsCompose}
411
+ */
412
+ function assertSitePasswords(workspace, manifest, stage, apps, target) {
413
+ for (const site of Object.values(manifest)) {
414
+ if (site.kind !== "site" || !site.password) continue;
415
+ for (const named of site.password.stages) if (!workspace.stages.deployed.includes(named)) throw new UnknownPasswordStage(site.id, named, workspace.stages.deployed);
416
+ if (sitePasswordKey(manifest, site, stage) && target !== "compose" && apps.includes(appKey(site.id))) throw new SitePasswordNeedsCompose(site.id, stage, target);
417
+ }
418
+ }
419
+ /**
420
+ * The login a site is served behind on `stage`, from the password kept under
421
+ * `key`.
422
+ *
423
+ * The hash's salt is derived from the password, so the same password always
424
+ * renders the same edge config: a deploy that changed nothing rewrites
425
+ * nothing, and the proxy is not reloaded for it. A per-hash random salt
426
+ * guards against a precomputed table of common passwords; a generated one is
427
+ * 43 random characters, which no table holds.
428
+ *
429
+ * @throws {SitePasswordMissing} where the stage's secrets hold none
430
+ */
431
+ function siteAuth(stage, key, custom) {
432
+ const password = custom[key];
433
+ if (!password) throw new SitePasswordMissing(stage, key);
434
+ return {
435
+ user: stage,
436
+ password,
437
+ hash: bcrypt.hashSync(password, saltFor(password)),
438
+ key
439
+ };
440
+ }
441
+ /** bcrypt's own base-64 alphabet, in which a salt is written. */
442
+ const BCRYPT_ALPHABET = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
443
+ /**
444
+ * A bcrypt salt — `$2a$`, which Caddy and Traefik both read, at cost 10 —
445
+ * derived from the password.
446
+ */
447
+ function saltFor(password) {
448
+ const digest = createHash("sha256").update(password).digest();
449
+ let salt = "";
450
+ for (let i = 0; i < 22; i++) salt += BCRYPT_ALPHABET[digest[i] % 64];
451
+ return `$2a$10$${salt}`;
452
+ }
453
+ //#endregion
454
+ //#region src/compose/traefik.ts
455
+ /**
456
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
457
+ * with, and what one stack registers with it.
458
+ *
459
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
460
+ * HTTPS. It is configured through its file provider alone: each stack writes
461
+ * one file — its routers, services and middlewares, every name prefixed with
462
+ * its compose project — into a directory the edge watches, and removes it
463
+ * when it stops. There is no Docker socket: the edge never learns what runs
464
+ * on the server except from those files.
465
+ *
466
+ * The edge and the stacks meet on one external Docker network. Only a
467
+ * stack's public services join it, each under an alias prefixed with its
468
+ * project (`<project>-api`), because the network is shared: a bare service
469
+ * name there would be answered by every stack's `api`.
470
+ *
471
+ * Pure but for the edge's name, read from the environment once (see
472
+ * {@link EDGE_PROJECT_ENV}): the documents are data, and the edge's side
473
+ * effects are `edge.ts`'s.
474
+ */
475
+ /**
476
+ * The image, pinned: the edge is every stack's way in, so a new version is a
477
+ * change to this line, not whatever `latest` is on the day a server starts.
478
+ */
479
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
480
+ /** The edge's compose project: `GKM_EDGE_PROJECT`, else `gkm-edge`. */
481
+ function edgeProject(env = process.env) {
482
+ return env["GKM_EDGE_PROJECT"] || "gkm-edge";
483
+ }
484
+ /**
485
+ * The edge's compose project, one per server — read once, when gkm starts,
486
+ * so every step of a run names the same edge.
487
+ */
488
+ const EDGE_PROJECT = edgeProject();
489
+ /**
490
+ * The external network the edge and every stack's public services share:
491
+ * named after the edge, so a renamed edge has a network of its own.
492
+ */
493
+ const EDGE_NETWORK = EDGE_PROJECT;
494
+ /** The edge's compose service. */
495
+ const EDGE_SERVICE = "traefik";
496
+ /** Inside the edge's container: what it watches, and where certificates are. */
497
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
498
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
499
+ /** The certificate resolver every deployed route without its own certificate uses. */
500
+ const ACME_RESOLVER = "letsencrypt";
501
+ /**
502
+ * The resolver a wildcard site's `*.<domain>` certificate comes from: Let's
503
+ * Encrypt issues a wildcard only over the DNS challenge, which the edge
504
+ * answers by writing an `_acme-challenge` TXT record through Route 53.
505
+ */
506
+ const ACME_DNS_RESOLVER = "letsencrypt-dns";
507
+ /**
508
+ * The key the edge writes those records with, inside its container: written
509
+ * by the deploy of a stage with a wildcard site, and allowed nothing but
510
+ * each such stage's `_acme-challenge` record (see `acmeDns.ts`).
511
+ */
512
+ const EDGE_AWS_CREDENTIALS = `${EDGE_CERTS_DIR}/aws-credentials`;
513
+ /** The internal entrypoint the edge's health check asks; never published. */
514
+ const PING_PORT = 8082;
515
+ /** A stack's service, as the edge — and the stack itself — reach it. */
516
+ function edgeAlias(project, service) {
517
+ return `${project}-${service}`;
518
+ }
519
+ /** A stack's certificate, as the edge's container reads it. */
520
+ function edgeCertificatePaths(project) {
521
+ return {
522
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
523
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
524
+ };
525
+ }
526
+ /**
527
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
528
+ * the directory it watches. No API and no dashboard — nothing about the edge
529
+ * is reachable but the routes stacks register.
530
+ */
531
+ function traefikStatic(ports) {
532
+ return {
533
+ global: {
534
+ checkNewVersion: false,
535
+ sendAnonymousUsage: false
536
+ },
537
+ entryPoints: {
538
+ web: {
539
+ address: ":80",
540
+ http: { redirections: { entryPoint: {
541
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
542
+ scheme: "https",
543
+ permanent: true
544
+ } } }
545
+ },
546
+ websecure: { address: ":443" },
547
+ ping: { address: `:${PING_PORT}` }
548
+ },
549
+ ping: { entryPoint: "ping" },
550
+ providers: { file: {
551
+ directory: EDGE_DYNAMIC_DIR,
552
+ watch: true
553
+ } },
554
+ certificatesResolvers: {
555
+ [ACME_RESOLVER]: { acme: {
556
+ storage: "/acme/acme.json",
557
+ httpChallenge: { entryPoint: "web" }
558
+ } },
559
+ [ACME_DNS_RESOLVER]: { acme: {
560
+ storage: "/acme/acme-dns.json",
561
+ dnsChallenge: {
562
+ provider: "route53",
563
+ resolvers: ["1.1.1.1:53", "8.8.8.8:53"]
564
+ }
565
+ } }
566
+ },
567
+ log: { level: "INFO" }
568
+ };
569
+ }
570
+ /** The edge's compose document. */
571
+ function edgeCompose(options) {
572
+ const { ports } = options;
573
+ return {
574
+ name: EDGE_PROJECT,
575
+ services: { [EDGE_SERVICE]: {
576
+ image: TRAEFIK_IMAGE,
577
+ restart: "unless-stopped",
578
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
579
+ configs: [{
580
+ source: "traefik",
581
+ target: "/etc/traefik/traefik.yml"
582
+ }],
583
+ volumes: [
584
+ `dynamic:${EDGE_DYNAMIC_DIR}`,
585
+ `certs:${EDGE_CERTS_DIR}`,
586
+ "acme:/acme"
587
+ ],
588
+ labels: { "dev.geekmidas.edge.config": createHash("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
589
+ environment: {
590
+ AWS_SHARED_CREDENTIALS_FILE: EDGE_AWS_CREDENTIALS,
591
+ AWS_REGION: "us-east-1"
592
+ },
593
+ networks: ["edge"],
594
+ ...EDGE_LIMITS,
595
+ healthcheck: {
596
+ test: [
597
+ "CMD",
598
+ "traefik",
599
+ "healthcheck",
600
+ "--ping"
601
+ ],
602
+ interval: "10s",
603
+ timeout: "5s",
604
+ retries: 5
605
+ },
606
+ logging: options.logging
607
+ } },
608
+ configs: { traefik: { content: options.staticConfig } },
609
+ volumes: {
610
+ acme: {},
611
+ dynamic: {},
612
+ certs: {}
613
+ },
614
+ networks: { edge: {
615
+ name: EDGE_NETWORK,
616
+ external: true
617
+ } }
618
+ };
619
+ }
620
+ /** A stack's dynamic configuration, as an object. */
621
+ function traefikDynamic(routes, options) {
622
+ const { project, tls, edgeToken } = options;
623
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
624
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
625
+ const routers = {};
626
+ const services = {};
627
+ const middlewares = {};
628
+ const strip = `${project}-strip-gkm-headers`;
629
+ if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [CLIENT_IP_HEADER]: "" } } };
630
+ for (const route of routes) {
631
+ const chain = [strip];
632
+ if (route.allow) {
633
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
634
+ chain.push(name(route, "allow"));
635
+ }
636
+ if (route.auth) {
637
+ middlewares[name(route, "auth")] = { basicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] } };
638
+ chain.push(name(route, "auth"));
639
+ }
640
+ if (route.prefix) {
641
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
642
+ chain.push(name(route, "prefix"));
643
+ }
644
+ assertRouteRenderable(route);
645
+ const allowed = [...(route.paths ?? []).map((path) => `Path(\`${path}\`)`), ...(route.prefixes ?? []).map((prefix) => `PathPrefix(\`${prefix}\`)`)];
646
+ const paths = allowed.length ? ` && (${allowed.join(" || ")})` : "";
647
+ const header = route.requireHeader ? ` && Header(\`${route.requireHeader.name}\`, \`${route.requireHeader.value}\`)` : "";
648
+ const certificate = () => route.wildcard?.tls.kind === "dns" ? {
649
+ certResolver: ACME_DNS_RESOLVER,
650
+ domains: [{ main: `*.${route.wildcard.domain}` }]
651
+ } : tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {};
652
+ for (const handler of route.handlers ?? []) {
653
+ const handlerName = name(route, handler.name);
654
+ routers[handlerName] = {
655
+ rule: `Host(\`${route.host}\`) && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
656
+ priority: 1e4,
657
+ entryPoints: ["websecure"],
658
+ service: handlerName,
659
+ middlewares: [strip],
660
+ tls: certificate()
661
+ };
662
+ services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
663
+ }
664
+ const rule = `${hostRule(route)}${paths}${header}`;
665
+ routers[name(route)] = {
666
+ rule,
667
+ ...route.wildcard ? { priority: 1 } : {},
668
+ entryPoints: ["websecure"],
669
+ service: name(route),
670
+ middlewares: chain,
671
+ tls: certificate()
672
+ };
673
+ if (edgeToken && !route.prefix) routers[name(route, "stack")] = {
674
+ rule: `${rule} && Header(\`${EDGE_TOKEN_HEADER}\`, \`${edgeToken}\`)`,
675
+ ...route.wildcard ? { priority: 2 } : {},
676
+ entryPoints: ["websecure"],
677
+ service: name(route),
678
+ ...chain.length > 1 ? { middlewares: chain.slice(1) } : {},
679
+ tls: certificate()
680
+ };
681
+ services[name(route)] = { loadBalancer: {
682
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
683
+ ...route.prefix ? { passHostHeader: false } : {},
684
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
685
+ ...route.health ? { healthCheck: {
686
+ path: route.health,
687
+ interval: "5s",
688
+ timeout: "3s"
689
+ } } : {}
690
+ } };
691
+ }
692
+ return {
693
+ http: {
694
+ routers,
695
+ services,
696
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
697
+ },
698
+ ...tls.kind === "files" ? { tls: { certificates: [{
699
+ certFile: tls.certFile,
700
+ keyFile: tls.keyFile
701
+ }] } } : {}
702
+ };
703
+ }
704
+ /**
705
+ * The hosts a route answers, as a Traefik rule: its own, or — for a wildcard
706
+ * site — exactly one label under its domain, but the ones it never takes.
707
+ * One label, as a wildcard certificate covers: a stage at
708
+ * `staging.example.com` is never reached through `example.com`'s wildcard.
709
+ */
710
+ function hostRule(route) {
711
+ if (!route.wildcard) return `Host(\`${route.host}\`)`;
712
+ const { domain, except } = route.wildcard;
713
+ return [`HostRegexp(\`${`^[a-z0-9-]+\\.${domain.replace(/\./g, "\\.")}$`}\`)`, ...except.map((label) => `!Host(\`${label}.${domain}\`)`)].join(" && ");
714
+ }
715
+ /** What a stack's routes claim on the edge, from the route model. */
716
+ function edgeClaims(routes) {
717
+ return routes.map((route) => route.wildcard ? {
718
+ wildcard: route.wildcard.domain.toLowerCase(),
719
+ except: [...route.wildcard.except]
720
+ } : { host: route.host.toLowerCase() });
721
+ }
722
+ /**
723
+ * The comment line a stack's file carries its claims on: a comment, because
724
+ * Traefik's file provider refuses a whole file over a key it does not know,
725
+ * and gkm reads it back rather than taking the routers' rules apart.
726
+ */
727
+ const CLAIMS_PREFIX = "# gkm-claims: ";
728
+ /**
729
+ * The hosts a stack's file on the edge claims: from its claims line, or — a
730
+ * file written before gkm wrote one — from its routers' rules, in the shapes
731
+ * `traefikDynamic` renders them.
732
+ */
733
+ function readEdgeClaims(file) {
734
+ for (const line of file.split("\n")) {
735
+ if (!line.startsWith(CLAIMS_PREFIX)) continue;
736
+ try {
737
+ const claims = JSON.parse(line.slice(14));
738
+ if (Array.isArray(claims)) return claims.filter(isClaim);
739
+ } catch {}
740
+ }
741
+ let document;
742
+ try {
743
+ document = parse$1(file);
744
+ } catch {
745
+ return [];
746
+ }
747
+ const routers = document?.http?.routers;
748
+ if (!routers || typeof routers !== "object") return [];
749
+ const claims = [];
750
+ for (const router of Object.values(routers)) {
751
+ const rule = router?.rule;
752
+ if (typeof rule === "string") claims.push(...ruleClaims(rule));
753
+ }
754
+ return claims;
755
+ }
756
+ function isClaim(value) {
757
+ if (!value || typeof value !== "object") return false;
758
+ const claim = value;
759
+ return typeof claim.host === "string" || typeof claim.wildcard === "string" && Array.isArray(claim.except);
760
+ }
761
+ /**
762
+ * The hosts a rule matches: each `Host(\`a\`)` not negated, and a
763
+ * `HostRegexp` of a wildcard site — one label under a domain — with the
764
+ * `!Host` labels it leaves out.
765
+ */
766
+ function ruleClaims(rule) {
767
+ const negated = [...rule.matchAll(/!\s*Host\(`([^`]+)`\)/g)].map((match) => match[1].toLowerCase());
768
+ const wildcard = /HostRegexp\(`\^\[a-z0-9-\]\+\\\.(.+)\$`\)/.exec(rule);
769
+ if (wildcard) {
770
+ const domain = wildcard[1].replace(/\\\./g, ".").toLowerCase();
771
+ const suffix = `.${domain}`;
772
+ return [{
773
+ wildcard: domain,
774
+ except: negated.filter((host) => host.endsWith(suffix)).map((host) => host.slice(0, -suffix.length))
775
+ }];
776
+ }
777
+ return [...rule.matchAll(/(?<![!\w])Host\(`([^`]+)`\)/g)].map((match) => ({ host: match[1].toLowerCase() }));
778
+ }
779
+ /**
780
+ * Where two claims meet, as a host to name — or undefined where they never
781
+ * do. A wildcard takes one label under its domain, so it meets a name one
782
+ * label under it that it does not leave out, and another wildcard on the
783
+ * same domain.
784
+ */
785
+ function claimsOverlap(a, b) {
786
+ if ("host" in a && "host" in b) return a.host === b.host ? a.host : void 0;
787
+ if ("wildcard" in a && "wildcard" in b) return a.wildcard === b.wildcard ? `*.${a.wildcard}` : void 0;
788
+ const [name, wildcard] = "host" in a ? [a, b] : [b, a];
789
+ const suffix = `.${wildcard.wildcard}`;
790
+ if (!name.host.endsWith(suffix)) return void 0;
791
+ const label = name.host.slice(0, -suffix.length);
792
+ if (!/^[a-z0-9-]+$/.test(label) || wildcard.except.includes(label)) return;
793
+ return name.host;
794
+ }
795
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
796
+ function traefikDynamicFile(routes, options) {
797
+ return `# Generated by gkm compose for ${options.project} — do not edit.
798
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
799
+ # one is removed by gkm compose --down. The hosts it routes, which no other
800
+ # stack on the edge may route:
801
+ ${CLAIMS_PREFIX}${JSON.stringify(edgeClaims(routes))}
802
+ ${yaml(traefikDynamic(routes, options))}`;
803
+ }
804
+ /** The edge's static configuration file. */
805
+ function traefikStaticFile(ports) {
806
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
807
+ ${yaml(traefikStatic(ports))}`;
808
+ }
809
+ /** The edge's compose file. */
810
+ function edgeComposeFile(options) {
811
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
812
+ #
813
+ # Started by the first stack that runs with proxy: 'traefik', and left
814
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
815
+ #
816
+ # docker compose -p ${EDGE_PROJECT} down
817
+ ${yaml(edgeCompose(options))}`;
818
+ }
819
+ function yaml(value) {
820
+ return stringify(value, {
821
+ lineWidth: 0,
822
+ aliasDuplicateObjects: false
823
+ });
824
+ }
825
+ //#endregion
826
+ //#region src/compose/stack.ts
827
+ /**
828
+ * The stack a workspace runs as for one stage — pure.
829
+ *
830
+ * Everything `gkm compose` writes is decided here, as data: the compose file,
831
+ * the Caddyfile, one env file per process that reads one — each backend,
832
+ * worker and site that runs a server — and the image each app runs. The
833
+ * command around it reads the workspace, asks the registry, writes the files
834
+ * and starts Docker; none of those decide anything, so all of it can be
835
+ * asserted without a daemon.
836
+ *
837
+ * The values come from the same derivations every other target uses. The
838
+ * plan is reconcile's `planFor`, the keys a process reads are
839
+ * `processEnvKeys` — the rule `gkm dev` and `gkm exec` apply — and every URL
840
+ * is `envFor`'s, with each app at its public address: a browser and a sibling
841
+ * service reach an API by the same name, through the edge.
842
+ */
843
+ /** Where a stack's files are written, relative to the workspace root. */
844
+ function stackDir(stage) {
845
+ return `.gkm/compose/${stage}`;
846
+ }
847
+ /**
848
+ * The compose project a stage's stack runs as.
849
+ *
850
+ * The deploy identity's scope, so two workspaces with one name in different
851
+ * namespaces never share containers or volumes — and the stage, so a
852
+ * machine can run two stages side by side.
853
+ */
854
+ function composeProject(identity) {
855
+ return `${identity.scope}-${identity.stage}`;
856
+ }
857
+ /** The ports the edge is published on, and the variables that move them. */
858
+ const EDGE_PORT_ENV = {
859
+ https: "GKM_COMPOSE_HTTPS_PORT",
860
+ http: "GKM_COMPOSE_HTTP_PORT"
861
+ };
862
+ /**
863
+ * The variable that moves the local stage's OpenObserve off its loopback
864
+ * port, 5080 — which the local stage takes from nowhere else, since it
865
+ * ignores `deploy.telemetry`. Another stack, or another tool, may hold 5080.
866
+ */
867
+ const LOGS_PORT_ENV = "GKM_COMPOSE_LOGS_PORT";
868
+ /**
869
+ * Containers this target does not run.
870
+ *
871
+ * The AWS emulator never applies: a stack is a server target, whose events
872
+ * are pg-boss. Reconcile's Caddy fronts `gkm dev`'s host processes; the stack
873
+ * brings its own edge.
874
+ *
875
+ * MinIO and Mailpit run on the local stage always, and on a deployed stage
876
+ * only where `--allow-dev-services` allowed them and its secrets configure no
877
+ * real bucket or mail server — see `devServices.ts`.
878
+ */
879
+ const NOT_RUN = {
880
+ localstack: true,
881
+ caddy: true
882
+ };
883
+ /** The kinds a deployed stage takes from its secrets, or a dev service. */
884
+ const SERVICE_KINDS = {
885
+ email: "email",
886
+ objects: "objects",
887
+ "file-server": "file-server"
888
+ };
889
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
890
+ const MINIO_REGION = "us-east-1";
891
+ /** The S3 client's credentials, read beside a bucket's URL when it has them. */
892
+ const STORAGE_KEYS = [
893
+ "AWS_ACCESS_KEY_ID",
894
+ "AWS_SECRET_ACCESS_KEY",
895
+ "AWS_REGION"
896
+ ];
897
+ /**
898
+ * Every service's Docker logs, rotated. The json-file driver keeps a
899
+ * container's output in one file that grows until the disk is full — on a
900
+ * small server, in weeks. Three files of 10 MB each per container is enough
901
+ * to see what happened and never fills anything. A project's own override
902
+ * file that sets `logging` wins over it.
903
+ */
904
+ const LOG_ROTATION = {
905
+ driver: "json-file",
906
+ options: {
907
+ "max-size": "10m",
908
+ "max-file": "3"
909
+ }
910
+ };
911
+ /** A CDN serves the bucket, and the secret it sends the processors is not in the stage. */
912
+ var ProcessorOriginSecretMissing = class extends GkmError {
913
+ fileServer;
914
+ key;
915
+ stage;
916
+ constructor(fileServer, key, stage) {
917
+ super(`'${fileServer}' has processors, and its bucket is not the stack's MinIO, so they are reached through the CDN in front of it — which sends ${key}, and stage '${stage}' has none. It is written by the deploy that creates the CDN (\`deploy.objects.${stage}\` on s3, cdn on): run gkm deploy --stage ${stage}.`);
918
+ this.fileServer = fileServer;
919
+ this.key = key;
920
+ this.stage = stage;
921
+ this.name = "ProcessorOriginSecretMissing";
922
+ }
923
+ };
924
+ /**
925
+ * The stack with Caddy's files inline: its Caddyfile and, where the stage has
926
+ * one, its own certificate — `configs` with their `content`, which compose
927
+ * copies into the container through the engine's API. Nothing is mounted from
928
+ * a path, so the stack runs the same on a server's engine, over SSH, as on
929
+ * this machine's. Their hash is a label: a changed file is a changed service,
930
+ * which `up` recreates (compose does not, for a config's content alone).
931
+ */
932
+ function withCaddyConfigs(compose, files) {
933
+ const caddy = compose.services.caddy;
934
+ if (!caddy) return compose;
935
+ const configs = {
936
+ caddyfile: { content: files.caddyfile },
937
+ ...files.tls ? {
938
+ "tls-cert": { content: files.tls.cert },
939
+ "tls-key": { content: files.tls.key }
940
+ } : {}
941
+ };
942
+ const hash = createHash("sha256");
943
+ for (const [name, { content }] of Object.entries(configs)) hash.update(`${name}\0${content}\0`);
944
+ return {
945
+ ...compose,
946
+ services: {
947
+ ...compose.services,
948
+ caddy: {
949
+ ...caddy,
950
+ configs: [{
951
+ source: "caddyfile",
952
+ target: "/etc/caddy/Caddyfile"
953
+ }, ...files.tls ? [{
954
+ source: "tls-cert",
955
+ target: `${CADDY_TLS_DIR}/cert.pem`
956
+ }, {
957
+ source: "tls-key",
958
+ target: `${CADDY_TLS_DIR}/key.pem`,
959
+ mode: 256
960
+ }] : []],
961
+ labels: {
962
+ ...caddy.labels,
963
+ "dev.geekmidas.caddy.config": hash.digest("hex").slice(0, 16)
964
+ }
965
+ }
966
+ },
967
+ configs: {
968
+ ...compose.configs,
969
+ ...configs
970
+ }
971
+ };
972
+ }
973
+ /** The label the local stage's Mailpit inbox answers on. */
974
+ const MAIL_INBOX_LABEL = "mail";
975
+ /** Mailpit's web UI and API, inside the stack's network. */
976
+ const MAILPIT_WEB_PORT = 8025;
977
+ /** An app of the local stage on the host its Mailpit inbox is served at. */
978
+ var MailInboxHostTaken = class extends GkmError {
979
+ host;
980
+ app;
981
+ constructor(host, app) {
982
+ super(`'${app}' answers on ${host}, which the local stage serves its Mailpit inbox at. Give '${app}' another subdomain — '${MAIL_INBOX_LABEL}' is reserved for the inbox on the local stage.`);
983
+ this.host = host;
984
+ this.app = app;
985
+ this.name = "MailInboxHostTaken";
986
+ }
987
+ };
988
+ /**
989
+ * The services a stack publishes on its engine's loopback, and the port each
990
+ * answers on inside — what gkm reaches from this machine to provision the
991
+ * stack and run its migrations and seeds. Everything else is reached only on
992
+ * the stack's network.
993
+ */
994
+ const LOOPBACK_SERVICES = {
995
+ postgres: 5432,
996
+ minio: 9e3
997
+ };
998
+ /** The local stage's stack, without the logins `gkm dev` generates. */
999
+ var LocalCredentialsMissing = class extends GkmError {
1000
+ stage;
1001
+ constructor(stage) {
1002
+ super(`The local stage '${stage}' runs with this machine's generated logins, and none were passed. Load them with loadLocalCredentials(workspace) and pass them as localCredentials.`);
1003
+ this.stage = stage;
1004
+ this.name = "LocalCredentialsMissing";
1005
+ }
1006
+ };
1007
+ /**
1008
+ * A deployed stage's container logins, derived from its seed like its role
1009
+ * passwords — so every deploy of the stage computes the same ones, and no one
1010
+ * reading the repo can.
1011
+ */
1012
+ function derivedCredentials(project, plan, seed) {
1013
+ const derive = (purpose) => localRolePassword(project, plan, purpose, seed);
1014
+ return {
1015
+ postgres: {
1016
+ user: postgresSuperuser(project),
1017
+ password: derive("master")
1018
+ },
1019
+ minio: {
1020
+ user: `${project}-minio`,
1021
+ password: derive("minio")
1022
+ },
1023
+ rabbitmq: {
1024
+ user: LOCAL_RABBITMQ_USER,
1025
+ password: derive("rabbitmq")
1026
+ },
1027
+ redis: { password: derive("redis") },
1028
+ cacheToken: derive("cache-token"),
1029
+ emulator: {
1030
+ accessKeyId: EMULATOR_ACCESS_KEY_ID,
1031
+ secretAccessKey: derive("emulator")
1032
+ },
1033
+ logs: {
1034
+ email: `admin@${project}`,
1035
+ password: derive("logs")
1036
+ }
1037
+ };
1038
+ }
1039
+ /** A value only the stage's secrets can hold, and they do not. */
1040
+ var StageSecretMissing = class extends GkmError {
1041
+ app;
1042
+ key;
1043
+ stage;
1044
+ constructor(app, key, stage) {
1045
+ super(`'${app}' reads ${key}, and the stage '${stage}' has none. Nothing in the stack can derive it; set it in the stage's secrets: gkm secrets:set ${key} '…' --stage ${stage}`);
1046
+ this.app = app;
1047
+ this.key = key;
1048
+ this.stage = stage;
1049
+ this.name = "StageSecretMissing";
1050
+ }
1051
+ };
1052
+ /**
1053
+ * One key of a deployed inbox — the one rule every target reads it by.
1054
+ *
1055
+ * Its domain is the stage's, which mail is addressed to. Everything else (where
1056
+ * its raw messages are read, its topic's publisher string) is what its
1057
+ * provider made and wrote to the stage's secrets; nothing can derive it.
1058
+ *
1059
+ * @throws {NoDomainForStage} for its domain when the stage has none.
1060
+ * @throws {StageSecretMissing} when the provider has not written the key.
1061
+ */
1062
+ function deployedInboxValue(inbox, key, sources) {
1063
+ if (key === provideKey(inbox, "domain")) {
1064
+ if (!sources.domain) throw new NoDomainForStage(sources.stage);
1065
+ return sources.domain;
1066
+ }
1067
+ const value = sources.secrets[key];
1068
+ if (value === void 0) throw new StageSecretMissing(sources.reader, key, sources.stage);
1069
+ return value;
1070
+ }
1071
+ /**
1072
+ * Every deployed inbox's keys, and its topic's publisher string, by key: what
1073
+ * a target that provisions nothing of the inbox's (SST) is handed, read by
1074
+ * {@link deployedInboxValue} as the compose stack reads each.
1075
+ */
1076
+ function deployedInboxEnv(manifest, sources) {
1077
+ const env = {};
1078
+ for (const declaration of Object.values(manifest)) {
1079
+ if (declaration.kind !== "inbox") continue;
1080
+ const keys = [...declaration.provides ?? [], provideKey(declaration.topic, "publisherConnectionString")];
1081
+ for (const key of keys) env[key] = deployedInboxValue(declaration.id, key, sources);
1082
+ }
1083
+ return env;
1084
+ }
1085
+ /** A deployed stage's secrets with no seed to derive its passwords from. */
1086
+ var StageSeedMissing = class extends GkmError {
1087
+ stage;
1088
+ constructor(stage) {
1089
+ super(`The stage '${stage}' has no seed in its secrets, and a deployed stage's database passwords are derived from it. Run gkm compose --stage ${stage} without --dry-run once, or gkm deploy, to generate it.`);
1090
+ this.stage = stage;
1091
+ this.name = "StageSeedMissing";
1092
+ }
1093
+ };
1094
+ /** A workspace with no API and no site to run. */
1095
+ var NothingToCompose = class extends GkmError {
1096
+ root;
1097
+ constructor(root) {
1098
+ super(`${root} declares no RestApi, no site and no Worker with work to do, so a stack would run nothing. Mobile apps ship through their own toolchain.`);
1099
+ this.root = root;
1100
+ this.name = "NothingToCompose";
1101
+ }
1102
+ };
1103
+ /** A value that cannot be written to an env file a line at a time. */
1104
+ var EnvValueMultiline = class extends GkmError {
1105
+ app;
1106
+ key;
1107
+ constructor(app, key) {
1108
+ super(`${key} for '${app}' spans more than one line, and an env file holds one value per line. Store it on one line — base64, or JSON — and decode it where it is read.`);
1109
+ this.app = app;
1110
+ this.key = key;
1111
+ this.name = "EnvValueMultiline";
1112
+ }
1113
+ };
1114
+ /** The services a stack's apps wait on. */
1115
+ const HEALTHY = { condition: "service_healthy" };
1116
+ /**
1117
+ * What Caddy waits on of each app: that it started, never that it is
1118
+ * healthy. Its routes are served whatever an app's health — Caddy's own
1119
+ * upstream health checks take one out of rotation — so one app that never
1120
+ * turns healthy leaves the others routed, and a site whose health check goes
1121
+ * through the edge can turn healthy at all.
1122
+ */
1123
+ const STARTED = { condition: "service_started" };
1124
+ /**
1125
+ * An app's health check: its own server, asked on 127.0.0.1 — not
1126
+ * `localhost`, which resolves to `::1` first in an Alpine container while a
1127
+ * server may listen on IPv4 alone.
1128
+ */
1129
+ function probe(port, path) {
1130
+ return {
1131
+ test: [
1132
+ "CMD",
1133
+ "wget",
1134
+ "-q",
1135
+ "-O",
1136
+ "/dev/null",
1137
+ `http://127.0.0.1:${port}${path}`
1138
+ ],
1139
+ interval: "5s",
1140
+ timeout: "3s",
1141
+ retries: 20,
1142
+ start_period: "10s"
1143
+ };
1144
+ }
1145
+ /**
1146
+ * What a stage's stack provisions: reconcile's plan, with a server target's
1147
+ * backends whatever `deploy.default` says — the stack is one machine running
1148
+ * containers, so events are pg-boss beside the declared database, and every
1149
+ * cache, one declared from that database included, is in the stack's own
1150
+ * Redis.
1151
+ */
1152
+ function stackPlan(workspace, manifest, stage) {
1153
+ const protectedSubdomains = [...workspace.protectedSubdomains ?? [], ...nestedStageLabels(workspace.domains, stage)];
1154
+ return planFor(manifest, stage, provisionOrder(manifest), {
1155
+ localStage: workspace.stages.local,
1156
+ ...protectedSubdomains.length > 0 ? { protectedSubdomains } : {},
1157
+ events: DEFAULT_EVENTS.server,
1158
+ cache: STACK_CACHE,
1159
+ edge: false
1160
+ });
1161
+ }
1162
+ /** The stack for one stage. */
1163
+ function composeStack(input) {
1164
+ const { workspace, manifest, stage, identity } = input;
1165
+ const local = stage === workspace.stages.local;
1166
+ const project = composeProject(identity);
1167
+ const custom = input.secrets?.custom ?? {};
1168
+ const https = input.ports?.https ?? 443;
1169
+ const http = input.ports?.http ?? 80;
1170
+ const proxy = proxyFor(workspace.deploy?.compose, stage, local);
1171
+ const certificate = certificateFor(workspace.deploy?.compose, stage, workspace.root);
1172
+ const plan = stackPlan(workspace, manifest, stage);
1173
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1174
+ if (local && !input.localCredentials) throw new LocalCredentialsMissing(stage);
1175
+ const seed = local ? input.localCredentials.seed : input.secrets?.seed;
1176
+ if (!seed) throw new StageSeedMissing(stage);
1177
+ const containers = local ? input.localCredentials : derivedCredentials(workspace.name, plan, seed);
1178
+ const credential = {
1179
+ containers: {
1180
+ ...containers,
1181
+ minio: {
1182
+ user: custom.AWS_ACCESS_KEY_ID ?? containers.minio.user,
1183
+ password: custom.AWS_SECRET_ACCESS_KEY ?? containers.minio.password
1184
+ }
1185
+ },
1186
+ seed
1187
+ };
1188
+ const apps = stackApps(workspace, manifest, plan, {
1189
+ local,
1190
+ stage,
1191
+ https,
1192
+ identity,
1193
+ images: input.images
1194
+ });
1195
+ const workers = stackWorkers(workerUnits(workspace, manifest, input.background ?? {}), {
1196
+ stage,
1197
+ identity,
1198
+ images: input.images
1199
+ });
1200
+ const processors = stackProcessors(processorUnits(workspace, manifest), {
1201
+ manifest,
1202
+ stage,
1203
+ identity,
1204
+ images: input.images
1205
+ });
1206
+ if (apps.length === 0 && workers.length === 0 && processors.length === 0) throw new NothingToCompose(workspace.root);
1207
+ const owners = /* @__PURE__ */ new Map();
1208
+ for (const resource of plan.resources) {
1209
+ owners.set(resource.envKey, resource);
1210
+ if (resource.kind === "email") {
1211
+ owners.set(provideKey(resource.id, "from"), resource);
1212
+ owners.set(provideKey(resource.id, "inboxUrl"), resource);
1213
+ }
1214
+ if (resource.kind === "external-api") owners.set(provideKey(resource.id, "credentials"), resource);
1215
+ if (resource.kind === "inbox") owners.set(provideKey(resource.id, "domain"), resource);
1216
+ if (resource.kind === "websocket-api") owners.set(provideKey(resource.id, "publisherConnectionString"), resource);
1217
+ }
1218
+ const domain = workspace.domains?.[stage];
1219
+ const telemetry = resolveStageTelemetry({
1220
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1221
+ stage,
1222
+ local,
1223
+ target: "compose",
1224
+ runtime: "server",
1225
+ selfHosted: true,
1226
+ used: usesTelemetry(manifest)
1227
+ });
1228
+ const logsBase = telemetry?.provider === "self-hosted" ? stackLogs({
1229
+ config: local && input.ports?.logs ? {
1230
+ ...telemetry.selfHosted,
1231
+ port: input.ports.logs
1232
+ } : telemetry.selfHosted,
1233
+ stage,
1234
+ local,
1235
+ project: workspace.name,
1236
+ ...domain ? { domain } : {},
1237
+ custom,
1238
+ https,
1239
+ ...local ? { localLogin: input.localCredentials.logs } : {}
1240
+ }) : void 0;
1241
+ const services = local ? {
1242
+ missing: [],
1243
+ minio: plan.resources.filter((r) => r.kind === "objects").map((r) => r.id),
1244
+ mailpit: plan.resources.filter((r) => r.kind === "email" || r.kind === "inbox").map((r) => r.id)
1245
+ } : externalServices({
1246
+ stage,
1247
+ declarations: stageServiceDeclarations({ manifest }),
1248
+ supplied: custom,
1249
+ allow: input.allowDevServices === true,
1250
+ ...domain ? { domain } : {},
1251
+ providers: stageProviderNotes(workspace, stage)
1252
+ });
1253
+ const redis = stackRedis({
1254
+ plan,
1255
+ stage,
1256
+ local,
1257
+ custom,
1258
+ ...local ? { localPassword: input.localCredentials.redis.password } : {}
1259
+ });
1260
+ const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== LOGS_SERVICE).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logsBase ? [LOGS_SERVICE] : []].sort();
1261
+ const mailInbox = local && infra.includes("mailpit") ? (() => {
1262
+ const host = [
1263
+ MAIL_INBOX_LABEL,
1264
+ workspace.name,
1265
+ LOCAL_TLD
1266
+ ].filter(Boolean).join(".");
1267
+ return {
1268
+ host,
1269
+ url: `https://${host}${https !== 443 ? `:${https}` : ""}`
1270
+ };
1271
+ })() : void 0;
1272
+ const storage = infra.includes("minio") ? (() => {
1273
+ const buckets = services.minio.map((id) => byId.get(id)?.name).filter((name) => Boolean(name)).sort();
1274
+ return {
1275
+ ...credential.containers.minio,
1276
+ buckets,
1277
+ policies: bucketPolicies(plan).filter((p) => buckets.includes(p.bucket)),
1278
+ objects: services.minio.map((id) => ({
1279
+ id,
1280
+ name: byId.get(id)?.name
1281
+ })).filter((b) => Boolean(b.name)).sort((a, b) => a.name.localeCompare(b.name)),
1282
+ webhooks: [],
1283
+ lifecycles: bucketLifecycles(plan).filter((l) => buckets.includes(l.bucket))
1284
+ };
1285
+ })() : void 0;
1286
+ const bucketEventKeys = /* @__PURE__ */ new Map();
1287
+ for (const resource of plan.resources) {
1288
+ if (resource.kind !== "objects") continue;
1289
+ bucketEventKeys.set(provideKey(resource.id, "eventsConnectionString"), resource.id);
1290
+ bucketEventKeys.set(provideKey(resource.id, "eventsToken"), resource.id);
1291
+ }
1292
+ const fileServers = /* @__PURE__ */ new Map();
1293
+ if (storage) for (const resource of plan.resources) {
1294
+ if (resource.kind !== "file-server" || !resource.of) continue;
1295
+ if (!services.minio.includes(resource.of)) continue;
1296
+ if (custom[resource.envKey] !== void 0) continue;
1297
+ const bucket = byId.get(resource.of);
1298
+ if (!bucket) continue;
1299
+ let host;
1300
+ if (local) host = hostFor(resource, workspace.name);
1301
+ else {
1302
+ if (!domain) throw new NoDomainForStage(stage);
1303
+ host = `${resource.subdomain ?? appKey(resource.id)}.${domain}`;
1304
+ }
1305
+ fileServers.set(resource.id, {
1306
+ url: `https://${host}${local && https !== 443 ? `:${https}` : ""}`,
1307
+ route: {
1308
+ name: `files-${appKey(resource.id)}`,
1309
+ host,
1310
+ upstreams: [{
1311
+ service: "minio",
1312
+ port: 9e3
1313
+ }],
1314
+ streaming: false,
1315
+ prefix: `/${bucket.name}`
1316
+ }
1317
+ });
1318
+ }
1319
+ const edgeServices = new Set(proxy === "traefik" ? [
1320
+ ...apps.flatMap(replicaNames),
1321
+ ...fileServers.size > 0 ? ["minio"] : [],
1322
+ ...logsBase?.host && logsBase.public ? [LOGS_SERVICE] : [],
1323
+ ...mailInbox ? ["mailpit"] : []
1324
+ ] : []);
1325
+ const hostOf = (service) => edgeServices.has(service) ? edgeAlias(project, service) : service;
1326
+ const logs = logsBase && {
1327
+ ...logsBase,
1328
+ appEnv: {
1329
+ ...logsBase.appEnv,
1330
+ OTEL_EXPORTER_OTLP_ENDPOINT: logsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(`//openobserve:`, `//${hostOf("openobserve")}:`)
1331
+ }
1332
+ };
1333
+ const derivation = {
1334
+ project: workspace.name,
1335
+ credentials: credential.containers,
1336
+ seed: credential.seed,
1337
+ ...!local && domain ? { mailFrom: `noreply@${domain}` } : {},
1338
+ relayedBuckets: [...watchedBuckets(manifest, input.subscribers ?? {}).keys()].filter((bucket) => services.minio.includes(bucket))
1339
+ };
1340
+ const publicAddresses = Object.fromEntries(apps.map((app) => [app.id, app.url]));
1341
+ const outside = networkEnv(plan, {
1342
+ ...derivation,
1343
+ addresses: publicAddresses
1344
+ }, hostOf);
1345
+ /**
1346
+ * What a key resolves to for one app, from the stage's secrets where only
1347
+ * they can hold it, and the derivations otherwise.
1348
+ */
1349
+ const valueFor = (app, key, owner) => {
1350
+ if (isReservedStageKey(key)) return void 0;
1351
+ const watching = bucketEventKeys.get(key);
1352
+ if (watching) {
1353
+ if (custom[key] !== void 0) return custom[key];
1354
+ return services.minio.includes(watching) ? outside[key] : void 0;
1355
+ }
1356
+ if (owner?.kind === "inbox") {
1357
+ if (local) return outside[key];
1358
+ return deployedInboxValue(owner.id, key, {
1359
+ reader: app.name,
1360
+ stage,
1361
+ domain,
1362
+ secrets: custom
1363
+ });
1364
+ }
1365
+ if (!local && owner?.kind === "email" && key.endsWith("_INBOX_URL")) return;
1366
+ if (owner && SERVICE_KINDS[owner.kind]) {
1367
+ if (custom[key] !== void 0) return custom[key];
1368
+ if (owner.kind === "file-server") return fileServers.get(owner.id)?.url;
1369
+ return outside[key];
1370
+ }
1371
+ if (owner && suppliedOnly(owner.kind, owner.id, key, local)) {
1372
+ const value = custom[key];
1373
+ if (value === void 0) throw new StageSecretMissing(app.name, key, stage);
1374
+ return value;
1375
+ }
1376
+ if (custom[key] !== void 0) return custom[key];
1377
+ if (owner?.kind === "cache") return redis?.urls[key];
1378
+ if (owner?.kind === "websocket-api" && key === provideKey(owner.id, "publisherConnectionString")) return redis?.urls[key];
1379
+ return outside[key];
1380
+ };
1381
+ const telemetryValues = logs ? telemetryEnv({
1382
+ endpoint: logs.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT,
1383
+ headers: logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS
1384
+ }, telemetry?.sampleRate ?? 1) : telemetry?.provider === "otlp" ? otlpTelemetryEnv(telemetry) : void 0;
1385
+ /** Each key one backend process reads, resolved for this stage. */
1386
+ const valuesFor = (app, keys) => {
1387
+ const values = {};
1388
+ for (const key of [...keys].sort()) {
1389
+ if (isTelemetryKey(key)) continue;
1390
+ const owner = owners.get(key) ?? storageOwner(key, plan);
1391
+ if (STORAGE_KEYS.includes(key)) {
1392
+ const value = custom[key] ?? storageValue(key, storage);
1393
+ if (value !== void 0) values[key] = value;
1394
+ continue;
1395
+ }
1396
+ const value = valueFor(app, key, owner);
1397
+ if (value !== void 0) values[key] = value;
1398
+ }
1399
+ return values;
1400
+ };
1401
+ const stageKeys = Object.keys(custom);
1402
+ for (const app of apps) {
1403
+ const site = manifest[app.id];
1404
+ if (site?.kind === "site") {
1405
+ const args = publicBuildValues(site, manifest, (key) => valueFor(app, key, owners.get(key)), custom);
1406
+ if (app.build && Object.keys(args).length > 0) app.build.args = args;
1407
+ const offline = offlineBuildHosts(site, manifest, (key) => valueFor(app, key, owners.get(key)));
1408
+ if (app.build && offline.length > 0) app.build.offlineHosts = offline;
1409
+ if (!app.runtime) continue;
1410
+ }
1411
+ if (input.buildOnly) continue;
1412
+ const values = valuesFor(app, processEnvKeys(manifest, { app: app.name }, stageKeys) ?? /* @__PURE__ */ new Set());
1413
+ app.env = {
1414
+ ...scopeTelemetryEnv(values, {
1415
+ uses: app.kind !== "site" && telemetryOf(manifest, app.id) !== void 0,
1416
+ serviceName: app.name,
1417
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1418
+ }),
1419
+ NODE_ENV: "production",
1420
+ PORT: String(app.port),
1421
+ STAGE: stage
1422
+ };
1423
+ for (const [key, value] of Object.entries(app.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(app.name, key);
1424
+ }
1425
+ const mobileApps = [];
1426
+ for (const declaration of Object.values(manifest)) {
1427
+ if (declaration.kind !== "mobile-app") continue;
1428
+ const app = {
1429
+ name: appKey(declaration.id),
1430
+ id: declaration.id,
1431
+ kind: "site"
1432
+ };
1433
+ mobileApps.push({
1434
+ name: app.name,
1435
+ id: app.id,
1436
+ values: publicBuildValues(declaration, manifest, (key) => valueFor(app, key, owners.get(key)), custom)
1437
+ });
1438
+ }
1439
+ for (const worker of input.buildOnly ? [] : workers) {
1440
+ const keys = processEnvKeys(manifest, { workers: [worker.id] }, stageKeys) ?? /* @__PURE__ */ new Set();
1441
+ const resolved = valuesFor({
1442
+ name: worker.name,
1443
+ id: worker.id,
1444
+ kind: "rest-api"
1445
+ }, keys);
1446
+ const push = local ? void 0 : workerPush(worker, input.subscribers?.[worker.id] ?? [], resolved, {
1447
+ stage,
1448
+ ...domain ? { domain } : {}
1449
+ });
1450
+ if (push) {
1451
+ worker.push = push;
1452
+ if (proxy === "traefik") edgeServices.add(worker.name);
1453
+ }
1454
+ worker.env = {
1455
+ ...scopeTelemetryEnv(resolved, {
1456
+ uses: telemetryOf(manifest, worker.id) !== void 0,
1457
+ serviceName: worker.name,
1458
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1459
+ }),
1460
+ ...push && !input.recordingSubscriptions ? { [SNS_SUBSCRIPTIONS_KEY]: recordedSubscriptions(worker, push, input.pushSubscriptions?.[worker.id]) } : {},
1461
+ NODE_ENV: "production",
1462
+ PORT: String(worker.port),
1463
+ STAGE: stage
1464
+ };
1465
+ for (const [key, value] of Object.entries(worker.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);
1466
+ }
1467
+ for (const unit of processors) {
1468
+ const served = fileServers.get(unit.id);
1469
+ if (served) served.route = {
1470
+ ...served.route,
1471
+ handlers: [{
1472
+ name: unit.name,
1473
+ prefixes: unit.prefixes,
1474
+ upstreams: [{
1475
+ service: unit.name,
1476
+ port: unit.port
1477
+ }]
1478
+ }]
1479
+ };
1480
+ else if (!local && !input.buildOnly) {
1481
+ if (!domain) throw new NoDomainForStage(stage);
1482
+ const key = originSecretKey(unit.id);
1483
+ const secret = custom[key];
1484
+ if (!secret) throw new ProcessorOriginSecretMissing(unit.id, key, stage);
1485
+ unit.origin = {
1486
+ host: processorOriginHost(unit.id, domain),
1487
+ secret
1488
+ };
1489
+ }
1490
+ if (proxy === "traefik" && (served || unit.origin)) edgeServices.add(unit.name);
1491
+ if (input.buildOnly) continue;
1492
+ const keys = processEnvKeys(manifest, { processors: [unit.id] }, stageKeys) ?? /* @__PURE__ */ new Set();
1493
+ unit.env = {
1494
+ ...scopeTelemetryEnv(valuesFor({
1495
+ name: unit.name,
1496
+ id: unit.id,
1497
+ kind: "rest-api"
1498
+ }, keys), {
1499
+ uses: telemetryOf(manifest, unit.id) !== void 0,
1500
+ serviceName: unit.name,
1501
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1502
+ }),
1503
+ NODE_ENV: "production",
1504
+ PORT: String(unit.port),
1505
+ STAGE: stage
1506
+ };
1507
+ for (const [key, value] of Object.entries(unit.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(unit.name, key);
1508
+ }
1509
+ if (storage && !input.buildOnly) {
1510
+ const watched = watchedBuckets(manifest, input.subscribers ?? {});
1511
+ for (const [bucket, workerId] of watched) {
1512
+ if (!services.minio.includes(bucket)) continue;
1513
+ const worker = workers.find((w) => w.id === workerId);
1514
+ const relay = worker?.env?.[provideKey(bucket, "eventsConnectionString")];
1515
+ const token = worker?.env?.[provideKey(bucket, "eventsToken")];
1516
+ if (!worker || !relay || relay.startsWith("sns:") || !token) continue;
1517
+ storage.webhooks.push({
1518
+ bucket,
1519
+ endpoint: `http://${hostOf(worker.name)}:${worker.port}${objectsRoute(bucket)}`,
1520
+ token
1521
+ });
1522
+ }
1523
+ }
1524
+ let inboxRelay;
1525
+ if (local && infra.includes("mailpit") && !input.buildOnly) {
1526
+ const relayId = inboxRelayWorker(manifest, input.subscribers ?? {});
1527
+ const relay = workers.find((w) => w.id === relayId);
1528
+ const token = relay?.env?.[INBOX_RELAY_TOKEN_KEY];
1529
+ if (relay && token) inboxRelay = inboxWebhookUrl(`http://${hostOf(relay.name)}:${relay.port}`, token);
1530
+ }
1531
+ const tls = certificate || local ? {
1532
+ kind: "files",
1533
+ ...proxy === "caddy" ? {
1534
+ certFile: `${CADDY_TLS_DIR}/cert.pem`,
1535
+ keyFile: `${CADDY_TLS_DIR}/key.pem`
1536
+ } : edgeCertificatePaths(project)
1537
+ } : { kind: "acme" };
1538
+ const authority = local && !certificate ? input.localAuthority ?? localAuthorityPaths() : void 0;
1539
+ const root = authority?.certFile ?? certificate?.caFile;
1540
+ const backupsChoice = input.buildOnly ? void 0 : stageBackups(workspace, manifest, stage);
1541
+ const backups = backupsChoice?.mode === "on" && infra.includes("postgres") ? stackBackups({
1542
+ workspace,
1543
+ stage,
1544
+ project,
1545
+ plan,
1546
+ backups: backupsChoice.backups,
1547
+ custom,
1548
+ seed,
1549
+ superuser: credential.containers.postgres,
1550
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1551
+ }) : void 0;
1552
+ if (!local) for (const app of apps) {
1553
+ const site = manifest[app.id];
1554
+ if (site?.kind !== "site") continue;
1555
+ const key = sitePasswordKey(manifest, site, stage);
1556
+ if (key) app.auth = siteAuth(stage, key, custom);
1557
+ }
1558
+ const wildcard = local ? void 0 : stackWildcard(apps, {
1559
+ manifest,
1560
+ byId,
1561
+ workspace,
1562
+ stage,
1563
+ proxy,
1564
+ certificate: certificate !== void 0,
1565
+ hostOf
1566
+ });
1567
+ const routes = [
1568
+ ...apps.map((app) => ({
1569
+ name: app.name,
1570
+ host: app.host,
1571
+ ...wildcard?.site === app.id ? { wildcard: wildcard.edge } : {},
1572
+ upstreams: replicaNames(app).map((service) => ({
1573
+ service,
1574
+ port: app.port
1575
+ })),
1576
+ streaming: true,
1577
+ ...app.auth ? { auth: {
1578
+ user: app.auth.user,
1579
+ hash: app.auth.hash
1580
+ } } : {},
1581
+ health: app.kind === "site" ? "/" : "/health"
1582
+ })),
1583
+ ...[...fileServers.values()].map(({ route }) => route),
1584
+ ...processors.flatMap(({ name, port, prefixes, origin }) => origin ? [{
1585
+ name,
1586
+ host: origin.host,
1587
+ upstreams: [{
1588
+ service: name,
1589
+ port
1590
+ }],
1591
+ streaming: false,
1592
+ prefixes,
1593
+ requireHeader: {
1594
+ name: ORIGIN_VERIFY_HEADER,
1595
+ value: origin.secret
1596
+ },
1597
+ health: "/health"
1598
+ }] : []),
1599
+ ...workers.flatMap(({ name, port, push }) => push ? [{
1600
+ name,
1601
+ host: push.host,
1602
+ upstreams: [{
1603
+ service: name,
1604
+ port
1605
+ }],
1606
+ streaming: false,
1607
+ paths: push.paths,
1608
+ health: "/health"
1609
+ }] : []),
1610
+ ...logs?.host && logs.public ? [{
1611
+ name: LOGS_SERVICE,
1612
+ host: logs.host,
1613
+ upstreams: [{
1614
+ service: LOGS_SERVICE,
1615
+ port: LOGS_PORT
1616
+ }],
1617
+ streaming: true,
1618
+ allow: logs.public.allow
1619
+ }] : []
1620
+ ];
1621
+ if (mailInbox) {
1622
+ const taken = routes.find((route) => route.host === mailInbox.host);
1623
+ if (taken) throw new MailInboxHostTaken(mailInbox.host, taken.name);
1624
+ routes.push({
1625
+ name: "mailpit",
1626
+ host: mailInbox.host,
1627
+ upstreams: [{
1628
+ service: "mailpit",
1629
+ port: MAILPIT_WEB_PORT
1630
+ }],
1631
+ streaming: true
1632
+ });
1633
+ }
1634
+ assertHostsUnique(routes);
1635
+ const layout = input.layout ?? defaultLayout(workspace.root);
1636
+ const compose = stackFile({
1637
+ project,
1638
+ plan,
1639
+ infra,
1640
+ apps,
1641
+ workers,
1642
+ processors,
1643
+ credentials: credential.containers,
1644
+ ...storage ? { storage } : {},
1645
+ ...inboxRelay ? { inboxRelay } : {},
1646
+ ...logs ? { logs } : {},
1647
+ ...redis ? { redis } : {},
1648
+ ...backups ? { backups } : {},
1649
+ https,
1650
+ http,
1651
+ composeDir: join(workspace.root, stackDir(stage)),
1652
+ buildRoot: layout.buildRoot,
1653
+ workspaceRoot: workspace.root,
1654
+ envFiles: !input.buildOnly,
1655
+ proxy,
1656
+ edge: new Map([...edgeServices].map((service) => [service, hostOf(service)])),
1657
+ ...local ? { localEdge: {
1658
+ hosts: stackPublicHosts(routes),
1659
+ ...root ? { authority: root } : {}
1660
+ } } : {}
1661
+ });
1662
+ const dockerfiles = {};
1663
+ for (const app of apps) {
1664
+ if (!app.build) continue;
1665
+ dockerfiles[app.build.dockerfile] = appDockerfile(app.name, workspace.apps[app.name], {
1666
+ layout,
1667
+ workspaceRoot: workspace.root,
1668
+ apps: workspace.apps,
1669
+ manifest,
1670
+ cache: STACK_CACHE,
1671
+ workspace,
1672
+ stage,
1673
+ ...app.kind === "site" && app.build.args ? { publicUrlArgs: Object.keys(app.build.args) } : {}
1674
+ });
1675
+ }
1676
+ for (const worker of workers) {
1677
+ if (!worker.build) continue;
1678
+ dockerfiles[worker.build.dockerfile] = workerDockerfile({
1679
+ id: worker.id,
1680
+ name: worker.name,
1681
+ app: worker.host
1682
+ }, workspace.apps[worker.host], {
1683
+ layout,
1684
+ workspaceRoot: workspace.root,
1685
+ cache: STACK_CACHE
1686
+ });
1687
+ }
1688
+ for (const unit of processors) {
1689
+ if (!unit.build) continue;
1690
+ dockerfiles[unit.build.dockerfile] = processorDockerfile({
1691
+ id: unit.id,
1692
+ name: unit.name,
1693
+ app: unit.host
1694
+ }, workspace.apps[unit.host], {
1695
+ layout,
1696
+ workspaceRoot: workspace.root,
1697
+ cache: STACK_CACHE
1698
+ });
1699
+ }
1700
+ return {
1701
+ project,
1702
+ stage,
1703
+ local,
1704
+ ...authority ? { authority } : {},
1705
+ apps,
1706
+ workers,
1707
+ processors,
1708
+ mobileApps,
1709
+ infra,
1710
+ compose,
1711
+ proxy,
1712
+ routes,
1713
+ ...wildcard ? { wildcard: {
1714
+ site: wildcard.site,
1715
+ host: `*.${wildcard.edge.domain}`,
1716
+ tls: wildcard.edge.tls.kind
1717
+ } } : {},
1718
+ ...proxy === "caddy" ? { caddyfile: edgeCaddyfile(routes, {
1719
+ tls,
1720
+ edgeToken: outside[EDGE_TOKEN_KEY],
1721
+ ...local ? { redirects: false } : {}
1722
+ }) } : { traefik: traefikDynamicFile(routes, {
1723
+ project,
1724
+ tls,
1725
+ edgeToken: outside[EDGE_TOKEN_KEY]
1726
+ }) },
1727
+ ...certificate ? { tls: certificate } : {},
1728
+ dockerfiles,
1729
+ plan,
1730
+ credential,
1731
+ resolution: {
1732
+ ...derivation,
1733
+ addresses: {
1734
+ ...publicAddresses,
1735
+ ...Object.fromEntries([...fileServers].map(([id, { url }]) => [id, url]))
1736
+ }
1737
+ },
1738
+ ...storage ? { storage } : {},
1739
+ devServices: local ? [] : devServicesUsed(services),
1740
+ ...logs ? { logs } : {},
1741
+ ...telemetry ? { telemetry } : {},
1742
+ ...redis ? { redis } : {},
1743
+ ...backups ? { backups } : {},
1744
+ ...mailInbox ? { mailInbox } : {}
1745
+ };
1746
+ }
1747
+ /** The stack's MinIO's value for one of the S3 client's keys. */
1748
+ function storageValue(key, storage) {
1749
+ if (!storage) return void 0;
1750
+ if (key === "AWS_ACCESS_KEY_ID") return storage.user;
1751
+ if (key === "AWS_SECRET_ACCESS_KEY") return storage.password;
1752
+ if (key === "AWS_REGION") return MINIO_REGION;
1753
+ }
1754
+ /** Which bucket an S3 credential key belongs to — the first one declared. */
1755
+ function storageOwner(key, plan) {
1756
+ if (!STORAGE_KEYS.includes(key)) return void 0;
1757
+ return plan.resources.find((r) => r.kind === "objects");
1758
+ }
1759
+ /** The apps a stack runs: every API and every site, at its stage address. */
1760
+ function stackApps(workspace, manifest, plan, options) {
1761
+ const apps = [];
1762
+ const resources = new Map(plan.resources.map((r) => [r.id, r]));
1763
+ for (const [id, declaration] of Object.entries(manifest)) {
1764
+ if (declaration.kind !== "rest-api" && declaration.kind !== "websocket-api" && declaration.kind !== "site") continue;
1765
+ const name = appKey(id);
1766
+ const app = workspace.apps[name];
1767
+ const resource = resources.get(id);
1768
+ if (!app || !resource || !app.port) continue;
1769
+ const host = hostOf(name, app, workspace, resource, options);
1770
+ const site = declaration.kind === "site";
1771
+ const tag = site ? siteTag(options.images.tag, options.stage) : options.images.tag;
1772
+ const ref = validateImageRef(imageRef(options.identity, name, options.images.registry, tag));
1773
+ apps.push({
1774
+ app: name,
1775
+ name,
1776
+ id,
1777
+ kind: declaration.kind,
1778
+ ...declaration.kind === "site" ? { variant: declaration.variant } : {},
1779
+ replicas: declaration.kind === "websocket-api" ? declaration.replicas ?? 1 : 1,
1780
+ runtime: !site || runsServer(declaration),
1781
+ path: app.path,
1782
+ port: app.port,
1783
+ host,
1784
+ url: `${declaration.kind === "websocket-api" ? "wss" : "https"}://${host}${options.local && options.https !== 443 ? `:${options.https}` : ""}`,
1785
+ ref,
1786
+ tag,
1787
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${name}` } } : {}
1788
+ });
1789
+ }
1790
+ return apps.sort((a, b) => a.name.localeCompare(b.name));
1791
+ }
1792
+ /**
1793
+ * Where SNS pushes to a worker on a deployed stage, or nothing when it pushes
1794
+ * to none of its subscribers.
1795
+ *
1796
+ * A subscriber is pushed to when the connection string its deliveries come
1797
+ * from — its topic's, or its bucket's events — as this stage resolved it for
1798
+ * the worker, is an SNS one — the same test the worker's own
1799
+ * startup makes, so the edge exposes a route exactly when the worker mounts
1800
+ * it. Each such route, and nothing else the worker serves, answers on
1801
+ * `<worker>.<domain>`.
1802
+ */
1803
+ function workerPush(worker, subscribers, env, options) {
1804
+ const pushed = subscribers.filter(({ connectionKey }) => env[connectionKey]?.startsWith("sns:")).filter((subscriber, index, all) => all.findIndex((s) => s.name === subscriber.name) === index).sort((a, b) => a.name.localeCompare(b.name));
1805
+ if (pushed.length === 0) return void 0;
1806
+ if (!options.domain) throw new NoDomainForStage(options.stage);
1807
+ const host = `${worker.name}.${options.domain}`;
1808
+ const url = `https://${host}`;
1809
+ return {
1810
+ host,
1811
+ url,
1812
+ paths: pushed.map(({ name }) => subscriberRoute(name)),
1813
+ subscribers: pushed.map(({ name, connectionKey, events }) => ({
1814
+ name,
1815
+ connectionKey,
1816
+ endpoint: `${url}${subscriberRoute(name)}`,
1817
+ ...events ? { events } : {}
1818
+ }))
1819
+ };
1820
+ }
1821
+ /** A pushed subscriber the deploy recorded no SNS subscription for. */
1822
+ var PushSubscriptionMissing = class extends GkmError {
1823
+ worker;
1824
+ subscriber;
1825
+ constructor(worker, subscriber) {
1826
+ super(`SNS pushes to '${subscriber}' on the worker '${worker}', and the deploy recorded no subscription for it, so the worker would mount no route and SNS would deliver nowhere. Deploy the stage, which subscribes each pushed subscriber and records its ARN.`);
1827
+ this.worker = worker;
1828
+ this.subscriber = subscriber;
1829
+ this.name = "PushSubscriptionMissing";
1830
+ }
1831
+ };
1832
+ /**
1833
+ * The worker's `GKM_SNS_SUBSCRIPTIONS`: each pushed subscriber's recorded
1834
+ * subscription ARN, and nothing for a subscriber it does not run.
1835
+ *
1836
+ * @throws {PushSubscriptionMissing} when one has none
1837
+ */
1838
+ function recordedSubscriptions(worker, push, recorded = {}) {
1839
+ const arns = {};
1840
+ for (const { name } of push.subscribers) {
1841
+ const arn = recorded[name];
1842
+ if (!arn) throw new PushSubscriptionMissing(worker.name, name);
1843
+ arns[name] = arn;
1844
+ }
1845
+ return JSON.stringify(arns);
1846
+ }
1847
+ /**
1848
+ * A wildcard site on a deployed stage with nowhere to get a certificate for
1849
+ * its tenants' hosts from. Let's Encrypt issues a wildcard certificate only
1850
+ * over the DNS challenge, so the stage either brings its own or gives the
1851
+ * proxy a way to get one.
1852
+ */
1853
+ var WildcardSiteCertificateMissing = class extends GkmError {
1854
+ site;
1855
+ stage;
1856
+ proxy;
1857
+ domain;
1858
+ constructor(site, stage, proxy, domain) {
1859
+ super(proxy === "traefik" ? `'${site}' answers on every subdomain of ${domain}, and '${stage}' has no certificate for them. Set deploy.compose.tls for '${stage}' to a *.${domain} certificate, or manage ${domain} with dns: { '<root domain>': { provider: 'route53' } } so the shared edge gets one over the DNS challenge.` : `'${site}' answers on every subdomain of ${domain}, and '${stage}' has no certificate for them. Set deploy.compose.tls for '${stage}' to a *.${domain} certificate, or give the site \`hosts\` so Caddy gets one per tenant, on demand.`);
1860
+ this.site = site;
1861
+ this.stage = stage;
1862
+ this.proxy = proxy;
1863
+ this.domain = domain;
1864
+ this.name = "WildcardSiteCertificateMissing";
1865
+ }
1866
+ };
1867
+ /**
1868
+ * A deployed stage's wildcard site, as its edge serves it: the labels it
1869
+ * never takes, and its certificate — the stage's own (`deploy.compose.tls`)
1870
+ * first; then, on the shared Traefik edge, a `*.<domain>` one over the DNS
1871
+ * challenge when Route 53 manages the domain; on the stack's own Caddy, one
1872
+ * per host on demand, asked of the site's `hosts` route.
1873
+ *
1874
+ * @throws {WildcardSiteCertificateMissing} when neither applies
1875
+ */
1876
+ function stackWildcard(apps, options) {
1877
+ const { manifest, workspace, stage, proxy } = options;
1878
+ const app = apps.find((a) => isWildcardSite(manifest[a.id]));
1879
+ if (!app) return void 0;
1880
+ const declaration = manifest[app.id];
1881
+ if (!isWildcardSite(declaration)) return void 0;
1882
+ const domain = workspace.domains?.[stage];
1883
+ if (!domain) throw new NoDomainForStage(stage);
1884
+ const except = options.byId.get(app.id)?.protectedSubdomains ?? [];
1885
+ const tls = (() => {
1886
+ if (options.certificate) return { kind: "stage" };
1887
+ if (proxy === "traefik") {
1888
+ const dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};
1889
+ const root = findRootDomain(domain, dns);
1890
+ if (root && dns[root]?.provider === "route53") return { kind: "dns" };
1891
+ } else if (declaration.hosts) {
1892
+ const surface = apps.find((a) => a.id === declaration.hosts?.surface);
1893
+ if (surface) return {
1894
+ kind: "on-demand",
1895
+ ask: `http://${options.hostOf(surface.name)}:${surface.port}${declaration.hosts.path}`
1896
+ };
1897
+ }
1898
+ throw new WildcardSiteCertificateMissing(app.id, stage, proxy, domain);
1899
+ })();
1900
+ return {
1901
+ site: app.id,
1902
+ edge: {
1903
+ domain,
1904
+ except,
1905
+ tls
1906
+ }
1907
+ };
1908
+ }
1909
+ /**
1910
+ * The first label under `stage`'s domain of every other stage's domain that
1911
+ * sits beneath it — `staging` for `staging.example.com` (or
1912
+ * `a.staging.example.com`) under `example.com`.
1913
+ */
1914
+ function nestedStageLabels(domains, stage) {
1915
+ const own = domains?.[stage]?.toLowerCase();
1916
+ if (!own) return [];
1917
+ const labels = /* @__PURE__ */ new Set();
1918
+ for (const [other, domain] of Object.entries(domains ?? {})) {
1919
+ if (other === stage || !domain) continue;
1920
+ const lower = domain.toLowerCase();
1921
+ if (!lower.endsWith(`.${own}`)) continue;
1922
+ const rest = lower.slice(0, -(own.length + 1)).split(".");
1923
+ labels.add(rest.at(-1));
1924
+ }
1925
+ return [...labels].sort();
1926
+ }
1927
+ /** Two constructs the edge would answer on one host. */
1928
+ var EdgeHostTaken = class extends GkmError {
1929
+ host;
1930
+ first;
1931
+ second;
1932
+ constructor(host, first, second) {
1933
+ super(`'${first}' and '${second}' would both answer on ${host}, and the edge can send a host to only one of them. Give one a subdomain of its own, or rename it.`);
1934
+ this.host = host;
1935
+ this.first = first;
1936
+ this.second = second;
1937
+ this.name = "EdgeHostTaken";
1938
+ }
1939
+ };
1940
+ /** Refuse a stack where one host would be routed to two services. */
1941
+ function assertHostsUnique(routes) {
1942
+ const claimed = /* @__PURE__ */ new Map();
1943
+ for (const { host, name } of routes) {
1944
+ const first = claimed.get(host);
1945
+ if (first !== void 0) throw new EdgeHostTaken(host, first, name);
1946
+ claimed.set(host, name);
1947
+ }
1948
+ }
1949
+ /** Each processor unit's image, and where it is built from. */
1950
+ function stackProcessors(units, options) {
1951
+ return units.map((unit) => {
1952
+ const server = options.manifest[unit.id];
1953
+ const processors = server?.kind === "file-server" ? server.processors ?? [] : [];
1954
+ return {
1955
+ app: unit.name,
1956
+ name: unit.name,
1957
+ id: unit.id,
1958
+ host: unit.app,
1959
+ port: PROCESSOR_PORT,
1960
+ prefixes: [...new Set(processors.map((p) => p.prefix))].sort(),
1961
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
1962
+ tag: options.images.tag,
1963
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
1964
+ };
1965
+ });
1966
+ }
1967
+ /** Each worker's image, and where it is built from. */
1968
+ function stackWorkers(units, options) {
1969
+ return units.map((unit) => ({
1970
+ app: unit.name,
1971
+ name: unit.name,
1972
+ id: unit.id,
1973
+ host: unit.app,
1974
+ port: WORKER_PORT,
1975
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
1976
+ tag: options.images.tag,
1977
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
1978
+ }));
1979
+ }
1980
+ /**
1981
+ * The host an app answers on for a stage: the `gkm dev` edge's
1982
+ * `*.localhost` names for the local stage, and the stage's domain — by the
1983
+ * same rule a deploy follows — for any other.
1984
+ */
1985
+ function hostOf(name, app, workspace, resource, options) {
1986
+ if (options.local) return hostFor(resource, workspace.name);
1987
+ if (resource.subdomain === WILDCARD_SUBDOMAIN) {
1988
+ const domain = workspace.domains?.[options.stage];
1989
+ if (!domain) throw new NoDomainForStage(options.stage);
1990
+ return `${WILDCARD_SUBDOMAIN}.${domain}`;
1991
+ }
1992
+ return resolveHost(name, app, options.stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
1993
+ }
1994
+ /** An app's compose services, one per replica: `api`, `api-2`, `api-3`. */
1995
+ function replicaNames(app) {
1996
+ return [app.name, ...Array.from({ length: app.replicas - 1 }, (_, i) => `${app.name}-${i + 2}`)];
1997
+ }
1998
+ /** Where an app container reads gkm's root certificate: mounted read-only. */
1999
+ const LOCAL_CA_IN_CONTAINER = "/etc/gkm/local-ca.pem";
2000
+ /**
2001
+ * The local stage's public hosts a container can be pointed at: every
2002
+ * route's but a wildcard's, which no host entry can name.
2003
+ */
2004
+ function stackPublicHosts(routes) {
2005
+ return [...new Set(routes.map((route) => route.host))].filter((host) => !host.startsWith("*.")).sort();
2006
+ }
2007
+ /**
2008
+ * What a local stack's container needs to call the stage's own public hosts —
2009
+ * `https://api.<project>.localhost`, which a site's server-side code is
2010
+ * handed because a browser is.
2011
+ *
2012
+ * Inside a container `*.localhost` is its own loopback, so each host is
2013
+ * resolved to the host's gateway, where the edge — the stack's Caddy, or the
2014
+ * shared Traefik edge — publishes its ports. Not a network alias on the edge:
2015
+ * the address may carry the edge's published port
2016
+ * (`https://api.shop.localhost:8443`), which only the host answers on. And the
2017
+ * container trusts the root the edge's certificate chains to — gkm's, or the
2018
+ * one the stage's own certificate names — its public certificate, never a
2019
+ * key, mounted read-only.
2020
+ */
2021
+ function localEdgeAccess(edge) {
2022
+ return {
2023
+ extra_hosts: edge.hosts.map((host) => `${host}:host-gateway`),
2024
+ volumes: edge.authority ? [`${edge.authority}:${LOCAL_CA_IN_CONTAINER}:ro`] : [],
2025
+ environment: edge.authority ? { NODE_EXTRA_CA_CERTS: LOCAL_CA_IN_CONTAINER } : {}
2026
+ };
2027
+ }
2028
+ /** The compose document: the infrastructure, the apps, and the edge. */
2029
+ function stackFile(options) {
2030
+ const { project, plan, apps } = options;
2031
+ const infra = options.infra.filter((name) => name !== LOGS_SERVICE);
2032
+ const derived = composeFor({
2033
+ ...plan,
2034
+ containers: [...infra]
2035
+ }, {
2036
+ project,
2037
+ ports: Object.fromEntries(portKeys(infra, plan.fakes).map((key) => [key, 0])),
2038
+ credentials: options.credentials
2039
+ });
2040
+ const services = {};
2041
+ const volumes = {
2042
+ ...derived.volumes,
2043
+ ...options.proxy === "caddy" ? {
2044
+ "caddy-data": {},
2045
+ "caddy-config": {}
2046
+ } : {},
2047
+ ...options.logs ? { "openobserve-data": {} } : {}
2048
+ };
2049
+ for (const name of infra) {
2050
+ const { ports: _ports, depends_on, profiles: _profiles, ...service } = derived.services[name];
2051
+ services[name] = {
2052
+ ...service,
2053
+ ...depends_on?.length ? { depends_on: Object.fromEntries(depends_on.map((dep) => [dep, HEALTHY])) } : {}
2054
+ };
2055
+ }
2056
+ const postgres = services.postgres;
2057
+ if (postgres) postgres.ports = [`127.0.0.1::${LOOPBACK_SERVICES.postgres}`];
2058
+ const minio = services.minio;
2059
+ if (minio && options.storage) {
2060
+ minio.environment = {
2061
+ ...minio.environment,
2062
+ MINIO_ROOT_USER: options.storage.user,
2063
+ MINIO_ROOT_PASSWORD: options.storage.password,
2064
+ ...minioWebhookEnv(options.storage.webhooks)
2065
+ };
2066
+ minio.ports = [`127.0.0.1::${LOOPBACK_SERVICES.minio}`];
2067
+ }
2068
+ const mailpit = services.mailpit;
2069
+ if (mailpit && options.inboxRelay) mailpit.environment = {
2070
+ ...mailpit.environment,
2071
+ MP_WEBHOOK_URL: options.inboxRelay
2072
+ };
2073
+ if (services["redis"] && options.redis) services[REDIS_SERVICE] = redisService(options.redis);
2074
+ if (options.logs) services[LOGS_SERVICE] = logsService(options.logs);
2075
+ if (options.backups) services[BACKUPS_SERVICE] = backupsService(options.backups, options.envFiles);
2076
+ for (const app of apps) {
2077
+ const definition = {
2078
+ image: app.ref,
2079
+ ...app.build ? { build: {
2080
+ ...composeBuildPaths({
2081
+ composeDir: options.composeDir,
2082
+ buildRoot: options.buildRoot,
2083
+ workspaceRoot: options.workspaceRoot,
2084
+ dockerfile: app.build.dockerfile
2085
+ }),
2086
+ ...app.build.args ? { args: app.build.args } : {},
2087
+ ...app.build.offlineHosts ? { extra_hosts: app.build.offlineHosts.map((host) => `${host}:${OFFLINE_BUILD_ADDRESS}`) } : {}
2088
+ } } : {},
2089
+ restart: "unless-stopped",
2090
+ ...app.runtime ? { env_file: [{
2091
+ path: `./${app.name}.env`,
2092
+ format: "raw"
2093
+ }] } : {},
2094
+ ...app.kind !== "site" && infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
2095
+ healthcheck: probe(app.port, app.kind === "site" ? "/" : "/health"),
2096
+ ...app.kind === "websocket-api" ? { ulimits: { nofile: NOFILE } } : {}
2097
+ };
2098
+ for (const name of replicaNames(app)) services[name] = { ...definition };
2099
+ }
2100
+ for (const worker of [...options.workers, ...options.processors]) services[worker.name] = {
2101
+ image: worker.ref,
2102
+ ...worker.build ? { build: composeBuildPaths({
2103
+ composeDir: options.composeDir,
2104
+ buildRoot: options.buildRoot,
2105
+ workspaceRoot: options.workspaceRoot,
2106
+ dockerfile: worker.build.dockerfile
2107
+ }) } : {},
2108
+ restart: "unless-stopped",
2109
+ env_file: [{
2110
+ path: `./${worker.name}.env`,
2111
+ format: "raw"
2112
+ }],
2113
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
2114
+ healthcheck: probe(worker.port, "/health")
2115
+ };
2116
+ if (options.localEdge) {
2117
+ const access = localEdgeAccess(options.localEdge);
2118
+ for (const name of [
2119
+ ...apps.flatMap(replicaNames),
2120
+ ...options.workers.map((w) => w.name),
2121
+ ...options.processors.map((p) => p.name)
2122
+ ]) {
2123
+ const service = services[name];
2124
+ if (!service) continue;
2125
+ services[name] = {
2126
+ ...service,
2127
+ environment: {
2128
+ ...service.environment,
2129
+ ...access.environment
2130
+ },
2131
+ ...access.volumes.length ? { volumes: [...service.volumes ?? [], ...access.volumes] } : {},
2132
+ ...access.extra_hosts.length ? { extra_hosts: [...service.extra_hosts ?? [], ...access.extra_hosts] } : {}
2133
+ };
2134
+ }
2135
+ }
2136
+ if (options.proxy === "caddy") services.caddy = {
2137
+ image: DEFAULT_IMAGES.caddy,
2138
+ restart: "unless-stopped",
2139
+ ports: [`${options.https}:443`, `${options.http}:80`],
2140
+ volumes: ["caddy-data:/data", "caddy-config:/config"],
2141
+ ...EDGE_LIMITS,
2142
+ depends_on: Object.fromEntries([
2143
+ ...apps.flatMap(replicaNames),
2144
+ ...options.workers.filter((w) => w.push).map((w) => w.name),
2145
+ ...options.processors.map((p) => p.name)
2146
+ ].map((name) => [name, STARTED])),
2147
+ healthcheck: {
2148
+ test: [
2149
+ "CMD",
2150
+ "caddy",
2151
+ "version"
2152
+ ],
2153
+ interval: "10s",
2154
+ timeout: "5s",
2155
+ retries: 5
2156
+ }
2157
+ };
2158
+ for (const [service, alias] of options.edge) {
2159
+ const definition = services[service];
2160
+ if (!definition) continue;
2161
+ definition.networks = {
2162
+ default: { aliases: [alias] },
2163
+ edge: { aliases: [alias] }
2164
+ };
2165
+ }
2166
+ for (const service of Object.values(services)) {
2167
+ if (!options.envFiles) delete service.env_file;
2168
+ service.logging = {
2169
+ driver: LOG_ROTATION.driver,
2170
+ options: { ...LOG_ROTATION.options }
2171
+ };
2172
+ }
2173
+ return {
2174
+ name: project,
2175
+ services,
2176
+ volumes,
2177
+ ...options.edge.size > 0 ? { networks: { edge: {
2178
+ name: EDGE_NETWORK,
2179
+ external: true
2180
+ } } } : {}
2181
+ };
2182
+ }
2183
+ /**
2184
+ * A build without a layout: the workspace is the build root, with pnpm.
2185
+ * What a caller that never looked at the filesystem gets.
2186
+ */
2187
+ function defaultLayout(root) {
2188
+ return {
2189
+ buildRoot: root,
2190
+ gkmRoot: ".",
2191
+ tools: {
2192
+ packageManager: "pnpm",
2193
+ turboVersion: TURBO_VERSION,
2194
+ monorepo: true
2195
+ },
2196
+ gkmPaths: ["gkm.config.*"]
2197
+ };
2198
+ }
2199
+ /** Render an app's env file: one `KEY=value` per line, read raw by compose. */
2200
+ function envFile(env) {
2201
+ return `${Object.entries(env).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n")}\n`;
2202
+ }
2203
+ //#endregion
2204
+ export { traefikStaticFile as C, parseDigests as D, assertImagesExist as E, pinImages as O, readEdgeClaims as S, RegistryRequired as T, EDGE_NETWORK as _, composeProject as a, claimsOverlap as b, derivedCredentials as c, stackDir as d, stackPlan as f, EDGE_DYNAMIC_DIR as g, EDGE_CERTS_DIR as h, LOOPBACK_SERVICES as i, pinnedRef as k, envFile as l, EDGE_AWS_CREDENTIALS as m, LOGS_PORT_ENV as n, composeStack as o, withCaddyConfigs as p, LOG_ROTATION as r, deployedInboxEnv as s, EDGE_PORT_ENV as t, replicaNames as u, EDGE_PROJECT as v, assertSitePasswords as w, edgeComposeFile as x, EDGE_SERVICE as y };
2205
+
2206
+ //# sourceMappingURL=stack-BZG5HoVN.mjs.map