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

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 (262) hide show
  1. package/dist/{EndpointGenerator-BMRL04ic.mjs → EndpointGenerator-CusLH-9S.mjs} +2 -2
  2. package/dist/{EndpointGenerator-BMRL04ic.mjs.map → EndpointGenerator-CusLH-9S.mjs.map} +1 -1
  3. package/dist/{EndpointGenerator-ePscnbwB.cjs → EndpointGenerator-DyLMYClE.cjs} +2 -2
  4. package/dist/{EndpointGenerator-ePscnbwB.cjs.map → EndpointGenerator-DyLMYClE.cjs.map} +1 -1
  5. package/dist/{GoDaddyProvider-BgY6mqoH.mjs → GoDaddyProvider-BIibcRG4.mjs} +2 -3
  6. package/dist/{GoDaddyProvider-BgY6mqoH.mjs.map → GoDaddyProvider-BIibcRG4.mjs.map} +1 -1
  7. package/dist/{GoDaddyProvider-C-rs22Zv.cjs → GoDaddyProvider-C7Zt4dVy.cjs} +5 -6
  8. package/dist/{GoDaddyProvider-C-rs22Zv.cjs.map → GoDaddyProvider-C7Zt4dVy.cjs.map} +1 -1
  9. package/dist/{HostingerProvider-DEqpvoiD.cjs → HostingerProvider-BVhFhzCW.cjs} +2 -2
  10. package/dist/{HostingerProvider-DEqpvoiD.cjs.map → HostingerProvider-BVhFhzCW.cjs.map} +1 -1
  11. package/dist/{HostingerProvider-CgMuKgO_.mjs → HostingerProvider-DSHpNBim.mjs} +2 -2
  12. package/dist/{HostingerProvider-CgMuKgO_.mjs.map → HostingerProvider-DSHpNBim.mjs.map} +1 -1
  13. package/dist/{LegacyStateStore-Dx65SWE9.mjs → LegacyStateStore-Bd2I3zz7.mjs} +3 -3
  14. package/dist/{LegacyStateStore-Dx65SWE9.mjs.map → LegacyStateStore-Bd2I3zz7.mjs.map} +1 -1
  15. package/dist/{LegacyStateStore-6xskEtld.cjs → LegacyStateStore-DzRGMFhs.cjs} +3 -3
  16. package/dist/{LegacyStateStore-6xskEtld.cjs.map → LegacyStateStore-DzRGMFhs.cjs.map} +1 -1
  17. package/dist/{LocalStateStore-DFtTtHty.cjs → LocalStateStore-Ci_tzIfp.cjs} +2 -2
  18. package/dist/{LocalStateStore-DFtTtHty.cjs.map → LocalStateStore-Ci_tzIfp.cjs.map} +1 -1
  19. package/dist/{LocalStateStore-Dto39TCx.mjs → LocalStateStore-CzNrVQd2.mjs} +2 -2
  20. package/dist/{LocalStateStore-Dto39TCx.mjs.map → LocalStateStore-CzNrVQd2.mjs.map} +1 -1
  21. package/dist/{OpenApiTsGenerator-B-PQLx8X.mjs → OpenApiTsGenerator-BTMuu1WS.mjs} +2 -2
  22. package/dist/{OpenApiTsGenerator-B-PQLx8X.mjs.map → OpenApiTsGenerator-BTMuu1WS.mjs.map} +1 -1
  23. package/dist/{OpenApiTsGenerator-BvacdbiG.cjs → OpenApiTsGenerator-CI-tceXV.cjs} +2 -2
  24. package/dist/{OpenApiTsGenerator-BvacdbiG.cjs.map → OpenApiTsGenerator-CI-tceXV.cjs.map} +1 -1
  25. package/dist/{S3StateStore-C01zMOYm.mjs → S3StateStore-DVtcCMEc.mjs} +4 -4
  26. package/dist/{S3StateStore-C01zMOYm.mjs.map → S3StateStore-DVtcCMEc.mjs.map} +1 -1
  27. package/dist/{S3StateStore-B-9ea-sX.cjs → S3StateStore-LrKb9lH7.cjs} +5 -5
  28. package/dist/{S3StateStore-B-9ea-sX.cjs.map → S3StateStore-LrKb9lH7.cjs.map} +1 -1
  29. package/dist/{SSMStateStore-k-4XM7mb.mjs → SSMStateStore-CNHYH6g7.mjs} +2 -2
  30. package/dist/{SSMStateStore-k-4XM7mb.mjs.map → SSMStateStore-CNHYH6g7.mjs.map} +1 -1
  31. package/dist/{SSMStateStore-CKArcPUh.cjs → SSMStateStore-CpkvL95K.cjs} +2 -2
  32. package/dist/{SSMStateStore-CKArcPUh.cjs.map → SSMStateStore-CpkvL95K.cjs.map} +1 -1
  33. package/dist/{SubscriberGenerator-DR4Y7ihK.cjs → SubscriberGenerator-BNJyPmXJ.cjs} +3 -3
  34. package/dist/{SubscriberGenerator-DR4Y7ihK.cjs.map → SubscriberGenerator-BNJyPmXJ.cjs.map} +1 -1
  35. package/dist/{SubscriberGenerator-DLPH-ynS.mjs → SubscriberGenerator-CzPrixYu.mjs} +3 -3
  36. package/dist/{SubscriberGenerator-DLPH-ynS.mjs.map → SubscriberGenerator-CzPrixYu.mjs.map} +1 -1
  37. package/dist/{add-BgzsYxUq.cjs → add-AlV6_ljM.cjs} +18 -17
  38. package/dist/{add-BgzsYxUq.cjs.map → add-AlV6_ljM.cjs.map} +1 -1
  39. package/dist/{add-CiIrpOb9.mjs → add-B51nMuUd.mjs} +8 -7
  40. package/dist/{add-CiIrpOb9.mjs.map → add-B51nMuUd.mjs.map} +1 -1
  41. package/dist/apps-C1KiJqth.mjs +4593 -0
  42. package/dist/apps-C1KiJqth.mjs.map +1 -0
  43. package/dist/apps-CPdR2pYw.cjs +5002 -0
  44. package/dist/apps-CPdR2pYw.cjs.map +1 -0
  45. package/dist/{bundler-DKxuDoVL.cjs → bundler-B-hw8rJi.cjs} +33 -9
  46. package/dist/bundler-B-hw8rJi.cjs.map +1 -0
  47. package/dist/{bundler-C4uMSy8e.mjs → bundler-DbIt3a6I.mjs} +34 -10
  48. package/dist/bundler-DbIt3a6I.mjs.map +1 -0
  49. package/dist/{cli-na0npMhC.cjs → cli-6eYxU_Q2.cjs} +4 -4
  50. package/dist/{cli-na0npMhC.cjs.map → cli-6eYxU_Q2.cjs.map} +1 -1
  51. package/dist/{cli-Bm2is6R_.mjs → cli-CmmrPCM_.mjs} +4 -4
  52. package/dist/{cli-Bm2is6R_.mjs.map → cli-CmmrPCM_.mjs.map} +1 -1
  53. package/dist/compose-B2dCLbrc.cjs +1895 -0
  54. package/dist/compose-B2dCLbrc.cjs.map +1 -0
  55. package/dist/{compose-CVatM7Cl.mjs → compose-DVARqEeR.mjs} +16 -1830
  56. package/dist/compose-DVARqEeR.mjs.map +1 -0
  57. package/dist/{compose-D8U9ygdm.cjs → compose-D_fNsrkx.cjs} +101 -1969
  58. package/dist/compose-D_fNsrkx.cjs.map +1 -0
  59. package/dist/compose-kOpW9Pa1.mjs +1554 -0
  60. package/dist/compose-kOpW9Pa1.mjs.map +1 -0
  61. package/dist/config-BKpzKP6W.mjs +659 -0
  62. package/dist/config-BKpzKP6W.mjs.map +1 -0
  63. package/dist/config-QAqAEgb0.cjs +772 -0
  64. package/dist/config-QAqAEgb0.cjs.map +1 -0
  65. package/dist/config.cjs +16 -419
  66. package/dist/config.mjs +2 -405
  67. package/dist/{credentialSchemas-DZ2Nh5li.cjs → credentialSchemas-BAklWDna.cjs} +4 -5
  68. package/dist/{credentialSchemas-DZ2Nh5li.cjs.map → credentialSchemas-BAklWDna.cjs.map} +1 -1
  69. package/dist/{credentialSchemas-DUCSYl9a.mjs → credentialSchemas-mz9QZTYh.mjs} +2 -3
  70. package/dist/{credentialSchemas-DUCSYl9a.mjs.map → credentialSchemas-mz9QZTYh.mjs.map} +1 -1
  71. package/dist/credentials-CIpa4Hgs.cjs +2336 -0
  72. package/dist/credentials-CIpa4Hgs.cjs.map +1 -0
  73. package/dist/credentials-CWa7hRXd.mjs +1851 -0
  74. package/dist/credentials-CWa7hRXd.mjs.map +1 -0
  75. package/dist/{databases-P824RTnx.cjs → databases-DawSdqBI.cjs} +2 -2
  76. package/dist/{databases-P824RTnx.cjs.map → databases-DawSdqBI.cjs.map} +1 -1
  77. package/dist/{databases-Db48ZIXL.mjs → databases-mzSUFBTw.mjs} +2 -2
  78. package/dist/{databases-Db48ZIXL.mjs.map → databases-mzSUFBTw.mjs.map} +1 -1
  79. package/dist/deploy/public.cjs +24 -24
  80. package/dist/deploy/public.cjs.map +1 -1
  81. package/dist/deploy/public.d.cts.map +1 -1
  82. package/dist/deploy/public.d.mts.map +1 -1
  83. package/dist/deploy/public.mjs +13 -13
  84. package/dist/{deploy-DrQB7ytj.cjs → deploy-CjJ447kd.cjs} +73 -72
  85. package/dist/{deploy-DrQB7ytj.cjs.map → deploy-CjJ447kd.cjs.map} +1 -1
  86. package/dist/{deploy-CDcO08Xz.mjs → deploy-DqJiCwI9.mjs} +16 -15
  87. package/dist/{deploy-CDcO08Xz.mjs.map → deploy-DqJiCwI9.mjs.map} +1 -1
  88. package/dist/{discover-yqeJ2Bx7.cjs → discover-CRywE7yc.cjs} +157 -6
  89. package/dist/discover-CRywE7yc.cjs.map +1 -0
  90. package/dist/{discover-B2m8ytyq.mjs → discover-DbDrCQ8h.mjs} +117 -8
  91. package/dist/discover-DbDrCQ8h.mjs.map +1 -0
  92. package/dist/docker-CCzFCus7.mjs +1407 -0
  93. package/dist/docker-CCzFCus7.mjs.map +1 -0
  94. package/dist/docker-DK4rmb0u.cjs +1514 -0
  95. package/dist/docker-DK4rmb0u.cjs.map +1 -0
  96. package/dist/{dokploy-k4_ZN8zN.mjs → dokploy-B5_Y5wf0.mjs} +2 -2
  97. package/dist/{dokploy-k4_ZN8zN.mjs.map → dokploy-B5_Y5wf0.mjs.map} +1 -1
  98. package/dist/{dokploy-BKjPDvSN.cjs → dokploy-EJKX2T7M.cjs} +2 -2
  99. package/dist/{dokploy-BKjPDvSN.cjs.map → dokploy-EJKX2T7M.cjs.map} +1 -1
  100. package/dist/{drivers-C47nm-wB.cjs → drivers-aM87NQJi.cjs} +4 -91
  101. package/dist/drivers-aM87NQJi.cjs.map +1 -0
  102. package/dist/{drivers-CDjpjakg.mjs → drivers-uxLBq3e3.mjs} +3 -60
  103. package/dist/drivers-uxLBq3e3.mjs.map +1 -0
  104. package/dist/{eas-Bg4dI6n2.cjs → eas-AqSay-vE.cjs} +6 -6
  105. package/dist/{eas-Bg4dI6n2.cjs.map → eas-AqSay-vE.cjs.map} +1 -1
  106. package/dist/{eas-B1wBvwPH.mjs → eas-BQlD6Z-u.mjs} +3 -3
  107. package/dist/{eas-B1wBvwPH.mjs.map → eas-BQlD6Z-u.mjs.map} +1 -1
  108. package/dist/{encryption-DL_y8t6V.cjs → encryption-B6_aL5d-.cjs} +6 -6
  109. package/dist/{encryption-DL_y8t6V.cjs.map → encryption-B6_aL5d-.cjs.map} +1 -1
  110. package/dist/{encryption-Bve0PVOo.mjs → encryption-Dlh5mcE1.mjs} +3 -3
  111. package/dist/{encryption-Bve0PVOo.mjs.map → encryption-Dlh5mcE1.mjs.map} +1 -1
  112. package/dist/{engine-BhR5lt_V.cjs → engine-BAkmPI2z.cjs} +99 -97
  113. package/dist/{engine-BhR5lt_V.cjs.map → engine-BAkmPI2z.cjs.map} +1 -1
  114. package/dist/{engine-HMLf20iZ.mjs → engine-D3P2P6RK.mjs} +12 -10
  115. package/dist/{engine-HMLf20iZ.mjs.map → engine-D3P2P6RK.mjs.map} +1 -1
  116. package/dist/{github-B2hJVl-n.cjs → github-DokGIXT-.cjs} +18 -17
  117. package/dist/{github-B2hJVl-n.cjs.map → github-DokGIXT-.cjs.map} +1 -1
  118. package/dist/{github-DKn9ACi2.mjs → github-STWxD6cu.mjs} +9 -8
  119. package/dist/{github-DKn9ACi2.mjs.map → github-STWxD6cu.mjs.map} +1 -1
  120. package/dist/{googlePlay-DtuN0-7D.cjs → googlePlay-DL0htRJD.cjs} +5 -5
  121. package/dist/{googlePlay-DtuN0-7D.cjs.map → googlePlay-DL0htRJD.cjs.map} +1 -1
  122. package/dist/{googlePlay-CWq7ND_X.mjs → googlePlay-uAyXzxlu.mjs} +5 -5
  123. package/dist/{googlePlay-CWq7ND_X.mjs.map → googlePlay-uAyXzxlu.mjs.map} +1 -1
  124. package/dist/index.cjs +196 -192
  125. package/dist/index.cjs.map +1 -1
  126. package/dist/index.mjs +70 -66
  127. package/dist/index.mjs.map +1 -1
  128. package/dist/{local-OPC9BCZt.cjs → local-C6ndR_Wx.cjs} +6 -6
  129. package/dist/{local-OPC9BCZt.cjs.map → local-C6ndR_Wx.cjs.map} +1 -1
  130. package/dist/{local-B7Zv1NoA.mjs → local-CC7rdmgg.mjs} +3 -3
  131. package/dist/{local-B7Zv1NoA.mjs.map → local-CC7rdmgg.mjs.map} +1 -1
  132. package/dist/{migrate-BLVZqHtN.cjs → migrate-BbJUJ4CY.cjs} +6 -6
  133. package/dist/{migrate-BLVZqHtN.cjs.map → migrate-BbJUJ4CY.cjs.map} +1 -1
  134. package/dist/{migrate-iUui7B4q.cjs → migrate-CMurhHuj.cjs} +15 -13
  135. package/dist/{migrate-iUui7B4q.cjs.map → migrate-CMurhHuj.cjs.map} +1 -1
  136. package/dist/{migrate-W0ruUNb9.mjs → migrate-D079sADO.mjs} +3 -3
  137. package/dist/{migrate-W0ruUNb9.mjs.map → migrate-D079sADO.mjs.map} +1 -1
  138. package/dist/{migrate-DCvD4RJW.mjs → migrate-D27h4H79.mjs} +7 -5
  139. package/dist/{migrate-DCvD4RJW.mjs.map → migrate-D27h4H79.mjs.map} +1 -1
  140. package/dist/notes-B655tUny.cjs +500 -0
  141. package/dist/notes-B655tUny.cjs.map +1 -0
  142. package/dist/notes-wPJlNUj7.mjs +399 -0
  143. package/dist/notes-wPJlNUj7.mjs.map +1 -0
  144. package/dist/openapi.cjs +4 -5
  145. package/dist/openapi.cjs.map +1 -1
  146. package/dist/openapi.mjs +3 -4
  147. package/dist/openapi.mjs.map +1 -1
  148. package/dist/{projectBucket-BBbQ1lHF.cjs → projectBucket-Bs8ftcgB.cjs} +2 -2
  149. package/dist/{projectBucket-BBbQ1lHF.cjs.map → projectBucket-Bs8ftcgB.cjs.map} +1 -1
  150. package/dist/{projectBucket-C_DN4WzF.mjs → projectBucket-XVxyvW1y.mjs} +2 -2
  151. package/dist/{projectBucket-C_DN4WzF.mjs.map → projectBucket-XVxyvW1y.mjs.map} +1 -1
  152. package/dist/{publish-CxIBBD3b.mjs → publish-B9BNIaf2.mjs} +2 -2
  153. package/dist/{publish-CxIBBD3b.mjs.map → publish-B9BNIaf2.mjs.map} +1 -1
  154. package/dist/{publish-CqvDA5ry.cjs → publish-Bwgb-1JN.cjs} +2 -2
  155. package/dist/{publish-CqvDA5ry.cjs.map → publish-Bwgb-1JN.cjs.map} +1 -1
  156. package/dist/{ready-DuU0FXSj.cjs → ready-BNh3zsSn.cjs} +6 -6
  157. package/dist/{ready-DuU0FXSj.cjs.map → ready-BNh3zsSn.cjs.map} +1 -1
  158. package/dist/{ready-CGqJ74Kt.mjs → ready-g25dcGzK.mjs} +6 -6
  159. package/dist/{ready-CGqJ74Kt.mjs.map → ready-g25dcGzK.mjs.map} +1 -1
  160. package/dist/reconcile/public.cjs +1 -1
  161. package/dist/reconcile/public.mjs +1 -1
  162. package/dist/{resolve-CMC0MI0Z.mjs → resolve-DheFxtmy.mjs} +4 -4
  163. package/dist/{resolve-CMC0MI0Z.mjs.map → resolve-DheFxtmy.mjs.map} +1 -1
  164. package/dist/{resolve-BEVVvi13.cjs → resolve-Dir9EjMu.cjs} +4 -4
  165. package/dist/{resolve-BEVVvi13.cjs.map → resolve-Dir9EjMu.cjs.map} +1 -1
  166. package/dist/{rollback-CZiQkukY.mjs → rollback-BWAB77F9.mjs} +8 -8
  167. package/dist/{rollback-CZiQkukY.mjs.map → rollback-BWAB77F9.mjs.map} +1 -1
  168. package/dist/{rollback-e0zGkaBx.cjs → rollback-CrtuUKqe.cjs} +11 -11
  169. package/dist/{rollback-e0zGkaBx.cjs.map → rollback-CrtuUKqe.cjs.map} +1 -1
  170. package/dist/{s3-BKnL6YGQ.cjs → s3-DKJfDHUQ.cjs} +2 -2
  171. package/dist/{s3-BKnL6YGQ.cjs.map → s3-DKJfDHUQ.cjs.map} +1 -1
  172. package/dist/{s3-DW7SLsb8.mjs → s3-DNp8U0Ea.mjs} +2 -2
  173. package/dist/{s3-DW7SLsb8.mjs.map → s3-DNp8U0Ea.mjs.map} +1 -1
  174. package/dist/sandbox/credentials-worker.cjs +3 -4
  175. package/dist/sandbox/credentials-worker.cjs.map +1 -1
  176. package/dist/sandbox/credentials-worker.mjs +2 -3
  177. package/dist/sandbox/credentials-worker.mjs.map +1 -1
  178. package/dist/sandbox/discover-worker.cjs +1 -1
  179. package/dist/sandbox/discover-worker.mjs +1 -1
  180. package/dist/sandbox/migrate-worker.cjs +3 -4
  181. package/dist/sandbox/migrate-worker.cjs.map +1 -1
  182. package/dist/sandbox/migrate-worker.mjs +2 -3
  183. package/dist/sandbox/migrate-worker.mjs.map +1 -1
  184. package/dist/seeds-B3xvUAQf.cjs +363 -0
  185. package/dist/seeds-B3xvUAQf.cjs.map +1 -0
  186. package/dist/seeds-BCC8vAXR.mjs +298 -0
  187. package/dist/seeds-BCC8vAXR.mjs.map +1 -0
  188. package/dist/{serverSetup-D2Xzsp2t.cjs → serverSetup-BVL9HhNE.cjs} +9 -8
  189. package/dist/{serverSetup-D2Xzsp2t.cjs.map → serverSetup-BVL9HhNE.cjs.map} +1 -1
  190. package/dist/{serverSetup-C3Tt9X1R.mjs → serverSetup-D---hcyW.mjs} +7 -6
  191. package/dist/{serverSetup-C3Tt9X1R.mjs.map → serverSetup-D---hcyW.mjs.map} +1 -1
  192. package/dist/{sniffer-BWgXPFAt.cjs → sniffer-BjHnOaCe.cjs} +9 -10
  193. package/dist/{sniffer-BWgXPFAt.cjs.map → sniffer-BjHnOaCe.cjs.map} +1 -1
  194. package/dist/{sniffer-eEF_fIId.mjs → sniffer-DOyzfgPF.mjs} +8 -9
  195. package/dist/{sniffer-eEF_fIId.mjs.map → sniffer-DOyzfgPF.mjs.map} +1 -1
  196. package/dist/{snsSubscriptions-BSoqUgsq.mjs → snsSubscriptions-Cf5DZfO5.mjs} +4 -453
  197. package/dist/snsSubscriptions-Cf5DZfO5.mjs.map +1 -0
  198. package/dist/{snsSubscriptions-Y9declDd.cjs → snsSubscriptions-DB0iRByH.cjs} +12 -559
  199. package/dist/snsSubscriptions-DB0iRByH.cjs.map +1 -0
  200. package/dist/{sst-Bz2HJlqc.mjs → sst-3V-rcKcw.mjs} +27 -5
  201. package/dist/sst-3V-rcKcw.mjs.map +1 -0
  202. package/dist/{sst-lvCHdYsY.cjs → sst-DuU7Ju0c.cjs} +29 -7
  203. package/dist/sst-DuU7Ju0c.cjs.map +1 -0
  204. package/dist/stack-BRKZ69bf.mjs +2307 -0
  205. package/dist/stack-BRKZ69bf.mjs.map +1 -0
  206. package/dist/stack-CmHjkg7D.cjs +2536 -0
  207. package/dist/stack-CmHjkg7D.cjs.map +1 -0
  208. package/dist/{stage-DhcbcAar.mjs → stage-CTq3Gjsx.mjs} +7 -7
  209. package/dist/{stage-DhcbcAar.mjs.map → stage-CTq3Gjsx.mjs.map} +1 -1
  210. package/dist/{stage-BEcxppsu.cjs → stage-s_8HOsH0.cjs} +13 -13
  211. package/dist/{stage-BEcxppsu.cjs.map → stage-s_8HOsH0.cjs.map} +1 -1
  212. package/dist/{stages--icWbhPy.cjs → stages-CFI0OiLj.cjs} +2 -2
  213. package/dist/{stages--icWbhPy.cjs.map → stages-CFI0OiLj.cjs.map} +1 -1
  214. package/dist/{stages-CUwSy39f.mjs → stages-DoYa81kN.mjs} +2 -2
  215. package/dist/{stages-CUwSy39f.mjs.map → stages-DoYa81kN.mjs.map} +1 -1
  216. package/dist/target/public.cjs +1 -1
  217. package/dist/target/public.mjs +1 -1
  218. package/dist/{terminal-DURcYlVX.cjs → terminal-ChxtuTYJ.cjs} +3 -3
  219. package/dist/{terminal-DURcYlVX.cjs.map → terminal-ChxtuTYJ.cjs.map} +1 -1
  220. package/dist/{terminal-yOZ7kKF9.mjs → terminal-oHKnZHkT.mjs} +3 -3
  221. package/dist/{terminal-yOZ7kKF9.mjs.map → terminal-oHKnZHkT.mjs.map} +1 -1
  222. package/dist/types-Bl_CwZC9.cjs +90 -0
  223. package/dist/types-Bl_CwZC9.cjs.map +1 -0
  224. package/dist/types-Y1NfWlyG.mjs +61 -0
  225. package/dist/types-Y1NfWlyG.mjs.map +1 -0
  226. package/dist/vitest.cjs +1 -1
  227. package/dist/vitest.mjs +1 -1
  228. package/package.json +15 -15
  229. package/dist/bundler-C4uMSy8e.mjs.map +0 -1
  230. package/dist/bundler-DKxuDoVL.cjs.map +0 -1
  231. package/dist/compose-CVatM7Cl.mjs.map +0 -1
  232. package/dist/compose-D8U9ygdm.cjs.map +0 -1
  233. package/dist/config.cjs.map +0 -1
  234. package/dist/config.mjs.map +0 -1
  235. package/dist/credentials-D7XJypNd.cjs +0 -520
  236. package/dist/credentials-D7XJypNd.cjs.map +0 -1
  237. package/dist/credentials-DpfnUvIR.mjs +0 -395
  238. package/dist/credentials-DpfnUvIR.mjs.map +0 -1
  239. package/dist/derive-Cd7Hl3r2.mjs +0 -259
  240. package/dist/derive-Cd7Hl3r2.mjs.map +0 -1
  241. package/dist/derive-CgZfoBU2.cjs +0 -282
  242. package/dist/derive-CgZfoBU2.cjs.map +0 -1
  243. package/dist/discover-B2m8ytyq.mjs.map +0 -1
  244. package/dist/discover-yqeJ2Bx7.cjs.map +0 -1
  245. package/dist/drivers-C47nm-wB.cjs.map +0 -1
  246. package/dist/drivers-CDjpjakg.mjs.map +0 -1
  247. package/dist/identity-CBXr4wNi.mjs +0 -129
  248. package/dist/identity-CBXr4wNi.mjs.map +0 -1
  249. package/dist/identity-CbLfgQNT.cjs +0 -182
  250. package/dist/identity-CbLfgQNT.cjs.map +0 -1
  251. package/dist/sandbox-CHv3OYXg.cjs +0 -165
  252. package/dist/sandbox-CHv3OYXg.cjs.map +0 -1
  253. package/dist/sandbox-CbVB7uOD.mjs +0 -118
  254. package/dist/sandbox-CbVB7uOD.mjs.map +0 -1
  255. package/dist/seeds-BR_7hJTw.cjs +0 -10541
  256. package/dist/seeds-BR_7hJTw.cjs.map +0 -1
  257. package/dist/seeds-nCxxlP5h.mjs +0 -9418
  258. package/dist/seeds-nCxxlP5h.mjs.map +0 -1
  259. package/dist/snsSubscriptions-BSoqUgsq.mjs.map +0 -1
  260. package/dist/snsSubscriptions-Y9declDd.cjs.map +0 -1
  261. package/dist/sst-Bz2HJlqc.mjs.map +0 -1
  262. package/dist/sst-lvCHdYsY.cjs.map +0 -1
