@geekmidas/cli 10.0.0-alpha.93 → 10.0.0-alpha.94

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 (196) hide show
  1. package/dist/{GoDaddyProvider-Mi3vptSR.mjs → GoDaddyProvider-BRZUWD8z.mjs} +3 -3
  2. package/dist/{GoDaddyProvider-Mi3vptSR.mjs.map → GoDaddyProvider-BRZUWD8z.mjs.map} +1 -1
  3. package/dist/{GoDaddyProvider-BZb-V14e.cjs → GoDaddyProvider-DzguxU_a.cjs} +3 -3
  4. package/dist/{GoDaddyProvider-BZb-V14e.cjs.map → GoDaddyProvider-DzguxU_a.cjs.map} +1 -1
  5. package/dist/{HostingerProvider-1mqD6aG8.mjs → HostingerProvider-Cjh_2Ml6.mjs} +9 -4
  6. package/dist/{HostingerProvider-1mqD6aG8.mjs.map → HostingerProvider-Cjh_2Ml6.mjs.map} +1 -1
  7. package/dist/{HostingerProvider-C6t-PSNe.cjs → HostingerProvider-OdQmKXE3.cjs} +9 -4
  8. package/dist/HostingerProvider-OdQmKXE3.cjs.map +1 -0
  9. package/dist/{LegacyStateStore-CtwO7fwy.mjs → LegacyStateStore-BQZb6-j2.mjs} +3 -2
  10. package/dist/{LegacyStateStore-CtwO7fwy.mjs.map → LegacyStateStore-BQZb6-j2.mjs.map} +1 -1
  11. package/dist/{LegacyStateStore-BlYXQQSE.cjs → LegacyStateStore-D50dgUPc.cjs} +10 -9
  12. package/dist/{LegacyStateStore-BlYXQQSE.cjs.map → LegacyStateStore-D50dgUPc.cjs.map} +1 -1
  13. package/dist/{LocalStateStore-D40_SDmJ.mjs → LocalStateStore-BSaS2535.mjs} +2 -2
  14. package/dist/{LocalStateStore-D40_SDmJ.mjs.map → LocalStateStore-BSaS2535.mjs.map} +1 -1
  15. package/dist/{LocalStateStore-oX_zxj9V.cjs → LocalStateStore-EFBUjuMX.cjs} +8 -8
  16. package/dist/{LocalStateStore-oX_zxj9V.cjs.map → LocalStateStore-EFBUjuMX.cjs.map} +1 -1
  17. package/dist/{S3StateStore-DeI7jtvi.cjs → S3StateStore-C5mv8To3.cjs} +5 -5
  18. package/dist/{S3StateStore-DeI7jtvi.cjs.map → S3StateStore-C5mv8To3.cjs.map} +1 -1
  19. package/dist/{S3StateStore-BzS0IeSt.mjs → S3StateStore-CrFq4UZU.mjs} +2 -2
  20. package/dist/{S3StateStore-BzS0IeSt.mjs.map → S3StateStore-CrFq4UZU.mjs.map} +1 -1
  21. package/dist/{SSMStateStore-k_Ew7TWx.mjs → SSMStateStore-D3Z6mZnA.mjs} +2 -2
  22. package/dist/{SSMStateStore-k_Ew7TWx.mjs.map → SSMStateStore-D3Z6mZnA.mjs.map} +1 -1
  23. package/dist/{SSMStateStore-CaCtrzFL.cjs → SSMStateStore-DuZCH7_v.cjs} +9 -9
  24. package/dist/{SSMStateStore-CaCtrzFL.cjs.map → SSMStateStore-DuZCH7_v.cjs.map} +1 -1
  25. package/dist/{add-CP1podDH.mjs → add-C85isXFl.mjs} +4 -4
  26. package/dist/add-C85isXFl.mjs.map +1 -0
  27. package/dist/{add-VcyJnsPX.cjs → add-DsVDdvon.cjs} +4 -4
  28. package/dist/add-DsVDdvon.cjs.map +1 -0
  29. package/dist/{bundler-Dfsr6KXU.cjs → bundler-BEgUKc4j.cjs} +5 -5
  30. package/dist/{bundler-Dfsr6KXU.cjs.map → bundler-BEgUKc4j.cjs.map} +1 -1
  31. package/dist/{bundler-BWrh-AJH.mjs → bundler-BSHog8CH.mjs} +5 -5
  32. package/dist/{bundler-BWrh-AJH.mjs.map → bundler-BSHog8CH.mjs.map} +1 -1
  33. package/dist/{cli-B8otnZfX.mjs → cli-BsFenyaf.mjs} +9 -5
  34. package/dist/cli-BsFenyaf.mjs.map +1 -0
  35. package/dist/{cli-DL19w4OE.cjs → cli-BvBdv660.cjs} +9 -5
  36. package/dist/cli-BvBdv660.cjs.map +1 -0
  37. package/dist/{compose-BHVKLluX.cjs → compose-Cd09gW-n.cjs} +58 -19
  38. package/dist/compose-Cd09gW-n.cjs.map +1 -0
  39. package/dist/{compose-DrEB_4F-.mjs → compose-D2RFYd_f.mjs} +56 -17
  40. package/dist/compose-D2RFYd_f.mjs.map +1 -0
  41. package/dist/{config-DCCcrOSo.d.cts → config-DvHNMoOp.d.cts} +4 -4
  42. package/dist/{config-CHX5GOo3.d.mts.map → config-DvHNMoOp.d.cts.map} +1 -1
  43. package/dist/{config-CHX5GOo3.d.mts → config-Ngesg4O8.d.mts} +4 -4
  44. package/dist/{config-DCCcrOSo.d.cts.map → config-Ngesg4O8.d.mts.map} +1 -1
  45. package/dist/config.cjs +1 -1
  46. package/dist/config.d.cts +3 -3
  47. package/dist/config.d.mts +3 -3
  48. package/dist/config.mjs +1 -1
  49. package/dist/{credentials-QBu7VgaQ.cjs → credentials-D7XJypNd.cjs} +9 -3
  50. package/dist/{credentials-QBu7VgaQ.cjs.map → credentials-D7XJypNd.cjs.map} +1 -1
  51. package/dist/{credentials-C4KII3PD.mjs → credentials-DpfnUvIR.mjs} +9 -3
  52. package/dist/{credentials-C4KII3PD.mjs.map → credentials-DpfnUvIR.mjs.map} +1 -1
  53. package/dist/deploy/public.cjs +13 -13
  54. package/dist/deploy/public.d.cts +24 -9
  55. package/dist/deploy/public.d.cts.map +1 -1
  56. package/dist/deploy/public.d.mts +24 -9
  57. package/dist/deploy/public.d.mts.map +1 -1
  58. package/dist/deploy/public.mjs +10 -10
  59. package/dist/{deploy-C3Mhnmus.cjs → deploy-C911Akkn.cjs} +125 -11
  60. package/dist/deploy-C911Akkn.cjs.map +1 -0
  61. package/dist/{deploy-DYIyIUYd.mjs → deploy-CeJ5D0xn.mjs} +123 -9
  62. package/dist/deploy-CeJ5D0xn.mjs.map +1 -0
  63. package/dist/{discover-vk2r5giK.d.cts → discover-CTzOSGUF.d.cts} +2 -2
  64. package/dist/{discover-DqwlBVyY.d.mts.map → discover-CTzOSGUF.d.cts.map} +1 -1
  65. package/dist/{discover-DqwlBVyY.d.mts → discover-CihAtaoj.d.mts} +2 -2
  66. package/dist/{discover-vk2r5giK.d.cts.map → discover-CihAtaoj.d.mts.map} +1 -1
  67. package/dist/{dokploy-rivb1RFt.cjs → dokploy-CV7GcobZ.cjs} +2 -2
  68. package/dist/{dokploy-rivb1RFt.cjs.map → dokploy-CV7GcobZ.cjs.map} +1 -1
  69. package/dist/{dokploy-o4I6vb9W.mjs → dokploy-D_aat2Xj.mjs} +2 -2
  70. package/dist/{dokploy-o4I6vb9W.mjs.map → dokploy-D_aat2Xj.mjs.map} +1 -1
  71. package/dist/{encryption-D7zmwzWz.cjs → encryption-DFcivJaO.cjs} +3 -3
  72. package/dist/{encryption-D7zmwzWz.cjs.map → encryption-DFcivJaO.cjs.map} +1 -1
  73. package/dist/{encryption-B6ilrT7p.mjs → encryption-_4qKqtTx.mjs} +3 -3
  74. package/dist/{encryption-B6ilrT7p.mjs.map → encryption-_4qKqtTx.mjs.map} +1 -1
  75. package/dist/{engine-Cfx8fEZU.cjs → engine-Bv-LZpmj.cjs} +10 -9
  76. package/dist/{engine-Cfx8fEZU.cjs.map → engine-Bv-LZpmj.cjs.map} +1 -1
  77. package/dist/{engine-DjEcovm-.mjs → engine-DPMHThkg.mjs} +7 -6
  78. package/dist/{engine-DjEcovm-.mjs.map → engine-DPMHThkg.mjs.map} +1 -1
  79. package/dist/{github-zneTMvnO.cjs → github-Br42NMrW.cjs} +94 -6
  80. package/dist/github-Br42NMrW.cjs.map +1 -0
  81. package/dist/{github-CzBbs43W.mjs → github-xsDT19im.mjs} +94 -6
  82. package/dist/github-xsDT19im.mjs.map +1 -0
  83. package/dist/{index-BiYU7cUl.d.mts → index-BlpcClwM.d.mts} +2 -2
  84. package/dist/{index-BiYU7cUl.d.mts.map → index-BlpcClwM.d.mts.map} +1 -1
  85. package/dist/{index-Dm6V9bwh.d.cts → index-CwLvFqtH.d.cts} +2 -2
  86. package/dist/{index-Dm6V9bwh.d.cts.map → index-CwLvFqtH.d.cts.map} +1 -1
  87. package/dist/index.cjs +147 -116
  88. package/dist/index.cjs.map +1 -1
  89. package/dist/index.mjs +143 -112
  90. package/dist/index.mjs.map +1 -1
  91. package/dist/{local-Otp74ak0.mjs → local-B7Zv1NoA.mjs} +2 -2
  92. package/dist/{local-Otp74ak0.mjs.map → local-B7Zv1NoA.mjs.map} +1 -1
  93. package/dist/{local-B61kUh0w.cjs → local-OPC9BCZt.cjs} +2 -2
  94. package/dist/{local-B61kUh0w.cjs.map → local-OPC9BCZt.cjs.map} +1 -1
  95. package/dist/{migrate-BaC4w0sb.mjs → migrate-B7evHv7O.mjs} +3 -3
  96. package/dist/{migrate-BaC4w0sb.mjs.map → migrate-B7evHv7O.mjs.map} +1 -1
  97. package/dist/{migrate-C8wTpakT.cjs → migrate-D5jUz20_.cjs} +3 -3
  98. package/dist/{migrate-C8wTpakT.cjs.map → migrate-D5jUz20_.cjs.map} +1 -1
  99. package/dist/{migrate-CsBZKALY.mjs → migrate-DhvFPGLi.mjs} +3 -3
  100. package/dist/{migrate-CsBZKALY.mjs.map → migrate-DhvFPGLi.mjs.map} +1 -1
  101. package/dist/{migrate-DFjbGnSr.cjs → migrate-SkWJotn5.cjs} +3 -3
  102. package/dist/{migrate-DFjbGnSr.cjs.map → migrate-SkWJotn5.cjs.map} +1 -1
  103. package/dist/openapi.cjs +1 -1
  104. package/dist/openapi.d.cts +1 -1
  105. package/dist/openapi.d.mts +1 -1
  106. package/dist/openapi.mjs +1 -1
  107. package/dist/providers-BFeP_mYw.cjs +1098 -0
  108. package/dist/providers-BFeP_mYw.cjs.map +1 -0
  109. package/dist/providers-sTj-BG0S.mjs +1079 -0
  110. package/dist/providers-sTj-BG0S.mjs.map +1 -0
  111. package/dist/reconcile/public.d.cts +2 -2
  112. package/dist/reconcile/public.d.mts +2 -2
  113. package/dist/{resolve-g8htuR80.cjs → resolve-CFEOtRsl.cjs} +4 -4
  114. package/dist/{resolve-g8htuR80.cjs.map → resolve-CFEOtRsl.cjs.map} +1 -1
  115. package/dist/{resolve-Ccjlpnd9.mjs → resolve-Dyd1S2wn.mjs} +4 -4
  116. package/dist/{resolve-Ccjlpnd9.mjs.map → resolve-Dyd1S2wn.mjs.map} +1 -1
  117. package/dist/{rollback--ympG9ss.cjs → rollback-D720SFhV.cjs} +11 -9
  118. package/dist/{rollback--ympG9ss.cjs.map → rollback-D720SFhV.cjs.map} +1 -1
  119. package/dist/{rollback-Drbg0OeR.mjs → rollback-NroNbGC0.mjs} +8 -6
  120. package/dist/{rollback-Drbg0OeR.mjs.map → rollback-NroNbGC0.mjs.map} +1 -1
  121. package/dist/{runtime-_wEVtshH.d.mts → runtime-BRCq6dQ7.d.mts} +2 -2
  122. package/dist/{runtime-D_J3ExJn.d.cts.map → runtime-BRCq6dQ7.d.mts.map} +1 -1
  123. package/dist/{runtime-D_J3ExJn.d.cts → runtime-VktAo_8B.d.cts} +2 -2
  124. package/dist/{runtime-_wEVtshH.d.mts.map → runtime-VktAo_8B.d.cts.map} +1 -1
  125. package/dist/{sandbox-CPJq1Kia.d.mts → sandbox-D1gd0iDz.d.cts} +2 -2
  126. package/dist/{sandbox-CPJq1Kia.d.mts.map → sandbox-D1gd0iDz.d.cts.map} +1 -1
  127. package/dist/{sandbox-JwuPAl7I.d.cts → sandbox-zHnRLCj0.d.mts} +2 -2
  128. package/dist/{sandbox-JwuPAl7I.d.cts.map → sandbox-zHnRLCj0.d.mts.map} +1 -1
  129. package/dist/{secrets-DbPmAS4k.mjs → secrets-CwLauUB_.mjs} +3 -3
  130. package/dist/secrets-CwLauUB_.mjs.map +1 -0
  131. package/dist/{secrets-DJteijZo.cjs → secrets-DAvi_O9g.cjs} +3 -3
  132. package/dist/secrets-DAvi_O9g.cjs.map +1 -0
  133. package/dist/{seeds-c-ByX9je.cjs → seeds-BCg8X36S.cjs} +1143 -2645
  134. package/dist/seeds-BCg8X36S.cjs.map +1 -0
  135. package/dist/{seeds-BSL55F6q.mjs → seeds-CTxTZa-R.mjs} +1289 -2760
  136. package/dist/seeds-CTxTZa-R.mjs.map +1 -0
  137. package/dist/{sniffer-Dq5BS98f.cjs → sniffer-C0z3NB2A.cjs} +572 -3
  138. package/dist/sniffer-C0z3NB2A.cjs.map +1 -0
  139. package/dist/{sniffer-BTtGAtm3.mjs → sniffer-DCcuzHz_.mjs} +496 -5
  140. package/dist/sniffer-DCcuzHz_.mjs.map +1 -0
  141. package/dist/{sst-CnKY-CSh.cjs → sst-DKNH243z.cjs} +3 -3
  142. package/dist/{sst-CnKY-CSh.cjs.map → sst-DKNH243z.cjs.map} +1 -1
  143. package/dist/{sst-BaRXp2Dd.mjs → sst-DRDSDwOk.mjs} +3 -3
  144. package/dist/{sst-BaRXp2Dd.mjs.map → sst-DRDSDwOk.mjs.map} +1 -1
  145. package/dist/{stack-1PeLJS2j.cjs → stack-B3fPDTBg.cjs} +3 -3
  146. package/dist/{stack-1PeLJS2j.cjs.map → stack-B3fPDTBg.cjs.map} +1 -1
  147. package/dist/{stack-Co4uZkAo.mjs → stack-NrdH5ngX.mjs} +3 -3
  148. package/dist/{stack-Co4uZkAo.mjs.map → stack-NrdH5ngX.mjs.map} +1 -1
  149. package/dist/{stages-BI8JvPzI.cjs → stages-CkqP1N4S.cjs} +16 -3
  150. package/dist/stages-CkqP1N4S.cjs.map +1 -0
  151. package/dist/{stages-DY-fQKmo.mjs → stages-veC4TcQe.mjs} +16 -3
  152. package/dist/stages-veC4TcQe.mjs.map +1 -0
  153. package/dist/target/public.cjs +1 -1
  154. package/dist/target/public.d.cts +2 -2
  155. package/dist/target/public.d.mts +2 -2
  156. package/dist/target/public.mjs +1 -1
  157. package/dist/{terminal-8XngdSTo.cjs → terminal-CkUYuAPd.cjs} +2 -2
  158. package/dist/{terminal-8XngdSTo.cjs.map → terminal-CkUYuAPd.cjs.map} +1 -1
  159. package/dist/{terminal-C4XRdwnU.mjs → terminal-DAHs2Zko.mjs} +2 -2
  160. package/dist/{terminal-C4XRdwnU.mjs.map → terminal-DAHs2Zko.mjs.map} +1 -1
  161. package/dist/{types-BibpiHKB.d.cts → types-DMoaFrjg.d.mts} +32 -9
  162. package/dist/types-DMoaFrjg.d.mts.map +1 -0
  163. package/dist/{types-B6lmD3en.d.mts → types-DXyaSmqu.d.cts} +33 -8
  164. package/dist/types-DXyaSmqu.d.cts.map +1 -0
  165. package/dist/workspace/index.cjs +1 -1
  166. package/dist/workspace/index.d.cts +2 -2
  167. package/dist/workspace/index.d.mts +2 -2
  168. package/dist/workspace/index.mjs +1 -1
  169. package/dist/{workspace-Bzw7Zs82.mjs → workspace-DWK1PTXP.mjs} +4 -4
  170. package/dist/workspace-DWK1PTXP.mjs.map +1 -0
  171. package/dist/{workspace-CHOB2Xg3.cjs → workspace-cSyi5nb1.cjs} +4 -4
  172. package/dist/workspace-cSyi5nb1.cjs.map +1 -0
  173. package/package.json +15 -15
  174. package/dist/HostingerProvider-C6t-PSNe.cjs.map +0 -1
  175. package/dist/add-CP1podDH.mjs.map +0 -1
  176. package/dist/add-VcyJnsPX.cjs.map +0 -1
  177. package/dist/cli-B8otnZfX.mjs.map +0 -1
  178. package/dist/cli-DL19w4OE.cjs.map +0 -1
  179. package/dist/compose-BHVKLluX.cjs.map +0 -1
  180. package/dist/compose-DrEB_4F-.mjs.map +0 -1
  181. package/dist/deploy-C3Mhnmus.cjs.map +0 -1
  182. package/dist/deploy-DYIyIUYd.mjs.map +0 -1
  183. package/dist/github-CzBbs43W.mjs.map +0 -1
  184. package/dist/github-zneTMvnO.cjs.map +0 -1
  185. package/dist/secrets-DJteijZo.cjs.map +0 -1
  186. package/dist/secrets-DbPmAS4k.mjs.map +0 -1
  187. package/dist/seeds-BSL55F6q.mjs.map +0 -1
  188. package/dist/seeds-c-ByX9je.cjs.map +0 -1
  189. package/dist/sniffer-BTtGAtm3.mjs.map +0 -1
  190. package/dist/sniffer-Dq5BS98f.cjs.map +0 -1
  191. package/dist/stages-BI8JvPzI.cjs.map +0 -1
  192. package/dist/stages-DY-fQKmo.mjs.map +0 -1
  193. package/dist/types-B6lmD3en.d.mts.map +0 -1
  194. package/dist/types-BibpiHKB.d.cts.map +0 -1
  195. package/dist/workspace-Bzw7Zs82.mjs.map +0 -1
  196. package/dist/workspace-CHOB2Xg3.cjs.map +0 -1
@@ -1,13 +1,13 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
2
  import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
3
- import { r as storedCredentials, s as run$1, t as MissingCredential, x as gkmHome } from "./credentials-C4KII3PD.mjs";
3
+ import { s as run$1, x as gkmHome } from "./credentials-DpfnUvIR.mjs";
4
4
  import { d as output, r as discover, u as ConstructGenerator } from "./discover-qjFapetL.mjs";
5
5
  import { t as appKey } from "./derive-B4vDpzgP.mjs";
6
- import { $ as RotationInProgress, B as LOGS_PORT, G as checkS3Config, H as provisioningOf, J as BucketNameUnavailable, K as AccessKeyLimit, Q as RecordedBucketUnreachable, R as stageSampleRate, U as stageProvider, W as S3_PROVISIONING, X as IamUserNotOwned, Y as BucketOwnedByAnotherProject, Z as ProvisionedBucketUnreachable, _ as PUBLIC_ENV_PREFIXES, a as allConstructGlobs, at as SERVER_IPV6_KEY, et as S3RegionRequired, it as SERVER_IPV4_KEY, j as TEST_STAGE, lt as UnknownSecretsStoreProvider, ot as cnameTarget, q as BucketKeySetElsewhere, st as isReservedStageKey, v as getPublicEnvPrefix, z as telemetryEnv } from "./workspace-Bzw7Zs82.mjs";
6
+ import { B as LOGS_PORT, H as provisioningOf, R as stageSampleRate, U as stageProvider, _ as PUBLIC_ENV_PREFIXES, a as allConstructGlobs, at as SERVER_IPV6_KEY, it as SERVER_IPV4_KEY, j as TEST_STAGE, lt as UnknownSecretsStoreProvider, ot as cnameTarget, st as isReservedStageKey, v as getPublicEnvPrefix, z as telemetryEnv } from "./workspace-DWK1PTXP.mjs";
7
7
  import { ConfigNotFound, NotInAnApp, loadWorkspaceAppInfo, loadWorkspaceConfig } from "./config.mjs";
8
8
  import { a as telemetryArgs, c as startTelemetryCode, n as runtimeFor, u as writeTelemetryModule } from "./EndpointGenerator-Bor2tZCm.mjs";
9
9
  import { a as DEFAULT_STORAGE, i as DEFAULT_EVENTS$1, n as readFakes, o as holdsEveryCache, r as DEFAULT_CACHE, t as SubscriberGenerator } from "./SubscriberGenerator-CyN2VF5X.mjs";
10
- import { c as runtimeOf } from "./resolve-Ccjlpnd9.mjs";
10
+ import { c as runtimeOf } from "./resolve-Dyd1S2wn.mjs";
11
11
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
12
12
  import { constants, existsSync, readFileSync } from "node:fs";
