@geekmidas/cli 10.0.0-alpha.184 → 10.0.0-alpha.186

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 (251) hide show
  1. package/dist/{LegacyStateStore-CTfoMtC2.mjs → LegacyStateStore-BwHw28fJ.mjs} +2 -2
  2. package/dist/{LegacyStateStore-CTfoMtC2.mjs.map → LegacyStateStore-BwHw28fJ.mjs.map} +1 -1
  3. package/dist/{LegacyStateStore-BtDLNkIH.cjs → LegacyStateStore-LpTY3S7z.cjs} +2 -2
  4. package/dist/{LegacyStateStore-BtDLNkIH.cjs.map → LegacyStateStore-LpTY3S7z.cjs.map} +1 -1
  5. package/dist/{LocalStateStore-BKp45OoB.cjs → LocalStateStore-Dpn9kBuK.cjs} +2 -2
  6. package/dist/{LocalStateStore-BKp45OoB.cjs.map → LocalStateStore-Dpn9kBuK.cjs.map} +1 -1
  7. package/dist/{LocalStateStore-C4zDHVM-.mjs → LocalStateStore-DsdNLm0_.mjs} +2 -2
  8. package/dist/{LocalStateStore-C4zDHVM-.mjs.map → LocalStateStore-DsdNLm0_.mjs.map} +1 -1
  9. package/dist/{S3StateStore-S0TXLlMW.mjs → S3StateStore-BIpCLzpk.mjs} +4 -4
  10. package/dist/{S3StateStore-S0TXLlMW.mjs.map → S3StateStore-BIpCLzpk.mjs.map} +1 -1
  11. package/dist/{S3StateStore-B6SjbLxh.cjs → S3StateStore-Bk_EIWLU.cjs} +5 -5
  12. package/dist/{S3StateStore-B6SjbLxh.cjs.map → S3StateStore-Bk_EIWLU.cjs.map} +1 -1
  13. package/dist/{SSMStateStore-6Di_zxwC.cjs → SSMStateStore-A1bgCF1P.cjs} +2 -2
  14. package/dist/{SSMStateStore-6Di_zxwC.cjs.map → SSMStateStore-A1bgCF1P.cjs.map} +1 -1
  15. package/dist/{SSMStateStore-ClPHFhRQ.mjs → SSMStateStore-PiZxPXeX.mjs} +2 -2
  16. package/dist/{SSMStateStore-ClPHFhRQ.mjs.map → SSMStateStore-PiZxPXeX.mjs.map} +1 -1
  17. package/dist/{add-BR8XW4IH.mjs → add-BBhzFpQ7.mjs} +4 -5
  18. package/dist/{add-BR8XW4IH.mjs.map → add-BBhzFpQ7.mjs.map} +1 -1
  19. package/dist/{add-Bd9MDHuU.cjs → add-sU71e0Lp.cjs} +13 -14
  20. package/dist/{add-Bd9MDHuU.cjs.map → add-sU71e0Lp.cjs.map} +1 -1
  21. package/dist/backups/runner.cjs +501 -13
  22. package/dist/backups/runner.cjs.map +1 -1
  23. package/dist/backups/runner.d.cts +87 -2
  24. package/dist/backups/runner.d.cts.map +1 -1
  25. package/dist/backups/runner.d.mts +87 -2
  26. package/dist/backups/runner.d.mts.map +1 -1
  27. package/dist/backups/runner.mjs +493 -15
  28. package/dist/backups/runner.mjs.map +1 -1
  29. package/dist/{bundler-4E-CGdL3.cjs → bundler-BM6lq-36.cjs} +9 -9
  30. package/dist/{bundler-4E-CGdL3.cjs.map → bundler-BM6lq-36.cjs.map} +1 -1
  31. package/dist/{bundler-Cwr4YSpp.mjs → bundler-QKbRwztS.mjs} +6 -6
  32. package/dist/{bundler-Cwr4YSpp.mjs.map → bundler-QKbRwztS.mjs.map} +1 -1
  33. package/dist/{cli-CrPJr29x.cjs → cli-D_iytris.cjs} +6 -6
  34. package/dist/{cli-CrPJr29x.cjs.map → cli-D_iytris.cjs.map} +1 -1
  35. package/dist/{cli-C3mHXsAE.mjs → cli-VCAfR-se.mjs} +4 -4
  36. package/dist/{cli-C3mHXsAE.mjs.map → cli-VCAfR-se.mjs.map} +1 -1
  37. package/dist/{clientTelemetry-Ej1tf1VE.d.cts → clientTelemetry-Bzc4KXz5.d.mts} +2 -2
  38. package/dist/clientTelemetry-Bzc4KXz5.d.mts.map +1 -0
  39. package/dist/{clientTelemetry-crdjgehZ.d.mts → clientTelemetry-N8NAguGI.d.cts} +2 -2
  40. package/dist/clientTelemetry-N8NAguGI.d.cts.map +1 -0
  41. package/dist/{compose-DPXoarGI.mjs → compose-CX2BF3LG.mjs} +58 -1029
  42. package/dist/compose-CX2BF3LG.mjs.map +1 -0
  43. package/dist/{compose-CKBieltT.cjs → compose-D3zc8QN1.cjs} +117 -1130
  44. package/dist/compose-D3zc8QN1.cjs.map +1 -0
  45. package/dist/{config-q4ewzIA_.d.mts → config-CTrfNKYd.d.mts} +3 -3
  46. package/dist/{config-lSOwPbUy.d.cts.map → config-CTrfNKYd.d.mts.map} +1 -1
  47. package/dist/{config-lSOwPbUy.d.cts → config-D9g_nYIu.d.cts} +3 -3
  48. package/dist/{config-q4ewzIA_.d.mts.map → config-D9g_nYIu.d.cts.map} +1 -1
  49. package/dist/config.cjs +1 -1
  50. package/dist/config.d.cts +3 -3
  51. package/dist/config.d.mts +3 -3
  52. package/dist/config.mjs +1 -1
  53. package/dist/{compose-CJznzQc7.mjs → credentials-BMdpNO8R.mjs} +1213 -1258
  54. package/dist/credentials-BMdpNO8R.mjs.map +1 -0
  55. package/dist/{dns-BzYrbB2Y.cjs → credentials-BQ1khM28.cjs} +6 -847
  56. package/dist/credentials-BQ1khM28.cjs.map +1 -0
  57. package/dist/{compose-CvNyjqwL.cjs → credentials-C3uaZ80e.cjs} +1270 -1285
  58. package/dist/credentials-C3uaZ80e.cjs.map +1 -0
  59. package/dist/{dns-C0wbTjVX.mjs → credentials-Ci8nKFw4.mjs} +5 -708
  60. package/dist/credentials-Ci8nKFw4.mjs.map +1 -0
  61. package/dist/{dbTunnel-DSzAG_wy.cjs → dbTunnel-D000s0YK.cjs} +8 -9
  62. package/dist/{dbTunnel-DSzAG_wy.cjs.map → dbTunnel-D000s0YK.cjs.map} +1 -1
  63. package/dist/{dbTunnel-CphoKGyk.mjs → dbTunnel-DqtSAdQK.mjs} +5 -6
  64. package/dist/{dbTunnel-CphoKGyk.mjs.map → dbTunnel-DqtSAdQK.mjs.map} +1 -1
  65. package/dist/deploy/public.cjs +25 -26
  66. package/dist/deploy/public.cjs.map +1 -1
  67. package/dist/deploy/public.d.cts +5 -5
  68. package/dist/deploy/public.d.cts.map +1 -1
  69. package/dist/deploy/public.d.mts +5 -5
  70. package/dist/deploy/public.d.mts.map +1 -1
  71. package/dist/deploy/public.mjs +10 -11
  72. package/dist/deploy/public.mjs.map +1 -1
  73. package/dist/{deploy-BaSYxpny.cjs → deploy-DRH6q_2r.cjs} +72 -62
  74. package/dist/deploy-DRH6q_2r.cjs.map +1 -0
  75. package/dist/{deploy-C_uZBzvS.mjs → deploy-DwtM6VSz.mjs} +25 -15
  76. package/dist/deploy-DwtM6VSz.mjs.map +1 -0
  77. package/dist/{destroy-yTBmL1jf.mjs → destroy-C6QwLj3b.mjs} +9 -9
  78. package/dist/{destroy-yTBmL1jf.mjs.map → destroy-C6QwLj3b.mjs.map} +1 -1
  79. package/dist/{destroy-PvrHxZDu.cjs → destroy-ChTJ_oUq.cjs} +21 -21
  80. package/dist/{destroy-PvrHxZDu.cjs.map → destroy-ChTJ_oUq.cjs.map} +1 -1
  81. package/dist/{dokploy-DqL3jeDu.mjs → dokploy-Dm8-eHtx.mjs} +2 -2
  82. package/dist/{dokploy-DqL3jeDu.mjs.map → dokploy-Dm8-eHtx.mjs.map} +1 -1
  83. package/dist/{dokploy-DYUMx2MY.cjs → dokploy-jeO7mz1R.cjs} +2 -2
  84. package/dist/{dokploy-DYUMx2MY.cjs.map → dokploy-jeO7mz1R.cjs.map} +1 -1
  85. package/dist/{eas-DEM-iWg6.cjs → eas-BAitvB5R.cjs} +3 -3
  86. package/dist/{eas-DEM-iWg6.cjs.map → eas-BAitvB5R.cjs.map} +1 -1
  87. package/dist/{eas-DHDU86PL.mjs → eas-CXYo8hos.mjs} +3 -3
  88. package/dist/{eas-DHDU86PL.mjs.map → eas-CXYo8hos.mjs.map} +1 -1
  89. package/dist/{encryption-CbMprdAb.mjs → encryption-B7IlQ6VO.mjs} +3 -3
  90. package/dist/{encryption-CbMprdAb.mjs.map → encryption-B7IlQ6VO.mjs.map} +1 -1
  91. package/dist/{encryption-BKWmbKkN.cjs → encryption-OPCsewWc.cjs} +6 -6
  92. package/dist/{encryption-BKWmbKkN.cjs.map → encryption-OPCsewWc.cjs.map} +1 -1
  93. package/dist/{engine-3imTFxdN.cjs → engine-BSnhQLaB.cjs} +105 -102
  94. package/dist/engine-BSnhQLaB.cjs.map +1 -0
  95. package/dist/{engine-DaI4iScI.mjs → engine-a6K99WIl.mjs} +12 -9
  96. package/dist/engine-a6K99WIl.mjs.map +1 -0
  97. package/dist/{github-Y6NAwHG1.cjs → github-C3gUSbLn.cjs} +18 -18
  98. package/dist/{github-Y6NAwHG1.cjs.map → github-C3gUSbLn.cjs.map} +1 -1
  99. package/dist/{github-Dijjr__H.mjs → github-D4hThtnt.mjs} +7 -7
  100. package/dist/{github-Dijjr__H.mjs.map → github-D4hThtnt.mjs.map} +1 -1
  101. package/dist/{googlePlay-Dcp3Yycu.cjs → googlePlay-C5Q7Zov3.cjs} +5 -5
  102. package/dist/{googlePlay-Dcp3Yycu.cjs.map → googlePlay-C5Q7Zov3.cjs.map} +1 -1
  103. package/dist/{googlePlay-SDT3j9Kf.mjs → googlePlay-DIS9PeFB.mjs} +4 -4
  104. package/dist/{googlePlay-SDT3j9Kf.mjs.map → googlePlay-DIS9PeFB.mjs.map} +1 -1
  105. package/dist/{iam-CqW9hsd2.mjs → iam-DloEBLXZ.mjs} +2 -2
  106. package/dist/{iam-CqW9hsd2.mjs.map → iam-DloEBLXZ.mjs.map} +1 -1
  107. package/dist/{iam-DeBQcSvw.cjs → iam-SxPKYCI_.cjs} +2 -2
  108. package/dist/{iam-DeBQcSvw.cjs.map → iam-SxPKYCI_.cjs.map} +1 -1
  109. package/dist/{index-DJzVO6Ht.d.cts → index-BThTZV8T.d.mts} +2 -2
  110. package/dist/{index-Ccsgoq3_.d.mts.map → index-BThTZV8T.d.mts.map} +1 -1
  111. package/dist/{index-Ccsgoq3_.d.mts → index-Cgd-ouyI.d.cts} +2 -2
  112. package/dist/{index-DJzVO6Ht.d.cts.map → index-Cgd-ouyI.d.cts.map} +1 -1
  113. package/dist/index.cjs +590 -246
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.mjs +443 -99
  116. package/dist/index.mjs.map +1 -1
  117. package/dist/{local-DjaAcHZb.cjs → local-B5R1WWEO.cjs} +3 -3
  118. package/dist/{local-DjaAcHZb.cjs.map → local-B5R1WWEO.cjs.map} +1 -1
  119. package/dist/{local-4gzM52HT.mjs → local-CMA_7b0_.mjs} +2 -2
  120. package/dist/{local-4gzM52HT.mjs.map → local-CMA_7b0_.mjs.map} +1 -1
  121. package/dist/{migrate-0Rfhftef.mjs → migrate-168wMF5m.mjs} +5 -5
  122. package/dist/{migrate-0Rfhftef.mjs.map → migrate-168wMF5m.mjs.map} +1 -1
  123. package/dist/{migrate-DDIc3twm.cjs → migrate-B0041tRF.cjs} +13 -13
  124. package/dist/{migrate-DDIc3twm.cjs.map → migrate-B0041tRF.cjs.map} +1 -1
  125. package/dist/{migrate-CuHGYJL9.cjs → migrate-BZxh_zU5.cjs} +6 -6
  126. package/dist/{migrate-CuHGYJL9.cjs.map → migrate-BZxh_zU5.cjs.map} +1 -1
  127. package/dist/{migrate-BLW4BwLd.mjs → migrate-BhnCtwMX.mjs} +3 -3
  128. package/dist/{migrate-BLW4BwLd.mjs.map → migrate-BhnCtwMX.mjs.map} +1 -1
  129. package/dist/openapi.cjs +1 -1
  130. package/dist/openapi.d.cts +2 -2
  131. package/dist/openapi.d.mts +2 -2
  132. package/dist/openapi.mjs +1 -1
  133. package/dist/{projectBucket-C5Ap5kGw.cjs → projectBucket-DEBaYEbi.cjs} +2 -2
  134. package/dist/{projectBucket-C5Ap5kGw.cjs.map → projectBucket-DEBaYEbi.cjs.map} +1 -1
  135. package/dist/{projectBucket-BhEOVVch.mjs → projectBucket-hF0-tlq9.mjs} +2 -2
  136. package/dist/{projectBucket-BhEOVVch.mjs.map → projectBucket-hF0-tlq9.mjs.map} +1 -1
  137. package/dist/{publish-BELe2FO2.cjs → publish-B-ffSuAX.cjs} +2 -2
  138. package/dist/{publish-BELe2FO2.cjs.map → publish-B-ffSuAX.cjs.map} +1 -1
  139. package/dist/{publish-DiDv40hA.mjs → publish-_lVOoWCy.mjs} +2 -2
  140. package/dist/{publish-DiDv40hA.mjs.map → publish-_lVOoWCy.mjs.map} +1 -1
  141. package/dist/{ready--_hMxbUX.cjs → ready-DCvnFZnJ.cjs} +2 -2
  142. package/dist/{ready--_hMxbUX.cjs.map → ready-DCvnFZnJ.cjs.map} +1 -1
  143. package/dist/{ready-CjIqXFXe.mjs → ready-sSPuiZ7N.mjs} +2 -2
  144. package/dist/{ready-CjIqXFXe.mjs.map → ready-sSPuiZ7N.mjs.map} +1 -1
  145. package/dist/reconcile/public.d.cts +1 -1
  146. package/dist/reconcile/public.d.mts +1 -1
  147. package/dist/{resolve-DIPHwLan.cjs → resolve-Cs38fbaX.cjs} +4 -4
  148. package/dist/{resolve-DIPHwLan.cjs.map → resolve-Cs38fbaX.cjs.map} +1 -1
  149. package/dist/{resolve-N8EZzWqJ.mjs → resolve-UK4b26dm.mjs} +4 -4
  150. package/dist/{resolve-N8EZzWqJ.mjs.map → resolve-UK4b26dm.mjs.map} +1 -1
  151. package/dist/{rollback-DIeA6dba.mjs → rollback-B0eg3M0J.mjs} +7 -6
  152. package/dist/{rollback-DIeA6dba.mjs.map → rollback-B0eg3M0J.mjs.map} +1 -1
  153. package/dist/{rollback-Bp6hepUh.cjs → rollback-DByniS9X.cjs} +10 -9
  154. package/dist/{rollback-Bp6hepUh.cjs.map → rollback-DByniS9X.cjs.map} +1 -1
  155. package/dist/{runtime-D_UphAAH.d.cts → runtime-BtoiRP5G.d.cts} +2 -2
  156. package/dist/{runtime-BZlClwy2.d.mts.map → runtime-BtoiRP5G.d.cts.map} +1 -1
  157. package/dist/{runtime-BZlClwy2.d.mts → runtime-Ct41f0tN.d.mts} +2 -2
  158. package/dist/{runtime-D_UphAAH.d.cts.map → runtime-Ct41f0tN.d.mts.map} +1 -1
  159. package/dist/{s3-Bwd6lhTU.cjs → s3-4rmPI6wv.cjs} +3 -3
  160. package/dist/{s3-Bwd6lhTU.cjs.map → s3-4rmPI6wv.cjs.map} +1 -1
  161. package/dist/{s3-CIEf4puu.mjs → s3-B-IJWFJA.mjs} +3 -3
  162. package/dist/{s3-CIEf4puu.mjs.map → s3-B-IJWFJA.mjs.map} +1 -1
  163. package/dist/{serverSetup-mRCLdZQW.mjs → serverSetup-Cok75j21.mjs} +7 -6
  164. package/dist/{serverSetup-mRCLdZQW.mjs.map → serverSetup-Cok75j21.mjs.map} +1 -1
  165. package/dist/{serverSetup-C9DP30J4.cjs → serverSetup-EY5vppoS.cjs} +9 -8
  166. package/dist/{serverSetup-C9DP30J4.cjs.map → serverSetup-EY5vppoS.cjs.map} +1 -1
  167. package/dist/{sniffer-CkPIytPI.cjs → sniffer-CcLTONfm.cjs} +7 -7
  168. package/dist/{sniffer-CkPIytPI.cjs.map → sniffer-CcLTONfm.cjs.map} +1 -1
  169. package/dist/{sniffer-01tbQFmg.mjs → sniffer-DIyYcOXJ.mjs} +7 -7
  170. package/dist/{sniffer-01tbQFmg.mjs.map → sniffer-DIyYcOXJ.mjs.map} +1 -1
  171. package/dist/{snsSubscriptions-DmKrw7AF.cjs → snsSubscriptions-Bore7t-W.cjs} +11 -12
  172. package/dist/{snsSubscriptions-DmKrw7AF.cjs.map → snsSubscriptions-Bore7t-W.cjs.map} +1 -1
  173. package/dist/{snsSubscriptions-k61hsIRw.mjs → snsSubscriptions-CYEVD7ml.mjs} +3 -4
  174. package/dist/{snsSubscriptions-k61hsIRw.mjs.map → snsSubscriptions-CYEVD7ml.mjs.map} +1 -1
  175. package/dist/{sst-DGsteg5j.cjs → sst-Bsu5O1Lt.cjs} +21 -8
  176. package/dist/sst-Bsu5O1Lt.cjs.map +1 -0
  177. package/dist/{sst-CvOnXAel.mjs → sst-DBH707Na.mjs} +19 -6
  178. package/dist/sst-DBH707Na.mjs.map +1 -0
  179. package/dist/stack-CwSx-6ea.cjs +11725 -0
  180. package/dist/stack-CwSx-6ea.cjs.map +1 -0
  181. package/dist/stack-DU2SunuO.mjs +10744 -0
  182. package/dist/stack-DU2SunuO.mjs.map +1 -0
  183. package/dist/{stage-CXIdtjY2.mjs → stage-BGyx0OjL.mjs} +5 -6
  184. package/dist/stage-BGyx0OjL.mjs.map +1 -0
  185. package/dist/{stage-8KJCtYtl.cjs → stage-BgD-kKY3.cjs} +11 -12
  186. package/dist/stage-BgD-kKY3.cjs.map +1 -0
  187. package/dist/{stages-BNoiMXfL.mjs → stages-DFvE7iEO.mjs} +2 -2
  188. package/dist/{stages-BNoiMXfL.mjs.map → stages-DFvE7iEO.mjs.map} +1 -1
  189. package/dist/{stages-tdJKM9qp.cjs → stages-Dk6Lv7DY.cjs} +2 -2
  190. package/dist/{stages-tdJKM9qp.cjs.map → stages-Dk6Lv7DY.cjs.map} +1 -1
  191. package/dist/target/public.cjs +1 -1
  192. package/dist/target/public.d.cts +2 -2
  193. package/dist/target/public.d.mts +2 -2
  194. package/dist/target/public.mjs +1 -1
  195. package/dist/{terminal-GzAW5lzO.mjs → terminal-BlJ90AIM.mjs} +2 -2
  196. package/dist/{terminal-GzAW5lzO.mjs.map → terminal-BlJ90AIM.mjs.map} +1 -1
  197. package/dist/{terminal-DSQgidon.cjs → terminal-GyXHsRAl.cjs} +5 -5
  198. package/dist/{terminal-DSQgidon.cjs.map → terminal-GyXHsRAl.cjs.map} +1 -1
  199. package/dist/{types-BRnmoWCt.d.cts → types-BVDaaLas.d.cts} +22 -4
  200. package/dist/{types-BRnmoWCt.d.cts.map → types-BVDaaLas.d.cts.map} +1 -1
  201. package/dist/{types-Bg7LSAD2.d.mts → types-CJTKWLkK.d.mts} +22 -4
  202. package/dist/{types-Bg7LSAD2.d.mts.map → types-CJTKWLkK.d.mts.map} +1 -1
  203. package/dist/{utils-D_fxUqvU.mjs → utils-CdKxD8Lt.mjs} +2 -2
  204. package/dist/{utils-D_fxUqvU.mjs.map → utils-CdKxD8Lt.mjs.map} +1 -1
  205. package/dist/{utils-D2Nk1Nv2.cjs → utils-DBqXbB8P.cjs} +2 -2
  206. package/dist/{utils-D2Nk1Nv2.cjs.map → utils-DBqXbB8P.cjs.map} +1 -1
  207. package/dist/vitest.cjs +1 -1
  208. package/dist/vitest.mjs +1 -1
  209. package/dist/workspace/index.cjs +1 -1
  210. package/dist/workspace/index.d.cts +2 -2
  211. package/dist/workspace/index.d.mts +2 -2
  212. package/dist/workspace/index.mjs +1 -1
  213. package/dist/{workspace-fGwzXa5l.cjs → workspace-CTspddnJ.cjs} +55 -16
  214. package/dist/workspace-CTspddnJ.cjs.map +1 -0
  215. package/dist/{workspace-DTX6CJi2.mjs → workspace-CdiCMRap.mjs} +55 -16
  216. package/dist/workspace-CdiCMRap.mjs.map +1 -0
  217. package/package.json +16 -16
  218. package/dist/apps-CXzjaPWR.mjs +0 -4650
  219. package/dist/apps-CXzjaPWR.mjs.map +0 -1
  220. package/dist/apps-vLzb0ZSA.cjs +0 -5174
  221. package/dist/apps-vLzb0ZSA.cjs.map +0 -1
  222. package/dist/clientTelemetry-Ej1tf1VE.d.cts.map +0 -1
  223. package/dist/clientTelemetry-crdjgehZ.d.mts.map +0 -1
  224. package/dist/compose-CJznzQc7.mjs.map +0 -1
  225. package/dist/compose-CKBieltT.cjs.map +0 -1
  226. package/dist/compose-CvNyjqwL.cjs.map +0 -1
  227. package/dist/compose-DPXoarGI.mjs.map +0 -1
  228. package/dist/deploy-BaSYxpny.cjs.map +0 -1
  229. package/dist/deploy-C_uZBzvS.mjs.map +0 -1
  230. package/dist/dns-BzYrbB2Y.cjs.map +0 -1
  231. package/dist/dns-C0wbTjVX.mjs.map +0 -1
  232. package/dist/docker-CPoUMg5X.mjs +0 -1649
  233. package/dist/docker-CPoUMg5X.mjs.map +0 -1
  234. package/dist/docker-CrhpQWnL.cjs +0 -1798
  235. package/dist/docker-CrhpQWnL.cjs.map +0 -1
  236. package/dist/engine-3imTFxdN.cjs.map +0 -1
  237. package/dist/engine-DaI4iScI.mjs.map +0 -1
  238. package/dist/notes-6F8YXU8m.mjs +0 -409
  239. package/dist/notes-6F8YXU8m.mjs.map +0 -1
  240. package/dist/notes-DMOLnNJI.cjs +0 -510
  241. package/dist/notes-DMOLnNJI.cjs.map +0 -1
  242. package/dist/sst-CvOnXAel.mjs.map +0 -1
  243. package/dist/sst-DGsteg5j.cjs.map +0 -1
  244. package/dist/stack-Dd-egttk.mjs +0 -1777
  245. package/dist/stack-Dd-egttk.mjs.map +0 -1
  246. package/dist/stack-vBnc84e8.cjs +0 -1887
  247. package/dist/stack-vBnc84e8.cjs.map +0 -1
  248. package/dist/stage-8KJCtYtl.cjs.map +0 -1
  249. package/dist/stage-CXIdtjY2.mjs.map +0 -1
  250. package/dist/workspace-DTX6CJi2.mjs.map +0 -1
  251. package/dist/workspace-fGwzXa5l.cjs.map +0 -1