@@ -0,0 +1,2536 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-DMC4Umsb.cjs");
3
+ const require_credentials = require("./credentials-CIpa4Hgs.cjs");
4
+ const require_workspace = require("./workspace-Dkm3HL9e.cjs");
5
+ const require_compose = require("./compose-B2dCLbrc.cjs");
6
+ const require_apps = require("./apps-CPdR2pYw.cjs");
7
+ const require_SubscriberGenerator = require("./SubscriberGenerator-BNJyPmXJ.cjs");
8
+ const require_config = require("./config-QAqAEgb0.cjs");
9
+ const require_types = require("./types-Bl_CwZC9.cjs");
10
+ const require_notes = require("./notes-B655tUny.cjs");
11
+ const require_docker = require("./docker-DK4rmb0u.cjs");
12
+ let node_path = require("node:path");
13
+ let node_fs = require("node:fs");
14
+ let node_crypto = require("node:crypto");
15
+ let _geekmidas_manifest = require("@geekmidas/manifest");
16
+ let node_module = require("node:module");
17
+ let node_url = require("node:url");
18
+ let yaml = require("yaml");
19
+ let bcryptjs = require("bcryptjs");
20
+ bcryptjs = require_rolldown_runtime.__toESM(bcryptjs, 1);
21
+ //#region src/providers/dns.ts
22
+ /** Whether the workspace deploys through the compose target. */
23
+ function deploysWithCompose(workspace) {
24
+ return workspace.deploy?.default === "compose" || Object.values(workspace.apps).some((app) => app.resolvedDeployTarget === "compose");
25
+ }
26
+ //#endregion
27
+ //#region src/backups/config.ts
28
+ /**
29
+ * Which stages take backups, and where they are kept.
30
+ *
31
+ * A deployed compose stage whose stack runs Postgres is backed up by
32
+ * default — every day at 02:00 UTC, kept 30 days — unless
33
+ * `deploy.backups.<stage>` says otherwise. The local stage never is.
34
+ *
35
+ * Every backup is kept in the project bucket (`providers/projectBucket.ts`),
36
+ * beside the stage's deploy state, one folder per run and one file per
37
+ * database:
38
+ *
39
+ * ```
40
+ * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/database.sql.gz
41
+ * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/auth-database.sql.gz
42
+ * ```
43
+ *
44
+ * The file is named after the database's construct, the way its migrations
45
+ * folder is: `AuthDatabase` is `db/auth-database`, and `auth-database.sql.gz`.
46
+ */
47
+ /** Whether the stack runs Postgres: some construct is a database. */
48
+ function runsPostgres(manifest) {
49
+ return Object.values(manifest).some((d) => d.kind === "database");
50
+ }
51
+ /**
52
+ * What `stage`'s backups are: on — by its entry or the default — off by
53
+ * `false`, or none, for the local stage, a stage compose does not deploy,
54
+ * and a stack with no database.
55
+ */
56
+ function stageBackups(workspace, manifest, stage) {
57
+ if (stage === workspace.stages?.local) return {
58
+ mode: "none",
59
+ reason: "local"
60
+ };
61
+ if (!deploysWithCompose(workspace)) return {
62
+ mode: "none",
63
+ reason: "not-compose"
64
+ };
65
+ if (!runsPostgres(manifest)) return {
66
+ mode: "none",
67
+ reason: "no-postgres"
68
+ };
69
+ const value = (workspace.deploy?.backups)?.[stage];
70
+ const checked = require_workspace.checkStageBackups(stage, value ?? {});
71
+ if (checked === false) return { mode: "disabled" };
72
+ return {
73
+ mode: "on",
74
+ backups: checked,
75
+ source: value === void 0 ? "default" : "config"
76
+ };
77
+ }
78
+ /**
79
+ * Where a stage's backups are, in the project bucket — under the same
80
+ * `<prefix>/<project>/<stage>` its deploy state is: `gkm/shop/production/backups`.
81
+ */
82
+ function backupsPrefix(workspace, stage) {
83
+ const state = workspace.state;
84
+ const prefix = state?.provider === "s3" && state.prefix !== void 0 ? state.prefix.replace(/\/+$/, "") : "gkm";
85
+ return `${prefix ? `${prefix}/` : ""}${workspace.name}/${stage}/backups`;
86
+ }
87
+ /** A run folder's time back, or `undefined` for a key that is not one. */
88
+ function runTime(folder) {
89
+ const match = /^(\d{4}-\d{2}-\d{2})\/(\d{2})-(\d{2})-(\d{2})Z$/.exec(folder);
90
+ if (!match) return void 0;
91
+ const at = /* @__PURE__ */ new Date(`${match[1]}T${match[2]}:${match[3]}:${match[4]}Z`);
92
+ return Number.isNaN(at.getTime()) ? void 0 : at;
93
+ }
94
+ /** A database's file in a run's folder: `auth-database.sql.gz`. */
95
+ function backupFile(database) {
96
+ return `${database.file}.sql.gz`;
97
+ }
98
+ /** Each database the stack runs, by its construct and its name in Postgres. */
99
+ function backupDatabases(resources) {
100
+ return resources.filter((r) => r.kind === "database").map((r) => ({
101
+ id: r.id,
102
+ file: (0, _geekmidas_manifest.kebabCase)(r.id),
103
+ name: r.name
104
+ })).sort((a, b) => a.file.localeCompare(b.file));
105
+ }
106
+ /**
107
+ * The expiry of every stage's backups, by each stage's own entry — what the
108
+ * project bucket's lifecycle carries beside its own rule.
109
+ *
110
+ * A put replaces a bucket's whole lifecycle, so this is built from every
111
+ * deployed stage each time, never from the stage being deployed alone: one
112
+ * stage's deploy keeps every other's rule. A stage set to `false` has none,
113
+ * and its backups are kept until someone deletes them.
114
+ */
115
+ function backupExpiries(workspace, manifest) {
116
+ const expiries = [];
117
+ for (const stage of [...workspace.stages?.deployed ?? []].sort()) {
118
+ const choice = stageBackups(workspace, manifest, stage);
119
+ if (choice.mode !== "on") continue;
120
+ expiries.push({
121
+ id: `gkm-backups-${stage}`,
122
+ prefix: `${backupsPrefix(workspace, stage)}/`,
123
+ days: choice.backups.keepDays,
124
+ abortIncompleteDays: 1
125
+ });
126
+ }
127
+ return expiries;
128
+ }
129
+ //#endregion
130
+ //#region src/backups/service.ts
131
+ /**
132
+ * The stack's `backups` service: what a deployed compose stage with Postgres
133
+ * runs beside its apps, unless `deploy.backups.<stage>` is `false`.
134
+ *
135
+ * - **The image** is built from the stack's own Postgres image —
136
+ * `postgres:<major>-alpine`, already on the server for the stack, and with
137
+ * the `pg_dump` that matches the server — with Node added and gkm's runner
138
+ * (`runner.ts`) copied in. Nothing is pulled that the stack does not have,
139
+ * and nothing is mounted from the host: the build context is two files.
140
+ * - **Its key** is `BACKUPS_URL`, from the stage's secrets, like any app's:
141
+ * allowed to put objects under the stage's backups prefix and nothing else.
142
+ * The server holds no AWS credentials of its own.
143
+ * - **Its login** is a role of its own, `<project>_backups`, granted
144
+ * `pg_read_all_data` — it can read every database and write none. Postgres
145
+ * before 14 has no such role, and there it signs in as the stack's
146
+ * superuser.
147
+ * - **Its health** is the last good run: unhealthy once that is more than
148
+ * twice the schedule's longest gap old, after a startup grace.
149
+ */
150
+ /** The service's name in the stack. */
151
+ const BACKUPS_SERVICE = "backups";
152
+ /** The secret its key is written to. */
153
+ const BACKUPS_URL_KEY = "BACKUPS_URL";
154
+ /** Where the runner is, in the image. */
155
+ const RUNNER_PATH = "/gkm/backup.mjs";
156
+ /** The first Postgres with `pg_read_all_data`. */
157
+ const READ_ALL_DATA_SINCE = 14;
158
+ /** A stage that backs up, and no key to back up with. */
159
+ var BackupsUrlMissing = class extends require_errors.GkmError {
160
+ stage;
161
+ constructor(stage) {
162
+ super(`'${stage}' runs Postgres, so its stack backs it up, and its secrets hold no ${BACKUPS_URL_KEY} to back up with. The deploy writes it — the IAM user and key it creates in the stage's AWS account — so run the deploy with the account's credentials. To take no backups on this stage, set deploy.backups.${stage}: false.`);
163
+ this.stage = stage;
164
+ this.name = "BackupsUrlMissing";
165
+ }
166
+ };
167
+ /** The backups role: `<project>_backups`, as the superuser is `<project>_admin`. */
168
+ function backupsRole(project) {
169
+ return `${require_compose.postgresRoleSlug(project)}_backups`;
170
+ }
171
+ /**
172
+ * The runner's source, as JavaScript: the built `backups/runner.mjs` beside
173
+ * the CLI's bundle, or — run from source — `runner.ts`, with its types
174
+ * stripped by esbuild.
175
+ */
176
+ function runnerSource() {
177
+ const here = (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
178
+ for (const path of [
179
+ (0, node_path.join)(here, "backups", "runner.mjs"),
180
+ (0, node_path.join)(here, "runner.mjs"),
181
+ (0, node_path.join)(here, "..", "backups", "runner.mjs")
182
+ ]) if ((0, node_fs.existsSync)(path)) return (0, node_fs.readFileSync)(path, "utf-8");
183
+ const { transformSync } = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("esbuild");
184
+ return transformSync((0, node_fs.readFileSync)((0, node_path.join)(here, "runner.ts"), "utf-8"), {
185
+ loader: "ts",
186
+ format: "esm",
187
+ target: "node22"
188
+ }).code;
189
+ }
190
+ /** The image's Dockerfile: the stack's Postgres, Node, and the runner. */
191
+ function backupsDockerfile(from) {
192
+ return `# Generated by gkm — the stage's backups: pg_dump from ${from}, and gkm's uploader.
193
+ FROM ${from}
194
+ RUN apk add --no-cache nodejs
195
+ COPY backup.mjs ${RUNNER_PATH}
196
+ USER postgres
197
+ ENTRYPOINT []
198
+ CMD ["node", "${RUNNER_PATH}", "serve"]
199
+ `;
200
+ }
201
+ /**
202
+ * The stack's backups service, for a stage whose backups are on.
203
+ *
204
+ * @throws {BackupsUrlMissing} when the stage's secrets hold no key
205
+ */
206
+ function stackBackups(input) {
207
+ const { plan, stage } = input;
208
+ const version = plan.resources.find((r) => r.version)?.version ?? _geekmidas_manifest.DEFAULT_POSTGRES_VERSION;
209
+ const from = require_compose.postgresImage(version);
210
+ const script = runnerSource();
211
+ const dockerfile = backupsDockerfile(from);
212
+ const hash = (0, node_crypto.createHash)("sha256").update(dockerfile).update(script).digest("hex").slice(0, 12);
213
+ const readOnly = version >= READ_ALL_DATA_SINCE;
214
+ const role = backupsRole(input.workspace.name);
215
+ const login = readOnly ? {
216
+ user: role,
217
+ password: require_apps.localRolePassword(input.workspace.name, plan, role, input.seed)
218
+ } : input.superuser;
219
+ const databases = backupDatabases(plan.resources);
220
+ const prefix = backupsPrefix(input.workspace, stage);
221
+ const { kind, ...schedule } = input.backups.schedule;
222
+ let env = {};
223
+ if (!input.buildOnly) {
224
+ const url = input.custom[BACKUPS_URL_KEY];
225
+ if (!url) throw new BackupsUrlMissing(stage);
226
+ env = {
227
+ BACKUPS_URL: url,
228
+ BACKUPS_PREFIX: prefix,
229
+ BACKUPS_DATABASES: JSON.stringify(databases.map(({ file, name }) => ({
230
+ file,
231
+ name
232
+ }))),
233
+ BACKUPS_SCHEDULE: JSON.stringify(kind === "cron" ? {
234
+ kind,
235
+ minutes: input.backups.schedule.minutes,
236
+ hours: input.backups.schedule.hours,
237
+ days: input.backups.schedule.days,
238
+ months: input.backups.schedule.months,
239
+ weekdays: input.backups.schedule.weekdays
240
+ } : {
241
+ kind,
242
+ ...schedule
243
+ }),
244
+ BACKUPS_MAX_GAP_SECONDS: String(input.backups.maxGapSeconds),
245
+ PGHOST: "postgres",
246
+ PGPORT: "5432",
247
+ PGUSER: login.user,
248
+ PGPASSWORD: login.password,
249
+ ...input.telemetry?.OTEL_EXPORTER_OTLP_ENDPOINT ? {
250
+ OTEL_EXPORTER_OTLP_ENDPOINT: input.telemetry.OTEL_EXPORTER_OTLP_ENDPOINT,
251
+ ...input.telemetry.OTEL_EXPORTER_OTLP_HEADERS ? { OTEL_EXPORTER_OTLP_HEADERS: input.telemetry.OTEL_EXPORTER_OTLP_HEADERS } : {},
252
+ OTEL_SERVICE_NAME: BACKUPS_SERVICE
253
+ } : {}
254
+ };
255
+ }
256
+ return {
257
+ backups: input.backups,
258
+ databases,
259
+ prefix,
260
+ from,
261
+ image: `${input.project}-backups:pg${version}-${hash}`,
262
+ files: {
263
+ Dockerfile: dockerfile,
264
+ "backup.mjs": script
265
+ },
266
+ login,
267
+ readOnly,
268
+ env
269
+ };
270
+ }
271
+ /** The service in the stack's compose file. */
272
+ function backupsService(backups, envFiles) {
273
+ return {
274
+ image: backups.image,
275
+ build: {
276
+ context: `./${BACKUPS_SERVICE}`,
277
+ dockerfile: "Dockerfile"
278
+ },
279
+ pull_policy: "build",
280
+ restart: "unless-stopped",
281
+ ...envFiles ? { env_file: [{
282
+ path: `./${BACKUPS_SERVICE}.env`,
283
+ format: "raw"
284
+ }] } : {},
285
+ depends_on: { postgres: { condition: "service_healthy" } },
286
+ healthcheck: {
287
+ test: [
288
+ "CMD",
289
+ "node",
290
+ RUNNER_PATH,
291
+ "health"
292
+ ],
293
+ interval: "1m",
294
+ timeout: "10s",
295
+ retries: 3,
296
+ start_period: "30s"
297
+ }
298
+ };
299
+ }
300
+ /**
301
+ * The backups role, created and kept: able to sign in and read every
302
+ * database, and nothing else. None when it signs in as the superuser.
303
+ */
304
+ function backupsRoleStatements(backups) {
305
+ if (!backups.readOnly) return [];
306
+ const role = require_apps.quoteIdentifier(backups.login.user);
307
+ const password = `'${backups.login.password.replace(/'/g, "''")}'`;
308
+ return [
309
+ {
310
+ id: BACKUPS_SERVICE,
311
+ describe: `role ${backups.login.user}`,
312
+ exists: {
313
+ sql: "SELECT 1 FROM pg_roles WHERE rolname = $1",
314
+ values: [backups.login.user]
315
+ },
316
+ create: `CREATE ROLE ${role} LOGIN PASSWORD ${password}`
317
+ },
318
+ {
319
+ id: BACKUPS_SERVICE,
320
+ describe: `role ${backups.login.user}: its password`,
321
+ create: `ALTER ROLE ${role} WITH LOGIN PASSWORD ${password}`
322
+ },
323
+ {
324
+ id: BACKUPS_SERVICE,
325
+ describe: `role ${backups.login.user}: read every database`,
326
+ create: `GRANT pg_read_all_data TO ${role}`
327
+ }
328
+ ];
329
+ }
330
+ //#endregion
331
+ //#region src/compose/routes.ts
332
+ /** A route with handlers and a check that would have to hold for each of them. */
333
+ var EdgeRouteConflict = class extends Error {
334
+ route;
335
+ constructor(route) {
336
+ 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.`);
337
+ this.route = route;
338
+ this.name = "EdgeRouteConflict";
339
+ }
340
+ };
341
+ /** @throws {EdgeRouteConflict} */
342
+ function assertRouteRenderable(route) {
343
+ if (route.handlers?.length && (route.allow || route.paths || route.prefixes || route.requireHeader)) throw new EdgeRouteConflict(route.name);
344
+ }
345
+ /** File descriptors a process holding sockets may open. */
346
+ const NOFILE = {
347
+ soft: 1048576,
348
+ hard: 1048576
349
+ };
350
+ /**
351
+ * What the edge runs with: a descriptor per socket, twice — the client's and
352
+ * the upstream's — and every local port for those upstream connections. One
353
+ * edge address to one upstream has only the ephemeral range to open
354
+ * connections from, ~28k by Linux's default; widened, ~64k per replica.
355
+ */
356
+ const EDGE_LIMITS = {
357
+ sysctls: { "net.ipv4.ip_local_port_range": "1024 65535" },
358
+ ulimits: { nofile: NOFILE }
359
+ };
360
+ //#endregion
361
+ //#region src/compose/caddyfile.ts
362
+ /**
363
+ * The stack's own edge, rendered for Caddy: one site block per route.
364
+ *
365
+ * Deployed, each host is the stage's real domain and Caddy gets it a
366
+ * certificate from Let's Encrypt on first request — the same automatic HTTPS
367
+ * it does anywhere, with nothing to configure but the name — or serves the
368
+ * stage's own certificate (`deploy.compose.tls`). Locally the hosts are
369
+ * `*.localhost` and the certificates come from Caddy's own CA, as the `gkm
370
+ * dev` edge does, so a local stack is `https://` like a deployed one.
371
+ *
372
+ * Pure: the routes are data (`routes.ts`), and rendering them is one string.
373
+ */
374
+ /** Where Caddy reads a stage's own certificate, inside its container. */
375
+ const CADDY_TLS_DIR = "/etc/caddy/tls";
376
+ /** An upstream on the stack's own network: its service name. */
377
+ function address({ service, port }) {
378
+ return `${service}:${port}`;
379
+ }
380
+ /** The Caddyfile for a stack's edge. */
381
+ function edgeCaddyfile(routes, options) {
382
+ const { tls } = options;
383
+ const ask = routes.find((route) => route.wildcard?.tls.kind === "on-demand")?.wildcard?.tls;
384
+ const onDemand = ask?.kind === "on-demand" ? `
385
+ on_demand_tls {
386
+ ask ${ask.ask}
387
+ }` : "";
388
+ const global = tls.kind === "internal" ? `{
389
+ # No ACME and no public DNS: the CA is Caddy's own and the names resolve
390
+ # to this machine.
391
+ local_certs
392
+ auto_https disable_redirects
393
+ }` : options.email || onDemand ? `{${options.email ? `\n\temail ${options.email}` : ""}${onDemand}
394
+ }` : "";
395
+ const certificate = tls.kind === "internal" ? `
396
+ tls internal
397
+ ` : tls.kind === "files" ? `
398
+ tls ${tls.certFile} ${tls.keyFile}
399
+ ` : "";
400
+ const blocks = [...routes.filter((route) => !route.wildcard), ...routes.filter((route) => route.wildcard)].map((route) => siteBlock(route, route.wildcard?.tls.kind === "on-demand" ? `
401
+ tls {
402
+ on_demand
403
+ }
404
+ ` : certificate));
405
+ return `${HEADER}${global ? `${global}\n\n` : ""}${blocks.join("\n\n")}\n`;
406
+ }
407
+ /** One route's site block. */
408
+ function siteBlock(route, certificate) {
409
+ assertRouteRenderable(route);
410
+ const { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;
411
+ const allowed = [...paths ?? [], ...(prefixes ?? []).map((prefix) => `${prefix}*`)];
412
+ const except = route.wildcard?.except ?? [];
413
+ const checks = `${except.length ? `
414
+ # Labels no tenant may take, although nothing in this stack answers them.
415
+ @protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(" ")}
416
+ respond @protected 404
417
+ ` : ""}${allow ? `
418
+ # Only these addresses — the peer Caddy sees, never a header a client
419
+ # could set. Everything else is refused before it reaches the upstream.
420
+ @denied not remote_ip ${allow.join(" ")}
421
+ respond @denied 403
422
+ ` : ""}${requireHeader ? `
423
+ # Only what the CDN sends: it adds this header to every request, and this
424
+ # host would be reached around the CDN otherwise.
425
+ @forged not header ${requireHeader.name} "${requireHeader.value}"
426
+ respond @forged 403
427
+ ` : ""}${auth ? `
428
+ # The stage's login, asked for before anything reaches the upstream.
429
+ basic_auth {
430
+ ${auth.user} ${auth.hash}
431
+ }
432
+ ` : ""}${allowed.length ? `
433
+ # Only these paths answer. Everything else on this host is refused before
434
+ # it reaches the upstream.
435
+ @elsewhere not path ${allowed.join(" ")}
436
+ respond @elsewhere 404
437
+ ` : ""}`;
438
+ const proxy = proxyBlock(route);
439
+ const body = handlers?.length ? `${handlers.map((handler, index) => `
440
+ # Answered by another service: ${handler.name}.
441
+ @handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(" ")}
442
+ handle @handler${index} {
443
+ reverse_proxy ${handler.upstreams.map(address).join(" ")}
444
+ }
445
+ `).join("")}
446
+ handle {${proxy.replace(/\n/g, "\n ")}
447
+ }` : proxy;
448
+ return `https://${host} {${certificate}
449
+ # gkm's own header, which only a service of this stack may send: the auth
450
+ # server rate-limits by the client address it carries.
451
+ request_header -${_geekmidas_manifest.CLIENT_IP_HEADER}
452
+ ${checks}${body}
453
+ }`;
454
+ }
455
+ /** Where a route's requests go, when no handler took them. */
456
+ function proxyBlock({ upstreams, prefix, streaming }) {
457
+ return prefix ? `
458
+ # A bucket, served at a host of its own: the bucket is a prefix on MinIO,
459
+ # which routes and signs on the Host header — so it is sent the upstream's.
460
+ reverse_proxy ${upstreams.map(address).join(" ")} {
461
+ rewrite ${prefix}{uri}
462
+ header_up Host {upstream_hostport}
463
+ }` : `
464
+ # Host and X-Forwarded-* are passed through as Caddy does by default, so
465
+ # an app builds redirects, cookies and links on the address a caller used.
466
+ reverse_proxy ${upstreams.map(address).join(" ")}${streaming ? ` {
467
+ # Never buffer: a streamed response — server-sent events, a Next.js
468
+ # RSC payload — reaches the client as each chunk is written.
469
+ flush_interval -1
470
+ }` : ""}`;
471
+ }
472
+ const HEADER = `# Generated by gkm compose from the construct manifest — do not edit.
473
+ #
474
+ # One host per API and site, each in front of its own container, one per
475
+ # file server in front of the stack's MinIO — its processors' paths sent to
476
+ # their own service — one per worker SNS pushes to and per processor unit a
477
+ # CDN reaches, answering only those paths, and — when its logs are served
478
+ # publicly — one for OpenObserve, to the addresses it allows. A site the
479
+ # stage puts behind a password asks for its login first.
480
+ `;
481
+ //#endregion
482
+ //#region src/compose/images.ts
483
+ /**
484
+ * Which image each app runs — and, for a tag, whether every one exists.
485
+ *
486
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
487
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
488
+ * image is asked of the registry before anything is pulled or the running
489
+ * stack is touched, and one missing image stops the whole run naming every
490
+ * one that is missing. Nor is a missing image quietly built instead — a build
491
+ * of whatever is checked out here is not the release the tag names.
492
+ */
493
+ /**
494
+ * The tag a site's image carries for a release.
495
+ *
496
+ * A site's public URLs are inlined when it is built, so one bundle serves one
497
+ * stage: `v1.4.0-production` and `v1.4.0-staging` are two images of the same
498
+ * commit. A backend reads its URLs at runtime, so one image serves every stage
499
+ * and its tag is the release's alone.
500
+ */
501
+ function siteTag(tag, stage) {
502
+ return `${tag}-${stage}`;
503
+ }
504
+ /** Images a tag names that the registry does not have. */
505
+ var ImageTagNotFound = class extends require_errors.GkmError {
506
+ tag;
507
+ refs;
508
+ constructor(tag, refs) {
509
+ 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.`);
510
+ this.tag = tag;
511
+ this.refs = refs;
512
+ this.name = "ImageTagNotFound";
513
+ }
514
+ };
515
+ /** The registry did not answer, or did not let this machine in. */
516
+ var RegistryUnreachable = class extends require_errors.GkmError {
517
+ ref;
518
+ detail;
519
+ constructor(ref, detail) {
520
+ 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>\`).`);
521
+ this.ref = ref;
522
+ this.detail = detail;
523
+ this.name = "RegistryUnreachable";
524
+ }
525
+ };
526
+ /**
527
+ * Assert every image exists, before anything else happens.
528
+ *
529
+ * Asked all at once and reported all at once: a release missing two images is
530
+ * one problem with two names, and finding the second only after fixing the
531
+ * first is a slower way to learn the same thing.
532
+ *
533
+ * @throws {RegistryUnreachable} when the registry cannot say
534
+ * @throws {ImageTagNotFound} listing every missing image
535
+ */
536
+ async function assertImagesExist(docker, tag, images) {
537
+ const lookups = await Promise.all(images.map((image) => docker.lookup(image.ref)));
538
+ const unreachable = lookups.find((lookup) => lookup.status === "unreachable");
539
+ if (unreachable?.status === "unreachable") throw new RegistryUnreachable(unreachable.ref, unreachable.detail);
540
+ const missing = lookups.filter((lookup) => lookup.status === "missing").map((lookup) => lookup.ref);
541
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
542
+ }
543
+ /**
544
+ * A push or a pull with no `deploy.registry` to push to or pull from.
545
+ *
546
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
547
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
548
+ * from, somebody else's account. It is never a fallback.
549
+ */
550
+ var RegistryRequired = class extends require_errors.GkmError {
551
+ operation;
552
+ ref;
553
+ constructor(operation, ref) {
554
+ 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." : ""));
555
+ this.operation = operation;
556
+ this.ref = ref;
557
+ this.name = "RegistryRequired";
558
+ }
559
+ };
560
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
561
+ function pinnedRef(ref, digest) {
562
+ return `${ref.split("@")[0]}@${digest}`;
563
+ }
564
+ /** A digests file with no entry for an app the stack runs. */
565
+ var ImageDigestMissing = class extends require_errors.GkmError {
566
+ file;
567
+ apps;
568
+ constructor(file, apps) {
569
+ 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.`);
570
+ this.file = file;
571
+ this.apps = apps;
572
+ this.name = "ImageDigestMissing";
573
+ }
574
+ };
575
+ /** A digests file entry that is not this app's image. */
576
+ var ImageDigestMismatch = class extends require_errors.GkmError {
577
+ app;
578
+ expected;
579
+ found;
580
+ constructor(app, expected, found) {
581
+ 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.`);
582
+ this.app = app;
583
+ this.expected = expected;
584
+ this.found = found;
585
+ this.name = "ImageDigestMismatch";
586
+ }
587
+ };
588
+ /** A digests file that is not a JSON object of app to pinned ref. */
589
+ var ImageDigestsInvalid = class extends require_errors.GkmError {
590
+ file;
591
+ detail;
592
+ constructor(file, detail) {
593
+ 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:…" }.`);
594
+ this.file = file;
595
+ this.detail = detail;
596
+ this.name = "ImageDigestsInvalid";
597
+ }
598
+ };
599
+ /** Parse a digests file's content, checking its shape. */
600
+ function parseDigests(file, content) {
601
+ let parsed;
602
+ try {
603
+ parsed = JSON.parse(content);
604
+ } catch (error) {
605
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
606
+ }
607
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
608
+ 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`);
609
+ return parsed;
610
+ }
611
+ /**
612
+ * Each image pinned to the digest the file names for it.
613
+ *
614
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
615
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
616
+ */
617
+ function pinImages(file, digests, images) {
618
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
619
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
620
+ return images.map((image) => {
621
+ const pinned = digests[image.app];
622
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
623
+ return {
624
+ ...image,
625
+ ref: pinned
626
+ };
627
+ });
628
+ }
629
+ //#endregion
630
+ //#region src/compose/sitePassword.ts
631
+ /**
632
+ * A site served behind a password on some deployed stages — a `StaticSite`'s
633
+ * `password`, naming a `RandomPassword` — so a staging build is not public
634
+ * while it is being tried.
635
+ *
636
+ * The edge asks for it with HTTP basic auth, before a request reaches the
637
+ * site: the browser prompts, and nothing of the site loads until the stage's
638
+ * login is given. The user is the stage's name; the password is the
639
+ * `RandomPassword`'s value on the stage, generated and kept like any other.
640
+ * Only its bcrypt hash reaches the edge's config.
641
+ *
642
+ * Pure.
643
+ */
644
+ /** A site's `password` names a `RandomPassword` the manifest does not hold. */
645
+ var SitePasswordNotDeclared = class extends require_errors.GkmError {
646
+ site;
647
+ secret;
648
+ constructor(site, secret) {
649
+ 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}');`);
650
+ this.site = site;
651
+ this.secret = secret;
652
+ this.name = "SitePasswordNotDeclared";
653
+ }
654
+ };
655
+ /** A site's `password` names a stage the workspace does not deploy. */
656
+ var UnknownPasswordStage = class extends require_errors.GkmError {
657
+ site;
658
+ stage;
659
+ deployed;
660
+ constructor(site, stage, deployed) {
661
+ 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.`);
662
+ this.site = site;
663
+ this.stage = stage;
664
+ this.deployed = deployed;
665
+ this.name = "UnknownPasswordStage";
666
+ }
667
+ };
668
+ /** A site behind a password, with none in the stage's secrets. */
669
+ var SitePasswordMissing = class extends require_errors.GkmError {
670
+ stage;
671
+ key;
672
+ constructor(stage, key) {
673
+ 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}`);
674
+ this.stage = stage;
675
+ this.key = key;
676
+ this.name = "SitePasswordMissing";
677
+ }
678
+ };
679
+ /**
680
+ * A site behind a password on a stage it deploys through a target that cannot
681
+ * ask for a login. Refused rather than ignored: ignored, the site would be
682
+ * public while its construct says it is not.
683
+ */
684
+ var SitePasswordNeedsCompose = class extends require_errors.GkmError {
685
+ site;
686
+ stage;
687
+ target;
688
+ constructor(site, stage, target) {
689
+ 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.`);
690
+ this.site = site;
691
+ this.stage = stage;
692
+ this.target = target;
693
+ this.name = "SitePasswordNeedsCompose";
694
+ }
695
+ };
696
+ /**
697
+ * The `RandomPassword` a site is served behind on `stage`, by its key —
698
+ * `SITE_PASSWORD` — or `undefined` where the stage asks for none.
699
+ *
700
+ * @throws {SitePasswordNotDeclared} where the password is not in the manifest
701
+ */
702
+ function sitePasswordKey(manifest, site, stage) {
703
+ const password = site.password;
704
+ if (!password?.stages.includes(stage)) return void 0;
705
+ const secret = manifest[password.secret];
706
+ const key = secret?.kind === "secret" ? secret.provides?.[0] : void 0;
707
+ if (!key) throw new SitePasswordNotDeclared(site.id, password.secret);
708
+ return key;
709
+ }
710
+ /**
711
+ * Before anything is deployed: every site behind a password names a deployed
712
+ * stage and a declared `RandomPassword`, and one of `apps` behind it on
713
+ * `stage` deploys through compose.
714
+ *
715
+ * @throws {UnknownPasswordStage}, {SitePasswordNotDeclared},
716
+ * {SitePasswordNeedsCompose}
717
+ */
718
+ function assertSitePasswords(workspace, manifest, stage, apps, target) {
719
+ for (const site of Object.values(manifest)) {
720
+ if (site.kind !== "site" || !site.password) continue;
721
+ for (const named of site.password.stages) if (!workspace.stages.deployed.includes(named)) throw new UnknownPasswordStage(site.id, named, workspace.stages.deployed);
722
+ if (sitePasswordKey(manifest, site, stage) && target !== "compose" && apps.includes(require_config.appKey(site.id))) throw new SitePasswordNeedsCompose(site.id, stage, target);
723
+ }
724
+ }
725
+ /**
726
+ * The login a site is served behind on `stage`, from the password kept under
727
+ * `key`.
728
+ *
729
+ * The hash's salt is derived from the password, so the same password always
730
+ * renders the same edge config: a deploy that changed nothing rewrites
731
+ * nothing, and the proxy is not reloaded for it. A per-hash random salt
732
+ * guards against a precomputed table of common passwords; a generated one is
733
+ * 43 random characters, which no table holds.
734
+ *
735
+ * @throws {SitePasswordMissing} where the stage's secrets hold none
736
+ */
737
+ function siteAuth(stage, key, custom) {
738
+ const password = custom[key];
739
+ if (!password) throw new SitePasswordMissing(stage, key);
740
+ return {
741
+ user: stage,
742
+ password,
743
+ hash: bcryptjs.default.hashSync(password, saltFor(password)),
744
+ key
745
+ };
746
+ }
747
+ /** bcrypt's own base-64 alphabet, in which a salt is written. */
748
+ const BCRYPT_ALPHABET = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
749
+ /**
750
+ * A bcrypt salt — `$2a$`, which Caddy and Traefik both read, at cost 10 —
751
+ * derived from the password.
752
+ */
753
+ function saltFor(password) {
754
+ const digest = (0, node_crypto.createHash)("sha256").update(password).digest();
755
+ let salt = "";
756
+ for (let i = 0; i < 22; i++) salt += BCRYPT_ALPHABET[digest[i] % 64];
757
+ return `$2a$10$${salt}`;
758
+ }
759
+ //#endregion
760
+ //#region src/compose/traefik.ts
761
+ /**
762
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
763
+ * with, and what one stack registers with it.
764
+ *
765
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
766
+ * HTTPS. It is configured through its file provider alone: each stack writes
767
+ * one file — its routers, services and middlewares, every name prefixed with
768
+ * its compose project — into a directory the edge watches, and removes it
769
+ * when it stops. There is no Docker socket: the edge never learns what runs
770
+ * on the server except from those files.
771
+ *
772
+ * The edge and the stacks meet on one external Docker network. Only a
773
+ * stack's public services join it, each under an alias prefixed with its
774
+ * project (`<project>-api`), because the network is shared: a bare service
775
+ * name there would be answered by every stack's `api`.
776
+ *
777
+ * Pure: the documents are data, and the edge's side effects are `edge.ts`'s.
778
+ */
779
+ /**
780
+ * The image, pinned: the edge is every stack's way in, so a new version is a
781
+ * change to this line, not whatever `latest` is on the day a server starts.
782
+ */
783
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
784
+ /** The edge's compose project, one per server. */
785
+ const EDGE_PROJECT = "gkm-edge";
786
+ /** The external network the edge and every stack's public services share. */
787
+ const EDGE_NETWORK = "gkm-edge";
788
+ /** The edge's compose service. */
789
+ const EDGE_SERVICE = "traefik";
790
+ /** Inside the edge's container: what it watches, and where certificates are. */
791
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
792
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
793
+ /** The certificate resolver every deployed route without its own certificate uses. */
794
+ const ACME_RESOLVER = "letsencrypt";
795
+ /**
796
+ * The resolver a wildcard site's `*.<domain>` certificate comes from: Let's
797
+ * Encrypt issues a wildcard only over the DNS challenge, which the edge
798
+ * answers by writing an `_acme-challenge` TXT record through Route 53.
799
+ */
800
+ const ACME_DNS_RESOLVER = "letsencrypt-dns";
801
+ /**
802
+ * The key the edge writes those records with, inside its container: written
803
+ * by the deploy of a stage with a wildcard site, and allowed nothing but
804
+ * each such stage's `_acme-challenge` record (see `acmeDns.ts`).
805
+ */
806
+ const EDGE_AWS_CREDENTIALS = `${EDGE_CERTS_DIR}/aws-credentials`;
807
+ /** The internal entrypoint the edge's health check asks; never published. */
808
+ const PING_PORT = 8082;
809
+ /** A stack's service, as the edge — and the stack itself — reach it. */
810
+ function edgeAlias(project, service) {
811
+ return `${project}-${service}`;
812
+ }
813
+ /** A stack's certificate, as the edge's container reads it. */
814
+ function edgeCertificatePaths(project) {
815
+ return {
816
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
817
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
818
+ };
819
+ }
820
+ /**
821
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
822
+ * the directory it watches. No API and no dashboard — nothing about the edge
823
+ * is reachable but the routes stacks register.
824
+ */
825
+ function traefikStatic(ports) {
826
+ return {
827
+ global: {
828
+ checkNewVersion: false,
829
+ sendAnonymousUsage: false
830
+ },
831
+ entryPoints: {
832
+ web: {
833
+ address: ":80",
834
+ http: { redirections: { entryPoint: {
835
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
836
+ scheme: "https",
837
+ permanent: true
838
+ } } }
839
+ },
840
+ websecure: { address: ":443" },
841
+ ping: { address: `:${PING_PORT}` }
842
+ },
843
+ ping: { entryPoint: "ping" },
844
+ providers: { file: {
845
+ directory: EDGE_DYNAMIC_DIR,
846
+ watch: true
847
+ } },
848
+ certificatesResolvers: {
849
+ [ACME_RESOLVER]: { acme: {
850
+ storage: "/acme/acme.json",
851
+ httpChallenge: { entryPoint: "web" }
852
+ } },
853
+ [ACME_DNS_RESOLVER]: { acme: {
854
+ storage: "/acme/acme-dns.json",
855
+ dnsChallenge: {
856
+ provider: "route53",
857
+ resolvers: ["1.1.1.1:53", "8.8.8.8:53"]
858
+ }
859
+ } }
860
+ },
861
+ log: { level: "INFO" }
862
+ };
863
+ }
864
+ /** The edge's compose document. */
865
+ function edgeCompose(options) {
866
+ const { ports } = options;
867
+ return {
868
+ name: EDGE_PROJECT,
869
+ services: { [EDGE_SERVICE]: {
870
+ image: TRAEFIK_IMAGE,
871
+ restart: "unless-stopped",
872
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
873
+ configs: [{
874
+ source: "traefik",
875
+ target: "/etc/traefik/traefik.yml"
876
+ }],
877
+ volumes: [
878
+ `dynamic:${EDGE_DYNAMIC_DIR}`,
879
+ `certs:${EDGE_CERTS_DIR}`,
880
+ "acme:/acme"
881
+ ],
882
+ labels: { "dev.geekmidas.edge.config": (0, node_crypto.createHash)("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
883
+ environment: {
884
+ AWS_SHARED_CREDENTIALS_FILE: EDGE_AWS_CREDENTIALS,
885
+ AWS_REGION: "us-east-1"
886
+ },
887
+ networks: ["edge"],
888
+ ...EDGE_LIMITS,
889
+ healthcheck: {
890
+ test: [
891
+ "CMD",
892
+ "traefik",
893
+ "healthcheck",
894
+ "--ping"
895
+ ],
896
+ interval: "10s",
897
+ timeout: "5s",
898
+ retries: 5
899
+ },
900
+ logging: options.logging
901
+ } },
902
+ configs: { traefik: { content: options.staticConfig } },
903
+ volumes: {
904
+ acme: {},
905
+ dynamic: {},
906
+ certs: {}
907
+ },
908
+ networks: { edge: {
909
+ name: EDGE_NETWORK,
910
+ external: true
911
+ } }
912
+ };
913
+ }
914
+ /** A stack's dynamic configuration, as an object. */
915
+ function traefikDynamic(routes, options) {
916
+ const { project, tls } = options;
917
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
918
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
919
+ const routers = {};
920
+ const services = {};
921
+ const middlewares = {};
922
+ const strip = `${project}-strip-gkm-headers`;
923
+ if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [_geekmidas_manifest.CLIENT_IP_HEADER]: "" } } };
924
+ for (const route of routes) {
925
+ const chain = [strip];
926
+ if (route.allow) {
927
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
928
+ chain.push(name(route, "allow"));
929
+ }
930
+ if (route.auth) {
931
+ middlewares[name(route, "auth")] = { basicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] } };
932
+ chain.push(name(route, "auth"));
933
+ }
934
+ if (route.prefix) {
935
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
936
+ chain.push(name(route, "prefix"));
937
+ }
938
+ assertRouteRenderable(route);
939
+ const allowed = [...(route.paths ?? []).map((path) => `Path(\`${path}\`)`), ...(route.prefixes ?? []).map((prefix) => `PathPrefix(\`${prefix}\`)`)];
940
+ const paths = allowed.length ? ` && (${allowed.join(" || ")})` : "";
941
+ const header = route.requireHeader ? ` && Header(\`${route.requireHeader.name}\`, \`${route.requireHeader.value}\`)` : "";
942
+ const certificate = () => route.wildcard?.tls.kind === "dns" ? {
943
+ certResolver: ACME_DNS_RESOLVER,
944
+ domains: [{ main: `*.${route.wildcard.domain}` }]
945
+ } : tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {};
946
+ for (const handler of route.handlers ?? []) {
947
+ const handlerName = name(route, handler.name);
948
+ routers[handlerName] = {
949
+ rule: `Host(\`${route.host}\`) && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
950
+ priority: 1e4,
951
+ entryPoints: ["websecure"],
952
+ service: handlerName,
953
+ middlewares: [strip],
954
+ tls: certificate()
955
+ };
956
+ services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
957
+ }
958
+ routers[name(route)] = {
959
+ rule: `${hostRule(route)}${paths}${header}`,
960
+ ...route.wildcard ? { priority: 1 } : {},
961
+ entryPoints: ["websecure"],
962
+ service: name(route),
963
+ middlewares: chain,
964
+ tls: certificate()
965
+ };
966
+ services[name(route)] = { loadBalancer: {
967
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
968
+ ...route.prefix ? { passHostHeader: false } : {},
969
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
970
+ ...route.health ? { healthCheck: {
971
+ path: route.health,
972
+ interval: "5s",
973
+ timeout: "3s"
974
+ } } : {}
975
+ } };
976
+ }
977
+ return {
978
+ http: {
979
+ routers,
980
+ services,
981
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
982
+ },
983
+ ...tls.kind === "files" ? { tls: { certificates: [{
984
+ certFile: tls.certFile,
985
+ keyFile: tls.keyFile
986
+ }] } } : {}
987
+ };
988
+ }
989
+ /**
990
+ * The hosts a route answers, as a Traefik rule: its own, or — for a wildcard
991
+ * site — exactly one label under its domain, but the ones it never takes.
992
+ * One label, as a wildcard certificate covers: a stage at
993
+ * `staging.example.com` is never reached through `example.com`'s wildcard.
994
+ */
995
+ function hostRule(route) {
996
+ if (!route.wildcard) return `Host(\`${route.host}\`)`;
997
+ const { domain, except } = route.wildcard;
998
+ return [`HostRegexp(\`${`^[a-z0-9-]+\\.${domain.replace(/\./g, "\\.")}$`}\`)`, ...except.map((label) => `!Host(\`${label}.${domain}\`)`)].join(" && ");
999
+ }
1000
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
1001
+ function traefikDynamicFile(routes, options) {
1002
+ return `# Generated by gkm compose for ${options.project} — do not edit.
1003
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
1004
+ # one is removed by gkm compose --down.
1005
+ ${yaml$1(traefikDynamic(routes, options))}`;
1006
+ }
1007
+ /** The edge's static configuration file. */
1008
+ function traefikStaticFile(ports) {
1009
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1010
+ ${yaml$1(traefikStatic(ports))}`;
1011
+ }
1012
+ /** The edge's compose file. */
1013
+ function edgeComposeFile(options) {
1014
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1015
+ #
1016
+ # Started by the first stack that runs with proxy: 'traefik', and left
1017
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
1018
+ #
1019
+ # docker compose -p ${EDGE_PROJECT} down
1020
+ ${yaml$1(edgeCompose(options))}`;
1021
+ }
1022
+ function yaml$1(value) {
1023
+ return (0, yaml.stringify)(value, {
1024
+ lineWidth: 0,
1025
+ aliasDuplicateObjects: false
1026
+ });
1027
+ }
1028
+ //#endregion
1029
+ //#region src/compose/stack.ts
1030
+ /**
1031
+ * The stack a workspace runs as for one stage — pure.
1032
+ *
1033
+ * Everything `gkm compose` writes is decided here, as data: the compose file,
1034
+ * the Caddyfile, one env file per backend, and the image each app runs. The
1035
+ * command around it reads the workspace, asks the registry, writes the files
1036
+ * and starts Docker; none of those decide anything, so all of it can be
1037
+ * asserted without a daemon.
1038
+ *
1039
+ * The values come from the same derivations every other target uses. The
1040
+ * plan is reconcile's `planFor`, the keys an app reads are `appEnvKeys`, and
1041
+ * every URL is `envFor`'s — asked twice, once with each app at its public
1042
+ * address and once on the compose network, because a browser and a sibling
1043
+ * service reach the same API by different names.
1044
+ */
1045
+ /** Where a stack's files are written, relative to the workspace root. */
1046
+ function stackDir(stage) {
1047
+ return `.gkm/compose/${stage}`;
1048
+ }
1049
+ /**
1050
+ * The compose project a stage's stack runs as.
1051
+ *
1052
+ * The deploy identity's scope, so two workspaces with one name in different
1053
+ * namespaces never share containers or volumes — and the stage, so a
1054
+ * machine can run two stages side by side.
1055
+ */
1056
+ function composeProject(identity) {
1057
+ return `${identity.scope}-${identity.stage}`;
1058
+ }
1059
+ /** The ports the edge is published on, and the variables that move them. */
1060
+ const EDGE_PORT_ENV = {
1061
+ https: "GKM_COMPOSE_HTTPS_PORT",
1062
+ http: "GKM_COMPOSE_HTTP_PORT"
1063
+ };
1064
+ /**
1065
+ * The variable that moves the local stage's OpenObserve off its loopback
1066
+ * port, 5080 — which the local stage takes from nowhere else, since it
1067
+ * ignores `deploy.telemetry`. Another stack, or another tool, may hold 5080.
1068
+ */
1069
+ const LOGS_PORT_ENV = "GKM_COMPOSE_LOGS_PORT";
1070
+ /**
1071
+ * Containers this target does not run.
1072
+ *
1073
+ * The AWS emulator never applies: a stack is a server target, whose events
1074
+ * are pg-boss. Reconcile's Caddy fronts `gkm dev`'s host processes; the stack
1075
+ * brings its own edge.
1076
+ *
1077
+ * MinIO and Mailpit run on the local stage always, and on a deployed stage
1078
+ * only where `--allow-dev-services` allowed them and its secrets configure no
1079
+ * real bucket or mail server — see `devServices.ts`.
1080
+ */
1081
+ const NOT_RUN = {
1082
+ localstack: true,
1083
+ caddy: true
1084
+ };
1085
+ /** The kinds a deployed stage takes from its secrets, or a dev service. */
1086
+ const SERVICE_KINDS = {
1087
+ email: "email",
1088
+ objects: "objects",
1089
+ "file-server": "file-server"
1090
+ };
1091
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
1092
+ const MINIO_REGION = "us-east-1";
1093
+ /** The S3 client's credentials, read beside a bucket's URL when it has them. */
1094
+ const STORAGE_KEYS = [
1095
+ "AWS_ACCESS_KEY_ID",
1096
+ "AWS_SECRET_ACCESS_KEY",
1097
+ "AWS_REGION"
1098
+ ];
1099
+ /**
1100
+ * Every service's Docker logs, rotated. The json-file driver keeps a
1101
+ * container's output in one file that grows until the disk is full — on a
1102
+ * small server, in weeks. Three files of 10 MB each per container is enough
1103
+ * to see what happened and never fills anything. A project's own override
1104
+ * file that sets `logging` wins over it.
1105
+ */
1106
+ const LOG_ROTATION = {
1107
+ driver: "json-file",
1108
+ options: {
1109
+ "max-size": "10m",
1110
+ "max-file": "3"
1111
+ }
1112
+ };
1113
+ /** A CDN serves the bucket, and the secret it sends the processors is not in the stage. */
1114
+ var ProcessorOriginSecretMissing = class extends require_errors.GkmError {
1115
+ fileServer;
1116
+ key;
1117
+ stage;
1118
+ constructor(fileServer, key, stage) {
1119
+ 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}.`);
1120
+ this.fileServer = fileServer;
1121
+ this.key = key;
1122
+ this.stage = stage;
1123
+ this.name = "ProcessorOriginSecretMissing";
1124
+ }
1125
+ };
1126
+ /**
1127
+ * The stack with Caddy's files inline: its Caddyfile and, where the stage has
1128
+ * one, its own certificate — `configs` with their `content`, which compose
1129
+ * copies into the container through the engine's API. Nothing is mounted from
1130
+ * a path, so the stack runs the same on a server's engine, over SSH, as on
1131
+ * this machine's. Their hash is a label: a changed file is a changed service,
1132
+ * which `up` recreates (compose does not, for a config's content alone).
1133
+ */
1134
+ function withCaddyConfigs(compose, files) {
1135
+ const caddy = compose.services.caddy;
1136
+ if (!caddy) return compose;
1137
+ const configs = {
1138
+ caddyfile: { content: files.caddyfile },
1139
+ ...files.tls ? {
1140
+ "tls-cert": { content: files.tls.cert },
1141
+ "tls-key": { content: files.tls.key }
1142
+ } : {}
1143
+ };
1144
+ const hash = (0, node_crypto.createHash)("sha256");
1145
+ for (const [name, { content }] of Object.entries(configs)) hash.update(`${name}\0${content}\0`);
1146
+ return {
1147
+ ...compose,
1148
+ services: {
1149
+ ...compose.services,
1150
+ caddy: {
1151
+ ...caddy,
1152
+ configs: [{
1153
+ source: "caddyfile",
1154
+ target: "/etc/caddy/Caddyfile"
1155
+ }, ...files.tls ? [{
1156
+ source: "tls-cert",
1157
+ target: `${CADDY_TLS_DIR}/cert.pem`
1158
+ }, {
1159
+ source: "tls-key",
1160
+ target: `${CADDY_TLS_DIR}/key.pem`,
1161
+ mode: 256
1162
+ }] : []],
1163
+ labels: {
1164
+ ...caddy.labels,
1165
+ "dev.geekmidas.caddy.config": hash.digest("hex").slice(0, 16)
1166
+ }
1167
+ }
1168
+ },
1169
+ configs: {
1170
+ ...compose.configs,
1171
+ ...configs
1172
+ }
1173
+ };
1174
+ }
1175
+ /**
1176
+ * The services a stack publishes on its engine's loopback, and the port each
1177
+ * answers on inside — what gkm reaches from this machine to provision the
1178
+ * stack and run its migrations and seeds. Everything else is reached only on
1179
+ * the stack's network.
1180
+ */
1181
+ const LOOPBACK_SERVICES = {
1182
+ postgres: 5432,
1183
+ minio: 9e3
1184
+ };
1185
+ /** The local stage's stack, without the logins `gkm dev` generates. */
1186
+ var LocalCredentialsMissing = class extends require_errors.GkmError {
1187
+ stage;
1188
+ constructor(stage) {
1189
+ 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.`);
1190
+ this.stage = stage;
1191
+ this.name = "LocalCredentialsMissing";
1192
+ }
1193
+ };
1194
+ /**
1195
+ * A deployed stage's container logins, derived from its seed like its role
1196
+ * passwords — so every deploy of the stage computes the same ones, and no one
1197
+ * reading the repo can.
1198
+ */
1199
+ function derivedCredentials(project, plan, seed) {
1200
+ const derive = (purpose) => require_apps.localRolePassword(project, plan, purpose, seed);
1201
+ return {
1202
+ postgres: {
1203
+ user: require_compose.postgresSuperuser(project),
1204
+ password: derive("master")
1205
+ },
1206
+ minio: {
1207
+ user: `${project}-minio`,
1208
+ password: derive("minio")
1209
+ },
1210
+ rabbitmq: {
1211
+ user: require_compose.LOCAL_RABBITMQ_USER,
1212
+ password: derive("rabbitmq")
1213
+ },
1214
+ redis: { password: derive("redis") },
1215
+ cacheToken: derive("cache-token"),
1216
+ emulator: {
1217
+ accessKeyId: require_compose.EMULATOR_ACCESS_KEY_ID,
1218
+ secretAccessKey: derive("emulator")
1219
+ },
1220
+ logs: {
1221
+ email: `admin@${project}`,
1222
+ password: derive("logs")
1223
+ }
1224
+ };
1225
+ }
1226
+ /** A value only the stage's secrets can hold, and they do not. */
1227
+ var StageSecretMissing = class extends require_errors.GkmError {
1228
+ app;
1229
+ key;
1230
+ stage;
1231
+ constructor(app, key, stage) {
1232
+ 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}`);
1233
+ this.app = app;
1234
+ this.key = key;
1235
+ this.stage = stage;
1236
+ this.name = "StageSecretMissing";
1237
+ }
1238
+ };
1239
+ /**
1240
+ * One key of a deployed inbox — the one rule every target reads it by.
1241
+ *
1242
+ * Its domain is the stage's, which mail is addressed to. Everything else (where
1243
+ * its raw messages are read, its topic's publisher string) is what its
1244
+ * provider made and wrote to the stage's secrets; nothing can derive it.
1245
+ *
1246
+ * @throws {NoDomainForStage} for its domain when the stage has none.
1247
+ * @throws {StageSecretMissing} when the provider has not written the key.
1248
+ */
1249
+ function deployedInboxValue(inbox, key, sources) {
1250
+ if (key === (0, _geekmidas_manifest.provideKey)(inbox, "domain")) {
1251
+ if (!sources.domain) throw new require_compose.NoDomainForStage(sources.stage);
1252
+ return sources.domain;
1253
+ }
1254
+ const value = sources.secrets[key];
1255
+ if (value === void 0) throw new StageSecretMissing(sources.reader, key, sources.stage);
1256
+ return value;
1257
+ }
1258
+ /**
1259
+ * Every deployed inbox's keys, and its topic's publisher string, by key: what
1260
+ * a target that provisions nothing of the inbox's (SST) is handed, read by
1261
+ * {@link deployedInboxValue} as the compose stack reads each.
1262
+ */
1263
+ function deployedInboxEnv(manifest, sources) {
1264
+ const env = {};
1265
+ for (const declaration of Object.values(manifest)) {
1266
+ if (declaration.kind !== "inbox") continue;
1267
+ const keys = [...declaration.provides ?? [], (0, _geekmidas_manifest.provideKey)(declaration.topic, "publisherConnectionString")];
1268
+ for (const key of keys) env[key] = deployedInboxValue(declaration.id, key, sources);
1269
+ }
1270
+ return env;
1271
+ }
1272
+ /** A deployed stage's secrets with no seed to derive its passwords from. */
1273
+ var StageSeedMissing = class extends require_errors.GkmError {
1274
+ stage;
1275
+ constructor(stage) {
1276
+ 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.`);
1277
+ this.stage = stage;
1278
+ this.name = "StageSeedMissing";
1279
+ }
1280
+ };
1281
+ /** A workspace with no API and no site to run. */
1282
+ var NothingToCompose = class extends require_errors.GkmError {
1283
+ root;
1284
+ constructor(root) {
1285
+ 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.`);
1286
+ this.root = root;
1287
+ this.name = "NothingToCompose";
1288
+ }
1289
+ };
1290
+ /** A value that cannot be written to an env file a line at a time. */
1291
+ var EnvValueMultiline = class extends require_errors.GkmError {
1292
+ app;
1293
+ key;
1294
+ constructor(app, key) {
1295
+ 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.`);
1296
+ this.app = app;
1297
+ this.key = key;
1298
+ this.name = "EnvValueMultiline";
1299
+ }
1300
+ };
1301
+ /** The services a stack's apps wait on and the edge waits on in turn. */
1302
+ const HEALTHY = { condition: "service_healthy" };
1303
+ /**
1304
+ * An app's health check: its own server, asked on 127.0.0.1 — not
1305
+ * `localhost`, which resolves to `::1` first in an Alpine container while a
1306
+ * server may listen on IPv4 alone.
1307
+ */
1308
+ function probe(port, path) {
1309
+ return {
1310
+ test: [
1311
+ "CMD",
1312
+ "wget",
1313
+ "-q",
1314
+ "-O",
1315
+ "/dev/null",
1316
+ `http://127.0.0.1:${port}${path}`
1317
+ ],
1318
+ interval: "5s",
1319
+ timeout: "3s",
1320
+ retries: 20,
1321
+ start_period: "10s"
1322
+ };
1323
+ }
1324
+ /**
1325
+ * What a stage's stack provisions: reconcile's plan, with a server target's
1326
+ * backends whatever `deploy.default` says — the stack is one machine running
1327
+ * containers, so events are pg-boss beside the declared database, and every
1328
+ * cache, one declared from that database included, is in the stack's own
1329
+ * Redis.
1330
+ */
1331
+ function stackPlan(workspace, manifest, stage) {
1332
+ const protectedSubdomains = [...workspace.protectedSubdomains ?? [], ...nestedStageLabels(workspace.domains, stage)];
1333
+ return require_apps.planFor(manifest, stage, (0, _geekmidas_manifest.provisionOrder)(manifest), {
1334
+ localStage: workspace.stages.local,
1335
+ ...protectedSubdomains.length > 0 ? { protectedSubdomains } : {},
1336
+ events: require_types.DEFAULT_EVENTS.server,
1337
+ cache: require_compose.STACK_CACHE,
1338
+ edge: false
1339
+ });
1340
+ }
1341
+ /** The stack for one stage. */
1342
+ function composeStack(input) {
1343
+ const { workspace, manifest, stage, identity } = input;
1344
+ const local = stage === workspace.stages.local;
1345
+ const project = composeProject(identity);
1346
+ const custom = input.secrets?.custom ?? {};
1347
+ const https = input.ports?.https ?? 443;
1348
+ const http = input.ports?.http ?? 80;
1349
+ const proxy = require_workspace.proxyFor(workspace.deploy?.compose, stage, local);
1350
+ const certificate = local ? void 0 : require_workspace.certificateFor(workspace.deploy?.compose, stage, workspace.root);
1351
+ const plan = stackPlan(workspace, manifest, stage);
1352
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1353
+ if (local && !input.localCredentials) throw new LocalCredentialsMissing(stage);
1354
+ const seed = local ? input.localCredentials.seed : input.secrets?.seed;
1355
+ if (!seed) throw new StageSeedMissing(stage);
1356
+ const containers = local ? input.localCredentials : derivedCredentials(workspace.name, plan, seed);
1357
+ const credential = {
1358
+ containers: {
1359
+ ...containers,
1360
+ minio: {
1361
+ user: custom.AWS_ACCESS_KEY_ID ?? containers.minio.user,
1362
+ password: custom.AWS_SECRET_ACCESS_KEY ?? containers.minio.password
1363
+ }
1364
+ },
1365
+ seed
1366
+ };
1367
+ const apps = stackApps(workspace, manifest, plan, {
1368
+ local,
1369
+ stage,
1370
+ https,
1371
+ identity,
1372
+ images: input.images
1373
+ });
1374
+ const workers = stackWorkers(require_apps.workerUnits(workspace, manifest, input.background ?? {}), {
1375
+ stage,
1376
+ identity,
1377
+ images: input.images
1378
+ });
1379
+ const processors = stackProcessors(require_apps.processorUnits(workspace, manifest), {
1380
+ manifest,
1381
+ stage,
1382
+ identity,
1383
+ images: input.images
1384
+ });
1385
+ if (apps.length === 0 && workers.length === 0 && processors.length === 0) throw new NothingToCompose(workspace.root);
1386
+ const owners = /* @__PURE__ */ new Map();
1387
+ for (const resource of plan.resources) {
1388
+ owners.set(resource.envKey, resource);
1389
+ if (resource.kind === "email") {
1390
+ owners.set((0, _geekmidas_manifest.provideKey)(resource.id, "from"), resource);
1391
+ owners.set((0, _geekmidas_manifest.provideKey)(resource.id, "inboxUrl"), resource);
1392
+ }
1393
+ if (resource.kind === "external-api") owners.set((0, _geekmidas_manifest.provideKey)(resource.id, "credentials"), resource);
1394
+ if (resource.kind === "inbox") owners.set((0, _geekmidas_manifest.provideKey)(resource.id, "domain"), resource);
1395
+ if (resource.kind === "websocket-api") owners.set((0, _geekmidas_manifest.provideKey)(resource.id, "publisherConnectionString"), resource);
1396
+ }
1397
+ const domain = workspace.domains?.[stage];
1398
+ const telemetry = require_workspace.resolveStageTelemetry({
1399
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1400
+ stage,
1401
+ local,
1402
+ target: "compose",
1403
+ runtime: "server",
1404
+ selfHosted: true,
1405
+ used: require_apps.usesTelemetry(manifest)
1406
+ });
1407
+ const logsBase = telemetry?.provider === "self-hosted" ? require_compose.stackLogs({
1408
+ config: local && input.ports?.logs ? {
1409
+ ...telemetry.selfHosted,
1410
+ port: input.ports.logs
1411
+ } : telemetry.selfHosted,
1412
+ stage,
1413
+ local,
1414
+ project: workspace.name,
1415
+ ...domain ? { domain } : {},
1416
+ custom,
1417
+ https,
1418
+ ...local ? { localLogin: input.localCredentials.logs } : {}
1419
+ }) : void 0;
1420
+ const services = local ? {
1421
+ missing: [],
1422
+ minio: plan.resources.filter((r) => r.kind === "objects").map((r) => r.id),
1423
+ mailpit: plan.resources.filter((r) => r.kind === "email" || r.kind === "inbox").map((r) => r.id)
1424
+ } : require_notes.externalServices({
1425
+ stage,
1426
+ declarations: require_notes.stageServiceDeclarations({ manifest }),
1427
+ supplied: custom,
1428
+ allow: input.allowDevServices === true,
1429
+ ...domain ? { domain } : {},
1430
+ providers: require_notes.stageProviderNotes(workspace, stage)
1431
+ });
1432
+ const redis = require_compose.stackRedis({
1433
+ plan,
1434
+ stage,
1435
+ local,
1436
+ custom,
1437
+ ...local ? { localPassword: input.localCredentials.redis.password } : {}
1438
+ });
1439
+ const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== require_compose.LOGS_SERVICE).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logsBase ? [require_compose.LOGS_SERVICE] : []].sort();
1440
+ const storage = infra.includes("minio") ? (() => {
1441
+ const buckets = services.minio.map((id) => byId.get(id)?.name).filter((name) => Boolean(name)).sort();
1442
+ return {
1443
+ ...credential.containers.minio,
1444
+ buckets,
1445
+ policies: require_apps.bucketPolicies(plan).filter((p) => buckets.includes(p.bucket)),
1446
+ objects: services.minio.map((id) => ({
1447
+ id,
1448
+ name: byId.get(id)?.name
1449
+ })).filter((b) => Boolean(b.name)).sort((a, b) => a.name.localeCompare(b.name)),
1450
+ webhooks: [],
1451
+ lifecycles: require_apps.bucketLifecycles(plan).filter((l) => buckets.includes(l.bucket))
1452
+ };
1453
+ })() : void 0;
1454
+ const bucketEventKeys = /* @__PURE__ */ new Map();
1455
+ for (const resource of plan.resources) {
1456
+ if (resource.kind !== "objects") continue;
1457
+ bucketEventKeys.set((0, _geekmidas_manifest.provideKey)(resource.id, "eventsConnectionString"), resource.id);
1458
+ bucketEventKeys.set((0, _geekmidas_manifest.provideKey)(resource.id, "eventsToken"), resource.id);
1459
+ }
1460
+ const fileServers = /* @__PURE__ */ new Map();
1461
+ if (storage) for (const resource of plan.resources) {
1462
+ if (resource.kind !== "file-server" || !resource.of) continue;
1463
+ if (!services.minio.includes(resource.of)) continue;
1464
+ if (custom[resource.envKey] !== void 0) continue;
1465
+ const bucket = byId.get(resource.of);
1466
+ if (!bucket) continue;
1467
+ let host;
1468
+ if (local) host = require_apps.hostFor(resource, workspace.name);
1469
+ else {
1470
+ if (!domain) throw new require_compose.NoDomainForStage(stage);
1471
+ host = `${resource.subdomain ?? require_config.appKey(resource.id)}.${domain}`;
1472
+ }
1473
+ fileServers.set(resource.id, {
1474
+ url: `https://${host}${local && https !== 443 ? `:${https}` : ""}`,
1475
+ route: {
1476
+ name: `files-${require_config.appKey(resource.id)}`,
1477
+ host,
1478
+ upstreams: [{
1479
+ service: "minio",
1480
+ port: 9e3
1481
+ }],
1482
+ streaming: false,
1483
+ prefix: `/${bucket.name}`
1484
+ }
1485
+ });
1486
+ }
1487
+ const edgeServices = new Set(proxy === "traefik" ? [
1488
+ ...apps.flatMap(replicaNames),
1489
+ ...fileServers.size > 0 ? ["minio"] : [],
1490
+ ...logsBase?.host && logsBase.public ? [require_compose.LOGS_SERVICE] : []
1491
+ ] : []);
1492
+ const hostOf = (service) => edgeServices.has(service) ? edgeAlias(project, service) : service;
1493
+ const logs = logsBase && {
1494
+ ...logsBase,
1495
+ appEnv: {
1496
+ ...logsBase.appEnv,
1497
+ OTEL_EXPORTER_OTLP_ENDPOINT: logsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(`//openobserve:`, `//${hostOf("openobserve")}:`)
1498
+ }
1499
+ };
1500
+ const derivation = {
1501
+ project: workspace.name,
1502
+ credentials: credential.containers,
1503
+ seed: credential.seed,
1504
+ ...!local && domain ? { mailFrom: `noreply@${domain}` } : {},
1505
+ relayedBuckets: [...require_compose.watchedBuckets(manifest, input.subscribers ?? {}).keys()].filter((bucket) => services.minio.includes(bucket))
1506
+ };
1507
+ const publicAddresses = Object.fromEntries(apps.map((app) => [app.id, app.url]));
1508
+ const outside = require_apps.networkEnv(plan, {
1509
+ ...derivation,
1510
+ addresses: publicAddresses
1511
+ }, hostOf);
1512
+ const inside = require_apps.networkEnv(plan, {
1513
+ ...derivation,
1514
+ addresses: Object.fromEntries(apps.map((app) => [app.id, `${app.kind === "websocket-api" ? "ws" : "http"}://${hostOf(app.name)}:${app.port}`]))
1515
+ }, hostOf);
1516
+ const surfaceUrls = new Map(plan.resources.filter((r) => r.kind === "rest-api" || r.kind === "websocket-api" || r.kind === "site").map((r) => [r.envKey, r.id]));
1517
+ const appById = new Map(apps.map((app) => [app.id, app]));
1518
+ /**
1519
+ * What a key resolves to for one app, from the stage's secrets where only
1520
+ * they can hold it, and the derivations otherwise.
1521
+ */
1522
+ const valueFor = (app, key, owner) => {
1523
+ if (require_workspace.isReservedStageKey(key)) return void 0;
1524
+ const watching = bucketEventKeys.get(key);
1525
+ if (watching) {
1526
+ if (custom[key] !== void 0) return custom[key];
1527
+ return services.minio.includes(watching) ? outside[key] : void 0;
1528
+ }
1529
+ if (owner?.kind === "inbox") {
1530
+ if (local) return outside[key];
1531
+ return deployedInboxValue(owner.id, key, {
1532
+ reader: app.name,
1533
+ stage,
1534
+ domain,
1535
+ secrets: custom
1536
+ });
1537
+ }
1538
+ if (!local && owner?.kind === "email" && key.endsWith("_INBOX_URL")) return;
1539
+ if (owner && SERVICE_KINDS[owner.kind]) {
1540
+ if (custom[key] !== void 0) return custom[key];
1541
+ if (owner.kind === "file-server") return fileServers.get(owner.id)?.url;
1542
+ return outside[key];
1543
+ }
1544
+ if (owner && require_notes.suppliedOnly(owner.kind, owner.id, key, local)) {
1545
+ const value = custom[key];
1546
+ if (value === void 0) throw new StageSecretMissing(app.name, key, stage);
1547
+ return value;
1548
+ }
1549
+ if (custom[key] !== void 0) return custom[key];
1550
+ if (owner?.kind === "cache") return redis?.urls[key];
1551
+ if (owner?.kind === "websocket-api" && key === (0, _geekmidas_manifest.provideKey)(owner.id, "publisherConnectionString")) return redis?.urls[key];
1552
+ const surface = surfaceUrls.get(key);
1553
+ if ((app.kind === "rest-api" || app.kind === "websocket-api") && surface && surface !== app.id) return inside[key];
1554
+ return outside[key];
1555
+ };
1556
+ const telemetryValues = logs ? require_workspace.telemetryEnv({
1557
+ endpoint: logs.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT,
1558
+ headers: logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS
1559
+ }, telemetry?.sampleRate ?? 1) : telemetry?.provider === "otlp" ? require_workspace.otlpTelemetryEnv(telemetry) : void 0;
1560
+ /** Each key one backend process reads, resolved for this stage. */
1561
+ const valuesFor = (app, keys) => {
1562
+ const values = {};
1563
+ for (const key of [...keys].sort()) {
1564
+ if (require_apps.isTelemetryKey(key)) continue;
1565
+ const owner = owners.get(key) ?? storageOwner(key, plan);
1566
+ if (STORAGE_KEYS.includes(key)) {
1567
+ const value = custom[key] ?? storageValue(key, storage);
1568
+ if (value !== void 0) values[key] = value;
1569
+ continue;
1570
+ }
1571
+ const value = valueFor(app, key, owner);
1572
+ if (value !== void 0) values[key] = value;
1573
+ }
1574
+ return values;
1575
+ };
1576
+ for (const app of apps) {
1577
+ if (app.kind === "site") {
1578
+ const site = manifest[app.id];
1579
+ if (site?.kind !== "site") continue;
1580
+ const args = require_apps.publicBuildValues(site, manifest, (key) => valueFor(app, key, owners.get(key)), custom);
1581
+ if (app.build && Object.keys(args).length > 0) app.build.args = args;
1582
+ continue;
1583
+ }
1584
+ if (input.buildOnly) continue;
1585
+ const keys = require_apps.appEnvKeys(manifest, app.name) ?? /* @__PURE__ */ new Set();
1586
+ const values = valuesFor(app, keys);
1587
+ const trusted = (0, _geekmidas_manifest.provideKey)(app.id, "trustedOrigins");
1588
+ if (keys.has(trusted)) {
1589
+ const internal = (byId.get(app.id)?.callers ?? []).map((caller) => appById.get(caller)).filter((caller) => caller?.kind === "rest-api" || caller?.kind === "websocket-api").map((caller) => `http://${hostOf(caller.name)}:${caller.port}`);
1590
+ const origins = [...(values[trusted] ?? "").split(",").filter(Boolean), ...internal];
1591
+ values[trusted] = [...new Set(origins)].join(",");
1592
+ }
1593
+ app.env = {
1594
+ ...require_apps.scopeTelemetryEnv(values, {
1595
+ uses: require_apps.telemetryOf(manifest, app.id) !== void 0,
1596
+ serviceName: app.name,
1597
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1598
+ }),
1599
+ NODE_ENV: "production",
1600
+ PORT: String(app.port),
1601
+ STAGE: stage
1602
+ };
1603
+ for (const [key, value] of Object.entries(app.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(app.name, key);
1604
+ }
1605
+ const mobileApps = [];
1606
+ for (const declaration of Object.values(manifest)) {
1607
+ if (declaration.kind !== "mobile-app") continue;
1608
+ const app = {
1609
+ name: require_config.appKey(declaration.id),
1610
+ id: declaration.id,
1611
+ kind: "site"
1612
+ };
1613
+ mobileApps.push({
1614
+ name: app.name,
1615
+ id: app.id,
1616
+ values: require_apps.publicBuildValues(declaration, manifest, (key) => valueFor(app, key, owners.get(key)), custom)
1617
+ });
1618
+ }
1619
+ for (const worker of input.buildOnly ? [] : workers) {
1620
+ const keys = require_apps.workerEnvKeys(manifest, worker.id) ?? /* @__PURE__ */ new Set();
1621
+ const resolved = valuesFor({
1622
+ name: worker.name,
1623
+ id: worker.id,
1624
+ kind: "rest-api"
1625
+ }, keys);
1626
+ const push = local ? void 0 : workerPush(worker, input.subscribers?.[worker.id] ?? [], resolved, {
1627
+ stage,
1628
+ ...domain ? { domain } : {}
1629
+ });
1630
+ if (push) {
1631
+ worker.push = push;
1632
+ if (proxy === "traefik") edgeServices.add(worker.name);
1633
+ }
1634
+ worker.env = {
1635
+ ...require_apps.scopeTelemetryEnv(resolved, {
1636
+ uses: require_apps.telemetryOf(manifest, worker.id) !== void 0,
1637
+ serviceName: worker.name,
1638
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1639
+ }),
1640
+ ...push && !input.recordingSubscriptions ? { [require_SubscriberGenerator.SNS_SUBSCRIPTIONS_KEY]: recordedSubscriptions(worker, push, input.pushSubscriptions?.[worker.id]) } : {},
1641
+ NODE_ENV: "production",
1642
+ PORT: String(worker.port),
1643
+ STAGE: stage
1644
+ };
1645
+ for (const [key, value] of Object.entries(worker.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);
1646
+ }
1647
+ for (const unit of processors) {
1648
+ const served = fileServers.get(unit.id);
1649
+ if (served) served.route = {
1650
+ ...served.route,
1651
+ handlers: [{
1652
+ name: unit.name,
1653
+ prefixes: unit.prefixes,
1654
+ upstreams: [{
1655
+ service: unit.name,
1656
+ port: unit.port
1657
+ }]
1658
+ }]
1659
+ };
1660
+ else if (!local && !input.buildOnly) {
1661
+ if (!domain) throw new require_compose.NoDomainForStage(stage);
1662
+ const key = require_credentials.originSecretKey(unit.id);
1663
+ const secret = custom[key];
1664
+ if (!secret) throw new ProcessorOriginSecretMissing(unit.id, key, stage);
1665
+ unit.origin = {
1666
+ host: require_credentials.processorOriginHost(unit.id, domain),
1667
+ secret
1668
+ };
1669
+ }
1670
+ if (proxy === "traefik" && (served || unit.origin)) edgeServices.add(unit.name);
1671
+ if (input.buildOnly) continue;
1672
+ const keys = require_apps.processorEnvKeys(manifest, unit.id) ?? /* @__PURE__ */ new Set();
1673
+ unit.env = {
1674
+ ...require_apps.scopeTelemetryEnv(valuesFor({
1675
+ name: unit.name,
1676
+ id: unit.id,
1677
+ kind: "rest-api"
1678
+ }, keys), {
1679
+ uses: require_apps.telemetryOf(manifest, unit.id) !== void 0,
1680
+ serviceName: unit.name,
1681
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1682
+ }),
1683
+ NODE_ENV: "production",
1684
+ PORT: String(unit.port),
1685
+ STAGE: stage
1686
+ };
1687
+ for (const [key, value] of Object.entries(unit.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(unit.name, key);
1688
+ }
1689
+ if (storage && !input.buildOnly) {
1690
+ const watched = require_compose.watchedBuckets(manifest, input.subscribers ?? {});
1691
+ for (const [bucket, workerId] of watched) {
1692
+ if (!services.minio.includes(bucket)) continue;
1693
+ const worker = workers.find((w) => w.id === workerId);
1694
+ const relay = worker?.env?.[(0, _geekmidas_manifest.provideKey)(bucket, "eventsConnectionString")];
1695
+ const token = worker?.env?.[(0, _geekmidas_manifest.provideKey)(bucket, "eventsToken")];
1696
+ if (!worker || !relay || relay.startsWith("sns:") || !token) continue;
1697
+ storage.webhooks.push({
1698
+ bucket,
1699
+ endpoint: `http://${hostOf(worker.name)}:${worker.port}${require_SubscriberGenerator.objectsRoute(bucket)}`,
1700
+ token
1701
+ });
1702
+ }
1703
+ }
1704
+ let inboxRelay;
1705
+ if (local && infra.includes("mailpit") && !input.buildOnly) {
1706
+ const relayId = require_SubscriberGenerator.inboxRelayWorker(manifest, input.subscribers ?? {});
1707
+ const relay = workers.find((w) => w.id === relayId);
1708
+ const token = relay?.env?.[require_SubscriberGenerator.INBOX_RELAY_TOKEN_KEY];
1709
+ if (relay && token) inboxRelay = require_SubscriberGenerator.inboxWebhookUrl(`http://${hostOf(relay.name)}:${relay.port}`, token);
1710
+ }
1711
+ const deployedTls = certificate ? {
1712
+ kind: "files",
1713
+ ...proxy === "caddy" ? {
1714
+ certFile: `${CADDY_TLS_DIR}/cert.pem`,
1715
+ keyFile: `${CADDY_TLS_DIR}/key.pem`
1716
+ } : edgeCertificatePaths(project)
1717
+ } : { kind: "acme" };
1718
+ const tls = local ? { kind: "internal" } : deployedTls;
1719
+ const backupsChoice = input.buildOnly ? void 0 : stageBackups(workspace, manifest, stage);
1720
+ const backups = backupsChoice?.mode === "on" && infra.includes("postgres") ? stackBackups({
1721
+ workspace,
1722
+ stage,
1723
+ project,
1724
+ plan,
1725
+ backups: backupsChoice.backups,
1726
+ custom,
1727
+ seed,
1728
+ superuser: credential.containers.postgres,
1729
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1730
+ }) : void 0;
1731
+ const layout = input.layout ?? defaultLayout(workspace.root);
1732
+ const compose = stackFile({
1733
+ project,
1734
+ plan,
1735
+ infra,
1736
+ apps,
1737
+ workers,
1738
+ processors,
1739
+ credentials: credential.containers,
1740
+ ...storage ? { storage } : {},
1741
+ ...inboxRelay ? { inboxRelay } : {},
1742
+ ...logs ? { logs } : {},
1743
+ ...redis ? { redis } : {},
1744
+ ...backups ? { backups } : {},
1745
+ https,
1746
+ http,
1747
+ composeDir: (0, node_path.join)(workspace.root, stackDir(stage)),
1748
+ buildRoot: layout.buildRoot,
1749
+ workspaceRoot: workspace.root,
1750
+ envFiles: !input.buildOnly,
1751
+ proxy,
1752
+ edge: new Map([...edgeServices].map((service) => [service, hostOf(service)]))
1753
+ });
1754
+ if (!local) for (const app of apps) {
1755
+ const site = manifest[app.id];
1756
+ if (site?.kind !== "site") continue;
1757
+ const key = sitePasswordKey(manifest, site, stage);
1758
+ if (key) app.auth = siteAuth(stage, key, custom);
1759
+ }
1760
+ const wildcard = local ? void 0 : stackWildcard(apps, {
1761
+ manifest,
1762
+ byId,
1763
+ workspace,
1764
+ stage,
1765
+ proxy,
1766
+ certificate: certificate !== void 0,
1767
+ hostOf
1768
+ });
1769
+ const routes = [
1770
+ ...apps.map((app) => ({
1771
+ name: app.name,
1772
+ host: app.host,
1773
+ ...wildcard?.site === app.id ? { wildcard: wildcard.edge } : {},
1774
+ upstreams: replicaNames(app).map((service) => ({
1775
+ service,
1776
+ port: app.port
1777
+ })),
1778
+ streaming: true,
1779
+ ...app.auth ? { auth: {
1780
+ user: app.auth.user,
1781
+ hash: app.auth.hash
1782
+ } } : {},
1783
+ health: app.kind === "site" ? "/" : "/health"
1784
+ })),
1785
+ ...[...fileServers.values()].map(({ route }) => route),
1786
+ ...processors.flatMap(({ name, port, prefixes, origin }) => origin ? [{
1787
+ name,
1788
+ host: origin.host,
1789
+ upstreams: [{
1790
+ service: name,
1791
+ port
1792
+ }],
1793
+ streaming: false,
1794
+ prefixes,
1795
+ requireHeader: {
1796
+ name: require_credentials.ORIGIN_VERIFY_HEADER,
1797
+ value: origin.secret
1798
+ },
1799
+ health: "/health"
1800
+ }] : []),
1801
+ ...workers.flatMap(({ name, port, push }) => push ? [{
1802
+ name,
1803
+ host: push.host,
1804
+ upstreams: [{
1805
+ service: name,
1806
+ port
1807
+ }],
1808
+ streaming: false,
1809
+ paths: push.paths,
1810
+ health: "/health"
1811
+ }] : []),
1812
+ ...logs?.host && logs.public ? [{
1813
+ name: require_compose.LOGS_SERVICE,
1814
+ host: logs.host,
1815
+ upstreams: [{
1816
+ service: require_compose.LOGS_SERVICE,
1817
+ port: require_workspace.LOGS_PORT
1818
+ }],
1819
+ streaming: true,
1820
+ allow: logs.public.allow
1821
+ }] : []
1822
+ ];
1823
+ assertHostsUnique(routes);
1824
+ const dockerfiles = {};
1825
+ for (const app of apps) {
1826
+ if (!app.build) continue;
1827
+ dockerfiles[app.build.dockerfile] = require_docker.appDockerfile(app.name, workspace.apps[app.name], {
1828
+ layout,
1829
+ workspaceRoot: workspace.root,
1830
+ apps: workspace.apps,
1831
+ manifest,
1832
+ cache: require_compose.STACK_CACHE,
1833
+ workspace,
1834
+ stage,
1835
+ ...app.kind === "site" && app.build.args ? { publicUrlArgs: Object.keys(app.build.args) } : {}
1836
+ });
1837
+ }
1838
+ for (const worker of workers) {
1839
+ if (!worker.build) continue;
1840
+ dockerfiles[worker.build.dockerfile] = require_docker.workerDockerfile({
1841
+ id: worker.id,
1842
+ name: worker.name,
1843
+ app: worker.host
1844
+ }, workspace.apps[worker.host], {
1845
+ layout,
1846
+ workspaceRoot: workspace.root,
1847
+ cache: require_compose.STACK_CACHE
1848
+ });
1849
+ }
1850
+ for (const unit of processors) {
1851
+ if (!unit.build) continue;
1852
+ dockerfiles[unit.build.dockerfile] = require_docker.processorDockerfile({
1853
+ id: unit.id,
1854
+ name: unit.name,
1855
+ app: unit.host
1856
+ }, workspace.apps[unit.host], {
1857
+ layout,
1858
+ workspaceRoot: workspace.root,
1859
+ cache: require_compose.STACK_CACHE
1860
+ });
1861
+ }
1862
+ return {
1863
+ project,
1864
+ stage,
1865
+ local,
1866
+ apps,
1867
+ workers,
1868
+ processors,
1869
+ mobileApps,
1870
+ infra,
1871
+ compose,
1872
+ proxy,
1873
+ routes,
1874
+ ...wildcard ? { wildcard: {
1875
+ site: wildcard.site,
1876
+ host: `*.${wildcard.edge.domain}`,
1877
+ tls: wildcard.edge.tls.kind
1878
+ } } : {},
1879
+ ...proxy === "caddy" ? { caddyfile: edgeCaddyfile(routes, { tls }) } : { traefik: traefikDynamicFile(routes, {
1880
+ project,
1881
+ tls: deployedTls
1882
+ }) },
1883
+ ...certificate ? { tls: certificate } : {},
1884
+ dockerfiles,
1885
+ plan,
1886
+ credential,
1887
+ resolution: {
1888
+ ...derivation,
1889
+ addresses: {
1890
+ ...publicAddresses,
1891
+ ...Object.fromEntries([...fileServers].map(([id, { url }]) => [id, url]))
1892
+ }
1893
+ },
1894
+ ...storage ? { storage } : {},
1895
+ devServices: local ? [] : require_notes.devServicesUsed(services),
1896
+ ...logs ? { logs } : {},
1897
+ ...telemetry ? { telemetry } : {},
1898
+ ...redis ? { redis } : {},
1899
+ ...backups ? { backups } : {}
1900
+ };
1901
+ }
1902
+ /** The stack's MinIO's value for one of the S3 client's keys. */
1903
+ function storageValue(key, storage) {
1904
+ if (!storage) return void 0;
1905
+ if (key === "AWS_ACCESS_KEY_ID") return storage.user;
1906
+ if (key === "AWS_SECRET_ACCESS_KEY") return storage.password;
1907
+ if (key === "AWS_REGION") return MINIO_REGION;
1908
+ }
1909
+ /** Which bucket an S3 credential key belongs to — the first one declared. */
1910
+ function storageOwner(key, plan) {
1911
+ if (!STORAGE_KEYS.includes(key)) return void 0;
1912
+ return plan.resources.find((r) => r.kind === "objects");
1913
+ }
1914
+ /** The apps a stack runs: every API and every site, at its stage address. */
1915
+ function stackApps(workspace, manifest, plan, options) {
1916
+ const apps = [];
1917
+ const resources = new Map(plan.resources.map((r) => [r.id, r]));
1918
+ for (const [id, declaration] of Object.entries(manifest)) {
1919
+ if (declaration.kind !== "rest-api" && declaration.kind !== "websocket-api" && declaration.kind !== "site") continue;
1920
+ const name = require_config.appKey(id);
1921
+ const app = workspace.apps[name];
1922
+ const resource = resources.get(id);
1923
+ if (!app || !resource || !app.port) continue;
1924
+ const host = hostOf(name, app, workspace, resource, options);
1925
+ const tag = declaration.kind === "site" ? siteTag(options.images.tag, options.stage) : options.images.tag;
1926
+ const ref = require_docker.validateImageRef(require_credentials.imageRef(options.identity, name, options.images.registry, tag));
1927
+ apps.push({
1928
+ app: name,
1929
+ name,
1930
+ id,
1931
+ kind: declaration.kind,
1932
+ replicas: declaration.kind === "websocket-api" ? declaration.replicas ?? 1 : 1,
1933
+ path: app.path,
1934
+ port: app.port,
1935
+ host,
1936
+ url: `${declaration.kind === "websocket-api" ? "wss" : "https"}://${host}${options.local && options.https !== 443 ? `:${options.https}` : ""}`,
1937
+ ref,
1938
+ tag,
1939
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${name}` } } : {}
1940
+ });
1941
+ }
1942
+ return apps.sort((a, b) => a.name.localeCompare(b.name));
1943
+ }
1944
+ /**
1945
+ * Where SNS pushes to a worker on a deployed stage, or nothing when it pushes
1946
+ * to none of its subscribers.
1947
+ *
1948
+ * A subscriber is pushed to when the connection string its deliveries come
1949
+ * from — its topic's, or its bucket's events — as this stage resolved it for
1950
+ * the worker, is an SNS one — the same test the worker's own
1951
+ * startup makes, so the edge exposes a route exactly when the worker mounts
1952
+ * it. Each such route, and nothing else the worker serves, answers on
1953
+ * `<worker>.<domain>`.
1954
+ */
1955
+ function workerPush(worker, subscribers, env, options) {
1956
+ 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));
1957
+ if (pushed.length === 0) return void 0;
1958
+ if (!options.domain) throw new require_compose.NoDomainForStage(options.stage);
1959
+ const host = `${worker.name}.${options.domain}`;
1960
+ const url = `https://${host}`;
1961
+ return {
1962
+ host,
1963
+ url,
1964
+ paths: pushed.map(({ name }) => require_SubscriberGenerator.subscriberRoute(name)),
1965
+ subscribers: pushed.map(({ name, connectionKey, events }) => ({
1966
+ name,
1967
+ connectionKey,
1968
+ endpoint: `${url}${require_SubscriberGenerator.subscriberRoute(name)}`,
1969
+ ...events ? { events } : {}
1970
+ }))
1971
+ };
1972
+ }
1973
+ /** A pushed subscriber the deploy recorded no SNS subscription for. */
1974
+ var PushSubscriptionMissing = class extends require_errors.GkmError {
1975
+ worker;
1976
+ subscriber;
1977
+ constructor(worker, subscriber) {
1978
+ 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.`);
1979
+ this.worker = worker;
1980
+ this.subscriber = subscriber;
1981
+ this.name = "PushSubscriptionMissing";
1982
+ }
1983
+ };
1984
+ /**
1985
+ * The worker's `GKM_SNS_SUBSCRIPTIONS`: each pushed subscriber's recorded
1986
+ * subscription ARN, and nothing for a subscriber it does not run.
1987
+ *
1988
+ * @throws {PushSubscriptionMissing} when one has none
1989
+ */
1990
+ function recordedSubscriptions(worker, push, recorded = {}) {
1991
+ const arns = {};
1992
+ for (const { name } of push.subscribers) {
1993
+ const arn = recorded[name];
1994
+ if (!arn) throw new PushSubscriptionMissing(worker.name, name);
1995
+ arns[name] = arn;
1996
+ }
1997
+ return JSON.stringify(arns);
1998
+ }
1999
+ /**
2000
+ * A wildcard site on a deployed stage with nowhere to get a certificate for
2001
+ * its tenants' hosts from. Let's Encrypt issues a wildcard certificate only
2002
+ * over the DNS challenge, so the stage either brings its own or gives the
2003
+ * proxy a way to get one.
2004
+ */
2005
+ var WildcardSiteCertificateMissing = class extends require_errors.GkmError {
2006
+ site;
2007
+ stage;
2008
+ proxy;
2009
+ domain;
2010
+ constructor(site, stage, proxy, domain) {
2011
+ 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.`);
2012
+ this.site = site;
2013
+ this.stage = stage;
2014
+ this.proxy = proxy;
2015
+ this.domain = domain;
2016
+ this.name = "WildcardSiteCertificateMissing";
2017
+ }
2018
+ };
2019
+ /**
2020
+ * A deployed stage's wildcard site, as its edge serves it: the labels it
2021
+ * never takes, and its certificate — the stage's own (`deploy.compose.tls`)
2022
+ * first; then, on the shared Traefik edge, a `*.<domain>` one over the DNS
2023
+ * challenge when Route 53 manages the domain; on the stack's own Caddy, one
2024
+ * per host on demand, asked of the site's `hosts` route.
2025
+ *
2026
+ * @throws {WildcardSiteCertificateMissing} when neither applies
2027
+ */
2028
+ function stackWildcard(apps, options) {
2029
+ const { manifest, workspace, stage, proxy } = options;
2030
+ const app = apps.find((a) => (0, _geekmidas_manifest.isWildcardSite)(manifest[a.id]));
2031
+ if (!app) return void 0;
2032
+ const declaration = manifest[app.id];
2033
+ if (!(0, _geekmidas_manifest.isWildcardSite)(declaration)) return void 0;
2034
+ const domain = workspace.domains?.[stage];
2035
+ if (!domain) throw new require_compose.NoDomainForStage(stage);
2036
+ const except = options.byId.get(app.id)?.protectedSubdomains ?? [];
2037
+ const tls = (() => {
2038
+ if (options.certificate) return { kind: "stage" };
2039
+ if (proxy === "traefik") {
2040
+ const dns = workspace.dns ? require_credentials.normalizeDnsConfig(workspace.dns) : {};
2041
+ const root = require_credentials.findRootDomain(domain, dns);
2042
+ if (root && dns[root]?.provider === "route53") return { kind: "dns" };
2043
+ } else if (declaration.hosts) {
2044
+ const surface = apps.find((a) => a.id === declaration.hosts?.surface);
2045
+ if (surface) return {
2046
+ kind: "on-demand",
2047
+ ask: `http://${options.hostOf(surface.name)}:${surface.port}${declaration.hosts.path}`
2048
+ };
2049
+ }
2050
+ throw new WildcardSiteCertificateMissing(app.id, stage, proxy, domain);
2051
+ })();
2052
+ return {
2053
+ site: app.id,
2054
+ edge: {
2055
+ domain,
2056
+ except,
2057
+ tls
2058
+ }
2059
+ };
2060
+ }
2061
+ /**
2062
+ * The first label under `stage`'s domain of every other stage's domain that
2063
+ * sits beneath it — `staging` for `staging.example.com` (or
2064
+ * `a.staging.example.com`) under `example.com`.
2065
+ */
2066
+ function nestedStageLabels(domains, stage) {
2067
+ const own = domains?.[stage]?.toLowerCase();
2068
+ if (!own) return [];
2069
+ const labels = /* @__PURE__ */ new Set();
2070
+ for (const [other, domain] of Object.entries(domains ?? {})) {
2071
+ if (other === stage || !domain) continue;
2072
+ const lower = domain.toLowerCase();
2073
+ if (!lower.endsWith(`.${own}`)) continue;
2074
+ const rest = lower.slice(0, -(own.length + 1)).split(".");
2075
+ labels.add(rest.at(-1));
2076
+ }
2077
+ return [...labels].sort();
2078
+ }
2079
+ /** Two constructs the edge would answer on one host. */
2080
+ var EdgeHostTaken = class extends require_errors.GkmError {
2081
+ host;
2082
+ first;
2083
+ second;
2084
+ constructor(host, first, second) {
2085
+ 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.`);
2086
+ this.host = host;
2087
+ this.first = first;
2088
+ this.second = second;
2089
+ this.name = "EdgeHostTaken";
2090
+ }
2091
+ };
2092
+ /** Refuse a stack where one host would be routed to two services. */
2093
+ function assertHostsUnique(routes) {
2094
+ const claimed = /* @__PURE__ */ new Map();
2095
+ for (const { host, name } of routes) {
2096
+ const first = claimed.get(host);
2097
+ if (first !== void 0) throw new EdgeHostTaken(host, first, name);
2098
+ claimed.set(host, name);
2099
+ }
2100
+ }
2101
+ /** Each processor unit's image, and where it is built from. */
2102
+ function stackProcessors(units, options) {
2103
+ return units.map((unit) => {
2104
+ const server = options.manifest[unit.id];
2105
+ const processors = server?.kind === "file-server" ? server.processors ?? [] : [];
2106
+ return {
2107
+ app: unit.name,
2108
+ name: unit.name,
2109
+ id: unit.id,
2110
+ host: unit.app,
2111
+ port: require_apps.PROCESSOR_PORT,
2112
+ prefixes: [...new Set(processors.map((p) => p.prefix))].sort(),
2113
+ ref: require_docker.validateImageRef(require_credentials.imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
2114
+ tag: options.images.tag,
2115
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
2116
+ };
2117
+ });
2118
+ }
2119
+ /** Each worker's image, and where it is built from. */
2120
+ function stackWorkers(units, options) {
2121
+ return units.map((unit) => ({
2122
+ app: unit.name,
2123
+ name: unit.name,
2124
+ id: unit.id,
2125
+ host: unit.app,
2126
+ port: require_apps.WORKER_PORT,
2127
+ ref: require_docker.validateImageRef(require_credentials.imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
2128
+ tag: options.images.tag,
2129
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
2130
+ }));
2131
+ }
2132
+ /**
2133
+ * The host an app answers on for a stage: the `gkm dev` edge's
2134
+ * `*.localhost` names for the local stage, and the stage's domain — by the
2135
+ * same rule a deploy follows — for any other.
2136
+ */
2137
+ function hostOf(name, app, workspace, resource, options) {
2138
+ if (options.local) return require_apps.hostFor(resource, workspace.name);
2139
+ if (resource.subdomain === _geekmidas_manifest.WILDCARD_SUBDOMAIN) {
2140
+ const domain = workspace.domains?.[options.stage];
2141
+ if (!domain) throw new require_compose.NoDomainForStage(options.stage);
2142
+ return `${_geekmidas_manifest.WILDCARD_SUBDOMAIN}.${domain}`;
2143
+ }
2144
+ return require_compose.resolveHost(name, app, options.stage, workspace.domains, require_compose.isMainFrontendApp(name, app, workspace.apps));
2145
+ }
2146
+ /** An app's compose services, one per replica: `api`, `api-2`, `api-3`. */
2147
+ function replicaNames(app) {
2148
+ return [app.name, ...Array.from({ length: app.replicas - 1 }, (_, i) => `${app.name}-${i + 2}`)];
2149
+ }
2150
+ /** The compose document: the infrastructure, the apps, and the edge. */
2151
+ function stackFile(options) {
2152
+ const { project, plan, apps } = options;
2153
+ const infra = options.infra.filter((name) => name !== require_compose.LOGS_SERVICE);
2154
+ const derived = require_compose.composeFor({
2155
+ ...plan,
2156
+ containers: [...infra]
2157
+ }, {
2158
+ project,
2159
+ ports: Object.fromEntries(require_compose.portKeys(infra, plan.fakes).map((key) => [key, 0])),
2160
+ credentials: options.credentials
2161
+ });
2162
+ const services = {};
2163
+ const volumes = {
2164
+ ...derived.volumes,
2165
+ ...options.proxy === "caddy" ? {
2166
+ "caddy-data": {},
2167
+ "caddy-config": {}
2168
+ } : {},
2169
+ ...options.logs ? { "openobserve-data": {} } : {}
2170
+ };
2171
+ for (const name of infra) {
2172
+ const { ports: _ports, depends_on, profiles: _profiles, ...service } = derived.services[name];
2173
+ services[name] = {
2174
+ ...service,
2175
+ ...depends_on?.length ? { depends_on: Object.fromEntries(depends_on.map((dep) => [dep, HEALTHY])) } : {}
2176
+ };
2177
+ }
2178
+ const postgres = services.postgres;
2179
+ if (postgres) postgres.ports = [`127.0.0.1::${LOOPBACK_SERVICES.postgres}`];
2180
+ const minio = services.minio;
2181
+ if (minio && options.storage) {
2182
+ minio.environment = {
2183
+ ...minio.environment,
2184
+ MINIO_ROOT_USER: options.storage.user,
2185
+ MINIO_ROOT_PASSWORD: options.storage.password,
2186
+ ...require_compose.minioWebhookEnv(options.storage.webhooks)
2187
+ };
2188
+ minio.ports = [`127.0.0.1::${LOOPBACK_SERVICES.minio}`];
2189
+ }
2190
+ const mailpit = services.mailpit;
2191
+ if (mailpit && options.inboxRelay) mailpit.environment = {
2192
+ ...mailpit.environment,
2193
+ MP_WEBHOOK_URL: options.inboxRelay
2194
+ };
2195
+ if (services["redis"] && options.redis) services[require_compose.REDIS_SERVICE] = require_compose.redisService(options.redis);
2196
+ if (options.logs) services[require_compose.LOGS_SERVICE] = require_compose.logsService(options.logs);
2197
+ if (options.backups) services[BACKUPS_SERVICE] = backupsService(options.backups, options.envFiles);
2198
+ for (const app of apps) {
2199
+ const definition = {
2200
+ image: app.ref,
2201
+ ...app.build ? { build: {
2202
+ ...require_apps.composeBuildPaths({
2203
+ composeDir: options.composeDir,
2204
+ buildRoot: options.buildRoot,
2205
+ workspaceRoot: options.workspaceRoot,
2206
+ dockerfile: app.build.dockerfile
2207
+ }),
2208
+ ...app.build.args ? { args: app.build.args } : {}
2209
+ } } : {},
2210
+ restart: "unless-stopped",
2211
+ ...app.kind !== "site" ? {
2212
+ env_file: [{
2213
+ path: `./${app.name}.env`,
2214
+ format: "raw"
2215
+ }],
2216
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {}
2217
+ } : {},
2218
+ healthcheck: probe(app.port, app.kind === "site" ? "/" : "/health"),
2219
+ ...app.kind === "websocket-api" ? { ulimits: { nofile: NOFILE } } : {}
2220
+ };
2221
+ for (const name of replicaNames(app)) services[name] = { ...definition };
2222
+ }
2223
+ for (const worker of [...options.workers, ...options.processors]) services[worker.name] = {
2224
+ image: worker.ref,
2225
+ ...worker.build ? { build: require_apps.composeBuildPaths({
2226
+ composeDir: options.composeDir,
2227
+ buildRoot: options.buildRoot,
2228
+ workspaceRoot: options.workspaceRoot,
2229
+ dockerfile: worker.build.dockerfile
2230
+ }) } : {},
2231
+ restart: "unless-stopped",
2232
+ env_file: [{
2233
+ path: `./${worker.name}.env`,
2234
+ format: "raw"
2235
+ }],
2236
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
2237
+ healthcheck: probe(worker.port, "/health")
2238
+ };
2239
+ if (options.proxy === "caddy") services.caddy = {
2240
+ image: require_compose.DEFAULT_IMAGES.caddy,
2241
+ restart: "unless-stopped",
2242
+ ports: [`${options.https}:443`, `${options.http}:80`],
2243
+ volumes: ["caddy-data:/data", "caddy-config:/config"],
2244
+ ...EDGE_LIMITS,
2245
+ depends_on: Object.fromEntries([
2246
+ ...apps.flatMap(replicaNames),
2247
+ ...options.workers.filter((w) => w.push).map((w) => w.name),
2248
+ ...options.processors.map((p) => p.name)
2249
+ ].map((name) => [name, HEALTHY])),
2250
+ healthcheck: {
2251
+ test: [
2252
+ "CMD",
2253
+ "caddy",
2254
+ "version"
2255
+ ],
2256
+ interval: "10s",
2257
+ timeout: "5s",
2258
+ retries: 5
2259
+ }
2260
+ };
2261
+ for (const [service, alias] of options.edge) {
2262
+ const definition = services[service];
2263
+ if (!definition) continue;
2264
+ definition.networks = {
2265
+ default: { aliases: [alias] },
2266
+ edge: { aliases: [alias] }
2267
+ };
2268
+ }
2269
+ for (const service of Object.values(services)) {
2270
+ if (!options.envFiles) delete service.env_file;
2271
+ service.logging = {
2272
+ driver: LOG_ROTATION.driver,
2273
+ options: { ...LOG_ROTATION.options }
2274
+ };
2275
+ }
2276
+ return {
2277
+ name: project,
2278
+ services,
2279
+ volumes,
2280
+ ...options.edge.size > 0 ? { networks: { edge: {
2281
+ name: EDGE_NETWORK,
2282
+ external: true
2283
+ } } } : {}
2284
+ };
2285
+ }
2286
+ /**
2287
+ * A build without a layout: the workspace is the build root, with pnpm.
2288
+ * What a caller that never looked at the filesystem gets.
2289
+ */
2290
+ function defaultLayout(root) {
2291
+ return {
2292
+ buildRoot: root,
2293
+ gkmRoot: ".",
2294
+ tools: {
2295
+ packageManager: "pnpm",
2296
+ turboVersion: require_apps.TURBO_VERSION,
2297
+ monorepo: true
2298
+ },
2299
+ gkmPaths: ["gkm.config.*"]
2300
+ };
2301
+ }
2302
+ /** Render an app's env file: one `KEY=value` per line, read raw by compose. */
2303
+ function envFile(env) {
2304
+ return `${Object.entries(env).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n")}\n`;
2305
+ }
2306
+ //#endregion
2307
+ Object.defineProperty(exports, "BACKUPS_SERVICE", {
2308
+ enumerable: true,
2309
+ get: function() {
2310
+ return BACKUPS_SERVICE;
2311
+ }
2312
+ });
2313
+ Object.defineProperty(exports, "BACKUPS_URL_KEY", {
2314
+ enumerable: true,
2315
+ get: function() {
2316
+ return BACKUPS_URL_KEY;
2317
+ }
2318
+ });
2319
+ Object.defineProperty(exports, "EDGE_AWS_CREDENTIALS", {
2320
+ enumerable: true,
2321
+ get: function() {
2322
+ return EDGE_AWS_CREDENTIALS;
2323
+ }
2324
+ });
2325
+ Object.defineProperty(exports, "EDGE_CERTS_DIR", {
2326
+ enumerable: true,
2327
+ get: function() {
2328
+ return EDGE_CERTS_DIR;
2329
+ }
2330
+ });
2331
+ Object.defineProperty(exports, "EDGE_DYNAMIC_DIR", {
2332
+ enumerable: true,
2333
+ get: function() {
2334
+ return EDGE_DYNAMIC_DIR;
2335
+ }
2336
+ });
2337
+ Object.defineProperty(exports, "EDGE_NETWORK", {
2338
+ enumerable: true,
2339
+ get: function() {
2340
+ return EDGE_NETWORK;
2341
+ }
2342
+ });
2343
+ Object.defineProperty(exports, "EDGE_PORT_ENV", {
2344
+ enumerable: true,
2345
+ get: function() {
2346
+ return EDGE_PORT_ENV;
2347
+ }
2348
+ });
2349
+ Object.defineProperty(exports, "EDGE_PROJECT", {
2350
+ enumerable: true,
2351
+ get: function() {
2352
+ return EDGE_PROJECT;
2353
+ }
2354
+ });
2355
+ Object.defineProperty(exports, "EDGE_SERVICE", {
2356
+ enumerable: true,
2357
+ get: function() {
2358
+ return EDGE_SERVICE;
2359
+ }
2360
+ });
2361
+ Object.defineProperty(exports, "LOGS_PORT_ENV", {
2362
+ enumerable: true,
2363
+ get: function() {
2364
+ return LOGS_PORT_ENV;
2365
+ }
2366
+ });
2367
+ Object.defineProperty(exports, "LOG_ROTATION", {
2368
+ enumerable: true,
2369
+ get: function() {
2370
+ return LOG_ROTATION;
2371
+ }
2372
+ });
2373
+ Object.defineProperty(exports, "LOOPBACK_SERVICES", {
2374
+ enumerable: true,
2375
+ get: function() {
2376
+ return LOOPBACK_SERVICES;
2377
+ }
2378
+ });
2379
+ Object.defineProperty(exports, "RUNNER_PATH", {
2380
+ enumerable: true,
2381
+ get: function() {
2382
+ return RUNNER_PATH;
2383
+ }
2384
+ });
2385
+ Object.defineProperty(exports, "RegistryRequired", {
2386
+ enumerable: true,
2387
+ get: function() {
2388
+ return RegistryRequired;
2389
+ }
2390
+ });
2391
+ Object.defineProperty(exports, "assertImagesExist", {
2392
+ enumerable: true,
2393
+ get: function() {
2394
+ return assertImagesExist;
2395
+ }
2396
+ });
2397
+ Object.defineProperty(exports, "assertSitePasswords", {
2398
+ enumerable: true,
2399
+ get: function() {
2400
+ return assertSitePasswords;
2401
+ }
2402
+ });
2403
+ Object.defineProperty(exports, "backupDatabases", {
2404
+ enumerable: true,
2405
+ get: function() {
2406
+ return backupDatabases;
2407
+ }
2408
+ });
2409
+ Object.defineProperty(exports, "backupExpiries", {
2410
+ enumerable: true,
2411
+ get: function() {
2412
+ return backupExpiries;
2413
+ }
2414
+ });
2415
+ Object.defineProperty(exports, "backupFile", {
2416
+ enumerable: true,
2417
+ get: function() {
2418
+ return backupFile;
2419
+ }
2420
+ });
2421
+ Object.defineProperty(exports, "backupsPrefix", {
2422
+ enumerable: true,
2423
+ get: function() {
2424
+ return backupsPrefix;
2425
+ }
2426
+ });
2427
+ Object.defineProperty(exports, "backupsRoleStatements", {
2428
+ enumerable: true,
2429
+ get: function() {
2430
+ return backupsRoleStatements;
2431
+ }
2432
+ });
2433
+ Object.defineProperty(exports, "composeProject", {
2434
+ enumerable: true,
2435
+ get: function() {
2436
+ return composeProject;
2437
+ }
2438
+ });
2439
+ Object.defineProperty(exports, "composeStack", {
2440
+ enumerable: true,
2441
+ get: function() {
2442
+ return composeStack;
2443
+ }
2444
+ });
2445
+ Object.defineProperty(exports, "deployedInboxEnv", {
2446
+ enumerable: true,
2447
+ get: function() {
2448
+ return deployedInboxEnv;
2449
+ }
2450
+ });
2451
+ Object.defineProperty(exports, "deploysWithCompose", {
2452
+ enumerable: true,
2453
+ get: function() {
2454
+ return deploysWithCompose;
2455
+ }
2456
+ });
2457
+ Object.defineProperty(exports, "derivedCredentials", {
2458
+ enumerable: true,
2459
+ get: function() {
2460
+ return derivedCredentials;
2461
+ }
2462
+ });
2463
+ Object.defineProperty(exports, "edgeAlias", {
2464
+ enumerable: true,
2465
+ get: function() {
2466
+ return edgeAlias;
2467
+ }
2468
+ });
2469
+ Object.defineProperty(exports, "edgeComposeFile", {
2470
+ enumerable: true,
2471
+ get: function() {
2472
+ return edgeComposeFile;
2473
+ }
2474
+ });
2475
+ Object.defineProperty(exports, "envFile", {
2476
+ enumerable: true,
2477
+ get: function() {
2478
+ return envFile;
2479
+ }
2480
+ });
2481
+ Object.defineProperty(exports, "parseDigests", {
2482
+ enumerable: true,
2483
+ get: function() {
2484
+ return parseDigests;
2485
+ }
2486
+ });
2487
+ Object.defineProperty(exports, "pinImages", {
2488
+ enumerable: true,
2489
+ get: function() {
2490
+ return pinImages;
2491
+ }
2492
+ });
2493
+ Object.defineProperty(exports, "pinnedRef", {
2494
+ enumerable: true,
2495
+ get: function() {
2496
+ return pinnedRef;
2497
+ }
2498
+ });
2499
+ Object.defineProperty(exports, "runTime", {
2500
+ enumerable: true,
2501
+ get: function() {
2502
+ return runTime;
2503
+ }
2504
+ });
2505
+ Object.defineProperty(exports, "stackDir", {
2506
+ enumerable: true,
2507
+ get: function() {
2508
+ return stackDir;
2509
+ }
2510
+ });
2511
+ Object.defineProperty(exports, "stackPlan", {
2512
+ enumerable: true,
2513
+ get: function() {
2514
+ return stackPlan;
2515
+ }
2516
+ });
2517
+ Object.defineProperty(exports, "stageBackups", {
2518
+ enumerable: true,
2519
+ get: function() {
2520
+ return stageBackups;
2521
+ }
2522
+ });
2523
+ Object.defineProperty(exports, "traefikStaticFile", {
2524
+ enumerable: true,
2525
+ get: function() {
2526
+ return traefikStaticFile;
2527
+ }
2528
+ });
2529
+ Object.defineProperty(exports, "withCaddyConfigs", {
2530
+ enumerable: true,
2531
+ get: function() {
2532
+ return withCaddyConfigs;
2533
+ }
2534
+ });
2535
+
2536
+ //# sourceMappingURL=stack-CmHjkg7D.cjs.map