13
13
  import { appendFile, chmod, copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
@@ -18,7 +18,7 @@ import { Queue } from "@geekmidas/constructs/queue";
18
18
  import { CLIENT_IP_HEADER, DEFAULT_POSTGRES_VERSION, TELEMETRY_KEYS, cacheTable, cookieDomain, dependenciesOf, dependentsOf, externalApiUrl, kebabCase, mobileOrigins, provideKey, providedKeyFor, provisionOrder, publicEnvFor, schemeBase, scopedName } from "@geekmidas/manifest";
19
19
  import { createServer, isIPv4, isIPv6 } from "node:net";
20
20
  import { execFile, spawn } from "node:child_process";
21
- import { createCipheriv, createDecipheriv, createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
21
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomInt } from "node:crypto";
22
22
  import { config } from "dotenv";
23
23
  import { stringify } from "yaml";
24
24
  import { formatKeyring, generateKeyring } from "@geekmidas/constructs/encryption";
@@ -31,7 +31,6 @@ import { CreateQueueCommand, GetQueueUrlCommand, SQSClient } from "@aws-sdk/clie
31
31
  import { Client } from "pg";
32
32
  import { cacheTableStatements } from "@geekmidas/cache/postgres";
33
33
  import { lookup } from "node:dns/promises";
34
- import * as s3Url from "@geekmidas/storage/s3-url";
35
34
  //#region src/workspace/rootSite.ts
36
35
  /**
37
36
  * Which site the base domain points at — deployed and locally alike.
@@ -4924,7 +4923,7 @@ function bucketPolicies(plan) {
4924
4923
  * client, can be admitted by the policy where the client would have said no.
4925
4924
  * Prefer `**` where crossing segments is what you meant.
4926
4925
  */
4927
- function bucketPolicy$1(bucket, open) {
4926
+ function bucketPolicy(bucket, open) {
4928
4927
  return JSON.stringify({
4929
4928
  Version: "2012-10-17",
4930
4929
  Statement: [{
@@ -5006,7 +5005,7 @@ async function databasesExist(client, names) {
5006
5005
  async function applyPolicies(client, policies) {
5007
5006
  const applied = [];
5008
5007
  for (const { bucket, open } of policies) {
5009
- const wanted = bucketPolicy$1(bucket, open);
5008
+ const wanted = bucketPolicy(bucket, open);
5010
5009
  const describe = `open paths on ${bucket}`;
5011
5010
  if (equivalent(await client.policy(bucket), wanted)) {
5012
5011
  applied.push({
@@ -6646,1295 +6645,385 @@ function isUnder(file, dir) {
6646
6645
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? !rel.startsWith(`..${sep}`) : false;
6647
6646
  }
6648
6647
  //#endregion
6649
- //#region src/deploy/devServices.ts
6648
+ //#region src/target/dokploy/dns/DnsProvider.ts
6650
6649
  /**
6651
- * Mail and object storage on a deployed stage: real ones, or — only when
6652
- * someone asked — the dev services the local stage runs.
6653
- *
6654
- * Locally a declared `Email` is Mailpit and a declared bucket is MinIO, and
6655
- * nobody has to configure either. Deployed, the same two containers would be
6656
- * a stage that silently delivers no mail and keeps its files on one
6657
- * container's disk. So a deployed stage on a server target takes both from
6658
- * its secrets — the mail server's URL and sending address, and each bucket's
6659
- * URL — and a stage missing any of them fails before anything is built,
6660
- * provisioned or written, naming every key at once.
6661
- *
6662
- * A bucket's credentials are not checked: they are optional, and come from
6663
- * either of two places. The bucket's URL may carry a key of its own
6664
- * (`s3://KEY:SECRET@uploads`), which wins; otherwise the S3 client's default
6665
- * chain applies — the stage's shared `AWS_ACCESS_KEY_ID`/
6666
- * `AWS_SECRET_ACCESS_KEY` when it set them, or a role.
6667
- *
6668
- * `--allow-dev-services` is the way out for a stage that is not production —
6669
- * a preview, a demo: every construct the stage does not account for gets the
6670
- * dev service the local stage runs for it — a bucket MinIO, mail Mailpit —
6671
- * and the target derives the keys from it. What the stage does account for
6672
- * still wins: a key set in its secrets, or a provider (`deploy.objects`)
6673
- * that backs the kind. Every run that uses one says so, loudly.
6674
- *
6675
- * Pure: what each target runs is decided here from declarations and the
6676
- * stage's values, and the targets do the running.
6650
+ * Check if value is a DnsProvider implementation.
6677
6651
  */
6652
+ function isDnsProvider(value) {
6653
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.getRecords === "function" && typeof value.upsertRecords === "function" && typeof value.deleteRecords === "function";
6654
+ }
6678
6655
  /**
6679
- * The dev services a deployed stage can run — one per kind that has one on
6680
- * every server target: a bucket's MinIO and mail's Mailpit. A cache or a
6681
- * database is not here because a server stage runs its own anyway.
6656
+ * Create a DNS provider based on configuration.
6657
+ *
6658
+ * - 'hostinger': HostingerProvider
6659
+ * - 'route53': Route53Provider
6660
+ * - 'godaddy': GoDaddyProvider
6661
+ * - 'manual': Returns null (user handles DNS)
6662
+ * - Custom: Use provided DnsProvider implementation
6682
6663
  */
6683
- const DEV_SERVICES = ["minio", "mailpit"];
6664
+ async function createDnsProvider(options) {
6665
+ const { config } = options;
6666
+ if (config.provider === "manual") return null;
6667
+ if (isDnsProvider(config.provider)) return config.provider;
6668
+ const provider = config.provider;
6669
+ if (provider === "hostinger") {
6670
+ const { HostingerProvider } = await import("./HostingerProvider-Cjh_2Ml6.mjs");
6671
+ return new HostingerProvider(options.hostinger);
6672
+ }
6673
+ if (provider === "route53") {
6674
+ const { Route53Provider } = await import("./Route53Provider-QXxjkZO1.mjs");
6675
+ const route53Config = config;
6676
+ return new Route53Provider({
6677
+ region: route53Config.region,
6678
+ profile: route53Config.profile,
6679
+ hostedZoneId: route53Config.hostedZoneId
6680
+ });
6681
+ }
6682
+ if (provider === "godaddy") {
6683
+ const { GoDaddyProvider } = await import("./GoDaddyProvider-BRZUWD8z.mjs");
6684
+ return new GoDaddyProvider(options.godaddy ?? {});
6685
+ }
6686
+ if (provider === "cloudflare") throw new DnsProviderNotImplemented("cloudflare");
6687
+ throw new DnsProviderUnknown(config);
6688
+ }
6684
6689
  /**
6685
- * The S3 client's shared key pair. Optional: a bucket whose URL carries its own
6686
- * key (`s3://KEY:SECRET@bucket`) signs with that, and one without signs with
6687
- * this pair when the stage set it, or with whatever else the SDK's default
6688
- * chain finds — a role.
6690
+ * The provider's credentials can write records and not read them — a key
6691
+ * scoped to updates only. What reads them falls back to writing every record,
6692
+ * which is idempotent, without a diff.
6689
6693
  */
6690
- const STORAGE_KEY_PAIR = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"];
6691
- /** Dev services asked of a target that runs no containers. */
6692
- var DevServicesNeedServerTarget = class extends GkmError {
6693
- target;
6694
- constructor(target) {
6695
- super(`--allow-dev-services applies to server targets only, and '${target}' deploys to AWS, where a bucket is S3 and mail is the stage's own. Drop --allow-dev-services.`);
6696
- this.target = target;
6697
- this.name = "DevServicesNeedServerTarget";
6694
+ var DnsRecordsUnreadable = class extends GkmError {
6695
+ provider;
6696
+ domain;
6697
+ reason;
6698
+ constructor(provider, domain, reason) {
6699
+ super(`The ${provider} key cannot read ${domain}'s DNS records (${reason}), so changes cannot be compared with what is there: every record is written, which leaves one that already has its value as it was.`);
6700
+ this.provider = provider;
6701
+ this.domain = domain;
6702
+ this.reason = reason;
6703
+ this.name = "DnsRecordsUnreadable";
6698
6704
  }
6699
6705
  };
6700
- /**
6701
- * `--allow-dev-services` given a value — the list it used to take. It is a
6702
- * switch now: every construct the stage does not account for gets its dev
6703
- * service.
6704
- */
6705
- var AllowDevServicesTakesNoValue = class extends GkmError {
6706
- value;
6707
- constructor(value) {
6708
- super(`--allow-dev-services takes no value (it was given '${value}'). It runs the dev service for every bucket and mail the stage does not account for — no key in its secrets, no provider in deploy.<kind>.<stage> — so there is nothing to list. Pass --allow-dev-services on its own.`);
6709
- this.value = value;
6710
- this.name = "AllowDevServicesTakesNoValue";
6706
+ /** A DNS provider gkm names and does not have yet. */
6707
+ var DnsProviderNotImplemented = class extends Error {
6708
+ provider;
6709
+ constructor(provider) {
6710
+ super(`The ${provider} DNS provider is not implemented yet. Use 'route53', 'godaddy', 'hostinger' or 'manual' for this domain in dns, or pass your own DnsProvider object.`);
6711
+ this.provider = provider;
6712
+ this.name = "DnsProviderNotImplemented";
6713
+ }
6714
+ };
6715
+ /** A `provider:` that is none of the built-ins, nor a DnsProvider object. */
6716
+ var DnsProviderUnknown = class extends GkmError {
6717
+ config;
6718
+ constructor(config) {
6719
+ super(`Unknown DNS provider: ${JSON.stringify(config)}. dns takes 'route53', 'godaddy', 'hostinger', 'manual', or an object implementing DnsProvider.`);
6720
+ this.config = config;
6721
+ this.name = "DnsProviderUnknown";
6711
6722
  }
6712
6723
  };
6724
+ //#endregion
6725
+ //#region src/deploy/state.ts
6713
6726
  /**
6714
- * Refuses `--allow-dev-services <value>` and `--allow-dev-services=<value>` on
6715
- * a command line, with the reason, before the parser calls the value an
6716
- * excess argument. `gkm deploy` and `gkm compose` take no positional
6717
- * argument, so whatever follows the flag and is not a flag was meant for it.
6718
- *
6719
- * @throws {AllowDevServicesTakesNoValue}
6727
+ * Create a new empty state for a stage
6720
6728
  */
6721
- function assertDevServicesFlag(argv) {
6722
- for (let i = 0; i < argv.length; i++) {
6723
- const arg = argv[i];
6724
- if (arg.startsWith("--allow-dev-services=")) throw new AllowDevServicesTakesNoValue(arg.slice(arg.indexOf("=") + 1));
6725
- const next = argv[i + 1];
6726
- if (arg === "--allow-dev-services" && next && !next.startsWith("-")) throw new AllowDevServicesTakesNoValue(next);
6727
- }
6729
+ function createEmptyState(stage, projectId, environmentId) {
6730
+ return {
6731
+ provider: "dokploy",
6732
+ stage,
6733
+ projectId,
6734
+ environmentId,
6735
+ applications: {},
6736
+ services: {},
6737
+ lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
6738
+ };
6739
+ }
6740
+ /** A new compose stage's state. */
6741
+ function createComposeState(stage) {
6742
+ return {
6743
+ provider: "compose",
6744
+ stage,
6745
+ lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
6746
+ };
6728
6747
  }
6729
6748
  /**
6730
- * A deployed stage with mail or object storage that its secrets do not
6731
- * configure — every missing key, across every app, at once.
6749
+ * `state` as the Dokploy target keeps it. A stage whose state another target
6750
+ * wrote — one moved from compose to Dokploy — keeps its core (releases,
6751
+ * identity) and starts with no Dokploy ids, as a first deploy would.
6732
6752
  */
6733
- var ExternalServicesNotConfigured = class extends GkmError {
6734
- stage;
6735
- missing;
6736
- constructor(stage, missing) {
6737
- const standIns = missing.some((m) => m.service !== void 0);
6738
- const lines = missing.map((m) => {
6739
- const by = m.apps?.length ? `, read by ${m.apps.join(", ")}` : "";
6740
- return ` gkm secrets:set ${m.key} '${m.example}' --stage ${stage}\n ${m.what}${by}` + (m.note ? `\n ${m.note}` : "") + (m.hint ? `\n ${m.hint}` : "");
6741
- });
6742
- super(`The stage '${stage}' is deployed, and a deployed stage's mail and object storage are real services: gkm runs no Mailpit or MinIO for it. Set ${missing.length === 1 ? "this key" : `these ${missing.length} keys`} in the stage's secrets:\n\n${lines.join("\n")}\n\n` + (standIns ? "For a stage that is not production — a preview, a demo — the dev services can run instead, with --allow-dev-services. Mailpit delivers no mail, and MinIO keeps every object on one container's disk.\n\n" : "") + `Or run: gkm secrets:add --stage ${stage}`);
6743
- this.stage = stage;
6744
- this.missing = missing;
6745
- this.name = "ExternalServicesNotConfigured";
6746
- }
6747
- };
6753
+ function asDokployState(state) {
6754
+ if (state.provider === "dokploy") return state;
6755
+ const { provider: _provider, ...core } = state;
6756
+ return {
6757
+ ...core,
6758
+ provider: "dokploy",
6759
+ projectId: "",
6760
+ environmentId: "",
6761
+ applications: {},
6762
+ services: {}
6763
+ };
6764
+ }
6748
6765
  /**
6749
- * Every mail and storage construct a manifest declares, with the apps that
6750
- * depend on each — what a target that provisions the whole manifest checks.
6766
+ * Set application ID in state (mutates state)
6751
6767
  */
6752
- function manifestServiceDeclarations(manifest) {
6753
- return Object.entries(manifest).flatMap(([id, declaration]) => {
6754
- const { kind } = declaration;
6755
- if (kind !== "email" && kind !== "objects" && kind !== "file-server") return [];
6756
- const apps = dependentsOf(manifest, id).filter((caller) => {
6757
- const callerKind = manifest[caller]?.kind;
6758
- return callerKind === "rest-api" || callerKind === "site";
6759
- }).map(appKey);
6760
- return [{
6761
- id,
6762
- kind,
6763
- ...declaration.kind === "file-server" ? { of: declaration.of } : {},
6764
- ...apps.length ? { apps } : {}
6765
- }];
6766
- });
6768
+ function setApplicationId(state, appName, applicationId) {
6769
+ state.applications[appName] = applicationId;
6770
+ }
6771
+ /** Two records naming the same image: by digest when both have one. */
6772
+ function sameImage(a, b) {
6773
+ return a.digest && b.digest ? a.digest === b.digest : a.ref === b.ref;
6774
+ }
6775
+ /** The newest release in `history` after `index` that a rollback may restore. */
6776
+ function restorable(history, index, current) {
6777
+ return history.slice(index + 1).find((entry) => !entry.rolledBack && !sameImage(entry, current));
6767
6778
  }
6768
6779
  /**
6769
- * Every key a stage must be given rather than derive — the one list both a
6770
- * deploy's checks and `gkm secrets:add` read, so what a deploy refuses and
6771
- * what the builder offers cannot drift.
6772
- *
6773
- * - Deployed, mail is its URL and its sending address, a bucket its URL, and
6774
- * a file server its public URL. Locally all of it is Mailpit and MinIO.
6775
- * - On every stage, a third party's credentials: nobody but the third party
6776
- * can issue them.
6777
- *
6778
- * Never a derived value: a database URL, a generated secret, the seed.
6780
+ * Record that `image` went live for `appName` (mutates state): it becomes
6781
+ * `current`, and what was current becomes `previous`. Releasing what already
6782
+ * runs — a redeploy of the same digest — changes nothing.
6779
6783
  */
6780
- function requiredStageKeys(input) {
6781
- const domain = input.domain ?? "example.com";
6782
- const keys = [];
6783
- const add = (entry) => {
6784
- if (!keys.some((k) => k.key === entry.key)) keys.push(entry);
6784
+ function recordRelease(state, appName, image, by, releasedAt = /* @__PURE__ */ new Date()) {
6785
+ const releases = state.releases?.[appName];
6786
+ if (releases && sameImage(releases.current, image)) return;
6787
+ const entry = {
6788
+ ...image,
6789
+ releasedAt: releasedAt.toISOString(),
6790
+ releasedBy: by
6785
6791
  };
6786
- const byId = (list) => [...list ?? []].sort((a, b) => a.id.localeCompare(b.id));
6787
- const apps = (d) => d.apps?.length ? { apps: [...d.apps].sort() } : {};
6788
- if (!input.local) {
6789
- const services = byId(input.services);
6790
- const objects = input.providers?.objects;
6791
- const storage = objects?.accounted ? objects.hint ? { hint: objects.hint } : {} : { service: "minio" };
6792
- for (const d of services.filter((d) => d.kind === "email")) {
6793
- add({
6794
- key: provideKey(d.id, "url"),
6795
- id: d.id,
6796
- kind: "email",
6797
- what: `where '${d.id}' sends mail — any SMTP server`,
6798
- example: `smtp://user:password@smtp.${domain}:587`,
6799
- service: "mailpit",
6800
- ...apps(d)
6801
- });
6802
- add({
6803
- key: provideKey(d.id, "from"),
6804
- id: d.id,
6805
- kind: "email",
6806
- what: `the address '${d.id}' sends from, on a domain the mail server has verified`,
6807
- example: `noreply@${domain}`,
6808
- service: "mailpit",
6809
- ...apps(d)
6810
- });
6792
+ const history = [entry, ...releases?.history ?? []].slice(0, 10);
6793
+ const previous = releases?.current;
6794
+ state.releases = {
6795
+ ...state.releases,
6796
+ [appName]: {
6797
+ current: entry,
6798
+ ...previous ? { previous } : {},
6799
+ history
6811
6800
  }
6812
- for (const d of services.filter((d) => d.kind === "objects")) add({
6813
- key: provideKey(d.id, "url"),
6814
- id: d.id,
6815
- kind: "bucket",
6816
- what: `the bucket '${d.id}' — S3, R2, or any S3-compatible store (add &endpoint=… for one that is not S3)`,
6817
- note: `credentials are optional: a key for this bucket alone in the URL (s3://KEY:SECRET@${appKey(d.id)}?…) wins; without one, the shared AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY or a role signs`,
6818
- example: `s3://${appKey(d.id)}?region=eu-west-1`,
6819
- ...storage,
6820
- ...apps(d)
6821
- });
6822
- for (const d of services.filter((d) => d.kind === "file-server")) add({
6823
- key: provideKey(d.id, "url"),
6824
- id: d.id,
6825
- kind: "file-server",
6826
- what: `the public address '${d.id}' serves its bucket on — a CDN or the bucket's own domain`,
6827
- example: `https://${appKey(d.id)}.${domain}`,
6828
- ...storage,
6829
- ...d.of ? { of: d.of } : {},
6830
- ...apps(d)
6831
- });
6832
- }
6833
- if (!input.local && input.server) add({
6834
- key: SERVER_IPV4_KEY,
6835
- id: "server",
6836
- kind: "server",
6837
- what: "the public IPv4 address of the server the stage's stack runs on — its hosts' DNS records point at it, and every deploy checks they do",
6838
- note: `${SERVER_IPV6_KEY} adds its IPv6 address (AAAA records); neither is ever handed to an app`,
6839
- example: "203.0.113.10"
6840
- });
6841
- for (const d of byId(input.credentials)) add({
6842
- key: provideKey(d.id, "credentials"),
6843
- id: d.id,
6844
- kind: d.kind,
6845
- what: d.kind === "external-api" ? `the credentials '${d.id}' was issued for this stage, as its schema describes them` : `the credential '${d.id}', as its schema describes it`,
6846
- example: "{\"apiKey\":\"…\"}",
6847
- ...apps(d)
6848
- });
6849
- return keys;
6801
+ };
6850
6802
  }
6851
6803
  /**
6852
- * Whether only the stage's secrets can supply `key` to a construct of `kind`
6853
- * — what nothing on the stage derives.
6854
- *
6855
- * A third party's credentials, always. Deployed, also each generated secret
6856
- * and keyring: the stage generated each one once, and every run reads the
6857
- * same value back.
6804
+ * Record that `appName` was rolled back to `to` (mutates state): every
6805
+ * release newer than it is marked rolled back, so neither this rollback nor
6806
+ * a later one restores it, and `previous` moves to the release before `to`.
6858
6807
  */
6859
- function suppliedOnly(kind, id, key, local) {
6860
- if (kind === "credential") return true;
6861
- if (kind === "external-api") return key === provideKey(id, "credentials");
6862
- if (local) return false;
6863
- return kind === "secret" || kind === "encryption";
6808
+ function recordRollback(state, appName, to) {
6809
+ const releases = state.releases?.[appName];
6810
+ if (!releases) return;
6811
+ const index = releases.history.findIndex((entry) => !entry.rolledBack && sameImage(entry, to));
6812
+ if (index === -1) return;
6813
+ const history = releases.history.map((entry, i) => i < index ? {
6814
+ ...entry,
6815
+ rolledBack: true
6816
+ } : entry);
6817
+ const current = history[index];
6818
+ const previous = restorable(history, index, current);
6819
+ state.releases = {
6820
+ ...state.releases,
6821
+ [appName]: {
6822
+ current,
6823
+ ...previous ? { previous } : {},
6824
+ history
6825
+ }
6826
+ };
6864
6827
  }
6865
6828
  /**
6866
- * Where a deployed stage's mail and storage come from, and what it lacks.
6867
- *
6868
- * - Mail is external once its URL is set, and then needs its sending
6869
- * address too. Unset, it is Mailpit where allowed — the address derived
6870
- * unless set — and missing otherwise.
6871
- * - A bucket is external once its URL is set; its credentials, in the URL or
6872
- * the shared pair, are optional. Unset, it is MinIO where allowed, and
6873
- * missing otherwise.
6874
- * - A file server's URL is derived where its bucket is MinIO, unless set;
6875
- * over an external bucket the stage must set it.
6876
- *
6877
- * The keys themselves are {@link requiredStageKeys}'s.
6829
+ * Get a generated secret for an app
6878
6830
  */
6879
- function externalServices(input) {
6880
- const { supplied, allow } = input;
6881
- const has = (key) => supplied[key] !== void 0;
6882
- const required = requiredStageKeys({
6883
- local: false,
6884
- services: input.declarations,
6885
- ...input.domain ? { domain: input.domain } : {},
6886
- ...input.providers ? { providers: input.providers } : {}
6887
- });
6888
- const standIn = (k) => allow && k.service !== void 0 && !has(k.key);
6889
- const mailpit = required.filter((k) => k.kind === "email" && k.key === provideKey(k.id, "url")).filter(standIn).map((k) => k.id);
6890
- const minio = required.filter((k) => k.kind === "bucket").filter(standIn).map((k) => k.id);
6891
- const covered = (k) => k.kind === "email" && mailpit.includes(k.id) || k.kind === "bucket" && minio.includes(k.id) || k.kind === "file-server" && k.of !== void 0 && minio.includes(k.of);
6892
- return {
6893
- missing: required.filter((k) => !has(k.key) && !covered(k)).map(({ key, id, what, note, example, service, apps, hint }) => ({
6894
- key,
6895
- id,
6896
- what,
6897
- ...note ? { note } : {},
6898
- example,
6899
- ...service ? { service } : {},
6900
- ...apps ? { apps } : {},
6901
- ...hint ? { hint } : {}
6902
- })),
6903
- minio,
6904
- mailpit
6905
- };
6831
+ function getGeneratedSecret(state, appName, secretName) {
6832
+ return state?.generatedSecrets?.[appName]?.[secretName];
6906
6833
  }
6907
6834
  /**
6908
- * `externalServices`, refusing a stage that lacks anything.
6909
- *
6910
- * @throws {ExternalServicesNotConfigured} naming every missing key
6835
+ * Set a generated secret for an app (mutates state)
6911
6836
  */
6912
- function assertExternalServices(input) {
6913
- const services = externalServices(input);
6914
- if (services.missing.length > 0) throw new ExternalServicesNotConfigured(input.stage, services.missing);
6915
- return services;
6916
- }
6917
- /** The dev services a run uses, one entry per service it runs. */
6918
- function devServicesUsed(services) {
6919
- const used = [];
6920
- if (services.mailpit.length > 0) used.push({
6921
- service: "mailpit",
6922
- ids: services.mailpit
6923
- });
6924
- if (services.minio.length > 0) used.push({
6925
- service: "minio",
6926
- ids: services.minio
6927
- });
6928
- return used;
6837
+ function setGeneratedSecret(state, appName, secretName, value) {
6838
+ if (!state.generatedSecrets) state.generatedSecrets = {};
6839
+ if (!state.generatedSecrets[appName]) state.generatedSecrets[appName] = {};
6840
+ state.generatedSecrets[appName][secretName] = value;
6929
6841
  }
6930
- /** The line a run prints for each dev service a deployed stage uses. */
6931
- function devServiceWarning(stage, use) {
6932
- return `⚠️ DEV SERVICE ON A DEPLOYED STAGE (${stage}): ${use.service === "mailpit" ? `Mailpit is catching mail for ${use.ids.join(", ")}. It delivers NO mail: nobody receives a sign-in link, a receipt or a reset` : `MinIO is storing ${use.ids.join(", ")}. Every object is on one container's disk, with no replication and no backup`}. It is not production-grade — set the stage's own keys in its secrets for that.`;
6842
+ /**
6843
+ * Set DNS verification record for a hostname (mutates state)
6844
+ */
6845
+ function setDnsVerification(state, hostname, serverIp) {
6846
+ if (!state.dnsVerified) state.dnsVerified = {};
6847
+ state.dnsVerified[hostname] = {
6848
+ serverIp,
6849
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
6850
+ };
6933
6851
  }
6934
6852
  /**
6935
- * Report each dev service a run uses: a loud line, and a `dev-service.used`
6936
- * event a host can act on.
6853
+ * Check if a hostname is already verified with the given IP
6937
6854
  */
6938
- function reportDevServices(ctx, uses) {
6939
- for (const use of uses) {
6940
- ctx.logger.warn(`\n${devServiceWarning(ctx.stage, use)}`);
6941
- ctx.emit({
6942
- type: "dev-service.used",
6943
- service: use.service,
6944
- stage: ctx.stage,
6945
- constructs: use.ids
6946
- });
6947
- }
6855
+ function isDnsVerified(state, hostname, serverIp) {
6856
+ return (state?.dnsVerified?.[hostname])?.serverIp === serverIp;
6948
6857
  }
6949
- //#endregion
6950
- //#region src/deploy/actor.ts
6951
6858
  /**
6952
- * Who wrote a stage's deploy state: a GitHub Actions run, or a person at a
6953
- * machine. Recorded on every state write (`updatedBy`), on every resource
6954
- * record and on every release (`releasedBy`), so "who put this here" has an
6955
- * answer that does not depend on anyone's memory.
6859
+ * Get the key for a DNS record in state
6956
6860
  */
6957
- /** Whether `env` is a CI job — GitHub Actions or any runner that sets `CI`. */
6958
- function isCi(env = process.env) {
6959
- return env.GITHUB_ACTIONS === "true" || env.CI === "true";
6861
+ function getDnsRecordKey(name, type) {
6862
+ return `${name}:${type}`;
6960
6863
  }
6961
- /** Who this process is writing as. */
6962
- function currentActor(env = process.env) {
6963
- if (env.GITHUB_ACTIONS === "true") {
6964
- const server = env.GITHUB_SERVER_URL ?? "https://github.com";
6965
- return {
6966
- kind: "github",
6967
- actor: env.GITHUB_ACTOR ?? "unknown",
6968
- run: `${server}/${env.GITHUB_REPOSITORY ?? "unknown"}/actions/runs/${env.GITHUB_RUN_ID ?? "unknown"}`,
6969
- ...env.GITHUB_WORKFLOW ? { workflow: env.GITHUB_WORKFLOW } : {}
6970
- };
6971
- }
6972
- let user = "unknown";
6973
- try {
6974
- user = userInfo().username;
6975
- } catch {}
6976
- return {
6977
- kind: "local",
6978
- user,
6979
- host: hostname()
6864
+ /**
6865
+ * Set a created DNS record in state (mutates state)
6866
+ */
6867
+ function setDnsRecord(state, record) {
6868
+ if (!state.dnsRecords) state.dnsRecords = {};
6869
+ const key = getDnsRecordKey(record.name, record.type);
6870
+ state.dnsRecords[key] = {
6871
+ ...record,
6872
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
6980
6873
  };
6981
6874
  }
6982
- /** `octocat (deploy, https://github.com/…/runs/1)` or `ada@laptop`. */
6983
- function describeActor(actor) {
6984
- if (!actor) return "unknown";
6985
- if (actor.kind === "local") return `${actor.user}@${actor.host}`;
6986
- return `${actor.actor} (${actor.workflow ? `${actor.workflow}, ` : ""}${actor.run})`;
6875
+ /**
6876
+ * Get backup state from state
6877
+ */
6878
+ function getBackupState(state) {
6879
+ return state?.backups;
6987
6880
  }
6988
- //#endregion
6989
- //#region src/deploy/dnsResources.ts
6990
- /** The resource type of a DNS record gkm wrote. */
6991
- const DNS_RECORD_RESOURCE = "dns-record";
6992
- /** A record's full name: `api.example.com`, or the domain for `@`. */
6993
- function dnsRecordFqdn(domain, name) {
6994
- return name === "@" || name === "" ? domain : `${name}.${domain}`;
6881
+ /**
6882
+ * Set backup state (mutates state)
6883
+ */
6884
+ function setBackupState(state, backupState) {
6885
+ state.backups = backupState;
6995
6886
  }
6996
- /** `dns-record:<fqdn>:<type>` */
6997
- function dnsResourceKey(fqdn, type) {
6998
- return `${DNS_RECORD_RESOURCE}:${fqdn.toLowerCase()}:${type.toUpperCase()}`;
6887
+ /**
6888
+ * Set postgres backup ID in state (mutates state)
6889
+ */
6890
+ function setPostgresBackupId(state, backupId) {
6891
+ if (state.backups) state.backups.postgresBackupId = backupId;
6999
6892
  }
7000
- /** The resource record a written DNS record is kept as. */
7001
- function dnsRecordResource(record) {
7002
- const fqdn = dnsRecordFqdn(record.domain, record.name).toLowerCase();
7003
- const type = record.type.toUpperCase();
7004
- const data = {
7005
- domain: record.domain,
7006
- name: record.name,
7007
- value: record.value,
7008
- ttl: record.ttl,
7009
- ...record.provider ? { provider: record.provider } : {}
7010
- };
7011
- return {
7012
- key: dnsResourceKey(fqdn, type),
7013
- type: DNS_RECORD_RESOURCE,
7014
- id: `${fqdn} ${type}`,
7015
- status: "ready",
7016
- data
7017
- };
7018
- }
7019
- /** Records that gkm wrote `record` — or updates the value it holds. */
7020
- async function recordDnsResource(journal, record) {
7021
- const { key, type, id, data } = dnsRecordResource(record);
7022
- await journal.ready({
7023
- key,
7024
- type,
7025
- ...data ? { data } : {}
7026
- }, id);
7027
- }
7028
- /** Forgets a DNS record gkm deleted. */
7029
- async function forgetDnsResource(journal, record) {
7030
- await journal.forget(dnsResourceKey(dnsRecordFqdn(record.domain, record.name), record.type));
6893
+ //#endregion
6894
+ //#region src/target/dokploy/dns/index.ts
6895
+ /**
6896
+ * DNS orchestration for deployments
6897
+ *
6898
+ * Handles automatic DNS record creation for deployed applications.
6899
+ */
6900
+ const logger$1 = output;
6901
+ /**
6902
+ * Check if DNS config is legacy format (single domain with `domain` property)
6903
+ */
6904
+ function isLegacyDnsConfig(config) {
6905
+ return typeof config === "object" && config !== null && "provider" in config && "domain" in config;
7031
6906
  }
7032
6907
  /**
7033
- * The changes a DNS step made, kept: what it created, updated or wrote is
7034
- * recorded, what it deleted is forgotten. A record it found already right is
7035
- * recorded only if gkm wrote it before; one it left to a person is not.
6908
+ * Normalize DNS config to new multi-domain format
7036
6909
  */
7037
- async function recordDnsChanges(journal, changes, providerOf) {
7038
- for (const change of changes) {
7039
- if (change.action === "delete") {
7040
- await forgetDnsResource(journal, change);
7041
- continue;
7042
- }
7043
- const written = change.action === "create" || change.action === "update" || change.action === "write";
7044
- const known = change.action === "unchanged" && journal.record(dnsResourceKey(dnsRecordFqdn(change.domain, change.name), change.type)) !== void 0;
7045
- if (!written && !known || change.value === void 0) continue;
7046
- const provider = providerOf(change.domain);
7047
- await recordDnsResource(journal, {
7048
- domain: change.domain,
7049
- name: change.name,
7050
- type: change.type,
7051
- value: change.value,
7052
- ttl: change.ttl ?? 0,
7053
- ...provider ? { provider } : {}
7054
- });
6910
+ function normalizeDnsConfig(config) {
6911
+ if (isLegacyDnsConfig(config)) {
6912
+ const { domain, ...providerConfig } = config;
6913
+ return { [domain]: providerConfig };
7055
6914
  }
6915
+ return config;
7056
6916
  }
7057
- /** Every DNS record gkm wrote for the stage, from its resource records. */
7058
- function dnsResources(resources) {
7059
- return Object.values(resources).filter((record) => record.type === DNS_RECORD_RESOURCE).map((record) => {
7060
- const data = record.data ?? {};
7061
- const [fqdn = "", type = ""] = (record.id ?? "").split(" ");
7062
- return {
7063
- ...data,
7064
- type,
7065
- fqdn
7066
- };
7067
- }).sort((a, b) => a.fqdn.localeCompare(b.fqdn) || a.type.localeCompare(b.type));
7068
- }
7069
- //#endregion
7070
- //#region src/deploy/StateProvider.ts
7071
6917
  /**
7072
- * Check if value is a StateProvider implementation.
6918
+ * Find the root domain for a hostname from available DNS configs
6919
+ *
6920
+ * @example
6921
+ * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })
6922
+ * // Returns 'geekmidas.com'
7073
6923
  */
7074
- function isStateProvider(value) {
7075
- return typeof value === "object" && value !== null && typeof value.read === "function" && typeof value.write === "function";
6924
+ function findRootDomain(hostname, dnsConfig) {
6925
+ const domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);
6926
+ for (const domain of domains) if (hostname === domain || hostname.endsWith(`.${domain}`)) return domain;
6927
+ return null;
7076
6928
  }
7077
- var StateLocked = class extends GkmError {
7078
- stage;
7079
- holder;
7080
- location;
7081
- constructor(stage, holder, location) {
7082
- const by = holder ? `${holder.owner}@${holder.host} (pid ${holder.pid}) since ${holder.acquiredAt}${holder.operation ? ` for '${holder.operation}'` : ""}` : "a run that did not record who it was";
7083
- super(`Deploy state for stage '${stage}' is locked by ${by} (${location}). Wait for that run to finish; if it crashed, release the lock with \`gkm state:unlock --stage ${stage}\`.`);
7084
- this.stage = stage;
7085
- this.holder = holder;
7086
- this.location = location;
7087
- this.name = "StateLocked";
7088
- }
7089
- };
7090
- var StateVersionConflict = class extends GkmError {
7091
- stage;
7092
- expectedVersion;
7093
- actualVersion;
7094
- constructor(stage, expectedVersion, actualVersion) {
7095
- super(`Deploy state for stage '${stage}' changed since it was read (expected ${expectedVersion ? `version ${expectedVersion}` : "no state"}, found ${actualVersion ? `version ${actualVersion}` : "no state"}). Another run wrote it: read the state again and re-apply the change, and hold the stage's lock so runs take turns.`);
7096
- this.stage = stage;
7097
- this.expectedVersion = expectedVersion;
7098
- this.actualVersion = actualVersion;
7099
- this.name = "StateVersionConflict";
7100
- }
7101
- };
7102
- var StageStateMissing = class extends GkmError {
7103
- stage;
7104
- constructor(stage) {
7105
- super(`There is no deploy state for stage '${stage}' to record a resource in. Write the stage's state first (write with expectedVersion: null).`);
7106
- this.stage = stage;
7107
- this.name = "StageStateMissing";
7108
- }
7109
- };
7110
- var StateUnreadable = class extends GkmError {
7111
- stage;
7112
- location;
7113
- constructor(stage, location, cause) {
7114
- super(`Deploy state for stage '${stage}' at ${location} is not valid JSON. Restore it from a backup (or the provider's history) rather than deploying without it — a deploy without state recreates every resource.`, { cause });
7115
- this.stage = stage;
7116
- this.location = location;
7117
- this.name = "StateUnreadable";
7118
- }
7119
- };
7120
- var StateSchemaTooNew = class extends GkmError {
7121
- stage;
7122
- schemaVersion;
7123
- constructor(stage, schemaVersion) {
7124
- super(`Deploy state for stage '${stage}' has schema version ${String(schemaVersion)}, newer than this @geekmidas/cli understands (3). Upgrade @geekmidas/cli to the version that wrote it.`);
7125
- this.stage = stage;
7126
- this.schemaVersion = schemaVersion;
7127
- this.name = "StateSchemaTooNew";
7128
- }
7129
- };
7130
6929
  /**
7131
- * Not thrown: emitted (once per store) when a custom `StateProvider` stands
7132
- * in for a store, so a deploy that cannot be protected from a concurrent one
7133
- * says so.
6930
+ * Group hostnames by their root domain
7134
6931
  */
7135
- var StateStoreWithoutLocking = class extends GkmError {
7136
- provider;
7137
- constructor(provider) {
7138
- super(`The custom state provider '${provider}' has no lock and no versions, so two deploys of the same stage can still overwrite each other. Implement StateStore (lock, versioned read, conditional write) or use the 'local', 'ssm' or 's3' state provider.`);
7139
- this.provider = provider;
7140
- this.name = "StateStoreWithoutLocking";
7141
- }
7142
- };
7143
- var StateStoreNeedsWorkspaceName = class extends GkmError {
7144
- provider;
7145
- constructor(provider) {
7146
- super(`The '${provider}' state provider keys state by workspace name. Set "name" in gkm.config.ts.`);
7147
- this.provider = provider;
7148
- this.name = "StateStoreNeedsWorkspaceName";
7149
- }
7150
- };
7151
- var UnknownStateProvider = class extends GkmError {
7152
- config;
7153
- constructor(config) {
7154
- super(`Unknown state provider ${JSON.stringify(config)}. Use 'local', 'ssm', 's3', or an object implementing StateStore or StateProvider.`);
7155
- this.config = config;
7156
- this.name = "UnknownStateProvider";
6932
+ function groupHostnamesByDomain(appHostnames, dnsConfig) {
6933
+ const grouped = /* @__PURE__ */ new Map();
6934
+ for (const [appName, hostname] of appHostnames) {
6935
+ const rootDomain = findRootDomain(hostname, dnsConfig);
6936
+ if (!rootDomain) {
6937
+ logger$1.log(` ⚠ No DNS config found for hostname: ${hostname}`);
6938
+ continue;
6939
+ }
6940
+ if (!grouped.has(rootDomain)) grouped.set(rootDomain, /* @__PURE__ */ new Map());
6941
+ grouped.get(rootDomain).set(appName, hostname);
7157
6942
  }
7158
- };
6943
+ return grouped;
6944
+ }
7159
6945
  /**
7160
- * A deploy, setup or rollback of a stage in CI, with the stage's state kept on
7161
- * the runner — which is discarded when the job ends.
6946
+ * Resolve IP address from a hostname
7162
6947
  */
7163
- var LocalStateInCi = class extends GkmError {
7164
- stage;
7165
- operation;
7166
- region;
7167
- constructor(stage, operation, region) {
7168
- super(`\`gkm ${operation}\` would keep stage '${stage}'s deploy state in .gkm/ on this CI runner, and the runner is discarded when the job ends: the next run would start without it — no releases to roll back to, no record of what was created. Keep the state in AWS — in gkm.config.ts:\n\n state: { provider: 'ssm', region: '${region}' },\n\nthen move the state you already have, from the machine that holds it:\n\n gkm state:push --stage ${stage}\n`);
7169
- this.stage = stage;
7170
- this.operation = operation;
7171
- this.region = region;
7172
- this.name = "LocalStateInCi";
7173
- }
7174
- };
7175
- /** A lock or write that could not get at the state backend in time. */
7176
- var StateStoreBusy = class extends GkmError {
7177
- stage;
7178
- location;
7179
- constructor(stage, location) {
7180
- super(`Timed out waiting to write deploy state for stage '${stage}' (${location}). If no other gkm process is running, remove ${location}.`);
7181
- this.stage = stage;
7182
- this.location = location;
7183
- this.name = "StateStoreBusy";
7184
- }
7185
- };
7186
- function decodeDocument(stage, body, location) {
7187
- let parsed;
6948
+ async function resolveHostnameToIp(hostname) {
7188
6949
  try {
7189
- parsed = JSON.parse(body);
6950
+ return (await lookup(hostname, { family: 4 })).address;
7190
6951
  } catch (error) {
7191
- throw new StateUnreadable(stage, location, error);
6952
+ throw new Error(`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : "Unknown error"}`);
7192
6953
  }
7193
- if (typeof parsed !== "object" || parsed === null) throw new StateUnreadable(stage, location, parsed);
7194
- const schemaVersion = parsed.schemaVersion;
7195
- if (schemaVersion === void 0) return {
7196
- schemaVersion: 1,
7197
- state: parsed
7198
- };
7199
- if (schemaVersion === 2) return {
7200
- schemaVersion: 2,
7201
- document: parsed
7202
- };
7203
- if (schemaVersion === 3) return {
7204
- schemaVersion: 3,
7205
- document: parsed
7206
- };
7207
- throw new StateSchemaTooNew(stage, schemaVersion);
7208
- }
7209
- function encodeDocument(document) {
7210
- return JSON.stringify(document, null, 2);
7211
6954
  }
7212
6955
  /**
7213
- * v1 state as a v2 document. The ids v1 kept are seeded as `ready` records,
7214
- * so the first journaled deploy after an upgrade adopts them rather than
7215
- * treating them as unknown.
6956
+ * Extract subdomain from full hostname relative to root domain
6957
+ *
6958
+ * @example
6959
+ * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'
6960
+ * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'
7216
6961
  */
7217
- function migrateV1(stage, state) {
7218
- const now = (/* @__PURE__ */ new Date()).toISOString();
7219
- const resources = {};
7220
- const seed = (type, name, id) => {
7221
- if (!id) return;
7222
- const key = name ? `${type}:${name}` : type;
7223
- resources[key] = {
7224
- key,
7225
- type,
7226
- id,
7227
- status: "ready",
7228
- updatedAt: now
7229
- };
7230
- };
7231
- seed("project", null, state.projectId);
7232
- seed("environment", null, state.environmentId);
7233
- for (const [app, id] of Object.entries(state.applications ?? {})) seed("application", app, id);
7234
- seed("postgres", null, state.services?.postgresId);
7235
- seed("redis", null, state.services?.redisId);
7236
- seed("backup-destination", null, state.backups?.destinationId);
7237
- return {
7238
- schemaVersion: 2,
7239
- stage,
7240
- serial: 1,
7241
- state,
7242
- resources,
7243
- updatedAt: now
7244
- };
6962
+ function extractSubdomain(hostname, rootDomain) {
6963
+ if (!hostname.endsWith(rootDomain)) throw new Error(`Hostname ${hostname} is not under root domain ${rootDomain}`);
6964
+ return hostname.slice(0, -(rootDomain.length + 1)) || "@";
7245
6965
  }
7246
- const isEmpty = (value) => !value || Object.keys(value).length === 0;
7247
6966
  /**
7248
- * Whether a v2 state in the Dokploy shape was written by the compose target.
7249
- *
7250
- * Before v3 every target wrote the Dokploy shape, and compose filled none of
7251
- * its Dokploy fields. So the rule is the shape's content, not the target the
7252
- * workspace names now: a state whose every Dokploy-only field is empty — no
7253
- * project or environment id, no application or service ids, no credentials,
7254
- * generated secrets, backups or registry — holds nothing only Dokploy could
7255
- * use, and reading it as compose loses nothing. One with any of them was
7256
- * written by Dokploy and is kept exactly as it is.
7257
- *
7258
- * The configured target is not used: a document decodes the same wherever it
7259
- * is read (`state:show`, `state:push`) without a workspace, a stage can be
7260
- * moved between targets, and `--target` can override a run.
6967
+ * Generate required DNS records for a deployment
7261
6968
  */
7262
- function writtenByCompose(state) {
7263
- return !state.projectId && !state.environmentId && isEmpty(state.applications) && !state.services?.postgresId && !state.services?.redisId && isEmpty(state.appCredentials) && isEmpty(state.generatedSecrets) && !state.backups && !state.registryId;
6969
+ function generateRequiredRecords(appHostnames, rootDomain, serverIp) {
6970
+ const records = [];
6971
+ for (const [appName, hostname] of appHostnames) {
6972
+ const subdomain = extractSubdomain(hostname, rootDomain);
6973
+ records.push({
6974
+ hostname,
6975
+ subdomain,
6976
+ type: "A",
6977
+ value: serverIp,
6978
+ appName
6979
+ });
6980
+ }
6981
+ return records;
7264
6982
  }
7265
6983
  /**
7266
- * A v2 state and its records as v3 keeps them. A compose-written state
7267
- * becomes the compose shape: its `dnsRecords` become `dns-record` resources,
7268
- * and `dnsVerified` and the empty Dokploy fields go — the DNS check is made
7269
- * on every deploy. A Dokploy state is returned as it is.
6984
+ * Print DNS records table
7270
6985
  */
7271
- function upgradeV2State(state, resources) {
7272
- if (!writtenByCompose(state)) return {
7273
- state,
7274
- resources
7275
- };
7276
- const compose = {
7277
- provider: "compose",
7278
- stage: state.stage,
7279
- lastDeployedAt: state.lastDeployedAt,
7280
- ...state.identity ? { identity: state.identity } : {},
7281
- ...state.releases ? { releases: state.releases } : {}
7282
- };
7283
- const upgraded = { ...resources };
7284
- for (const record of Object.values(state.dnsRecords ?? {})) {
7285
- const resource = migratedDnsResource(record);
7286
- upgraded[resource.key] = resource;
6986
+ function printDnsRecordsTable(records, rootDomain) {
6987
+ logger$1.log(`\n 📋 DNS Records for ${rootDomain}:`);
6988
+ logger$1.log(" ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐");
6989
+ logger$1.log(" │ Subdomain │ Type │ Value │ Status │");
6990
+ logger$1.log(" ├─────────────────────────────────────┼──────┼─────────────────┼────────┤");
6991
+ for (const record of records) {
6992
+ const subdomain = record.subdomain.padEnd(35);
6993
+ const type = record.type.padEnd(4);
6994
+ const value = record.value.padEnd(15);
6995
+ let status;
6996
+ if (record.error) status = "✗";
6997
+ else if (record.created) status = "✓ new";
6998
+ else if (record.existed) status = "✓";
6999
+ else status = "?";
7000
+ logger$1.log(` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`);
7287
7001
  }
7288
- return {
7289
- state: compose,
7290
- resources: upgraded
7291
- };
7292
- }
7293
- /** A v2 `dnsRecords` entry as the `dns-record` resource v3 keeps. */
7294
- function migratedDnsResource(record) {
7295
- return {
7296
- ...dnsRecordResource({
7297
- domain: record.domain,
7298
- name: record.name,
7299
- type: record.type,
7300
- value: record.value,
7301
- ttl: record.ttl
7302
- }),
7303
- updatedAt: record.createdAt
7304
- };
7305
- }
7306
- /** A v2 document as v3 — not written until the next write. */
7307
- function migrateV2(document) {
7308
- const { state, resources } = upgradeV2State(document.state, document.resources);
7309
- return {
7310
- schemaVersion: 3,
7311
- stage: document.stage,
7312
- serial: document.serial,
7313
- state,
7314
- resources,
7315
- updatedAt: document.updatedAt,
7316
- history: []
7317
- };
7318
- }
7319
- function newLockHolder(options) {
7320
- let owner = "unknown";
7321
- try {
7322
- owner = userInfo().username;
7323
- } catch {}
7324
- return {
7325
- id: randomUUID(),
7326
- owner,
7327
- host: hostname(),
7328
- pid: process.pid,
7329
- acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
7330
- operation: options?.operation
7331
- };
7332
- }
7333
- function contentVersion(body) {
7334
- return createHash("sha256").update(body).digest("hex").slice(0, 16);
7002
+ logger$1.log(" └─────────────────────────────────────┴──────┴─────────────────┴────────┘");
7335
7003
  }
7336
7004
  /**
7337
- * `history` with this write at its head. A run makes many writes — one per
7338
- * resource it journals — so a run is one entry: a write by the run that
7339
- * wrote the newest entry (the same lock) replaces it, and any other is
7340
- * added. Without a lock, each write is its own entry.
7005
+ * Print DNS records in a simple format for manual setup
7341
7006
  */
7342
- function appendHistory(history, entry, sameRun) {
7343
- return [entry, ...sameRun ? history.slice(1) : history].slice(0, 20);
7007
+ function printDnsRecordsSimple(records, rootDomain) {
7008
+ logger$1.log("\n 📋 Required DNS Records:");
7009
+ logger$1.log(` Add these A records to your DNS provider (${rootDomain}):\n`);
7010
+ for (const record of records) logger$1.log(` ${record.subdomain} → ${record.value} (A record)`);
7011
+ logger$1.log("");
7344
7012
  }
7345
7013
  /**
7346
- * A store over a backend that can read and conditionally write one blob per
7347
- * stage, and create a lock object only if it does not exist. Migration,
7348
- * resource records and history are the same for every such backend, so they
7349
- * live here.
7014
+ * Create DNS records for a single domain using its configured provider
7350
7015
  */
7351
- var DocumentStateStore = class {
7352
- /** The lock this store holds for each stage — what its writes are for. */
7353
- held = /* @__PURE__ */ new Map();
7354
- /** Per stage, the lock whose run wrote the newest history entry. */
7355
- logged = /* @__PURE__ */ new Map();
7356
- /** Who this store writes as. */
7357
- actor() {
7358
- return currentActor();
7359
- }
7360
- async lock(stage, options) {
7361
- const holder = newLockHolder(options);
7362
- await this.createLock(stage, holder);
7363
- this.held.set(stage, holder);
7364
- let released = false;
7365
- return {
7366
- stage,
7367
- holder,
7368
- release: async () => {
7369
- if (released) return;
7370
- released = true;
7371
- if (this.held.get(stage)?.id === holder.id) this.held.delete(stage);
7372
- await this.removeLock(stage, holder);
7373
- }
7374
- };
7375
- }
7376
- async forceUnlock(stage) {
7377
- const holder = await this.readLock(stage);
7378
- await this.removeLock(stage, null);
7379
- return holder;
7380
- }
7381
- async read(stage) {
7382
- const current = await this.readDocument(stage);
7383
- if (!current) return null;
7384
- return {
7385
- state: current.document.state,
7386
- resources: current.document.resources,
7387
- history: current.document.history,
7388
- version: current.version
7389
- };
7390
- }
7391
- async write(stage, state, options) {
7392
- if (options.expectedVersion === null) {
7393
- const document = this.stamp(stage, {
7394
- schemaVersion: 3,
7395
- stage,
7396
- serial: 1,
7397
- state,
7398
- resources: {},
7399
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
7400
- history: []
7401
- });
7402
- return this.writeRaw(stage, encodeDocument(document), null);
7403
- }
7404
- return this.mutate(stage, options.expectedVersion, (document) => ({
7405
- ...document,
7406
- state
7407
- }));
7408
- }
7409
- async putResource(stage, record, options) {
7410
- return this.mutate(stage, options?.expectedVersion, (document) => ({
7411
- ...document,
7412
- resources: {
7413
- ...document.resources,
7414
- [record.key]: {
7415
- ...record,
7416
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
7417
- updatedBy: this.actor()
7418
- }
7419
- }
7420
- }));
7421
- }
7422
- async deleteResource(stage, key, options) {
7423
- return this.mutate(stage, options?.expectedVersion, (document) => {
7424
- const { [key]: _removed, ...resources } = document.resources;
7425
- return {
7426
- ...document,
7427
- resources
7428
- };
7429
- });
7430
- }
7431
- /** `document` as this write leaves it: who wrote it, in its history. */
7432
- stamp(stage, document) {
7433
- const by = this.actor();
7434
- const holder = this.held.get(stage);
7435
- const operation = holder?.operation ?? "write";
7436
- const history = document.history ?? [];
7437
- const sameRun = holder !== void 0 && this.logged.get(stage) === holder.id && history[0]?.operation === operation;
7438
- if (holder) this.logged.set(stage, holder.id);
7439
- return {
7440
- ...document,
7441
- updatedBy: by,
7442
- history: appendHistory(history, {
7443
- serial: document.serial,
7444
- at: document.updatedAt,
7445
- by,
7446
- operation
7447
- }, sameRun)
7448
- };
7449
- }
7450
- async mutate(stage, expectedVersion, change) {
7451
- const current = await this.readDocument(stage);
7452
- if (!current) {
7453
- if (expectedVersion !== void 0) throw new StateVersionConflict(stage, expectedVersion, null);
7454
- throw new StageStateMissing(stage);
7455
- }
7456
- if (expectedVersion !== void 0 && current.version !== expectedVersion) throw new StateVersionConflict(stage, expectedVersion, current.version);
7457
- const next = change(current.document);
7458
- next.schemaVersion = 3;
7459
- next.serial = current.document.serial + 1;
7460
- next.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
7461
- return this.writeRaw(stage, encodeDocument(this.stamp(stage, next)), current.version);
7462
- }
7463
- /**
7464
- * Reads the stage's document as v3. A v1 document is migrated in place on
7465
- * the way — itself a conditional write: if another run migrated (or wrote)
7466
- * first, its result is read instead. A v2 document is upgraded in memory
7467
- * and written as v3 by the next write.
7468
- */
7469
- async readDocument(stage, attempt = 0) {
7470
- const raw = await this.readRaw(stage);
7471
- if (!raw) return null;
7472
- const decoded = decodeDocument(stage, raw.body, this.location(stage));
7473
- if (decoded.schemaVersion === 3) return {
7474
- document: decoded.document,
7475
- version: raw.version
7476
- };
7477
- if (decoded.schemaVersion === 2) return {
7478
- document: migrateV2(decoded.document),
7479
- version: raw.version
7480
- };
7481
- await this.writeV1Backup(stage, raw.body);
7482
- const document = this.stamp(stage, migrateV2(migrateV1(stage, decoded.state)));
7483
- try {
7484
- return {
7485
- document,
7486
- version: await this.writeRaw(stage, encodeDocument(document), raw.version)
7487
- };
7488
- } catch (error) {
7489
- if (error instanceof StateVersionConflict && attempt < 2) return this.readDocument(stage, attempt + 1);
7490
- throw error;
7491
- }
7492
- }
7493
- };
7494
- /** Whether `config` keeps state on this machine — `local`, or none given. */
7495
- function isLocalState(config) {
7496
- return !config || config.provider === "local";
7497
- }
7498
- /**
7499
- * Refuses, with `LocalStateInCi`, a run that would write a deployed stage's
7500
- * state to a CI runner's disk — the local stage, which runs on the runner
7501
- * itself, is exempt. Local use is untouched. The region the message
7502
- * suggests is the secrets store's, when the workspace keeps them in AWS.
7503
- */
7504
- function assertStateOutlivesRun(workspace, stage, operation, env = process.env) {
7505
- if (stage === workspace.stages?.local) return;
7506
- if (!isCi(env) || !isLocalState(workspace.state)) return;
7507
- const store = workspace.secrets?.store;
7508
- throw new LocalStateInCi(stage, operation, typeof store === "object" && store && typeof store.region === "string" ? store.region : "<region>");
7509
- }
7510
- function isStateStore(value) {
7511
- return typeof value === "object" && value !== null && typeof value.lock === "function" && typeof value.read === "function" && typeof value.write === "function" && typeof value.putResource === "function";
7512
- }
7513
- /**
7514
- * The store for a workspace's `state` config:
7515
- *
7516
- * - none / `'local'`: `LocalStateStore` under `.gkm/`
7517
- * - `'ssm'`: `SSMStateStore`, with no local cache — SSM is read directly, so
7518
- * a stale local copy can never win over it
7519
- * - `'s3'`: `S3StateStore`
7520
- * - a `StateStore` object: used as is
7521
- * - a `StateProvider` object: wrapped by `LegacyStateStore`
7522
- */
7523
- async function createStateStore(options) {
7524
- const { config, workspaceRoot, workspaceName } = options;
7525
- if (!config || config.provider === "local") {
7526
- const { LocalStateStore } = await import("./LocalStateStore-D40_SDmJ.mjs").then((n) => n.n);
7527
- return new LocalStateStore(workspaceRoot);
7528
- }
7529
- if (isStateStore(config.provider)) return config.provider;
7530
- if (isStateProvider(config.provider)) {
7531
- const { LegacyStateStore } = await import("./LegacyStateStore-CtwO7fwy.mjs");
7532
- return new LegacyStateStore(config.provider, { warn: options.warn });
7533
- }
7534
- if (config.provider === "ssm") {
7535
- if (!workspaceName) throw new StateStoreNeedsWorkspaceName("ssm");
7536
- const { SSMStateStore } = await import("./SSMStateStore-k_Ew7TWx.mjs");
7537
- const ssm = config;
7538
- return SSMStateStore.create({
7539
- workspaceName,
7540
- region: ssm.region,
7541
- profile: ssm.profile
7542
- });
7543
- }
7544
- if (config.provider === "s3") {
7545
- if (!workspaceName) throw new StateStoreNeedsWorkspaceName("s3");
7546
- const { S3StateStore } = await import("./S3StateStore-BzS0IeSt.mjs");
7547
- const s3 = config;
7548
- return S3StateStore.create({
7549
- workspaceName,
7550
- bucket: s3.bucket,
7551
- prefix: s3.prefix,
7552
- region: s3.region,
7553
- profile: s3.profile
7554
- });
7555
- }
7556
- throw new UnknownStateProvider(config);
7557
- }
7558
- //#endregion
7559
- //#region src/target/dokploy/dns/DnsProvider.ts
7560
- /**
7561
- * Check if value is a DnsProvider implementation.
7562
- */
7563
- function isDnsProvider(value) {
7564
- return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.getRecords === "function" && typeof value.upsertRecords === "function" && typeof value.deleteRecords === "function";
7565
- }
7566
- /**
7567
- * Create a DNS provider based on configuration.
7568
- *
7569
- * - 'hostinger': HostingerProvider
7570
- * - 'route53': Route53Provider
7571
- * - 'godaddy': GoDaddyProvider
7572
- * - 'manual': Returns null (user handles DNS)
7573
- * - Custom: Use provided DnsProvider implementation
7574
- */
7575
- async function createDnsProvider(options) {
7576
- const { config } = options;
7577
- if (config.provider === "manual") return null;
7578
- if (isDnsProvider(config.provider)) return config.provider;
7579
- const provider = config.provider;
7580
- if (provider === "hostinger") {
7581
- const { HostingerProvider } = await import("./HostingerProvider-1mqD6aG8.mjs");
7582
- return new HostingerProvider();
7583
- }
7584
- if (provider === "route53") {
7585
- const { Route53Provider } = await import("./Route53Provider-QXxjkZO1.mjs");
7586
- const route53Config = config;
7587
- return new Route53Provider({
7588
- region: route53Config.region,
7589
- profile: route53Config.profile,
7590
- hostedZoneId: route53Config.hostedZoneId
7591
- });
7592
- }
7593
- if (provider === "godaddy") {
7594
- const { GoDaddyProvider } = await import("./GoDaddyProvider-Mi3vptSR.mjs");
7595
- return new GoDaddyProvider(options.godaddy ?? {});
7596
- }
7597
- if (provider === "cloudflare") throw new DnsProviderNotImplemented("cloudflare");
7598
- throw new DnsProviderUnknown(config);
7599
- }
7600
- /**
7601
- * The provider's credentials can write records and not read them — a key
7602
- * scoped to updates only. What reads them falls back to writing every record,
7603
- * which is idempotent, without a diff.
7604
- */
7605
- var DnsRecordsUnreadable = class extends GkmError {
7606
- provider;
7607
- domain;
7608
- reason;
7609
- constructor(provider, domain, reason) {
7610
- super(`The ${provider} key cannot read ${domain}'s DNS records (${reason}), so changes cannot be compared with what is there: every record is written, which leaves one that already has its value as it was.`);
7611
- this.provider = provider;
7612
- this.domain = domain;
7613
- this.reason = reason;
7614
- this.name = "DnsRecordsUnreadable";
7615
- }
7616
- };
7617
- /** A DNS provider gkm names and does not have yet. */
7618
- var DnsProviderNotImplemented = class extends Error {
7619
- provider;
7620
- constructor(provider) {
7621
- super(`The ${provider} DNS provider is not implemented yet. Use 'route53', 'godaddy', 'hostinger' or 'manual' for this domain in dns, or pass your own DnsProvider object.`);
7622
- this.provider = provider;
7623
- this.name = "DnsProviderNotImplemented";
7624
- }
7625
- };
7626
- /** A `provider:` that is none of the built-ins, nor a DnsProvider object. */
7627
- var DnsProviderUnknown = class extends GkmError {
7628
- config;
7629
- constructor(config) {
7630
- super(`Unknown DNS provider: ${JSON.stringify(config)}. dns takes 'route53', 'godaddy', 'hostinger', 'manual', or an object implementing DnsProvider.`);
7631
- this.config = config;
7632
- this.name = "DnsProviderUnknown";
7633
- }
7634
- };
7635
- //#endregion
7636
- //#region src/deploy/state.ts
7637
- /**
7638
- * Create a new empty state for a stage
7639
- */
7640
- function createEmptyState(stage, projectId, environmentId) {
7641
- return {
7642
- provider: "dokploy",
7643
- stage,
7644
- projectId,
7645
- environmentId,
7646
- applications: {},
7647
- services: {},
7648
- lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
7649
- };
7650
- }
7651
- /** A new compose stage's state. */
7652
- function createComposeState(stage) {
7653
- return {
7654
- provider: "compose",
7655
- stage,
7656
- lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
7657
- };
7658
- }
7659
- /**
7660
- * `state` as the Dokploy target keeps it. A stage whose state another target
7661
- * wrote — one moved from compose to Dokploy — keeps its core (releases,
7662
- * identity) and starts with no Dokploy ids, as a first deploy would.
7663
- */
7664
- function asDokployState(state) {
7665
- if (state.provider === "dokploy") return state;
7666
- const { provider: _provider, ...core } = state;
7667
- return {
7668
- ...core,
7669
- provider: "dokploy",
7670
- projectId: "",
7671
- environmentId: "",
7672
- applications: {},
7673
- services: {}
7674
- };
7675
- }
7676
- /**
7677
- * Set application ID in state (mutates state)
7678
- */
7679
- function setApplicationId(state, appName, applicationId) {
7680
- state.applications[appName] = applicationId;
7681
- }
7682
- /** Two records naming the same image: by digest when both have one. */
7683
- function sameImage(a, b) {
7684
- return a.digest && b.digest ? a.digest === b.digest : a.ref === b.ref;
7685
- }
7686
- /** The newest release in `history` after `index` that a rollback may restore. */
7687
- function restorable(history, index, current) {
7688
- return history.slice(index + 1).find((entry) => !entry.rolledBack && !sameImage(entry, current));
7689
- }
7690
- /**
7691
- * Record that `image` went live for `appName` (mutates state): it becomes
7692
- * `current`, and what was current becomes `previous`. Releasing what already
7693
- * runs — a redeploy of the same digest — changes nothing.
7694
- */
7695
- function recordRelease(state, appName, image, by, releasedAt = /* @__PURE__ */ new Date()) {
7696
- const releases = state.releases?.[appName];
7697
- if (releases && sameImage(releases.current, image)) return;
7698
- const entry = {
7699
- ...image,
7700
- releasedAt: releasedAt.toISOString(),
7701
- releasedBy: by
7702
- };
7703
- const history = [entry, ...releases?.history ?? []].slice(0, 10);
7704
- const previous = releases?.current;
7705
- state.releases = {
7706
- ...state.releases,
7707
- [appName]: {
7708
- current: entry,
7709
- ...previous ? { previous } : {},
7710
- history
7711
- }
7712
- };
7713
- }
7714
- /**
7715
- * Record that `appName` was rolled back to `to` (mutates state): every
7716
- * release newer than it is marked rolled back, so neither this rollback nor
7717
- * a later one restores it, and `previous` moves to the release before `to`.
7718
- */
7719
- function recordRollback(state, appName, to) {
7720
- const releases = state.releases?.[appName];
7721
- if (!releases) return;
7722
- const index = releases.history.findIndex((entry) => !entry.rolledBack && sameImage(entry, to));
7723
- if (index === -1) return;
7724
- const history = releases.history.map((entry, i) => i < index ? {
7725
- ...entry,
7726
- rolledBack: true
7727
- } : entry);
7728
- const current = history[index];
7729
- const previous = restorable(history, index, current);
7730
- state.releases = {
7731
- ...state.releases,
7732
- [appName]: {
7733
- current,
7734
- ...previous ? { previous } : {},
7735
- history
7736
- }
7737
- };
7738
- }
7739
- /**
7740
- * Get a generated secret for an app
7741
- */
7742
- function getGeneratedSecret(state, appName, secretName) {
7743
- return state?.generatedSecrets?.[appName]?.[secretName];
7744
- }
7745
- /**
7746
- * Set a generated secret for an app (mutates state)
7747
- */
7748
- function setGeneratedSecret(state, appName, secretName, value) {
7749
- if (!state.generatedSecrets) state.generatedSecrets = {};
7750
- if (!state.generatedSecrets[appName]) state.generatedSecrets[appName] = {};
7751
- state.generatedSecrets[appName][secretName] = value;
7752
- }
7753
- /**
7754
- * Set DNS verification record for a hostname (mutates state)
7755
- */
7756
- function setDnsVerification(state, hostname, serverIp) {
7757
- if (!state.dnsVerified) state.dnsVerified = {};
7758
- state.dnsVerified[hostname] = {
7759
- serverIp,
7760
- verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
7761
- };
7762
- }
7763
- /**
7764
- * Check if a hostname is already verified with the given IP
7765
- */
7766
- function isDnsVerified(state, hostname, serverIp) {
7767
- return (state?.dnsVerified?.[hostname])?.serverIp === serverIp;
7768
- }
7769
- /**
7770
- * Get the key for a DNS record in state
7771
- */
7772
- function getDnsRecordKey(name, type) {
7773
- return `${name}:${type}`;
7774
- }
7775
- /**
7776
- * Set a created DNS record in state (mutates state)
7777
- */
7778
- function setDnsRecord(state, record) {
7779
- if (!state.dnsRecords) state.dnsRecords = {};
7780
- const key = getDnsRecordKey(record.name, record.type);
7781
- state.dnsRecords[key] = {
7782
- ...record,
7783
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
7784
- };
7785
- }
7786
- /**
7787
- * Get backup state from state
7788
- */
7789
- function getBackupState(state) {
7790
- return state?.backups;
7791
- }
7792
- /**
7793
- * Set backup state (mutates state)
7794
- */
7795
- function setBackupState(state, backupState) {
7796
- state.backups = backupState;
7797
- }
7798
- /**
7799
- * Set postgres backup ID in state (mutates state)
7800
- */
7801
- function setPostgresBackupId(state, backupId) {
7802
- if (state.backups) state.backups.postgresBackupId = backupId;
7803
- }
7804
- //#endregion
7805
- //#region src/target/dokploy/dns/index.ts
7806
- /**
7807
- * DNS orchestration for deployments
7808
- *
7809
- * Handles automatic DNS record creation for deployed applications.
7810
- */
7811
- const logger$1 = output;
7812
- /**
7813
- * Check if DNS config is legacy format (single domain with `domain` property)
7814
- */
7815
- function isLegacyDnsConfig(config) {
7816
- return typeof config === "object" && config !== null && "provider" in config && "domain" in config;
7817
- }
7818
- /**
7819
- * Normalize DNS config to new multi-domain format
7820
- */
7821
- function normalizeDnsConfig(config) {
7822
- if (isLegacyDnsConfig(config)) {
7823
- const { domain, ...providerConfig } = config;
7824
- return { [domain]: providerConfig };
7825
- }
7826
- return config;
7827
- }
7828
- /**
7829
- * Find the root domain for a hostname from available DNS configs
7830
- *
7831
- * @example
7832
- * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })
7833
- * // Returns 'geekmidas.com'
7834
- */
7835
- function findRootDomain(hostname, dnsConfig) {
7836
- const domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);
7837
- for (const domain of domains) if (hostname === domain || hostname.endsWith(`.${domain}`)) return domain;
7838
- return null;
7839
- }
7840
- /**
7841
- * Group hostnames by their root domain
7842
- */
7843
- function groupHostnamesByDomain(appHostnames, dnsConfig) {
7844
- const grouped = /* @__PURE__ */ new Map();
7845
- for (const [appName, hostname] of appHostnames) {
7846
- const rootDomain = findRootDomain(hostname, dnsConfig);
7847
- if (!rootDomain) {
7848
- logger$1.log(` ⚠ No DNS config found for hostname: ${hostname}`);
7849
- continue;
7850
- }
7851
- if (!grouped.has(rootDomain)) grouped.set(rootDomain, /* @__PURE__ */ new Map());
7852
- grouped.get(rootDomain).set(appName, hostname);
7853
- }
7854
- return grouped;
7855
- }
7856
- /**
7857
- * Resolve IP address from a hostname
7858
- */
7859
- async function resolveHostnameToIp(hostname) {
7860
- try {
7861
- return (await lookup(hostname, { family: 4 })).address;
7862
- } catch (error) {
7863
- throw new Error(`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : "Unknown error"}`);
7864
- }
7865
- }
7866
- /**
7867
- * Extract subdomain from full hostname relative to root domain
7868
- *
7869
- * @example
7870
- * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'
7871
- * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'
7872
- */
7873
- function extractSubdomain(hostname, rootDomain) {
7874
- if (!hostname.endsWith(rootDomain)) throw new Error(`Hostname ${hostname} is not under root domain ${rootDomain}`);
7875
- return hostname.slice(0, -(rootDomain.length + 1)) || "@";
7876
- }
7877
- /**
7878
- * Generate required DNS records for a deployment
7879
- */
7880
- function generateRequiredRecords(appHostnames, rootDomain, serverIp) {
7881
- const records = [];
7882
- for (const [appName, hostname] of appHostnames) {
7883
- const subdomain = extractSubdomain(hostname, rootDomain);
7884
- records.push({
7885
- hostname,
7886
- subdomain,
7887
- type: "A",
7888
- value: serverIp,
7889
- appName
7890
- });
7891
- }
7892
- return records;
7893
- }
7894
- /**
7895
- * Print DNS records table
7896
- */
7897
- function printDnsRecordsTable(records, rootDomain) {
7898
- logger$1.log(`\n 📋 DNS Records for ${rootDomain}:`);
7899
- logger$1.log(" ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐");
7900
- logger$1.log(" │ Subdomain │ Type │ Value │ Status │");
7901
- logger$1.log(" ├─────────────────────────────────────┼──────┼─────────────────┼────────┤");
7902
- for (const record of records) {
7903
- const subdomain = record.subdomain.padEnd(35);
7904
- const type = record.type.padEnd(4);
7905
- const value = record.value.padEnd(15);
7906
- let status;
7907
- if (record.error) status = "✗";
7908
- else if (record.created) status = "✓ new";
7909
- else if (record.existed) status = "✓";
7910
- else status = "?";
7911
- logger$1.log(` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`);
7912
- }
7913
- logger$1.log(" └─────────────────────────────────────┴──────┴─────────────────┴────────┘");
7914
- }
7915
- /**
7916
- * Print DNS records in a simple format for manual setup
7917
- */
7918
- function printDnsRecordsSimple(records, rootDomain) {
7919
- logger$1.log("\n 📋 Required DNS Records:");
7920
- logger$1.log(` Add these A records to your DNS provider (${rootDomain}):\n`);
7921
- for (const record of records) logger$1.log(` ${record.subdomain} → ${record.value} (A record)`);
7922
- logger$1.log("");
7923
- }
7924
- /**
7925
- * Create DNS records for a single domain using its configured provider
7926
- */
7927
- async function createDnsRecordsForDomain(records, rootDomain, providerConfig) {
7928
- const ttl = "ttl" in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;
7929
- let provider;
7930
- try {
7931
- provider = await createDnsProvider({ config: providerConfig });
7932
- } catch (error) {
7933
- const message = error instanceof Error ? error.message : "Unknown error";
7934
- logger$1.log(` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`);
7935
- return records.map((r) => ({
7936
- ...r,
7937
- error: message
7016
+ async function createDnsRecordsForDomain(records, rootDomain, providerConfig) {
7017
+ const ttl = "ttl" in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;
7018
+ let provider;
7019
+ try {
7020
+ provider = await createDnsProvider({ config: providerConfig });
7021
+ } catch (error) {
7022
+ const message = error instanceof Error ? error.message : "Unknown error";
7023
+ logger$1.log(` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`);
7024
+ return records.map((r) => ({
7025
+ ...r,
7026
+ error: message
7938
7027
  }));
7939
7028
  }
7940
7029
  if (!provider) return records.map((r) => ({
@@ -8168,6 +7257,10 @@ async function verifyDnsRecords(appHostnames, serverIp, state) {
8168
7257
  * resolver. One that is not the server stops the deploy with
8169
7258
  * {@link HostNotPointingAtServer}, before Caddy or Traefik ask Let's Encrypt
8170
7259
  * for a certificate it cannot get — and use up the rate limit trying.
7260
+ * - **The step** (`stageDns`): all three, as every deploy runs them — the plan applied through each provider,
7261
+ * what was written read back from the provider, and only the hosts no
7262
+ * provider wrote resolved publicly. A brand-new name is never looked up
7263
+ * before its record exists, so no resolver caches it as missing.
8171
7264
  */
8172
7265
  /** The line that says how to set the server's address. */
8173
7266
  function serverAddressHint(stage) {
@@ -8256,6 +7349,21 @@ function recordTtl(config) {
8256
7349
  function providerName(config) {
8257
7350
  return typeof config.provider === "string" ? config.provider : "custom";
8258
7351
  }
7352
+ /**
7353
+ * A wildcard host: gkm writes one record per public host, so a stage on
7354
+ * another server — or a name someone else points elsewhere — is never caught
7355
+ * by a record it did not ask for.
7356
+ */
7357
+ var DnsWildcardRefused = class extends GkmError {
7358
+ stage;
7359
+ host;
7360
+ constructor(stage, host) {
7361
+ super(`'${stage}' would point ${host} at its server, and gkm never writes a wildcard record: each public host gets its own. Give the app a subdomain of its own instead.`);
7362
+ this.stage = stage;
7363
+ this.host = host;
7364
+ this.name = "DnsWildcardRefused";
7365
+ }
7366
+ };
8259
7367
  /** The records a stage's hosts need — pure. */
8260
7368
  function planStackDns(input) {
8261
7369
  const { stage, server } = input;
@@ -8279,6 +7387,7 @@ function planStackDns(input) {
8279
7387
  };
8280
7388
  for (const raw of input.hosts) {
8281
7389
  const host = raw.toLowerCase();
7390
+ if (host.includes("*")) throw new DnsWildcardRefused(stage, host);
8282
7391
  const domain = findRootDomain(host, dns);
8283
7392
  if (!domain) {
8284
7393
  uncovered.push(host);
@@ -8308,6 +7417,22 @@ function planStackDns(input) {
8308
7417
  uncovered: uncovered.sort()
8309
7418
  };
8310
7419
  }
7420
+ /** Records a provider accepted and then did not read back with their value. */
7421
+ var DnsRecordsNotConfirmed = class extends GkmError {
7422
+ stage;
7423
+ domain;
7424
+ provider;
7425
+ records;
7426
+ constructor(stage, domain, provider, records) {
7427
+ const lines = records.map((r) => ` - ${r.host} ${r.type}: ${r.found.length > 0 ? r.found.join(", ") : "nothing"}, expected ${r.expected}`);
7428
+ super(`${provider} accepted '${stage}''s records for ${domain}, and reading them back does not show them:\n${lines.join("\n")}\nDeploy again; if it persists, check the records in the provider's console — another tool may be writing the same names.`);
7429
+ this.stage = stage;
7430
+ this.domain = domain;
7431
+ this.provider = provider;
7432
+ this.records = records;
7433
+ this.name = "DnsRecordsNotConfirmed";
7434
+ }
7435
+ };
8311
7436
  /** `api.example.com A 203.0.113.10 (TTL 600)` */
8312
7437
  function describe(record) {
8313
7438
  return `${record.host.padEnd(32)} ${record.type.padEnd(5)} ${record.value} (TTL ${record.ttl})`;
@@ -8413,37 +7538,48 @@ function printChange(change, dryRun, log) {
8413
7538
  }
8414
7539
  }
8415
7540
  /**
8416
- * Each domain's records, through its provider. Returns every change, the
8417
- * unchanged included; a dry run makes none of them.
7541
+ * Each domain's records, through its provider — and, with `confirm`, what was
7542
+ * written read back from it. A record already holding its value is neither
7543
+ * written nor read again.
7544
+ *
7545
+ * @throws {DnsRecordsNotConfirmed} when a written record does not read back
8418
7546
  */
8419
- async function applyStackDns(plan, options = {}) {
7547
+ async function settleStackDns(plan, options = {}) {
8420
7548
  const dryRun = options.dryRun === true;
8421
7549
  const log = options.log ?? ((line) => console.log(line));
8422
7550
  const providerFor = options.providerFor ?? ((config) => createDnsProvider({
8423
7551
  config,
8424
- ...options.credentials ? { godaddy: options.credentials } : {}
7552
+ ...options.credentials ? { godaddy: options.credentials } : {},
7553
+ ...options.hostinger ? { hostinger: options.hostinger } : {}
8425
7554
  }));
8426
7555
  const changes = [];
7556
+ const confirmed = /* @__PURE__ */ new Set();
7557
+ const unconfirmed = /* @__PURE__ */ new Set();
7558
+ const hostsOf = (domain) => new Set(domain.records.map((r) => r.host));
8427
7559
  for (const host of plan.uncovered) log(` ⚠ ${host} is under no domain in dns — point it at ${plan.server.ipv4} yourself`);
8428
7560
  for (const domain of plan.domains) {
8429
7561
  if (domain.provider === "manual") {
8430
7562
  changes.push(...printManual(domain, log, "manual"));
7563
+ for (const host of hostsOf(domain)) unconfirmed.add(host);
8431
7564
  continue;
8432
7565
  }
8433
7566
  const provider = await providerFor(domain.config);
8434
7567
  if (!provider) {
8435
7568
  changes.push(...printManual(domain, log, "manual"));
7569
+ for (const host of hostsOf(domain)) unconfirmed.add(host);
8436
7570
  continue;
8437
7571
  }
8438
7572
  log(` ${domain.domain} (${provider.name})${dryRun ? " — dry run" : ""}`);
8439
7573
  let existing;
8440
7574
  let diff;
7575
+ let unreadable = false;
8441
7576
  try {
8442
7577
  existing = await existingRecords(provider, domain);
8443
7578
  diff = diffDomainDns(domain, existing);
8444
7579
  } catch (error) {
8445
7580
  if (!(error instanceof DnsRecordsUnreadable)) throw error;
8446
7581
  log(` ℹ The ${provider.name} key cannot read ${domain.domain}'s DNS records, so changes cannot be diffed: every record is written (idempotent).`);
7582
+ unreadable = true;
8447
7583
  existing = [];
8448
7584
  diff = domain.records.map((r) => ({
8449
7585
  domain: r.domain,
@@ -8461,6 +7597,10 @@ async function applyStackDns(plan, options = {}) {
8461
7597
  if (aaaa && planned && aaaa.values.length > 0) log(` ⚠ ${fullName(domain.domain, name)} also has AAAA ${aaaa.values.join(", ")}: set ${SERVER_IPV6_KEY} in the '${plan.stage}' stage's secrets to the server's IPv6 address, or remove that record, or IPv6 clients go elsewhere`);
8462
7598
  }
8463
7599
  changes.push(...diff);
7600
+ const written = new Set(diff.filter((c) => c.action !== "unchanged").map((c) => fullName(c.domain, c.name)));
7601
+ for (const host of hostsOf(domain)) if (unreadable) {
7602
+ if (!dryRun) unconfirmed.add(host);
7603
+ } else if (!written.has(host)) confirmed.add(host);
8464
7604
  if (dryRun) continue;
8465
7605
  const deletes = diff.filter((c) => c.action === "delete");
8466
7606
  if (deletes.length > 0) await provider.deleteRecords(domain.domain, deletes.map((c) => ({
@@ -8474,8 +7614,32 @@ async function applyStackDns(plan, options = {}) {
8474
7614
  value: c.value,
8475
7615
  ttl: c.ttl
8476
7616
  })));
7617
+ if (!options.confirm || unreadable || written.size === 0) continue;
7618
+ const rewritten = {
7619
+ ...domain,
7620
+ records: domain.records.filter((r) => written.has(r.host))
7621
+ };
7622
+ const after = await existingRecords(provider, rewritten);
7623
+ const missing = [];
7624
+ for (const record of rewritten.records) {
7625
+ const values = after.find((r) => r.name === record.name && r.type === record.type)?.values ?? [];
7626
+ if (values.length !== 1 || !same(values[0], record.value)) missing.push({
7627
+ host: record.host,
7628
+ type: record.type,
7629
+ expected: record.value,
7630
+ found: values
7631
+ });
7632
+ }
7633
+ if (missing.length > 0) throw new DnsRecordsNotConfirmed(plan.stage, domain.domain, provider.name, missing);
7634
+ for (const host of written) confirmed.add(host);
7635
+ log(` ✓ ${written.size} host${written.size === 1 ? "" : "s"} read back from ${provider.name}`);
8477
7636
  }
8478
- return changes;
7637
+ for (const host of plan.uncovered) unconfirmed.add(host);
7638
+ return {
7639
+ changes,
7640
+ confirmed: [...confirmed].sort(),
7641
+ unconfirmed: [...unconfirmed].filter((h) => !confirmed.has(h)).sort()
7642
+ };
8479
7643
  }
8480
7644
  /** The system resolver: what the server's own clients would be told. */
8481
7645
  const systemLookup = async (host) => {
@@ -8490,7 +7654,7 @@ var HostNotPointingAtServer = class extends GkmError {
8490
7654
  constructor(stage, hosts, expected, fix) {
8491
7655
  const want = expected.ipv6 ? `${expected.ipv4} (and ${expected.ipv6})` : expected.ipv4;
8492
7656
  const lines = hosts.map((h) => ` - ${h.host} → ${h.resolved.length > 0 ? h.resolved.join(", ") : `nothing${h.error ? ` (${h.error})` : ""}`}, expected ${want}`);
8493
- super(`${hosts.length === 1 ? "A host" : `${hosts.length} hosts`} of '${stage}' do${hosts.length === 1 ? "es" : ""} not resolve to its server, so a certificate for ${hosts.length === 1 ? "it" : "them"} cannot be issued:\n${lines.join("\n")}\n${fix}\nRecords can take a few minutes to propagate. With a CDN or proxy in front of the server, pass --skip-dns-check.`);
7657
+ super(`${hosts.length === 1 ? "A host" : `${hosts.length} hosts`} of '${stage}' do${hosts.length === 1 ? "es" : ""} not resolve to its server, so a certificate for ${hosts.length === 1 ? "it" : "them"} cannot be issued:\n${lines.join("\n")}\n${fix}\nRecords can take a few minutes to propagate. With a CDN or proxy in front of the server, pass --skip-dns.`);
8494
7658
  this.stage = stage;
8495
7659
  this.hosts = hosts;
8496
7660
  this.expected = expected;
@@ -8535,7 +7699,7 @@ async function checkStackDns(input) {
8535
7699
  }, dnsFix(input, bad));
8536
7700
  return ok;
8537
7701
  }
8538
- /** How to fix it: `gkm setup`, or the records to create by hand. */
7702
+ /** How to fix it: the deploy, or the records to create by hand. */
8539
7703
  function dnsFix(input, bad) {
8540
7704
  const hosts = bad.map((h) => h.host);
8541
7705
  let plan;
@@ -8557,1671 +7721,1036 @@ function dnsFix(input, bad) {
8557
7721
  const automatic = plan.domains.filter((d) => d.provider !== "manual");
8558
7722
  const byHand = [...plan.domains.filter((d) => d.provider === "manual").flatMap((d) => d.records.map(describe)), ...plan.uncovered.flatMap((host) => [`${host.padEnd(32)} A ${input.server.ipv4}`, ...input.server.ipv6 ? [`${host.padEnd(32)} AAAA ${input.server.ipv6}`] : []])];
8559
7723
  const lines = [];
8560
- if (automatic.length > 0) lines.push(`Fix: gkm setup --stage ${input.stage} writes the records for ${automatic.map((d) => d.domain).join(", ")} (gkm setup --stage ${input.stage} --dry-run shows them first).`);
7724
+ if (automatic.length > 0) lines.push(`Fix: gkm deploy --stage ${input.stage} writes the records for ${automatic.map((d) => d.domain).join(", ")} through their provider (--dry-run shows them first).`);
8561
7725
  if (byHand.length > 0) lines.push(`${automatic.length > 0 ? "And create" : "Fix: create"} these records at the DNS host:`, ...byHand.map((line) => ` ${line}`));
8562
7726
  return lines.join("\n");
8563
7727
  }
8564
- //#endregion
8565
- //#region src/docker/imageRef.ts
7728
+ /** The environment variable each token-authenticated provider reads. */
7729
+ const DNS_TOKEN_KEYS = {
7730
+ godaddy: "GODADDY_API_TOKEN",
7731
+ hostinger: "HOSTINGER_API_TOKEN"
7732
+ };
8566
7733
  /**
8567
- * An image reference, checked before it reaches `docker`.
8568
- *
8569
- * The parts come from the workspace — a registry in `gkm.config.ts`, an image
8570
- * name from the project, a tag from `--tag` — and an argument array already
8571
- * keeps them out of a shell. What it cannot do is stop `docker` reading a value
8572
- * that starts with `-` as one of its own flags, so a ref is held to Docker's
8573
- * own grammar (distribution/reference) and anything else is refused by name
8574
- * before a build starts.
7734
+ * A domain whose records the deploy writes, and no token to write them with.
7735
+ * Raised before anything is built, started or written.
8575
7736
  */
8576
- const DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
8577
- const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
8578
- const PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
8579
- const REFERENCE = new RegExp(`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::[\\w][\\w.-]{0,127})?(?:@[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,})?$`);
8580
- /** Docker refuses a repository name longer than this. */
8581
- const MAX_NAME_LENGTH = 255;
8582
- /** A value that is not an image reference was about to be built or pushed. */
8583
- var ImageRefInvalid = class extends GkmError {
8584
- ref;
8585
- constructor(ref) {
8586
- super(`'${ref}' is not a valid image reference. An image is \`[registry/]name[:tag]\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`);
8587
- this.ref = ref;
8588
- this.name = "ImageRefInvalid";
7737
+ var DnsCredentialMissing = class extends GkmError {
7738
+ stage;
7739
+ domain;
7740
+ provider;
7741
+ key;
7742
+ constructor(stage, domain, provider, key) {
7743
+ super(`'${stage}''s hosts are under ${domain}, whose DNS is ${provider}'s, and the deploy writes their records — but ${key} is not set. In CI, add ${key} as a secret on the '${stage}' GitHub environment and pass it to the step that writes the records: env: { ${key}: \${{ secrets.${key} }} }. On this machine, export ${key} or run gkm login --provider ${provider}. With a CDN or proxy in front of the server, pass --skip-dns.`);
7744
+ this.stage = stage;
7745
+ this.domain = domain;
7746
+ this.provider = provider;
7747
+ this.key = key;
7748
+ this.name = "DnsCredentialMissing";
8589
7749
  }
8590
7750
  };
8591
- /** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */
8592
- function validateImageRef(ref) {
8593
- const name = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
8594
- if (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) throw new ImageRefInvalid(ref);
8595
- return ref;
7751
+ /**
7752
+ * The `dns` domain a stage's own domain (`domains.<stage>`) is under — where
7753
+ * its hosts' records go — or none.
7754
+ */
7755
+ function stageDnsDomains(stage, domains, dns) {
7756
+ const own = domains?.[stage];
7757
+ if (!own || !dns || isLocalHost(own)) return [];
7758
+ const normalized = normalizeDnsConfig(dns);
7759
+ const root = findRootDomain(own.toLowerCase(), normalized);
7760
+ return root ? [{
7761
+ domain: root,
7762
+ config: normalized[root]
7763
+ }] : [];
8596
7764
  }
8597
- //#endregion
8598
- //#region src/docker/index.ts
8599
- const logger = output;
8600
- /** `docker build` failed; what docker printed above says why. */
8601
- var DockerBuildFailed = class extends Error {
8602
- imageRef;
8603
- constructor(imageRef, cause) {
8604
- super(`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
8605
- this.imageRef = imageRef;
8606
- this.name = "DockerBuildFailed";
8607
- }
8608
- };
8609
- /** `docker push` failed — usually the registry login or its permissions. */
8610
- var DockerPushFailed = class extends Error {
8611
- imageRef;
8612
- constructor(imageRef, cause) {
8613
- super(`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
8614
- this.imageRef = imageRef;
8615
- this.name = "DockerPushFailed";
8616
- }
8617
- };
8618
- /** `gkm docker --push` was asked for with nowhere to push to. */
8619
- var PushNeedsRegistry = class extends GkmError {
8620
- imageName;
8621
- constructor(imageName) {
8622
- super(`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`);
8623
- this.imageName = imageName;
8624
- this.name = "PushNeedsRegistry";
7765
+ /**
7766
+ * Each token the domains' providers need, from `credentials` — `manual`,
7767
+ * Route53 (the AWS SDK's own chain) and a provider object need none.
7768
+ *
7769
+ * @throws {DnsCredentialMissing} naming the first domain with no token
7770
+ */
7771
+ async function dnsCredentials(stage, domains, credentials) {
7772
+ const found = {};
7773
+ for (const { domain, config } of domains) {
7774
+ const provider = config.provider;
7775
+ if (provider !== "godaddy" && provider !== "hostinger") continue;
7776
+ if (found[provider]) continue;
7777
+ const token = await credentials.get({ kind: provider });
7778
+ if (!token?.token) throw new DnsCredentialMissing(stage, domain, provider, DNS_TOKEN_KEYS[provider]);
7779
+ found[provider] = token;
8625
7780
  }
8626
- };
7781
+ return found;
7782
+ }
8627
7783
  /**
8628
- * Docker command implementation: one Dockerfile per deployable app, each
8629
- * building its image inside Docker from a turbo-pruned slice of the build
8630
- * root — nothing is built on the host — plus the build root's
8631
- * `.dockerignore` and `docker-compose.constructs.yml`.
7784
+ * A stage's DNS, as every deploy runs it: the
7785
+ * stage's own hosts planned, written through each domain's provider where
7786
+ * they differ, and read back from it. Only A, AAAA and CNAME records of
7787
+ * those names are touched; nothing is a wildcard, and no other name is read,
7788
+ * written or deleted. What no provider confirms — a `manual` domain, a host
7789
+ * under no domain in `dns`, a key that cannot read — is resolved publicly.
7790
+ * A dry run prints the plan and writes nothing.
7791
+ *
7792
+ * @throws {DnsCredentialMissing} before anything is read or written
7793
+ * @throws {DnsRecordsNotConfirmed} when a written record does not read back
7794
+ * @throws {HostNotPointingAtServer} when a resolved host is not the server
8632
7795
  */
8633
- async function dockerCommand(options) {
8634
- const cwd = options.cwd ?? process.cwd();
8635
- const loaded = await loadWorkspaceConfig(cwd);
8636
- const names = loaded.type === "single" ? Object.fromEntries(Object.keys(loaded.workspace.apps).map((name) => [name, resolveDockerConfig(loaded.raw).imageName])) : {};
8637
- const result = await workspaceDockerCommand(loaded.workspace, loaded.manifest, names, loaded.background, options.stage);
8638
- if (options.build) for (const app of result.apps) await buildDockerImage(app, result.buildRoot, options);
8639
- if (options.push) for (const app of result.apps) await pushDockerImage(app.imageName, options, result.buildRoot);
8640
- return result;
7796
+ async function stageDns(input) {
7797
+ const { stage, server } = input;
7798
+ const log = input.log ?? ((line) => console.log(line));
7799
+ const plan = planStackDns({
7800
+ stage,
7801
+ hosts: input.hosts,
7802
+ server,
7803
+ dns: input.dns
7804
+ });
7805
+ const tokens = await dnsCredentials(stage, plan.domains.map(({ domain, config }) => ({
7806
+ domain,
7807
+ config
7808
+ })), input.credentials);
7809
+ const applied = !input.dns ? {
7810
+ changes: [],
7811
+ confirmed: [],
7812
+ unconfirmed: [...plan.uncovered]
7813
+ } : await settleStackDns(plan, {
7814
+ ...input.dryRun ? { dryRun: true } : { confirm: true },
7815
+ log,
7816
+ credentials: {
7817
+ ...input.godaddy ?? {},
7818
+ ...tokens.godaddy ? { credential: tokens.godaddy } : {},
7819
+ log
7820
+ },
7821
+ ...tokens.hostinger ? { hostinger: tokens.hostinger } : {},
7822
+ ...input.providerFor ? { providerFor: input.providerFor } : {}
7823
+ });
7824
+ let resolved = [];
7825
+ if (applied.unconfirmed.length > 0) resolved = await checkStackDns({
7826
+ stage,
7827
+ hosts: applied.unconfirmed,
7828
+ server,
7829
+ dns: input.dns,
7830
+ ...input.lookup ? { lookup: input.lookup } : {}
7831
+ });
7832
+ return {
7833
+ plan,
7834
+ changes: applied.changes,
7835
+ confirmed: applied.confirmed,
7836
+ resolved
7837
+ };
7838
+ }
7839
+ //#endregion
7840
+ //#region src/providers/dns.ts
7841
+ var dns_exports = /* @__PURE__ */ __exportAll({
7842
+ composeStageHosts: () => composeStageHosts,
7843
+ deploysWithCompose: () => deploysWithCompose
7844
+ });
7845
+ /** Whether the workspace deploys through the compose target. */
7846
+ function deploysWithCompose(workspace) {
7847
+ return workspace.deploy?.default === "compose" || Object.values(workspace.apps).some((app) => app.resolvedDeployTarget === "compose");
8641
7848
  }
8642
7849
  /**
8643
- * Build one app's image, from the build root.
8644
- * Uses BuildKit for cache mount support
7850
+ * The hosts a compose stage serves: its stack composed as a deploy would —
7851
+ * with the secrets it would generate made up in memory, never written — and
7852
+ * every route's host read off it.
8645
7853
  */
8646
- async function buildDockerImage(app, buildRoot, options) {
8647
- const tag = options.tag ?? "latest";
8648
- const registry = options.registry;
8649
- const fullImageName = validateImageRef(registry ? `${registry}/${app.imageName}:${tag}` : `${app.imageName}:${tag}`);
8650
- logger.log(`\n🐳 Building Docker image: ${fullImageName}`);
8651
- try {
8652
- await run$1("docker", [
8653
- "build",
8654
- `--file=${relative(buildRoot, app.dockerfile)}`,
8655
- `--tag=${fullImageName}`,
8656
- "."
8657
- ], {
8658
- cwd: buildRoot,
8659
- env: {
8660
- ...process.env,
8661
- DOCKER_BUILDKIT: "1"
8662
- }
8663
- });
8664
- logger.log(`✅ Docker image built: ${fullImageName}`);
8665
- } catch (error) {
8666
- throw new DockerBuildFailed(fullImageName, error);
7854
+ async function composeStageHosts(options) {
7855
+ const { workspace, stage, manifest } = options;
7856
+ const { deployedStackSecrets } = await import("./secrets-CwLauUB_.mjs").then((n) => n.n);
7857
+ const { composeStack } = await import("./stack-NrdH5ngX.mjs").then((n) => n.c);
7858
+ const { secrets } = deployedStackSecrets(workspace, stage, options.stored, manifest);
7859
+ return stackHosts(composeStack({
7860
+ workspace,
7861
+ manifest,
7862
+ runnables: options.runnables,
7863
+ background: options.background,
7864
+ stage,
7865
+ identity: deployIdentity(workspace, stage),
7866
+ images: {
7867
+ mode: "pull",
7868
+ tag: "dns",
7869
+ ...workspace.deploy?.registry ? { registry: workspace.deploy.registry } : {}
7870
+ },
7871
+ secrets,
7872
+ buildOnly: true,
7873
+ allowDevServices: true
7874
+ }));
7875
+ }
7876
+ //#endregion
7877
+ //#region src/providers/types.ts
7878
+ /** The manifest kinds a stage can name a provider for. */
7879
+ const PROVIDER_KINDS = ["objects"];
7880
+ //#endregion
7881
+ //#region src/providers/notes.ts
7882
+ /** The constructs of a kind: `objects` is every bucket. */
7883
+ function constructsOf(manifest, kind) {
7884
+ return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
7885
+ }
7886
+ /** A stage that names `false` for a kind, and declares constructs of it. */
7887
+ var StageProviderDisabled = class extends GkmError {
7888
+ kind;
7889
+ stage;
7890
+ ids;
7891
+ constructor(kind, stage, ids) {
7892
+ super(`deploy.${kind}.${stage} is false — the stage has no ${kind} — and ${ids.join(", ")} ${ids.length === 1 ? "is" : "are"} declared. Name what backs ${ids.length === 1 ? "it" : "them"} on '${stage}' (deploy.${kind}.${stage}: 'external', or a provider), or remove the ${ids.length === 1 ? "construct" : "constructs"}.`);
7893
+ this.kind = kind;
7894
+ this.stage = stage;
7895
+ this.ids = ids;
7896
+ this.name = "StageProviderDisabled";
8667
7897
  }
7898
+ };
7899
+ /** The command a stage's providers are run with: every deploy runs them. */
7900
+ function provisionCommand(stage) {
7901
+ return `gkm deploy --stage ${stage}`;
7902
+ }
7903
+ /**
7904
+ * The line a stage missing a key a provider would write is given: what
7905
+ * creates it, and with which credentials. Undefined when no provider backs
7906
+ * the kind on the stage.
7907
+ */
7908
+ function provisionHint(workspace, kind, stage) {
7909
+ const choice = stageProvider(workspace, kind, stage);
7910
+ if (choice.mode !== "provider") return void 0;
7911
+ const provisioning = provisioningOf(kind, choice.name);
7912
+ if (!provisioning) return void 0;
7913
+ return `deploy.${kind}.${stage} is ${choice.name}: the deploy (${provisionCommand(stage)}) creates it and writes this key, with ${provisioning.describe}` + (provisioning.login ? `, or gkm login --provider ${provisioning.login}` : "");
8668
7914
  }
8669
7915
  /**
8670
- * Push Docker image to registry
7916
+ * What a deploy's checks read off the stage's providers: whether each kind is
7917
+ * accounted for — a provider, or `false` — so no dev service stands in for
7918
+ * it, and what creates a missing key of it.
8671
7919
  */
8672
- async function pushDockerImage(imageName, options, cwd) {
8673
- const tag = options.tag ?? "latest";
8674
- const registry = options.registry;
8675
- if (!registry) throw new PushNeedsRegistry(imageName);
8676
- const fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);
8677
- logger.log(`\n🚀 Pushing Docker image: ${fullImageName}`);
8678
- try {
8679
- await run$1("docker", ["push", fullImageName], { cwd });
8680
- logger.log(`✅ Docker image pushed: ${fullImageName}`);
8681
- } catch (error) {
8682
- throw new DockerPushFailed(fullImageName, error);
8683
- }
7920
+ function stageProviderNotes(workspace, stage) {
7921
+ if (stageProvider(workspace, "objects", stage).mode === "external") return {};
7922
+ const hint = provisionHint(workspace, "objects", stage);
7923
+ return { objects: {
7924
+ accounted: true,
7925
+ ...hint ? { hint } : {}
7926
+ } };
8684
7927
  }
8685
7928
  /**
8686
- * Generate Dockerfiles for all apps in a workspace.
8687
- * @internal Exported for testing
7929
+ * A kind the stage set to `false`, declared anyway — refused before anything
7930
+ * else is checked. Pure: what a stack is composed from.
7931
+ *
7932
+ * @throws {StageProviderDisabled}
8688
7933
  */
8689
- async function workspaceDockerCommand(workspace, manifest, imageNames = {}, background = {}, stage) {
8690
- const results = [];
8691
- const layout = imageLayout(workspace);
8692
- logger.log(`\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);
8693
- logger.log(` Build root: ${layout.buildRoot}`);
8694
- logger.log(` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ""}, turbo@${layout.tools.turboVersion}`);
8695
- for (const [appName, app] of Object.entries(workspace.apps)) {
8696
- if (app.type === "mobile") {
8697
- logger.log(`\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`);
8698
- continue;
8699
- }
8700
- const buildType = app.entry ? "entry" : app.type;
8701
- logger.log(`\n 📄 Generating Dockerfile for ${appName} (${buildType})`);
8702
- const dockerfile = appDockerfile(appName, app, {
8703
- layout,
8704
- workspaceRoot: workspace.root,
8705
- apps: workspace.apps,
8706
- ...manifest ? { manifest } : {},
8707
- workspace,
8708
- ...stage ? { stage } : {}
8709
- });
8710
- const path = dockerfileOf(appName, app.path);
8711
- const dockerfilePath = join(workspace.root, path);
8712
- await mkdir(dirname(dockerfilePath), { recursive: true });
8713
- await writeFile(dockerfilePath, dockerfile);
8714
- logger.log(` Generated: ${path}`);
8715
- results.push({
8716
- appName,
8717
- type: app.type,
8718
- dockerfile: dockerfilePath,
8719
- imageName: imageNames[appName] ?? appName
8720
- });
7934
+ function assertStageProvidersEnabled(workspace, manifest, stage) {
7935
+ for (const kind of PROVIDER_KINDS) {
7936
+ const ids = constructsOf(manifest, kind);
7937
+ if (ids.length === 0) continue;
7938
+ if (stageProvider(workspace, kind, stage).mode === "none") throw new StageProviderDisabled(kind, stage, ids);
8721
7939
  }
8722
- for (const worker of manifest ? workerUnits(workspace, manifest, background) : []) {
8723
- logger.log(`\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`);
8724
- const dockerfile = workerDockerfile(worker, workspace.apps[worker.app], {
8725
- layout,
8726
- workspaceRoot: workspace.root
8727
- });
8728
- const path = workerDockerfileOf(worker.name);
8729
- const dockerfilePath = join(workspace.root, path);
8730
- await mkdir(dirname(dockerfilePath), { recursive: true });
8731
- await writeFile(dockerfilePath, dockerfile);
8732
- logger.log(` Generated: ${path}`);
8733
- results.push({
8734
- appName: worker.name,
8735
- type: "backend",
8736
- dockerfile: dockerfilePath,
8737
- imageName: imageNames[worker.name] ?? worker.name
8738
- });
7940
+ }
7941
+ const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
7942
+ /** A name that S3 would refuse — what the name builder never returns. */
7943
+ var InvalidBucketName = class extends GkmError {
7944
+ bucket;
7945
+ reason;
7946
+ constructor(bucket, reason) {
7947
+ super(`'${bucket}' is not a valid S3 bucket name: ${reason}. Rename the construct or set deploy.namespace in gkm.config.ts to something that leaves room for it.`);
7948
+ this.bucket = bucket;
7949
+ this.reason = reason;
7950
+ this.name = "InvalidBucketName";
8739
7951
  }
8740
- const dockerignorePath = await ensureDockerignore(layout.buildRoot);
8741
- logger.log(`\n Ensured: ${dockerignorePath}`);
8742
- const composePath = await writeConstructsCompose(workspace);
8743
- logger.log(`\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`);
8744
- logger.log(`\n📋 Build commands (from ${layout.buildRoot}):`);
8745
- for (const result of results) {
8746
- const icon = result.type === "backend" ? "⚙️" : result.type === "mobile" ? "📱" : "🌐";
8747
- logger.log(` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`);
7952
+ };
7953
+ /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
7954
+ function part(value) {
7955
+ return kebabCase(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
7956
+ }
7957
+ /**
7958
+ * `parts` joined by `-`, shortened to `max` characters by trimming the longest
7959
+ * part one character at a time — so a long construct id gives way before a
7960
+ * short stage name does, and every part keeps its start.
7961
+ */
7962
+ function fitParts(parts, max) {
7963
+ const kept = parts.map(part).filter(Boolean);
7964
+ const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
7965
+ while (length() > max) {
7966
+ let longest = 0;
7967
+ for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
7968
+ if (kept[longest].length <= 1) break;
7969
+ kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
8748
7970
  }
8749
- printRunInstructions(workspace);
8750
- return {
8751
- apps: results,
8752
- dockerCompose: composePath,
8753
- dockerignore: dockerignorePath,
8754
- buildRoot: layout.buildRoot
8755
- };
7971
+ return kept.join("-");
7972
+ }
7973
+ /** Why `name` is not a valid bucket name, or undefined when it is. */
7974
+ function bucketNameProblem(name) {
7975
+ if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
7976
+ if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
7977
+ if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
7978
+ if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
7979
+ if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
8756
7980
  }
8757
7981
  /**
8758
- * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,
8759
- * a backend with its own entry bundled by esbuild, or a site by its
8760
- * framework. The one choice every builder of images makes.
7982
+ * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
7983
+ * dots, shortened to leave room for a clash's suffix.
7984
+ *
7985
+ * @throws {InvalidBucketName} when nothing usable is left
8761
7986
  */
8762
- function appDockerfile(appName, app, options) {
8763
- const image = appImageOptions(options.layout, appName, app, options.workspaceRoot, options.apps, app.type === "web" && options.manifest && options.workspace ? siteClientTelemetry(options.manifest, appName, options.workspace, options.stage) : void 0);
8764
- if (app.type === "web") return siteDockerfile(appName, app, {
8765
- image,
8766
- ...options.manifest ? { manifest: options.manifest } : {},
8767
- ...options.publicUrlArgs ? { publicUrlArgs: options.publicUrlArgs } : {}
8768
- });
8769
- if (app.entry) return generateEntryDockerfile({
8770
- ...image,
8771
- entry: app.entry,
8772
- healthCheckPath: "/health"
8773
- });
8774
- return generateBackendDockerfile({
8775
- ...image,
8776
- healthCheckPath: "/health",
8777
- ...options.cache ? { cache: options.cache } : {}
8778
- });
7987
+ function bucketName(input) {
7988
+ const name = fitParts([
7989
+ input.scope,
7990
+ input.stage,
7991
+ input.id
7992
+ ], 56);
7993
+ const problem = bucketNameProblem(name);
7994
+ if (problem) throw new InvalidBucketName(name, problem);
7995
+ return name;
8779
7996
  }
8780
- /** Where `gkm docker` writes a worker's Dockerfile. */
8781
- function workerDockerfileOf(worker) {
8782
- return `.gkm/docker/Dockerfile.${worker}`;
7997
+ /** Six random `[a-z0-9]` characters. */
7998
+ function randomSuffix(random = randomInt) {
7999
+ let suffix = "";
8000
+ for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
8001
+ return suffix;
8002
+ }
8003
+ /** The good name with a clash's suffix. */
8004
+ function suffixedBucketName(good, suffix) {
8005
+ return `${good}-${suffix}`;
8783
8006
  }
8784
8007
  /**
8785
- * A Worker's Dockerfile: its host app's build, and the worker's bundle as the
8786
- * runner — see `generateWorkerDockerfile`.
8008
+ * The IAM user a bucket is reached with on a stage:
8009
+ * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
8787
8010
  */
8788
- function workerDockerfile(worker, host, options) {
8789
- return generateWorkerDockerfile({
8790
- ...appImageOptions(options.layout, worker.app, host, options.workspaceRoot),
8791
- imageName: worker.name,
8792
- port: WORKER_PORT,
8793
- worker: worker.id,
8794
- bundle: workerBundleName(worker.id),
8795
- healthCheckPath: "/health",
8796
- ...options.cache ? { cache: options.cache } : {}
8797
- });
8011
+ function iamUserName(input) {
8012
+ return fitParts([
8013
+ "gkm",
8014
+ input.scope,
8015
+ input.stage,
8016
+ input.id
8017
+ ], 64);
8798
8018
  }
8019
+ /** The path every user gkm creates is under, so it finds its own. */
8020
+ const IAM_USER_PATH = "/gkm/";
8021
+ /** The inline policy each user is given. */
8022
+ const IAM_POLICY_NAME = "gkm-bucket";
8023
+ //#endregion
8024
+ //#region src/deploy/devServices.ts
8799
8025
  /**
8800
- * A site's Dockerfile, with an `ARG` for every key its bundler inlines.
8026
+ * Mail and object storage on a deployed stage: real ones, or — only when
8027
+ * someone asked — the dev services the local stage runs.
8801
8028
  *
8802
- * The keys come from the site's declaration where there is one — every
8803
- * public key its edges give it, `VITE_UPLOADS_SERVER_URL` included — and an
8804
- * `ARG` the Dockerfile does not declare is a build argument the build drops,
8805
- * leaving the bundle with an empty URL.
8029
+ * Locally a declared `Email` is Mailpit and a declared bucket is MinIO, and
8030
+ * nobody has to configure either. Deployed, the same two containers would be
8031
+ * a stage that silently delivers no mail and keeps its files on one
8032
+ * container's disk. So a deployed stage on a server target takes both from
8033
+ * its secrets — the mail server's URL and sending address, and each bucket's
8034
+ * URL — and a stage missing any of them fails before anything is built,
8035
+ * provisioned or written, naming every key at once.
8036
+ *
8037
+ * A bucket's credentials are not checked: they are optional, and come from
8038
+ * either of two places. The bucket's URL may carry a key of its own
8039
+ * (`s3://KEY:SECRET@uploads`), which wins; otherwise the S3 client's default
8040
+ * chain applies — the stage's shared `AWS_ACCESS_KEY_ID`/
8041
+ * `AWS_SECRET_ACCESS_KEY` when it set them, or a role.
8042
+ *
8043
+ * `--allow-dev-services` is the way out for a stage that is not production —
8044
+ * a preview, a demo: every construct the stage does not account for gets the
8045
+ * dev service the local stage runs for it — a bucket MinIO, mail Mailpit —
8046
+ * and the target derives the keys from it. What the stage does account for
8047
+ * still wins: a key set in its secrets, or a provider (`deploy.objects`)
8048
+ * that backs the kind. Every run that uses one says so, loudly.
8049
+ *
8050
+ * Pure: what each target runs is decided here from declarations and the
8051
+ * stage's values, and the targets do the running.
8052
+ */
8053
+ /**
8054
+ * The dev services a deployed stage can run — one per kind that has one on
8055
+ * every server target: a bucket's MinIO and mail's Mailpit. A cache or a
8056
+ * database is not here because a server stage runs its own anyway.
8057
+ */
8058
+ const DEV_SERVICES = ["minio", "mailpit"];
8059
+ /**
8060
+ * The S3 client's shared key pair. Optional: a bucket whose URL carries its own
8061
+ * key (`s3://KEY:SECRET@bucket`) signs with that, and one without signs with
8062
+ * this pair when the stage set it, or with whatever else the SDK's default
8063
+ * chain finds — a role.
8806
8064
  */
8807
- function siteDockerfile(appName, app, options) {
8808
- const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1] : void 0;
8809
- const publicUrlArgs = options.publicUrlArgs ?? (declared?.kind === "site" && options.manifest ? Object.keys(publicEnvFor(declared, options.manifest)) : getPublicUrlArgNames(app));
8810
- const webOpts = {
8811
- ...options.image,
8812
- publicUrlArgs
8813
- };
8814
- switch (app.framework) {
8815
- case "vite": return generateViteStaticDockerfile(webOpts);
8816
- case "tanstack-start":
8817
- case "remix": return generateNodeWebDockerfile(webOpts);
8818
- default: return generateNextjsDockerfile(webOpts);
8065
+ const STORAGE_KEY_PAIR = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"];
8066
+ /** Dev services asked of a target that runs no containers. */
8067
+ var DevServicesNeedServerTarget = class extends GkmError {
8068
+ target;
8069
+ constructor(target) {
8070
+ super(`--allow-dev-services applies to server targets only, and '${target}' deploys to AWS, where a bucket is S3 and mail is the stage's own. Drop --allow-dev-services.`);
8071
+ this.target = target;
8072
+ this.name = "DevServicesNeedServerTarget";
8819
8073
  }
8820
- }
8074
+ };
8821
8075
  /**
8822
- * What a build root's `.dockerignore` must leave out of every image's
8823
- * context: dependencies installed for another platform, anything built on the
8824
- * host (every image builds from source), git, and gkm's own output —
8825
- * `.gkm/compose`'s env files hold a stage's secrets.
8076
+ * `--allow-dev-services` given a value — the list it used to take. It is a
8077
+ * switch now: every construct the stage does not account for gets its dev
8078
+ * service.
8826
8079
  */
8827
- const REQUIRED_IGNORES = [
8828
- "**/node_modules",
8829
- ".git",
8830
- "**/dist",
8831
- "**/.next",
8832
- "**/.turbo",
8833
- "**/.gkm",
8834
- "**/.gkm/compose"
8835
- ];
8080
+ var AllowDevServicesTakesNoValue = class extends GkmError {
8081
+ value;
8082
+ constructor(value) {
8083
+ super(`--allow-dev-services takes no value (it was given '${value}'). It runs the dev service for every bucket and mail the stage does not account for — no key in its secrets, no provider in deploy.<kind>.<stage> — so there is nothing to list. Pass --allow-dev-services on its own.`);
8084
+ this.value = value;
8085
+ this.name = "AllowDevServicesTakesNoValue";
8086
+ }
8087
+ };
8836
8088
  /**
8837
- * Make sure the build root's `.dockerignore` leaves out what no image may
8838
- * hold: written whole where there is none, and each missing line appended to
8839
- * one the project keeps.
8089
+ * Refuses `--allow-dev-services <value>` and `--allow-dev-services=<value>` on
8090
+ * a command line, with the reason, before the parser calls the value an
8091
+ * excess argument. `gkm deploy` and `gkm compose` take no positional
8092
+ * argument, so whatever follows the flag and is not a flag was meant for it.
8093
+ *
8094
+ * @throws {AllowDevServicesTakesNoValue}
8840
8095
  */
8841
- async function ensureDockerignore(buildRoot) {
8842
- const path = join(buildRoot, ".dockerignore");
8843
- if (!existsSync(path)) {
8844
- await writeFile(path, generateDockerignore());
8845
- return path;
8096
+ function assertDevServicesFlag(argv) {
8097
+ for (let i = 0; i < argv.length; i++) {
8098
+ const arg = argv[i];
8099
+ if (arg.startsWith("--allow-dev-services=")) throw new AllowDevServicesTakesNoValue(arg.slice(arg.indexOf("=") + 1));
8100
+ const next = argv[i + 1];
8101
+ if (arg === "--allow-dev-services" && next && !next.startsWith("-")) throw new AllowDevServicesTakesNoValue(next);
8846
8102
  }
8847
- const current = await readFile(path, "utf-8");
8848
- const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
8849
- const missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));
8850
- if (missing.length === 0) return path;
8851
- await appendFile(path, `${current.endsWith("\n") || current === "" ? "" : "\n"}\n# gkm: images build from source, and a stack's env files hold its secrets\n${missing.join("\n")}\n`);
8852
- return path;
8853
8103
  }
8854
8104
  /**
8855
- * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with
8856
- * the apps beside the containers their constructs derive.
8857
- *
8858
- * Through reconcile rather than a second generator, so what `gkm docker`
8859
- * describes and what `gkm dev` runs cannot disagree. Nothing is started.
8105
+ * A deployed stage with mail or object storage that its secrets do not
8106
+ * configure — every missing key, across every app, at once.
8860
8107
  */
8861
- async function writeConstructsCompose(workspace) {
8862
- await reconcileWorkspace(workspace, {
8863
- stage: workspace.stages.local,
8864
- start: false
8865
- });
8866
- logger.log(` Generated: ${COMPOSE_PATH} (project root)`);
8867
- return join(workspace.root, COMPOSE_PATH);
8868
- }
8869
- function printRunInstructions(workspace) {
8870
- const project = existsSync(join(workspace.root, "docker-compose.yml")) ? " -f docker-compose.yml" : "";
8871
- logger.log("\n📋 Run everything (the apps sit behind the \"apps\" profile):");
8872
- logger.log(" gkm setup # starts the containers and creates what they hold");
8873
- logger.log(` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`);
8874
- }
8875
- //#endregion
8876
- //#region src/providers/types.ts
8877
- /** The manifest kinds a stage can name a provider for. */
8878
- const PROVIDER_KINDS = ["objects"];
8879
- //#endregion
8880
- //#region src/providers/notes.ts
8881
- /** The constructs of a kind: `objects` is every bucket. */
8882
- function constructsOf$1(manifest, kind) {
8883
- return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
8884
- }
8885
- /** A stage that names `false` for a kind, and declares constructs of it. */
8886
- var StageProviderDisabled = class extends GkmError {
8887
- kind;
8108
+ var ExternalServicesNotConfigured = class extends GkmError {
8888
8109
  stage;
8889
- ids;
8890
- constructor(kind, stage, ids) {
8891
- super(`deploy.${kind}.${stage} is false — the stage has no ${kind} — and ${ids.join(", ")} ${ids.length === 1 ? "is" : "are"} declared. Name what backs ${ids.length === 1 ? "it" : "them"} on '${stage}' (deploy.${kind}.${stage}: 'external', or a provider), or remove the ${ids.length === 1 ? "construct" : "constructs"}.`);
8892
- this.kind = kind;
8110
+ missing;
8111
+ constructor(stage, missing) {
8112
+ const standIns = missing.some((m) => m.service !== void 0);
8113
+ const lines = missing.map((m) => {
8114
+ const by = m.apps?.length ? `, read by ${m.apps.join(", ")}` : "";
8115
+ return ` gkm secrets:set ${m.key} '${m.example}' --stage ${stage}\n ${m.what}${by}` + (m.note ? `\n ${m.note}` : "") + (m.hint ? `\n ${m.hint}` : "");
8116
+ });
8117
+ super(`The stage '${stage}' is deployed, and a deployed stage's mail and object storage are real services: gkm runs no Mailpit or MinIO for it. Set ${missing.length === 1 ? "this key" : `these ${missing.length} keys`} in the stage's secrets:\n\n${lines.join("\n")}\n\n` + (standIns ? "For a stage that is not production — a preview, a demo — the dev services can run instead, with --allow-dev-services. Mailpit delivers no mail, and MinIO keeps every object on one container's disk.\n\n" : "") + `Or run: gkm secrets:add --stage ${stage}`);
8893
8118
  this.stage = stage;
8894
- this.ids = ids;
8895
- this.name = "StageProviderDisabled";
8119
+ this.missing = missing;
8120
+ this.name = "ExternalServicesNotConfigured";
8896
8121
  }
8897
8122
  };
8898
- /** The command a stage's providers are run with. */
8899
- function provisionCommand(stage) {
8900
- return `gkm setup --stage ${stage}`;
8901
- }
8902
- /**
8903
- * The line a stage missing a key a provider would write is given: what
8904
- * creates it, and with which credentials. Undefined when no provider backs
8905
- * the kind on the stage.
8906
- */
8907
- function provisionHint(workspace, kind, stage) {
8908
- const choice = stageProvider(workspace, kind, stage);
8909
- if (choice.mode !== "provider") return void 0;
8910
- const provisioning = provisioningOf(kind, choice.name);
8911
- if (!provisioning) return void 0;
8912
- return `deploy.${kind}.${stage} is ${choice.name}: ${provisionCommand(stage)} creates it and writes this key, with ${provisioning.describe}` + (provisioning.login ? `, or gkm login --provider ${provisioning.login}` : "");
8913
- }
8914
8123
  /**
8915
- * What a deploy's checks read off the stage's providers: whether each kind is
8916
- * accounted for — a provider, or `false` — so no dev service stands in for
8917
- * it, and what creates a missing key of it.
8124
+ * Every mail and storage construct a manifest declares, with the apps that
8125
+ * depend on each — what a target that provisions the whole manifest checks.
8918
8126
  */
8919
- function stageProviderNotes(workspace, stage) {
8920
- if (stageProvider(workspace, "objects", stage).mode === "external") return {};
8921
- const hint = provisionHint(workspace, "objects", stage);
8922
- return { objects: {
8923
- accounted: true,
8924
- ...hint ? { hint } : {}
8925
- } };
8127
+ function manifestServiceDeclarations(manifest) {
8128
+ return Object.entries(manifest).flatMap(([id, declaration]) => {
8129
+ const { kind } = declaration;
8130
+ if (kind !== "email" && kind !== "objects" && kind !== "file-server") return [];
8131
+ const apps = dependentsOf(manifest, id).filter((caller) => {
8132
+ const callerKind = manifest[caller]?.kind;
8133
+ return callerKind === "rest-api" || callerKind === "site";
8134
+ }).map(appKey);
8135
+ return [{
8136
+ id,
8137
+ kind,
8138
+ ...declaration.kind === "file-server" ? { of: declaration.of } : {},
8139
+ ...apps.length ? { apps } : {}
8140
+ }];
8141
+ });
8926
8142
  }
8927
8143
  /**
8928
- * A kind the stage set to `false`, declared anyway — refused before anything
8929
- * else is checked. Pure: what a stack is composed from.
8144
+ * Every key a stage must be given rather than derive — the one list both a
8145
+ * deploy's checks and `gkm secrets:add` read, so what a deploy refuses and
8146
+ * what the builder offers cannot drift.
8930
8147
  *
8931
- * @throws {StageProviderDisabled}
8148
+ * - Deployed, mail is its URL and its sending address, a bucket its URL, and
8149
+ * a file server its public URL. Locally all of it is Mailpit and MinIO.
8150
+ * - On every stage, a third party's credentials: nobody but the third party
8151
+ * can issue them.
8152
+ *
8153
+ * Never a derived value: a database URL, a generated secret, the seed.
8932
8154
  */
8933
- function assertStageProvidersEnabled(workspace, manifest, stage) {
8934
- for (const kind of PROVIDER_KINDS) {
8935
- const ids = constructsOf$1(manifest, kind);
8936
- if (ids.length === 0) continue;
8937
- if (stageProvider(workspace, kind, stage).mode === "none") throw new StageProviderDisabled(kind, stage, ids);
8938
- }
8939
- }
8940
- //#endregion
8941
- //#region src/deploy/journal.ts
8942
- var DeployJournal = class DeployJournal {
8943
- store;
8944
- stage;
8945
- state;
8946
- resources;
8947
- version;
8948
- existed;
8949
- constructor(store, stage, state, resources, version, existed) {
8950
- this.store = store;
8951
- this.stage = stage;
8952
- this.state = state;
8953
- this.resources = resources;
8954
- this.version = version;
8955
- this.existed = existed;
8956
- }
8957
- static async open(store, stage, initial, adopt = (stored) => stored) {
8958
- const stored = await store.read(stage);
8959
- if (stored) return new DeployJournal(store, stage, adopt(stored.state), stored.resources, stored.version, true);
8960
- const state = initial();
8961
- const version = await store.write(stage, state, { expectedVersion: null });
8962
- return new DeployJournal(store, stage, state, {}, version, false);
8963
- }
8964
- record(key) {
8965
- return this.resources[key];
8966
- }
8967
- /** The keys a previous run marked `pending` and never saw created. */
8968
- unfinished() {
8969
- return Object.values(this.resources).filter((record) => record.status === "pending").map((record) => record.key);
8970
- }
8971
- /** Records that `entry` is about to be created. */
8972
- async pending(entry) {
8973
- await this.put({
8974
- ...entry,
8975
- status: "pending"
8155
+ function requiredStageKeys(input) {
8156
+ const domain = input.domain ?? "example.com";
8157
+ const keys = [];
8158
+ const add = (entry) => {
8159
+ if (!keys.some((k) => k.key === entry.key)) keys.push(entry);
8160
+ };
8161
+ const byId = (list) => [...list ?? []].sort((a, b) => a.id.localeCompare(b.id));
8162
+ const apps = (d) => d.apps?.length ? { apps: [...d.apps].sort() } : {};
8163
+ if (!input.local) {
8164
+ const services = byId(input.services);
8165
+ const objects = input.providers?.objects;
8166
+ const storage = objects?.accounted ? objects.hint ? { hint: objects.hint } : {} : { service: "minio" };
8167
+ for (const d of services.filter((d) => d.kind === "email")) {
8168
+ add({
8169
+ key: provideKey(d.id, "url"),
8170
+ id: d.id,
8171
+ kind: "email",
8172
+ what: `where '${d.id}' sends mail — any SMTP server`,
8173
+ example: `smtp://user:password@smtp.${domain}:587`,
8174
+ service: "mailpit",
8175
+ ...apps(d)
8176
+ });
8177
+ add({
8178
+ key: provideKey(d.id, "from"),
8179
+ id: d.id,
8180
+ kind: "email",
8181
+ what: `the address '${d.id}' sends from, on a domain the mail server has verified`,
8182
+ example: `noreply@${domain}`,
8183
+ service: "mailpit",
8184
+ ...apps(d)
8185
+ });
8186
+ }
8187
+ for (const d of services.filter((d) => d.kind === "objects")) add({
8188
+ key: provideKey(d.id, "url"),
8189
+ id: d.id,
8190
+ kind: "bucket",
8191
+ what: `the bucket '${d.id}' — S3, R2, or any S3-compatible store (add &endpoint=… for one that is not S3)`,
8192
+ note: `credentials are optional: a key for this bucket alone in the URL (s3://KEY:SECRET@${appKey(d.id)}?…) wins; without one, the shared AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY or a role signs`,
8193
+ example: `s3://${appKey(d.id)}?region=eu-west-1`,
8194
+ ...storage,
8195
+ ...apps(d)
8976
8196
  });
8977
- }
8978
- /**
8979
- * Records `entry` as existing with `id`; a no-op if it already is, with
8980
- * the same data.
8981
- */
8982
- async ready(entry, id) {
8983
- const current = this.resources[entry.key];
8984
- if (current?.status === "ready" && current.id === id && JSON.stringify(current.data) === JSON.stringify(entry.data)) return;
8985
- await this.put({
8986
- ...entry,
8987
- status: "ready",
8988
- id
8197
+ for (const d of services.filter((d) => d.kind === "file-server")) add({
8198
+ key: provideKey(d.id, "url"),
8199
+ id: d.id,
8200
+ kind: "file-server",
8201
+ what: `the public address '${d.id}' serves its bucket on — a CDN or the bucket's own domain`,
8202
+ example: `https://${appKey(d.id)}.${domain}`,
8203
+ ...storage,
8204
+ ...d.of ? { of: d.of } : {},
8205
+ ...apps(d)
8989
8206
  });
8990
- }
8991
- /**
8992
- * The resource `entry` names: by its recorded id, else by looking it up,
8993
- * else created — with `pending` written before the create and `ready`
8994
- * after, so a run that dies in between leaves a record the next run
8995
- * resolves by looking the resource up rather than creating another.
8996
- */
8997
- async ensure(entry, steps) {
8998
- const record = this.resources[entry.key];
8999
- let staleId;
9000
- if (record?.status === "ready" && record.id && steps.get) {
9001
- const known = await steps.get(record.id);
9002
- if (known) {
9003
- await this.ready(entry, steps.id(known));
9004
- return {
9005
- resource: known,
9006
- via: "recorded"
9007
- };
9008
- }
9009
- staleId = record.id;
9010
- }
9011
- const existing = await steps.find();
9012
- if (existing) {
9013
- await this.ready(entry, steps.id(existing));
9014
- return {
9015
- resource: existing,
9016
- via: record?.status === "pending" ? "resumed" : "found",
9017
- ...staleId ? { staleId } : {}
9018
- };
9019
- }
9020
- await this.pending(entry);
9021
- const created = await steps.create();
9022
- await this.ready(entry, steps.id(created));
9023
- return {
9024
- resource: created,
9025
- via: "created",
9026
- ...staleId ? { staleId } : {}
9027
- };
9028
- }
9029
- /** Removes `key`'s record — a resource that no longer exists. */
9030
- async forget(key) {
9031
- if (!(key in this.resources)) return;
9032
- this.version = await this.store.deleteResource(this.stage, key, { expectedVersion: this.version });
9033
- const { [key]: _removed, ...resources } = this.resources;
9034
- this.resources = resources;
9035
- }
9036
- /** Every record, as the journal last wrote or read it. */
9037
- records() {
9038
- return this.resources;
9039
- }
9040
- /** Writes the stage's state, keeping its resource records. */
9041
- async save() {
9042
- this.state.lastDeployedAt = (/* @__PURE__ */ new Date()).toISOString();
9043
- this.version = await this.store.write(this.stage, this.state, { expectedVersion: this.version });
9044
- }
9045
- async put(record) {
9046
- this.version = await this.store.putResource(this.stage, record, { expectedVersion: this.version });
9047
- this.resources = {
9048
- ...this.resources,
9049
- [record.key]: {
9050
- ...record,
9051
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
9052
- }
9053
- };
9054
- }
9055
- };
9056
- //#endregion
9057
- //#region src/providers/dns.ts
9058
- /** Whether the workspace deploys through the compose target. */
9059
- function deploysWithCompose(workspace) {
9060
- return workspace.deploy?.default === "compose" || Object.values(workspace.apps).some((app) => app.resolvedDeployTarget === "compose");
8207
+ }
8208
+ if (!input.local && input.server) add({
8209
+ key: SERVER_IPV4_KEY,
8210
+ id: "server",
8211
+ kind: "server",
8212
+ what: "the public IPv4 address of the server the stage's stack runs on — its hosts' DNS records point at it, and every deploy checks they do",
8213
+ note: `${SERVER_IPV6_KEY} adds its IPv6 address (AAAA records); neither is ever handed to an app`,
8214
+ example: "203.0.113.10"
8215
+ });
8216
+ for (const d of byId(input.credentials)) add({
8217
+ key: provideKey(d.id, "credentials"),
8218
+ id: d.id,
8219
+ kind: d.kind,
8220
+ what: d.kind === "external-api" ? `the credentials '${d.id}' was issued for this stage, as its schema describes them` : `the credential '${d.id}', as its schema describes it`,
8221
+ example: "{\"apiKey\":\"…\"}",
8222
+ ...apps(d)
8223
+ });
8224
+ return keys;
9061
8225
  }
9062
8226
  /**
9063
- * A compose stage that serves a domain has its server's address in its
9064
- * secrets — checked before `gkm setup --stage` does anything else.
8227
+ * Whether only the stage's secrets can supply `key` to a construct of `kind`
8228
+ * — what nothing on the stage derives.
9065
8229
  *
9066
- * @throws {ServerAddressMissing} for a compose stage with a domain and none
9067
- * @throws {ServerAddressInvalid} for a value that is not an address
8230
+ * A third party's credentials, always. Deployed, also each generated secret
8231
+ * and keyring: the stage generated each one once, and every run reads the
8232
+ * same value back.
9068
8233
  */
9069
- function assertStageServer(workspace, stage, secrets) {
9070
- if (stage === workspace.stages.local) return void 0;
9071
- if (!deploysWithCompose(workspace)) return serverAddress(stage, secrets?.custom);
9072
- return requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
8234
+ function suppliedOnly(kind, id, key, local) {
8235
+ if (kind === "credential") return true;
8236
+ if (kind === "external-api") return key === provideKey(id, "credentials");
8237
+ if (local) return false;
8238
+ return kind === "secret" || kind === "encryption";
9073
8239
  }
9074
8240
  /**
9075
- * The hosts a compose stage serves: its stack composed as a deploy would —
9076
- * with the secrets it would generate made up in memory, never written — and
9077
- * every route's host read off it.
8241
+ * Where a deployed stage's mail and storage come from, and what it lacks.
8242
+ *
8243
+ * - Mail is external once its URL is set, and then needs its sending
8244
+ * address too. Unset, it is Mailpit where allowed — the address derived
8245
+ * unless set — and missing otherwise.
8246
+ * - A bucket is external once its URL is set; its credentials, in the URL or
8247
+ * the shared pair, are optional. Unset, it is MinIO where allowed, and
8248
+ * missing otherwise.
8249
+ * - A file server's URL is derived where its bucket is MinIO, unless set;
8250
+ * over an external bucket the stage must set it.
8251
+ *
8252
+ * The keys themselves are {@link requiredStageKeys}'s.
9078
8253
  */
9079
- async function composeStageHosts(options) {
9080
- const { workspace, stage } = options;
9081
- const runnables = options.runnables ?? {};
9082
- const background = options.background ?? {};
9083
- const manifest = options.manifest ?? await discover({
9084
- patterns: constructGlobs(workspace),
9085
- cwd: workspace.root,
9086
- runnables,
9087
- background
8254
+ function externalServices(input) {
8255
+ const { supplied, allow } = input;
8256
+ const has = (key) => supplied[key] !== void 0;
8257
+ const required = requiredStageKeys({
8258
+ local: false,
8259
+ services: input.declarations,
8260
+ ...input.domain ? { domain: input.domain } : {},
8261
+ ...input.providers ? { providers: input.providers } : {}
9088
8262
  });
9089
- const stored = await (await secretsStoreFor(workspace, stage, {
9090
- ...options.profile ? { profile: options.profile } : {},
9091
- ...options.home ? { home: options.home } : {}
9092
- })).read(stage);
9093
- const { deployedStackSecrets } = await import("./secrets-DbPmAS4k.mjs").then((n) => n.n);
9094
- const { composeStack } = await import("./stack-Co4uZkAo.mjs").then((n) => n.c);
9095
- const { secrets } = deployedStackSecrets(workspace, stage, stored, manifest);
9096
- return stackHosts(composeStack({
9097
- workspace,
9098
- manifest,
9099
- runnables,
9100
- background,
9101
- stage,
9102
- identity: deployIdentity(workspace, stage),
9103
- images: {
9104
- mode: "pull",
9105
- tag: "dns",
9106
- ...workspace.deploy?.registry ? { registry: workspace.deploy.registry } : {}
9107
- },
9108
- secrets,
9109
- buildOnly: true,
9110
- allowDevServices: true
9111
- }));
8263
+ const standIn = (k) => allow && k.service !== void 0 && !has(k.key);
8264
+ const mailpit = required.filter((k) => k.kind === "email" && k.key === provideKey(k.id, "url")).filter(standIn).map((k) => k.id);
8265
+ const minio = required.filter((k) => k.kind === "bucket").filter(standIn).map((k) => k.id);
8266
+ const covered = (k) => k.kind === "email" && mailpit.includes(k.id) || k.kind === "bucket" && minio.includes(k.id) || k.kind === "file-server" && k.of !== void 0 && minio.includes(k.of);
8267
+ return {
8268
+ missing: required.filter((k) => !has(k.key) && !covered(k)).map(({ key, id, what, note, example, service, apps, hint }) => ({
8269
+ key,
8270
+ id,
8271
+ what,
8272
+ ...note ? { note } : {},
8273
+ example,
8274
+ ...service ? { service } : {},
8275
+ ...apps ? { apps } : {},
8276
+ ...hint ? { hint } : {}
8277
+ })),
8278
+ minio,
8279
+ mailpit
8280
+ };
9112
8281
  }
9113
8282
  /**
9114
- * `GKM_SERVER_IPV4` from the stage's secrets and `dns`: each public host's
9115
- * records, created or corrected. A dry run reads and prints, and writes
9116
- * nothing.
8283
+ * `externalServices`, refusing a stage that lacks anything.
8284
+ *
8285
+ * @throws {ExternalServicesNotConfigured} naming every missing key
9117
8286
  */
9118
- async function provisionStageDns(options) {
9119
- const { workspace, stage } = options;
9120
- const log = options.log ?? ((line) => console.log(line));
9121
- if (stage === workspace.stages.local || !workspace.dns || !deploysWithCompose(workspace)) return {
9122
- mode: "none",
9123
- hosts: [],
9124
- changes: []
9125
- };
9126
- const server = serverAddress(stage, (await (await secretsStoreFor(workspace, stage, {
9127
- ...options.profile ? { profile: options.profile } : {},
9128
- ...options.home ? { home: options.home } : {}
9129
- })).read(stage))?.custom);
9130
- if (!server) {
9131
- log(`\n🌐 DNS for '${stage}': no GKM_SERVER_IPV4 in its secrets, so no records — ${serverAddressHint(stage)}`);
9132
- return {
9133
- mode: "none",
9134
- hosts: [],
9135
- changes: []
9136
- };
9137
- }
9138
- const hosts = [...options.hosts ?? await composeStageHosts({
9139
- workspace,
9140
- stage,
9141
- ...options.profile ? { profile: options.profile } : {},
9142
- ...options.home ? { home: options.home } : {},
9143
- ...options.manifest ? { manifest: options.manifest } : {},
9144
- ...options.runnables ? { runnables: options.runnables } : {},
9145
- ...options.background ? { background: options.background } : {}
9146
- })];
9147
- log(`\n🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${options.dryRun ? " (dry run — nothing is written)" : ""}`);
9148
- const plan = planStackDns({
9149
- stage,
9150
- hosts,
9151
- server,
9152
- dns: workspace.dns
8287
+ function assertExternalServices(input) {
8288
+ const services = externalServices(input);
8289
+ if (services.missing.length > 0) throw new ExternalServicesNotConfigured(input.stage, services.missing);
8290
+ return services;
8291
+ }
8292
+ /** The dev services a run uses, one entry per service it runs. */
8293
+ function devServicesUsed(services) {
8294
+ const used = [];
8295
+ if (services.mailpit.length > 0) used.push({
8296
+ service: "mailpit",
8297
+ ids: services.mailpit
9153
8298
  });
9154
- try {
9155
- const changes = await applyStackDns(plan, {
9156
- ...options.dryRun ? { dryRun: true } : {},
9157
- log,
9158
- credentials: {
9159
- env: options.env ?? process.env,
9160
- ...options.home ? { home: options.home } : {},
9161
- log
9162
- },
9163
- ...options.providerFor ? { providerFor: options.providerFor } : {}
8299
+ if (services.minio.length > 0) used.push({
8300
+ service: "minio",
8301
+ ids: services.minio
8302
+ });
8303
+ return used;
8304
+ }
8305
+ /** The line a run prints for each dev service a deployed stage uses. */
8306
+ function devServiceWarning(stage, use) {
8307
+ return `⚠️ DEV SERVICE ON A DEPLOYED STAGE (${stage}): ${use.service === "mailpit" ? `Mailpit is catching mail for ${use.ids.join(", ")}. It delivers NO mail: nobody receives a sign-in link, a receipt or a reset` : `MinIO is storing ${use.ids.join(", ")}. Every object is on one container's disk, with no replication and no backup`}. It is not production-grade — set the stage's own keys in its secrets for that.`;
8308
+ }
8309
+ /**
8310
+ * Report each dev service a run uses: a loud line, and a `dev-service.used`
8311
+ * event a host can act on.
8312
+ */
8313
+ function reportDevServices(ctx, uses) {
8314
+ for (const use of uses) {
8315
+ ctx.logger.warn(`\n${devServiceWarning(ctx.stage, use)}`);
8316
+ ctx.emit({
8317
+ type: "dev-service.used",
8318
+ service: use.service,
8319
+ stage: ctx.stage,
8320
+ constructs: use.ids
9164
8321
  });
9165
- if (options.journal && !options.dryRun) {
9166
- const providers = new Map(plan.domains.map((domain) => [domain.domain, domain.provider]));
9167
- await recordDnsChanges(options.journal, changes, (domain) => providers.get(domain));
9168
- }
9169
- return {
9170
- mode: "records",
9171
- hosts,
9172
- changes
9173
- };
9174
- } catch (error) {
9175
- if (error instanceof MissingCredential) {
9176
- log(` ⚠ ${error.message}`);
9177
- log(" Until then, create these records yourself:");
9178
- for (const domain of plan.domains) for (const r of domain.records) log(` ${r.host.padEnd(32)} ${r.type.padEnd(5)} ${r.value} (TTL ${r.ttl})`);
9179
- return {
9180
- mode: "records",
9181
- hosts,
9182
- changes: []
9183
- };
9184
- }
9185
- throw error;
9186
8322
  }
9187
8323
  }
9188
8324
  //#endregion
9189
- //#region src/providers/aws.ts
9190
- /**
9191
- * The AWS account a provider provisions in — the stage's, found the way the
9192
- * SSM and Secrets Manager stores find it.
9193
- *
9194
- * 1. `--profile`, resolved on its own: exported keys left over from another
9195
- * account never win over a profile someone named.
9196
- * 2. `AWS_PROFILE`, else `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` — the
9197
- * deploy's own `aws` credential kind (`storedCredentials`).
9198
- * 3. The SDK's default chain: `~/.aws` default profile, SSO, a role. In CI,
9199
- * whatever `aws-actions/configure-aws-credentials` exported.
9200
- *
9201
- * None of them: the provider has no provisioning credentials, and the stage
9202
- * is treated as `external`.
9203
- */
9204
- async function awsProvisioningCredentials(lookup) {
9205
- const region = lookup.env.AWS_REGION ?? lookup.env.AWS_DEFAULT_REGION;
9206
- const where = region ? { region } : {};
9207
- if (lookup.profile) return {
9208
- profile: lookup.profile,
9209
- ...where
9210
- };
9211
- const stored = await storedCredentials({
9212
- env: lookup.env,
9213
- ...lookup.home ? { home: lookup.home } : {}
9214
- }).get({
9215
- kind: "aws",
9216
- stage: lookup.stage
9217
- });
9218
- if (stored) return stored;
9219
- try {
9220
- const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
9221
- await fromNodeProviderChain({
9222
- timeout: 1e3,
9223
- maxRetries: 0
9224
- })();
9225
- return {
9226
- chain: true,
9227
- ...where
9228
- };
9229
- } catch {
9230
- return;
9231
- }
9232
- }
8325
+ //#region src/deploy/actor.ts
9233
8326
  /**
9234
- * An S3-compatible endpoint the environment points the SDK at — the AWS
9235
- * emulator in tests. The SDK reads it itself; it is read here too, because
9236
- * an emulator takes path-style requests, and a key written for one has to
9237
- * say where it is.
8327
+ * Who wrote a stage's deploy state: a GitHub Actions run, or a person at a
8328
+ * machine. Recorded on every state write (`updatedBy`), on every resource
8329
+ * record and on every release (`releasedBy`), so "who put this here" has an
8330
+ * answer that does not depend on anyone's memory.
9238
8331
  */
9239
- function awsEndpoint(env, service) {
9240
- return env[`AWS_ENDPOINT_URL_${service}`] ?? env.AWS_ENDPOINT_URL;
8332
+ /** Whether `env` is a CI job — GitHub Actions or any runner that sets `CI`. */
8333
+ function isCi(env = process.env) {
8334
+ return env.GITHUB_ACTIONS === "true" || env.CI === "true";
9241
8335
  }
9242
- /** An SDK client's config for a provisioning credential. */
9243
- async function awsClientConfig(credential, region) {
9244
- if ("profile" in credential) {
9245
- const { fromIni } = await import("@aws-sdk/credential-providers");
8336
+ /** Who this process is writing as. */
8337
+ function currentActor(env = process.env) {
8338
+ if (env.GITHUB_ACTIONS === "true") {
8339
+ const server = env.GITHUB_SERVER_URL ?? "https://github.com";
9246
8340
  return {
9247
- region,
9248
- credentials: fromIni({ profile: credential.profile })
8341
+ kind: "github",
8342
+ actor: env.GITHUB_ACTOR ?? "unknown",
8343
+ run: `${server}/${env.GITHUB_REPOSITORY ?? "unknown"}/actions/runs/${env.GITHUB_RUN_ID ?? "unknown"}`,
8344
+ ...env.GITHUB_WORKFLOW ? { workflow: env.GITHUB_WORKFLOW } : {}
9249
8345
  };
9250
8346
  }
9251
- if ("accessKeyId" in credential) return {
9252
- region,
9253
- credentials: {
9254
- accessKeyId: credential.accessKeyId,
9255
- secretAccessKey: credential.secretAccessKey,
9256
- ...credential.sessionToken ? { sessionToken: credential.sessionToken } : {}
9257
- }
8347
+ let user = "unknown";
8348
+ try {
8349
+ user = userInfo().username;
8350
+ } catch {}
8351
+ return {
8352
+ kind: "local",
8353
+ user,
8354
+ host: hostname()
9258
8355
  };
9259
- return { region };
9260
8356
  }
9261
- const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
9262
- /** A name that S3 would refuse — what the name builder never returns. */
9263
- var InvalidBucketName = class extends GkmError {
9264
- bucket;
9265
- reason;
9266
- constructor(bucket, reason) {
9267
- super(`'${bucket}' is not a valid S3 bucket name: ${reason}. Rename the construct or set deploy.namespace in gkm.config.ts to something that leaves room for it.`);
9268
- this.bucket = bucket;
9269
- this.reason = reason;
9270
- this.name = "InvalidBucketName";
9271
- }
9272
- };
9273
- /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
9274
- function part(value) {
9275
- return kebabCase(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
8357
+ /** `octocat (deploy, https://github.com/…/runs/1)` or `ada@laptop`. */
8358
+ function describeActor(actor) {
8359
+ if (!actor) return "unknown";
8360
+ if (actor.kind === "local") return `${actor.user}@${actor.host}`;
8361
+ return `${actor.actor} (${actor.workflow ? `${actor.workflow}, ` : ""}${actor.run})`;
9276
8362
  }
9277
- /**
9278
- * `parts` joined by `-`, shortened to `max` characters by trimming the longest
9279
- * part one character at a time — so a long construct id gives way before a
9280
- * short stage name does, and every part keeps its start.
9281
- */
9282
- function fitParts(parts, max) {
9283
- const kept = parts.map(part).filter(Boolean);
9284
- const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
9285
- while (length() > max) {
9286
- let longest = 0;
9287
- for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
9288
- if (kept[longest].length <= 1) break;
9289
- kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
9290
- }
9291
- return kept.join("-");
8363
+ //#endregion
8364
+ //#region src/deploy/dnsResources.ts
8365
+ /** The resource type of a DNS record gkm wrote. */
8366
+ const DNS_RECORD_RESOURCE = "dns-record";
8367
+ /** A record's full name: `api.example.com`, or the domain for `@`. */
8368
+ function dnsRecordFqdn(domain, name) {
8369
+ return name === "@" || name === "" ? domain : `${name}.${domain}`;
9292
8370
  }
9293
- /** Why `name` is not a valid bucket name, or undefined when it is. */
9294
- function bucketNameProblem(name) {
9295
- if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
9296
- if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
9297
- if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
9298
- if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
9299
- if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
8371
+ /** `dns-record:<fqdn>:<type>` */
8372
+ function dnsResourceKey(fqdn, type) {
8373
+ return `${DNS_RECORD_RESOURCE}:${fqdn.toLowerCase()}:${type.toUpperCase()}`;
9300
8374
  }
9301
- /**
9302
- * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
9303
- * dots, shortened to leave room for a clash's suffix.
9304
- *
9305
- * @throws {InvalidBucketName} when nothing usable is left
9306
- */
9307
- function bucketName(input) {
9308
- const name = fitParts([
9309
- input.scope,
9310
- input.stage,
9311
- input.id
9312
- ], 56);
9313
- const problem = bucketNameProblem(name);
9314
- if (problem) throw new InvalidBucketName(name, problem);
9315
- return name;
8375
+ /** The resource record a written DNS record is kept as. */
8376
+ function dnsRecordResource(record) {
8377
+ const fqdn = dnsRecordFqdn(record.domain, record.name).toLowerCase();
8378
+ const type = record.type.toUpperCase();
8379
+ const data = {
8380
+ domain: record.domain,
8381
+ name: record.name,
8382
+ value: record.value,
8383
+ ttl: record.ttl,
8384
+ ...record.provider ? { provider: record.provider } : {}
8385
+ };
8386
+ return {
8387
+ key: dnsResourceKey(fqdn, type),
8388
+ type: DNS_RECORD_RESOURCE,
8389
+ id: `${fqdn} ${type}`,
8390
+ status: "ready",
8391
+ data
8392
+ };
9316
8393
  }
9317
- /** Six random `[a-z0-9]` characters. */
9318
- function randomSuffix(random = randomInt) {
9319
- let suffix = "";
9320
- for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
9321
- return suffix;
8394
+ /** Records that gkm wrote `record` — or updates the value it holds. */
8395
+ async function recordDnsResource(journal, record) {
8396
+ const { key, type, id, data } = dnsRecordResource(record);
8397
+ await journal.ready({
8398
+ key,
8399
+ type,
8400
+ ...data ? { data } : {}
8401
+ }, id);
9322
8402
  }
9323
- /** The good name with a clash's suffix. */
9324
- function suffixedBucketName(good, suffix) {
9325
- return `${good}-${suffix}`;
8403
+ /** Forgets a DNS record gkm deleted. */
8404
+ async function forgetDnsResource(journal, record) {
8405
+ await journal.forget(dnsResourceKey(dnsRecordFqdn(record.domain, record.name), record.type));
9326
8406
  }
9327
8407
  /**
9328
- * The IAM user a bucket is reached with on a stage:
9329
- * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
8408
+ * The changes a DNS step made, kept: what it created, updated or wrote is
8409
+ * recorded, what it deleted is forgotten. A record it found already right is
8410
+ * recorded only if gkm wrote it before; one it left to a person is not.
9330
8411
  */
9331
- function iamUserName(input) {
9332
- return fitParts([
9333
- "gkm",
9334
- input.scope,
9335
- input.stage,
9336
- input.id
9337
- ], 64);
9338
- }
9339
- /** The path every user gkm creates is under, so it finds its own. */
9340
- const IAM_USER_PATH = "/gkm/";
9341
- /** The inline policy each user is given. */
9342
- const IAM_POLICY_NAME = "gkm-bucket";
9343
- //#endregion
9344
- //#region src/providers/s3/origins.ts
9345
- /**
9346
- * Which browser origins may call a bucket: the stage's sites that depend on
9347
- * an API using it.
9348
- *
9349
- * The same reading of the graph an API's own CORS origins are — its callers —
9350
- * taken one step further: a site that calls an API which hands it a presigned
9351
- * upload URL is a site whose browser PUTs to the bucket. A site that reads the
9352
- * bucket (or a file server over it) itself is one too. Nothing is written
9353
- * down: add a site that calls the API and the next provision run allows it.
9354
- */
9355
- /** The keys a reader of this bucket holds: its URL, and each server's over it. */
9356
- function bucketKeys(manifest, bucket) {
9357
- return [provideKey(bucket, "url"), ...Object.entries(manifest).filter(([, d]) => d.kind === "file-server" && d.of === bucket).map(([id]) => provideKey(id, "url"))];
9358
- }
9359
- function bucketOrigins(input) {
9360
- const { manifest, workspace, stage } = input;
9361
- const keys = bucketKeys(manifest, input.bucket);
9362
- const readers = Object.entries(manifest).filter(([, d]) => d.kind === "rest-api" || d.kind === "site").filter(([id]) => {
9363
- const env = appEnvKeys(manifest, appKey(id), input.runnables);
9364
- return env !== void 0 && keys.some((key) => env.has(key));
9365
- });
9366
- const sites = /* @__PURE__ */ new Set();
9367
- for (const [id, declaration] of readers) {
9368
- if (declaration.kind === "site") {
9369
- sites.add(id);
9370
- continue;
9371
- }
9372
- for (const caller of dependentsOf(manifest, id)) if (manifest[caller]?.kind === "site") sites.add(caller);
9373
- }
9374
- const origins = /* @__PURE__ */ new Set();
9375
- const unresolved = [];
9376
- for (const id of [...sites].sort()) {
9377
- const name = appKey(id);
9378
- const app = workspace.apps[name];
9379
- if (!app) {
9380
- unresolved.push(name);
8412
+ async function recordDnsChanges(journal, changes, providerOf) {
8413
+ for (const change of changes) {
8414
+ if (change.action === "delete") {
8415
+ await forgetDnsResource(journal, change);
9381
8416
  continue;
9382
8417
  }
9383
- try {
9384
- const host = resolveHost(name, app, stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
9385
- origins.add(`https://${host}`);
9386
- } catch (error) {
9387
- if (!(error instanceof NoDomainForStage)) throw error;
9388
- unresolved.push(name);
9389
- }
8418
+ const written = change.action === "create" || change.action === "update" || change.action === "write";
8419
+ const known = change.action === "unchanged" && journal.record(dnsResourceKey(dnsRecordFqdn(change.domain, change.name), change.type)) !== void 0;
8420
+ if (!written && !known || change.value === void 0) continue;
8421
+ const provider = providerOf(change.domain);
8422
+ await recordDnsResource(journal, {
8423
+ domain: change.domain,
8424
+ name: change.name,
8425
+ type: change.type,
8426
+ value: change.value,
8427
+ ttl: change.ttl ?? 0,
8428
+ ...provider ? { provider } : {}
8429
+ });
9390
8430
  }
9391
- return {
9392
- origins: [...origins].sort(),
9393
- unresolved
9394
- };
8431
+ }
8432
+ /** Every DNS record gkm wrote for the stage, from its resource records. */
8433
+ function dnsResources(resources) {
8434
+ return Object.values(resources).filter((record) => record.type === DNS_RECORD_RESOURCE).map((record) => {
8435
+ const data = record.data ?? {};
8436
+ const [fqdn = "", type = ""] = (record.id ?? "").split(" ");
8437
+ return {
8438
+ ...data,
8439
+ type,
8440
+ fqdn
8441
+ };
8442
+ }).sort((a, b) => a.fqdn.localeCompare(b.fqdn) || a.type.localeCompare(b.type));
9395
8443
  }
9396
8444
  //#endregion
9397
- //#region src/providers/s3/policy.ts
9398
- const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
8445
+ //#region src/docker/imageRef.ts
9399
8446
  /**
9400
- * What the app's key may do: objects in this bucket, and listing it — and
9401
- * nothing else in the account.
8447
+ * An image reference, checked before it reaches `docker`.
9402
8448
  *
9403
- * Multipart uploads are in it because a presigned upload of a large file is
9404
- * one, and an abandoned one is cleaned up by the app. Reading old versions is
9405
- * added only when the bucket keeps them.
8449
+ * The parts come from the workspace — a registry in `gkm.config.ts`, an image
8450
+ * name from the project, a tag from `--tag` — and an argument array already
8451
+ * keeps them out of a shell. What it cannot do is stop `docker` reading a value
8452
+ * that starts with `-` as one of its own flags, so a ref is held to Docker's
8453
+ * own grammar (distribution/reference) and anything else is refused by name
8454
+ * before a build starts.
9406
8455
  */
9407
- function userPolicy(bucket, options = {}) {
9408
- return {
9409
- Version: "2012-10-17",
9410
- Statement: [{
9411
- Sid: "GkmObjects",
9412
- Effect: "Allow",
9413
- Action: [
9414
- "s3:GetObject",
9415
- "s3:PutObject",
9416
- "s3:DeleteObject",
9417
- "s3:AbortMultipartUpload",
9418
- "s3:ListMultipartUploadParts",
9419
- ...options.versioning ? ["s3:GetObjectVersion"] : []
9420
- ],
9421
- Resource: `${bucketArn(bucket)}/*`
9422
- }, {
9423
- Sid: "GkmBucket",
9424
- Effect: "Allow",
9425
- Action: [
9426
- "s3:ListBucket",
9427
- "s3:GetBucketLocation",
9428
- "s3:ListBucketMultipartUploads"
9429
- ],
9430
- Resource: bucketArn(bucket)
9431
- }]
9432
- };
8456
+ const DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
8457
+ const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
8458
+ const PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
8459
+ const REFERENCE = new RegExp(`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::[\\w][\\w.-]{0,127})?(?:@[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,})?$`);
8460
+ /** Docker refuses a repository name longer than this. */
8461
+ const MAX_NAME_LENGTH = 255;
8462
+ /** A value that is not an image reference was about to be built or pushed. */
8463
+ var ImageRefInvalid = class extends GkmError {
8464
+ ref;
8465
+ constructor(ref) {
8466
+ super(`'${ref}' is not a valid image reference. An image is \`[registry/]name[:tag]\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`);
8467
+ this.ref = ref;
8468
+ this.name = "ImageRefInvalid";
8469
+ }
8470
+ };
8471
+ /** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */
8472
+ function validateImageRef(ref) {
8473
+ const name = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
8474
+ if (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) throw new ImageRefInvalid(ref);
8475
+ return ref;
9433
8476
  }
8477
+ //#endregion
8478
+ //#region src/docker/index.ts
8479
+ const logger = output;
8480
+ /** `docker build` failed; what docker printed above says why. */
8481
+ var DockerBuildFailed = class extends Error {
8482
+ imageRef;
8483
+ constructor(imageRef, cause) {
8484
+ super(`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
8485
+ this.imageRef = imageRef;
8486
+ this.name = "DockerBuildFailed";
8487
+ }
8488
+ };
8489
+ /** `docker push` failed — usually the registry login or its permissions. */
8490
+ var DockerPushFailed = class extends Error {
8491
+ imageRef;
8492
+ constructor(imageRef, cause) {
8493
+ super(`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
8494
+ this.imageRef = imageRef;
8495
+ this.name = "DockerPushFailed";
8496
+ }
8497
+ };
8498
+ /** `gkm docker --push` was asked for with nowhere to push to. */
8499
+ var PushNeedsRegistry = class extends GkmError {
8500
+ imageName;
8501
+ constructor(imageName) {
8502
+ super(`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`);
8503
+ this.imageName = imageName;
8504
+ this.name = "PushNeedsRegistry";
8505
+ }
8506
+ };
9434
8507
  /**
9435
- * One open pattern as the resource it is public on. A `**` is S3's `*`; a
9436
- * single `*` is too, which crosses `/` where the construct's own check does
9437
- * not — the construct is the stricter of the two (see `bucketPolicy` in
9438
- * reconcile, which the local MinIO is given the same way).
8508
+ * Docker command implementation: one Dockerfile per deployable app, each
8509
+ * building its image inside Docker from a turbo-pruned slice of the build
8510
+ * root — nothing is built on the host — plus the build root's
8511
+ * `.dockerignore` and `docker-compose.constructs.yml`.
9439
8512
  */
9440
- function openResource(bucket, pattern) {
9441
- const path = pattern.replace(/^\/+/, "").replace(/\*\*/g, "*");
9442
- return `${bucketArn(bucket)}/${path}`;
8513
+ async function dockerCommand(options) {
8514
+ const cwd = options.cwd ?? process.cwd();
8515
+ const loaded = await loadWorkspaceConfig(cwd);
8516
+ const names = loaded.type === "single" ? Object.fromEntries(Object.keys(loaded.workspace.apps).map((name) => [name, resolveDockerConfig(loaded.raw).imageName])) : {};
8517
+ const result = await workspaceDockerCommand(loaded.workspace, loaded.manifest, names, loaded.background, options.stage);
8518
+ if (options.build) for (const app of result.apps) await buildDockerImage(app, result.buildRoot, options);
8519
+ if (options.push) for (const app of result.apps) await pushDockerImage(app.imageName, options, result.buildRoot);
8520
+ return result;
9443
8521
  }
9444
8522
  /**
9445
- * The bucket's own policy: every request refused unless it came over TLS,
9446
- * and — only when a file server opens paths on it — anonymous `s3:GetObject`
9447
- * on exactly those prefixes.
8523
+ * Build one app's image, from the build root.
8524
+ * Uses BuildKit for cache mount support
9448
8525
  */
9449
- function bucketPolicy(bucket, open = []) {
9450
- const statements = [{
9451
- Sid: "GkmDenyInsecureTransport",
9452
- Effect: "Deny",
9453
- Principal: "*",
9454
- Action: "s3:*",
9455
- Resource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],
9456
- Condition: { Bool: { "aws:SecureTransport": "false" } }
9457
- }];
9458
- if (open.length > 0) statements.push({
9459
- Sid: "GkmOpenPaths",
9460
- Effect: "Allow",
9461
- Principal: "*",
9462
- Action: "s3:GetObject",
9463
- Resource: [...new Set(open.map((p) => openResource(bucket, p)))].sort()
9464
- });
9465
- return {
9466
- Version: "2012-10-17",
9467
- Statement: statements
9468
- };
8526
+ async function buildDockerImage(app, buildRoot, options) {
8527
+ const tag = options.tag ?? "latest";
8528
+ const registry = options.registry;
8529
+ const fullImageName = validateImageRef(registry ? `${registry}/${app.imageName}:${tag}` : `${app.imageName}:${tag}`);
8530
+ logger.log(`\n🐳 Building Docker image: ${fullImageName}`);
8531
+ try {
8532
+ await run$1("docker", [
8533
+ "build",
8534
+ `--file=${relative(buildRoot, app.dockerfile)}`,
8535
+ `--tag=${fullImageName}`,
8536
+ "."
8537
+ ], {
8538
+ cwd: buildRoot,
8539
+ env: {
8540
+ ...process.env,
8541
+ DOCKER_BUILDKIT: "1"
8542
+ }
8543
+ });
8544
+ logger.log(`✅ Docker image built: ${fullImageName}`);
8545
+ } catch (error) {
8546
+ throw new DockerBuildFailed(fullImageName, error);
8547
+ }
9469
8548
  }
9470
8549
  /**
9471
- * Block Public Access. All four flags on, unless the bucket has open paths:
9472
- * then a *policy* may make it public (`BlockPublicPolicy`,
9473
- * `RestrictPublicBuckets` off), and ACLs still may not.
8550
+ * Push Docker image to registry
9474
8551
  */
9475
- function publicAccessBlock(open) {
9476
- return {
9477
- BlockPublicAcls: true,
9478
- IgnorePublicAcls: true,
9479
- BlockPublicPolicy: !open,
9480
- RestrictPublicBuckets: !open
9481
- };
9482
- }
9483
- function corsRule(origins) {
9484
- return {
9485
- AllowedMethods: [
9486
- "GET",
9487
- "HEAD",
9488
- "POST",
9489
- "PUT"
9490
- ],
9491
- AllowedOrigins: [...new Set(origins)].sort(),
9492
- AllowedHeaders: ["*"],
9493
- ExposeHeaders: ["ETag"],
9494
- MaxAgeSeconds: 3e3
9495
- };
8552
+ async function pushDockerImage(imageName, options, cwd) {
8553
+ const tag = options.tag ?? "latest";
8554
+ const registry = options.registry;
8555
+ if (!registry) throw new PushNeedsRegistry(imageName);
8556
+ const fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);
8557
+ logger.log(`\n🚀 Pushing Docker image: ${fullImageName}`);
8558
+ try {
8559
+ await run$1("docker", ["push", fullImageName], { cwd });
8560
+ logger.log(`✅ Docker image pushed: ${fullImageName}`);
8561
+ } catch (error) {
8562
+ throw new DockerPushFailed(fullImageName, error);
8563
+ }
9496
8564
  }
9497
8565
  /**
9498
- * A policy document in one canonical form — keys sorted, a lone string a
9499
- * one-element list, lists sorted — so one AWS reformatted reads as the same
9500
- * document rather than as drift.
8566
+ * Generate Dockerfiles for all apps in a workspace.
8567
+ * @internal Exported for testing
9501
8568
  */
9502
- function canonicalPolicy(value) {
9503
- return JSON.stringify(canonical(value));
9504
- }
9505
- function canonical(value, key) {
9506
- if (Array.isArray(value)) {
9507
- const items = value.map((v) => canonical(v));
9508
- return key === "Statement" ? items : items.map((v) => JSON.stringify(v)).sort();
8569
+ async function workspaceDockerCommand(workspace, manifest, imageNames = {}, background = {}, stage) {
8570
+ const results = [];
8571
+ const layout = imageLayout(workspace);
8572
+ logger.log(`\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);
8573
+ logger.log(` Build root: ${layout.buildRoot}`);
8574
+ logger.log(` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ""}, turbo@${layout.tools.turboVersion}`);
8575
+ for (const [appName, app] of Object.entries(workspace.apps)) {
8576
+ if (app.type === "mobile") {
8577
+ logger.log(`\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`);
8578
+ continue;
8579
+ }
8580
+ const buildType = app.entry ? "entry" : app.type;
8581
+ logger.log(`\n 📄 Generating Dockerfile for ${appName} (${buildType})`);
8582
+ const dockerfile = appDockerfile(appName, app, {
8583
+ layout,
8584
+ workspaceRoot: workspace.root,
8585
+ apps: workspace.apps,
8586
+ ...manifest ? { manifest } : {},
8587
+ workspace,
8588
+ ...stage ? { stage } : {}
8589
+ });
8590
+ const path = dockerfileOf(appName, app.path);
8591
+ const dockerfilePath = join(workspace.root, path);
8592
+ await mkdir(dirname(dockerfilePath), { recursive: true });
8593
+ await writeFile(dockerfilePath, dockerfile);
8594
+ logger.log(` Generated: ${path}`);
8595
+ results.push({
8596
+ appName,
8597
+ type: app.type,
8598
+ dockerfile: dockerfilePath,
8599
+ imageName: imageNames[appName] ?? appName
8600
+ });
8601
+ }
8602
+ for (const worker of manifest ? workerUnits(workspace, manifest, background) : []) {
8603
+ logger.log(`\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`);
8604
+ const dockerfile = workerDockerfile(worker, workspace.apps[worker.app], {
8605
+ layout,
8606
+ workspaceRoot: workspace.root
8607
+ });
8608
+ const path = workerDockerfileOf(worker.name);
8609
+ const dockerfilePath = join(workspace.root, path);
8610
+ await mkdir(dirname(dockerfilePath), { recursive: true });
8611
+ await writeFile(dockerfilePath, dockerfile);
8612
+ logger.log(` Generated: ${path}`);
8613
+ results.push({
8614
+ appName: worker.name,
8615
+ type: "backend",
8616
+ dockerfile: dockerfilePath,
8617
+ imageName: imageNames[worker.name] ?? worker.name
8618
+ });
9509
8619
  }
9510
- if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => {
9511
- const v = value[k];
9512
- return [k, canonical(k === "Action" || k === "Resource" || k === "AWS" ? Array.isArray(v) ? v : [v] : v, k)];
9513
- }));
9514
- return value;
9515
- }
9516
- //#endregion
9517
- //#region src/providers/s3/index.ts
9518
- /** The tags gkm finds its own buckets and users by. */
9519
- const TAG_PROJECT = "gkm:project";
9520
- const TAG_STAGE = "gkm:stage";
9521
- const TAG_CONSTRUCT = "gkm:construct";
9522
- function bucketConstructs(manifest) {
9523
- return Object.entries(manifest).filter(([, d]) => d.kind === "objects").map(([id, d]) => ({
9524
- id,
9525
- versioned: d.versioned === true,
9526
- servers: Object.entries(manifest).filter(([, s]) => s.kind === "file-server" && s.of === id).map(([sid, s]) => ({
9527
- id: sid,
9528
- open: s.open ?? []
9529
- })).sort((a, b) => a.id.localeCompare(b.id))
9530
- })).sort((a, b) => a.id.localeCompare(b.id));
9531
- }
9532
- /**
9533
- * The region the stage's buckets are created in: the entry's, the secrets
9534
- * store's when it is in AWS, the credential's, `AWS_REGION`.
9535
- */
9536
- function s3Region(ctx, env = process.env) {
9537
- const store = ctx.workspace.secrets?.store;
9538
- const storeRegion = store && typeof store === "object" && "region" in store ? store.region : void 0;
9539
- const region = ctx.config.region ?? storeRegion ?? ctx.credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
9540
- if (!region) throw new S3RegionRequired(ctx.stage);
9541
- return region;
9542
- }
9543
- /**
9544
- * The address a file server over `bucket` serves on: the bucket's regional
9545
- * virtual-host endpoint, which is what `FileServer.url(key)` appends a key to
9546
- * — `https://<bucket>.s3.<region>.amazonaws.com/<key>`. Against an emulator,
9547
- * its path-style address.
9548
- */
9549
- function bucketPublicUrl(bucket, region, endpoint) {
9550
- if (endpoint) return `${endpoint.replace(/\/+$/, "")}/${bucket}`;
9551
- return `https://${bucket}.s3.${region}.amazonaws.com`;
9552
- }
9553
- /** What an AWS SDK error is called, whichever field carries it. */
9554
- function errorName(error) {
9555
- const e = error;
9556
- return e?.Code ?? e?.name ?? "";
9557
- }
9558
- /** A read whose "there is none" answer is one of `missing`. */
9559
- async function readOr(read, missing) {
9560
- try {
9561
- return await read();
9562
- } catch (error) {
9563
- if (missing.includes(errorName(error))) return void 0;
9564
- throw error;
8620
+ const dockerignorePath = await ensureDockerignore(layout.buildRoot);
8621
+ logger.log(`\n Ensured: ${dockerignorePath}`);
8622
+ const composePath = await writeConstructsCompose(workspace);
8623
+ logger.log(`\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`);
8624
+ logger.log(`\n📋 Build commands (from ${layout.buildRoot}):`);
8625
+ for (const result of results) {
8626
+ const icon = result.type === "backend" ? "⚙️" : result.type === "mobile" ? "📱" : "🌐";
8627
+ logger.log(` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`);
9565
8628
  }
9566
- }
9567
- const defaultClients = async (credential, region) => {
9568
- const S3 = await import("@aws-sdk/client-s3");
9569
- const IAM = await import("@aws-sdk/client-iam");
9570
- const config = await awsClientConfig(credential, region);
9571
- const endpoint = awsEndpoint(process.env, "S3");
8629
+ printRunInstructions(workspace);
9572
8630
  return {
9573
- S3,
9574
- IAM,
9575
- s3: new S3.S3Client({
9576
- ...config,
9577
- ...endpoint ? {
9578
- endpoint,
9579
- forcePathStyle: true
9580
- } : {}
9581
- }),
9582
- iam: new IAM.IAMClient(config),
9583
- region,
9584
- ...endpoint ? { endpoint } : {}
9585
- };
9586
- };
9587
- /** For tests: what makes the clients. */
9588
- let makeClients = defaultClients;
9589
- async function ensureS3(ctx) {
9590
- const region = s3Region(ctx);
9591
- const clients = await makeClients(ctx.credential, region);
9592
- for (const construct of bucketConstructs(ctx.manifest)) await ensureBucket(ctx, clients, construct);
9593
- }
9594
- /** The keys gkm tags a bucket and a user with. */
9595
- function identityTags(ctx, id) {
9596
- return [
9597
- {
9598
- Key: TAG_PROJECT,
9599
- Value: ctx.identity.key
9600
- },
9601
- {
9602
- Key: TAG_STAGE,
9603
- Value: ctx.stage
9604
- },
9605
- {
9606
- Key: TAG_CONSTRUCT,
9607
- Value: id
9608
- }
9609
- ];
9610
- }
9611
- async function ensureBucket(ctx, clients, construct) {
9612
- const { id } = construct;
9613
- const nameInput = {
9614
- scope: ctx.identity.scope,
9615
- stage: ctx.stage,
9616
- id: appKey(id)
8631
+ apps: results,
8632
+ dockerCompose: composePath,
8633
+ dockerignore: dockerignorePath,
8634
+ buildRoot: layout.buildRoot
9617
8635
  };
9618
- const versioning = ctx.config.versioning ?? construct.versioned;
9619
- const open = [...new Set(construct.servers.flatMap((s) => s.open))].sort();
9620
- const { bucket, exists } = await ensureBucketName(ctx, clients, id, bucketName(nameInput));
9621
- await ensureBucketSettings(ctx, clients, {
9622
- id,
9623
- bucket,
9624
- exists,
9625
- versioning,
9626
- open
9627
- });
9628
- await ensureAccessKey(ctx, clients, {
9629
- id,
9630
- bucket,
9631
- ...await ensureUser(ctx, clients, id, iamUserName(nameInput), userPolicy(bucket, { versioning }))
9632
- });
9633
- const publicUrl = bucketPublicUrl(bucket, clients.region, clients.endpoint);
9634
- for (const server of construct.servers) {
9635
- const key = provideKey(server.id, "url");
9636
- const entry = {
9637
- key: `file-server:${server.id}`,
9638
- type: "url"
9639
- };
9640
- const recorded = ctx.state.record(entry.key)?.id;
9641
- const current = ctx.secrets[key];
9642
- if (current === publicUrl) {
9643
- await ctx.state.ready(entry, publicUrl);
9644
- continue;
9645
- }
9646
- if (current !== void 0 && current !== recorded) {
9647
- ctx.log(` ${key} is set to ${current} by you, and kept — the bucket's own address is ${publicUrl}`);
9648
- continue;
9649
- }
9650
- await ctx.change({
9651
- construct: server.id,
9652
- resource: key,
9653
- change: `set to ${publicUrl}`
9654
- }, async () => {
9655
- await ctx.writeSecrets({ [key]: publicUrl });
9656
- await ctx.state.ready(entry, publicUrl);
9657
- });
9658
- }
9659
8636
  }
9660
8637
  /**
9661
- * The bucket's name: the recorded one, else the good name, else the good
9662
- * name with a random suffix — up to {@link SUFFIX_ATTEMPTS} times.
8638
+ * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,
8639
+ * a backend with its own entry bundled by esbuild, or a site by its
8640
+ * framework. The one choice every builder of images makes.
9663
8641
  */
9664
- async function ensureBucketName(ctx, clients, id, good) {
9665
- const { S3, s3, region } = clients;
9666
- const key = `s3-bucket:${id}`;
9667
- const record = ctx.state.record(key);
9668
- const entry = (name) => ({
9669
- key,
9670
- type: "s3-bucket",
9671
- data: {
9672
- name,
9673
- region
9674
- }
9675
- });
9676
- /** Whether this account holds `name`: yes, no, or someone else does. */
9677
- const probe = async (name) => {
9678
- try {
9679
- await s3.send(new S3.HeadBucketCommand({ Bucket: name }));
9680
- return "ours";
9681
- } catch (error) {
9682
- const name = errorName(error);
9683
- if (name === "NotFound" || name === "NoSuchBucket") return "none";
9684
- if (name === "Forbidden" || name === "AccessDenied") return "taken";
9685
- throw error;
9686
- }
9687
- };
9688
- const create = async (name) => {
9689
- if (ctx.dryRun) {
9690
- const found = await probe(name);
9691
- if (found === "none") {
9692
- await ctx.change({
9693
- construct: id,
9694
- resource: `bucket ${name}`,
9695
- change: `create in ${region}`
9696
- }, async () => {});
9697
- return "created";
9698
- }
9699
- return found;
9700
- }
9701
- await ctx.state.pending(entry(name));
9702
- try {
9703
- await s3.send(new S3.CreateBucketCommand({
9704
- Bucket: name,
9705
- ...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
9706
- }));
9707
- } catch (error) {
9708
- const code = errorName(error);
9709
- if (code === "BucketAlreadyOwnedByYou") return "ours";
9710
- if (code === "BucketAlreadyExists") return "taken";
9711
- throw error;
9712
- }
9713
- await ctx.change({
9714
- construct: id,
9715
- resource: `bucket ${name}`,
9716
- change: `create in ${region}`
9717
- }, async () => {});
9718
- return "created";
9719
- };
9720
- const adopt = async (name) => {
9721
- const owner = (await readOr(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket: name })), ["NoSuchTagSet", "NoSuchTagSetError"]))?.TagSet?.find((t) => t.Key === TAG_PROJECT)?.Value;
9722
- if (owner && owner !== ctx.identity.key) throw new BucketOwnedByAnotherProject(name, owner, ctx.identity.key);
9723
- };
9724
- if (record?.status === "ready" && record.id) {
9725
- const found = await probe(record.id);
9726
- if (found === "ours") return {
9727
- bucket: record.id,
9728
- exists: true
9729
- };
9730
- if (found === "taken") throw new RecordedBucketUnreachable(id, record.id);
9731
- const made = await create(record.id);
9732
- if (made === "taken") throw new RecordedBucketUnreachable(id, record.id);
9733
- if (!ctx.dryRun) await ctx.state.ready(entry(record.id), record.id);
9734
- return {
9735
- bucket: record.id,
9736
- exists: made === "ours"
9737
- };
9738
- }
9739
- const pending = record?.data?.name;
9740
- const names = [
9741
- ...typeof pending === "string" && pending !== good ? [pending] : [],
9742
- good,
9743
- ...Array.from({ length: 5 }, () => suffixedBucketName(good, randomSuffix()))
9744
- ];
9745
- const tried = [];
9746
- for (const name of names) {
9747
- tried.push(name);
9748
- const made = await create(name);
9749
- if (made === "taken") continue;
9750
- if (made === "ours") await adopt(name);
9751
- if (!ctx.dryRun) await ctx.state.ready(entry(name), name);
9752
- if (name !== good) ctx.log(` '${good}' is taken by another account; '${id}' is '${name}', recorded in the stage's state`);
9753
- return {
9754
- bucket: name,
9755
- exists: made === "ours"
9756
- };
9757
- }
9758
- throw new BucketNameUnavailable(id, tried.filter((n) => n !== pending));
9759
- }
9760
- /** Tags, Block Public Access, encryption, policy, versioning and CORS. */
9761
- async function ensureBucketSettings(ctx, clients, input) {
9762
- const { S3, s3 } = clients;
9763
- const { id, bucket } = input;
9764
- const Bucket = bucket;
9765
- const fresh = ctx.dryRun && !input.exists;
9766
- const read = async (fn, missing) => fresh ? void 0 : readOr(fn, missing);
9767
- const set = (change, apply) => ctx.change({
9768
- construct: id,
9769
- resource: `bucket ${bucket}`,
9770
- change
9771
- }, () => apply().then(() => void 0));
9772
- const tagged = await read(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket })), ["NoSuchTagSet", "NoSuchTagSetError"]);
9773
- const ours = identityTags(ctx, id);
9774
- const others = (tagged?.TagSet ?? []).filter((t) => !ours.some((o) => o.Key === t.Key));
9775
- if (ours.some((o) => !tagged?.TagSet?.some((t) => t.Key === o.Key && t.Value === o.Value))) await set("tag", () => s3.send(new S3.PutBucketTaggingCommand({
9776
- Bucket,
9777
- Tagging: { TagSet: [...others, ...ours].map((t) => ({
9778
- Key: t.Key,
9779
- Value: t.Value
9780
- })) }
9781
- })));
9782
- const isOpen = input.open.length > 0;
9783
- const block = publicAccessBlock(isOpen);
9784
- const ensureBlock = async () => {
9785
- const now = (await read(() => s3.send(new S3.GetPublicAccessBlockCommand({ Bucket })), ["NoSuchPublicAccessBlockConfiguration"]))?.PublicAccessBlockConfiguration;
9786
- if (!(now && Object.keys(block).every((k) => (now[k] ?? false) === block[k]))) await set(isOpen ? "block public access (ACLs; the policy opens the open paths)" : "block all public access", () => s3.send(new S3.PutPublicAccessBlockCommand({
9787
- Bucket,
9788
- PublicAccessBlockConfiguration: block
9789
- })));
9790
- };
9791
- const policy = bucketPolicy(bucket, input.open);
9792
- const ensurePolicy = async () => {
9793
- const current = await read(() => s3.send(new S3.GetBucketPolicyCommand({ Bucket })), ["NoSuchBucketPolicy"]);
9794
- if (!(current?.Policy !== void 0 && canonicalPolicy(JSON.parse(current.Policy)) === canonicalPolicy(policy))) await set(isOpen ? `policy: TLS only, public read on ${input.open.join(", ")}` : "policy: TLS only", () => s3.send(new S3.PutBucketPolicyCommand({
9795
- Bucket,
9796
- Policy: JSON.stringify(policy)
9797
- })));
9798
- };
9799
- if (isOpen) {
9800
- await ensureBlock();
9801
- await ensurePolicy();
9802
- } else {
9803
- await ensurePolicy();
9804
- await ensureBlock();
9805
- }
9806
- if ((await read(() => s3.send(new S3.GetBucketEncryptionCommand({ Bucket })), ["ServerSideEncryptionConfigurationNotFoundError"]))?.ServerSideEncryptionConfiguration?.Rules?.[0]?.ApplyServerSideEncryptionByDefault?.SSEAlgorithm !== "AES256" && !fresh) await set("encrypt by default (SSE-S3)", () => s3.send(new S3.PutBucketEncryptionCommand({
9807
- Bucket,
9808
- ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
9809
- })));
9810
- const status = (await read(() => s3.send(new S3.GetBucketVersioningCommand({ Bucket })), []))?.Status;
9811
- if (input.versioning && status !== "Enabled") await set("enable versioning", () => s3.send(new S3.PutBucketVersioningCommand({
9812
- Bucket,
9813
- VersioningConfiguration: { Status: "Enabled" }
9814
- })));
9815
- else if (!input.versioning && status === "Enabled") await set("suspend versioning", () => s3.send(new S3.PutBucketVersioningCommand({
9816
- Bucket,
9817
- VersioningConfiguration: { Status: "Suspended" }
9818
- })));
9819
- const { origins, unresolved } = bucketOrigins({
9820
- workspace: ctx.workspace,
9821
- manifest: ctx.manifest,
9822
- runnables: ctx.runnables,
9823
- stage: ctx.stage,
9824
- bucket: id
9825
- });
9826
- if (unresolved.length > 0) ctx.log(` ${unresolved.join(", ")} ${unresolved.length === 1 ? "has" : "have"} no address on '${ctx.stage}' (domains.${ctx.stage}), so ${unresolved.length === 1 ? "is" : "are"} not in '${bucket}''s CORS`);
9827
- if (origins.length === 0) return;
9828
- const rule = corsRule(origins);
9829
- const cors = await read(() => s3.send(new S3.GetBucketCorsCommand({ Bucket })), ["NoSuchCORSConfiguration"]);
9830
- if (!(cors?.CORSRules?.length === 1 && canonicalCors(cors.CORSRules[0]) === canonicalCors(rule))) await set(`CORS for ${origins.join(", ")}`, () => s3.send(new S3.PutBucketCorsCommand({
9831
- Bucket,
9832
- CORSConfiguration: { CORSRules: [rule] }
9833
- })));
9834
- }
9835
- function canonicalCors(rule) {
9836
- const sorted = (list) => [...list ?? []].sort();
9837
- return JSON.stringify({
9838
- AllowedMethods: sorted(rule.AllowedMethods),
9839
- AllowedOrigins: sorted(rule.AllowedOrigins),
9840
- AllowedHeaders: sorted(rule.AllowedHeaders),
9841
- ExposeHeaders: sorted(rule.ExposeHeaders),
9842
- MaxAgeSeconds: rule.MaxAgeSeconds ?? null
8642
+ function appDockerfile(appName, app, options) {
8643
+ const image = appImageOptions(options.layout, appName, app, options.workspaceRoot, options.apps, app.type === "web" && options.manifest && options.workspace ? siteClientTelemetry(options.manifest, appName, options.workspace, options.stage) : void 0);
8644
+ if (app.type === "web") return siteDockerfile(appName, app, {
8645
+ image,
8646
+ ...options.manifest ? { manifest: options.manifest } : {},
8647
+ ...options.publicUrlArgs ? { publicUrlArgs: options.publicUrlArgs } : {}
9843
8648
  });
9844
- }
9845
- /** The bucket's IAM user and its inline policy. */
9846
- async function ensureUser(ctx, clients, id, user, policy) {
9847
- const { IAM, iam } = clients;
9848
- const entry = {
9849
- key: `iam-user:${id}`,
9850
- type: "iam-user"
9851
- };
9852
- const found = await readOr(() => iam.send(new IAM.GetUserCommand({ UserName: user })), ["NoSuchEntity", "NoSuchEntityException"]);
9853
- if (found?.User) {
9854
- const tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
9855
- const tag = (key) => tags.Tags?.find((t) => t.Key === key)?.Value;
9856
- if (found.User.Path !== "/gkm/" || tag("gkm:project") !== ctx.identity.key || tag("gkm:stage") !== ctx.stage) throw new IamUserNotOwned(user, ctx.identity.key, ctx.stage);
9857
- await ctx.state.ready(entry, user);
9858
- } else await ctx.change({
9859
- construct: id,
9860
- resource: `IAM user ${user}`,
9861
- change: `create under ${IAM_USER_PATH}`
9862
- }, async () => {
9863
- await ctx.state.pending(entry);
9864
- await iam.send(new IAM.CreateUserCommand({
9865
- UserName: user,
9866
- Path: IAM_USER_PATH,
9867
- Tags: identityTags(ctx, id)
9868
- }));
9869
- await ctx.state.ready(entry, user);
8649
+ if (app.entry) return generateEntryDockerfile({
8650
+ ...image,
8651
+ entry: app.entry,
8652
+ healthCheckPath: "/health"
9870
8653
  });
9871
- const exists = Boolean(found?.User) || !ctx.dryRun;
9872
- const current = exists ? await readOr(() => iam.send(new IAM.GetUserPolicyCommand({
9873
- UserName: user,
9874
- PolicyName: IAM_POLICY_NAME
9875
- })), ["NoSuchEntity", "NoSuchEntityException"]) : void 0;
9876
- const document = current?.PolicyDocument ? JSON.parse(decodePolicy(current.PolicyDocument)) : void 0;
9877
- if (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) await ctx.change({
9878
- construct: id,
9879
- resource: `IAM user ${user}`,
9880
- change: `policy ${IAM_POLICY_NAME}: this bucket only`
9881
- }, async () => {
9882
- await iam.send(new IAM.PutUserPolicyCommand({
9883
- UserName: user,
9884
- PolicyName: IAM_POLICY_NAME,
9885
- PolicyDocument: JSON.stringify(policy)
9886
- }));
8654
+ return generateBackendDockerfile({
8655
+ ...image,
8656
+ healthCheckPath: "/health",
8657
+ ...options.cache ? { cache: options.cache } : {}
9887
8658
  });
9888
- return {
9889
- user,
9890
- exists
9891
- };
9892
8659
  }
9893
- /** IAM returns a policy document URL-encoded; an emulator may not. */
9894
- function decodePolicy(document) {
9895
- try {
9896
- return decodeURIComponent(document);
9897
- } catch {
9898
- return document;
9899
- }
8660
+ /** Where `gkm docker` writes a worker's Dockerfile. */
8661
+ function workerDockerfileOf(worker) {
8662
+ return `.gkm/docker/Dockerfile.${worker}`;
9900
8663
  }
9901
8664
  /**
9902
- * The user's access key, in the stage's secrets as the bucket's URL.
9903
- *
9904
- * - First run: one key, written into the stage's secrets.
9905
- * - `--rotate-keys`: a second key, written in place of the first; the first
9906
- * stays active until the stage has deployed with the second, and the next
9907
- * run after that deploy — or `--retire-old-keys` — deletes it.
9908
- * - A key the secrets no longer hold (a store emptied by hand): replaced the
9909
- * same way, since its secret cannot be read back.
8665
+ * A Worker's Dockerfile: its host app's build, and the worker's bundle as the
8666
+ * runner — see `generateWorkerDockerfile`.
9910
8667
  */
9911
- async function ensureAccessKey(ctx, clients, input) {
9912
- const { IAM, iam } = clients;
9913
- const { id, bucket, user } = input;
9914
- const urlKey = provideKey(id, "url");
9915
- const entryKey = `iam-access-key:${id}`;
9916
- const record = ctx.state.record(entryKey);
9917
- const given = ctx.secrets[urlKey];
9918
- let inUrl;
9919
- if (given !== void 0) {
9920
- let parsed;
9921
- try {
9922
- parsed = s3Url.parse(given);
9923
- } catch {
9924
- parsed = void 0;
9925
- }
9926
- if (parsed?.bucket !== bucket) throw new BucketKeySetElsewhere(urlKey, bucket, parsed?.bucket ?? given.replace(/\/\/[^@]*@/, "//"), ctx.stage);
9927
- inUrl = parsed.accessKeyId;
9928
- }
9929
- const listed = input.exists ? (await iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))).AccessKeyMetadata?.map((k) => k.AccessKeyId) ?? [] : [];
9930
- let current = record?.status === "ready" ? record.id : void 0;
9931
- let previous = typeof record?.data?.previous === "string" ? record.data.previous : void 0;
9932
- const rotatedAt = typeof record?.data?.rotatedAt === "string" ? record.data.rotatedAt : void 0;
9933
- const entry = (data = {}) => ({
9934
- key: entryKey,
9935
- type: "iam-access-key",
9936
- data: {
9937
- user,
9938
- ...data
9939
- }
9940
- });
9941
- if (previous && current) {
9942
- const deployed = rotatedAt !== void 0 && ctx.state.lastDeployedAt !== void 0 && ctx.state.lastDeployedAt > rotatedAt;
9943
- if (ctx.retireOldKeys || deployed) {
9944
- const old = previous;
9945
- const keep = current;
9946
- await ctx.change({
9947
- construct: id,
9948
- resource: `IAM user ${user}`,
9949
- change: `delete the rotated-out access key ${old}`
9950
- }, async () => {
9951
- if (listed.includes(old)) await iam.send(new IAM.DeleteAccessKeyCommand({
9952
- UserName: user,
9953
- AccessKeyId: old
9954
- }));
9955
- await ctx.state.ready(entry(), keep);
9956
- });
9957
- previous = void 0;
9958
- } else ctx.log(` ${id}: the old access key ${previous} stays active until '${ctx.stage}' is deployed with the new one; the next gkm setup --stage ${ctx.stage} after that deletes it (or pass --retire-old-keys)`);
9959
- }
9960
- if (!current && inUrl && listed.includes(inUrl)) {
9961
- await ctx.state.ready(entry(), inUrl);
9962
- current = inUrl;
9963
- }
9964
- if (current !== void 0 && listed.includes(current) && inUrl === current && !ctx.rotateKeys) return;
9965
- if (ctx.rotateKeys && previous) throw new RotationInProgress(id, previous, ctx.stage);
9966
- const outgoing = current && listed.includes(current) ? current : void 0;
9967
- if (listed.length >= 2) throw new AccessKeyLimit(user, listed);
9968
- const why = !current ? "create an access key" : ctx.rotateKeys ? "rotate: issue a new access key" : "issue a new access key (the secrets no longer hold the recorded one)";
9969
- await ctx.change({
9970
- construct: id,
9971
- resource: `IAM user ${user}`,
9972
- change: why
9973
- }, async () => {
9974
- await ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));
9975
- const key = (await iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }))).AccessKey;
9976
- await ctx.writeSecrets({ [urlKey]: s3Url.build({
9977
- bucket,
9978
- region: clients.region,
9979
- ...clients.endpoint ? {
9980
- endpoint: clients.endpoint,
9981
- forcePathStyle: true
9982
- } : {},
9983
- accessKeyId: key.AccessKeyId,
9984
- secretAccessKey: key.SecretAccessKey
9985
- }) });
9986
- await ctx.state.ready(entry(outgoing ? {
9987
- previous: outgoing,
9988
- rotatedAt: (/* @__PURE__ */ new Date()).toISOString()
9989
- } : {}), key.AccessKeyId);
8668
+ function workerDockerfile(worker, host, options) {
8669
+ return generateWorkerDockerfile({
8670
+ ...appImageOptions(options.layout, worker.app, host, options.workspaceRoot),
8671
+ imageName: worker.name,
8672
+ port: WORKER_PORT,
8673
+ worker: worker.id,
8674
+ bundle: workerBundleName(worker.id),
8675
+ healthCheckPath: "/health",
8676
+ ...options.cache ? { cache: options.cache } : {}
9990
8677
  });
9991
- if (outgoing) ctx.log(` ${urlKey} holds the new key. Deploy '${ctx.stage}' now; the next gkm setup --stage ${ctx.stage} after that deploy deletes the old key ${outgoing}`);
9992
- }
9993
- /**
9994
- * Each provisioned bucket answers `HeadBucket` to the key in the stage's
9995
- * secrets — the one the apps will use. A bucket whose URL carries no key is
9996
- * not one this provider wrote, and the deploy's own check covers a URL that
9997
- * is missing.
9998
- */
9999
- async function verifyS3(ctx) {
10000
- const S3 = await import("@aws-sdk/client-s3");
10001
- for (const { id } of bucketConstructs(ctx.manifest)) {
10002
- const url = ctx.secrets[provideKey(id, "url")];
10003
- if (url === void 0) continue;
10004
- const address = s3Url.parse(url);
10005
- if (!address.accessKeyId || !address.secretAccessKey) continue;
10006
- const client = new S3.S3Client({
10007
- region: address.region ?? ctx.config.region ?? "us-east-1",
10008
- credentials: {
10009
- accessKeyId: address.accessKeyId,
10010
- secretAccessKey: address.secretAccessKey
10011
- },
10012
- ...address.endpoint ? { endpoint: address.endpoint } : {},
10013
- ...address.forcePathStyle ? { forcePathStyle: true } : {}
10014
- });
10015
- try {
10016
- await client.send(new S3.HeadBucketCommand({ Bucket: address.bucket }));
10017
- } catch (error) {
10018
- const name = errorName(error);
10019
- throw new ProvisionedBucketUnreachable(id, address.bucket, ctx.stage, name === "NotFound" ? "it does not exist" : name === "Forbidden" ? "the key is refused" : name || String(error));
10020
- } finally {
10021
- client.destroy();
10022
- }
10023
- }
10024
- }
10025
- //#endregion
10026
- //#region src/providers/registry.ts
10027
- /**
10028
- * The providers gkm ships, by kind and name — registered the way a deploy
10029
- * target's built-ins are (`target/builtins.ts`). A provider from a package is
10030
- * one more entry here once there is a loading story for it.
10031
- */
10032
- const BUILTIN_PROVIDERS = { objects: { s3: {
10033
- kind: "objects",
10034
- name: "s3",
10035
- check: checkS3Config,
10036
- provisioning: S3_PROVISIONING,
10037
- credentials: awsProvisioningCredentials,
10038
- runtimeKeys(manifest) {
10039
- return bucketConstructs(manifest).flatMap((b) => [provideKey(b.id, "url"), ...b.servers.map((s) => provideKey(s.id, "url"))]);
10040
- },
10041
- ensure: ensureS3,
10042
- verify: verifyS3
10043
- } } };
10044
- /** The provider `kind` names `name`, if gkm has one. */
10045
- function builtinProvider(kind, name) {
10046
- return Object.hasOwn(BUILTIN_PROVIDERS[kind], name) ? BUILTIN_PROVIDERS[kind][name] : void 0;
10047
- }
10048
- //#endregion
10049
- //#region src/providers/index.ts
10050
- /** The constructs of a kind: `objects` is every bucket. */
10051
- function constructsOf(manifest, kind) {
10052
- return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
10053
8678
  }
10054
8679
  /**
10055
- * What every deploy runs: each provider's `verify()` — the cheap check that
10056
- * what it created is still there and the stage's key reaches it. Nothing on
10057
- * the local stage, and nothing for a kind on `external`.
8680
+ * A site's Dockerfile, with an `ARG` for every key its bundler inlines.
10058
8681
  *
10059
- * @throws {StageProviderDisabled} for a declared kind the stage has none of
8682
+ * The keys come from the site's declaration where there is one — every
8683
+ * public key its edges give it, `VITE_UPLOADS_SERVER_URL` included — and an
8684
+ * `ARG` the Dockerfile does not declare is a build argument the build drops,
8685
+ * leaving the bundle with an empty URL.
10060
8686
  */
10061
- async function verifyStageProviders(input) {
10062
- assertStageProvidersEnabled(input.workspace, input.manifest, input.stage);
10063
- const verified = [];
10064
- for (const kind of PROVIDER_KINDS) {
10065
- if (constructsOf(input.manifest, kind).length === 0) continue;
10066
- const choice = stageProvider(input.workspace, kind, input.stage);
10067
- if (choice.mode !== "provider") continue;
10068
- const provider = builtinProvider(kind, choice.name);
10069
- await provider.verify({
10070
- workspace: input.workspace,
10071
- manifest: input.manifest,
10072
- stage: input.stage,
10073
- config: choice.config,
10074
- secrets: input.secrets
10075
- });
10076
- verified.push(`${kind}: ${provider.name}`);
8687
+ function siteDockerfile(appName, app, options) {
8688
+ const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1] : void 0;
8689
+ const publicUrlArgs = options.publicUrlArgs ?? (declared?.kind === "site" && options.manifest ? Object.keys(publicEnvFor(declared, options.manifest)) : getPublicUrlArgNames(app));
8690
+ const webOpts = {
8691
+ ...options.image,
8692
+ publicUrlArgs
8693
+ };
8694
+ switch (app.framework) {
8695
+ case "vite": return generateViteStaticDockerfile(webOpts);
8696
+ case "tanstack-start":
8697
+ case "remix": return generateNodeWebDockerfile(webOpts);
8698
+ default: return generateNextjsDockerfile(webOpts);
10077
8699
  }
10078
- return verified;
10079
8700
  }
10080
8701
  /**
10081
- * `ensure()` for every provider the stage configures — find or create, fix
10082
- * drift, record in the stage's state, write the runtime keys into its
10083
- * secrets. A provider without provisioning credentials leaves the stage as
10084
- * `external` and says how to supply them.
8702
+ * What a build root's `.dockerignore` must leave out of every image's
8703
+ * context: dependencies installed for another platform, anything built on the
8704
+ * host (every image builds from source), git, and gkm's own output —
8705
+ * `.gkm/compose`'s env files hold a stage's secrets.
10085
8706
  */
10086
- async function provisionStage(options) {
10087
- const { workspace, stage } = options;
10088
- const dryRun = options.dryRun === true;
10089
- const env = options.env ?? process.env;
10090
- const log = options.log ?? ((line) => console.log(line));
10091
- const named = PROVIDER_KINDS.some((kind) => stageProvider(workspace, kind, stage).mode === "provider");
10092
- let found = options.manifest;
10093
- let runnables = options.runnables ?? {};
10094
- if (!found && named) {
10095
- runnables = {};
10096
- found = await discover({
10097
- patterns: constructGlobs(workspace),
10098
- cwd: workspace.root,
10099
- runnables
10100
- });
10101
- }
10102
- const manifest = found ?? {};
10103
- const reports = [];
10104
- const configured = [];
10105
- for (const kind of PROVIDER_KINDS) {
10106
- const choice = stageProvider(workspace, kind, stage);
10107
- if (choice.mode !== "provider") {
10108
- reports.push({
10109
- kind,
10110
- mode: choice.mode,
10111
- actions: []
10112
- });
10113
- continue;
10114
- }
10115
- const provider = builtinProvider(kind, choice.name);
10116
- const report = {
10117
- kind,
10118
- mode: "provider",
10119
- provider: provider.name,
10120
- actions: []
10121
- };
10122
- reports.push(report);
10123
- if (constructsOf(manifest, kind).length === 0) {
10124
- log(` ${kind}: ${provider.name} — nothing declared to provision`);
10125
- continue;
10126
- }
10127
- const credential = await provider.credentials({
10128
- stage,
10129
- env,
10130
- ...options.profile ? { profile: options.profile } : {},
10131
- ...options.home ? { home: options.home } : {}
10132
- });
10133
- report.credentials = credential !== void 0;
10134
- if (credential === void 0) {
10135
- log(` ${kind}: ${provider.name} — no credentials to provision with, so '${stage}' is external for now: its keys (${provider.runtimeKeys(manifest).join(", ")}) are yours to set with gkm secrets:add --stage ${stage}. To have gkm create them, supply ${provider.provisioning.describe}` + (provider.provisioning.login ? `, or run gkm login --provider ${provider.provisioning.login}` : "") + `, and run ${provisionCommand(stage)}.`);
10136
- continue;
10137
- }
10138
- configured.push({
10139
- kind,
10140
- provider,
10141
- config: choice.config,
10142
- credential,
10143
- report
10144
- });
10145
- }
10146
- if (configured.length === 0) return reports;
10147
- const identity = deployIdentity(workspace, stage);
10148
- const secretsStore = await secretsStoreFor(workspace, stage, {
10149
- ...options.profile ? { profile: options.profile } : {},
10150
- ...options.home ? { home: options.home } : {}
10151
- });
10152
- let secrets = (await secretsStore.read(stage))?.custom ?? {};
10153
- const stateStore = await createStateStore({
10154
- config: workspace.state,
10155
- workspaceRoot: workspace.root,
10156
- workspaceName: workspace.name
10157
- });
10158
- const lock = dryRun ? void 0 : await stateStore.lock(stage, { operation: "provision" });
10159
- try {
10160
- const state = dryRun ? await readOnlyState(stateStore, stage) : journalState(await DeployJournal.open(stateStore, stage, () => deploysWithCompose(workspace) ? createComposeState(stage) : createEmptyState(stage, "", "")));
10161
- const writeSecrets = async (values) => {
10162
- if (dryRun) return;
10163
- const stored = await secretsStore.read(stage) ?? initStageSecrets(stage);
10164
- const next = {
10165
- ...stored,
10166
- custom: {
10167
- ...stored.custom,
10168
- ...values
10169
- },
10170
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10171
- };
10172
- await secretsStore.write(stage, next);
10173
- secrets = next.custom;
10174
- };
10175
- for (const entry of configured) {
10176
- log(` ${entry.kind}: ${entry.provider.name}${dryRun ? " (dry run)" : ""}`);
10177
- await entry.provider.ensure({
10178
- workspace,
10179
- manifest,
10180
- runnables,
10181
- stage,
10182
- identity,
10183
- config: entry.config,
10184
- credential: entry.credential,
10185
- get secrets() {
10186
- return secrets;
10187
- },
10188
- state,
10189
- dryRun,
10190
- rotateKeys: options.rotateKeys === true,
10191
- retireOldKeys: options.retireOldKeys === true,
10192
- async change(action, apply) {
10193
- if (!dryRun) await apply();
10194
- entry.report.actions.push(action);
10195
- log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
10196
- },
10197
- writeSecrets,
10198
- log
10199
- });
10200
- if (entry.report.actions.length === 0) log(" up to date");
10201
- }
10202
- } finally {
10203
- await lock?.release();
8707
+ const REQUIRED_IGNORES = [
8708
+ "**/node_modules",
8709
+ ".git",
8710
+ "**/dist",
8711
+ "**/.next",
8712
+ "**/.turbo",
8713
+ "**/.gkm",
8714
+ "**/.gkm/compose"
8715
+ ];
8716
+ /**
8717
+ * Make sure the build root's `.dockerignore` leaves out what no image may
8718
+ * hold: written whole where there is none, and each missing line appended to
8719
+ * one the project keeps.
8720
+ */
8721
+ async function ensureDockerignore(buildRoot) {
8722
+ const path = join(buildRoot, ".dockerignore");
8723
+ if (!existsSync(path)) {
8724
+ await writeFile(path, generateDockerignore());
8725
+ return path;
10204
8726
  }
10205
- return reports;
8727
+ const current = await readFile(path, "utf-8");
8728
+ const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
8729
+ const missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));
8730
+ if (missing.length === 0) return path;
8731
+ await appendFile(path, `${current.endsWith("\n") || current === "" ? "" : "\n"}\n# gkm: images build from source, and a stack's env files hold its secrets\n${missing.join("\n")}\n`);
8732
+ return path;
10206
8733
  }
10207
- /** The journal as `ensure()` sees it. */
10208
- function journalState(journal) {
10209
- return {
10210
- record: (key) => journal.record(key),
10211
- pending: (entry) => journal.pending(entry),
10212
- ready: (entry, id) => journal.ready(entry, id),
10213
- lastDeployedAt: journal.existed ? journal.state.lastDeployedAt : void 0
10214
- };
8734
+ /**
8735
+ * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with
8736
+ * the apps beside the containers their constructs derive.
8737
+ *
8738
+ * Through reconcile rather than a second generator, so what `gkm docker`
8739
+ * describes and what `gkm dev` runs cannot disagree. Nothing is started.
8740
+ */
8741
+ async function writeConstructsCompose(workspace) {
8742
+ await reconcileWorkspace(workspace, {
8743
+ stage: workspace.stages.local,
8744
+ start: false
8745
+ });
8746
+ logger.log(` Generated: ${COMPOSE_PATH} (project root)`);
8747
+ return join(workspace.root, COMPOSE_PATH);
10215
8748
  }
10216
- /** What a dry run reads, and the writes it does not make. */
10217
- async function readOnlyState(store, stage) {
10218
- const stored = await store.read(stage);
10219
- return {
10220
- record: (key) => stored?.resources[key],
10221
- pending: async () => {},
10222
- ready: async () => {},
10223
- ...stored ? { lastDeployedAt: stored.state.lastDeployedAt } : {}
10224
- };
8749
+ function printRunInstructions(workspace) {
8750
+ const project = existsSync(join(workspace.root, "docker-compose.yml")) ? " -f docker-compose.yml" : "";
8751
+ logger.log("\n📋 Run everything (the apps sit behind the \"apps\" profile):");
8752
+ logger.log(" gkm setup # starts the containers and creates what they hold");
8753
+ logger.log(` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`);
10225
8754
  }
10226
8755
  //#endregion
10227
8756
  //#region src/secrets/stale.ts
@@ -10372,6 +8901,6 @@ function reportPlannedSeeds(planned, log) {
10372
8901
  for (const { folder, seeds } of planned) log(`🌱 ${folder}: would run ${seeds.length} (${seeds.join(", ")})`);
10373
8902
  }
10374
8903
  //#endregion
10375
- export { contentVersion as $, projectKey as $n, bucketClient as $t, orchestrateDns as A, telemetryOf as An, workspace_exports as At, setBackupState as B, findAvailablePort as Bn, stackRedis as Bt, HostNotPointingAtServer as C, planFor as Cn, QueueGenerator as Ct, serverAddressHint as D, isTelemetryKey as Dn, constructGlobs as Dt, requiredServerAddress as E, appTelemetry as En, backendsOf as Et, getBackupState as F, portKeys as Fn, withGeneratedSecrets as Ft, LocalStateInCi as G, prepareEntryCredentials as Gn, applyPolicies as Gt, setPostgresBackupId as H, loadEnvFiles as Hn, LOCAL_CA_PATH as Ht, getGeneratedSecret as I, portsOf as In, REDIS_SERVICE as It, StateStoreBusy as J, storeFromConfig as Jn, postgresDatabaseNames as Jt, StageStateMissing as K, isRemoteStore as Kn, applyPostgres as Kt, recordRelease as L, primaryPortKey as Ln, STACK_CACHE as Lt, asDokployState as M, DEFAULT_IMAGES as Mn, loadLocalCredentials as Mt, createComposeState as N, describeServices as Nn, postgresSuperuser as Nt, stackHosts as O, scopeTelemetryEnv as On, derivedContainers as Ot, createEmptyState as P, fakeKey as Pn, readLocalCredentials as Pt, assertStateOutlivesRun as Q, keystoreProject as Qn, ensurePostgresLogin as Qt, recordRollback as R, createCredentialsPreload as Rn, redisService as Rt, validateImageRef as S, TELEMETRY_CONTAINER as Sn, resolveHost as Sr, workerEntryDir as St, isLocalHost as T, hostFor as Tn, FAKE_ENV as Tt, DnsRecordsUnreadable as U, loadPortState as Un, forgetState as Ut, setGeneratedSecret as V, isPortAvailable as Vn, withRedisPassword as Vt, DocumentStateStore as W, loadSecretsForApp as Wn, applyBuckets as Wt, StateVersionConflict as X, FileSecretsStore as Xn, quoteIdentifier as Xt, StateStoreWithoutLocking as Y, store_exports as Yn, postgresStatements as Yt, appendHistory as Z, getKeyPath as Zn, LEGACY_LOCAL_LOGIN as Zt, appDockerfile as _, providerOf as _n, logsService as _r, requiredStageKeys as _t, provisionStage as a, envFor as an, isOwnedBy as ar, describeActor as at, workerDockerfile as b, composeFor as bn, NoDomainForStage as br, WorkerGenerator as bt, deploysWithCompose as c, imageLayout as cn, projectName as cr, DevServicesNeedServerTarget as ct, StageProviderDisabled as d, detectPackageManager as dn, storage_exports as dr, assertDevServicesFlag as dt, pgClient as en, readKey as er, createStateStore as et, assertStageProvidersEnabled as f, findBuildRoot as fn, toEmbeddableSecrets as fr, assertExternalServices as ft, DockerPushFailed as g, eventsBackendFor as gn, logsAccess as gr, reportDevServices as gt, DockerBuildFailed as h, cacheBackendFor as hn, LOGS_SERVICE as hr, manifestServiceDeclarations as ht, assertNoStaleSecrets as i, workerEnvKeys as in, imageRef as ir, currentActor as it, verifyDnsRecords as j, usesTelemetry as jn, LOCAL_RABBITMQ_USER as jt, systemLookup as k, surfaceClientTraced as kn, reconcileWorkspace as kt, provisionStageDns as l, TURBO_VERSION as ln, initStageSecrets as lr, ExternalServicesNotConfigured as lt, stageProviderNotes as m, isImageBuild as mn, LOCAL_LOGS_EMAIL as mr, externalServices as mt, reportDatabaseRuns as n, dockerfileOf as nn, deployIdentity as nr, upgradeV2State as nt, verifyStageProviders as o, localRolePassword as on, markerOf as or, AllowDevServicesTakesNoValue as ot, provisionCommand as p, imageBuildCredentials as pn, withCustomSecret as pr, devServicesUsed as pt, StateLocked as q, secretsStoreFor as qn, bucketPolicies as qt, reportPlannedSeeds as r, networkEnv as rn, imageName as rr, dnsResources as rt, assertStageServer as s, composeBuildPaths as sn, ownershipMarker as sr, DEV_SERVICES as st, DeploySeedsFailed as t, appEnvKeys as tn, applicationName as tr, newLockHolder as tt, DeployJournal as u, WORKER_PORT as un, maskPassword as ur, STORAGE_KEY_PAIR as ut, dockerCommand as v, storageBackendFor as vn, stackLogs as vr, suppliedOnly as vt, checkStackDns as w, resourceName as wn, CronGenerator as wt, workerDockerfileOf as x, EMULATOR_ACCESS_KEY_ID as xn, isMainFrontendApp as xr, workerBundleName as xt, ensureDockerignore as y, CLUSTER_DATABASE as yn, withLogsPassword as yr, workerUnits as yt, setApplicationId as z, createEntryWrapper as zn, runsRedis as zt };
8904
+ export { systemLookup as $, imageRef as $n, workerEnvKeys as $t, requiredStageKeys as A, portKeys as An, withGeneratedSecrets as At, provisionCommand as B, prepareEntryCredentials as Bn, applyPolicies as Bt, STORAGE_KEY_PAIR as C, scopeTelemetryEnv as Cn, derivedContainers as Ct, externalServices as D, DEFAULT_IMAGES as Dn, loadLocalCredentials as Dt, devServicesUsed as E, usesTelemetry as En, LOCAL_RABBITMQ_USER as Et, iamUserName as F, findAvailablePort as Fn, stackRedis as Ft, HostNotPointingAtServer as G, FileSecretsStore as Gn, quoteIdentifier as Gt, PROVIDER_KINDS as H, secretsStoreFor as Hn, bucketPolicies as Ht, randomSuffix as I, isPortAvailable as In, withRedisPassword as It, requiredServerAddress as J, projectKey as Jn, bucketClient as Jt, dnsCredentials as K, getKeyPath as Kn, LEGACY_LOCAL_LOGIN as Kt, suffixedBucketName as L, loadEnvFiles as Ln, LOCAL_CA_PATH as Lt, IAM_POLICY_NAME as M, primaryPortKey as Mn, STACK_CACHE as Mt, IAM_USER_PATH as N, createCredentialsPreload as Nn, redisService as Nt, manifestServiceDeclarations as O, describeServices as On, postgresSuperuser as Ot, bucketName as P, createEntryWrapper as Pn, runsRedis as Pt, stageDnsDomains as Q, imageName as Qn, networkEnv as Qt, StageProviderDisabled as R, loadPortState as Rn, forgetState as Rt, ExternalServicesNotConfigured as S, isTelemetryKey as Sn, constructGlobs as St, assertExternalServices as T, telemetryOf as Tn, workspace_exports as Tt, deploysWithCompose as U, storeFromConfig as Un, postgresDatabaseNames as Ut, stageProviderNotes as V, isRemoteStore as Vn, applyPostgres as Vt, dns_exports as W, store_exports as Wn, postgresStatements as Wt, stackHosts as X, applicationName as Xn, appEnvKeys as Xt, serverAddressHint as Y, readKey as Yn, pgClient as Yt, stageDns as Z, deployIdentity as Zn, dockerfileOf as Zt, describeActor as _, TELEMETRY_CONTAINER as _n, resolveHost as _r, workerEntryDir as _t, DockerBuildFailed as a, WORKER_PORT as an, maskPassword as ar, getBackupState as at, DEV_SERVICES as b, hostFor as bn, FAKE_ENV as bt, dockerCommand as c, imageBuildCredentials as cn, withCustomSecret as cr, recordRollback as ct, workerDockerfileOf as d, eventsBackendFor as dn, logsAccess as dr, setGeneratedSecret as dt, envFor as en, isOwnedBy as er, orchestrateDns as et, validateImageRef as f, providerOf as fn, logsService as fr, setPostgresBackupId as ft, currentActor as g, EMULATOR_ACCESS_KEY_ID as gn, isMainFrontendApp as gr, workerBundleName as gt, recordDnsChanges as h, composeFor as hn, NoDomainForStage as hr, WorkerGenerator as ht, assertNoStaleSecrets as i, TURBO_VERSION as in, initStageSecrets as ir, createEmptyState as it, suppliedOnly as j, portsOf as jn, REDIS_SERVICE as jt, reportDevServices as k, fakeKey as kn, readLocalCredentials as kt, ensureDockerignore as l, isImageBuild as ln, LOCAL_LOGS_EMAIL as lr, setApplicationId as lt, dnsResources as m, CLUSTER_DATABASE as mn, withLogsPassword as mr, workerUnits as mt, reportDatabaseRuns as n, composeBuildPaths as nn, ownershipMarker as nr, asDokployState as nt, DockerPushFailed as o, detectPackageManager as on, storage_exports as or, getGeneratedSecret as ot, dnsRecordResource as p, storageBackendFor as pn, stackLogs as pr, DnsRecordsUnreadable as pt, isLocalHost as q, keystoreProject as qn, ensurePostgresLogin as qt, reportPlannedSeeds as r, imageLayout as rn, projectName as rr, createComposeState as rt, appDockerfile as s, findBuildRoot as sn, toEmbeddableSecrets as sr, recordRelease as st, DeploySeedsFailed as t, localRolePassword as tn, markerOf as tr, verifyDnsRecords as tt, workerDockerfile as u, cacheBackendFor as un, LOGS_SERVICE as ur, setBackupState as ut, isCi as v, planFor as vn, QueueGenerator as vt, assertDevServicesFlag as w, surfaceClientTraced as wn, reconcileWorkspace as wt, DevServicesNeedServerTarget as x, appTelemetry as xn, backendsOf as xt, AllowDevServicesTakesNoValue as y, resourceName as yn, CronGenerator as yt, assertStageProvidersEnabled as z, loadSecretsForApp as zn, applyBuckets as zt };
10376
8905
 
10377
- //# sourceMappingURL=seeds-BSL55F6q.mjs.map
8906
+ //# sourceMappingURL=seeds-CTxTZa-R.mjs.map