@@ -1,4650 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { t as GkmError } from "./errors-C9uIyIDt.mjs";
3
- import { C as providerOf, F as externalsManifestName, S as eventsBackendFor, _t as gkmHome, x as cacheBackendFor } from "./dns-C0wbTjVX.mjs";
4
- import { Pt as checkStageBackups, Rt as isReservedStageKey, _ as PUBLIC_ENV_PREFIXES, a as allConstructGlobs, dt as fileServerLabel, j as TEST_STAGE, ot as appKey, z as telemetryEnv } from "./workspace-DTX6CJi2.mjs";
5
- import { $ as hostFor$1, B as NOTIFICATION_RULE_PREFIX, D as PgBossNeedsDatabase, J as emulatorQueueUrl, K as EMULATOR_REGION, N as scopeTelemetryEnv, O as TELEMETRY_CONTAINER, Q as caddyfileRoot, St as otlpHeaders, U as objectsWebhookToken, V as minioNotificationRule, W as watchedBuckets, X as CADDY_SITES_IN_CONTAINER, Y as emulatorTopicArn, b as REDIS_PASSWORD_KEY, ct as portsOf, dt as serviceAddresses, et as hostsFor, f as savePortState, h as postgresRoleSlug, ht as LOGS_PASSWORD_KEY, j as appTelemetry, k as planFor, l as loadPortState, lt as postgresImage, m as loadLocalCredentials, mt as LOGS_ORG, n as composeFor, nt as toCaddyfile, pt as LOGS_EMAIL_KEY, q as emulatorEndpoint, r as toYaml, st as portKeys, t as CLUSTER_DATABASE, tt as sitesFor, ut as primaryPortKey, v as saveLocalCredentials, z as HOST_GATEWAY } from "./compose-CJznzQc7.mjs";
6
- import { c as INBOX_RELAY_TOKEN_KEY, d as inboxWebhookUrl, i as readFakes, l as inboxRelayToken, o as objectsRoute, r as readCredentialFakes, u as inboxRelayWorker } from "./SubscriberGenerator-Cfoz8uTY.mjs";
7
- import { u as telemetryArgs } from "./EndpointGenerator-CBKH87_b.mjs";
8
- import { i as discover, w as workerEdges, x as eventsEdgeBucket } from "./discover-Dfmn6HQ7.mjs";
9
- import { createRequire } from "node:module";
10
- import { dirname, isAbsolute, join, parse, posix, relative, sep } from "node:path";
11
- import { existsSync, readFileSync } from "node:fs";
12
- import { chmod, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
13
- import { networkInterfaces } from "node:os";
14
- import { execFile, spawn } from "node:child_process";
15
- import { createServer } from "node:net";
16
- import { createHash, randomBytes } from "node:crypto";
17
- import { ensureLocalAuthority, ensureLocalCertificate, localAuthorityPaths, localCertificateNames } from "@geekmidas/edge/certificates/local";
18
- import { DEFAULT_POSTGRES_VERSION, EDGE_TOKEN_KEY, PUBLIC_PREFIX, TELEMETRY_KEYS, cacheTable, cookieDomain, dependenciesOf, dependentsOf, drawSecret, environmentCase, externalApiUrl, imageOrigins, imageOriginsFor, isPublicDeclaration, kebabCase, mobileOrigins, providedKeyFor, provisionOrder, publicEnvFor, publicValues, reachesServerHalf, schemeBase, senderAddress, wildcardDomainOf } from "@geekmidas/manifest";
19
- import { fileURLToPath } from "node:url";
20
- import { formatKeyring } from "@geekmidas/constructs/encryption";
21
- import { ownerRole, readerRole, roleStatements } from "@geekmidas/db/pg/roles";
22
- import * as snsUrl from "@geekmidas/events/sns/url";
23
- import * as sqsUrl from "@geekmidas/events/sqs/url";
24
- import * as s3Url from "@geekmidas/storage/s3-url";
25
- import { cacheTableStatements } from "@geekmidas/cache/postgres";
26
- import { promisify } from "node:util";
27
- import { CreateBucketCommand, DeleteBucketLifecycleCommand, GetBucketLifecycleConfigurationCommand, GetBucketNotificationConfigurationCommand, GetBucketPolicyCommand, HeadBucketCommand, ListBucketsCommand, PutBucketLifecycleConfigurationCommand, PutBucketNotificationConfigurationCommand, PutBucketPolicyCommand, S3Client } from "@aws-sdk/client-s3";
28
- import { CreateTopicCommand, GetTopicAttributesCommand, SNSClient } from "@aws-sdk/client-sns";
29
- import { CreateQueueCommand, GetQueueUrlCommand, SQSClient } from "@aws-sdk/client-sqs";
30
- import { Client } from "pg";
31
- //#region src/providers/dns.ts
32
- /** Whether the workspace deploys through the compose target. */
33
- function deploysWithCompose(workspace) {
34
- return workspace.deploy?.default === "compose" || Object.values(workspace.apps).some((app) => app.resolvedDeployTarget === "compose");
35
- }
36
- //#endregion
37
- //#region src/backups/config.ts
38
- /**
39
- * Which stages take backups, and where they are kept.
40
- *
41
- * A deployed compose stage whose stack runs Postgres is backed up by
42
- * default — every day at 02:00 UTC, kept 30 days — unless
43
- * `deploy.backups.<stage>` says otherwise. The local stage never is.
44
- *
45
- * Every backup is kept in the project bucket (`providers/projectBucket.ts`),
46
- * beside the stage's deploy state, one folder per run and one file per
47
- * database:
48
- *
49
- * ```
50
- * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/database.sql.gz
51
- * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/auth-database.sql.gz
52
- * ```
53
- *
54
- * Beside the runs, `imports/` holds files prepared by hand for
55
- * `gkm backup:restore --from` — never listed as a run, never expired.
56
- *
57
- * The file is named after the database's construct, the way its migrations
58
- * folder is: `AuthDatabase` is `db/auth-database`, and `auth-database.sql.gz`.
59
- */
60
- /** Whether the stack runs Postgres: some construct is a database. */
61
- function runsPostgres(manifest) {
62
- return Object.values(manifest).some((d) => d.kind === "database");
63
- }
64
- /**
65
- * What `stage`'s backups are: on — by its entry or the default — off by
66
- * `false`, or none, for the local stage, a stage compose does not deploy,
67
- * and a stack with no database.
68
- */
69
- function stageBackups(workspace, manifest, stage) {
70
- if (stage === workspace.stages?.local) return {
71
- mode: "none",
72
- reason: "local"
73
- };
74
- if (!deploysWithCompose(workspace)) return {
75
- mode: "none",
76
- reason: "not-compose"
77
- };
78
- if (!runsPostgres(manifest)) return {
79
- mode: "none",
80
- reason: "no-postgres"
81
- };
82
- const value = (workspace.deploy?.backups)?.[stage];
83
- const checked = checkStageBackups(stage, value ?? {});
84
- if (checked === false) return { mode: "disabled" };
85
- return {
86
- mode: "on",
87
- backups: checked,
88
- source: value === void 0 ? "default" : "config"
89
- };
90
- }
91
- /**
92
- * Where a stage's backups are, in the project bucket — under the same
93
- * `<prefix>/<project>/<stage>` its deploy state is: `gkm/shop/production/backups`.
94
- */
95
- function backupsPrefix(workspace, stage) {
96
- const state = workspace.state;
97
- const prefix = state?.provider === "s3" && state.prefix !== void 0 ? state.prefix.replace(/\/+$/, "") : "gkm";
98
- return `${prefix ? `${prefix}/` : ""}${workspace.name}/${stage}/backups`;
99
- }
100
- /** A run folder's time back, or `undefined` for a key that is not one. */
101
- function runTime(folder) {
102
- const match = /^(\d{4}-\d{2}-\d{2})\/(\d{2})-(\d{2})-(\d{2})Z$/.exec(folder);
103
- if (!match) return void 0;
104
- const at = /* @__PURE__ */ new Date(`${match[1]}T${match[2]}:${match[3]}:${match[4]}Z`);
105
- return Number.isNaN(at.getTime()) ? void 0 : at;
106
- }
107
- /** A database's file in a run's folder: `auth-database.sql.gz`. */
108
- function backupFile(database) {
109
- return `${database.file}.sql.gz`;
110
- }
111
- /** Each database the stack runs, by its construct and its name in Postgres. */
112
- function backupDatabases(resources) {
113
- return resources.filter((r) => r.kind === "database").map((r) => ({
114
- id: r.id,
115
- file: kebabCase(r.id),
116
- name: r.name
117
- })).sort((a, b) => a.file.localeCompare(b.file));
118
- }
119
- /**
120
- * The expiry of every stage's backups, by each stage's own entry — what the
121
- * project bucket's lifecycle carries beside its own rule.
122
- *
123
- * A put replaces a bucket's whole lifecycle, so this is built from every
124
- * deployed stage each time, never from the stage being deployed alone: one
125
- * stage's deploy keeps every other's rule. A stage set to `false` has none,
126
- * and its backups are kept until someone deletes them.
127
- *
128
- * The rule covers the runs and nothing else beside them: a lifecycle filter
129
- * cannot leave a folder out, so it matches what every run folder starts
130
- * with — its year, `2…` — and the stage's `imports/` is never expired.
131
- */
132
- function backupExpiries(workspace, manifest) {
133
- const expiries = [];
134
- for (const stage of [...workspace.stages?.deployed ?? []].sort()) {
135
- const choice = stageBackups(workspace, manifest, stage);
136
- if (choice.mode !== "on") continue;
137
- expiries.push({
138
- id: `gkm-backups-${stage}`,
139
- prefix: `${backupsPrefix(workspace, stage)}/2`,
140
- days: choice.backups.keepDays,
141
- abortIncompleteDays: 1
142
- });
143
- }
144
- return expiries;
145
- }
146
- //#endregion
147
- //#region src/reconcile/signedOrigins.ts
148
- /**
149
- * Where each bucket's presigned links point, derived from its connection.
150
- *
151
- * Not stored and not provisioned: the origin is a function of the connection
152
- * string (`s3Url.signedOrigin`), so it is computed wherever the connection is
153
- * resolved — a stage's secrets, MinIO locally — and can never disagree with
154
- * the links the bucket's client signs.
155
- */
156
- /**
157
- * `<ID>_SIGNED_ORIGIN` for each bucket whose connection `lookup` resolves to
158
- * an `s3://` URL with a knowable host. A bucket with none, or another scheme,
159
- * gets nothing rather than a guess.
160
- */
161
- function signedOrigins(buckets, lookup) {
162
- const origins = {};
163
- for (const id of buckets) {
164
- const connection = lookup(providedKeyFor(id, "objects", "connectionString"));
165
- if (!connection?.startsWith("s3:")) continue;
166
- let origin;
167
- try {
168
- origin = s3Url.signedOrigin(s3Url.parse(connection));
169
- } catch {
170
- continue;
171
- }
172
- if (origin) origins[providedKeyFor(id, "objects", "signedOrigin")] = origin;
173
- }
174
- return origins;
175
- }
176
- //#endregion
177
- //#region src/reconcile/env.ts
178
- /**
179
- * The URLs a reconciled stage injects.
180
- *
181
- * One `<NAME>_URL` per construct, and the protocol picks the driver. This is the
182
- * seam between the target that writes a URL and the client that parses it, so
183
- * every component of it is read off the resource — never inherited from ambient
184
- * environment. A bucket can live in a different region than the function reading
185
- * it, and `AWS_REGION` in a Lambda is the *function's* region, so a URL that
186
- * omits `?region=` breaks cross-region silently at runtime.
187
- *
188
- * Locally that self-containment is what lets the port be whatever was free: the
189
- * app reads `ORDERS_URL` and never sees a host or a port.
190
- */
191
- /** Where Node reads extra roots from: gkm's local CA, behind the local edge. */
192
- const LOCAL_CA_KEY = "NODE_EXTRA_CA_CERTS";
193
- /** The host containers are published on. */
194
- const LOCAL_HOST = "localhost";
195
- /** The region local buckets claim, so the client has one to sign with. */
196
- const LOCAL_REGION = "us-east-1";
197
- /**
198
- * The credentials the S3 client resolves for MinIO.
199
- *
200
- * An `s3://` URL deliberately carries none: deployed, the SDK reads them from
201
- * the execution role, so a URL that embedded a key would be one more thing to
202
- * rotate and one more thing to leak into a log. Locally there is no role, and
203
- * the same chain reads these — which is why they are injected beside the URL
204
- * rather than written into it.
205
- */
206
- function storageCredentials(credentials) {
207
- return {
208
- AWS_ACCESS_KEY_ID: credentials.minio.user,
209
- AWS_SECRET_ACCESS_KEY: credentials.minio.password,
210
- AWS_REGION: LOCAL_REGION
211
- };
212
- }
213
- /** The port Mailpit's inbox — its web UI and HTTP API — is published under. */
214
- const MAILPIT_INBOX_PORT = "mailpit-web";
215
- /** The schema pg-boss keeps its tables in, inside the declared database. */
216
- const PGBOSS_SCHEMA = "pgboss";
217
- /** The exchange every local topic and queue shares on RabbitMQ. */
218
- const RABBITMQ_EXCHANGE = "gkm.events";
219
- /** The credential `options` describe. */
220
- function credentialOf(options) {
221
- return {
222
- containers: options.credentials,
223
- ...options.seed ? { seed: options.seed } : {}
224
- };
225
- }
226
- /**
227
- * What project code run against a stage is handed — a migration, a seed, an
228
- * app under `gkm dev`, `gkm exec`'s command, `gkm compose`'s seeds: the
229
- * stage's stored secrets, under every value the stage resolved.
230
- *
231
- * One merge for every command, so a seed sees the same keys whichever one
232
- * runs it. Each command supplies only what is its own — the ports it reaches
233
- * the containers on, their logins — as inputs to {@link envFor}.
234
- *
235
- * The resolved values win: they are the statement of what exists, and a
236
- * stored URL naming an old port is the drift resolution replaces. A command
237
- * whose stage says a value by hand (a deployed stack's) leaves that key out
238
- * of `resolved`.
239
- */
240
- function stageEnv(stored, resolved) {
241
- return {
242
- ...stored,
243
- ...resolved
244
- };
245
- }
246
- /**
247
- * The token a stack's own services prove themselves with at its edge
248
- * (`EDGE_TOKEN_HEADER`): derived from the stage's seed, as a bucket's webhook
249
- * token is, so every process, the edge and the auth server agree on it with
250
- * nothing stored.
251
- */
252
- function edgeToken(project, seed) {
253
- return createHash("sha256").update(`${seed ? `${seed}:` : ""}${project}:edge-token`).digest("base64url").slice(0, 43);
254
- }
255
- /**
256
- * Every env key a reconciled plan resolves, and its value.
257
- *
258
- * Keys come from the declaration rather than being re-derived, so what the build
259
- * publishes and what the app reads cannot drift.
260
- */
261
- function envFor(plan, options) {
262
- const env = {};
263
- const credential = credentialOf(options);
264
- const resolved = {};
265
- const devices = options.lanAddress ? deviceBuckets(plan) : /* @__PURE__ */ new Set();
266
- for (const resource of plan.resources) {
267
- const url = urlFor(resource, plan, options.ports, options.project ?? "", options.addresses, credential, devices.has(resource.id) ? options.lanAddress : void 0);
268
- if (url) resolved[resource.id] = url;
269
- }
270
- const aliased = aliasAddressesFor(plan, options);
271
- for (const resource of plan.resources) {
272
- const url = resolved[resource.id];
273
- if (resource.kind === "rest-api") Object.assign(env, surfaceEnv(resource, url, resolved, {
274
- plan,
275
- aliased,
276
- ...options.addresses ? { addresses: options.addresses } : {},
277
- ...options.lanAddress ? { lanAddress: options.lanAddress } : {},
278
- ...options.metroPorts ? { metroPorts: options.metroPorts } : {}
279
- }));
280
- if (resource.kind === "websocket-api") {
281
- const origins = surfaceEnv(resource, url, resolved, { aliased })[providedKeyFor(resource.id, resource.kind, "trustedOrigins")];
282
- if (origins !== void 0) env[providedKeyFor(resource.id, resource.kind, "trustedOrigins")] = origins;
283
- const publisher = webSocketPublisher(resource, options.ports, options.project ?? "", credential);
284
- if (publisher) env[providedKeyFor(resource.id, resource.kind, "publisherConnectionString")] = publisher;
285
- }
286
- if (url) env[resource.envKey] = url;
287
- if (resource.kind === "site" && resource.protectedSubdomains && url) {
288
- const domain = wildcardDomainOf(new URL(url).hostname);
289
- if (domain) {
290
- env[providedKeyFor(resource.id, resource.kind, "domain")] = domain;
291
- env[providedKeyFor(resource.id, resource.kind, "protectedSubdomains")] = resource.protectedSubdomains.join(",");
292
- }
293
- }
294
- if (isDatabase(resource.kind) && resource.roles !== false) {
295
- const owner = ownerUrl(resource, plan, options.ports, options.project ?? "", credential);
296
- if (owner) env[providedKeyFor(resource.id, resource.kind, "ownerUrl")] = owner;
297
- }
298
- if (resource.kind === "external-api" && url && resource.fake) env[providedKeyFor(resource.id, resource.kind, "credentials")] = resource.fake.credentials;
299
- if (resource.kind === "credential" && resource.fakeCredentials !== void 0) env[resource.envKey] = resource.fakeCredentials;
300
- if (resource.kind === "telemetry" && url) {
301
- const login = options.credentials.logs;
302
- Object.assign(env, telemetryEnv({
303
- endpoint: url,
304
- headers: otlpHeaders(login.email, login.password)
305
- }, 1));
306
- }
307
- if (resource.kind === "inbox" && url) {
308
- const base = resource.id.toLowerCase();
309
- const stage = resource.name === base ? void 0 : resource.name.slice(base.length + 1);
310
- env[providedKeyFor(resource.id, resource.kind, "domain")] = [
311
- stage,
312
- options.project,
313
- LOCAL_HOST
314
- ].filter(Boolean).join(".");
315
- const smtp = options.ports[primaryPortKey("mailpit")];
316
- if (smtp !== void 0) env[providedKeyFor(resource.id, resource.kind, "smtpUrl")] = `smtp://${LOCAL_HOST}:${smtp}`;
317
- }
318
- if (resource.kind === "email" && url) {
319
- env[providedKeyFor(resource.id, resource.kind, "from")] = senderAddress(resource, options.mailDomain ?? LOCAL_HOST);
320
- const inbox = options.ports[MAILPIT_INBOX_PORT];
321
- if (inbox !== void 0) env[providedKeyFor(resource.id, resource.kind, "inboxUrl")] = `http://${LOCAL_HOST}:${inbox}`;
322
- }
323
- }
324
- Object.assign(env, signedOrigins(plan.resources.filter((r) => r.kind === "objects").map((r) => r.id), (key) => env[key]));
325
- Object.assign(env, publicEnv(plan, env, options.addresses));
326
- Object.assign(env, brokerEnv(plan, options.ports, credential));
327
- const relay = env.EVENT_PUBLISHER_CONNECTION_STRING;
328
- if (relay && options.relayedBuckets?.length) for (const resource of plan.resources) {
329
- if (resource.kind !== "objects" || resource.container !== "minio") continue;
330
- if (!options.relayedBuckets.includes(resource.id)) continue;
331
- if (!env[resource.envKey]) continue;
332
- env[providedKeyFor(resource.id, resource.kind, "eventsConnectionString")] = relay;
333
- env[providedKeyFor(resource.id, resource.kind, "eventsToken")] = objectsWebhookToken(options.project ?? "", resource.id, credential.seed);
334
- }
335
- if (plan.resources.some((r) => r.kind === "inbox" && env[r.envKey])) env[INBOX_RELAY_TOKEN_KEY] = inboxRelayToken(options.project ?? "", credential.seed);
336
- if (plan.resources.some((r) => (r.kind === "rest-api" || r.kind === "websocket-api") && env[r.envKey])) env[EDGE_TOKEN_KEY] = edgeToken(options.project ?? "", credential.seed);
337
- if (plan.resources.some((r) => r.kind === "objects" && env[r.envKey])) Object.assign(env, storageCredentials(options.credentials));
338
- return env;
339
- }
340
- /**
341
- * The values a site's bundler inlines, under the names it inlines them by.
342
- *
343
- * A rename and nothing more. `API_URL` was resolved once, by the same code that
344
- * resolved it for the server; a site reads the same value under `VITE_API_URL`
345
- * because that prefix is how its bundler is told to ship it. Nothing is derived
346
- * twice, so a site and its API cannot come to disagree about where the API is.
347
- *
348
- * A source that resolved to nothing is skipped rather than written empty: an
349
- * inlined empty string is a frontend that builds and then fails at runtime
350
- * against `http:///`, where a missing variable fails at build with the name of
351
- * the thing that is missing.
352
- */
353
- function publicEnv(plan, resolved, addresses = {}) {
354
- const env = {};
355
- const owners = new Map(plan.resources.map((r) => [r.envKey, r.id]));
356
- for (const resource of plan.resources) {
357
- for (const [key, source] of Object.entries(resource.publicEnv ?? {})) {
358
- const value = (resource.kind === "mobile-app" ? addresses[owners.get(source) ?? ""] : void 0) ?? resolved[source];
359
- if (value) env[key] = value;
360
- }
361
- if (resource.imageOrigins) {
362
- const origins = imageOrigins(resource.imageOrigins.sources, (key) => resolved[key]);
363
- if (origins) env[resource.imageOrigins.key] = origins;
364
- }
365
- }
366
- return env;
367
- }
368
- /**
369
- * What a surface publishes beyond its own address: who may call it, and where
370
- * a cookie set by it is readable.
371
- *
372
- * Both are read off the same list — the constructs that declared an edge to
373
- * this surface — which is why neither appears in application code. A surface
374
- * that listed its own callers would be edited every time something new called
375
- * it, and the thing being edited is already recorded in the graph.
376
- *
377
- * An empty origin list is written, and a surface with no address writes nothing
378
- * at all. The two cases look alike and are not: "nothing depends on this yet" is
379
- * a real state a target should publish, while "this surface has no address here"
380
- * means it is not running in this stage, and keys belong with the address they
381
- * describe.
382
- */
383
- function surfaceEnv(resource, url, resolved = {}, local = {}) {
384
- if (!url) return {};
385
- const origins = [...new Set((resource.callers ?? []).flatMap((caller) => resolved[caller] ? [resolved[caller], ...local.aliased?.[caller] ?? []] : []).map(originOf).filter((origin) => Boolean(origin)))].sort();
386
- const domain = cookieDomain([url, ...origins]);
387
- const mobile = (resource.callers ?? []).map((caller) => local.plan?.resources.find((r) => r.id === caller && r.kind === "mobile-app")).filter((caller) => Boolean(caller));
388
- const hosts = [...local.lanAddress ? [local.lanAddress] : [], LOCAL_HOST];
389
- const schemes = mobile.flatMap((caller) => {
390
- const scheme = resolved[caller.id];
391
- const port = local.metroPorts?.[caller.id];
392
- return scheme ? mobileOrigins(scheme, {
393
- hosts,
394
- ...port ? { port } : {}
395
- }) : [];
396
- });
397
- const own = local.addresses?.[resource.id];
398
- const device = mobile.length > 0 && local.lanAddress && own ? own.replace(/\/\/(localhost|127\.0\.0\.1)(?=[:/]|$)/, `//${local.lanAddress}`) : void 0;
399
- return {
400
- [providedKeyFor(resource.id, resource.kind, "trustedOrigins")]: [...origins, ...new Set(schemes)].join(","),
401
- ...domain ? { [providedKeyFor(resource.id, resource.kind, "cookieDomain")]: domain } : {},
402
- ...device ? { [providedKeyFor(resource.id, resource.kind, "deviceUrl")]: device } : {}
403
- };
404
- }
405
- /**
406
- * Every construct's alias addresses: where a target placed them, and
407
- * otherwise — behind the local edge — each alias under the project, on the
408
- * edge's port, as {@link hostsFor} names it. Never a redirect's.
409
- */
410
- function aliasAddressesFor(plan, options) {
411
- if (options.aliasAddresses) return { ...options.aliasAddresses };
412
- const edge = plan.containers.includes("caddy") ? options.ports[primaryPortKey("caddy")] : void 0;
413
- if (edge === void 0) return {};
414
- const aliased = {};
415
- for (const resource of plan.resources) {
416
- if (!resource.aliases?.length) continue;
417
- if (!options.addresses?.[resource.id]) continue;
418
- aliased[resource.id] = hostsFor(resource, options.project ?? "").aliases.map((host) => `https://${host}:${edge}`);
419
- }
420
- return aliased;
421
- }
422
- /**
423
- * The buckets whose links a phone opens: those a surface a mobile app calls
424
- * depends on.
425
- *
426
- * The surface hands the app a URL it built — a file server's public link, a
427
- * bucket's presigned one — and the phone cannot resolve `*.localhost`, or
428
- * reach `localhost` at all. A presigned URL's signature covers its host, so
429
- * nothing downstream can move it either: the bucket has to be resolved on the
430
- * LAN address in the first place.
431
- */
432
- function deviceBuckets(plan) {
433
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
434
- const fromApp = (id) => {
435
- const caller = byId.get(id);
436
- if (caller?.kind === "mobile-app") return true;
437
- return (caller?.kind === "rest-api" || caller?.kind === "websocket-api") && (caller.callers ?? []).some((c) => byId.get(c)?.kind === "mobile-app");
438
- };
439
- const buckets = new Set(plan.resources.filter((r) => r.kind === "objects" || r.kind === "file-server").filter((r) => (r.callers ?? []).some(fromApp)).map((r) => r.id));
440
- for (const r of plan.resources) if (r.kind === "file-server" && r.of && buckets.has(r.of)) buckets.add(r.id);
441
- return buckets;
442
- }
443
- /**
444
- * Where a WebSocket surface's publisher meets its sockets: the local Redis,
445
- * on channels named for the project and the surface, so two projects sharing
446
- * one Redis never see each other's frames.
447
- */
448
- function webSocketPublisher(resource, ports, project, credential) {
449
- const port = ports[primaryPortKey("redis")];
450
- if (port === void 0) return void 0;
451
- const channel = encodeURIComponent(`gkm:ws:${project ? `${project}:` : ""}${resource.id}`);
452
- return `redis://:${encodeURIComponent(credential.containers.redis.password)}@${LOCAL_HOST}:${port}?channel=${channel}`;
453
- }
454
- /**
455
- * An address reduced to the origin a browser compares against.
456
- *
457
- * A WebSocket surface's address is `wss://`, but its host is served over
458
- * HTTPS like any other: its origin is that one, and a non-web scheme among the
459
- * origins means a mobile app to whoever reads the list.
460
- */
461
- function originOf(address) {
462
- try {
463
- return new URL(address.replace(/^ws(s?):/, "http$1:")).origin;
464
- } catch {
465
- return;
466
- }
467
- }
468
- /**
469
- * The runtime role of whatever a derived node hangs off.
470
- *
471
- * A reader's parent may itself be a schema tenant, so this follows `of` by one
472
- * hop rather than assuming the cluster — the reader of a tenant reads that
473
- * tenant's schema, not the database's.
474
- */
475
- function parentRole(resource, plan) {
476
- const parent = plan.resources.find((r) => r.id === resource.of);
477
- return parent ? localRole(parent) : resource.name;
478
- }
479
- /** Whether a kind connects to Postgres and therefore has an owner role. */
480
- function isDatabase(kind) {
481
- return kind === "database" || kind === "database-schema";
482
- }
483
- /**
484
- * The URL a migrator connects with — the owner role, which can create, alter
485
- * and drop.
486
- *
487
- * Never in `provides`, which is the whole point. A handler that could reach this
488
- * could `DROP TABLE`, and the security property the role split exists for is
489
- * that it cannot: the value is injected by `gkm exec` for the migrate step and
490
- * by nothing else.
491
- */
492
- function ownerUrl(resource, plan, ports, project, credential) {
493
- if (!resource.container) return void 0;
494
- const port = ports[primaryPortKey(resource.container)];
495
- if (port === void 0) return void 0;
496
- const owner = ownerRole(localRole(resource));
497
- return postgres(port, rootDatabase(resource, plan), {
498
- user: owner,
499
- password: localRolePassword(project, plan, owner, credential.seed)
500
- });
501
- }
502
- /**
503
- * The shared broker keys, when anything is published or consumed.
504
- *
505
- * A queue's own key is the producer's. These two are the *connection* itself,
506
- * which locally is one broker for every queue and topic in the project: the
507
- * generated pollers open a single connection and subscribe each worker by name
508
- * on it. Deployed there is no such thing — a Lambda is handed its own event
509
- * source — so this pair exists for the local target and says so.
510
- */
511
- function brokerEnv(plan, ports, credential) {
512
- const carrier = plan.resources.find((r) => r.kind === "queue" || r.kind === "topic");
513
- const publisher = carrier ? urlFor(carrier, plan, ports, "", {}, credential) : plan.workerBroker ? workerBroker(plan, ports, credential) : void 0;
514
- if (!publisher) return {};
515
- if (plan.events === "sns") return {};
516
- return { EVENT_PUBLISHER_CONNECTION_STRING: publisher };
517
- }
518
- /**
519
- * The broker a worker schedules its crons through, when nothing else declared
520
- * one — pg-boss in the declared database, on that database's port.
521
- */
522
- function workerBroker(plan, ports, credential) {
523
- const database = plan.resources.find((r) => r.kind === "database");
524
- if (!database?.container) return void 0;
525
- const port = ports[primaryPortKey(database.container)];
526
- return port === void 0 ? void 0 : broker(plan, port, credential);
527
- }
528
- /**
529
- * The URL for one planned resource.
530
- *
531
- * Every part of it comes from the resource and the port it was published on.
532
- */
533
- function urlFor(resource, plan, ports, project, addresses, credential, lan) {
534
- if (resource.kind === "secret") return localSecret(project, plan, resource);
535
- if (resource.kind === "encryption") return localKeyring(project, plan, resource);
536
- if (resource.kind === "mobile-app") return schemeBase(project, resource.scheme);
537
- if (resource.kind === "credential") return void 0;
538
- if (resource.kind === "external-api") {
539
- if (!resource.fake) return resource.url === void 0 ? void 0 : externalApiUrl({
540
- id: resource.id,
541
- url: resource.url
542
- }, plan.stage);
543
- const port = ports[resource.fake.key];
544
- return port === void 0 ? void 0 : `http://${LOCAL_HOST}:${port}`;
545
- }
546
- if (resource.kind === "rest-api" || resource.kind === "site") {
547
- const address = addresses?.[resource.id];
548
- const edge = plan.containers.includes("caddy") ? ports[primaryPortKey("caddy")] : void 0;
549
- return address && edge !== void 0 ? `https://${hostFor$1(resource, project)}:${edge}` : address;
550
- }
551
- if (resource.kind === "websocket-api") {
552
- const address = addresses?.[resource.id];
553
- const edge = plan.containers.includes("caddy") ? ports[primaryPortKey("caddy")] : void 0;
554
- return address && edge !== void 0 ? `wss://${hostFor$1(resource, project)}:${edge}` : address?.replace(/^http/, "ws");
555
- }
556
- if (!resource.container) return void 0;
557
- const port = ports[primaryPortKey(resource.container)];
558
- if (port === void 0) return void 0;
559
- switch (resource.kind) {
560
- case "database":
561
- case "database-schema":
562
- case "database-reader": {
563
- const database = rootDatabase(resource, plan);
564
- if (resource.roles === false) {
565
- const schema = schemaOf(resource, plan);
566
- const master = credential.containers.postgres;
567
- return schema ? `${postgres(port, database, master)}?search_path=${schema}` : postgres(port, database, master);
568
- }
569
- const role = resource.kind === "database-reader" ? readerRole(parentRole(resource, plan)) : localRole(resource);
570
- return postgres(port, database, {
571
- user: role,
572
- password: localRolePassword(project, plan, role, credential.seed)
573
- });
574
- }
575
- case "telemetry": return `http://${LOCAL_HOST}:${port}/api/${LOGS_ORG}`;
576
- case "email": return `smtp://${LOCAL_HOST}:${port}`;
577
- case "inbox": {
578
- const api = ports[MAILPIT_INBOX_PORT];
579
- return api === void 0 ? void 0 : `http://${LOCAL_HOST}:${api}`;
580
- }
581
- case "objects": return `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${lan ?? LOCAL_HOST}:${port}&forcePathStyle=true`;
582
- case "file-server": {
583
- const origin = plan.resources.find((r) => r.id === resource.of);
584
- if (!origin) return void 0;
585
- const placed = addresses?.[resource.id];
586
- if (placed) return placed;
587
- const objects = origin.container ? ports[primaryPortKey(origin.container)] : void 0;
588
- if (lan && !resource.processors?.length && objects !== void 0) return `http://${lan}:${objects}/${origin.name}`;
589
- return plan.containers.includes("caddy") ? `https://${hostFor$1(resource, project)}:${port}` : `http://${LOCAL_HOST}:${port}/${origin.name}`;
590
- }
591
- case "cache":
592
- if (resource.of) {
593
- const parent = plan.resources.find((r) => r.id === resource.of);
594
- const url = parent ? urlFor(parent, plan, ports, project, addresses, credential) : void 0;
595
- return url ? withTable(url, resource.table ?? cacheTable(resource.id)) : void 0;
596
- }
597
- switch (plan.cache) {
598
- case "elasticache":
599
- case "redis": return `redis://:${encodeURIComponent(credential.containers.redis.password)}@${LOCAL_HOST}:${port}`;
600
- default: return `http://:${encodeURIComponent(credential.containers.cacheToken)}@${LOCAL_HOST}:${port}`;
601
- }
602
- case "queue":
603
- case "topic": return broker(plan, port, credential, resource);
604
- default: return;
605
- }
606
- }
607
- /**
608
- * The producer's connection string, composed from the backend the plan chose.
609
- *
610
- * The protocol is what picks the transport, so a producer never branches: the
611
- * same `.publish()` reaches pg-boss here and SQS deployed because the string it
612
- * was handed said so.
613
- */
614
- function broker(plan, port, credential, resource) {
615
- switch (plan.events) {
616
- case "pgboss": {
617
- const database = plan.resources.find((r) => r.kind === "database");
618
- if (!database) throw new PgBossNeedsDatabase([]);
619
- const { user, password } = credential.containers.postgres;
620
- return `pgboss://${user}:${encodeURIComponent(password)}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;
621
- }
622
- case "rabbitmq": {
623
- const { user, password } = credential.containers.rabbitmq;
624
- return `rabbitmq://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;
625
- }
626
- case "sns": {
627
- if (!resource) throw new UnprovisionedEventsBackend("sns");
628
- const endpoint = emulatorEndpoint(port);
629
- const address = resource.kind === "topic" ? snsUrl.build({
630
- topicArn: emulatorTopicArn(resource.name),
631
- region: EMULATOR_REGION,
632
- endpoint
633
- }) : sqsUrl.build({
634
- queueUrl: emulatorQueueUrl(resource.name, port),
635
- region: EMULATOR_REGION,
636
- endpoint
637
- });
638
- const url = new URL(address);
639
- const { accessKeyId, secretAccessKey } = credential.containers.emulator;
640
- url.searchParams.set("accessKeyId", accessKeyId);
641
- url.searchParams.set("secretAccessKey", secretAccessKey);
642
- return url.toString();
643
- }
644
- }
645
- }
646
- /** A local Postgres URL, with the login it connects as. */
647
- function postgres(port, database, credential) {
648
- return `postgres://${credential.user}:${encodeURIComponent(credential.password)}@${LOCAL_HOST}:${port}/${database}`;
649
- }
650
- /**
651
- * The role a handler connects as, for one database or tenant.
652
- *
653
- * The construct's id, lowercased and stage-scoped exactly as its database or
654
- * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two
655
- * stages sharing one cluster cannot share a credential. Roles are cluster-scoped
656
- * in Postgres, which is why the suffix is not optional here the way it is for a
657
- * schema.
658
- */
659
- function localRole(resource) {
660
- return resource.name;
661
- }
662
- /**
663
- * The password for a derived local role.
664
- *
665
- * Derived rather than random, for the same reason the local secret is: a
666
- * password that changed on every `gkm dev` would lock a developer out of the
667
- * data they had a moment ago. Seeded by the project so two checkouts do not
668
- * share one, and by the stage so `test` and `development` do not.
669
- *
670
- * Without a seed it is a *local* credential by construction — the cluster is
671
- * on loopback and everything it is derived from is in the repo. `gkm compose`
672
- * serving a deployed stage passes that stage's random seed, which is what
673
- * makes the same derivation a secret.
674
- */
675
- function localRolePassword(project, plan, role, seed) {
676
- return createHash("sha256").update(`${seed ? `${seed}:` : ""}${project}:${plan.stage}:role:${role}`).digest("base64url").slice(0, 32);
677
- }
678
- /**
679
- * A cache's address: its database's URL, carrying the table it reads.
680
- *
681
- * Appended rather than kept beside the URL as a second key, for the reason the
682
- * design gives everywhere else — an address and what it opens are one fact, and
683
- * two keys are one more thing to keep in step.
684
- */
685
- function withTable(url, table) {
686
- const parsed = new URL(url);
687
- parsed.searchParams.set("table", table);
688
- return parsed.toString();
689
- }
690
- /**
691
- * The physical database a derived resource lives in.
692
- *
693
- * Walks `of` to the top rather than reading the immediate parent, because a
694
- * reader's parent may itself be a schema tenant — two hops from the database
695
- * that actually exists.
696
- */
697
- function rootDatabase(resource, plan) {
698
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
699
- let current = resource;
700
- while (current.of) {
701
- const parent = byId.get(current.of);
702
- if (!parent) break;
703
- current = parent;
704
- }
705
- return current.name;
706
- }
707
- /** The schema a derived resource puts on its search path, if it has one. */
708
- function schemaOf(resource, plan) {
709
- const byId = new Map(plan.resources.map((r) => [r.id, r]));
710
- let current = resource;
711
- while (current) {
712
- if (current.kind === "database-schema") return current.schema;
713
- current = current.of ? byId.get(current.of) : void 0;
714
- }
715
- }
716
- /**
717
- * A broker address asked for without the topic or queue it would name.
718
- *
719
- * On SNS each topic and queue is its own address, so there is no project-wide
720
- * one to hand out — a cron's schedule store, say, cannot live there.
721
- */
722
- var UnprovisionedEventsBackend = class extends GkmError {
723
- backend;
724
- constructor(backend) {
725
- super(`'${backend}' has no single broker address: each topic and queue is addressed by its own ARN. Something asked for one without naming the topic or queue.`);
726
- this.backend = backend;
727
- this.name = "UnprovisionedEventsBackend";
728
- }
729
- };
730
- /**
731
- * The keyring an `Encryption` construct resolves to locally.
732
- *
733
- * Derived like a secret — stable across restarts, distinct per project, stage
734
- * and construct, never written to disk — so what `gkm dev` encrypted yesterday
735
- * still opens today. One key, because nothing local is worth rotating: a
736
- * server stage's keyring is generated and rotated in its secrets instead.
737
- */
738
- function localKeyring(project, plan, resource) {
739
- const derive = (purpose) => createHash("sha256").update(`${project}:${plan.stage}:${resource.id}:${purpose}`).digest();
740
- return formatKeyring({
741
- keys: [{
742
- id: "k1",
743
- key: derive("k1")
744
- }],
745
- index: derive("index")
746
- });
747
- }
748
- /**
749
- * The value a secret resolves to locally.
750
- *
751
- * A hash of what identifies it, so it is stable, distinct per project, stage
752
- * and construct, and never written to disk as a literal. Deployed this is the
753
- * one kind whose value does *not* come from here — a secret manager generates
754
- * it once and the target reads it back. Drawn in the format the deploy draws
755
- * it in, so a value that passes a third party's rules here passes them there.
756
- */
757
- function localSecret(project, plan, resource) {
758
- return drawSecret(hashStream(`${project}:${plan.stage}:${resource.id}`), resource.format);
759
- }
760
- /**
761
- * Integers in `[0, n)` drawn from a hash of `seed`, the same every time —
762
- * what a local secret is drawn with instead of `crypto`, so `gkm dev` and
763
- * `gkm test` need nothing stored. Rejection-sampled, so no character is
764
- * likelier than another.
765
- */
766
- function hashStream(seed) {
767
- let block = 0;
768
- let bytes = Buffer.alloc(0);
769
- let offset = 0;
770
- const next = () => {
771
- if (offset === bytes.length) {
772
- bytes = createHash("sha256").update(`${seed}:${block++}`).digest();
773
- offset = 0;
774
- }
775
- return bytes[offset++];
776
- };
777
- return (n) => {
778
- const limit = 256 - 256 % n;
779
- for (;;) {
780
- const byte = next();
781
- if (byte < limit) return byte % n;
782
- }
783
- };
784
- }
785
- //#endregion
786
- //#region src/providers/s3/lifecycle.ts
787
- /**
788
- * A bucket's lifecycle, as the constructs declare it: one expiry rule per
789
- * prefix, merged into whatever else the bucket's lifecycle already holds.
790
- *
791
- * S3 — and MinIO, which speaks the same API — keeps one lifecycle document
792
- * per bucket, and a write replaces all of it. So gkm owns only the rules it
793
- * names (`gkm-…`): every other rule is read and put back as it was, a rule of
794
- * gkm's that is no longer declared is dropped, and nothing is written when
795
- * gkm's rules already say what the manifest does.
796
- *
797
- * Shared by the `s3` provider and the MinIO a local or compose stack runs,
798
- * so a prefix expires the same way on both.
799
- */
800
- /** The id every rule gkm writes starts with — and the only ones it touches. */
801
- const GKM_RULE_PREFIX = "gkm-";
802
- /**
803
- * The rule id for one prefix: readable, and unique however the prefix is
804
- * spelled — `a/b` and `a-b` read alike once sanitised, so a short hash of the
805
- * prefix itself follows.
806
- */
807
- function expireRuleId(prefix) {
808
- const readable = prefix.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200);
809
- const hash = createHash("sha256").update(prefix).digest("hex").slice(0, 8);
810
- return `${GKM_RULE_PREFIX}expire-${readable ? `${readable}-` : ""}${hash}`;
811
- }
812
- /** The rules a bucket's expiry asks for, in a stable order. */
813
- function expireRules(expire) {
814
- return Object.entries(expire ?? {}).map(([prefix, days]) => ({
815
- ID: expireRuleId(prefix),
816
- Status: "Enabled",
817
- Filter: { Prefix: prefix },
818
- Expiration: { Days: days }
819
- })).sort((a, b) => a.ID.localeCompare(b.ID));
820
- }
821
- /**
822
- * Merge the declared expiry into the bucket's current rules.
823
- *
824
- * @param current the bucket's rules, or nothing when it has no lifecycle
825
- */
826
- function mergeLifecycle(current, expire) {
827
- const wanted = expireRules(expire);
828
- const rules = current ?? [];
829
- const others = rules.filter((r) => !r.ID?.startsWith(GKM_RULE_PREFIX));
830
- const ours = rules.filter((r) => r.ID?.startsWith(GKM_RULE_PREFIX));
831
- return {
832
- changed: canonical(ours) !== canonical(wanted) || new Set(ours.map((r) => r.ID)).size !== ours.length,
833
- rules: [...others, ...wanted],
834
- describe: describeExpiry(expire)
835
- };
836
- }
837
- /** `expire quotes/ after 30 days, tmp/ after 1 day` — or what removing says. */
838
- function describeExpiry(expire) {
839
- const entries = Object.entries(expire ?? {}).sort(([a], [b]) => a.localeCompare(b));
840
- if (entries.length === 0) return "remove expiry rules";
841
- return `expire ${entries.map(([prefix, days]) => `${prefix} after ${days} day${days === 1 ? "" : "s"}`).join(", ")}`;
842
- }
843
- /** gkm's rules as the fields it sets, order-free. */
844
- function canonical(rules) {
845
- return JSON.stringify(rules.map((r) => ({
846
- id: r.ID,
847
- status: r.Status,
848
- prefix: r.Filter?.Prefix ?? r.Prefix ?? "",
849
- days: r.Expiration?.Days ?? null
850
- })).sort((a, b) => (a.id ?? "").localeCompare(b.id ?? "")));
851
- }
852
- //#endregion
853
- //#region src/reconcile/provision.ts
854
- /**
855
- * The Postgres work a plan implies.
856
- *
857
- * Databases before the schemas inside them, which `provisionOrder` already
858
- * guarantees by putting parents first.
859
- */
860
- function postgresStatements(plan, project = "", seed) {
861
- const statements = [];
862
- const cacheTables = [];
863
- for (const resource of plan.resources) {
864
- if (!resource.provisions || resource.container !== "postgres") continue;
865
- if (resource.kind === "database") {
866
- statements.push({
867
- id: resource.id,
868
- describe: `database ${resource.name}`,
869
- exists: {
870
- sql: "SELECT 1 FROM pg_database WHERE datname = $1",
871
- values: [resource.name]
872
- },
873
- create: `CREATE DATABASE ${quoteIdentifier(resource.name)}`
874
- });
875
- if (resource.schema) statements.push(...rolesFor(resource, resource.schema, plan, project, seed));
876
- continue;
877
- }
878
- if (resource.kind === "database-schema" && resource.schema) statements.push(...rolesFor(resource, resource.schema, plan, project, seed));
879
- const cacheHome = resource.kind === "cache" && resource.of ? plan.resources.find((r) => r.id === resource.of) : void 0;
880
- if (cacheHome) cacheTables.push(...cacheTableDdl(resource, cacheHome, plan));
881
- }
882
- return [...statements, ...cacheTables];
883
- }
884
- /**
885
- * A cache's table, in the schema the role that reads it resolves names in.
886
- *
887
- * Two things have to line up, and neither is the table's contents. The driver
888
- * names the table unqualified and lets the connection's `search_path` place it
889
- * — which the role carries — so creating it from the master connection, whose
890
- * path is `public`, leaves a table the application cannot see and a
891
- * `relation "cache" does not exist` on the first request. And the default
892
- * privileges that make a tenant's tables reachable are granted *for the owner
893
- * role*, so nothing covers a table the master created.
894
- *
895
- * Hence: qualified with the tenant's schema, handed to its owner, and granted
896
- * explicitly — `roleStatements` grants what exists at the time it runs, and
897
- * this table does not exist yet.
898
- *
899
- * A database that opted out of roles needs none of it: everything connects as
900
- * the master, whose `search_path` finds `public`, and the table it creates
901
- * there is the table it reads.
902
- */
903
- function cacheTableDdl(cache, home, plan) {
904
- const database = rootDatabase(home, plan);
905
- const schema = home.roles === false ? void 0 : home.schema;
906
- const name = cache.table ?? cacheTable(cache.id);
907
- const table = schema ? `${schema}.${name}` : name;
908
- const created = cacheTableStatements({ table }).map((statement) => ({
909
- id: cache.id,
910
- describe: statement.describe,
911
- database,
912
- ...statement.exists ? { exists: statement.exists } : {},
913
- create: statement.sql
914
- }));
915
- if (!schema) return created;
916
- const runtime = localRole(home);
917
- const owner = ownerRole(runtime);
918
- const qualified = table.split(".").map((part) => quoteIdentifier(part)).join(".");
919
- return [
920
- ...created,
921
- {
922
- id: cache.id,
923
- describe: `cache table ${table} is owned by ${owner}`,
924
- database,
925
- create: `ALTER TABLE ${qualified} OWNER TO ${quoteIdentifier(owner)}`
926
- },
927
- {
928
- id: cache.id,
929
- describe: `${runtime} may read and write ${table}`,
930
- database,
931
- create: `GRANT SELECT, INSERT, UPDATE, DELETE ON ${qualified} TO ${quoteIdentifier(runtime)}`
932
- }
933
- ];
934
- }
935
- /**
936
- * The roles and schema for one database or tenant.
937
- *
938
- * Skipped entirely when the construct declared `roles: false` — the documented
939
- * downgrade, where both URLs fall back to the cluster's master credential. It
940
- * is a choice someone made rather than a default they got.
941
- */
942
- function rolesFor(resource, schema, plan, project, seed) {
943
- if (resource.roles === false) return [];
944
- const runtime = localRole(resource);
945
- const owner = ownerRole(runtime);
946
- const reader = plan.resources.some((r) => r.kind === "database-reader" && r.of === resource.id) ? readerRole(runtime) : void 0;
947
- return roleStatements({
948
- runtime,
949
- owner,
950
- ...reader ? { reader } : {},
951
- schema,
952
- ...resource.kind === "database" ? { database: rootDatabase(resource, plan) } : {},
953
- ...resource.extensions ? { extensions: resource.extensions } : {},
954
- passwords: {
955
- runtime: localRolePassword(project, plan, runtime, seed),
956
- owner: localRolePassword(project, plan, owner, seed),
957
- ...reader ? { reader: localRolePassword(project, plan, reader, seed) } : {}
958
- }
959
- }).map((statement) => ({
960
- id: resource.id,
961
- describe: statement.describe,
962
- database: rootDatabase(resource, plan),
963
- ...statement.exists ? { exists: statement.exists } : {},
964
- create: statement.sql
965
- }));
966
- }
967
- /** The buckets a plan implies. */
968
- function bucketNames(plan) {
969
- return plan.resources.filter((r) => r.provisions && r.kind === "objects").map((r) => r.name);
970
- }
971
- /**
972
- * Quote an identifier for use in DDL.
973
- *
974
- * Names reaching here are already canonical and stage-suffixed, so this is
975
- * defence rather than sanitisation — but DDL cannot be parameterised, and an
976
- * unquoted identifier is the one place a name could ever be more than a name.
977
- */
978
- function quoteIdentifier(name) {
979
- return `"${name.replace(/"/g, "\"\"")}"`;
980
- }
981
- /**
982
- * Apply the plan's Postgres statements.
983
- *
984
- * Each is checked before it is run, so this converges rather than erroring on a
985
- * second pass.
986
- */
987
- async function applyPostgres(client, statements) {
988
- const applied = [];
989
- for (const statement of statements) {
990
- if (!statement.exists) {
991
- await client.query(statement.database, statement.create);
992
- applied.push({
993
- id: statement.id,
994
- describe: statement.describe,
995
- created: false
996
- });
997
- continue;
998
- }
999
- if ((await client.query(statement.database, statement.exists.sql, statement.exists.values)).length > 0) {
1000
- applied.push({
1001
- id: statement.id,
1002
- describe: statement.describe,
1003
- created: false
1004
- });
1005
- continue;
1006
- }
1007
- await client.query(statement.database, statement.create);
1008
- applied.push({
1009
- id: statement.id,
1010
- describe: statement.describe,
1011
- created: true
1012
- });
1013
- }
1014
- return applied;
1015
- }
1016
- /**
1017
- * What each bucket's open paths are, if anything serves it.
1018
- *
1019
- * Keyed by the *origin*, because that is where the policy lives: two servers
1020
- * over one bucket contribute to one policy, so the patterns are unioned rather
1021
- * than the last one winning.
1022
- */
1023
- function bucketPolicies(plan) {
1024
- const byBucket = /* @__PURE__ */ new Map();
1025
- for (const resource of plan.resources) {
1026
- if (resource.kind !== "file-server" || !resource.open?.length) continue;
1027
- const origin = plan.resources.find((r) => r.id === resource.of);
1028
- if (!origin) continue;
1029
- const patterns = byBucket.get(origin.name) ?? /* @__PURE__ */ new Set();
1030
- for (const pattern of resource.open) patterns.add(pattern);
1031
- byBucket.set(origin.name, patterns);
1032
- }
1033
- return [...byBucket].map(([bucket, open]) => ({
1034
- bucket,
1035
- open: [...open].sort()
1036
- })).sort((a, b) => a.bucket.localeCompare(b.bucket));
1037
- }
1038
- /**
1039
- * What each bucket keeps, and for how long: the buckets that declare an
1040
- * expiry, by their stage-scoped name.
1041
- *
1042
- * Every bucket in the plan, not only those that declare one, is what a
1043
- * removed expiry needs — its rules are dropped from a bucket that no longer
1044
- * asks for them — so a bucket with none is listed with an empty expiry.
1045
- */
1046
- function bucketLifecycles(plan) {
1047
- return plan.resources.filter((r) => r.kind === "objects" && r.provisions).map((r) => ({
1048
- bucket: r.name,
1049
- expire: r.expire ?? {}
1050
- })).sort((a, b) => a.bucket.localeCompare(b.bucket));
1051
- }
1052
- /**
1053
- * One bucket's open paths as an S3 bucket policy.
1054
- *
1055
- * Anonymous `s3:GetObject` on the named prefixes and nothing else — which is
1056
- * what "open" means everywhere: the server serves that path without a
1057
- * signature, and the bucket stays private for everything else.
1058
- *
1059
- * One fidelity note, stated rather than discovered: an S3 policy resource's `*`
1060
- * crosses `/`, so a single-star pattern is *wider* here than the construct's own
1061
- * runtime check, which stops at a segment boundary. The construct is the
1062
- * stricter of the two, so a key it refuses to serve unsigned is never one this
1063
- * policy was relied on to refuse — but a key fetched directly, bypassing the
1064
- * client, can be admitted by the policy where the client would have said no.
1065
- * Prefer `**` where crossing segments is what you meant.
1066
- */
1067
- function bucketPolicy(bucket, open) {
1068
- return JSON.stringify({
1069
- Version: "2012-10-17",
1070
- Statement: [{
1071
- Sid: "GkmOpenPaths",
1072
- Effect: "Allow",
1073
- Principal: { AWS: ["*"] },
1074
- Action: ["s3:GetObject"],
1075
- Resource: open.map((pattern) => `arn:aws:s3:::${bucket}/${pattern.replace(/\*\*/g, "*")}`)
1076
- }]
1077
- });
1078
- }
1079
- /**
1080
- * The topics and queues to create on the AWS emulator.
1081
- *
1082
- * Only on the `sns` backend: pg-boss makes its own tables on first connect and
1083
- * a RabbitMQ exchange is declared by the client, but an SNS topic and an SQS
1084
- * queue must exist before anything can publish to them.
1085
- */
1086
- function carrierNames(plan) {
1087
- if (plan.events !== "sns") return {
1088
- topics: [],
1089
- queues: []
1090
- };
1091
- const named = (kind) => plan.resources.filter((r) => r.kind === kind).map((r) => r.name);
1092
- return {
1093
- topics: named("topic"),
1094
- queues: named("queue")
1095
- };
1096
- }
1097
- /** Create each topic and queue the plan names, skipping those that exist. */
1098
- async function applyCarriers(client, carriers) {
1099
- const applied = [];
1100
- for (const name of carriers.topics) {
1101
- const created = !await client.topicExists(name);
1102
- if (created) await client.createTopic(name);
1103
- applied.push({
1104
- id: name,
1105
- describe: `topic ${name}`,
1106
- created
1107
- });
1108
- }
1109
- for (const name of carriers.queues) {
1110
- const created = !await client.queueExists(name);
1111
- if (created) await client.createQueue(name);
1112
- applied.push({
1113
- id: name,
1114
- describe: `queue ${name}`,
1115
- created
1116
- });
1117
- }
1118
- return applied;
1119
- }
1120
- /** The Postgres databases the plan creates — each is a `CREATE DATABASE`. */
1121
- function postgresDatabaseNames(plan) {
1122
- return plan.resources.filter((resource) => resource.kind === "database" && resource.provisions && resource.container === "postgres").map((resource) => resource.name);
1123
- }
1124
- /**
1125
- * Whether every one of these databases exists. A database dropped behind the
1126
- * recorded state's back — by another checkout's test teardown, against the
1127
- * same container — makes the state a lie, and only asking Postgres finds out.
1128
- * Unreachable counts as missing: applying again is what finds out why.
1129
- */
1130
- async function databasesExist(client, names) {
1131
- if (names.length === 0) return true;
1132
- try {
1133
- const rows = await client.query(void 0, "SELECT datname FROM pg_catalog.pg_database WHERE datname = ANY($1)", [names]);
1134
- return new Set(rows.map((row) => row.datname)).size === names.length;
1135
- } catch {
1136
- return false;
1137
- }
1138
- }
1139
- /**
1140
- * Point each watched bucket's events at its webhook target, and stop sending
1141
- * an unwatched one's.
1142
- *
1143
- * Merged rather than written whole: only the rule gkm owns on a bucket
1144
- * (`gkm-<Bucket>`) is added or removed, and every other rule — one somebody
1145
- * added by hand — is kept. Compared before writing, so a converged reconcile
1146
- * changes nothing.
1147
- *
1148
- * @param buckets - each bucket the plan names, by construct id and name
1149
- * @param watched - the construct ids whose events are relayed
1150
- */
1151
- async function applyNotifications(client, buckets, watched) {
1152
- const applied = [];
1153
- for (const { id, name } of buckets) {
1154
- const current = await client.notification(name);
1155
- const queues = current.QueueConfigurations ?? [];
1156
- const others = queues.filter((rule) => !rule.Id?.startsWith(NOTIFICATION_RULE_PREFIX));
1157
- const wanted = watched.has(id) ? [...others, minioNotificationRule(id)] : others;
1158
- if (!watched.has(id) && others.length === queues.length) continue;
1159
- const describe = `object events from ${name}`;
1160
- const ours = queues.filter((rule) => rule.Id?.startsWith(NOTIFICATION_RULE_PREFIX));
1161
- if (watched.has(id) ? ours.length === 1 && sameRule(ours[0], minioNotificationRule(id)) : ours.length === 0) {
1162
- applied.push({
1163
- id: `${name}:events`,
1164
- describe,
1165
- created: false
1166
- });
1167
- continue;
1168
- }
1169
- await client.setNotification(name, {
1170
- ...current,
1171
- QueueConfigurations: wanted
1172
- });
1173
- applied.push({
1174
- id: `${name}:events`,
1175
- describe,
1176
- created: true
1177
- });
1178
- }
1179
- return applied;
1180
- }
1181
- /**
1182
- * Whether a rule read back says what gkm wrote: the same target, the same
1183
- * events in any order, and no filter — the store may hand back an empty one.
1184
- */
1185
- function sameRule(current, wanted) {
1186
- const filter = current.Filter;
1187
- return current.Id === wanted.Id && current.QueueArn === wanted.QueueArn && JSON.stringify([...current.Events ?? []].sort()) === JSON.stringify([...wanted.Events ?? []].sort()) && (filter?.Key?.FilterRules?.length ?? 0) === 0;
1188
- }
1189
- /**
1190
- * Apply each bucket's expiry, beside whatever other rules it has, skipping
1191
- * those already correct — the same merge the `s3` provider makes deployed.
1192
- */
1193
- async function applyLifecycles(client, lifecycles) {
1194
- const applied = [];
1195
- for (const { bucket, expire } of lifecycles) {
1196
- const merge = mergeLifecycle(await client.lifecycle(bucket), expire);
1197
- const id = `${bucket}:lifecycle`;
1198
- const describe = `${merge.describe} on ${bucket}`;
1199
- if (!merge.changed && Object.keys(expire).length === 0) continue;
1200
- if (!merge.changed) {
1201
- applied.push({
1202
- id,
1203
- describe,
1204
- created: false
1205
- });
1206
- continue;
1207
- }
1208
- await client.setLifecycle(bucket, merge.rules);
1209
- applied.push({
1210
- id,
1211
- describe,
1212
- created: true
1213
- });
1214
- }
1215
- return applied;
1216
- }
1217
- /**
1218
- * Apply each served bucket's open-path policy, skipping those already correct.
1219
- *
1220
- * Compared as parsed JSON rather than as text: the same policy re-serialised
1221
- * with different key order is the same policy, and rewriting it every reconcile
1222
- * would report a change on every start.
1223
- */
1224
- async function applyPolicies(client, policies) {
1225
- const applied = [];
1226
- for (const { bucket, open } of policies) {
1227
- const wanted = bucketPolicy(bucket, open);
1228
- const describe = `open paths on ${bucket}`;
1229
- if (equivalent(await client.policy(bucket), wanted)) {
1230
- applied.push({
1231
- id: `${bucket}:policy`,
1232
- describe,
1233
- created: false
1234
- });
1235
- continue;
1236
- }
1237
- await client.setPolicy(bucket, wanted);
1238
- applied.push({
1239
- id: `${bucket}:policy`,
1240
- describe,
1241
- created: true
1242
- });
1243
- }
1244
- return applied;
1245
- }
1246
- /** Whether two policy documents say the same thing. */
1247
- function equivalent(current, wanted) {
1248
- if (!current) return false;
1249
- try {
1250
- return JSON.stringify(JSON.parse(current)) === JSON.stringify(JSON.parse(wanted));
1251
- } catch {
1252
- return false;
1253
- }
1254
- }
1255
- /** Create every bucket the plan names, skipping those that exist. */
1256
- async function applyBuckets(client, buckets) {
1257
- const applied = [];
1258
- for (const bucket of buckets) {
1259
- if (await client.exists(bucket)) {
1260
- applied.push({
1261
- id: bucket,
1262
- describe: `bucket ${bucket}`,
1263
- created: false
1264
- });
1265
- continue;
1266
- }
1267
- await client.create(bucket);
1268
- applied.push({
1269
- id: bucket,
1270
- describe: `bucket ${bucket}`,
1271
- created: true
1272
- });
1273
- }
1274
- return applied;
1275
- }
1276
- //#endregion
1277
- //#region src/backups/service.ts
1278
- /**
1279
- * The stack's `backups` service: what a deployed compose stage with Postgres
1280
- * runs beside its apps, unless `deploy.backups.<stage>` is `false`.
1281
- *
1282
- * - **The image** is built from the stack's own Postgres image —
1283
- * `postgres:<major>-alpine`, already on the server for the stack, and with
1284
- * the `pg_dump` that matches the server — with Node added and gkm's runner
1285
- * (`runner.ts`) copied in. Nothing is pulled that the stack does not have,
1286
- * and nothing is mounted from the host: the build context is two files.
1287
- * - **Its key** is `BACKUPS_URL`, from the stage's secrets, like any app's:
1288
- * allowed to put objects under the stage's backups prefix and nothing else.
1289
- * The server holds no AWS credentials of its own.
1290
- * - **Its login** is a role of its own, `<project>_backups`, granted
1291
- * `pg_read_all_data` — it can read every database and write none. Postgres
1292
- * before 14 has no such role, and there it signs in as the stack's
1293
- * superuser.
1294
- * - **Its health** is the last good run: unhealthy once that is more than
1295
- * twice the schedule's longest gap old, after a startup grace.
1296
- */
1297
- /** The service's name in the stack. */
1298
- const BACKUPS_SERVICE = "backups";
1299
- /** The secret its key is written to. */
1300
- const BACKUPS_URL_KEY = "BACKUPS_URL";
1301
- /** Where the runner is, in the image. */
1302
- const RUNNER_PATH = "/gkm/backup.mjs";
1303
- /** The first Postgres with `pg_read_all_data`. */
1304
- const READ_ALL_DATA_SINCE = 14;
1305
- /** A stage that backs up, and no key to back up with. */
1306
- var BackupsUrlMissing = class extends GkmError {
1307
- stage;
1308
- constructor(stage) {
1309
- 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.`);
1310
- this.stage = stage;
1311
- this.name = "BackupsUrlMissing";
1312
- }
1313
- };
1314
- /** The backups role: `<project>_backups`, as the superuser is `<project>_admin`. */
1315
- function backupsRole(project) {
1316
- return `${postgresRoleSlug(project)}_backups`;
1317
- }
1318
- /**
1319
- * The runner's source, as JavaScript: the built `backups/runner.mjs` beside
1320
- * the CLI's bundle, or — run from source — `runner.ts`, with its types
1321
- * stripped by esbuild.
1322
- */
1323
- function runnerSource() {
1324
- const here = dirname(fileURLToPath(import.meta.url));
1325
- for (const path of [
1326
- join(here, "backups", "runner.mjs"),
1327
- join(here, "runner.mjs"),
1328
- join(here, "..", "backups", "runner.mjs")
1329
- ]) if (existsSync(path)) return readFileSync(path, "utf-8");
1330
- const { transformSync } = createRequire(import.meta.url)("esbuild");
1331
- return transformSync(readFileSync(join(here, "runner.ts"), "utf-8"), {
1332
- loader: "ts",
1333
- format: "esm",
1334
- target: "node22"
1335
- }).code;
1336
- }
1337
- /** The image's Dockerfile: the stack's Postgres, Node, and the runner. */
1338
- function backupsDockerfile(from) {
1339
- return `# Generated by gkm — the stage's backups: pg_dump from ${from}, and gkm's uploader.
1340
- FROM ${from}
1341
- RUN apk add --no-cache nodejs
1342
- COPY backup.mjs ${RUNNER_PATH}
1343
- USER postgres
1344
- ENTRYPOINT []
1345
- CMD ["node", "${RUNNER_PATH}", "serve"]
1346
- `;
1347
- }
1348
- /**
1349
- * The stack's backups service, for a stage whose backups are on.
1350
- *
1351
- * @throws {BackupsUrlMissing} when the stage's secrets hold no key
1352
- */
1353
- function stackBackups(input) {
1354
- const { plan, stage } = input;
1355
- const version = plan.resources.find((r) => r.version)?.version ?? DEFAULT_POSTGRES_VERSION;
1356
- const from = postgresImage(version);
1357
- const script = runnerSource();
1358
- const dockerfile = backupsDockerfile(from);
1359
- const hash = createHash("sha256").update(dockerfile).update(script).digest("hex").slice(0, 12);
1360
- const readOnly = version >= READ_ALL_DATA_SINCE;
1361
- const role = backupsRole(input.workspace.name);
1362
- const login = readOnly ? {
1363
- user: role,
1364
- password: localRolePassword(input.workspace.name, plan, role, input.seed)
1365
- } : input.superuser;
1366
- const databases = backupDatabases(plan.resources);
1367
- const prefix = backupsPrefix(input.workspace, stage);
1368
- const { kind, ...schedule } = input.backups.schedule;
1369
- let env = {};
1370
- if (!input.buildOnly) {
1371
- const url = input.custom[BACKUPS_URL_KEY];
1372
- if (!url) throw new BackupsUrlMissing(stage);
1373
- env = {
1374
- BACKUPS_URL: url,
1375
- BACKUPS_PREFIX: prefix,
1376
- BACKUPS_DATABASES: JSON.stringify(databases.map(({ file, name }) => ({
1377
- file,
1378
- name
1379
- }))),
1380
- BACKUPS_SCHEDULE: JSON.stringify(kind === "cron" ? {
1381
- kind,
1382
- minutes: input.backups.schedule.minutes,
1383
- hours: input.backups.schedule.hours,
1384
- days: input.backups.schedule.days,
1385
- months: input.backups.schedule.months,
1386
- weekdays: input.backups.schedule.weekdays
1387
- } : {
1388
- kind,
1389
- ...schedule
1390
- }),
1391
- BACKUPS_MAX_GAP_SECONDS: String(input.backups.maxGapSeconds),
1392
- PGHOST: "postgres",
1393
- PGPORT: "5432",
1394
- PGUSER: login.user,
1395
- PGPASSWORD: login.password,
1396
- ...input.telemetry?.OTEL_EXPORTER_OTLP_ENDPOINT ? {
1397
- OTEL_EXPORTER_OTLP_ENDPOINT: input.telemetry.OTEL_EXPORTER_OTLP_ENDPOINT,
1398
- ...input.telemetry.OTEL_EXPORTER_OTLP_HEADERS ? { OTEL_EXPORTER_OTLP_HEADERS: input.telemetry.OTEL_EXPORTER_OTLP_HEADERS } : {},
1399
- OTEL_SERVICE_NAME: BACKUPS_SERVICE
1400
- } : {}
1401
- };
1402
- }
1403
- return {
1404
- backups: input.backups,
1405
- databases,
1406
- prefix,
1407
- from,
1408
- image: `${input.project}-backups:pg${version}-${hash}`,
1409
- files: {
1410
- Dockerfile: dockerfile,
1411
- "backup.mjs": script
1412
- },
1413
- login,
1414
- readOnly,
1415
- env
1416
- };
1417
- }
1418
- /** The service in the stack's compose file. */
1419
- function backupsService(backups, envFiles) {
1420
- return {
1421
- image: backups.image,
1422
- build: {
1423
- context: `./${BACKUPS_SERVICE}`,
1424
- dockerfile: "Dockerfile"
1425
- },
1426
- pull_policy: "build",
1427
- restart: "unless-stopped",
1428
- ...envFiles ? { env_file: [{
1429
- path: `./${BACKUPS_SERVICE}.env`,
1430
- format: "raw"
1431
- }] } : {},
1432
- depends_on: { postgres: { condition: "service_healthy" } },
1433
- healthcheck: {
1434
- test: [
1435
- "CMD",
1436
- "node",
1437
- RUNNER_PATH,
1438
- "health"
1439
- ],
1440
- interval: "1m",
1441
- timeout: "10s",
1442
- retries: 3,
1443
- start_period: "30s"
1444
- }
1445
- };
1446
- }
1447
- /**
1448
- * The backups role, created and kept: able to sign in and read every
1449
- * database, and nothing else. None when it signs in as the superuser.
1450
- */
1451
- function backupsRoleStatements(backups) {
1452
- if (!backups.readOnly) return [];
1453
- const role = quoteIdentifier(backups.login.user);
1454
- const password = `'${backups.login.password.replace(/'/g, "''")}'`;
1455
- return [
1456
- {
1457
- id: BACKUPS_SERVICE,
1458
- describe: `role ${backups.login.user}`,
1459
- exists: {
1460
- sql: "SELECT 1 FROM pg_roles WHERE rolname = $1",
1461
- values: [backups.login.user]
1462
- },
1463
- create: `CREATE ROLE ${role} LOGIN PASSWORD ${password}`
1464
- },
1465
- {
1466
- id: BACKUPS_SERVICE,
1467
- describe: `role ${backups.login.user}: its password`,
1468
- create: `ALTER ROLE ${role} WITH LOGIN PASSWORD ${password}`
1469
- },
1470
- {
1471
- id: BACKUPS_SERVICE,
1472
- describe: `role ${backups.login.user}: read every database`,
1473
- create: `GRANT pg_read_all_data TO ${role}`
1474
- }
1475
- ];
1476
- }
1477
- //#endregion
1478
- //#region src/build/workers.ts
1479
- /** A worker with background work and no backend app to build it from. */
1480
- var WorkerHasNoApp = class extends GkmError {
1481
- worker;
1482
- constructor(worker) {
1483
- super(`The worker '${worker}' has crons, queues or subscribers, and the workspace has no backend app that builds a server to carry its entry. Declare a RestApi whose app holds the worker's code.`);
1484
- this.worker = worker;
1485
- this.name = "WorkerHasNoApp";
1486
- }
1487
- };
1488
- /** A worker whose service name an app already has. */
1489
- var WorkerNameTaken = class extends GkmError {
1490
- worker;
1491
- service;
1492
- constructor(worker, service) {
1493
- super(`The worker '${worker}' runs as the service '${service}', and an app is already called that. Rename the worker — new Worker('${worker}Worker') — so each container has a name of its own.`);
1494
- this.worker = worker;
1495
- this.service = service;
1496
- this.name = "WorkerNameTaken";
1497
- }
1498
- };
1499
- /**
1500
- * The workers a workspace deploys — each one that has background work — and
1501
- * the app each is built from.
1502
- *
1503
- * The host is the backend app whose directory holds the most of the worker's
1504
- * files; one whose work sits outside every app (a shared `jobs/` directory)
1505
- * is built by the first backend, by name, that generates a server. An app
1506
- * with its own entry is never one — gkm's generators do not build it — and a
1507
- * surface that serves itself, an auth server, only when it holds the work.
1508
- *
1509
- * @param background Each worker's files, from discovery's `background`.
1510
- */
1511
- function workerUnits(workspace, manifest, background) {
1512
- const hosts = hostApps(workspace, manifest);
1513
- const units = [];
1514
- for (const [id, declaration] of Object.entries(manifest)) {
1515
- if (declaration.kind !== "worker") continue;
1516
- const files = background[id] ?? [];
1517
- if (files.length === 0) continue;
1518
- const name = appKey(id);
1519
- if (workspace.apps[name]) throw new WorkerNameTaken(id, name);
1520
- const host = hostFor(hosts, files);
1521
- if (!host) throw new WorkerHasNoApp(id);
1522
- units.push({
1523
- id,
1524
- name,
1525
- app: host.name
1526
- });
1527
- }
1528
- return units.sort((a, b) => a.name.localeCompare(b.name));
1529
- }
1530
- /** The service and image name of a file server's processors: `assets-processors`. */
1531
- function processorUnitName(fileServerId) {
1532
- return `${fileServerLabel(fileServerId)}-processors`;
1533
- }
1534
- /** A file server with processors and no backend app to build them from. */
1535
- var ProcessorsHaveNoApp = class extends GkmError {
1536
- fileServer;
1537
- constructor(fileServer) {
1538
- super(`The file server '${fileServer}' has processors, and the workspace has no backend app that builds a server to carry their entry. Declare a RestApi whose app holds the processors' code.`);
1539
- this.fileServer = fileServer;
1540
- this.name = "ProcessorsHaveNoApp";
1541
- }
1542
- };
1543
- /**
1544
- * The processor units a workspace deploys — each file server with processors
1545
- * — and the app each is built from, chosen as a worker's is: the backend app
1546
- * holding the most of its processors' files.
1547
- */
1548
- function processorUnits(workspace, manifest) {
1549
- const hosts = hostApps(workspace, manifest);
1550
- const units = [];
1551
- for (const declaration of Object.values(manifest)) {
1552
- if (declaration.kind !== "file-server") continue;
1553
- const processors = declaration.processors ?? [];
1554
- if (processors.length === 0) continue;
1555
- const host = hostFor(hosts, processors.map(({ handler }) => {
1556
- const file = handler.split("#")[0] ?? handler;
1557
- return isAbsolute(file) ? file : join(workspace.root, file);
1558
- }));
1559
- if (!host) throw new ProcessorsHaveNoApp(declaration.id);
1560
- const name = processorUnitName(declaration.id);
1561
- if (workspace.apps[name]) throw new WorkerNameTaken(declaration.id, name);
1562
- units.push({
1563
- id: declaration.id,
1564
- name,
1565
- app: host.name
1566
- });
1567
- }
1568
- return units.sort((a, b) => a.name.localeCompare(b.name));
1569
- }
1570
- /** The backend apps whose builds generate a server, each where it lives. */
1571
- function hostApps(workspace, manifest) {
1572
- return Object.entries(workspace.apps).filter(([, app]) => app.type === "backend" && !app.entry).map(([name, app]) => {
1573
- const surface = Object.entries(manifest).find(([id, d]) => (d.kind === "rest-api" || d.kind === "websocket-api") && appKey(id) === name)?.[1];
1574
- return {
1575
- name,
1576
- root: isAbsolute(app.path) ? app.path : join(workspace.root, app.path),
1577
- generated: !(surface?.kind === "websocket-api" || surface?.kind === "rest-api" && surface.servesItself === true)
1578
- };
1579
- }).sort((a, b) => a.name.localeCompare(b.name));
1580
- }
1581
- /**
1582
- * The app holding the most of these files; then one that generates a server;
1583
- * then by name. None when no app holds any and none generates a server.
1584
- */
1585
- function hostFor(hosts, files) {
1586
- const ranked = hosts.map((host) => ({
1587
- host,
1588
- holds: files.filter((file) => isUnder(file, host.root)).length
1589
- })).sort((a, b) => b.holds - a.holds || Number(b.host.generated) - Number(a.host.generated));
1590
- const host = ranked[0]?.host;
1591
- if (!host || ranked[0].holds === 0 && !host.generated) return void 0;
1592
- return host;
1593
- }
1594
- /** Whether `file` is inside `dir`. */
1595
- function isUnder(file, dir) {
1596
- const rel = relative(dir, file);
1597
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? !rel.startsWith(`..${sep}`) : false;
1598
- }
1599
- //#endregion
1600
- //#region src/compose/siteBuild.ts
1601
- /**
1602
- * A site's build inlines where it loads files from — a file server's URL, a
1603
- * bucket's signed origin — and the stage has not resolved it yet: a provider
1604
- * writes it on the stage's first deploy. Built anyway, the bundle would ship
1605
- * without its own asset host, and every image from it would be refused.
1606
- */
1607
- var SiteBuildValueUnresolved = class extends GkmError {
1608
- site;
1609
- key;
1610
- stage;
1611
- from;
1612
- constructor(site, key, stage, from) {
1613
- super(`'${site}' inlines ${key} into its build, and the stage '${stage}' has ${from ? `no ${from} to derive it from` : "no value for it"} yet. A provider writes it on the stage's first deploy: deploy the stage first (gkm deploy --stage ${stage}), then build. Or set it: gkm secrets:set ${from ?? key} '…' --stage ${stage}`);
1614
- this.site = site;
1615
- this.key = key;
1616
- this.stage = stage;
1617
- this.from = from;
1618
- this.name = "SiteBuildValueUnresolved";
1619
- }
1620
- };
1621
- /**
1622
- * What a site's image is built with — or a mobile app's EAS build: every
1623
- * value its build reads, resolved for the stage, and so every `ARG` a site's
1624
- * Dockerfile declares.
1625
- *
1626
- * - **Its edges' public values and its own address**, under the variant's
1627
- * public prefix (`publicEnvFor`): what the bundler inlines.
1628
- * - **Its own address under its own name** (`WEB_URL`). Server code runs at
1629
- * build too — `next build` prerenders, and a page's `metadataBase` is read
1630
- * then — and `gkm exec -- next build` has it locally, so the image build
1631
- * must, or a site that builds locally fails in CI. A mobile app has no
1632
- * address: its own value is its scheme (`APP_SCHEME`), which its
1633
- * `app.config.ts` reads when EAS builds it.
1634
- * - **Every stage secret already named for the bundle**: a key carrying the
1635
- * variant's public prefix (`NEXT_PUBLIC_APP_STORE_URL` on a `next` site) was
1636
- * declared public by whoever named it, so it is passed. Anything else is
1637
- * not: a secret without the prefix never reaches a site's build.
1638
- *
1639
- * A value the stage resolves to nothing is left out rather than passed empty
1640
- * — except, with `requireFileOrigins`, where its pages load files from.
1641
- * A derived value wins over a stage secret of the same name: the site's
1642
- * addresses are the construct's, not a copy someone set.
1643
- */
1644
- function publicBuildValues(site, manifest, resolve, secrets, options = {}) {
1645
- const args = {};
1646
- const own = providedKeyFor(site.id, site.kind, site.kind === "site" ? "url" : "scheme");
1647
- const ownValue = resolve(own);
1648
- if (ownValue) args[own] = ownValue;
1649
- const derived = signedOrigins(Object.keys(manifest).filter((id) => manifest[id]?.kind === "objects"), resolve);
1650
- for (const [key, source] of Object.entries(publicEnvFor(site, manifest))) {
1651
- const value = resolve(source) ?? derived[source];
1652
- if (value) args[key] = value;
1653
- }
1654
- const prefix = PUBLIC_PREFIX[site.variant];
1655
- const required = options.requireFileOrigins;
1656
- if (required) for (const value of publicValues(site, manifest)) {
1657
- if (value.kind === "file-server" && value.role === "url") {
1658
- if (!resolve(value.key)) throw new SiteBuildValueUnresolved(site.id, value.key, required.stage);
1659
- }
1660
- if (value.kind === "objects" && value.role === "signedOrigin") {
1661
- const connection = providedKeyFor(value.id, "objects", "connectionString");
1662
- if (!resolve(value.key) && !resolve(connection)) throw new SiteBuildValueUnresolved(site.id, value.key, required.stage, connection);
1663
- }
1664
- }
1665
- const images = imageOriginsFor(site, manifest);
1666
- const origins = images && imageOrigins(images.sources, (source) => resolve(source) ?? derived[source]);
1667
- if (images && origins) args[images.key] = origins;
1668
- for (const [key, value] of Object.entries(secrets)) if (key.startsWith(prefix) && args[key] === void 0 && value) args[key] = value;
1669
- return args;
1670
- }
1671
- /**
1672
- * Where a site's own hosts point during its image build: this loopback
1673
- * address, on which nothing in a build container listens — so a request to
1674
- * one is refused at once instead of waiting on a host that is not up yet.
1675
- */
1676
- const OFFLINE_BUILD_ADDRESS = "127.0.0.1";
1677
- /**
1678
- * The hosts a site's image build must not wait on: its own and those of the
1679
- * constructs its `.dependsOn()` names, as this stage serves them.
1680
- *
1681
- * None of them answers while the image is built — the stack the site belongs
1682
- * to is started after it — and a fetch to a public host that does not answer
1683
- * yet can stall until the framework's prerender limit (Next's 60s). Mapped to
1684
- * {@link OFFLINE_BUILD_ADDRESS} in the build's `/etc/hosts`, each is refused
1685
- * at once, and the page renders on its first request instead.
1686
- *
1687
- * The mapping is the build's only: the URLs the bundle inlines are the real
1688
- * ones, and the running container resolves them as anything else does. A
1689
- * stage secret named for the bundle is someone else's host (an analytics
1690
- * service, a store) and is left alone, as are `localhost` and an address.
1691
- *
1692
- * None for a site that pre-renders against its stage (`prerender: 'stage'`):
1693
- * it is built once those hosts answer, and has to reach them.
1694
- */
1695
- function offlineBuildHosts(site, manifest, resolve) {
1696
- if (site.prerender === "stage") return [];
1697
- const sources = [providedKeyFor(site.id, site.kind, "url"), ...Object.values(publicEnvFor(site, manifest))];
1698
- const hosts = /* @__PURE__ */ new Set();
1699
- for (const source of sources) {
1700
- const host = hostOf(resolve(source));
1701
- if (host) hosts.add(host);
1702
- }
1703
- return [...hosts].sort();
1704
- }
1705
- /** A URL's host, where it is a name `/etc/hosts` can map. */
1706
- function hostOf(value) {
1707
- if (!value || !URL.canParse(value)) return void 0;
1708
- const { protocol, hostname } = new URL(value);
1709
- if (!/^(https?|wss?):$/.test(protocol)) return void 0;
1710
- if (hostname === "localhost" || hostname.includes("*")) return void 0;
1711
- if (/^[\d.]+$/.test(hostname) || hostname.startsWith("[")) return void 0;
1712
- return hostname;
1713
- }
1714
- /**
1715
- * {@link offlineBuildHosts} for a target that knows each app's public URL by
1716
- * its app key rather than by construct key — the site's own, and each app it
1717
- * calls. None, for an app that declares no site.
1718
- */
1719
- function siteOfflineHosts(manifest, appName, ownUrl, urls) {
1720
- const entries = Object.entries(manifest);
1721
- const site = entries.find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1];
1722
- if (site?.kind !== "site") return [];
1723
- const byKey = /* @__PURE__ */ new Map();
1724
- for (const [id] of entries) {
1725
- const name = appKey(id);
1726
- const url = name === appName ? ownUrl : urls[name];
1727
- if (url) byKey.set(providedKeyFor(id, manifest[id].kind, "url"), url);
1728
- }
1729
- return offlineBuildHosts(site, manifest, (key) => byKey.get(key));
1730
- }
1731
- /**
1732
- * Whether a site runs a server of its own — Next's, TanStack Start's — which
1733
- * reads an environment at runtime as a backend does: its edges' public URLs
1734
- * and the stage's secrets. A `static` site is a finished bundle, and reads
1735
- * nothing once it is built.
1736
- */
1737
- function runsServer(site) {
1738
- return site.variant !== "static";
1739
- }
1740
- //#endregion
1741
- //#region src/exec/imageBuild.ts
1742
- /**
1743
- * Set by a site's Dockerfile in its builder stage: this process is building
1744
- * an image.
1745
- *
1746
- * Inside an image there is no stage to load secrets for and no local
1747
- * container to resolve an address from — the public URLs the bundle inlines
1748
- * arrived as the Dockerfile's build args, already in the environment. So
1749
- * `gkm exec -- next build` there injects exactly those, and never the
1750
- * `localhost` addresses a workspace resolves on a developer's machine.
1751
- */
1752
- const IMAGE_BUILD_ENV = "GKM_IMAGE_BUILD";
1753
- /** Whether this process is building an image. */
1754
- function isImageBuild(env = process.env) {
1755
- return env[IMAGE_BUILD_ENV] === "1";
1756
- }
1757
- /**
1758
- * Set by a site's Dockerfile in its builder stage: this build is offline —
1759
- * no stage is reachable from it.
1760
- *
1761
- * A site's image is built before the stack it belongs to runs, so the APIs
1762
- * its `.dependsOn()` names do not answer yet: data a page fetches while the
1763
- * framework prerenders it would be none, cached as the page. A site tests
1764
- * `process.env.GKM_BUILD_OFFLINE === '1'` to skip that fetch, and renders the
1765
- * page on its first request instead — which gkm's warm-up after a deploy
1766
- * makes before any visitor does.
1767
- *
1768
- * Separate from {@link IMAGE_BUILD_ENV}, which says what `gkm exec` injects:
1769
- * this says what the build can reach. Only the builder stage sets it; the
1770
- * running container never has it.
1771
- */
1772
- const BUILD_OFFLINE_ENV = "GKM_BUILD_OFFLINE";
1773
- /**
1774
- * What `gkm exec` injects inside an image build: the public values its build
1775
- * args set — every `NEXT_PUBLIC_*`, `VITE_*` and `EXPO_PUBLIC_*` — and
1776
- * nothing read from a secrets store, a file or a container.
1777
- */
1778
- function imageBuildCredentials(env = process.env) {
1779
- const credentials = {};
1780
- for (const [key, value] of Object.entries(env)) {
1781
- if (value === void 0) continue;
1782
- if (PUBLIC_ENV_PREFIXES.some((prefix) => key.startsWith(prefix))) credentials[key] = value;
1783
- }
1784
- return credentials;
1785
- }
1786
- //#endregion
1787
- //#region src/docker/templates.ts
1788
- /**
1789
- * The turbo every image prunes and builds with when the build root resolves
1790
- * none of its own: a repository without turbo still needs `turbo prune` to
1791
- * cut its slice of the workspace, and an unpinned `turbo` is whatever the
1792
- * registry says on the day of the build.
1793
- */
1794
- const TURBO_VERSION = "2.5.4";
1795
- /**
1796
- * Caddy, which serves a static site's files. A 2.x tag, so a rebuild picks
1797
- * up patch releases and never a major.
1798
- */
1799
- const STATIC_SITE_IMAGE = "caddy:2.10-alpine";
1800
- /**
1801
- * The image generated Dockerfiles build on unless one is configured. Pinned to
1802
- * a Node security release, not the floating `node:22-alpine` tag, so a cached
1803
- * or older image can't put a build below the patched version — and the
1804
- * Dockerfile says which version it runs.
1805
- */
1806
- const DEFAULT_BASE_IMAGE = "node:22.23.4-alpine";
1807
- /**
1808
- * The build secret a site that pre-renders against its stage reads the root
1809
- * certificate of the stage's edge from — gkm's local CA, on the local stage,
1810
- * whose hosts no public root vouches for. A certificate, not a key; a secret
1811
- * only because a build has no other way to be handed a file it should not
1812
- * keep. Absent on a deployed stage, whose certificates are public ones.
1813
- */
1814
- const LOCAL_CA_BUILD_SECRET = "gkm_local_ca";
1815
- /**
1816
- * The build argument naming the deploy a site that pre-renders against its
1817
- * stage is built for — new on every deploy, so the layer that fetches the
1818
- * stage's data is never served from Docker's cache.
1819
- */
1820
- const PRERENDER_RUN_ARG = "GKM_PRERENDER_RUN";
1821
- const LOCKFILES = [
1822
- ["pnpm-lock.yaml", "pnpm"],
1823
- ["bun.lockb", "bun"],
1824
- ["yarn.lock", "yarn"],
1825
- ["package-lock.json", "npm"]
1826
- ];
1827
- /**
1828
- * Detect package manager from lockfiles
1829
- * Walks up the directory tree to find lockfile (for monorepos)
1830
- */
1831
- function detectPackageManager(cwd = process.cwd()) {
1832
- const lockfile = findLockfilePath(cwd);
1833
- if (!lockfile) return "pnpm";
1834
- const name = lockfile.slice(dirname(lockfile).length + 1);
1835
- return LOCKFILES.find(([file]) => file === name)?.[1] ?? "pnpm";
1836
- }
1837
- /**
1838
- * Find the lockfile path by walking up the directory tree
1839
- * Returns the full path to the lockfile, or null if not found
1840
- */
1841
- function findLockfilePath(cwd = process.cwd()) {
1842
- for (const dir of upFrom(cwd)) for (const [lockfile] of LOCKFILES) {
1843
- const lockfilePath = join(dir, lockfile);
1844
- if (existsSync(lockfilePath)) return lockfilePath;
1845
- }
1846
- return null;
1847
- }
1848
- /**
1849
- * The directory every image is built from: the nearest at or above `cwd`
1850
- * holding a lockfile or a `pnpm-workspace.yaml` — the package manager's root,
1851
- * which is what an install resolves the workspace's dependencies against.
1852
- *
1853
- * In a project of its own that is the gkm workspace's root. A gkm workspace
1854
- * nested inside a monorepo, whose dependencies are the monorepo's
1855
- * `workspace:*` packages, is built from the monorepo's root. `cwd` itself
1856
- * when neither is found.
1857
- */
1858
- function findBuildRoot(cwd = process.cwd()) {
1859
- for (const dir of upFrom(cwd)) {
1860
- if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1861
- for (const [lockfile] of LOCKFILES) if (existsSync(join(dir, lockfile))) return dir;
1862
- }
1863
- return cwd;
1864
- }
1865
- /** `cwd` and every directory above it, the filesystem root last. */
1866
- function upFrom(cwd) {
1867
- const dirs = [];
1868
- const root = parse(cwd).root;
1869
- let dir = cwd;
1870
- while (dir !== root) {
1871
- dirs.push(dir);
1872
- dir = dirname(dir);
1873
- }
1874
- dirs.push(root);
1875
- return dirs;
1876
- }
1877
- /** The package manager, its version, turbo's and the shape of a build root. */
1878
- function resolveBuildTools(buildRoot) {
1879
- const pkg = readJson(join(buildRoot, "package.json"));
1880
- const packageManager = detectPackageManager(buildRoot);
1881
- const field = typeof pkg?.packageManager === "string" ? pkg.packageManager : "";
1882
- const match = /^([a-z]+)@(\d[^+\s]*)/.exec(field);
1883
- const packageManagerVersion = match && match[1] === packageManager ? match[2] : void 0;
1884
- return {
1885
- packageManager,
1886
- ...packageManagerVersion ? { packageManagerVersion } : {},
1887
- turboVersion: resolveTurboVersion(buildRoot) ?? "2.5.4",
1888
- monorepo: existsSync(join(buildRoot, "pnpm-workspace.yaml")) || pkg?.workspaces !== void 0
1889
- };
1890
- }
1891
- /**
1892
- * The turbo version a build root resolves: what is installed, or what its
1893
- * lockfile pins. Undefined when it has none.
1894
- */
1895
- function resolveTurboVersion(buildRoot) {
1896
- const installed = readJson(join(buildRoot, "node_modules", "turbo", "package.json"));
1897
- if (typeof installed?.version === "string") return installed.version;
1898
- const read = (file) => {
1899
- try {
1900
- return readFileSync(join(buildRoot, file), "utf-8");
1901
- } catch {
1902
- return;
1903
- }
1904
- };
1905
- const pnpm = read("pnpm-lock.yaml");
1906
- const fromPnpm = pnpm && /^ {2}'?turbo@(\d[^:'(\s]*)'?:/m.exec(pnpm);
1907
- if (fromPnpm) return fromPnpm[1];
1908
- const npm = read("package-lock.json");
1909
- if (npm) {
1910
- const version = safeParse(npm)?.packages?.["node_modules/turbo"]?.version;
1911
- if (version) return version;
1912
- }
1913
- const yarn = read("yarn.lock");
1914
- const fromYarn = yarn && /^"?turbo@[^\n]*:\n\s+version:? "?(\d[^"\s]*)"?/m.exec(yarn);
1915
- if (fromYarn) return fromYarn[1];
1916
- }
1917
- function readJson(path) {
1918
- try {
1919
- return safeParse(readFileSync(path, "utf-8"));
1920
- } catch {
1921
- return;
1922
- }
1923
- }
1924
- function safeParse(text) {
1925
- try {
1926
- const value = JSON.parse(text);
1927
- return value && typeof value === "object" ? value : void 0;
1928
- } catch {
1929
- return;
1930
- }
1931
- }
1932
- /**
1933
- * Check if turbo.json exists (walks up directory tree)
1934
- */
1935
- function hasTurboConfig(cwd = process.cwd()) {
1936
- return upFrom(cwd).some((dir) => existsSync(join(dir, "turbo.json")));
1937
- }
1938
- /**
1939
- * Package manager specific commands. `version` pins what corepack (or npm,
1940
- * for bun) installs; without it, the latest.
1941
- */
1942
- function getPmConfig(pm, version) {
1943
- return {
1944
- pnpm: {
1945
- install: `corepack enable && corepack prepare pnpm@${version ?? "latest"} --activate`,
1946
- lockfile: "pnpm-lock.yaml",
1947
- installCmd: "pnpm install",
1948
- cacheTarget: "/root/.local/share/pnpm/store",
1949
- cacheId: "pnpm",
1950
- run: "pnpm run",
1951
- dlx: "pnpm dlx"
1952
- },
1953
- npm: {
1954
- install: version ? `npm install -g npm@${version}` : "",
1955
- lockfile: "package-lock.json",
1956
- installCmd: "npm install",
1957
- cacheTarget: "/root/.npm",
1958
- cacheId: "npm",
1959
- run: "npm run",
1960
- dlx: "npx --yes"
1961
- },
1962
- yarn: {
1963
- install: `corepack enable && corepack prepare yarn@${version ?? "stable"} --activate`,
1964
- lockfile: "yarn.lock",
1965
- installCmd: "yarn install",
1966
- cacheTarget: "/root/.yarn/cache",
1967
- cacheId: "yarn",
1968
- run: "yarn run",
1969
- dlx: "yarn dlx"
1970
- },
1971
- bun: {
1972
- install: `npm install -g bun@${version ?? "latest"}`,
1973
- lockfile: "bun.lockb",
1974
- installCmd: "bun install",
1975
- cacheTarget: "/root/.bun/install/cache",
1976
- cacheId: "bun",
1977
- run: "bun run",
1978
- dlx: "bunx"
1979
- }
1980
- }[pm];
1981
- }
1982
- /** What every template's first three stages need, resolved from options. */
1983
- function layout(options) {
1984
- const pm = getPmConfig(options.packageManager, options.packageManagerVersion);
1985
- const turbo = `${pm.dlx} turbo@${options.turboVersion ?? "2.5.4"}`;
1986
- const gkmRoot = options.gkmRoot ?? ".";
1987
- return {
1988
- pm,
1989
- turbo,
1990
- installPm: pm.install ? `RUN ${pm.install}` : "",
1991
- monorepo: options.monorepo ?? true,
1992
- gkmRoot,
1993
- /** The app, absolute inside the image. */
1994
- app: `/app/${options.appPath}`.replace(/\/\.$/, "")
1995
- };
1996
- }
1997
- /**
1998
- * The pruner stage: the build context cut to the app's slice, in turbo's
1999
- * `out/` layout — `out/json` for the install, `out/full` for the build.
2000
- *
2001
- * `turbo prune` keeps the packages the app depends on and nothing else at
2002
- * the root, so the root's own files (a `tsconfig.base.json` the packages
2003
- * extend, the config their build reads) and what the gkm workspace keeps
2004
- * outside any package are copied in beside them. A single package is copied
2005
- * whole.
2006
- */
2007
- /**
2008
- * The Node image every stage builds on, as a build argument: declared before
2009
- * the first `FROM`, so each stage can read it, and defaulted to the configured
2010
- * image. A compose file's `build.args`, or `docker build --build-arg`, picks
2011
- * another version without regenerating the Dockerfile.
2012
- */
2013
- function nodeImageArg(options) {
2014
- return `# The Node image; override with --build-arg NODE_IMAGE=node:<version>-alpine
2015
- ARG NODE_IMAGE=${options.baseImage}`;
2016
- }
2017
- function prunerStage(options) {
2018
- const { pm, turbo, installPm, monorepo, gkmRoot } = layout(options);
2019
- const scopes = [options.turboPackage, ...options.prunePackages ?? []].join(" ");
2020
- if (!monorepo) return `${nodeImageArg(options)}
2021
-
2022
- # Stage 1: The build context, in the layout the stages below read
2023
- FROM \${NODE_IMAGE} AS pruner
2024
- WORKDIR /app
2025
- COPY . .
2026
- RUN mkdir -p /tmp/out/json /tmp/out/full && \\
2027
- cp package.json /tmp/out/json/ && \\
2028
- cp ${pm.lockfile} /tmp/out/ && \\
2029
- cp -a . /tmp/out/full/ && \\
2030
- mv /tmp/out ./out`;
2031
- const gkmPaths = options.gkmPaths ?? [];
2032
- const nested = gkmRoot !== ".";
2033
- const dest = nested ? `/app/out/full/${gkmRoot}` : "/app/out/full";
2034
- const copyGkm = gkmPaths.length ? `
2035
-
2036
- # What the gkm workspace keeps outside any package — its config, the
2037
- # directories its constructs are declared in — beside the slice.
2038
- RUN ${nested ? `cd ${gkmRoot} && ` : ""}for path in ${gkmPaths.join(" ")}; do \\
2039
- if [ -e "$path" ]; then \\
2040
- mkdir -p "${dest}" && cp -rn "$path" "${dest}/"; \\
2041
- fi; \\
2042
- done` : "";
2043
- return `${nodeImageArg(options)}
2044
-
2045
- # Stage 1: Prune the monorepo to the app's slice
2046
- FROM \${NODE_IMAGE} AS pruner
2047
- WORKDIR /app
2048
- ${installPm}
2049
- COPY . .
2050
- RUN ${turbo} prune ${scopes} --docker
2051
-
2052
- # The root's own files — the tsconfig the packages extend, the config their
2053
- # build reads — which turbo prune leaves out. What the install itself reads
2054
- # (registry config, local tarballs) goes beside the manifests too.
2055
- RUN find . -maxdepth 1 -type f ! -name '${pm.lockfile}' ! -name package.json \\
2056
- -exec cp -n {} out/full/ \\; && \\
2057
- for file in .npmrc .yarnrc.yml .pnpmfile.cjs bunfig.toml *.tgz; do \\
2058
- if [ -f "$file" ]; then cp "$file" out/json/; fi; \\
2059
- done${copyGkm}`;
2060
- }
2061
- /** The deps stage: the slice's dependencies, installed from its lockfile. */
2062
- function depsStage(options) {
2063
- const { pm, installPm } = layout(options);
2064
- return `# Stage 2: Install dependencies
2065
- FROM \${NODE_IMAGE} AS deps
2066
- WORKDIR /app
2067
- ${installPm}
2068
- COPY --from=pruner /app/out/${pm.lockfile} ./
2069
- COPY --from=pruner /app/out/json/ ./
2070
- RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
2071
- ${pm.installCmd}`;
2072
- }
2073
- /**
2074
- * The start of the builder stage: the slice's source over its dependencies,
2075
- * and every workspace package the app depends on built from it.
2076
- *
2077
- * Nothing built on the host reaches the image — `.dockerignore` keeps every
2078
- * `dist` out — so a workspace package (a CLI that is a sibling package) is
2079
- * built here: turbo's build of the app's dependencies (`^build`) and nothing
2080
- * else. The root's own `build` script is never run: the slice holds one app,
2081
- * and a root `build` that is `gkm build` (what `gkm init` scaffolds) builds
2082
- * every app the workspace declares, most of which are not in it. The app
2083
- * itself is built after this, by `gkm build` or its framework.
2084
- */
2085
- function builderStage(options, extra = {}) {
2086
- const { turbo, monorepo } = layout(options);
2087
- const args = extra.args ?? [];
2088
- const argLines = args.length ? `\n# Build-time args: public values the bundler inlines\n${args.map((a) => `ARG ${a}=""`).join("\n")}\n${args.map((a) => `ENV ${a}=$${a}`).join("\n")}\n` : "";
2089
- const scopes = [options.turboPackage, ...options.prunePackages ?? []];
2090
- return `# Stage 3: Build
2091
- FROM deps AS builder
2092
- WORKDIR /app
2093
- ${argLines}
2094
- COPY --from=pruner /app/out/full/ ./${monorepo ? `\n# The workspace packages the app depends on, built from source.\nRUN ${turbo} run build ${scopes.map((s) => `--filter='${s}^...'`).join(" ")}` : ""}`;
2095
- }
2096
- /**
2097
- * The PATH a command in the app's directory runs with: the app's binaries,
2098
- * then the gkm workspace's, then the root's — a nested workspace's apps
2099
- * declare nothing, and its CLI is installed where its config is.
2100
- */
2101
- function binPath(options) {
2102
- const { app, gkmRoot } = layout(options);
2103
- const dirs = [
2104
- `${app}/node_modules/.bin`,
2105
- gkmRoot === "." ? "" : `/app/${gkmRoot}/node_modules/.bin`,
2106
- "/app/node_modules/.bin"
2107
- ].filter(Boolean);
2108
- return `PATH="${[...new Set(dirs)].join(":")}:$PATH"`;
2109
- }
2110
- /**
2111
- * Run the gkm CLI the app resolves, from the app's directory: node on its
2112
- * `bin/gkm.mjs`, found the way Node resolves a package — up from the app.
2113
- *
2114
- * Not through `node_modules/.bin`: a CLI that is a workspace package has no
2115
- * bin linked, since its files were not there when the slice's dependencies
2116
- * were installed.
2117
- */
2118
- function gkmCommand(args) {
2119
- return `GKM_BIN="$(node -e '${FIND_GKM_BIN}')" && node "$GKM_BIN" ${args}`;
2120
- }
2121
- /** Prints the `bin/gkm.mjs` Node resolves from the cwd, or fails saying so. */
2122
- const FIND_GKM_BIN = `let d=process.cwd();const{existsSync:e}=require("fs"),{dirname:u,join:j}=require("path");for(;;){const p=j(d,"node_modules/@geekmidas/cli/bin/gkm.mjs");if(e(p)){console.log(p);break}if(u(d)===d){console.error("@geekmidas/cli is not installed where the app can resolve it");process.exit(1)}d=u(d)}`;
2123
- /**
2124
- * What a site's builder does with the gkm workspace it carries, before its
2125
- * framework builds it — all of it inside the image, nothing from the host:
2126
- *
2127
- * - `gkm` on the PATH: the CLI the workspace installs, so a build script that
2128
- * is `gkm exec -- next build` runs. Resolved from the gkm root rather than
2129
- * through `node_modules/.bin`, where a CLI that is a workspace package has
2130
- * no bin linked.
2131
- * - `GKM_IMAGE_BUILD`, which has `gkm exec` inject the build args above — the
2132
- * stage's public URLs — and never load a secret or resolve a local address.
2133
- * - `GKM_BUILD_OFFLINE`, which tells the site's own code that no stage is
2134
- * reachable from this build: its APIs are not up yet, so a page that
2135
- * fetches from them renders on request rather than at build.
2136
- * - each backend's typed client, generated from its endpoints at the
2137
- * workspace root's `.gkm/client/`, where the site's tsconfig paths point.
2138
- */
2139
- function siteWorkspaceSteps(options) {
2140
- const { gkmRoot } = layout(options);
2141
- const root = `/app/${gkmRoot}`.replace(/\/\.$/, "");
2142
- const clients = options.clients ?? [];
2143
- const generate = clients.length ? `
2144
-
2145
- # The typed client of each API this site calls, generated from its endpoints
2146
- # into ${gkmRoot === "." ? "" : `${gkmRoot}/`}.gkm/client/ — offline, with no secret and no container.
2147
- RUN ${clients.map(({ app, path, telemetry }) => [
2148
- "cd",
2149
- `/app/${path}`,
2150
- "&&",
2151
- "gkm",
2152
- "openapi",
2153
- "--app",
2154
- app,
2155
- ...telemetryArgs(telemetry)
2156
- ].join(" ")).join(" && \\\n ")}` : "";
2157
- return `# The gkm CLI the workspace installs, as \`gkm\`
2158
- RUN cd ${root} && GKM_BIN="$(node -e '${FIND_GKM_BIN}')" && \\
2159
- { echo '#!/bin/sh'; echo "exec node \\"$GKM_BIN\\" \\"\\$@\\""; } > /usr/local/bin/gkm && \\
2160
- chmod +x /usr/local/bin/gkm
2161
-
2162
- # \`gkm exec\` in this build injects the build args, never a stage's secrets
2163
- ENV ${IMAGE_BUILD_ENV}=1
2164
- ${options.prerender ? `# Built once the site's APIs are up on its stage: it pre-renders from them` : `# No stage is reachable from this build: the site's APIs are not up yet
2165
- ENV ${BUILD_OFFLINE_ENV}=1`}${generate}`;
2166
- }
2167
- /**
2168
- * Build the site with turbo. Loose env mode, so the task sees what the
2169
- * Dockerfile set — the build args, `GKM_IMAGE_BUILD` and `GKM_BUILD_OFFLINE`
2170
- * — whatever the project's turbo.json declares: the image's environment
2171
- * holds nothing else.
2172
- */
2173
- function siteBuild(options) {
2174
- const { turbo } = layout(options);
2175
- const build = `${turbo} run build --filter='${options.turboPackage}' --env-mode=loose`;
2176
- if (!options.prerender) return `RUN ${build}`;
2177
- const ca = `/run/secrets/${LOCAL_CA_BUILD_SECRET}`;
2178
- return `ARG ${PRERENDER_RUN_ARG}=""
2179
- RUN --mount=type=secret,id=${LOCAL_CA_BUILD_SECRET},required=false \\
2180
- echo "prerendered for: \${${PRERENDER_RUN_ARG}:-any run}" && \\
2181
- if [ -s ${ca} ]; then export NODE_EXTRA_CA_CERTS=${ca}; fi && \\
2182
- ${build}`;
2183
- }
2184
- /**
2185
- * The encrypted credentials, from a build secret — never an ARG, which is
2186
- * recorded in the image history — written where the build embeds them from.
2187
- * Two lines, ciphertext then IV; absent when the app has no secrets.
2188
- *
2189
- * A BuildKit secret is not part of the cache key, so `GKM_CIPHERTEXT_HASH`
2190
- * (a hash of the ciphertext, not a secret) is: credentials encrypted under a
2191
- * new key rebuild the layer that embeds them.
2192
- */
2193
- function credentialsStep(appDir, then) {
2194
- return `ARG GKM_CIPHERTEXT_HASH=""
2195
- RUN --mount=type=secret,id=gkm_credentials,required=false \\
2196
- echo "credentials: \${GKM_CIPHERTEXT_HASH:-none}" && \\
2197
- if [ -s /run/secrets/gkm_credentials ]; then \\
2198
- mkdir -p ${appDir}/.gkm && \\
2199
- sed -n 1p /run/secrets/gkm_credentials > ${appDir}/.gkm/credentials.enc && \\
2200
- sed -n 2p /run/secrets/gkm_credentials > ${appDir}/.gkm/credentials.iv; \\
2201
- fi && \\
2202
- ${then} && \\
2203
- rm -f ${appDir}/.gkm/credentials.enc ${appDir}/.gkm/credentials.iv`;
2204
- }
2205
- /**
2206
- * The packages a bundle left out — its native ones, which load a binary built
2207
- * for the platform they were installed on — installed for Linux beside it.
2208
- * `gkm build` records them, at the versions it resolved, in a `package.json`
2209
- * beside the bundle (`externalsManifestName`), so the image installs exactly
2210
- * what the build left out: nothing, for most apps.
2211
- */
2212
- function externalsStages(distDir, bundle) {
2213
- return {
2214
- stage: `
2215
- # The packages the bundle leaves out, installed for Linux at the versions the
2216
- # build resolved — and nothing else.
2217
- FROM \${NODE_IMAGE} AS externals
2218
- WORKDIR /externals
2219
- COPY --from=builder ${distDir}/${externalsManifestName(bundle)} ./package.json
2220
- RUN --mount=type=cache,id=npm,target=/root/.npm \\
2221
- npm install --omit=dev --no-package-lock --no-audit --no-fund && \\
2222
- mkdir -p node_modules
2223
- `,
2224
- copy: `\nCOPY --from=externals --chown=hono:nodejs /externals/node_modules ./node_modules`
2225
- };
2226
- }
2227
- /**
2228
- * Generate .dockerignore file
2229
- *
2230
- * Written at the build root. Nothing built on the host may reach an image —
2231
- * every image builds its packages from source — and nothing secret may reach
2232
- * a build context.
2233
- */
2234
- function generateDockerignore() {
2235
- return `# Dependencies: installed in the image, for Linux
2236
- **/node_modules
2237
- .pnpm-store
2238
-
2239
- # Build output: every image builds from source, never from the host's
2240
- **/dist
2241
- **/.next
2242
- **/.turbo
2243
- **/.gkm
2244
-
2245
- # The key gkm build --stage encrypted secrets with: runtime env only, never
2246
- # the build context
2247
- **/master.key
2248
-
2249
- # gkm compose's stacks: each app's env file holds its stage's secrets
2250
- **/.gkm/compose
2251
-
2252
- # IDE and editor
2253
- .idea
2254
- .vscode
2255
- *.swp
2256
- *.swo
2257
-
2258
- # Git
2259
- .git
2260
-
2261
- # Logs
2262
- *.log
2263
- npm-debug.log*
2264
- pnpm-debug.log*
2265
-
2266
- # Test files
2267
- coverage
2268
-
2269
- # Environment files (handle secrets separately)
2270
- **/.env
2271
- **/.env.*
2272
- !**/.env.example
2273
-
2274
- # Docker files (don't copy recursively)
2275
- Dockerfile*
2276
- docker-compose*
2277
- .dockerignore
2278
- `;
2279
- }
2280
- /**
2281
- * Resolve Docker configuration from GkmConfig with defaults
2282
- */
2283
- function resolveDockerConfig(config) {
2284
- const docker = config.docker ?? {};
2285
- return {
2286
- registry: docker.registry ?? "",
2287
- imageName: docker.imageName ?? config.name ?? "api",
2288
- baseImage: docker.baseImage ?? "node:22.23.4-alpine",
2289
- port: docker.port ?? 3e3
2290
- };
2291
- }
2292
- /** A site's root answers its health check. */
2293
- function siteHealthcheck(port) {
2294
- return `# A site answers at its root; Docker, and Dokploy, read the container's
2295
- # health from it rather than from the process merely running. 127.0.0.1, not
2296
- # localhost: the server listens on IPv4, and localhost can resolve to ::1.
2297
- HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
2298
- CMD wget -qO- http://127.0.0.1:${port}/ > /dev/null 2>&1 || exit 1`;
2299
- }
2300
- /**
2301
- * Generate a Dockerfile for Next.js frontend apps using standalone output.
2302
- *
2303
- * Pruned at the build root, Next traces from there, so the standalone
2304
- * server lands at `<appPath>/server.js` under `.next/standalone`.
2305
- * @internal Exported for testing
2306
- */
2307
- function generateNextjsDockerfile(options) {
2308
- const { port, appPath, publicUrlArgs = ["NEXT_PUBLIC_API_URL", "NEXT_PUBLIC_AUTH_URL"] } = options;
2309
- return `# syntax=docker/dockerfile:1
2310
- # Next.js standalone Dockerfile, built from a turbo-pruned slice
2311
-
2312
- ${prunerStage(options)}
2313
-
2314
- ${depsStage(options)}
2315
-
2316
- ${builderStage(options, { args: publicUrlArgs })}
2317
-
2318
- ${siteWorkspaceSteps(options)}
2319
-
2320
- # Ensure public directory exists (may be empty for scaffolded projects)
2321
- RUN mkdir -p ${appPath}/public
2322
-
2323
- ENV NEXT_TELEMETRY_DISABLED=1
2324
-
2325
- # Build the application
2326
- ${siteBuild(options)}
2327
-
2328
- # The runner needs the standalone server; without it there is nothing to run.
2329
- RUN if [ ! -d ${appPath}/.next/standalone ]; then \\
2330
- echo "${appPath}/.next/standalone was not built: set output: 'standalone' in next.config so the image can run the app without node_modules." >&2; \\
2331
- exit 1; \\
2332
- fi
2333
-
2334
- # Stage 4: Production
2335
- FROM \${NODE_IMAGE} AS runner
2336
-
2337
- WORKDIR /app
2338
-
2339
- # Install tini for proper signal handling
2340
- RUN apk add --no-cache tini
2341
-
2342
- # Create non-root user
2343
- RUN addgroup --system --gid 1001 nodejs && \\
2344
- adduser --system --uid 1001 nextjs
2345
-
2346
- # Set environment
2347
- ENV NODE_ENV=production
2348
- ENV NEXT_TELEMETRY_DISABLED=1
2349
- ENV PORT=${port}
2350
- ENV HOSTNAME="0.0.0.0"
2351
-
2352
- # The standalone server, with its static files and public directory beside it
2353
- COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/standalone ./
2354
- COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/static ./${appPath}/.next/static
2355
- COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/public ./${appPath}/public
2356
-
2357
- USER nextjs
2358
-
2359
- EXPOSE ${port}
2360
-
2361
- ${siteHealthcheck(port)}
2362
-
2363
- ENTRYPOINT ["/sbin/tini", "--"]
2364
- CMD ["node", "${appPath}/server.js"]
2365
- `;
2366
- }
2367
- /**
2368
- * Where Next's prerender manifest is in the image {@link
2369
- * generateNextjsDockerfile} builds: the standalone output is copied to the
2370
- * runner's `/app`, and the app's `.next/` — its manifests among them — sits
2371
- * beside its `server.js`, at `appPath` under it.
2372
- */
2373
- function nextPrerenderManifest(appPath) {
2374
- return posix.join("/app", appPath, ".next", "prerender-manifest.json");
2375
- }
2376
- /**
2377
- * Generate a Dockerfile for a gkm backend: pruned, installed, and bundled by
2378
- * `gkm build --provider server --production` inside the image. The runner is
2379
- * `server.mjs` — plus the packages the bundle leaves out, which is none
2380
- * unless it uses one with native code.
2381
- * @internal Exported for testing
2382
- */
2383
- function generateBackendDockerfile(options) {
2384
- return gkmBundleDockerfile(options, {
2385
- title: "Backend Dockerfile",
2386
- bundle: "server.mjs",
2387
- as: "server.mjs",
2388
- expose: true
2389
- });
2390
- }
2391
- /** The port a worker answers its health check on, inside its container. */
2392
- const WORKER_PORT = 3e3;
2393
- /** The port a processor unit answers on, inside its container. */
2394
- const PROCESSOR_PORT = 3e3;
2395
- /**
2396
- * A Worker's image: the same build as its host app's backend — a pruned
2397
- * slice, `gkm build --provider server --production` in the image, with the
2398
- * encrypted credentials from the `gkm_credentials` secret — and a runner that
2399
- * is the worker's bundle alone. It publishes nothing: its one route is the
2400
- * health check the HEALTHCHECK asks.
2401
- * @internal Exported for testing
2402
- */
2403
- function generateWorkerDockerfile(options) {
2404
- return gkmBundleDockerfile(options, {
2405
- title: `Worker Dockerfile (${options.worker})`,
2406
- bundle: options.bundle,
2407
- as: "worker.mjs",
2408
- expose: false
2409
- });
2410
- }
2411
- /**
2412
- * A file server's processor unit: its host app's build, and the unit's bundle
2413
- * as the runner. Its native packages — `sharp` — are installed for the image's
2414
- * platform beside the bundle, at the versions the build resolved, as for
2415
- * every bundle.
2416
- */
2417
- function generateProcessorDockerfile(options) {
2418
- return gkmBundleDockerfile(options, {
2419
- title: `Processors Dockerfile (${options.fileServer})`,
2420
- bundle: options.bundle,
2421
- as: "processors.mjs",
2422
- expose: true
2423
- });
2424
- }
2425
- function gkmBundleDockerfile(options, runner) {
2426
- const { port, healthCheckPath = "/health" } = options;
2427
- const { app } = layout(options);
2428
- const shared = options.sharedDirectoryApp;
2429
- const dist = `${app}/.gkm/server${shared ? `/${shared}` : ""}/dist`;
2430
- const externals = externalsStages(dist, runner.bundle);
2431
- return `# syntax=docker/dockerfile:1
2432
- # ${runner.title}: a turbo-pruned slice, bundled by gkm build in the image
2433
-
2434
- ${prunerStage(options)}
2435
-
2436
- ${depsStage(options)}
2437
-
2438
- ${builderStage(options)}
2439
-
2440
- # Bundle the production server, with the encrypted credentials embedded
2441
- ${credentialsStep(app, `cd ${app} && ${gkmCommand(`build --provider server --production${shared ? ` --app ${shared}` : ""}${options.cache ? ` --cache ${options.cache}` : ""}`)}`)}
2442
- ${externals.stage}
2443
- # Production
2444
- FROM \${NODE_IMAGE} AS runner
2445
-
2446
- WORKDIR /app
2447
-
2448
- RUN apk add --no-cache tini
2449
-
2450
- RUN addgroup --system --gid 1001 nodejs && \\
2451
- adduser --system --uid 1001 hono
2452
-
2453
- # The bundled ${runner.as.replace(/\.mjs$/, "")}
2454
- COPY --from=builder --chown=hono:nodejs ${dist}/${runner.bundle} ./${runner.as === runner.bundle ? "" : runner.as}${externals.copy}
2455
-
2456
- ENV NODE_ENV=production
2457
- ENV PORT=${port}
2458
-
2459
- HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
2460
- CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
2461
-
2462
- USER hono
2463
- ${runner.expose ? `\nEXPOSE ${port}\n` : ""}
2464
- ENTRYPOINT ["/sbin/tini", "--"]
2465
- CMD ["node", "${runner.as}"]
2466
- `;
2467
- }
2468
- /**
2469
- * Generate a Dockerfile for apps with a custom entry point.
2470
- * Uses esbuild to bundle the entry point into dist/index.mjs with all dependencies.
2471
- * This is used for apps that don't use gkm routes (e.g., Better Auth servers).
2472
- * @internal Exported for testing
2473
- */
2474
- function generateEntryDockerfile(options) {
2475
- const { port, entry, healthCheckPath = "/health" } = options;
2476
- const { app } = layout(options);
2477
- const esbuild = (defines) => `esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \\
2478
- --outfile=dist/index.mjs --packages=bundle \\
2479
- --banner:js='import { createRequire } from "module"; const require = createRequire(import.meta.url);'${defines}`;
2480
- return `# syntax=docker/dockerfile:1
2481
- # Entry-based Dockerfile: a turbo-pruned slice, bundled by esbuild in the image
2482
-
2483
- ${prunerStage(options)}
2484
-
2485
- ${depsStage(options)}
2486
-
2487
- ${builderStage(options)}
2488
-
2489
- # Bundle the entry point with every dependency (dist/index.mjs), embedding the
2490
- # encrypted credentials when there are any.
2491
- ARG GKM_CIPHERTEXT_HASH=""
2492
- RUN --mount=type=secret,id=gkm_credentials,required=false \\
2493
- echo "credentials: \${GKM_CIPHERTEXT_HASH:-none}" && \\
2494
- cd ${app} && export ${binPath(options)} && \\
2495
- if [ -s /run/secrets/gkm_credentials ]; then \\
2496
- CREDS=$(sed -n 1p /run/secrets/gkm_credentials) && \\
2497
- IV=$(sed -n 2p /run/secrets/gkm_credentials) && \\
2498
- ${esbuild(` \\
2499
- --define:__GKM_ENCRYPTED_CREDENTIALS__="\\"$CREDS\\"" \\
2500
- --define:__GKM_CREDENTIALS_IV__="\\"$IV\\""`)}; \\
2501
- else \\
2502
- ${esbuild("")}; \\
2503
- fi
2504
-
2505
- # Production
2506
- FROM \${NODE_IMAGE} AS runner
2507
-
2508
- WORKDIR /app
2509
-
2510
- RUN apk add --no-cache tini
2511
-
2512
- RUN addgroup --system --gid 1001 nodejs && \\
2513
- adduser --system --uid 1001 app
2514
-
2515
- # Copy bundled output only (no node_modules needed - fully bundled)
2516
- COPY --from=builder --chown=app:nodejs ${app}/dist/index.mjs ./
2517
-
2518
- ENV NODE_ENV=production
2519
- ENV PORT=${port}
2520
-
2521
- HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
2522
- CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
2523
-
2524
- USER app
2525
-
2526
- EXPOSE ${port}
2527
-
2528
- ENTRYPOINT ["/sbin/tini", "--"]
2529
- CMD ["node", "index.mjs"]
2530
- `;
2531
- }
2532
- /**
2533
- * Generate a Dockerfile for Node-based SSR web frameworks (TanStack Start,
2534
- * Remix). Builds with turbo, then runs the framework's production start
2535
- * script.
2536
- *
2537
- * Public URL build args are declared so framework bundlers (Vite, Vinxi)
2538
- * can inline them at build time. Per-framework prefix is the caller's job.
2539
- * @internal Exported for testing
2540
- */
2541
- function generateNodeWebDockerfile(options) {
2542
- const { port, appPath } = options;
2543
- return `# syntax=docker/dockerfile:1
2544
- # Node SSR web Dockerfile (TanStack Start / Remix), from a turbo-pruned slice
2545
-
2546
- ${prunerStage(options)}
2547
-
2548
- ${depsStage(options)}
2549
-
2550
- ${builderStage(options, { args: options.publicUrlArgs ?? [] })}
2551
-
2552
- ${siteWorkspaceSteps(options)}
2553
-
2554
- ${siteBuild(options)}
2555
-
2556
- FROM \${NODE_IMAGE} AS runner
2557
- WORKDIR /app
2558
- RUN apk add --no-cache tini
2559
- RUN addgroup --system --gid 1001 nodejs && \\
2560
- adduser --system --uid 1001 app
2561
-
2562
- # Copy the whole built workspace — frameworks differ on output paths
2563
- COPY --from=builder --chown=app:nodejs /app/ ./
2564
-
2565
- ENV NODE_ENV=production
2566
- ENV PORT=${port}
2567
- ENV HOSTNAME="0.0.0.0"
2568
-
2569
- USER app
2570
- EXPOSE ${port}
2571
-
2572
- ${siteHealthcheck(port)}
2573
-
2574
- ENTRYPOINT ["/sbin/tini", "--"]
2575
- # npm ships with node, and runs the start script whichever package manager
2576
- # installed it: the runner needs no other.
2577
- CMD ["sh", "-c", "cd ${appPath} && npm start"]
2578
- `;
2579
- }
2580
- /**
2581
- * Generate a Dockerfile for Vite SPA apps. Builds the static bundle with
2582
- * turbo, then serves it with Caddy: Vite's hashed `/assets/*` cached for a
2583
- * year, everything else — `index.html`, and every deep link that falls back
2584
- * to it — revalidated on each request.
2585
- * @internal Exported for testing
2586
- */
2587
- function generateViteStaticDockerfile(options) {
2588
- const { port, appPath } = options;
2589
- return `# syntax=docker/dockerfile:1
2590
- # Vite SPA Dockerfile — a turbo-pruned slice built to static files, served by Caddy
2591
-
2592
- ${prunerStage(options)}
2593
-
2594
- ${depsStage(options)}
2595
-
2596
- ${builderStage(options, { args: options.publicUrlArgs ?? [] })}
2597
-
2598
- ${siteWorkspaceSteps(options)}
2599
-
2600
- ${siteBuild(options)}
2601
-
2602
- FROM ${STATIC_SITE_IMAGE} AS runner
2603
-
2604
- COPY <<'EOF' /etc/caddy/Caddyfile
2605
- {
2606
- admin off
2607
- auto_https off
2608
- persist_config off
2609
- }
2610
-
2611
- :${port} {
2612
- root * /srv
2613
- encode zstd gzip
2614
-
2615
- # Vite names every built asset by its content hash: a changed file is a
2616
- # new URL, so the old one can be cached for good.
2617
- handle /assets/* {
2618
- header Cache-Control "public, max-age=31536000, immutable"
2619
- file_server
2620
- }
2621
-
2622
- # index.html, and every client-side route that falls back to it, is
2623
- # asked for again each time so a deploy is seen at once.
2624
- handle {
2625
- header Cache-Control "no-cache"
2626
- try_files {path} /index.html
2627
- file_server
2628
- }
2629
- }
2630
- EOF
2631
-
2632
- COPY --from=builder /app/${appPath}/dist /srv
2633
-
2634
- RUN addgroup -S -g 1001 site && adduser -S -u 1001 -G site site && \\
2635
- chown -R site:site /data /config
2636
-
2637
- USER site
2638
-
2639
- EXPOSE ${port}
2640
-
2641
- ${siteHealthcheck(port)}
2642
-
2643
- CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
2644
- `;
2645
- }
2646
- //#endregion
2647
- //#region src/docker/layout.ts
2648
- /**
2649
- * Where a workspace's images are built from, and what each is built with.
2650
- *
2651
- * Every builder of images — `gkm docker`, `gkm compose`, a Dokploy deploy —
2652
- * builds from the same place with the same templates: the build root (the
2653
- * package manager's root, at or above the gkm workspace), cut by `turbo
2654
- * prune` to one app's slice. Nothing is built on the host.
2655
- */
2656
- /** A workspace of packages with no turbo.json, which every image prunes with. */
2657
- var MonorepoNeedsTurbo = class extends GkmError {
2658
- buildRoot;
2659
- constructor(buildRoot) {
2660
- super(`${buildRoot} is a workspace of packages, and its images are built from a turbo-pruned slice of it — but it has no turbo.json.\n\nTo fix this:
2661
- 1. Install turbo: pnpm add -Dw turbo
2662
- 2. Create turbo.json in ${buildRoot}\n 3. Run this command again
2663
-
2664
- See: https://turbo.build/repo/docs/guides/tools/docker`);
2665
- this.buildRoot = buildRoot;
2666
- this.name = "MonorepoNeedsTurbo";
2667
- }
2668
- };
2669
- /**
2670
- * Where a workspace's images are built from.
2671
- *
2672
- * Refuses a workspace of packages with no turbo.json — every image prunes
2673
- * with turbo — so only a caller about to generate or build images asks.
2674
- */
2675
- function imageLayout(workspace) {
2676
- const buildRoot = findBuildRoot(workspace.root);
2677
- const tools = resolveBuildTools(buildRoot);
2678
- if (tools.monorepo && !hasTurboConfig(buildRoot)) throw new MonorepoNeedsTurbo(buildRoot);
2679
- const gkmRoot = toPosix(relative(buildRoot, workspace.root)) || ".";
2680
- const workspacePackage = gkmRoot !== "." ? packageName(workspace.root) : void 0;
2681
- return {
2682
- buildRoot,
2683
- gkmRoot,
2684
- tools,
2685
- ...workspacePackage ? { workspacePackage } : {},
2686
- gkmPaths: ["gkm.config.*", ...constructRoots(workspace)]
2687
- };
2688
- }
2689
- /**
2690
- * How a compose file builds an app: the build root as the context, relative
2691
- * to the directory the compose file is in, and the Dockerfile — written under
2692
- * the gkm root — relative to that context, which is what compose resolves
2693
- * `dockerfile` against.
2694
- */
2695
- function composeBuildPaths(options) {
2696
- const { composeDir, buildRoot, workspaceRoot, dockerfile } = options;
2697
- return {
2698
- context: toPosix(relative(composeDir, buildRoot)) || ".",
2699
- dockerfile: toPosix(join(relative(buildRoot, workspaceRoot), dockerfile))
2700
- };
2701
- }
2702
- /** A path under the gkm root, as the build root sees it. */
2703
- function fromBuildRoot(layout, path) {
2704
- if (layout.gkmRoot === ".") return toPosix(path);
2705
- const joined = toPosix(join(layout.gkmRoot, path));
2706
- return joined === "" ? "." : joined;
2707
- }
2708
- /** Everything a template needs about one app, relative to the build root. */
2709
- function appImageOptions(layout, appName, app, workspaceRoot, apps = {}, clientTelemetry) {
2710
- const turboPackage = packageName(isAbsolute(app.path) ? app.path : join(workspaceRoot, app.path)) ?? appName;
2711
- return {
2712
- imageName: appName,
2713
- baseImage: DEFAULT_BASE_IMAGE,
2714
- port: app.port,
2715
- appPath: fromBuildRoot(layout, app.path),
2716
- turboPackage,
2717
- packageManager: layout.tools.packageManager,
2718
- ...layout.tools.packageManagerVersion ? { packageManagerVersion: layout.tools.packageManagerVersion } : {},
2719
- turboVersion: layout.tools.turboVersion,
2720
- monorepo: layout.tools.monorepo,
2721
- gkmRoot: layout.gkmRoot,
2722
- ...app.type === "backend" ? {
2723
- gkmPaths: layout.gkmPaths,
2724
- ...layout.workspacePackage && layout.workspacePackage !== turboPackage ? { prunePackages: [layout.workspacePackage] } : {}
2725
- } : app.type === "web" ? siteWorkspace(layout, app, apps, workspaceRoot, turboPackage, clientTelemetry) : {}
2726
- };
2727
- }
2728
- /**
2729
- * What a site's image carries of the gkm workspace: its config and construct
2730
- * directories, the workspace's own package where it is nested in a monorepo
2731
- * (it holds the CLI), and each backend the site calls — whose endpoints its
2732
- * client is generated from, and whose package their imports resolve in.
2733
- */
2734
- function siteWorkspace(layout, site, apps, workspaceRoot, turboPackage, clientTelemetry) {
2735
- const clients = siteClients(site, apps);
2736
- const packages = /* @__PURE__ */ new Set();
2737
- if (layout.workspacePackage) packages.add(layout.workspacePackage);
2738
- for (const { app } of clients) {
2739
- const backend = apps[app];
2740
- const name = packageName(isAbsolute(backend.path) ? backend.path : join(workspaceRoot, backend.path));
2741
- if (name) packages.add(name);
2742
- }
2743
- packages.delete(turboPackage);
2744
- return {
2745
- gkmPaths: layout.gkmPaths,
2746
- ...packages.size > 0 ? { prunePackages: [...packages].sort() } : {},
2747
- ...clients.length > 0 ? { clients: clients.map(({ app }) => ({
2748
- app,
2749
- path: fromBuildRoot(layout, apps[app].path),
2750
- ...clientTelemetry ? { telemetry: clientTelemetry } : {}
2751
- })) } : {}
2752
- };
2753
- }
2754
- /**
2755
- * The backends whose clients a site imports: each it depends on that gkm
2756
- * builds from endpoints — not one with an entry of its own, and not one that
2757
- * turned OpenAPI off.
2758
- */
2759
- function siteClients(site, apps) {
2760
- return site.dependencies.filter((name) => {
2761
- const app = apps[name];
2762
- if (!app || app.type !== "backend" || app.entry) return false;
2763
- if (app.openapi === false) return false;
2764
- if (typeof app.openapi === "object" && app.openapi.enabled === false) return false;
2765
- return true;
2766
- }).sort().map((app) => ({ app }));
2767
- }
2768
- /**
2769
- * The directories the workspace's construct globs start in, relative to its
2770
- * root: `./constructs/**\/*.ts` reads from `constructs`.
2771
- */
2772
- function constructRoots(workspace) {
2773
- const roots = /* @__PURE__ */ new Set();
2774
- for (const glob of allConstructGlobs(workspace)) {
2775
- const rel = toPosix(relative(workspace.root, glob));
2776
- if (!rel || rel.startsWith("..")) continue;
2777
- const first = rel.split("/")[0];
2778
- if (/[*?{}[\]!]/.test(first)) continue;
2779
- roots.add(first);
2780
- }
2781
- return [...roots].sort();
2782
- }
2783
- function packageName(dir) {
2784
- try {
2785
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
2786
- return typeof pkg.name === "string" ? pkg.name : void 0;
2787
- } catch {
2788
- return;
2789
- }
2790
- }
2791
- function toPosix(path) {
2792
- return path.split(sep).join("/");
2793
- }
2794
- //#endregion
2795
- //#region src/providers/processorOrigin.ts
2796
- /**
2797
- * A file server's processors as a CDN origin: the names both sides agree on.
2798
- *
2799
- * On a compose stage whose bucket is on S3, the CDN serves the bucket and
2800
- * sends each processor pattern to the stack's processor unit, at a host of
2801
- * its own. That host is public — a CDN reaches its origin over the internet —
2802
- * so the CDN adds a secret header and the edge refuses any request without
2803
- * it. One definition, read by the CDN that sends the header and by the stack
2804
- * whose edge checks it, so the two cannot drift.
2805
- */
2806
- /** The header the CDN adds to every request it sends a processor. */
2807
- const ORIGIN_VERIFY_HEADER = "X-Gkm-Origin-Verify";
2808
- /**
2809
- * Where a file server's processors answer the CDN:
2810
- * `<fileserver>-processors.<domain>`, `assets-processors.example.com` for
2811
- * `AssetsServer`.
2812
- */
2813
- function processorOriginHost(serverId, domain) {
2814
- return `${fileServerLabel(serverId)}-processors.${domain}`.toLowerCase();
2815
- }
2816
- /** The stage secret holding the header's value: `ASSETS_SERVER_ORIGIN_SECRET`. */
2817
- function originSecretKey(serverId) {
2818
- return environmentCase(`${serverId}_originSecret`);
2819
- }
2820
- /**
2821
- * What the processor unit reads that secret from. Set wherever the CDN fronts
2822
- * it, so the unit refuses a request without the header itself — on Dokploy,
2823
- * whose edge cannot match a header, the only check; behind the stack's own
2824
- * edge, a second one.
2825
- */
2826
- const PROCESSOR_ORIGIN_SECRET_ENV = "GKM_PROCESSOR_ORIGIN_SECRET";
2827
- /** A new value for that secret: random, generated once, kept in the stage. */
2828
- function newOriginSecret() {
2829
- return randomBytes(32).toString("base64url");
2830
- }
2831
- //#endregion
2832
- //#region src/secrets/stackKeys.ts
2833
- /**
2834
- * The stage secrets gkm keeps for the stack itself rather than for the
2835
- * application: the server's address, the logins of the containers it runs
2836
- * (Redis, OpenObserve), the key backups write with, the secret a CDN sends a
2837
- * file server's processors.
2838
- *
2839
- * Nothing in an app reads them, so no process is handed one as "the stage's
2840
- * own" (`processEnvKeys`) — the containers that do read them are given them
2841
- * by name.
2842
- */
2843
- const STACK_KEYS = /* @__PURE__ */ new Set([
2844
- BACKUPS_URL_KEY,
2845
- LOGS_EMAIL_KEY,
2846
- LOGS_PASSWORD_KEY,
2847
- REDIS_PASSWORD_KEY,
2848
- PROCESSOR_ORIGIN_SECRET_ENV
2849
- ]);
2850
- /** A file server's origin secret: `ASSETS_SERVER_ORIGIN_SECRET`. */
2851
- const ORIGIN_SECRET = /_ORIGIN_SECRET$/;
2852
- /** Whether a stage secret is the stack's own, which no app process reads. */
2853
- function isStackKey(key) {
2854
- return isReservedStageKey(key) || key.startsWith("GKM_") || STACK_KEYS.has(key) || ORIGIN_SECRET.test(key);
2855
- }
2856
- //#endregion
2857
- //#region src/reconcile/clients.ts
2858
- /**
2859
- * The real Postgres and MinIO clients the applier runs against.
2860
- *
2861
- * Kept apart from `provision.ts` so the rules there — what gets created, in what
2862
- * order, and never dropping anything — are asserted against fakes, while the
2863
- * drivers live here where there is nothing to assert but wiring.
2864
- *
2865
- * Both are constructed from the same local addresses the env writer composes,
2866
- * so the applier cannot end up talking to a different container than the app.
2867
- */
2868
- /**
2869
- * A Postgres client that opens one connection per database it is asked about.
2870
- *
2871
- * `CREATE DATABASE` cannot run from a connection to the database being created,
2872
- * and a schema must be created from inside its own database — so the database is
2873
- * part of each query rather than fixed when the client is built.
2874
- */
2875
- function pgClient(port, login) {
2876
- return { async query(database, sql, values) {
2877
- const client = new Client({
2878
- host: "localhost",
2879
- port,
2880
- user: login.user,
2881
- password: login.password,
2882
- database: database ?? "postgres"
2883
- });
2884
- await client.connect();
2885
- try {
2886
- return (await client.query(sql, values)).rows;
2887
- } finally {
2888
- await client.end();
2889
- }
2890
- } };
2891
- }
2892
- /** A bucket client pointed at a MinIO on this machine. */
2893
- function bucketClient(port, credentials) {
2894
- const s3 = new S3Client({
2895
- region: "us-east-1",
2896
- endpoint: `http://localhost:${port}`,
2897
- forcePathStyle: true,
2898
- credentials: {
2899
- accessKeyId: credentials.user,
2900
- secretAccessKey: credentials.password
2901
- }
2902
- });
2903
- return {
2904
- async exists(bucket) {
2905
- try {
2906
- await s3.send(new HeadBucketCommand({ Bucket: bucket }));
2907
- return true;
2908
- } catch {
2909
- return false;
2910
- }
2911
- },
2912
- async create(bucket) {
2913
- await s3.send(new CreateBucketCommand({ Bucket: bucket }));
2914
- },
2915
- async policy(bucket) {
2916
- try {
2917
- return (await s3.send(new GetBucketPolicyCommand({ Bucket: bucket }))).Policy;
2918
- } catch {
2919
- return;
2920
- }
2921
- },
2922
- async setPolicy(bucket, policy) {
2923
- await s3.send(new PutBucketPolicyCommand({
2924
- Bucket: bucket,
2925
- Policy: policy
2926
- }));
2927
- },
2928
- async lifecycle(bucket) {
2929
- try {
2930
- return (await s3.send(new GetBucketLifecycleConfigurationCommand({ Bucket: bucket }))).Rules;
2931
- } catch (error) {
2932
- if (error.name === "NoSuchLifecycleConfiguration") return;
2933
- throw error;
2934
- }
2935
- },
2936
- async setLifecycle(bucket, rules) {
2937
- if (rules.length === 0) {
2938
- await s3.send(new DeleteBucketLifecycleCommand({ Bucket: bucket }));
2939
- return;
2940
- }
2941
- await s3.send(new PutBucketLifecycleConfigurationCommand({
2942
- Bucket: bucket,
2943
- LifecycleConfiguration: { Rules: rules }
2944
- }));
2945
- },
2946
- async notification(bucket) {
2947
- const { $metadata: _, ...notification } = await s3.send(new GetBucketNotificationConfigurationCommand({ Bucket: bucket }));
2948
- return notification;
2949
- },
2950
- async setNotification(bucket, notification) {
2951
- await s3.send(new PutBucketNotificationConfigurationCommand({
2952
- Bucket: bucket,
2953
- NotificationConfiguration: notification
2954
- }));
2955
- }
2956
- };
2957
- }
2958
- /** A topic and queue client pointed at the local AWS emulator. */
2959
- function carrierClient(port, credentials) {
2960
- const config = {
2961
- region: EMULATOR_REGION,
2962
- endpoint: emulatorEndpoint(port),
2963
- credentials
2964
- };
2965
- const sns = new SNSClient(config);
2966
- const sqs = new SQSClient(config);
2967
- return {
2968
- async topicExists(name) {
2969
- try {
2970
- await sns.send(new GetTopicAttributesCommand({ TopicArn: emulatorTopicArn(name) }));
2971
- return true;
2972
- } catch {
2973
- return false;
2974
- }
2975
- },
2976
- async createTopic(name) {
2977
- await sns.send(new CreateTopicCommand({ Name: name }));
2978
- },
2979
- async queueExists(name) {
2980
- try {
2981
- await sqs.send(new GetQueueUrlCommand({ QueueName: name }));
2982
- return true;
2983
- } catch {
2984
- return false;
2985
- }
2986
- },
2987
- async createQueue(name) {
2988
- await sqs.send(new CreateQueueCommand({ QueueName: name }));
2989
- }
2990
- };
2991
- }
2992
- //#endregion
2993
- //#region src/reconcile/docker.ts
2994
- /**
2995
- * The real Docker, behind the small interface reconcile needs.
2996
- *
2997
- * Shells out to `docker compose` rather than talking to the daemon socket: it is
2998
- * what a developer runs by hand when something is wrong, so the two cannot
2999
- * disagree, and it keeps Docker out of this package's dependencies.
3000
- *
3001
- * Every call that acts is scoped to the generated compose file. Nothing here
3002
- * can touch a container this project did not generate; `publisher` only reads
3003
- * who holds a port.
3004
- */
3005
- const run = promisify(execFile);
3006
- /**
3007
- * The generated file, then the project's own if it has one.
3008
- *
3009
- * Merged in that order so the project's wins — an `image:` there pins a
3010
- * container this file derived, and a service there is added beside them.
3011
- */
3012
- function composeFiles(composePath) {
3013
- const project = join(dirname(composePath), "docker-compose.yml");
3014
- return [
3015
- "-f",
3016
- composePath,
3017
- ...existsSync(project) ? ["-f", project] : []
3018
- ];
3019
- }
3020
- /** How long to wait for containers to pass their health checks. */
3021
- const HEALTH_TIMEOUT_MS = 12e4;
3022
- /** `docker compose up` exited unsuccessfully; its own output said why. */
3023
- var ComposeUpFailed = class extends Error {
3024
- services;
3025
- code;
3026
- constructor(services, code) {
3027
- super(`docker compose could not start ${services.join(", ")} (exit ${code ?? "signal"}). Its output above names the container; \`docker compose logs <service>\` shows why it stopped.`);
3028
- this.services = services;
3029
- this.code = code;
3030
- this.name = "ComposeUpFailed";
3031
- }
3032
- };
3033
- /** Run compose with its output on this terminal rather than captured. */
3034
- function shown(args, services) {
3035
- return new Promise((resolve, reject) => {
3036
- const child = spawn("docker", args, { stdio: [
3037
- "ignore",
3038
- "inherit",
3039
- "inherit"
3040
- ] });
3041
- child.on("error", reject);
3042
- child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeUpFailed(services, code)));
3043
- });
3044
- }
3045
- const dockerCli = {
3046
- async publishedPort(composePath, service, inside) {
3047
- try {
3048
- const { stdout } = await run("docker", [
3049
- "compose",
3050
- ...composeFiles(composePath),
3051
- "port",
3052
- service,
3053
- String(inside)
3054
- ]);
3055
- const port = Number(stdout.trim().split(":").pop());
3056
- return Number.isFinite(port) && port > 0 ? port : void 0;
3057
- } catch {
3058
- return;
3059
- }
3060
- },
3061
- async publisher(port) {
3062
- try {
3063
- const { stdout } = await run("docker", [
3064
- "ps",
3065
- "--filter",
3066
- `publish=${port}`,
3067
- "--format",
3068
- "{{.Label \"com.docker.compose.project\"}}"
3069
- ]);
3070
- return stdout.trim().split("\n")[0] || void 0;
3071
- } catch {
3072
- return;
3073
- }
3074
- },
3075
- async up(composePath, services, options = {}) {
3076
- const args = [
3077
- "compose",
3078
- ...composeFiles(composePath),
3079
- "up",
3080
- "-d",
3081
- "--remove-orphans",
3082
- "--wait",
3083
- `--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1e3)}`,
3084
- ...services
3085
- ];
3086
- if (options.show) return shown(args, services);
3087
- await run("docker", args);
3088
- },
3089
- async reload(composePath, service) {
3090
- await run("docker", [
3091
- "compose",
3092
- ...composeFiles(composePath),
3093
- "exec",
3094
- "-T",
3095
- service,
3096
- "caddy",
3097
- "reload",
3098
- "--config",
3099
- "/etc/caddy/Caddyfile",
3100
- "--force"
3101
- ]);
3102
- },
3103
- async exec(composePath, service, argv) {
3104
- try {
3105
- const { stdout, stderr } = await run("docker", [
3106
- "compose",
3107
- ...composeFiles(composePath),
3108
- "exec",
3109
- "-T",
3110
- service,
3111
- ...argv
3112
- ]);
3113
- return {
3114
- ok: true,
3115
- output: `${stdout}${stderr}`
3116
- };
3117
- } catch (error) {
3118
- const { stdout = "", stderr = "" } = error;
3119
- return {
3120
- ok: false,
3121
- output: `${stdout}${stderr}`
3122
- };
3123
- }
3124
- },
3125
- async healthy(composePath, services, { mounted = [] } = {}) {
3126
- if (services.length === 0) return true;
3127
- const checkout = dirname(composePath);
3128
- try {
3129
- const { stdout } = await run("docker", [
3130
- "compose",
3131
- ...composeFiles(composePath),
3132
- "ps",
3133
- "--format",
3134
- "json",
3135
- ...services
3136
- ]);
3137
- const running = /* @__PURE__ */ new Set();
3138
- for (const line of stdout.trim().split("\n").filter(Boolean)) {
3139
- const entry = JSON.parse(line);
3140
- const ok = entry.State === "running" && (entry.Health === void 0 || entry.Health === "" || entry.Health === "healthy");
3141
- const fromHere = !entry.Service || !mounted.includes(entry.Service) || label(entry.Labels, "com.docker.compose.project.working_dir") === checkout;
3142
- if (ok && fromHere && entry.Service) running.add(entry.Service);
3143
- }
3144
- return services.every((service) => running.has(service));
3145
- } catch {
3146
- return false;
3147
- }
3148
- }
3149
- };
3150
- /** One label's value out of `docker compose ps`'s comma-joined `Labels`. */
3151
- function label(labels, name) {
3152
- const prefix = `${name}=`;
3153
- return labels?.split(",").find((pair) => pair.startsWith(prefix))?.slice(prefix.length);
3154
- }
3155
- //#endregion
3156
- //#region src/reconcile/lan.ts
3157
- /**
3158
- * This machine's address on the local network — what a phone running the app
3159
- * reaches it on.
3160
- */
3161
- /**
3162
- * The first private IPv4 address of an interface that is up and not loopback.
3163
- *
3164
- * Private ranges only (`10/8`, `172.16/12`, `192.168/16`): a public address
3165
- * would mean listening for a phone on the open internet, and a link-local one
3166
- * (`169.254/16`) is what an interface has when it found no network at all.
3167
- * Undefined when there is none — a laptop on no network still runs, its mobile
3168
- * app reaching only a simulator.
3169
- */
3170
- function lanAddress(interfaces = networkInterfaces()) {
3171
- for (const entries of Object.values(interfaces)) for (const entry of entries ?? []) {
3172
- if (entry.family !== "IPv4" || entry.internal) continue;
3173
- if (isPrivate(entry.address)) return entry.address;
3174
- }
3175
- }
3176
- function isPrivate(address) {
3177
- return /^10\./.test(address) || /^192\.168\./.test(address) || /^172\.(1[6-9]|2\d|3[01])\./.test(address);
3178
- }
3179
- //#endregion
3180
- //#region src/reconcile/logins.ts
3181
- /**
3182
- * Bringing a container that already has data in line with the workspace's
3183
- * generated logins.
3184
- *
3185
- * Postgres and RabbitMQ read their login from the environment once, when the
3186
- * volume is first initialised; a volume an older gkm made was initialised
3187
- * with the old fixed one, and a changed environment alone would lock the
3188
- * developer out of their own data. So after the containers are up, each one
3189
- * is asked whether the generated login opens it, and if not:
3190
- *
3191
- * - **Postgres**: signed in to with the old login, the generated superuser is
3192
- * created (or given its password), and the old one stops logging in. Where
3193
- * no login is accepted — another checkout of the same project rotated it —
3194
- * the password is set from inside the container, which trusts its own
3195
- * socket.
3196
- * - **MinIO** reads its root login on every start, so recreating the
3197
- * container rotated it already. If the old login is still the one it takes —
3198
- * a project's own `docker-compose.yml` pins it — that is kept, with a note.
3199
- * - **RabbitMQ**: the user is added, or given its password, with `rabbitmqctl`
3200
- * inside the container.
3201
- *
3202
- * Nothing is deleted: no volume, no database, no bucket.
3203
- */
3204
- /**
3205
- * The login every local container was brought up with before logins were
3206
- * generated. Kept only to recognise — and rotate away from — a volume made
3207
- * then.
3208
- */
3209
- const LEGACY_LOCAL_LOGIN = Object.freeze({
3210
- user: "geekmidas",
3211
- password: "geekmidas"
3212
- });
3213
- /** No login this workspace knows opens its Postgres. */
3214
- var PostgresLoginRefused = class extends GkmError {
3215
- port;
3216
- user;
3217
- constructor(port, user) {
3218
- super(`The Postgres on port ${port} accepts neither '${user}' with this workspace's generated password nor the login older gkm versions used, and could not be reset from inside its container. If it is not this project's container, stop whatever holds the port. If it is, removing its volume starts it over with the generated login — and deletes its data: docker compose -f docker-compose.constructs.yml down -v`);
3219
- this.port = port;
3220
- this.user = user;
3221
- this.name = "PostgresLoginRefused";
3222
- }
3223
- };
3224
- /** No login this workspace knows opens its MinIO. */
3225
- var MinioLoginRefused = class extends GkmError {
3226
- port;
3227
- user;
3228
- constructor(port, user) {
3229
- super(`The MinIO on port ${port} accepts neither '${user}' with this workspace's generated password nor the login older gkm versions used. If your docker-compose.yml sets MINIO_ROOT_USER or MINIO_ROOT_PASSWORD, remove them so the generated login applies.`);
3230
- this.port = port;
3231
- this.user = user;
3232
- this.name = "MinioLoginRefused";
3233
- }
3234
- };
3235
- /** Whether `login` opens the Postgres on `port`, as a connected client. */
3236
- async function connect$1(port, login) {
3237
- const client = new Client({
3238
- host: "localhost",
3239
- port,
3240
- user: login.user,
3241
- password: login.password,
3242
- database: CLUSTER_DATABASE
3243
- });
3244
- try {
3245
- await client.connect();
3246
- return client;
3247
- } catch (error) {
3248
- await client.end().catch(() => {});
3249
- const code = error.code;
3250
- if (code === "28P01" || code === "28000" || code === "3D000") return null;
3251
- throw error;
3252
- }
3253
- }
3254
- /** Quote a string literal for DDL that cannot take parameters. */
3255
- function literal(value) {
3256
- return `'${value.replace(/'/g, "''")}'`;
3257
- }
3258
- function ident(name) {
3259
- return `"${name.replace(/"/g, "\"\"")}"`;
3260
- }
3261
- /** The SQL that makes `login` a superuser with its password, new or not. */
3262
- function superuserSql(login) {
3263
- return `DO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(login.user)}) THEN ALTER ROLE ${ident(login.user)} WITH SUPERUSER LOGIN PASSWORD ${literal(login.password)}; ELSE CREATE ROLE ${ident(login.user)} WITH SUPERUSER LOGIN PASSWORD ${literal(login.password)}; END IF; END \$\$`;
3264
- }
3265
- /**
3266
- * Make the Postgres on `port` take `login`, rotating it from an older one
3267
- * where that is what it takes.
3268
- */
3269
- async function ensurePostgresLogin(options) {
3270
- const { port, login, legacy } = options;
3271
- const current = await connect$1(port, login);
3272
- if (current) {
3273
- await current.end();
3274
- return {
3275
- service: "postgres",
3276
- status: "current",
3277
- login
3278
- };
3279
- }
3280
- for (const old of legacy) {
3281
- const client = await connect$1(port, old);
3282
- if (!client) continue;
3283
- try {
3284
- await client.query(superuserSql(login));
3285
- } catch {
3286
- await client.end();
3287
- return {
3288
- service: "postgres",
3289
- status: "kept",
3290
- login: old,
3291
- notice: `⚠️ Postgres still signs in as '${old.user}' with the old fixed password: it could not be rotated. To start over with a generated one, remove its volume (this deletes its data): docker compose -f docker-compose.constructs.yml down -v`
3292
- };
3293
- }
3294
- await client.end();
3295
- await retire(port, login, old);
3296
- return {
3297
- service: "postgres",
3298
- status: "rotated",
3299
- login,
3300
- notice: `🔑 Postgres moved from the old fixed login to a generated one ('${login.user}'); its data is unchanged. See it with: gkm dev:credentials`
3301
- };
3302
- }
3303
- if (options.exec) for (const user of [login.user, ...legacy.map((l) => l.user)]) {
3304
- if (!(await options.exec("postgres", [
3305
- "psql",
3306
- "-v",
3307
- "ON_ERROR_STOP=1",
3308
- "-U",
3309
- user,
3310
- "-d",
3311
- "postgres",
3312
- "-c",
3313
- superuserSql(login)
3314
- ])).ok) continue;
3315
- const client = await connect$1(port, login);
3316
- if (!client) continue;
3317
- await client.end();
3318
- for (const old of legacy) await retire(port, login, old);
3319
- return {
3320
- service: "postgres",
3321
- status: "rotated",
3322
- login,
3323
- notice: `🔑 Postgres's login was reset to this workspace's generated one ('${login.user}'); its data is unchanged.`
3324
- };
3325
- }
3326
- throw new PostgresLoginRefused(port, login.user);
3327
- }
3328
- /** Stop an older login from opening the cluster, now another does. */
3329
- async function retire(port, login, old) {
3330
- if (old.user === login.user) return;
3331
- const client = await connect$1(port, login);
3332
- if (!client) return;
3333
- try {
3334
- if ((await client.query("SELECT 1 FROM pg_roles WHERE rolname = $1", [old.user])).rowCount) await client.query(`ALTER ROLE ${ident(old.user)} WITH NOLOGIN PASSWORD NULL`);
3335
- } finally {
3336
- await client.end();
3337
- }
3338
- }
3339
- /** Whether `login` signs in to the MinIO on `port`. */
3340
- async function minioAccepts(port, login) {
3341
- const s3 = new S3Client({
3342
- region: "us-east-1",
3343
- endpoint: `http://localhost:${port}`,
3344
- forcePathStyle: true,
3345
- credentials: {
3346
- accessKeyId: login.user,
3347
- secretAccessKey: login.password
3348
- },
3349
- maxAttempts: 1
3350
- });
3351
- try {
3352
- await s3.send(new ListBucketsCommand({}));
3353
- return true;
3354
- } catch (error) {
3355
- const name = error.name ?? "";
3356
- if (name === "InvalidAccessKeyId" || name === "SignatureDoesNotMatch" || name === "AccessDenied") return false;
3357
- throw error;
3358
- } finally {
3359
- s3.destroy();
3360
- }
3361
- }
3362
- /**
3363
- * Check the MinIO on `port` takes `login`. It reads its root login on every
3364
- * start, so a recreated container already does — unless something pins an
3365
- * older one, which is then kept.
3366
- */
3367
- async function ensureMinioLogin(options) {
3368
- const { port, login, legacy } = options;
3369
- if (await minioAccepts(port, login)) return {
3370
- service: "minio",
3371
- status: "current",
3372
- login
3373
- };
3374
- for (const old of legacy) if (await minioAccepts(port, old)) return {
3375
- service: "minio",
3376
- status: "kept",
3377
- login: old,
3378
- notice: `⚠️ MinIO still signs in as '${old.user}' with the old fixed password: something — usually your docker-compose.yml's MINIO_ROOT_USER/MINIO_ROOT_PASSWORD — pins it. Remove that to use the generated login.`
3379
- };
3380
- throw new MinioLoginRefused(port, login.user);
3381
- }
3382
- /**
3383
- * Make the RabbitMQ in the project's container take `login`, with
3384
- * `rabbitmqctl` inside it — which needs no password.
3385
- */
3386
- async function ensureRabbitmqLogin(options) {
3387
- const { login, legacy, exec } = options;
3388
- const ctl = (...args) => exec("rabbitmq", ["rabbitmqctl", ...args]);
3389
- if ((await ctl("authenticate_user", login.user, login.password)).ok) return {
3390
- service: "rabbitmq",
3391
- status: "current",
3392
- login
3393
- };
3394
- if (!(await ctl("add_user", login.user, login.password)).ok) await ctl("change_password", login.user, login.password);
3395
- await ctl("set_user_tags", login.user, "administrator");
3396
- await ctl("set_permissions", "-p", "/", login.user, ".*", ".*", ".*");
3397
- for (const old of legacy) if (old.user !== login.user) await ctl("delete_user", old.user);
3398
- return {
3399
- service: "rabbitmq",
3400
- status: "rotated",
3401
- login,
3402
- notice: `🔑 RabbitMQ moved from the old fixed login to a generated one ('${login.user}'); its queues are unchanged.`
3403
- };
3404
- }
3405
- /**
3406
- * Check the login of each running container that keeps one, and the
3407
- * credentials to use from here: the generated ones, or an older login a
3408
- * service could not be moved off.
3409
- */
3410
- async function ensureLogins(options) {
3411
- const { containers, ports, exec } = options;
3412
- let credentials = options.credentials;
3413
- const outcomes = [];
3414
- const legacy = [LEGACY_LOCAL_LOGIN];
3415
- if (containers.includes("postgres") && ports.postgres !== void 0) {
3416
- const outcome = await ensurePostgresLogin({
3417
- port: ports.postgres,
3418
- login: credentials.postgres,
3419
- legacy,
3420
- ...exec ? { exec } : {}
3421
- });
3422
- outcomes.push(outcome);
3423
- credentials = {
3424
- ...credentials,
3425
- postgres: outcome.login
3426
- };
3427
- }
3428
- if (containers.includes("minio") && ports.minio !== void 0) {
3429
- const outcome = await ensureMinioLogin({
3430
- port: ports.minio,
3431
- login: credentials.minio,
3432
- legacy
3433
- });
3434
- outcomes.push(outcome);
3435
- credentials = {
3436
- ...credentials,
3437
- minio: outcome.login
3438
- };
3439
- }
3440
- if (containers.includes("rabbitmq") && exec) outcomes.push(await ensureRabbitmqLogin({
3441
- login: credentials.rabbitmq,
3442
- legacy,
3443
- exec
3444
- }));
3445
- return {
3446
- credentials,
3447
- outcomes
3448
- };
3449
- }
3450
- //#endregion
3451
- //#region src/reconcile/ports.ts
3452
- /**
3453
- * Port allocation — why two projects can run at once.
3454
- *
3455
- * Publishing `5432:5432` means the second project on your machine cannot start.
3456
- * Nothing solves that except giving each project its own ports, and what makes
3457
- * it *possible* is the single-`<NAME>_URL` rule: an app reads `ORDERS_URL` and
3458
- * never sees a host or a port, so reconcile is free to bind whatever is
3459
- * available and compose the URL from what it bound. An app reading `DB_HOST` and
3460
- * `DB_PORT` separately could not be moved this way.
3461
- *
3462
- * Assignments are **persisted, not recomputed**. Recomputing means adding a
3463
- * construct renumbers its neighbours, and every running container, saved
3464
- * connection string, and `psql` history goes stale at once.
3465
- *
3466
- * Pure, with the liveness probe injected — a collision with another project's
3467
- * stack is a fact about the machine, and keeping it a parameter is what lets the
3468
- * rules be asserted without binding a socket.
3469
- */
3470
- /**
3471
- * The window ports are drawn from.
3472
- *
3473
- * Above the registered range so nothing here needs privileges, and below the
3474
- * ephemeral range both Linux (32768+) and macOS (49152+) allocate from — a port
3475
- * the kernel might hand to an outgoing connection is one that is free when
3476
- * checked and taken by the time it is bound.
3477
- */
3478
- const WINDOW = {
3479
- min: 2e4,
3480
- max: 32e3
3481
- };
3482
- /**
3483
- * How far apart two projects start.
3484
- *
3485
- * Wide enough that a project can add containers without walking into its
3486
- * neighbour's block, narrow enough that the window holds many projects.
3487
- */
3488
- const BLOCK = 50;
3489
- /**
3490
- * Where a project's ports start.
3491
- *
3492
- * Derived from the name rather than assigned sequentially so that a fresh clone
3493
- * of the same project on the same machine lands on the same block — the first
3494
- * run has nothing persisted to read, and hashing is what keeps that first run
3495
- * from colliding with whatever else is already allocated.
3496
- *
3497
- * @example startingPort('toolbox') // stable for a given name
3498
- */
3499
- function startingPort(project) {
3500
- const digest = createHash("sha256").update(project).digest();
3501
- const blocks = Math.floor((WINDOW.max - WINDOW.min) / BLOCK);
3502
- return WINDOW.min + digest.readUInt32BE(0) % blocks * BLOCK;
3503
- }
3504
- /**
3505
- * Assign a port to every container that has none, keeping the ones that do.
3506
- *
3507
- * Existing assignments are returned untouched even when the container is no
3508
- * longer in the plan: removing a construct must not renumber what is left, and
3509
- * keeping the entry means re-adding it later restores the same port rather than
3510
- * inventing a new one.
3511
- *
3512
- * @param probe - reports what is actually listening. A port assigned to this
3513
- * project is skipped without probing, because on a converged reconcile our own
3514
- * container is the thing listening on it.
3515
- * @throws {NoPortAvailable} when the window is exhausted.
3516
- */
3517
- async function allocate(project, containers, existing = {}, probe = isPortFree) {
3518
- const assignments = { ...existing };
3519
- const taken = new Set(Object.values(assignments));
3520
- for (const container of [...containers].sort()) {
3521
- if (assignments[container] !== void 0) continue;
3522
- const port = await nextFree(startingPort(project), taken, probe);
3523
- assignments[container] = port;
3524
- taken.add(port);
3525
- }
3526
- return assignments;
3527
- }
3528
- /**
3529
- * The ports to keep: what running containers are observed on, then what was
3530
- * saved — minus any saved entry whose port something else already holds.
3531
- *
3532
- * Spreading one over the other let an observed port override its own key and
3533
- * leave a *different* key still saved on the same number: two services on one
3534
- * port, and whichever answered first won. Saved keys for containers the plan no
3535
- * longer has — a backend switched and back — were the usual source. Observed
3536
- * wins because it is what is actually bound; a dropped entry is simply
3537
- * allocated again.
3538
- */
3539
- function keptPorts(saved = {}, observed = {}) {
3540
- const kept = { ...observed };
3541
- const taken = new Set(Object.values(observed));
3542
- for (const [key, port] of Object.entries(saved).sort(([a], [b]) => a < b ? -1 : 1)) {
3543
- if (key in kept || taken.has(port)) continue;
3544
- kept[key] = port;
3545
- taken.add(port);
3546
- }
3547
- return kept;
3548
- }
3549
- /**
3550
- * The kept ports, among those the plan publishes, that something other than
3551
- * this project now holds.
3552
- *
3553
- * A saved port is only a memory of a free one. Another checkout's stack — the
3554
- * same project name hashes to the same block — can bind it in the meantime,
3555
- * and keeping it unchecked fails `docker compose up` with "port is already
3556
- * allocated". An observed port is ours by definition and is never asked
3557
- * about; neither is a saved one the plan no longer publishes, which is only
3558
- * kept for when it returns.
3559
- */
3560
- async function heldElsewhere(kept, keys, observed, probe, ours) {
3561
- const held = [];
3562
- for (const key of [...keys].sort()) {
3563
- const port = kept[key];
3564
- if (port === void 0 || key in observed) continue;
3565
- if (await probe(port)) continue;
3566
- if (await ours(port)) continue;
3567
- held.push(key);
3568
- }
3569
- return held;
3570
- }
3571
- /** The window was exhausted. */
3572
- var NoPortAvailable = class extends GkmError {
3573
- /** Where the search started. */
3574
- from;
3575
- /** The window searched, so the caller can report what was full. */
3576
- window = WINDOW;
3577
- constructor(from) {
3578
- super("No free port is available in the local port range");
3579
- this.name = "NoPortAvailable";
3580
- this.from = from;
3581
- }
3582
- };
3583
- /**
3584
- * The first port at or after `from` that is neither ours nor in use.
3585
- *
3586
- * Wraps at the top of the window rather than stopping, so a project whose block
3587
- * sits near the end is not the one that fails.
3588
- */
3589
- async function nextFree(from, taken, probe) {
3590
- const span = WINDOW.max - WINDOW.min;
3591
- for (let offset = 0; offset < span; offset++) {
3592
- const port = WINDOW.min + (from - WINDOW.min + offset) % span;
3593
- if (taken.has(port)) continue;
3594
- if (await probe(port)) return port;
3595
- }
3596
- throw new NoPortAvailable(from);
3597
- }
3598
- /**
3599
- * Whether nothing is listening on a port.
3600
- *
3601
- * Binds rather than connects: a refused connection says nothing about whether
3602
- * the port can be *published*, which is the question Docker will ask. Binds on
3603
- * `0.0.0.0` for the same reason — a port free on loopback can still be taken on
3604
- * the address Docker publishes to — and then on `127.0.0.1`, because on macOS
3605
- * a wildcard bind succeeds beside a listener on loopback alone.
3606
- *
3607
- * Inherently racy, and that is acceptable: Docker failing to bind stays the real
3608
- * check. This exists so the common case surfaces as a message at reconcile
3609
- * rather than as a connection failure ten minutes later.
3610
- */
3611
- async function isPortFree(port) {
3612
- return await canBind(port, "0.0.0.0") && await canBind(port, "127.0.0.1");
3613
- }
3614
- function canBind(port, host) {
3615
- return new Promise((resolve) => {
3616
- const server = createServer();
3617
- server.once("error", () => resolve(false));
3618
- server.once("listening", () => server.close(() => resolve(true)));
3619
- server.listen(port, host);
3620
- });
3621
- }
3622
- //#endregion
3623
- //#region src/reconcile/state.ts
3624
- /**
3625
- * What reconcile records, and the hash that lets it do nothing.
3626
- *
3627
- * Reconciling on every `gkm dev` is only acceptable if the converged case is
3628
- * free, so the desired plan is hashed: matching hash plus healthy containers
3629
- * means there is nothing to do. Without that, the automatic reconcile the design
3630
- * asks for would tax every start.
3631
- *
3632
- * Almost nothing needs recording — roles are queried, migrations have their own
3633
- * table, containers are remembered by Docker. Only ports and this hash have no
3634
- * other owner.
3635
- */
3636
- const STATE_DIR = ".gkm/reconcile";
3637
- /**
3638
- * The hash of everything a reconcile would act on.
3639
- *
3640
- * Covers the compose document rather than the plan alone, because the plan is
3641
- * unchanged when only an image pin moves — and a changed image is exactly a
3642
- * container that must be recreated. `stringify` is stable here because
3643
- * `composeFor` sorts its containers, which is what makes the hash meaningful.
3644
- *
3645
- * Deliberately a plain function over serialisable input: the deployed target
3646
- * keys its provisioner invocation on the same idea, and the two must not be able
3647
- * to disagree about what counts as a change.
3648
- */
3649
- function planHash(plan, compose, generated = {}) {
3650
- return createHash("sha256").update(JSON.stringify({
3651
- stage: plan.stage,
3652
- plan,
3653
- compose,
3654
- generated
3655
- })).digest("hex");
3656
- }
3657
- /** Read the recorded state, or nothing if this stage has never reconciled. */
3658
- async function loadState(root, stage) {
3659
- try {
3660
- const raw = await readFile(statePath(root, stage), "utf-8");
3661
- const state = JSON.parse(raw);
3662
- return state.stage === stage ? state : void 0;
3663
- } catch {
3664
- return;
3665
- }
3666
- }
3667
- /** Record what was applied, so the next run can skip it. */
3668
- async function saveState(root, state) {
3669
- const path = statePath(root, state.stage);
3670
- await mkdir(dirname(path), { recursive: true });
3671
- await writeFile(path, `${JSON.stringify(state, null, 2)}\n`);
3672
- }
3673
- /**
3674
- * Forget what was applied, so the next reconcile of this stage converges from
3675
- * nothing — creating again whatever was dropped underneath the record.
3676
- */
3677
- async function forgetState(root, stage) {
3678
- await rm(statePath(root, stage), { force: true });
3679
- }
3680
- function statePath(root, stage) {
3681
- return join(root, STATE_DIR, `${stage}.json`);
3682
- }
3683
- //#endregion
3684
- //#region src/reconcile/index.ts
3685
- /**
3686
- * Reconcile — the one convergent function `gkm dev`, `gkm test`, and `gkm setup`
3687
- * all call.
3688
- *
3689
- * Three phases, and only this one has side effects: declaring is pure (`gkm
3690
- * build` and the dev watcher), running reads `<NAME>_URL` and provisions
3691
- * nothing. Reconcile computes the desired state, compares, and applies the
3692
- * difference — which is what makes "when does it run" answerable with
3693
- * *whenever, repeatedly*.
3694
- *
3695
- * It is safe to run automatically because its blast radius is entirely local:
3696
- * this project's containers, this project's `.gkm/`. Nothing it does can reach a
3697
- * cloud. The line is drawn at data, not at side effects — it allocates ports,
3698
- * writes compose, starts containers, and creates roles; it never seeds, resets,
3699
- * or drops.
3700
- *
3701
- * Docker is injected rather than imported so the rules above can be asserted
3702
- * without a daemon. The default implementation is the real one.
3703
- */
3704
- /**
3705
- * Where the generated compose file is written, relative to the project root.
3706
- *
3707
- * At the root, beside the project's own `docker-compose.yml`, because the two
3708
- * are one stack: this file is everything the constructs imply and is never
3709
- * edited, that one is anything they cannot express — an image pin, an extra
3710
- * service — and is merged over it, so it wins.
3711
- */
3712
- const COMPOSE_PATH = "docker-compose.constructs.yml";
3713
- /**
3714
- * The local edge's config, beside the compose file that mounts it.
3715
- *
3716
- * Relative in the compose volume, so it resolves against `.gkm/` wherever the
3717
- * project lives.
3718
- */
3719
- const CADDYFILE_PATH = ".gkm/Caddyfile";
3720
- /**
3721
- * The containers that mount this checkout's files: Caddy reads its routes out
3722
- * of `.gkm/`, so one started from a worktree serves that worktree's ports.
3723
- */
3724
- const CHECKOUT_MOUNTS = ["caddy"];
3725
- /**
3726
- * Where one stage's routes live, imported by the file above.
3727
- *
3728
- * Per stage because one edge serves every stage, the same way one Postgres
3729
- * holds `orders` and `orders_test`. A single file would mean `gkm test`
3730
- * deleting the routes `gkm dev` is serving.
3731
- */
3732
- const caddySitesPath = (stage) => `.gkm/caddy-sites/${stage}.caddy`;
3733
- /**
3734
- * Where one stage's certificate is kept: certificate and key in one PEM,
3735
- * issued from gkm's local authority (`@geekmidas/edge/certificates/local`), beside the
3736
- * stage's routes — so the edge reads it through the mount it already has, and
3737
- * a stage removed takes its certificate with it.
3738
- */
3739
- const caddyCertificatePath = (stage) => `.gkm/caddy-sites/${stage}.pem`;
3740
- /**
3741
- * Converge the local target on what the manifest declares.
3742
- *
3743
- * Cheap when there is nothing to do: the hash is compared before the compose
3744
- * file is written or a container is touched, and a converged project pays one
3745
- * hash and one health check.
3746
- */
3747
- async function reconcile(options) {
3748
- const { root, project, manifest, stage, start = true, provision = true, docker = dockerCli, probe = isPortFree, sql = pgClient, buckets = bucketClient, carriers = carrierClient, logins = ensureLogins } = options;
3749
- const { seed } = options.credentials;
3750
- const plan = planFor(manifest, stage, provisionOrder(manifest), {
3751
- localStage: options.localStage,
3752
- events: options.events,
3753
- cache: options.cache,
3754
- extraContainers: options.extraContainers,
3755
- ...options.fakes ? { fakes: options.fakes } : {},
3756
- ...options.credentialFakes ? { credentialFakes: options.credentialFakes } : {},
3757
- ...options.edge === void 0 ? {} : { edge: options.edge },
3758
- ...options.protectedSubdomains ? { protectedSubdomains: options.protectedSubdomains } : {}
3759
- });
3760
- const exports = stage !== TEST_STAGE;
3761
- const running = exports ? plan.containers : plan.containers.filter((c) => c !== TELEMETRY_CONTAINER);
3762
- const composePath = join(root, COMPOSE_PATH);
3763
- const observed = await observedPorts(docker, composePath, plan.containers, plan.fakes);
3764
- const keys = portKeys(plan.containers, plan.fakes);
3765
- const kept = keptPorts(options.saved, observed);
3766
- const composeProject = process.env.COMPOSE_PROJECT_NAME || project;
3767
- const held = await heldElsewhere(kept, keys, observed, probe, async (port) => await docker.publisher?.(port) === composeProject);
3768
- const ports = await allocate(project, keys, Object.fromEntries(Object.entries(kept).filter(([key]) => !held.includes(key))), probe);
3769
- const moved = held.map((key) => ({
3770
- key,
3771
- from: kept[key],
3772
- to: ports[key]
3773
- }));
3774
- const compose = composeFor(plan, {
3775
- project,
3776
- ports,
3777
- credentials: options.credentials,
3778
- ...options.apps ? { apps: options.apps(plan.containers) } : {},
3779
- ...options.objectWebhooks?.length ? { objectWebhooks: options.objectWebhooks } : {},
3780
- ...options.inboxRelay ? { inboxRelay: options.inboxRelay } : {}
3781
- });
3782
- const sites = sitesFor(plan, project, options.addresses, options.processorAddresses);
3783
- const edged = plan.containers.includes("caddy");
3784
- const authorityPaths = options.authority ?? localAuthorityPaths(gkmHome());
3785
- const edgePort = ports[primaryPortKey("caddy")];
3786
- const caddyfile = toCaddyfile(sites, {
3787
- certificate: `${CADDY_SITES_IN_CONTAINER}/${stage}.pem`,
3788
- edgeToken: edgeToken(project, seed),
3789
- ...edgePort !== void 0 ? { port: edgePort } : {}
3790
- });
3791
- const hash = planHash(plan, compose, {
3792
- caddyfile,
3793
- postgres: postgresStatements(plan, project, seed).map((statement) => statement.create).join(";\n")
3794
- });
3795
- const services = serviceAddresses(running, ports, plan.fakes);
3796
- const lan = plan.resources.some((r) => r.kind === "mobile-app") ? options.lanAddress === void 0 ? lanAddress() : options.lanAddress ?? void 0 : void 0;
3797
- const envWith = (credentials) => {
3798
- const resolved = envFor(plan, {
3799
- ports,
3800
- project,
3801
- credentials,
3802
- seed,
3803
- ...options.mailDomain ? { mailDomain: options.mailDomain } : {},
3804
- ...options.addresses ? { addresses: options.addresses } : {},
3805
- ...lan ? { lanAddress: lan } : {},
3806
- ...options.metroPorts ? { metroPorts: options.metroPorts } : {},
3807
- ...options.objectWebhooks?.length ? { relayedBuckets: options.objectWebhooks.map((hook) => hook.bucket) } : {}
3808
- });
3809
- const env = exports ? resolved : scopeTelemetryEnv(resolved, {
3810
- uses: false,
3811
- serviceName: project
3812
- });
3813
- if (edged) env[LOCAL_CA_KEY] = authorityPaths.certFile;
3814
- return env;
3815
- };
3816
- const result = {
3817
- stage,
3818
- plan,
3819
- compose,
3820
- ports,
3821
- moved,
3822
- services,
3823
- env: envWith(options.credentials),
3824
- credentials: options.credentials,
3825
- logins: [],
3826
- provisioned: [],
3827
- fakes: options.fakes ?? {},
3828
- hash,
3829
- changed: false
3830
- };
3831
- const certificate = edged ? await ensureLocalCertificate(await ensureLocalAuthority(authorityPaths), localCertificateNames(project, sites.flatMap((site) => [
3832
- site.host,
3833
- ...site.aliases ?? [],
3834
- ...site.redirects ?? []
3835
- ])), join(root, caddyCertificatePath(stage))) : void 0;
3836
- const recorded = await loadState(root, stage);
3837
- const postgresPort = ports[primaryPortKey("postgres")];
3838
- if (!certificate?.issued && recorded?.hash === hash && existsSync(composePath) && (!start || await docker.healthy(composePath, running, { mounted: CHECKOUT_MOUNTS })) && (!start || !provision || postgresPort === void 0 || await databasesExist(sql(postgresPort, options.credentials.postgres), postgresDatabaseNames(plan)))) return result;
3839
- await write(composePath, toYaml(compose), 384);
3840
- if (edged) {
3841
- await write(join(root, CADDYFILE_PATH), caddyfileRoot());
3842
- await write(join(root, caddySitesPath(stage)), caddyfile);
3843
- await pruneCaddySites(root, [
3844
- stage,
3845
- options.localStage,
3846
- TEST_STAGE
3847
- ]);
3848
- }
3849
- if (start && running.length > 0) {
3850
- options.progress?.(`🐳 Starting ${running.join(", ")} — the first start pulls each image, which can take a few minutes`);
3851
- await docker.up(composePath, running, options.progress ? { show: true } : {});
3852
- }
3853
- if (start && edged) await docker.reload(composePath, "caddy").catch(() => {});
3854
- const checked = start && plan.containers.length > 0 ? await logins({
3855
- credentials: options.credentials,
3856
- containers: plan.containers,
3857
- ports: {
3858
- ...postgresPort !== void 0 ? { postgres: postgresPort } : {},
3859
- ...ports[primaryPortKey("minio")] !== void 0 ? { minio: ports[primaryPortKey("minio")] } : {}
3860
- },
3861
- ...docker.exec ? { exec: (service, argv) => docker.exec(composePath, service, argv) } : {}
3862
- }) : {
3863
- credentials: options.credentials,
3864
- outcomes: []
3865
- };
3866
- const credentials = checked.credentials;
3867
- if (start && provision) options.progress?.("🗄️ Creating what the constructs declare — databases, roles, buckets, topics");
3868
- const provisioned = start && provision ? await create(plan, ports, credentials, sql, buckets, carriers, project, new Set(stage === (options.localStage ?? stage) ? (options.objectWebhooks ?? []).map((hook) => hook.bucket) : [])) : [];
3869
- await saveState(root, {
3870
- hash,
3871
- stage
3872
- });
3873
- return {
3874
- ...result,
3875
- ...credentials === options.credentials ? {} : { env: envWith(credentials) },
3876
- credentials,
3877
- logins: checked.outcomes,
3878
- provisioned,
3879
- changed: true
3880
- };
3881
- }
3882
- /**
3883
- * Create the databases, schemas, buckets, topics and queues the plan names.
3884
- *
3885
- * Idempotent throughout, so this runs on every non-converged reconcile rather
3886
- * than being something to remember.
3887
- */
3888
- async function create(plan, ports, credentials, sql, buckets, emulatorCarriers, project, watched) {
3889
- const applied = [];
3890
- const postgresPort = ports[primaryPortKey("postgres")];
3891
- const statements = postgresStatements(plan, project, credentials.seed);
3892
- if (postgresPort !== void 0 && statements.length > 0) applied.push(...await applyPostgres(sql(postgresPort, credentials.postgres), statements));
3893
- const minioPort = ports[primaryPortKey("minio")];
3894
- const names = bucketNames(plan);
3895
- const policies = bucketPolicies(plan);
3896
- const lifecycles = bucketLifecycles(plan);
3897
- if (minioPort !== void 0 && (names.length > 0 || policies.length > 0)) {
3898
- const client = buckets(minioPort, credentials.minio);
3899
- if (names.length > 0) applied.push(...await applyBuckets(client, names));
3900
- if (policies.length > 0) applied.push(...await applyPolicies(client, policies));
3901
- if (lifecycles.length > 0) applied.push(...await applyLifecycles(client, lifecycles));
3902
- if (names.length > 0) applied.push(...await applyNotifications(client, plan.resources.filter((r) => r.provisions && r.kind === "objects").map((r) => ({
3903
- id: r.id,
3904
- name: r.name
3905
- })), watched));
3906
- }
3907
- const emulatorPort = ports[primaryPortKey("localstack")];
3908
- const carriers = carrierNames(plan);
3909
- if (emulatorPort !== void 0 && carriers.topics.length + carriers.queues.length > 0) applied.push(...await applyCarriers(emulatorCarriers(emulatorPort, credentials.emulator), carriers));
3910
- return applied;
3911
- }
3912
- /**
3913
- * The host ports of containers already running.
3914
- *
3915
- * Keyed the same way allocation keys them, so the two merge without either
3916
- * knowing about the other.
3917
- */
3918
- async function observedPorts(docker, composePath, containers, fakes) {
3919
- const observed = {};
3920
- for (const container of containers) for (const port of portsOf(container, fakes)) {
3921
- const running = await docker.publishedPort(composePath, container, port.inside);
3922
- if (running !== void 0) observed[port.key] = running;
3923
- }
3924
- return observed;
3925
- }
3926
- /** Write a file only when its content would change, so mtimes stay meaningful. */
3927
- /**
3928
- * Remove the routes of stages this project no longer reconciles.
3929
- *
3930
- * Only the local stage and `test` are ever written, so any other file is left
3931
- * over from a stage that was renamed — `development` becoming `dev`. Caddy
3932
- * imports every file, and the leftover declares the same hosts as its
3933
- * replacement: it refuses the whole config as ambiguous, and every URL behind
3934
- * the edge goes with it.
3935
- */
3936
- async function pruneCaddySites(root, stages) {
3937
- const dir = dirname(join(root, caddySitesPath(TEST_STAGE)));
3938
- const keep = new Set(stages.flatMap((stage) => stage ? [`${stage}.caddy`, `${stage}.pem`] : []));
3939
- for (const file of await readdir(dir)) if (/\.(caddy|pem)$/.test(file) && !keep.has(file)) await rm(join(dir, file));
3940
- }
3941
- async function write(path, content, mode) {
3942
- try {
3943
- if (await readFile(path, "utf-8") === content) {
3944
- if (mode !== void 0) await chmod(path, mode);
3945
- return;
3946
- }
3947
- } catch {}
3948
- await mkdir(dirname(path), { recursive: true });
3949
- await writeFile(path, content, mode === void 0 ? {} : { mode });
3950
- if (mode !== void 0) await chmod(path, mode);
3951
- }
3952
- //#endregion
3953
- //#region src/reconcile/workspace.ts
3954
- /**
3955
- * Workspace config → reconcile.
3956
- *
3957
- * Nothing here is read from a `services:` block — there is none. Which
3958
- * containers exist comes from the manifest; which backend a cache or a broker
3959
- * resolves to comes from the deploy target; and an image pin is the project's
3960
- * own `docker-compose.yml`, merged over the generated file.
3961
- *
3962
- * Shared by `gkm setup`, `gkm dev`, and `gkm test` so all three converge on the
3963
- * same state, differing only in the stage they pass.
3964
- */
3965
- var workspace_exports = /* @__PURE__ */ __exportAll({
3966
- FAKE_ENV: () => FAKE_ENV,
3967
- backendsOf: () => backendsOf,
3968
- constructGlobs: () => constructGlobs,
3969
- derivedContainers: () => derivedContainers,
3970
- fakesApply: () => fakesApply,
3971
- localInboxWebhook: () => localInboxWebhook,
3972
- localObjectWebhooks: () => localObjectWebhooks,
3973
- metroPorts: () => metroPorts,
3974
- processorAddresses: () => processorAddresses,
3975
- reconcileWorkspace: () => reconcileWorkspace,
3976
- surfaceAddresses: () => surfaceAddresses
3977
- });
3978
- /**
3979
- * Every constructs glob in the workspace, resolved against its app.
3980
- *
3981
- * Absolute because discovery globs from a single cwd while apps live in
3982
- * different directories.
3983
- */
3984
- function constructGlobs(workspace) {
3985
- return allConstructGlobs(workspace);
3986
- }
3987
- /** The backends a workspace's target implies, as the plan takes them. */
3988
- function backendsOf(workspace) {
3989
- const on = providerOf(workspace);
3990
- return {
3991
- events: eventsBackendFor(on),
3992
- cache: cacheBackendFor(on)
3993
- };
3994
- }
3995
- /**
3996
- * The containers a workspace's declarations imply, without reconciling.
3997
- *
3998
- * The same derivation `reconcileWorkspace` makes, available to callers that
3999
- * need to know *what would run* without starting anything or writing ports —
4000
- * `gkm setup` deciding which credentials to generate, `gkm docker` writing a
4001
- * compose file. Those used to each read a boolean per service out of config,
4002
- * which is how a container could exist because config asked for one rather than
4003
- * because something declared it.
4004
- */
4005
- async function derivedContainers(workspace, stage, manifest) {
4006
- const found = manifest ?? await discover({
4007
- patterns: constructGlobs(workspace),
4008
- cwd: workspace.root
4009
- });
4010
- return planFor(found, stage, provisionOrder(found), {
4011
- localStage: workspace.stages.local,
4012
- ...backendsOf(workspace)
4013
- }).containers;
4014
- }
4015
- /**
4016
- * Set by `gkm dev --fake` for the apps it starts. Each app's own `gkm dev`
4017
- * reconciles too, and must answer the way the workspace did.
4018
- */
4019
- const FAKE_ENV = "GKM_FAKE";
4020
- /**
4021
- * Whether third parties are faked — external APIs, and credentials with a
4022
- * fake: always for `gkm test`, and for `gkm dev`
4023
- * only when asked — by `--fake`, or by the workspace that started this app
4024
- * with it. Never for anything acting on a deployed stage.
4025
- */
4026
- function fakesApply(stage, fake, env = process.env) {
4027
- return fake === true || stage === "test" || env["GKM_FAKE"] === "1";
4028
- }
4029
- /**
4030
- * Reconcile a workspace for one stage.
4031
- *
4032
- * Ports are loaded and saved around the call rather than inside it, so the loop
4033
- * stays a pure-ish function of its inputs and the store keeps its single owner.
4034
- */
4035
- async function reconcileWorkspace(workspace, options) {
4036
- const background = {};
4037
- const subscribers = {};
4038
- const discovered = await discover({
4039
- patterns: constructGlobs(workspace),
4040
- cwd: workspace.root,
4041
- background,
4042
- subscribers
4043
- });
4044
- const manifest = options.manifest ?? discovered;
4045
- const faked = fakesApply(options.stage, options.fake);
4046
- const fakes = faked ? await readFakes(workspace.root, manifest) : {};
4047
- const credentialFakes = faked ? await readCredentialFakes(workspace.root, manifest) : {};
4048
- const { credentials } = await loadLocalCredentials(workspace);
4049
- const objectWebhooks = localObjectWebhooks(workspace, manifest, {
4050
- background,
4051
- subscribers,
4052
- seed: credentials.seed
4053
- });
4054
- const inboxRelay = localInboxWebhook(workspace, manifest, {
4055
- background,
4056
- subscribers,
4057
- seed: credentials.seed
4058
- });
4059
- const result = await reconcile({
4060
- credentials,
4061
- root: workspace.root,
4062
- project: workspace.name,
4063
- manifest,
4064
- stage: options.stage,
4065
- localStage: workspace.stages.local,
4066
- ...backendsOf(workspace),
4067
- ...workspace.protectedSubdomains ? { protectedSubdomains: workspace.protectedSubdomains } : {},
4068
- saved: await loadPortState(workspace.root),
4069
- addresses: surfaceAddresses(workspace, manifest),
4070
- processorAddresses: processorAddresses(workspace, manifest),
4071
- metroPorts: metroPorts(workspace, manifest),
4072
- fakes,
4073
- credentialFakes,
4074
- ...objectWebhooks.length > 0 ? { objectWebhooks } : {},
4075
- ...inboxRelay ? { inboxRelay } : {},
4076
- apps: (containers) => appServices(workspace, manifest, containers, credentials, fakes, credentialFakes),
4077
- ...options.start === void 0 ? {} : { start: options.start },
4078
- ...options.progress ? { progress: options.progress } : {}
4079
- });
4080
- await savePortState(workspace.root, { ...result.ports });
4081
- for (const { key, from, to } of result.moved) console.log(`⚠️ Port ${from} (${key}) is held by another process; moved to ${to}.`);
4082
- if (result.credentials !== credentials) await saveLocalCredentials(workspace, result.credentials);
4083
- for (const outcome of result.logins) if (outcome.notice) console.log(outcome.notice);
4084
- return {
4085
- ...result,
4086
- manifest,
4087
- background
4088
- };
4089
- }
4090
- /**
4091
- * Where MinIO posts each watched bucket's events under `gkm dev`: the dev
4092
- * server of the app that builds the worker running the bucket's subscribers,
4093
- * on the host, on that app's port — the process that relays them onto the
4094
- * broker.
4095
- *
4096
- * None where the broker is SNS: there a bucket's events come from a topic, and
4097
- * nothing relays them. None for a worker no app can build — `gkm build` says
4098
- * so; a dev loop has nothing to post to.
4099
- */
4100
- function localObjectWebhooks(workspace, manifest, options) {
4101
- if (backendsOf(workspace).events === "sns") return [];
4102
- const watched = watchedBuckets(manifest, options.subscribers);
4103
- if (watched.size === 0) return [];
4104
- let units;
4105
- try {
4106
- units = workerUnits(workspace, manifest, options.background);
4107
- } catch (error) {
4108
- if (error instanceof WorkerHasNoApp) return [];
4109
- throw error;
4110
- }
4111
- const hooks = [];
4112
- for (const [bucket, worker] of watched) {
4113
- const app = units.find((unit) => unit.id === worker)?.app;
4114
- const port = app ? workspace.apps[app]?.port : void 0;
4115
- if (!port) continue;
4116
- hooks.push({
4117
- bucket,
4118
- endpoint: `http://${HOST_GATEWAY}:${port}${objectsRoute(bucket)}`,
4119
- token: objectsWebhookToken(workspace.name, bucket, options.seed)
4120
- });
4121
- }
4122
- return hooks;
4123
- }
4124
- /**
4125
- * Where Mailpit posts each message it receives, locally: the relay route on
4126
- * the dev server of the app that builds the worker running the inbox
4127
- * subscribers, through the host's gateway — as MinIO reaches a bucket's
4128
- * subscribers. `undefined` with no inbox subscriber, or none an app builds.
4129
- */
4130
- function localInboxWebhook(workspace, manifest, options) {
4131
- const worker = inboxRelayWorker(manifest, options.subscribers);
4132
- if (!worker) return void 0;
4133
- let units;
4134
- try {
4135
- units = workerUnits(workspace, manifest, options.background);
4136
- } catch (error) {
4137
- if (error instanceof WorkerHasNoApp) return void 0;
4138
- throw error;
4139
- }
4140
- const app = units.find((unit) => unit.id === worker)?.app;
4141
- const port = app ? workspace.apps[app]?.port : void 0;
4142
- if (!port) return void 0;
4143
- return inboxWebhookUrl(`http://${HOST_GATEWAY}:${port}`, inboxRelayToken(workspace.name, options.seed));
4144
- }
4145
- /**
4146
- * Where each mobile app's Metro runs: its app's port, which `gkm exec` hands
4147
- * Expo as `RCT_METRO_PORT`. Kept apart from the surfaces' addresses — a phone
4148
- * reaches Metro by `exp://`, not through the edge.
4149
- */
4150
- function metroPorts(workspace, manifest) {
4151
- const ports = {};
4152
- for (const [id, declaration] of Object.entries(manifest)) {
4153
- if (declaration.kind !== "mobile-app") continue;
4154
- const port = workspace.apps[appKey(id)]?.port;
4155
- if (port) ports[id] = port;
4156
- }
4157
- return ports;
4158
- }
4159
- /**
4160
- * Where each file server's processors answer locally: the dev server of the
4161
- * app holding them, which `gkm dev` mounts them on — the same app whose build
4162
- * writes their unit deployed.
4163
- */
4164
- function processorAddresses(workspace, manifest) {
4165
- const addresses = {};
4166
- for (const unit of processorUnits(workspace, manifest)) {
4167
- const port = workspace.apps[unit.app]?.port;
4168
- if (port) addresses[unit.id] = localAddress(port);
4169
- }
4170
- return addresses;
4171
- }
4172
- /**
4173
- * Where each declared surface and site answers locally.
4174
- *
4175
- * The addresses come from the ports the workspace already assigns; which
4176
- * construct sits at which one comes from the manifest. That split is the point:
4177
- * this used to answer "who may call whom" by listing every app the workspace
4178
- * runs, which is a different question that happened to give the same answer in
4179
- * a single-repo workspace and no answer at all deployed. Now it answers only
4180
- * "where does this construct answer", and the graph answers the rest.
4181
- *
4182
- * A site is matched to its app by `path`, because that is the one thing a site
4183
- * declaration and a workspace app both name. Surfaces are matched to the
4184
- * backend app: every `rest-api` in a process answers on that process's port, so
4185
- * an app serving both its own API and an auth server publishes one address
4186
- * twice — which is exactly what it does at runtime.
4187
- */
4188
- function surfaceAddresses(workspace, manifest, at = (_app, port) => localAddress(port)) {
4189
- const addresses = {};
4190
- for (const [id, declaration] of Object.entries(manifest)) {
4191
- if (declaration.kind !== "rest-api" && declaration.kind !== "websocket-api" && declaration.kind !== "site") continue;
4192
- const host = appKey(id);
4193
- const port = workspace.apps[host]?.port;
4194
- if (port) addresses[id] = at(host, port);
4195
- }
4196
- return addresses;
4197
- }
4198
- /** Where a local process answers, given the port the workspace gave it. */
4199
- function localAddress(port) {
4200
- return `http://localhost:${port}`;
4201
- }
4202
- //#endregion
4203
- //#region src/reconcile/apps.ts
4204
- /**
4205
- * The apps, as services beside the containers their constructs derive.
4206
- *
4207
- * `gkm docker` used to write these by hand: every backend got
4208
- * `DATABASE_URL=postgresql://…@postgres:5432/app` and `REDIS_URL=redis://redis`,
4209
- * which was right only for a project whose single database happened to be
4210
- * called `Database` — an `Orders` database publishes `ORDERS_URL`, a schema
4211
- * tenant has a URL of its own, and buckets and mail were not wired at all.
4212
- *
4213
- * Now an app's environment is exactly what reconcile hands `gkm dev`: every key
4214
- * the declared constructs provide, from the same derivation. The only
4215
- * difference is where the addresses point — at the containers by service name
4216
- * on the compose network, rather than at `localhost` on the ports published for
4217
- * the host.
4218
- *
4219
- * Always from the *local* stage's plan, whichever stage is being reconciled:
4220
- * `gkm test` rewrites the same file, and running the tests must not quietly
4221
- * point these apps at the test databases.
4222
- */
4223
- var apps_exports = /* @__PURE__ */ __exportAll({
4224
- APPS_PROFILE: () => APPS_PROFILE,
4225
- appEnvKeys: () => appEnvKeys,
4226
- appProcess: () => appProcess,
4227
- appServices: () => appServices,
4228
- callerKeys: () => callerKeys,
4229
- constructKeys: () => constructKeys,
4230
- dockerfileOf: () => dockerfileOf,
4231
- healthcheck: () => healthcheck,
4232
- networkEnv: () => networkEnv,
4233
- processEnv: () => processEnv,
4234
- processEnvKeys: () => processEnvKeys,
4235
- processorEnvKeys: () => processorEnvKeys,
4236
- sitePublicArgs: () => sitePublicArgs,
4237
- workerEnvKeys: () => workerEnvKeys
4238
- });
4239
- /** The profile app services carry, so `gkm dev` starts only the containers. */
4240
- const APPS_PROFILE = "apps";
4241
- /**
4242
- * Where an app's image is built from.
4243
- *
4244
- * An app at the project root is a single-app project, whose `gkm docker`
4245
- * writes `.gkm/docker/Dockerfile`; a workspace writes one per app.
4246
- */
4247
- function dockerfileOf(appName, path) {
4248
- return path === "." ? ".gkm/docker/Dockerfile" : `.gkm/docker/Dockerfile.${appName}`;
4249
- }
4250
- /**
4251
- * The local stage's plan, which the app services are always written from.
4252
- *
4253
- * Without the edge: these apps reach each other by service name and a browser
4254
- * reaches them on the ports this file publishes. Behind the edge every
4255
- * surface resolved to its `*.localhost` host on the edge's port, which the
4256
- * rewrite to the compose network then turned into an address nothing answers.
4257
- */
4258
- function localPlan(workspace, manifest, fakes = {}, credentialFakes = {}) {
4259
- return planFor(manifest, workspace.stages.local, provisionOrder(manifest), {
4260
- localStage: workspace.stages.local,
4261
- ...backendsOf(workspace),
4262
- ...workspace.protectedSubdomains ? { protectedSubdomains: workspace.protectedSubdomains } : {},
4263
- fakes,
4264
- credentialFakes,
4265
- edge: false
4266
- });
4267
- }
4268
- /**
4269
- * The values a site's bundler inlines, by the name it inlines them under —
4270
- * `{ VITE_API_URL: 'http://localhost:3000' }`.
4271
- *
4272
- * Build arguments, not environment: a static bundle is finished when it is
4273
- * built, so a value handed to its container at runtime reaches nothing. And
4274
- * addresses a *browser* can open, since that is where the bundle runs — the
4275
- * host's port for each app, never a name on the compose network.
4276
- */
4277
- function sitePublicArgs(manifest, appName, env) {
4278
- const declaration = Object.entries(manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1];
4279
- if (declaration?.kind !== "site") return {};
4280
- return publicBuildValues(declaration, manifest, (key) => env[key], {});
4281
- }
4282
- /**
4283
- * Every key a plan resolves, with each container addressed by its service
4284
- * name on the compose network — `postgres:5432` rather than the port
4285
- * published for the host.
4286
- *
4287
- * The addresses of surfaces and sites are the caller's: `gkm compose` hands
4288
- * every process the public ones, which one app calls another on through the
4289
- * edge; `gkm docker`'s apps profile, which runs no edge, the compose
4290
- * network's.
4291
- */
4292
- function networkEnv(plan, options, hostOf = (container) => container) {
4293
- const placeholders = {};
4294
- const targets = /* @__PURE__ */ new Map();
4295
- let next = 49152;
4296
- for (const container of [...plan.containers].sort()) for (const port of portsOf(container, plan.fakes)) {
4297
- placeholders[port.key] = next;
4298
- targets.set(next, `${hostOf(container)}:${port.inside}`);
4299
- next += 1;
4300
- }
4301
- for (const key of portKeys(plan.containers, plan.fakes)) placeholders[key] ??= next++;
4302
- const env = envFor(plan, {
4303
- ...options,
4304
- ports: placeholders
4305
- });
4306
- const rewrite = (value) => value.replace(/(?:localhost|127\.0\.0\.1):(\d+)/g, (match, port) => {
4307
- return targets.get(Number(port)) ?? match;
4308
- });
4309
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, rewrite(value)]));
4310
- }
4311
- /**
4312
- * The keys one app's environment may hold: what its own declaration provides
4313
- * and requires, what each construct it has an edge to provides, and — for a
4314
- * surface — the identity of each client with an edge to it.
4315
- *
4316
- * The one rule for every command and stage: `gkm dev`, `gkm exec` and `gkm
4317
- * test` hand an app these keys (through `processEnvKeys`), `gkm compose`
4318
- * writes them to its env file, and `gkm docker`'s apps profile to its
4319
- * service. A key missing here is missing everywhere, so an app that reads it
4320
- * fails on its first local request rather than in production.
4321
- *
4322
- * What an edge `caller.dependsOn([target])` hands each side, `<C>` and `<T>`
4323
- * being the caller's and the target's ids (`providedKeyFor`) — keep this list and
4324
- * `apps/docs/guide/edges.md` in step with the code below:
4325
- *
4326
- * - `rest-api`: the caller gets `<T>_URL`. The target gets `<C>_URL` from a
4327
- * site caller and `<C>_SCHEME` from a mobile app caller (`callerKeys`).
4328
- * - `websocket-api`: the caller gets `<T>_URL`, and a server process also
4329
- * `<T>_PUBLISHER_CONNECTION_STRING`. The target gets what a `rest-api`
4330
- * does.
4331
- * - `queue`, `topic`: the caller gets the target's `provides` and
4332
- * `EVENT_PUBLISHER_CONNECTION_STRING`. The target gets nothing.
4333
- * - `objects`: the target's `provides`, its file server's, and the S3 key
4334
- * pair (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`). A site
4335
- * or mobile app gets `<T>_SIGNED_ORIGIN` and nothing else on its plain
4336
- * edge, and all of it, signed origin included, on `.server`
4337
- * (`reachesServerHalf`).
4338
- * - `inbox`: the target's `provides`, and the local relay token.
4339
- * - anything else (a database, cache, secret, credential, external API…):
4340
- * the target's `provides`. The target gets nothing.
4341
- *
4342
- * Beside the keys, a surface's `<T>_TRUSTED_ORIGINS` lists every caller's
4343
- * origin (a mobile app's as its scheme) and `<T>_COOKIE_DOMAIN` the parent
4344
- * they share — values of the surface's own keys, derived from the same
4345
- * inbound edges (`surfaceEnv`).
4346
- *
4347
- * A site or mobile app is a bundle: it also gets the public-prefixed name of
4348
- * each of those its bundler inlines (`publicEnvFor`: `VITE_API_URL`,
4349
- * `EXPO_PUBLIC_API_URL`), and never a `Telemetry` node's keys.
4350
- *
4351
- * The edges, not the manifest. Every app used to be handed every key the
4352
- * workspace resolved — a web app got the database's owner URL and the auth
4353
- * server's signing secret, and the API got the auth server's database — which
4354
- * is exactly what a declared edge exists to rule out. A deploy composes an
4355
- * app's environment from its edges; so does this.
4356
- *
4357
- * One hop: a surface an app calls is reached over HTTP, so its URL is the
4358
- * app's business and its database is not.
4359
- *
4360
- * A surface's process runs its own endpoints and nothing else. A Worker's
4361
- * crons, queue consumers and subscribers run in the worker's own process
4362
- * (`workerEnvKeys`), so no surface is handed a worker's edges — however its
4363
- * endpoints were found.
4364
- *
4365
- * `undefined` for an app no declaration describes, which gets nothing but its
4366
- * port.
4367
- */
4368
- function appEnvKeys(manifest, appName) {
4369
- const entry = Object.entries(manifest).find(([id, d]) => (d.kind === "rest-api" || d.kind === "websocket-api" || d.kind === "site" || d.kind === "mobile-app") && appKey(id) === appName);
4370
- if (!entry) return void 0;
4371
- const [id, declaration] = entry;
4372
- const keys = /* @__PURE__ */ new Set([
4373
- ...declaration.provides ?? [],
4374
- ...declaration.requires ?? [],
4375
- ...declaration.kind === "rest-api" ? declaration.endpoints.flatMap((endpoint) => endpoint.requires ?? []) : []
4376
- ]);
4377
- const client = isPublicDeclaration(declaration);
4378
- addEdgeKeys(manifest, dependenciesOf(declaration).filter((edge) => manifest[edge.target]?.kind !== "objects" || reachesServerHalf(declaration, edge)).map((edge) => edge.target), keys, client);
4379
- if (declaration.kind === "rest-api" || declaration.kind === "websocket-api") for (const key of callerKeys(manifest, id)) keys.add(key);
4380
- if (client) {
4381
- for (const key of TELEMETRY_KEYS) keys.delete(key);
4382
- for (const key of Object.keys(publicEnvFor(declaration, manifest))) keys.add(key);
4383
- for (const { key } of publicValues(declaration, manifest)) keys.add(key);
4384
- const images = imageOriginsFor(declaration, manifest);
4385
- if (images) keys.add(images.key);
4386
- }
4387
- return keys;
4388
- }
4389
- /**
4390
- * The keys a Worker's own process reads: what the worker and everything built
4391
- * from it declared an edge to — the queues its consumers drain and the topics
4392
- * its subscribers are bound to among them (see `workerEdges`) — and the
4393
- * broker its crons schedule through.
4394
- *
4395
- * `undefined` when no worker has that id.
4396
- */
4397
- function workerEnvKeys(manifest, workerId) {
4398
- const declaration = manifest[workerId];
4399
- if (declaration?.kind !== "worker") return void 0;
4400
- const keys = /* @__PURE__ */ new Set([
4401
- ...declaration.provides ?? [],
4402
- ...declaration.requires ?? [],
4403
- "EVENT_PUBLISHER_CONNECTION_STRING"
4404
- ]);
4405
- addEdgeKeys(manifest, workerEdges(manifest, workerId), keys);
4406
- return keys;
4407
- }
4408
- /**
4409
- * The keys a file server's processor unit reads: its bucket's, and what each
4410
- * of its processors depends on. `undefined` for a file server with none.
4411
- */
4412
- function processorEnvKeys(manifest, fileServerId) {
4413
- const server = manifest[fileServerId];
4414
- if (server?.kind !== "file-server" || !server.processors?.length) return;
4415
- const keys = /* @__PURE__ */ new Set();
4416
- addEdgeKeys(manifest, [server.of, ...server.processors.flatMap((p) => p.dependencies.map((d) => d.target))], keys);
4417
- return keys;
4418
- }
4419
- /**
4420
- * The keys the declared constructs hand to some process — each scoped to the
4421
- * processes with an edge to it. A stage key outside this set is the stage's
4422
- * own: one set by hand, which nothing declares a reader of.
4423
- */
4424
- function constructKeys(manifest) {
4425
- const keys = /* @__PURE__ */ new Set();
4426
- const add = (more) => {
4427
- for (const key of more ?? []) keys.add(key);
4428
- };
4429
- for (const [id, declaration] of Object.entries(manifest)) {
4430
- add(declaration.provides);
4431
- add(declaration.requires);
4432
- if (declaration.kind === "worker") add(workerEnvKeys(manifest, id));
4433
- if (declaration.kind === "file-server") add(processorEnvKeys(manifest, id));
4434
- if (declaration.kind === "rest-api" || declaration.kind === "websocket-api" || declaration.kind === "site" || declaration.kind === "mobile-app") add(appEnvKeys(manifest, appKey(id)));
4435
- }
4436
- return keys;
4437
- }
4438
- /**
4439
- * The keys one process is handed — the one rule `gkm dev`, `gkm exec` and
4440
- * `gkm compose` all apply, so an app gets the same keys whichever runs it:
4441
- *
4442
- * - **What its constructs reach**, by their edges: `appEnvKeys` for its app,
4443
- * `workerEnvKeys` for each worker it runs, `processorEnvKeys` for each
4444
- * file server's processors. A key a construct provides reaches only a
4445
- * process with an edge to it, a stored one included — an auth server's
4446
- * signing secret stays with the auth server.
4447
- * - **The stack's edge token** (`EDGE_TOKEN_KEY`), which a call to a
4448
- * sibling through the edge carries beside the client's address.
4449
- * - **The local CA** (`NODE_EXTRA_CA_CERTS`), where the stage's certificates
4450
- * come from gkm's: without it Node cannot verify a sibling's https address.
4451
- * - **Every one of the stage's own keys** (`stageKeys` no construct
4452
- * provides): a value set with `gkm secrets:set` that the code reads with
4453
- * `get('X')`. Nothing declares which process reads it, so every process is
4454
- * handed it — but for what gkm keeps for the stack itself (`isStackKey`):
4455
- * a container's login, the backups key, the server's address.
4456
- *
4457
- * `undefined` for an app no declaration describes, which nothing narrows.
4458
- */
4459
- function processEnvKeys(manifest, units, stageKeys) {
4460
- const keys = /* @__PURE__ */ new Set();
4461
- if (units.app !== void 0) {
4462
- const own = appEnvKeys(manifest, units.app);
4463
- if (!own && !units.workers?.length && !units.processors?.length) return;
4464
- for (const key of own ?? []) keys.add(key);
4465
- }
4466
- for (const id of units.workers ?? []) for (const key of workerEnvKeys(manifest, id) ?? []) keys.add(key);
4467
- for (const id of units.processors ?? []) for (const key of processorEnvKeys(manifest, id) ?? []) keys.add(key);
4468
- keys.add(EDGE_TOKEN_KEY);
4469
- keys.add(LOCAL_CA_KEY);
4470
- const owned = constructKeys(manifest);
4471
- for (const key of stageKeys) if (!owned.has(key) && !isStackKey(key)) keys.add(key);
4472
- return keys;
4473
- }
4474
- /**
4475
- * One process's environment, from the stage's stored keys and every value
4476
- * it resolved (`stageEnv`'s merge): exactly {@link processEnvKeys}.
4477
- */
4478
- function processEnv(manifest, units, stored, resolved) {
4479
- const env = stageEnv(stored, resolved);
4480
- const keys = processEnvKeys(manifest, units, Object.keys(stored));
4481
- if (!keys) return env;
4482
- return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key)));
4483
- }
4484
- /**
4485
- * What an app's own process runs locally: its surface or site, and the
4486
- * workers and processors whose code it holds — the same choice `gkm build`
4487
- * makes (`workerUnits`, `processorUnits`).
4488
- *
4489
- * A worker no app can build is left out here: `gkm build` says so, and a
4490
- * dev loop has nothing to run it in.
4491
- */
4492
- function appProcess(workspace, manifest, background, appName) {
4493
- const hosted = (units) => {
4494
- try {
4495
- return units().filter((unit) => unit.app === appName).map((unit) => unit.id);
4496
- } catch (error) {
4497
- if (error instanceof WorkerHasNoApp || error instanceof WorkerNameTaken || error instanceof ProcessorsHaveNoApp) return [];
4498
- throw error;
4499
- }
4500
- };
4501
- return {
4502
- app: appName,
4503
- workers: hosted(() => workerUnits(workspace, manifest, background)),
4504
- processors: hosted(() => processorUnits(workspace, manifest))
4505
- };
4506
- }
4507
- /**
4508
- * What a surface is told about the clients that call it: the identity it
4509
- * links and redirects back to.
4510
- *
4511
- * An API that finishes an OAuth callback by sending a phone back into the app
4512
- * builds `<scheme>://…`; one that mails a link to the site builds it on the
4513
- * site's address. Both are the caller's own key, named by the caller's id —
4514
- * `APP_SCHEME` for `MobileApp('App')`, `WEB_URL` for `StaticSite('Web')` — so
4515
- * two apps calling one API arrive as `APP_SCHEME` and `ADMIN_APP_SCHEME`.
4516
- *
4517
- * Clients only. A surface or a worker that calls this one is something it
4518
- * answers, never somewhere it sends a user, so nothing of theirs comes back
4519
- * along the edge. Their origins still reach the surface, folded into its
4520
- * `<ID>_TRUSTED_ORIGINS`.
4521
- */
4522
- function callerKeys(manifest, surfaceId) {
4523
- const keys = [];
4524
- for (const caller of dependentsOf(manifest, surfaceId)) {
4525
- const declaration = manifest[caller];
4526
- if (declaration?.kind === "mobile-app") keys.push(providedKeyFor(caller, declaration.kind, "scheme"));
4527
- else if (declaration?.kind === "site") keys.push(providedKeyFor(caller, declaration.kind, "url"));
4528
- }
4529
- return keys;
4530
- }
4531
- /**
4532
- * What a caller gets for each construct it has an edge to — the left half of
4533
- * the table on {@link appEnvKeys}.
4534
- */
4535
- function addEdgeKeys(manifest, edges, keys, client = false) {
4536
- for (const id of edges) {
4537
- const bucket = eventsEdgeBucket(id);
4538
- if (bucket) {
4539
- if (manifest[bucket]?.kind === "objects") {
4540
- keys.add(providedKeyFor(bucket, "objects", "eventsConnectionString"));
4541
- keys.add(providedKeyFor(bucket, "objects", "eventsToken"));
4542
- }
4543
- continue;
4544
- }
4545
- const target = manifest[id];
4546
- if (!target) continue;
4547
- if (target.kind === "rest-api") {
4548
- keys.add(providedKeyFor(id, target.kind, "url"));
4549
- continue;
4550
- }
4551
- if (target.kind === "websocket-api") {
4552
- keys.add(providedKeyFor(id, target.kind, "url"));
4553
- if (!client) keys.add(providedKeyFor(id, target.kind, "publisherConnectionString"));
4554
- continue;
4555
- }
4556
- for (const key of target.provides ?? []) keys.add(key);
4557
- if (target.kind === "inbox") keys.add(INBOX_RELAY_TOKEN_KEY);
4558
- if (target.kind === "queue" || target.kind === "topic") keys.add("EVENT_PUBLISHER_CONNECTION_STRING");
4559
- if (target.kind === "objects") {
4560
- for (const other of Object.values(manifest)) if (other.kind === "file-server" && other.of === id) for (const key of other.provides ?? []) keys.add(key);
4561
- keys.add("AWS_ACCESS_KEY_ID");
4562
- keys.add("AWS_SECRET_ACCESS_KEY");
4563
- keys.add("AWS_REGION");
4564
- }
4565
- }
4566
- }
4567
- /** One compose service per app the workspace runs, behind the apps profile. */
4568
- function appServices(workspace, manifest, containers, credentials, fakes = {}, credentialFakes = {}) {
4569
- const plan = localPlan(workspace, manifest, fakes, credentialFakes);
4570
- const derivation = {
4571
- project: workspace.name,
4572
- credentials,
4573
- seed: credentials.seed
4574
- };
4575
- const env = networkEnv(plan, {
4576
- ...derivation,
4577
- addresses: surfaceAddresses(workspace, manifest, (app, port) => `http://${app}:${port}`)
4578
- });
4579
- const browser = networkEnv(plan, {
4580
- ...derivation,
4581
- addresses: surfaceAddresses(workspace, manifest)
4582
- });
4583
- const services = {};
4584
- const buildRoot = findBuildRoot(workspace.root);
4585
- for (const [name, app] of Object.entries(workspace.apps)) {
4586
- if (app.type === "mobile" || !app.port) continue;
4587
- const key = appKey(name);
4588
- const health = app.type === "web" ? "/" : "/health";
4589
- const build = composeBuildPaths({
4590
- composeDir: workspace.root,
4591
- buildRoot,
4592
- workspaceRoot: workspace.root,
4593
- dockerfile: dockerfileOf(name, app.path)
4594
- });
4595
- const ports = [`${app.port}:${app.port}`];
4596
- if (app.type === "web") {
4597
- const args = sitePublicArgs(manifest, name, browser);
4598
- services[key] = {
4599
- image: `${key}:\${TAG:-latest}`,
4600
- build: {
4601
- ...build,
4602
- ...Object.keys(args).length ? { args } : {}
4603
- },
4604
- profiles: [APPS_PROFILE],
4605
- ports,
4606
- healthcheck: healthcheck(app.port, health)
4607
- };
4608
- continue;
4609
- }
4610
- const allowed = appEnvKeys(manifest, name);
4611
- const own = scopeTelemetryEnv(Object.fromEntries(Object.entries(env).filter(([envKey]) => allowed?.has(envKey))), {
4612
- uses: appTelemetry(manifest, name) !== void 0,
4613
- serviceName: name,
4614
- telemetry: env
4615
- });
4616
- services[key] = {
4617
- image: `${key}:\${TAG:-latest}`,
4618
- build,
4619
- profiles: [APPS_PROFILE],
4620
- ports,
4621
- environment: {
4622
- NODE_ENV: "production",
4623
- PORT: String(app.port),
4624
- ...own
4625
- },
4626
- ...containers.some((c) => c !== "caddy") ? { depends_on: containers.filter((c) => c !== "caddy") } : {},
4627
- healthcheck: healthcheck(app.port, health)
4628
- };
4629
- }
4630
- return services;
4631
- }
4632
- /** An app's health check: its own server answering on `path`. */
4633
- function healthcheck(port, path) {
4634
- return {
4635
- test: [
4636
- "CMD",
4637
- "wget",
4638
- "-q",
4639
- "--spider",
4640
- `http://localhost:${port}${path}`
4641
- ],
4642
- interval: "10s",
4643
- timeout: "5s",
4644
- retries: 5
4645
- };
4646
- }
4647
- //#endregion
4648
- export { runsServer as $, imageLayout as A, backupsPrefix as At, generateEntryDockerfile as B, PROCESSOR_ORIGIN_SECRET_ENV as C, isDatabase as Ct, appImageOptions as D, backupDatabases as Dt, processorOriginHost as E, signedOrigins as Et, WORKER_PORT as F, generateWorkerDockerfile as G, generateNodeWebDockerfile as H, detectPackageManager as I, imageBuildCredentials as J, nextPrerenderManifest as K, findBuildRoot as L, PRERENDER_RUN_ARG as M, stageBackups as Mt, PROCESSOR_PORT as N, deploysWithCompose as Nt, composeBuildPaths as O, backupExpiries as Ot, TURBO_VERSION as P, publicBuildValues as Q, generateBackendDockerfile as R, ORIGIN_VERIFY_HEADER as S, envFor as St, originSecretKey as T, stageEnv as Tt, generateProcessorDockerfile as U, generateNextjsDockerfile as V, generateViteStaticDockerfile as W, OFFLINE_BUILD_ADDRESS as X, isImageBuild as Y, offlineBuildHosts as Z, forgetState as _, bucketPolicies as _t, networkEnv as a, BACKUPS_SERVICE as at, bucketClient as b, quoteIdentifier as bt, processorEnvKeys as c, backupsRoleStatements as ct, backendsOf as d, applyBuckets as dt, siteOfflineHosts as et, constructGlobs as f, applyLifecycles as ft, COMPOSE_PATH as g, bucketLifecycles as gt, workspace_exports as h, applyPostgres as ht, dockerfileOf as i, workerUnits as it, LOCAL_CA_BUILD_SECRET as j, runTime as jt, fromBuildRoot as k, backupFile as kt, workerEnvKeys as l, backupsService as lt, reconcileWorkspace as m, applyPolicies as mt, appProcess as n, processorUnitName as nt, processEnv as o, BACKUPS_URL_KEY as ot, derivedContainers as p, applyNotifications as pt, resolveDockerConfig as q, apps_exports as r, processorUnits as rt, processEnvKeys as s, RUNNER_PATH as st, appEnvKeys as t, isUnder as tt, FAKE_ENV as u, stackBackups as ut, LEGACY_LOCAL_LOGIN as v, postgresDatabaseNames as vt, newOriginSecret as w, localRolePassword as wt, pgClient as x, mergeLifecycle as xt, ensurePostgresLogin as y, postgresStatements as yt, generateDockerignore as z };
4649
-
4650
- //# sourceMappingURL=apps-CXzjaPWR.mjs.map