@geekmidas/cli 10.0.0-alpha.19 → 10.0.0-alpha.190

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 (436) hide show
  1. package/README.md +323 -380
  2. package/bin/adjacent-tsconfig.mjs +46 -8
  3. package/bin/gkm.mjs +11 -3
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/EndpointGenerator-CBKH87_b.mjs +1043 -0
  7. package/dist/EndpointGenerator-CBKH87_b.mjs.map +1 -0
  8. package/dist/EndpointGenerator-iyA3HkOH.cjs +1102 -0
  9. package/dist/EndpointGenerator-iyA3HkOH.cjs.map +1 -0
  10. package/dist/LegacyStateStore-CWiswz6T.mjs +124 -0
  11. package/dist/LegacyStateStore-CWiswz6T.mjs.map +1 -0
  12. package/dist/LegacyStateStore-CuSe37fl.cjs +124 -0
  13. package/dist/LegacyStateStore-CuSe37fl.cjs.map +1 -0
  14. package/dist/LocalStateStore-BciJ_DF0.cjs +178 -0
  15. package/dist/LocalStateStore-BciJ_DF0.cjs.map +1 -0
  16. package/dist/LocalStateStore-CLHasLJI.mjs +167 -0
  17. package/dist/LocalStateStore-CLHasLJI.mjs.map +1 -0
  18. package/dist/OpenApiTsGenerator-CoVA3Ykv.mjs +534 -0
  19. package/dist/OpenApiTsGenerator-CoVA3Ykv.mjs.map +1 -0
  20. package/dist/OpenApiTsGenerator-vy-fOJgs.cjs +539 -0
  21. package/dist/OpenApiTsGenerator-vy-fOJgs.cjs.map +1 -0
  22. package/dist/S3StateStore-BHLRjoj3.cjs +222 -0
  23. package/dist/S3StateStore-BHLRjoj3.cjs.map +1 -0
  24. package/dist/S3StateStore-CTiv2_ON.mjs +223 -0
  25. package/dist/S3StateStore-CTiv2_ON.mjs.map +1 -0
  26. package/dist/SSMStateStore-BqT3MXXb.cjs +204 -0
  27. package/dist/SSMStateStore-BqT3MXXb.cjs.map +1 -0
  28. package/dist/SSMStateStore-D6qqaem2.mjs +205 -0
  29. package/dist/SSMStateStore-D6qqaem2.mjs.map +1 -0
  30. package/dist/SubscriberGenerator-Cfoz8uTY.mjs +787 -0
  31. package/dist/SubscriberGenerator-Cfoz8uTY.mjs.map +1 -0
  32. package/dist/SubscriberGenerator-CxzECrfj.cjs +852 -0
  33. package/dist/SubscriberGenerator-CxzECrfj.cjs.map +1 -0
  34. package/dist/add-B2OmIQzs.cjs +712 -0
  35. package/dist/add-B2OmIQzs.cjs.map +1 -0
  36. package/dist/add-CXwL549o.mjs +710 -0
  37. package/dist/add-CXwL549o.mjs.map +1 -0
  38. package/dist/appPorts-BoXMwolc.mjs +249 -0
  39. package/dist/appPorts-BoXMwolc.mjs.map +1 -0
  40. package/dist/appPorts-IW-OZmRi.cjs +296 -0
  41. package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
  42. package/dist/aws-BXfiWNbi.cjs +108 -0
  43. package/dist/aws-BXfiWNbi.cjs.map +1 -0
  44. package/dist/aws-BjvSTTcE.mjs +97 -0
  45. package/dist/aws-BjvSTTcE.mjs.map +1 -0
  46. package/dist/awsStore-BYYCmXiq.mjs +121 -0
  47. package/dist/awsStore-BYYCmXiq.mjs.map +1 -0
  48. package/dist/awsStore-DKQUElJL.cjs +138 -0
  49. package/dist/awsStore-DKQUElJL.cjs.map +1 -0
  50. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  51. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  52. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  53. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  54. package/dist/backups/runner.cjs +1007 -0
  55. package/dist/backups/runner.cjs.map +1 -0
  56. package/dist/backups/runner.d.cts +187 -0
  57. package/dist/backups/runner.d.cts.map +1 -0
  58. package/dist/backups/runner.d.mts +187 -0
  59. package/dist/backups/runner.d.mts.map +1 -0
  60. package/dist/backups/runner.mjs +984 -0
  61. package/dist/backups/runner.mjs.map +1 -0
  62. package/dist/{bundler-mwH7WOb1.mjs → bundler-CHXyJFsS.mjs} +68 -15
  63. package/dist/bundler-CHXyJFsS.mjs.map +1 -0
  64. package/dist/{bundler-mjqGAvu1.cjs → bundler-CLoVtcBi.cjs} +67 -14
  65. package/dist/bundler-CLoVtcBi.cjs.map +1 -0
  66. package/dist/cli-Bjua3PaZ.mjs +80 -0
  67. package/dist/cli-Bjua3PaZ.mjs.map +1 -0
  68. package/dist/cli-DiuUr1Am.cjs +80 -0
  69. package/dist/cli-DiuUr1Am.cjs.map +1 -0
  70. package/dist/clientTelemetry-DXuYNH-J.d.cts +10 -0
  71. package/dist/clientTelemetry-DXuYNH-J.d.cts.map +1 -0
  72. package/dist/clientTelemetry-eC8VQ6nB.d.mts +10 -0
  73. package/dist/clientTelemetry-eC8VQ6nB.d.mts.map +1 -0
  74. package/dist/compose-DUOETDhc.mjs +2855 -0
  75. package/dist/compose-DUOETDhc.mjs.map +1 -0
  76. package/dist/compose-gnNrY3NQ.cjs +2939 -0
  77. package/dist/compose-gnNrY3NQ.cjs.map +1 -0
  78. package/dist/config-1zirYXeO.d.mts +300 -0
  79. package/dist/config-1zirYXeO.d.mts.map +1 -0
  80. package/dist/config-rSlB-bXj.d.cts +300 -0
  81. package/dist/config-rSlB-bXj.d.cts.map +1 -0
  82. package/dist/config.cjs +462 -9
  83. package/dist/config.cjs.map +1 -0
  84. package/dist/config.d.cts +4 -117
  85. package/dist/config.d.mts +4 -117
  86. package/dist/config.mjs +446 -3
  87. package/dist/config.mjs.map +1 -0
  88. package/dist/credentialSchemas-D_85KW2k.mjs +236 -0
  89. package/dist/credentialSchemas-D_85KW2k.mjs.map +1 -0
  90. package/dist/credentialSchemas-DjK6xKMk.cjs +271 -0
  91. package/dist/credentialSchemas-DjK6xKMk.cjs.map +1 -0
  92. package/dist/credentials-BI52H1ad.cjs +2911 -0
  93. package/dist/credentials-BI52H1ad.cjs.map +1 -0
  94. package/dist/credentials-Cp09PIsc.cjs +1451 -0
  95. package/dist/credentials-Cp09PIsc.cjs.map +1 -0
  96. package/dist/credentials-DbjLhvix.mjs +1140 -0
  97. package/dist/credentials-DbjLhvix.mjs.map +1 -0
  98. package/dist/credentials-VLP_959f.mjs +2390 -0
  99. package/dist/credentials-VLP_959f.mjs.map +1 -0
  100. package/dist/databases-CV22HzrI.mjs +588 -0
  101. package/dist/databases-CV22HzrI.mjs.map +1 -0
  102. package/dist/databases-DwYYH2mX.cjs +703 -0
  103. package/dist/databases-DwYYH2mX.cjs.map +1 -0
  104. package/dist/dbTunnel-CLsqWr7o.mjs +153 -0
  105. package/dist/dbTunnel-CLsqWr7o.mjs.map +1 -0
  106. package/dist/dbTunnel-DQcdaaLi.cjs +153 -0
  107. package/dist/dbTunnel-DQcdaaLi.cjs.map +1 -0
  108. package/dist/define-BfrNaY82.mjs +106 -0
  109. package/dist/define-BfrNaY82.mjs.map +1 -0
  110. package/dist/define-zKgLY65H.cjs +153 -0
  111. package/dist/define-zKgLY65H.cjs.map +1 -0
  112. package/dist/deploy/public.cjs +210 -0
  113. package/dist/deploy/public.cjs.map +1 -0
  114. package/dist/deploy/public.d.cts +659 -0
  115. package/dist/deploy/public.d.cts.map +1 -0
  116. package/dist/deploy/public.d.mts +659 -0
  117. package/dist/deploy/public.d.mts.map +1 -0
  118. package/dist/deploy/public.mjs +143 -0
  119. package/dist/deploy/public.mjs.map +1 -0
  120. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  121. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  122. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  123. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  124. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  125. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  126. package/dist/deploy/sniffer-hooks.cjs +1 -1
  127. package/dist/deploy/sniffer-hooks.mjs +1 -1
  128. package/dist/deploy/sniffer-loader.cjs +2 -2
  129. package/dist/deploy/sniffer-loader.mjs +1 -1
  130. package/dist/deploy/sniffer-routes-worker.cjs +2 -2
  131. package/dist/deploy/sniffer-routes-worker.mjs +1 -1
  132. package/dist/deploy-DhIy2Ftj.mjs +3854 -0
  133. package/dist/deploy-DhIy2Ftj.mjs.map +1 -0
  134. package/dist/deploy-DpQ_4Pu1.cjs +3910 -0
  135. package/dist/deploy-DpQ_4Pu1.cjs.map +1 -0
  136. package/dist/destroy-DmTDT6V7.cjs +791 -0
  137. package/dist/destroy-DmTDT6V7.cjs.map +1 -0
  138. package/dist/destroy-wV9yNLQV.mjs +790 -0
  139. package/dist/destroy-wV9yNLQV.mjs.map +1 -0
  140. package/dist/discover-Dfmn6HQ7.mjs +940 -0
  141. package/dist/discover-Dfmn6HQ7.mjs.map +1 -0
  142. package/dist/discover-OXczlq08.cjs +1085 -0
  143. package/dist/discover-OXczlq08.cjs.map +1 -0
  144. package/dist/dokploy-B61ww4Yb.cjs +38 -0
  145. package/dist/dokploy-B61ww4Yb.cjs.map +1 -0
  146. package/dist/dokploy-Jhl3sPd4.mjs +38 -0
  147. package/dist/dokploy-Jhl3sPd4.mjs.map +1 -0
  148. package/dist/drivers-BQRb3KsL.mjs +294 -0
  149. package/dist/drivers-BQRb3KsL.mjs.map +1 -0
  150. package/dist/drivers-DP7__dJX.cjs +377 -0
  151. package/dist/drivers-DP7__dJX.cjs.map +1 -0
  152. package/dist/eas-BmvO40xS.mjs +334 -0
  153. package/dist/eas-BmvO40xS.mjs.map +1 -0
  154. package/dist/eas-X09Gz8_E.cjs +337 -0
  155. package/dist/eas-X09Gz8_E.cjs.map +1 -0
  156. package/dist/emit-C4KSXOeS.mjs +153 -0
  157. package/dist/emit-C4KSXOeS.mjs.map +1 -0
  158. package/dist/emit-DiW0kbue.cjs +164 -0
  159. package/dist/emit-DiW0kbue.cjs.map +1 -0
  160. package/dist/encryption-BBIUewnL.cjs +90 -0
  161. package/dist/encryption-BBIUewnL.cjs.map +1 -0
  162. package/dist/encryption-BOmswIgE.mjs +89 -0
  163. package/dist/encryption-BOmswIgE.mjs.map +1 -0
  164. package/dist/engine-BhjhShKf.cjs +3333 -0
  165. package/dist/engine-BhjhShKf.cjs.map +1 -0
  166. package/dist/engine-DW2H3KNa.mjs +3220 -0
  167. package/dist/engine-DW2H3KNa.mjs.map +1 -0
  168. package/dist/errors-C9uIyIDt.mjs +27 -0
  169. package/dist/errors-C9uIyIDt.mjs.map +1 -0
  170. package/dist/errors-D1x8duqI.cjs +38 -0
  171. package/dist/errors-D1x8duqI.cjs.map +1 -0
  172. package/dist/github-Ptbigbrq.mjs +986 -0
  173. package/dist/github-Ptbigbrq.mjs.map +1 -0
  174. package/dist/github-xUtu4Ur7.cjs +987 -0
  175. package/dist/github-xUtu4Ur7.cjs.map +1 -0
  176. package/dist/googlePlay-B4xhz5xT.cjs +931 -0
  177. package/dist/googlePlay-B4xhz5xT.cjs.map +1 -0
  178. package/dist/googlePlay-C9rrwN5b.mjs +931 -0
  179. package/dist/googlePlay-C9rrwN5b.mjs.map +1 -0
  180. package/dist/iam-D7mXd6by.cjs +521 -0
  181. package/dist/iam-D7mXd6by.cjs.map +1 -0
  182. package/dist/iam-DNlbVN_l.mjs +442 -0
  183. package/dist/iam-DNlbVN_l.mjs.map +1 -0
  184. package/dist/{index-RCUizGxL.d.cts → index-B1gfXH5K.d.mts} +38 -14
  185. package/dist/index-B1gfXH5K.d.mts.map +1 -0
  186. package/dist/{index-B4H4XF7A.d.mts → index-CunkOPOu.d.cts} +38 -14
  187. package/dist/index-CunkOPOu.d.cts.map +1 -0
  188. package/dist/index.cjs +15566 -13457
  189. package/dist/index.cjs.map +1 -1
  190. package/dist/index.mjs +15249 -13138
  191. package/dist/index.mjs.map +1 -1
  192. package/dist/local-CvC-z86k.mjs +224 -0
  193. package/dist/local-CvC-z86k.mjs.map +1 -0
  194. package/dist/local-DAJrhvSC.cjs +241 -0
  195. package/dist/local-DAJrhvSC.cjs.map +1 -0
  196. package/dist/migrate-0-A4BOcd.cjs +272 -0
  197. package/dist/migrate-0-A4BOcd.cjs.map +1 -0
  198. package/dist/migrate-C_36JSwV.mjs +181 -0
  199. package/dist/migrate-C_36JSwV.mjs.map +1 -0
  200. package/dist/migrate-DHbXzZIJ.mjs +267 -0
  201. package/dist/migrate-DHbXzZIJ.mjs.map +1 -0
  202. package/dist/migrate-fGWfv2DV.cjs +181 -0
  203. package/dist/migrate-fGWfv2DV.cjs.map +1 -0
  204. package/dist/next.cjs +59 -0
  205. package/dist/next.cjs.map +1 -0
  206. package/dist/next.d.cts +44 -0
  207. package/dist/next.d.cts.map +1 -0
  208. package/dist/next.d.mts +44 -0
  209. package/dist/next.d.mts.map +1 -0
  210. package/dist/next.mjs +58 -0
  211. package/dist/next.mjs.map +1 -0
  212. package/dist/openapi.cjs +213 -7
  213. package/dist/openapi.cjs.map +1 -0
  214. package/dist/openapi.d.cts +27 -8
  215. package/dist/openapi.d.cts.map +1 -1
  216. package/dist/openapi.d.mts +27 -8
  217. package/dist/openapi.d.mts.map +1 -1
  218. package/dist/openapi.mjs +208 -2
  219. package/dist/openapi.mjs.map +1 -0
  220. package/dist/projectBucket-BAoFOQtA.cjs +263 -0
  221. package/dist/projectBucket-BAoFOQtA.cjs.map +1 -0
  222. package/dist/projectBucket-Dxub09V1.mjs +222 -0
  223. package/dist/projectBucket-Dxub09V1.mjs.map +1 -0
  224. package/dist/provider-BvjDbsTR.mjs +46 -0
  225. package/dist/provider-BvjDbsTR.mjs.map +1 -0
  226. package/dist/provider-DLhgo-mB.cjs +57 -0
  227. package/dist/provider-DLhgo-mB.cjs.map +1 -0
  228. package/dist/publish-BX8_zXaf.cjs +124 -0
  229. package/dist/publish-BX8_zXaf.cjs.map +1 -0
  230. package/dist/publish-DE_yBzlz.mjs +123 -0
  231. package/dist/publish-DE_yBzlz.mjs.map +1 -0
  232. package/dist/ready-DCvnFZnJ.cjs +404 -0
  233. package/dist/ready-DCvnFZnJ.cjs.map +1 -0
  234. package/dist/ready-sSPuiZ7N.mjs +375 -0
  235. package/dist/ready-sSPuiZ7N.mjs.map +1 -0
  236. package/dist/reconcile/public.cjs +3 -5
  237. package/dist/reconcile/public.d.cts +33 -89
  238. package/dist/reconcile/public.d.cts.map +1 -1
  239. package/dist/reconcile/public.d.mts +33 -89
  240. package/dist/reconcile/public.d.mts.map +1 -1
  241. package/dist/reconcile/public.mjs +3 -3
  242. package/dist/reconcile--I7V4Klj.mjs +34 -0
  243. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  244. package/dist/reconcile-CuCQBa5-.cjs +34 -0
  245. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  246. package/dist/resolve-CPB2jkB4.cjs +316 -0
  247. package/dist/resolve-CPB2jkB4.cjs.map +1 -0
  248. package/dist/resolve-DCPtP7-X.mjs +263 -0
  249. package/dist/resolve-DCPtP7-X.mjs.map +1 -0
  250. package/dist/rollback-sefKrjlE.mjs +137 -0
  251. package/dist/rollback-sefKrjlE.mjs.map +1 -0
  252. package/dist/rollback-ygh2qRWo.cjs +166 -0
  253. package/dist/rollback-ygh2qRWo.cjs.map +1 -0
  254. package/dist/runtime-BwiWhqkI.d.cts +82 -0
  255. package/dist/runtime-BwiWhqkI.d.cts.map +1 -0
  256. package/dist/runtime-Dx5F8-IL.d.mts +82 -0
  257. package/dist/runtime-Dx5F8-IL.d.mts.map +1 -0
  258. package/dist/s3-Bcvbg8io.cjs +240 -0
  259. package/dist/s3-Bcvbg8io.cjs.map +1 -0
  260. package/dist/s3-DK1ofU4f.mjs +240 -0
  261. package/dist/s3-DK1ofU4f.mjs.map +1 -0
  262. package/dist/sandbox/config-worker.cjs +43 -0
  263. package/dist/sandbox/config-worker.cjs.map +1 -0
  264. package/dist/sandbox/config-worker.d.cts +1 -0
  265. package/dist/sandbox/config-worker.d.mts +1 -0
  266. package/dist/sandbox/config-worker.mjs +44 -0
  267. package/dist/sandbox/config-worker.mjs.map +1 -0
  268. package/dist/sandbox/credentials-worker.cjs +53 -0
  269. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  270. package/dist/sandbox/credentials-worker.d.cts +1 -0
  271. package/dist/sandbox/credentials-worker.d.mts +1 -0
  272. package/dist/sandbox/credentials-worker.mjs +54 -0
  273. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  274. package/dist/sandbox/discover-worker.cjs +47 -0
  275. package/dist/sandbox/discover-worker.cjs.map +1 -0
  276. package/dist/sandbox/discover-worker.d.cts +1 -0
  277. package/dist/sandbox/discover-worker.d.mts +1 -0
  278. package/dist/sandbox/discover-worker.mjs +48 -0
  279. package/dist/sandbox/discover-worker.mjs.map +1 -0
  280. package/dist/sandbox/migrate-worker.cjs +75 -0
  281. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  282. package/dist/sandbox/migrate-worker.d.cts +1 -0
  283. package/dist/sandbox/migrate-worker.d.mts +1 -0
  284. package/dist/sandbox/migrate-worker.mjs +76 -0
  285. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  286. package/dist/{workspace-CRD9YinV.cjs → schemas-BCwKKA42.mjs} +399 -1179
  287. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  288. package/dist/{workspace-Bu3xNCej.mjs → schemas-BQ_v0lEX.cjs} +487 -982
  289. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  290. package/dist/secretsManager-CjTo6CRq.mjs +113 -0
  291. package/dist/secretsManager-CjTo6CRq.mjs.map +1 -0
  292. package/dist/secretsManager-CvmBGjdM.cjs +124 -0
  293. package/dist/secretsManager-CvmBGjdM.cjs.map +1 -0
  294. package/dist/seeds-Bc3niNVb.cjs +382 -0
  295. package/dist/seeds-Bc3niNVb.cjs.map +1 -0
  296. package/dist/seeds-Ccn0Ru2T.mjs +299 -0
  297. package/dist/seeds-Ccn0Ru2T.mjs.map +1 -0
  298. package/dist/serverSetup-ClU2iSeU.cjs +686 -0
  299. package/dist/serverSetup-ClU2iSeU.cjs.map +1 -0
  300. package/dist/serverSetup-D68Otrp0.mjs +686 -0
  301. package/dist/serverSetup-D68Otrp0.mjs.map +1 -0
  302. package/dist/sniffer-CFOmQQit.cjs +1997 -0
  303. package/dist/sniffer-CFOmQQit.cjs.map +1 -0
  304. package/dist/sniffer-CRF3eD_B.mjs +1824 -0
  305. package/dist/sniffer-CRF3eD_B.mjs.map +1 -0
  306. package/dist/snsSubscriptions-CwA6Ceg2.mjs +1024 -0
  307. package/dist/snsSubscriptions-CwA6Ceg2.mjs.map +1 -0
  308. package/dist/snsSubscriptions-S_CMCXqI.cjs +1149 -0
  309. package/dist/snsSubscriptions-S_CMCXqI.cjs.map +1 -0
  310. package/dist/sst-BgG7dJJu.cjs +514 -0
  311. package/dist/sst-BgG7dJJu.cjs.map +1 -0
  312. package/dist/sst-CDnHFO3U.mjs +491 -0
  313. package/dist/sst-CDnHFO3U.mjs.map +1 -0
  314. package/dist/stack-BXmLQf3K.mjs +10920 -0
  315. package/dist/stack-BXmLQf3K.mjs.map +1 -0
  316. package/dist/stack-BtnflNSa.cjs +11901 -0
  317. package/dist/stack-BtnflNSa.cjs.map +1 -0
  318. package/dist/stage-BbQidxxa.mjs +302 -0
  319. package/dist/stage-BbQidxxa.mjs.map +1 -0
  320. package/dist/stage-ssuPXLhP.cjs +331 -0
  321. package/dist/stage-ssuPXLhP.cjs.map +1 -0
  322. package/dist/stages-CQwD2QxS.cjs +190 -0
  323. package/dist/stages-CQwD2QxS.cjs.map +1 -0
  324. package/dist/stages-MA2sXnX4.mjs +190 -0
  325. package/dist/stages-MA2sXnX4.mjs.map +1 -0
  326. package/dist/target/public.cjs +15 -0
  327. package/dist/target/public.d.cts +28 -0
  328. package/dist/target/public.d.cts.map +1 -0
  329. package/dist/target/public.d.mts +28 -0
  330. package/dist/target/public.d.mts.map +1 -0
  331. package/dist/target/public.mjs +4 -0
  332. package/dist/terminal-BEGE1AEV.mjs +85 -0
  333. package/dist/terminal-BEGE1AEV.mjs.map +1 -0
  334. package/dist/terminal-BecJpgA3.cjs +85 -0
  335. package/dist/terminal-BecJpgA3.cjs.map +1 -0
  336. package/dist/{types-7R81hu0i.d.mts → types-BvokH0ya.d.cts} +2235 -459
  337. package/dist/types-BvokH0ya.d.cts.map +1 -0
  338. package/dist/{types-N7c2O2m7.d.cts → types-DmLnGeii.d.mts} +2233 -459
  339. package/dist/types-DmLnGeii.d.mts.map +1 -0
  340. package/dist/utils-CdKxD8Lt.mjs +156 -0
  341. package/dist/utils-CdKxD8Lt.mjs.map +1 -0
  342. package/dist/utils-DBqXbB8P.cjs +205 -0
  343. package/dist/utils-DBqXbB8P.cjs.map +1 -0
  344. package/dist/vitest.cjs +65 -0
  345. package/dist/vitest.cjs.map +1 -0
  346. package/dist/vitest.d.cts +29 -0
  347. package/dist/vitest.d.cts.map +1 -0
  348. package/dist/vitest.d.mts +29 -0
  349. package/dist/vitest.d.mts.map +1 -0
  350. package/dist/vitest.mjs +65 -0
  351. package/dist/vitest.mjs.map +1 -0
  352. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  353. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  354. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  355. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  356. package/dist/workspace/index.cjs +6 -2
  357. package/dist/workspace/index.d.cts +3 -3
  358. package/dist/workspace/index.d.mts +3 -3
  359. package/dist/workspace/index.mjs +2 -2
  360. package/dist/workspace-DEmfa9RO.cjs +3689 -0
  361. package/dist/workspace-DEmfa9RO.cjs.map +1 -0
  362. package/dist/workspace-RgU7TBgg.mjs +3133 -0
  363. package/dist/workspace-RgU7TBgg.mjs.map +1 -0
  364. package/package.json +76 -13
  365. package/dist/HostingerProvider-BY26bWwB.mjs +0 -243
  366. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  367. package/dist/HostingerProvider-BZFGYYVA.cjs +0 -243
  368. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  369. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  370. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  371. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  372. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  373. package/dist/Route53Provider-Cvj40A8I.mjs +0 -209
  374. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  375. package/dist/Route53Provider-DVILBsvV.cjs +0 -209
  376. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  377. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  378. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  379. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  380. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  381. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  382. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  383. package/dist/bundler-mjqGAvu1.cjs.map +0 -1
  384. package/dist/bundler-mwH7WOb1.mjs.map +0 -1
  385. package/dist/config-DSXI480r.cjs +0 -467
  386. package/dist/config-DSXI480r.cjs.map +0 -1
  387. package/dist/config-DdKkoUE1.mjs +0 -414
  388. package/dist/config-DdKkoUE1.mjs.map +0 -1
  389. package/dist/config.d.cts.map +0 -1
  390. package/dist/config.d.mts.map +0 -1
  391. package/dist/credentials-C6Pfn6GY.cjs +0 -2939
  392. package/dist/credentials-C6Pfn6GY.cjs.map +0 -1
  393. package/dist/credentials-lbv-j0Be.mjs +0 -2802
  394. package/dist/credentials-lbv-j0Be.mjs.map +0 -1
  395. package/dist/discover-BERGFg8v.cjs +0 -288
  396. package/dist/discover-BERGFg8v.cjs.map +0 -1
  397. package/dist/discover-CK-n3w6b.mjs +0 -244
  398. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  399. package/dist/emit-BdoPFjZf.cjs +0 -253
  400. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  401. package/dist/emit-Bzq7JsMP.mjs +0 -224
  402. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  403. package/dist/generator-LfZU7NlU.mjs +0 -247
  404. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  405. package/dist/generator-Wdfp0jCS.cjs +0 -282
  406. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  407. package/dist/github-BvfpvBcW.cjs +0 -216
  408. package/dist/github-BvfpvBcW.cjs.map +0 -1
  409. package/dist/github-DW3CP-4D.mjs +0 -216
  410. package/dist/github-DW3CP-4D.mjs.map +0 -1
  411. package/dist/index-B4H4XF7A.d.mts.map +0 -1
  412. package/dist/index-RCUizGxL.d.cts.map +0 -1
  413. package/dist/openapi-B8bu_OXN.cjs +0 -2038
  414. package/dist/openapi-B8bu_OXN.cjs.map +0 -1
  415. package/dist/openapi-DfjbhrsM.mjs +0 -1991
  416. package/dist/openapi-DfjbhrsM.mjs.map +0 -1
  417. package/dist/reconcile-gb1lz1Dk.mjs +0 -113
  418. package/dist/reconcile-gb1lz1Dk.mjs.map +0 -1
  419. package/dist/reconcile-hx_vBvux.cjs +0 -136
  420. package/dist/reconcile-hx_vBvux.cjs.map +0 -1
  421. package/dist/ssm-BKN1Cg4z.mjs +0 -60
  422. package/dist/ssm-BKN1Cg4z.mjs.map +0 -1
  423. package/dist/ssm-FxeSAt35.cjs +0 -60
  424. package/dist/ssm-FxeSAt35.cjs.map +0 -1
  425. package/dist/storage-DgypfSD6.cjs +0 -351
  426. package/dist/storage-DgypfSD6.cjs.map +0 -1
  427. package/dist/storage-TP0x118M.mjs +0 -304
  428. package/dist/storage-TP0x118M.mjs.map +0 -1
  429. package/dist/transfer-DjFZRgub.mjs +0 -122
  430. package/dist/transfer-DjFZRgub.mjs.map +0 -1
  431. package/dist/transfer-SeiSeKEF.cjs +0 -151
  432. package/dist/transfer-SeiSeKEF.cjs.map +0 -1
  433. package/dist/types-7R81hu0i.d.mts.map +0 -1
  434. package/dist/types-N7c2O2m7.d.cts.map +0 -1
  435. package/dist/workspace-Bu3xNCej.mjs.map +0 -1
  436. package/dist/workspace-CRD9YinV.cjs.map +0 -1
@@ -0,0 +1,3910 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-D1x8duqI.cjs");
3
+ const require_credentials = require("./credentials-Cp09PIsc.cjs");
4
+ const require_stack = require("./stack-BtnflNSa.cjs");
5
+ const require_workspace = require("./workspace-DEmfa9RO.cjs");
6
+ const require_define = require("./define-zKgLY65H.cjs");
7
+ const require_credentials$1 = require("./credentials-BI52H1ad.cjs");
8
+ const require_SubscriberGenerator = require("./SubscriberGenerator-CxzECrfj.cjs");
9
+ const require_discover = require("./discover-OXczlq08.cjs");
10
+ const require_config = require("./config.cjs");
11
+ const require_resolve = require("./resolve-CPB2jkB4.cjs");
12
+ const require_local = require("./local-DAJrhvSC.cjs");
13
+ const require_sniffer = require("./sniffer-CFOmQQit.cjs");
14
+ const require_snsSubscriptions = require("./snsSubscriptions-S_CMCXqI.cjs");
15
+ const require_iam = require("./iam-D7mXd6by.cjs");
16
+ const require_projectBucket = require("./projectBucket-BAoFOQtA.cjs");
17
+ const require_seeds = require("./seeds-Bc3niNVb.cjs");
18
+ const require_credentialSchemas = require("./credentialSchemas-DjK6xKMk.cjs");
19
+ let node_path = require("node:path");
20
+ let node_crypto = require("node:crypto");
21
+ let _geekmidas_manifest = require("@geekmidas/manifest");
22
+ let _geekmidas_storage_s3_url = require("@geekmidas/storage/s3-url");
23
+ _geekmidas_storage_s3_url = require_rolldown_runtime.__toESM(_geekmidas_storage_s3_url, 1);
24
+ let _geekmidas_edge_dns = require("@geekmidas/edge/dns");
25
+ //#region src/target/secrets.ts
26
+ /**
27
+ * A stage's secrets as a target sees them: read and written through the
28
+ * stage's own store, and masked in everything the run prints once read.
29
+ */
30
+ /**
31
+ * Shorter values are left alone: what a progress line legitimately prints —
32
+ * a port, a stage, an app name — would otherwise come out as `***` wherever
33
+ * a secret happened to share it.
34
+ */
35
+ const SHORTEST_MASKED = 6;
36
+ /** The values a run must never print, and the rewrite that keeps it so. */
37
+ var Redactor = class {
38
+ values = /* @__PURE__ */ new Set();
39
+ add(value) {
40
+ if (value && value.length >= SHORTEST_MASKED) this.values.add(value);
41
+ }
42
+ /** `text` with every masked value replaced by `***`, longest first. */
43
+ redact(text) {
44
+ if (this.values.size === 0) return text;
45
+ let out = text;
46
+ const longestFirst = [...this.values].sort((a, b) => b.length - a.length);
47
+ for (const value of longestFirst) out = out.replaceAll(value, "***");
48
+ return out;
49
+ }
50
+ };
51
+ /** Every value in `secrets` that is a secret rather than a label. */
52
+ function secretValues(secrets) {
53
+ return [
54
+ secrets.seed,
55
+ ...Object.entries(secrets.custom ?? {}).filter(([key]) => !require_workspace.isReservedStageKey(key) && key !== "ZO_ROOT_USER_EMAIL").map(([, value]) => value),
56
+ ...Object.values(secrets.urls ?? {}),
57
+ ...Object.values(secrets.services ?? {}).map((service) => service?.password)
58
+ ].filter((value) => typeof value === "string");
59
+ }
60
+ /**
61
+ * The stage's secrets through the store `secrets.store` names for it. Opening
62
+ * one builds a client and makes no request, so a target that never reads them
63
+ * costs nothing.
64
+ */
65
+ async function deploySecrets(workspace, stage, redactor, options = {}) {
66
+ const store = await require_credentials.secretsStoreFor(workspace, stage, options);
67
+ const mask = (secrets) => {
68
+ for (const value of secretValues(secrets)) redactor.add(value);
69
+ };
70
+ return {
71
+ store: store.name,
72
+ async read() {
73
+ const secrets = await store.read(stage);
74
+ if (secrets) mask(secrets);
75
+ return secrets;
76
+ },
77
+ async write(secrets) {
78
+ mask(secrets);
79
+ await store.write(stage, secrets);
80
+ },
81
+ mask: (value) => redactor.add(value)
82
+ };
83
+ }
84
+ //#endregion
85
+ //#region src/backups/provision.ts
86
+ /** What the backups user and its key are recorded and tagged as. */
87
+ const BACKUPS_ID = "backups";
88
+ /** The backups user's inline policy's name. */
89
+ const BACKUPS_POLICY_NAME = "gkm-backups";
90
+ /** Where a deploy's check puts its marker, under the backups prefix. */
91
+ const VERIFY_MARKER = ".gkm-verify";
92
+ /** The backups user's name: `gkm-<project>-<stage>-backups`. */
93
+ function backupsUserName(scope, stage) {
94
+ return require_workspace.iamUserName({
95
+ scope,
96
+ stage,
97
+ id: BACKUPS_ID
98
+ });
99
+ }
100
+ /**
101
+ * The backups key's policy: put objects under the stage's backups prefix.
102
+ * Uploading in parts is `s3:PutObject` too; aborting one is not, and the
103
+ * bucket's lifecycle does it instead.
104
+ */
105
+ function backupsPolicy(bucket, prefix) {
106
+ return {
107
+ Version: "2012-10-17",
108
+ Statement: [{
109
+ Sid: "GkmBackupsPut",
110
+ Effect: "Allow",
111
+ Action: ["s3:PutObject"],
112
+ Resource: `arn:aws:s3:::${bucket}/${prefix}/*`
113
+ }]
114
+ };
115
+ }
116
+ /** A stage that backs up, and no AWS credentials to create its key with. */
117
+ var BackupsCredentialsMissing = class extends require_errors.GkmError {
118
+ stage;
119
+ constructor(stage) {
120
+ super(`'${stage}' runs Postgres, so the deploy backs it up — and creates the IAM user and key it backs up with in the stage's AWS account — and it found no AWS credentials to do it with. On this machine, supply ${require_workspace.S3_PROVISIONING.describe}. In CI, the step that runs the deploy needs the stage's role (AWS_ROLE_ARN, from gkm deploy:github). To take no backups, set deploy.backups.${stage}: false.`);
121
+ this.stage = stage;
122
+ this.name = "BackupsCredentialsMissing";
123
+ }
124
+ };
125
+ /** No region to create the project bucket in. */
126
+ var BackupsRegionRequired = class extends require_errors.GkmError {
127
+ stage;
128
+ constructor(stage) {
129
+ super(`'${stage}' is backed up to the project bucket, and there is no region to find it in: set state: { provider: 's3', region } in gkm.config.ts, or AWS_REGION.`);
130
+ this.stage = stage;
131
+ this.name = "BackupsRegionRequired";
132
+ }
133
+ };
134
+ /** A bucket construct whose IAM user would be the backups user. */
135
+ var BackupsUserNameTaken = class extends require_errors.GkmError {
136
+ stage;
137
+ construct;
138
+ constructor(stage, construct) {
139
+ super(`The bucket '${construct}' is reached on '${stage}' with the IAM user the stage's backups are put with — both are named after 'backups'. Rename the construct, or set deploy.backups.${stage}: false.`);
140
+ this.stage = stage;
141
+ this.construct = construct;
142
+ this.name = "BackupsUserNameTaken";
143
+ }
144
+ };
145
+ /** The backups key could not put its marker: backups would fail too. */
146
+ var BackupsKeyRefused = class extends require_errors.GkmError {
147
+ stage;
148
+ bucket;
149
+ key;
150
+ said;
151
+ constructor(stage, bucket, key, said) {
152
+ super(`The ${require_stack.BACKUPS_URL_KEY} key of '${stage}' could not put s3://${bucket}/${key} (${said}), so its backups would fail the same way. Run the deploy with the stage's AWS credentials to put its user and policy back, or --rotate-keys to issue it a new key.`);
153
+ this.stage = stage;
154
+ this.bucket = bucket;
155
+ this.key = key;
156
+ this.said = said;
157
+ this.name = "BackupsKeyRefused";
158
+ }
159
+ };
160
+ /**
161
+ * The region the project bucket is in: the state's, when it is kept in S3,
162
+ * the secrets store's when that is in AWS, the credential's, `AWS_REGION`.
163
+ */
164
+ function backupsRegion(workspace, stage, credential, env = process.env) {
165
+ const state = workspace.state;
166
+ const store = workspace.secrets?.store;
167
+ const region = (state && "region" in state ? state.region : void 0) ?? (store && typeof store === "object" && "region" in store ? store.region : void 0) ?? credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
168
+ if (!region) throw new BackupsRegionRequired(stage);
169
+ return region;
170
+ }
171
+ /**
172
+ * The stage's backups bucket, lifecycle, user and key — or, for a stage set
173
+ * to `false`, a notice and nothing else. Returns what the stage's backups
174
+ * came to.
175
+ *
176
+ * @throws {BackupsCredentialsMissing} when there are no AWS credentials
177
+ */
178
+ async function ensureStageBackups(input) {
179
+ const { workspace, manifest, stage, ctx } = input;
180
+ const env = input.env ?? process.env;
181
+ const choice = require_stack.stageBackups(workspace, manifest, stage);
182
+ if (choice.mode === "disabled") {
183
+ ctx.log(`💾 backups: off — deploy.backups.${stage} is false. Nothing is backed up, and nothing already backed up is deleted.`);
184
+ return choice;
185
+ }
186
+ if (choice.mode !== "on") return choice;
187
+ if (require_workspace.stageProvider(workspace, "objects", stage).mode === "provider") {
188
+ const clash = Object.entries(manifest).find(([id, d]) => d.kind === "objects" && require_workspace.appKey(id) === "backups");
189
+ if (clash) throw new BackupsUserNameTaken(stage, clash[0]);
190
+ }
191
+ const credential = await require_stack.awsProvisioningCredentials({
192
+ stage,
193
+ env,
194
+ ...input.profile ? { profile: input.profile } : {},
195
+ ...input.home ? { home: input.home } : {}
196
+ });
197
+ if (!credential) throw new BackupsCredentialsMissing(stage);
198
+ const region = backupsRegion(workspace, stage, credential, env);
199
+ const clients = await backupsClients(credential, region, env);
200
+ const bucket = require_projectBucket.projectBucketName(ctx.identity.scope, await require_projectBucket.callerAccountId(clients.sts));
201
+ const prefix = require_stack.backupsPrefix(workspace, stage);
202
+ const expiries = require_stack.backupExpiries(workspace, manifest);
203
+ ctx.log(`💾 backups: ${choice.backups.describe}, to s3://${bucket}/${prefix}/${ctx.dryRun ? " (dry run)" : ""}`);
204
+ if (await require_projectBucket.findProjectBucket(clients.s3, bucket) === "none") await ctx.change({
205
+ construct: require_stack.BACKUPS_SERVICE,
206
+ resource: `bucket ${bucket}`,
207
+ change: `create in ${region}, expiring each stage's backups`
208
+ }, async () => {
209
+ await require_projectBucket.ensureProjectBucket(clients.s3, {
210
+ bucket,
211
+ region,
212
+ identity: ctx.identity,
213
+ expiries
214
+ });
215
+ });
216
+ else if (await require_projectBucket.reconcileProjectBucketLifecycle(clients.s3, bucket, expiries, { dryRun: true })) await ctx.change({
217
+ construct: require_stack.BACKUPS_SERVICE,
218
+ resource: `bucket ${bucket}`,
219
+ change: `lifecycle: ${expiries.map(describeExpiry).join(", ")}`
220
+ }, async () => {
221
+ await require_projectBucket.reconcileProjectBucketLifecycle(clients.s3, bucket, expiries);
222
+ });
223
+ const user = await require_iam.ensureIamUser(ctx, clients, {
224
+ id: BACKUPS_ID,
225
+ user: backupsUserName(ctx.identity.scope, stage),
226
+ policyName: BACKUPS_POLICY_NAME,
227
+ policy: backupsPolicy(bucket, prefix),
228
+ describe: `put objects under ${prefix}/ only`
229
+ });
230
+ await require_iam.ensureAccessKey(ctx, clients, {
231
+ id: BACKUPS_ID,
232
+ secret: require_iam.s3KeySecret(ctx, clients, {
233
+ bucket,
234
+ urlKey: require_stack.BACKUPS_URL_KEY
235
+ }),
236
+ ...user
237
+ });
238
+ if (choice.backups.pitr) {
239
+ ctx.log(` ${choice.backups.pitr.describe}, to ${require_stack.pitrPrefix(workspace, stage)}/`);
240
+ if (!ctx.secrets["PITR_KEY"]) await ctx.change({
241
+ construct: require_stack.BACKUPS_SERVICE,
242
+ resource: `secret ${require_stack.PITR_KEY}`,
243
+ change: "generate the key WAL and base backups are encrypted with"
244
+ }, () => ctx.writeSecrets({ [require_stack.PITR_KEY]: require_stack.newPitrKey() }));
245
+ }
246
+ return choice;
247
+ }
248
+ /** One lifecycle rule, for the deploy's change line. */
249
+ function describeExpiry(expiry) {
250
+ return `${expiry.prefix.endsWith(`/2`) ? `runs in ${expiry.prefix.slice(0, -1)}` : expiry.prefix} after ${expiry.days} days`;
251
+ }
252
+ /** The clients a backups run creates through. */
253
+ async function backupsClients(credential, region, env) {
254
+ const S3 = await import("@aws-sdk/client-s3");
255
+ const IAM = await import("@aws-sdk/client-iam");
256
+ const { STSClient } = await import("@aws-sdk/client-sts");
257
+ const config = await require_stack.awsClientConfig(credential, region);
258
+ const endpoint = require_stack.awsEndpoint(env, "S3");
259
+ return {
260
+ IAM,
261
+ iam: new IAM.IAMClient(config),
262
+ s3: new S3.S3Client({
263
+ ...config,
264
+ ...endpoint ? {
265
+ endpoint,
266
+ forcePathStyle: true
267
+ } : {}
268
+ }),
269
+ sts: new STSClient(config),
270
+ region,
271
+ ...endpoint ? { endpoint } : {}
272
+ };
273
+ }
274
+ /**
275
+ * The stage's backups key puts its marker under the prefix — the one thing
276
+ * it may do. A key issued by this deploy is waited for, as a bucket's is.
277
+ * Returns whether there was a key to check.
278
+ *
279
+ * @throws {BackupsKeyRefused}
280
+ */
281
+ async function verifyStageBackups(input) {
282
+ const { stage } = input;
283
+ if (require_stack.stageBackups(input.workspace, input.manifest, stage).mode !== "on") return false;
284
+ const url = input.secrets[require_stack.BACKUPS_URL_KEY];
285
+ if (!url) return false;
286
+ const address = (await import("@geekmidas/storage/s3-url")).parse(url);
287
+ if (!address.accessKeyId || !address.secretAccessKey) return false;
288
+ const S3 = await import("@aws-sdk/client-s3");
289
+ const client = new S3.S3Client({
290
+ region: address.region ?? "us-east-1",
291
+ credentials: {
292
+ accessKeyId: address.accessKeyId,
293
+ secretAccessKey: address.secretAccessKey
294
+ },
295
+ ...address.endpoint ? { endpoint: address.endpoint } : {},
296
+ ...address.forcePathStyle ? { forcePathStyle: true } : {}
297
+ });
298
+ const Key = `${require_stack.backupsPrefix(input.workspace, stage)}/${VERIFY_MARKER}`;
299
+ const put = async () => {
300
+ try {
301
+ await client.send(new S3.PutObjectCommand({
302
+ Bucket: address.bucket,
303
+ Key,
304
+ Body: (/* @__PURE__ */ new Date()).toISOString(),
305
+ ContentType: "text/plain"
306
+ }));
307
+ return {
308
+ ok: true,
309
+ said: ""
310
+ };
311
+ } catch (error) {
312
+ const e = error;
313
+ const status = e.$metadata?.httpStatusCode;
314
+ return {
315
+ ok: false,
316
+ ...status !== void 0 ? { status } : {},
317
+ said: `HTTP ${status ?? "no response"} ${e.name ?? "Error"}: ${e.message ?? ""}`
318
+ };
319
+ }
320
+ };
321
+ try {
322
+ const { answer } = await require_iam.whileKeyIsNew(await put(), {
323
+ issuedAt: require_iam.issuedJustNow(input.resources, BACKUPS_ID, address.accessKeyId),
324
+ refused: (answer) => !answer.ok && answer.status === 403,
325
+ ask: put,
326
+ onWait: () => input.log?.(` backups: waiting for the new key ${address.accessKeyId} to become active…`)
327
+ });
328
+ if (!answer.ok) throw new BackupsKeyRefused(stage, address.bucket, Key, answer.said);
329
+ return true;
330
+ } finally {
331
+ client.destroy();
332
+ }
333
+ }
334
+ //#endregion
335
+ //#region src/providers/dnsWriter.ts
336
+ /**
337
+ * The DNS records a provider asks for — a certificate's validation record, a
338
+ * CDN's name, a domain's MX — written through the stage's own DNS providers.
339
+ *
340
+ * The same machinery the deploy's DNS step uses for the stack's hosts
341
+ * (`settleStackDns`), handed a plan of CNAMEs and MX records instead of the
342
+ * server's addresses — an MX's value in its zone-file form,
343
+ * `<priority> <host>`, which every DNS provider reads and writes: a record holding its value is left alone, one with another value
344
+ * is replaced and printed, and what is written is read back. A host under no
345
+ * domain in `dns`, or under a `manual` one, is printed for the person to
346
+ * create and reported back, so the provider can say what it is waiting on.
347
+ *
348
+ * On a Cloudflare domain each is written DNS-only, beside whatever the
349
+ * stage's CDN proxies at the same name: the mail constructs' MX and DKIM
350
+ * records sit on the stage's domain, which is also a site's host.
351
+ */
352
+ async function writeProviderDns(records, options) {
353
+ const { log } = options;
354
+ const dns = options.workspace.dns ? require_stack.normalizeDnsConfig(options.workspace.dns) : {};
355
+ const manual = [];
356
+ const domains = /* @__PURE__ */ new Map();
357
+ for (const record of records) {
358
+ const host = record.host.toLowerCase().replace(/\.$/, "");
359
+ const target = record.value.replace(/\.$/, "");
360
+ const value = record.type === "MX" ? (0, _geekmidas_edge_dns.mxValue)(record.priority, target) : target;
361
+ const domain = require_stack.findRootDomain(host, dns);
362
+ if (!domain) {
363
+ log(` create at its DNS host: ${host} ${record.type} ${value}`);
364
+ manual.push(host);
365
+ continue;
366
+ }
367
+ const config = dns[domain];
368
+ const plan = domains.get(domain) ?? {
369
+ domain,
370
+ provider: typeof config.provider === "string" ? config.provider : "custom",
371
+ config,
372
+ records: []
373
+ };
374
+ const planned = {
375
+ host,
376
+ domain,
377
+ name: require_stack.extractSubdomain(host, domain),
378
+ type: record.type,
379
+ value,
380
+ ttl: require_snsSubscriptions.recordTtl(config),
381
+ ...plan.provider === "cloudflare" ? { proxied: false } : {}
382
+ };
383
+ plan.records.push(planned);
384
+ domains.set(domain, plan);
385
+ }
386
+ if (domains.size === 0) return {
387
+ manual,
388
+ changes: [],
389
+ providers: {}
390
+ };
391
+ const plans = [...domains.values()];
392
+ const tokens = await require_snsSubscriptions.dnsCredentials(options.stage, plans.map(({ domain, config }) => ({
393
+ domain,
394
+ config
395
+ })), options.credentials);
396
+ const applied = await require_snsSubscriptions.settleStackDns({
397
+ stage: options.stage,
398
+ server: { ipv4: "" },
399
+ domains: plans,
400
+ uncovered: []
401
+ }, {
402
+ ...options.dryRun ? { dryRun: true } : { confirm: true },
403
+ log,
404
+ credentials: {
405
+ ...tokens.godaddy ? { credential: tokens.godaddy } : {},
406
+ log
407
+ },
408
+ ...tokens.hostinger ? { hostinger: tokens.hostinger } : {},
409
+ ...tokens.cloudflare ? { cloudflare: tokens.cloudflare } : {},
410
+ ...options.providerFor ? { providerFor: options.providerFor } : {}
411
+ });
412
+ for (const change of applied.changes) {
413
+ if (change.action !== "manual") continue;
414
+ const host = plans.find((p) => p.domain === change.domain)?.records.find((r) => r.name === change.name)?.host;
415
+ if (host) manual.push(host);
416
+ }
417
+ return {
418
+ manual: [...new Set(manual)].sort(),
419
+ changes: applied.changes,
420
+ providers: Object.fromEntries(plans.map((p) => [p.domain, p.provider]))
421
+ };
422
+ }
423
+ //#endregion
424
+ //#region src/providers/s3/cdn.ts
425
+ /**
426
+ * A file server over an `s3` bucket, served through a CDN.
427
+ *
428
+ * Without one a file server answers on the bucket's regional endpoint: every
429
+ * reader, wherever they are, fetches from one region, on an `amazonaws.com`
430
+ * host. With one — the default — each file server gets, on the stage:
431
+ *
432
+ * - **a certificate** for `<fileserver>.<domain>`, from ACM in us-east-1 (the
433
+ * one region CloudFront reads certificates from), validated by a CNAME the
434
+ * deploy writes through the stage's DNS providers and keeps, because ACM
435
+ * renews against the same record;
436
+ * - **an origin access control**, which signs CloudFront's requests to the
437
+ * bucket, and a bucket policy statement granting exactly the stage's
438
+ * distributions `s3:GetObject` on exactly the open prefixes (see
439
+ * `bucketPolicy`) — the bucket itself is never public;
440
+ * - **response headers policies**: CORS for the stage's sites (the same
441
+ * derivation the bucket's own CORS rule uses), and, for the paths the file
442
+ * server calls `immutable`, `Cache-Control: public, max-age=31536000,
443
+ * immutable` over whatever the object was stored with;
444
+ * - **a distribution** on that name: HTTPS only, compressed, GET/HEAD/OPTIONS,
445
+ * cached with AWS's managed `CachingOptimized` policy — keyed on the path
446
+ * alone, so no query string or cookie fragments the cache;
447
+ * - **a CNAME** from the name to the distribution, through the same DNS
448
+ * providers.
449
+ *
450
+ * Open paths only: a key outside them is refused to CloudFront by the bucket
451
+ * policy, so the edge answers it 403, and a signed read goes to the bucket's
452
+ * own host as before (`signedUrl` is an S3 presign).
453
+ *
454
+ * Every resource is recorded in the stage's state and reused, found by its
455
+ * name when a run died before recording it, and put back when it drifted.
456
+ * Nothing is ever deleted.
457
+ */
458
+ /** AWS's managed `CachingOptimized` cache policy: path-keyed, gzip and brotli. */
459
+ const CACHING_OPTIMIZED = "658327ea-f89d-4fab-a63d-7e88639e58f6";
460
+ /** What an immutable path is served with. */
461
+ const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
462
+ /** The only region CloudFront reads a certificate from. */
463
+ const CDN_REGION = "us-east-1";
464
+ /** The distribution's bucket origin. */
465
+ const ORIGIN_ID = "bucket";
466
+ /** Its processors' origin: the stack's processor unit, at a host of its own. */
467
+ const PROCESSORS_ORIGIN_ID = "processors";
468
+ /**
469
+ * AWS's managed `CachingOptimizedForUncompressedObjects`: keyed on the path
470
+ * alone, and nothing re-compressed — a derivative is an image, already
471
+ * compressed, and its width is in the path, so nothing else may fragment it.
472
+ */
473
+ const CACHING_OPTIMIZED_UNCOMPRESSED = "b2884449-e4de-46a7-ac36-70bc7f1ddd6d";
474
+ /** A CDN is a name on the stage's domain, and the stage has none. */
475
+ var FileServerCdnNeedsDomain = class extends require_errors.GkmError {
476
+ server;
477
+ stage;
478
+ constructor(server, stage) {
479
+ super(`'${server}' is served through a CDN on '${stage}', which answers on <fileserver>.<domain> — and '${stage}' has no domain. Set domains.${stage} in gkm.config.ts, or set deploy.objects.${stage}.cdn to false to serve it from the bucket's own endpoint.`);
480
+ this.server = server;
481
+ this.stage = stage;
482
+ this.name = "FileServerCdnNeedsDomain";
483
+ }
484
+ };
485
+ /**
486
+ * The certificate is waiting on its validation record: one the person has to
487
+ * create, or one that has not propagated yet. Everything up to it is
488
+ * recorded, so the next deploy carries on from here.
489
+ */
490
+ var CdnCertificatePending = class extends require_errors.GkmError {
491
+ server;
492
+ host;
493
+ record;
494
+ reason;
495
+ constructor(server, host, record, reason) {
496
+ super((reason === "manual" ? `The certificate for ${host} ('${server}') is validated by a DNS record no DNS provider in gkm.config.ts can write. Create it at the domain's DNS host:
497
+ ` : `The certificate for ${host} ('${server}') is not issued yet: ACM has not seen its validation record. It is written; DNS can take a while to answer with it. Check it resolves:
498
+ `) + ` ${record.name} CNAME ${record.value}\nthen deploy again — the certificate and everything before it are recorded, and the deploy carries on from there.`);
499
+ this.server = server;
500
+ this.host = host;
501
+ this.record = record;
502
+ this.reason = reason;
503
+ this.name = "CdnCertificatePending";
504
+ }
505
+ };
506
+ /** ACM gave up on the certificate. */
507
+ var CdnCertificateFailed = class extends require_errors.GkmError {
508
+ server;
509
+ host;
510
+ status;
511
+ reason;
512
+ constructor(server, host, status, reason) {
513
+ super(`ACM did not issue the certificate for ${host} ('${server}'): ${status}` + (reason ? ` (${reason})` : "") + ". A CAA record on the domain that does not allow amazon.com, or a validation record removed before it was checked, are the usual causes. Fix it and deploy again: a new certificate is requested.");
514
+ this.server = server;
515
+ this.host = host;
516
+ this.status = status;
517
+ this.reason = reason;
518
+ this.name = "CdnCertificateFailed";
519
+ }
520
+ };
521
+ /**
522
+ * The name the stage's CDN resources go by, within CloudFront's limits:
523
+ * letters, digits, `-` and `_`, and at most 64 characters (an origin access
524
+ * control's). Kept whole where it fits; otherwise shortened with a hash of
525
+ * the whole, so two long names never meet.
526
+ */
527
+ function cdnName(scope, stage, serverId) {
528
+ const whole = `gkm-${scope}-${stage}-${require_workspace.appKey(serverId)}`.replace(/[^A-Za-z0-9_-]/g, "-");
529
+ if (whole.length <= 56) return whole;
530
+ return `${whole.slice(0, 47)}-${hash(whole)}`;
531
+ }
532
+ function hash(value) {
533
+ let h = 2166136261;
534
+ for (let i = 0; i < value.length; i++) {
535
+ h ^= value.charCodeAt(i);
536
+ h = Math.imul(h, 16777619);
537
+ }
538
+ return (h >>> 0).toString(36).padStart(8, "0").slice(0, 8);
539
+ }
540
+ /**
541
+ * An open or immutable glob as a CloudFront path pattern. CloudFront's `*`
542
+ * crosses `/`, so a single star is as wide as a double one — the bucket
543
+ * policy reads it the same way, and the construct's own check is the
544
+ * stricter of the three.
545
+ */
546
+ function pathPattern(glob) {
547
+ return glob.replace(/^\/+/, "").replace(/\*\*/g, "*");
548
+ }
549
+ /** A CloudFront list: its `Quantity` and, when it has some, its `Items`. */
550
+ function list(items) {
551
+ return items.length > 0 ? {
552
+ Quantity: items.length,
553
+ Items: [...items]
554
+ } : { Quantity: 0 };
555
+ }
556
+ /** One of the stage's response headers policies. */
557
+ function headersPolicyConfig(input) {
558
+ return {
559
+ Name: input.name,
560
+ Comment: input.comment,
561
+ ...input.origins.length > 0 ? { CorsConfig: {
562
+ AccessControlAllowOrigins: list([...input.origins].sort()),
563
+ AccessControlAllowHeaders: {
564
+ Quantity: 1,
565
+ Items: ["*"]
566
+ },
567
+ AccessControlAllowMethods: {
568
+ Quantity: 3,
569
+ Items: [
570
+ "GET",
571
+ "HEAD",
572
+ "OPTIONS"
573
+ ]
574
+ },
575
+ AccessControlAllowCredentials: false,
576
+ AccessControlMaxAgeSec: 86400,
577
+ OriginOverride: false
578
+ } } : {},
579
+ ...input.immutable ? { CustomHeadersConfig: {
580
+ Quantity: 1,
581
+ Items: [{
582
+ Header: "Cache-Control",
583
+ Value: IMMUTABLE_CACHE_CONTROL,
584
+ Override: true
585
+ }]
586
+ } } : {}
587
+ };
588
+ }
589
+ /** The parts of a distribution's config this provider owns. */
590
+ function distributionConfig(input) {
591
+ const behaviour = (policy) => ({
592
+ TargetOriginId: ORIGIN_ID,
593
+ ViewerProtocolPolicy: "redirect-to-https",
594
+ AllowedMethods: {
595
+ Quantity: 3,
596
+ Items: [
597
+ "GET",
598
+ "HEAD",
599
+ "OPTIONS"
600
+ ],
601
+ CachedMethods: {
602
+ Quantity: 2,
603
+ Items: ["GET", "HEAD"]
604
+ }
605
+ },
606
+ Compress: true,
607
+ CachePolicyId: CACHING_OPTIMIZED,
608
+ ...policy ? { ResponseHeadersPolicyId: policy } : {},
609
+ ...BEHAVIOUR_DEFAULTS
610
+ });
611
+ const patterns = [...new Set(input.immutable.map(pathPattern))].sort();
612
+ const processors = input.processors;
613
+ const processorPatterns = processors ? [...new Set(processors.prefixes.map((p) => `${pathPattern(p)}*`))].sort() : [];
614
+ return {
615
+ CallerReference: input.callerReference,
616
+ Comment: input.comment,
617
+ Enabled: true,
618
+ Aliases: {
619
+ Quantity: 1,
620
+ Items: [input.host]
621
+ },
622
+ Origins: list([{
623
+ Id: ORIGIN_ID,
624
+ DomainName: input.bucketDomain,
625
+ OriginPath: "",
626
+ S3OriginConfig: { OriginAccessIdentity: "" },
627
+ OriginAccessControlId: input.originAccessControlId,
628
+ CustomHeaders: { Quantity: 0 },
629
+ ...ORIGIN_DEFAULTS
630
+ }, ...processors ? [{
631
+ Id: PROCESSORS_ORIGIN_ID,
632
+ DomainName: processors.host,
633
+ OriginPath: "",
634
+ CustomOriginConfig: {
635
+ HTTPPort: 80,
636
+ HTTPSPort: 443,
637
+ OriginProtocolPolicy: "https-only",
638
+ OriginSslProtocols: {
639
+ Quantity: 1,
640
+ Items: ["TLSv1.2"]
641
+ },
642
+ OriginReadTimeout: 30,
643
+ OriginKeepaliveTimeout: 5
644
+ },
645
+ ...ORIGIN_DEFAULTS,
646
+ CustomHeaders: {
647
+ Quantity: 1,
648
+ Items: [{
649
+ HeaderName: require_stack.ORIGIN_VERIFY_HEADER,
650
+ HeaderValue: processors.secret
651
+ }]
652
+ }
653
+ }] : []]),
654
+ DefaultCacheBehavior: behaviour(input.corsPolicyId),
655
+ CacheBehaviors: list([...processorPatterns.map((PathPattern) => ({
656
+ ...behaviour(input.corsPolicyId),
657
+ TargetOriginId: PROCESSORS_ORIGIN_ID,
658
+ Compress: false,
659
+ CachePolicyId: CACHING_OPTIMIZED_UNCOMPRESSED,
660
+ PathPattern
661
+ })), ...patterns.map((PathPattern) => ({
662
+ ...behaviour(input.immutablePolicyId),
663
+ PathPattern
664
+ }))]),
665
+ ViewerCertificate: {
666
+ ACMCertificateArn: input.certificateArn,
667
+ SSLSupportMethod: "sni-only",
668
+ MinimumProtocolVersion: "TLSv1.2_2021",
669
+ CloudFrontDefaultCertificate: false
670
+ },
671
+ HttpVersion: "http2and3",
672
+ IsIPV6Enabled: true,
673
+ DefaultRootObject: ""
674
+ };
675
+ }
676
+ /**
677
+ * What CloudFront fills in a behaviour, at its own defaults. Optional when a
678
+ * distribution is created, required when it is updated — an update replaces
679
+ * each behaviour and origin whole, and one without them is refused ("The
680
+ * parameter SmoothStreaming flag is missing", "The 'OriginCustomHeaders'
681
+ * field is missing"). At the defaults, `holds` still matches a distribution
682
+ * CloudFront filled in itself.
683
+ */
684
+ const BEHAVIOUR_DEFAULTS = {
685
+ SmoothStreaming: false,
686
+ FieldLevelEncryptionId: "",
687
+ TrustedSigners: {
688
+ Enabled: false,
689
+ Quantity: 0
690
+ },
691
+ TrustedKeyGroups: {
692
+ Enabled: false,
693
+ Quantity: 0
694
+ },
695
+ LambdaFunctionAssociations: { Quantity: 0 },
696
+ FunctionAssociations: { Quantity: 0 }
697
+ };
698
+ /** What CloudFront fills in an origin, at its own defaults: see above. */
699
+ const ORIGIN_DEFAULTS = {
700
+ ConnectionAttempts: 3,
701
+ ConnectionTimeout: 10
702
+ };
703
+ /**
704
+ * Whether `current` already holds everything in `wanted`: each key `wanted`
705
+ * names, recursively, with lists compared as sets. What else `current` holds
706
+ * — logging, a WAF, geo restrictions set by hand — is left alone, and a
707
+ * `CallerReference`, fixed at creation, is never compared.
708
+ */
709
+ function holds(current, wanted, key) {
710
+ if (key === "CallerReference") return true;
711
+ if (Array.isArray(wanted)) return Array.isArray(current) && current.length === wanted.length && wanted.every((w) => current.some((c) => holds(c, w)));
712
+ if (wanted && typeof wanted === "object") {
713
+ if (!current || typeof current !== "object") return false;
714
+ return Object.entries(wanted).every(([k, v]) => holds(current[k], v, k));
715
+ }
716
+ return current === wanted;
717
+ }
718
+ /** Header configs a policy may hold that this provider never sets. */
719
+ const FOREIGN_HEADER_CONFIGS = [
720
+ "CorsConfig",
721
+ "CustomHeadersConfig",
722
+ "SecurityHeadersConfig",
723
+ "RemoveHeadersConfig",
724
+ "ServerTimingHeadersConfig"
725
+ ];
726
+ /** Whether a policy is exactly what is wanted: nothing missing, nothing more. */
727
+ function sameHeadersPolicy(current, wanted) {
728
+ if (!current || !holds(current, wanted)) return false;
729
+ return FOREIGN_HEADER_CONFIGS.every((k) => {
730
+ if (k in wanted) return true;
731
+ const extra = current[k];
732
+ return !extra || extra.Quantity === 0;
733
+ });
734
+ }
735
+ const defaultCdnClients = async (credential) => {
736
+ const CF = await import("@aws-sdk/client-cloudfront");
737
+ const ACM = await import("@aws-sdk/client-acm");
738
+ const config = await require_stack.awsClientConfig(credential, CDN_REGION);
739
+ const cloudfront = require_stack.awsEndpoint(process.env, "CLOUDFRONT");
740
+ const acm = require_stack.awsEndpoint(process.env, "ACM");
741
+ return {
742
+ CF,
743
+ ACM,
744
+ cloudfront: new CF.CloudFrontClient({
745
+ ...config,
746
+ ...cloudfront ? { endpoint: cloudfront } : {}
747
+ }),
748
+ acm: new ACM.ACMClient({
749
+ ...config,
750
+ ...acm ? { endpoint: acm } : {}
751
+ }),
752
+ wait: {
753
+ timeoutMs: 9e5,
754
+ intervalMs: 1e4
755
+ }
756
+ };
757
+ };
758
+ let makeCdnClients = defaultCdnClients;
759
+ /** What an AWS SDK error is called, whichever field carries it. */
760
+ function errorName$3(error) {
761
+ const e = error;
762
+ return e?.Code ?? e?.name ?? "";
763
+ }
764
+ async function readOr$2(read, missing) {
765
+ try {
766
+ return await read();
767
+ } catch (error) {
768
+ if (missing.includes(errorName$3(error))) return void 0;
769
+ throw error;
770
+ }
771
+ }
772
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
773
+ /** What stands in for an id a dry run would create. */
774
+ const PLANNED = "(created by this deploy)";
775
+ /** Each file server over a bucket, behind its own distribution. */
776
+ async function ensureBucketCdn(ctx, input) {
777
+ const domain = ctx.workspace.domains?.[ctx.stage];
778
+ if (!domain) throw new FileServerCdnNeedsDomain(input.servers[0].id, ctx.stage);
779
+ const clients = await makeCdnClients(ctx.credential);
780
+ const out = {
781
+ distributionArns: [],
782
+ urls: {}
783
+ };
784
+ for (const server of input.servers) {
785
+ const { arn, url } = await ensureServerCdn(ctx, clients, {
786
+ ...input,
787
+ server,
788
+ host: require_workspace.fileServerHost(server.id, domain),
789
+ processorHost: require_stack.processorOriginHost(server.id, domain)
790
+ });
791
+ out.distributionArns.push(arn);
792
+ out.urls[server.id] = url;
793
+ }
794
+ return out;
795
+ }
796
+ async function ensureServerCdn(ctx, clients, input) {
797
+ const { server, host } = input;
798
+ const name = cdnName(ctx.identity.scope, ctx.stage, server.id);
799
+ const comment = `gkm ${ctx.identity.key} ${ctx.stage} ${server.id}`.slice(0, 128);
800
+ const certificateArn = await ensureCertificate(ctx, clients, {
801
+ id: server.id,
802
+ host,
803
+ name
804
+ });
805
+ const originAccessControlId = await ensureOriginAccessControl(ctx, clients, {
806
+ id: server.id,
807
+ name,
808
+ bucket: input.bucket
809
+ });
810
+ const corsPolicyId = input.origins.length > 0 ? await ensureHeadersPolicy(ctx, clients, {
811
+ id: server.id,
812
+ kind: "cors",
813
+ config: headersPolicyConfig({
814
+ name: `${name}-cors`,
815
+ comment: `${comment}: CORS`,
816
+ origins: input.origins,
817
+ immutable: false
818
+ })
819
+ }) : void 0;
820
+ const immutablePolicyId = server.immutable.length > 0 ? await ensureHeadersPolicy(ctx, clients, {
821
+ id: server.id,
822
+ kind: "immutable",
823
+ config: headersPolicyConfig({
824
+ name: `${name}-immutable`,
825
+ comment: `${comment}: CORS and Cache-Control immutable`,
826
+ origins: input.origins,
827
+ immutable: true
828
+ })
829
+ }) : void 0;
830
+ const processors = server.processors?.length ? {
831
+ prefixes: server.processors,
832
+ host: input.processorHost,
833
+ secret: await ensureOriginSecret(ctx, server.id)
834
+ } : void 0;
835
+ const distribution = await ensureDistribution(ctx, clients, {
836
+ id: server.id,
837
+ comment,
838
+ config: distributionConfig({
839
+ comment,
840
+ callerReference: name,
841
+ host,
842
+ certificateArn,
843
+ bucketDomain: `${input.bucket}.s3.${input.region}.amazonaws.com`,
844
+ originAccessControlId,
845
+ ...corsPolicyId ? { corsPolicyId } : {},
846
+ ...immutablePolicyId ? { immutablePolicyId } : {},
847
+ immutable: server.immutable,
848
+ ...processors ? { processors } : {}
849
+ })
850
+ });
851
+ if (distribution.domainName !== PLANNED) {
852
+ if ((await ctx.writeDns([{
853
+ host,
854
+ type: "CNAME",
855
+ value: distribution.domainName
856
+ }])).manual.includes(host)) ctx.log(` ${host} answers once that record exists — ${server.id}'s URL is https://${host}`);
857
+ }
858
+ return {
859
+ arn: distribution.arn,
860
+ url: `https://${host}`
861
+ };
862
+ }
863
+ /**
864
+ * The idempotency token a certificate is requested with: one per file server
865
+ * and host. ACM answers a repeat of a token within the hour with the
866
+ * certificate it issued for it — so a host changed within the hour of the
867
+ * last request would otherwise get the old host's certificate back.
868
+ */
869
+ function certificateToken(name, host) {
870
+ return (0, node_crypto.createHash)("sha256").update(`${name}\n${host.toLowerCase()}`).digest("hex").slice(0, 32);
871
+ }
872
+ /**
873
+ * The secret the CDN sends a file server's processors: the one in the stage's
874
+ * secrets, or a new one written there — read by the stack, whose edge checks
875
+ * it, when it composes.
876
+ */
877
+ async function ensureOriginSecret(ctx, serverId) {
878
+ const key = require_stack.originSecretKey(serverId);
879
+ const kept = ctx.secrets[key];
880
+ if (kept) return kept;
881
+ const secret = require_stack.newOriginSecret();
882
+ ctx.log(` ${serverId}: a new processor origin secret, kept as ${key}`);
883
+ await ctx.writeSecrets({ [key]: secret });
884
+ return secret;
885
+ }
886
+ /** The certificate for `host`: recorded, adopted, or requested — then issued. */
887
+ async function ensureCertificate(ctx, clients, input) {
888
+ const { ACM, acm } = clients;
889
+ const { id, host } = input;
890
+ const entry = {
891
+ key: `acm-certificate:${id}`,
892
+ type: "acm-certificate",
893
+ data: { host }
894
+ };
895
+ const describe = (arn) => readOr$2(() => acm.send(new ACM.DescribeCertificateCommand({ CertificateArn: arn })), ["ResourceNotFoundException"]).then((out) => out?.Certificate);
896
+ let arn;
897
+ const recorded = ctx.state.record(entry.key);
898
+ if (recorded?.id && recorded.data?.host === host) {
899
+ const found = await describe(recorded.id);
900
+ if (found && found.Status !== "FAILED" && found.Status !== "VALIDATION_TIMED_OUT" && found.Status !== "REVOKED" && found.Status !== "EXPIRED") arn = recorded.id;
901
+ }
902
+ if (!arn) {
903
+ arn = await findCertificate(clients, host);
904
+ if (arn) ctx.log(` adopting the certificate for ${host} — ${arn}`);
905
+ }
906
+ if (!arn) {
907
+ if (ctx.dryRun) {
908
+ await ctx.change({
909
+ construct: id,
910
+ resource: `certificate ${host}`,
911
+ change: "request (ACM, us-east-1, DNS-validated)"
912
+ }, async () => {});
913
+ return PLANNED;
914
+ }
915
+ await ctx.state.pending(entry);
916
+ arn = (await acm.send(new ACM.RequestCertificateCommand({
917
+ DomainName: host,
918
+ ValidationMethod: "DNS",
919
+ IdempotencyToken: certificateToken(input.name, host),
920
+ Tags: require_iam.identityTags(ctx, id).map((t) => ({
921
+ Key: t.Key,
922
+ Value: t.Value
923
+ }))
924
+ }))).CertificateArn;
925
+ await ctx.change({
926
+ construct: id,
927
+ resource: `certificate ${host}`,
928
+ change: "request (ACM, us-east-1, DNS-validated)"
929
+ }, async () => {});
930
+ }
931
+ if (!ctx.dryRun) await ctx.state.ready(entry, arn);
932
+ let certificate = await describe(arn);
933
+ let record = certificate?.DomainValidationOptions?.[0]?.ResourceRecord;
934
+ for (let i = 0; !record && i < 15; i++) {
935
+ await sleep(Math.min(clients.wait.intervalMs, 2e3));
936
+ certificate = await describe(arn);
937
+ record = certificate?.DomainValidationOptions?.[0]?.ResourceRecord;
938
+ }
939
+ const validation = record ? {
940
+ name: record.Name.replace(/\.$/, ""),
941
+ value: record.Value.replace(/\.$/, "")
942
+ } : void 0;
943
+ const written = validation ? await ctx.writeDns([{
944
+ host: validation.name,
945
+ type: "CNAME",
946
+ value: validation.value
947
+ }]) : { manual: [] };
948
+ if (certificate?.Status === "ISSUED" || ctx.dryRun) return arn;
949
+ if (validation && written.manual.includes(validation.name.toLowerCase())) throw new CdnCertificatePending(id, host, validation, "manual");
950
+ ctx.log(` waiting for ACM to issue the certificate for ${host}…`);
951
+ const deadline = Date.now() + clients.wait.timeoutMs;
952
+ while (certificate?.Status === "PENDING_VALIDATION" && Date.now() < deadline) {
953
+ await sleep(clients.wait.intervalMs);
954
+ certificate = await describe(arn);
955
+ }
956
+ if (certificate?.Status === "ISSUED") return arn;
957
+ if (certificate?.Status === "PENDING_VALIDATION" || !certificate) throw new CdnCertificatePending(id, host, validation ?? {
958
+ name: `(not published yet) ${host}`,
959
+ value: ""
960
+ }, "timeout");
961
+ throw new CdnCertificateFailed(id, host, certificate.Status ?? "unknown", certificate.FailureReason);
962
+ }
963
+ /** An issued or pending certificate for exactly `host`, if the account has one. */
964
+ async function findCertificate(clients, host) {
965
+ const { ACM, acm } = clients;
966
+ let NextToken;
967
+ do {
968
+ const page = await acm.send(new ACM.ListCertificatesCommand({
969
+ CertificateStatuses: ["ISSUED", "PENDING_VALIDATION"],
970
+ ...NextToken ? { NextToken } : {}
971
+ }));
972
+ const match = page.CertificateSummaryList?.find((c) => c.DomainName?.toLowerCase() === host);
973
+ if (match?.CertificateArn) return match.CertificateArn;
974
+ NextToken = page.NextToken;
975
+ } while (NextToken);
976
+ }
977
+ /** The origin access control CloudFront signs its bucket requests with. */
978
+ async function ensureOriginAccessControl(ctx, clients, input) {
979
+ const { CF, cloudfront } = clients;
980
+ const entry = {
981
+ key: `cloudfront-oac:${input.id}`,
982
+ type: "cloudfront-oac",
983
+ data: { name: input.name }
984
+ };
985
+ const recorded = ctx.state.record(entry.key)?.id;
986
+ if (recorded) {
987
+ if (await readOr$2(() => cloudfront.send(new CF.GetOriginAccessControlCommand({ Id: recorded })), ["NoSuchOriginAccessControl"])) return recorded;
988
+ }
989
+ let Marker;
990
+ do {
991
+ const page = await cloudfront.send(new CF.ListOriginAccessControlsCommand({ ...Marker ? { Marker } : {} }));
992
+ const match = page.OriginAccessControlList?.Items?.find((o) => o.Name === input.name);
993
+ if (match?.Id) {
994
+ if (!ctx.dryRun) await ctx.state.ready(entry, match.Id);
995
+ return match.Id;
996
+ }
997
+ Marker = page.OriginAccessControlList?.NextMarker;
998
+ } while (Marker);
999
+ let id = PLANNED;
1000
+ await ctx.change({
1001
+ construct: input.id,
1002
+ resource: `origin access control ${input.name}`,
1003
+ change: `create (CloudFront signs its reads of ${input.bucket})`
1004
+ }, async () => {
1005
+ await ctx.state.pending(entry);
1006
+ id = (await cloudfront.send(new CF.CreateOriginAccessControlCommand({ OriginAccessControlConfig: {
1007
+ Name: input.name,
1008
+ Description: `gkm: CloudFront's reads of ${input.bucket}`,
1009
+ OriginAccessControlOriginType: "s3",
1010
+ SigningBehavior: "always",
1011
+ SigningProtocol: "sigv4"
1012
+ } }))).OriginAccessControl.Id;
1013
+ await ctx.state.ready(entry, id);
1014
+ });
1015
+ return id;
1016
+ }
1017
+ /** One response headers policy, as wanted. */
1018
+ async function ensureHeadersPolicy(ctx, clients, input) {
1019
+ const { CF, cloudfront } = clients;
1020
+ const { config } = input;
1021
+ const entry = {
1022
+ key: `cloudfront-headers:${input.id}:${input.kind}`,
1023
+ type: "cloudfront-headers",
1024
+ data: { name: config.Name }
1025
+ };
1026
+ const read = (Id) => readOr$2(() => cloudfront.send(new CF.GetResponseHeadersPolicyConfigCommand({ Id })), ["NoSuchResponseHeadersPolicy"]);
1027
+ let id = ctx.state.record(entry.key)?.id;
1028
+ let current = id ? await read(id) : void 0;
1029
+ if (!current) {
1030
+ id = void 0;
1031
+ let Marker;
1032
+ do {
1033
+ const page = await cloudfront.send(new CF.ListResponseHeadersPoliciesCommand({
1034
+ Type: "custom",
1035
+ ...Marker ? { Marker } : {}
1036
+ }));
1037
+ const match = page.ResponseHeadersPolicyList?.Items?.find((p) => p.ResponseHeadersPolicy?.ResponseHeadersPolicyConfig?.Name === config.Name);
1038
+ if (match?.ResponseHeadersPolicy?.Id) {
1039
+ id = match.ResponseHeadersPolicy.Id;
1040
+ current = await read(id);
1041
+ }
1042
+ Marker = page.ResponseHeadersPolicyList?.NextMarker;
1043
+ } while (!id && Marker);
1044
+ }
1045
+ if (id && current) {
1046
+ if (!ctx.dryRun) await ctx.state.ready(entry, id);
1047
+ if (sameHeadersPolicy(current.ResponseHeadersPolicyConfig, config)) return id;
1048
+ const existing = id;
1049
+ await ctx.change({
1050
+ construct: input.id,
1051
+ resource: `response headers policy ${config.Name}`,
1052
+ change: "put back what drifted"
1053
+ }, async () => {
1054
+ await cloudfront.send(new CF.UpdateResponseHeadersPolicyCommand({
1055
+ Id: existing,
1056
+ IfMatch: current.ETag,
1057
+ ResponseHeadersPolicyConfig: config
1058
+ }));
1059
+ });
1060
+ return existing;
1061
+ }
1062
+ let created = PLANNED;
1063
+ await ctx.change({
1064
+ construct: input.id,
1065
+ resource: `response headers policy ${config.Name}`,
1066
+ change: "create"
1067
+ }, async () => {
1068
+ await ctx.state.pending(entry);
1069
+ created = (await cloudfront.send(new CF.CreateResponseHeadersPolicyCommand({ ResponseHeadersPolicyConfig: config }))).ResponseHeadersPolicy.Id;
1070
+ await ctx.state.ready(entry, created);
1071
+ });
1072
+ return created;
1073
+ }
1074
+ /** The distribution: recorded, found by its comment, or created — as wanted. */
1075
+ async function ensureDistribution(ctx, clients, input) {
1076
+ const { CF, cloudfront } = clients;
1077
+ const entry = {
1078
+ key: `cloudfront-distribution:${input.id}`,
1079
+ type: "cloudfront-distribution"
1080
+ };
1081
+ const get = (Id) => readOr$2(() => cloudfront.send(new CF.GetDistributionCommand({ Id })), ["NoSuchDistribution"]);
1082
+ let found = ctx.state.record(entry.key)?.id ? await get(ctx.state.record(entry.key).id) : void 0;
1083
+ if (!found) {
1084
+ let Marker;
1085
+ do {
1086
+ const page = await cloudfront.send(new CF.ListDistributionsCommand({ ...Marker ? { Marker } : {} }));
1087
+ const match = page.DistributionList?.Items?.find((d) => d.Comment === input.comment);
1088
+ if (match?.Id) found = await get(match.Id);
1089
+ Marker = page.DistributionList?.NextMarker;
1090
+ } while (!found && Marker);
1091
+ }
1092
+ if (found?.Distribution) {
1093
+ const distribution = found.Distribution;
1094
+ const id = distribution.Id;
1095
+ const located = {
1096
+ arn: distribution.ARN,
1097
+ domainName: distribution.DomainName
1098
+ };
1099
+ if (!ctx.dryRun) await ctx.state.ready({
1100
+ ...entry,
1101
+ data: located
1102
+ }, id);
1103
+ const current = await cloudfront.send(new CF.GetDistributionConfigCommand({ Id: id }));
1104
+ if (holds(current.DistributionConfig, input.config)) return located;
1105
+ await ctx.change({
1106
+ construct: input.id,
1107
+ resource: `distribution ${id}`,
1108
+ change: "put back what drifted"
1109
+ }, async () => {
1110
+ await cloudfront.send(new CF.UpdateDistributionCommand({
1111
+ Id: id,
1112
+ IfMatch: current.ETag,
1113
+ DistributionConfig: {
1114
+ ...current.DistributionConfig,
1115
+ ...input.config,
1116
+ CallerReference: current.DistributionConfig.CallerReference
1117
+ }
1118
+ }));
1119
+ });
1120
+ return located;
1121
+ }
1122
+ let created = {
1123
+ arn: `arn:aws:cloudfront::${PLANNED}`,
1124
+ domainName: PLANNED
1125
+ };
1126
+ const host = input.config.Aliases?.Items?.[0] ?? input.id;
1127
+ await ctx.change({
1128
+ construct: input.id,
1129
+ resource: `distribution ${host}`,
1130
+ change: "create (CloudFront, takes minutes to reach every edge)"
1131
+ }, async () => {
1132
+ await ctx.state.pending(entry);
1133
+ const out = await cloudfront.send(new CF.CreateDistributionWithTagsCommand({ DistributionConfigWithTags: {
1134
+ DistributionConfig: input.config,
1135
+ Tags: { Items: require_iam.identityTags(ctx, input.id).map((t) => ({
1136
+ Key: t.Key,
1137
+ Value: t.Value
1138
+ })) }
1139
+ } }));
1140
+ created = {
1141
+ arn: out.Distribution.ARN,
1142
+ domainName: out.Distribution.DomainName
1143
+ };
1144
+ await ctx.state.ready({
1145
+ ...entry,
1146
+ data: created
1147
+ }, out.Distribution.Id);
1148
+ });
1149
+ return created;
1150
+ }
1151
+ //#endregion
1152
+ //#region src/providers/s3/events.ts
1153
+ /** What S3 tells the topic about: every object written, and every removed. */
1154
+ const BUCKET_EVENTS = ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"];
1155
+ /**
1156
+ * Each bucket a subscriber watches, with the subscribers watching it: the
1157
+ * worker that runs each, and its export — what its route is named after.
1158
+ *
1159
+ * Read off the bucket's own node, where discovery nests every subscriber
1160
+ * bound to it with the worker that owns it.
1161
+ */
1162
+ function bucketWatchers(manifest) {
1163
+ const watched = /* @__PURE__ */ new Map();
1164
+ for (const [id, declaration] of Object.entries(manifest)) {
1165
+ if (declaration.kind !== "objects") continue;
1166
+ const subscribers = declaration.subscribers ?? [];
1167
+ if (subscribers.length === 0) continue;
1168
+ watched.set(id, subscribers.flatMap((s) => s.owner ? [{
1169
+ worker: s.owner,
1170
+ name: s.id
1171
+ }] : []).sort((a, b) => `${a.worker}/${a.name}`.localeCompare(`${b.worker}/${b.name}`)));
1172
+ }
1173
+ return watched;
1174
+ }
1175
+ /** The topic a bucket's changes are published to. */
1176
+ function eventsTopicName(bucket) {
1177
+ return `${bucket.replaceAll(".", "-")}-events`;
1178
+ }
1179
+ /** What SNS gives up delivering, kept. */
1180
+ function eventsDeadLetterName(bucket) {
1181
+ return `${eventsTopicName(bucket)}-dlq`;
1182
+ }
1183
+ /** Only this bucket, in this account, may publish to its topic. */
1184
+ function eventsTopicPolicy(topicArn, bucket, account) {
1185
+ return {
1186
+ Version: "2012-10-17",
1187
+ Statement: [{
1188
+ Sid: "GkmBucketPublishes",
1189
+ Effect: "Allow",
1190
+ Principal: { Service: "s3.amazonaws.com" },
1191
+ Action: "sns:Publish",
1192
+ Resource: topicArn,
1193
+ Condition: {
1194
+ ArnLike: { "aws:SourceArn": `arn:aws:s3:::${bucket}` },
1195
+ StringEquals: { "aws:SourceAccount": account }
1196
+ }
1197
+ }]
1198
+ };
1199
+ }
1200
+ /** Only the bucket's topic may send to its dead-letter queue. */
1201
+ function eventsDeadLetterPolicy(queueArn, topicArn) {
1202
+ return {
1203
+ Version: "2012-10-17",
1204
+ Statement: [{
1205
+ Sid: "GkmTopicDeadLetters",
1206
+ Effect: "Allow",
1207
+ Principal: { Service: "sns.amazonaws.com" },
1208
+ Action: "sqs:SendMessage",
1209
+ Resource: queueArn,
1210
+ Condition: { ArnEquals: { "aws:SourceArn": topicArn } }
1211
+ }]
1212
+ };
1213
+ }
1214
+ /** The id this provider's notification entry goes under. */
1215
+ const notificationId = (id) => `gkm-${id}`;
1216
+ /**
1217
+ * The bucket's notifications with this provider's entry put back, and whether
1218
+ * that changed anything. Every other entry — a queue, a function, a topic
1219
+ * somebody added by hand — is kept exactly as it was.
1220
+ */
1221
+ function mergedNotifications(current, id, topicArn) {
1222
+ const own = notificationId(id);
1223
+ const wanted = {
1224
+ Id: own,
1225
+ TopicArn: topicArn,
1226
+ Events: [...BUCKET_EVENTS]
1227
+ };
1228
+ const topics = current.TopicConfigurations ?? [];
1229
+ const existing = topics.find((t) => t.Id === own);
1230
+ const same = existing !== void 0 && existing.TopicArn === topicArn && JSON.stringify([...existing.Events ?? []].sort()) === JSON.stringify([...BUCKET_EVENTS].sort()) && existing.Filter === void 0;
1231
+ const { ResponseMetadata: _, ...rest } = current;
1232
+ return {
1233
+ config: {
1234
+ ...rest,
1235
+ TopicConfigurations: [...topics.filter((t) => t.Id !== own), wanted]
1236
+ },
1237
+ changed: !same
1238
+ };
1239
+ }
1240
+ /** S3 refused the entry because another one already covers these events. */
1241
+ var BucketNotificationsOverlap = class extends require_errors.GkmError {
1242
+ bucket;
1243
+ detail;
1244
+ constructor(bucket, detail) {
1245
+ super(`'${bucket}' already sends object creates or deletes somewhere else, and S3 sends each event to one place only, so the deploy cannot add its own entry. Remove the other notification from the bucket, or give it a prefix, and deploy again. S3 said: ${detail}`);
1246
+ this.bucket = bucket;
1247
+ this.detail = detail;
1248
+ this.name = "BucketNotificationsOverlap";
1249
+ }
1250
+ };
1251
+ const defaultEventsClients = async (credential, region) => {
1252
+ const SNS = await import("@aws-sdk/client-sns");
1253
+ const SQS = await import("@aws-sdk/client-sqs");
1254
+ const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
1255
+ const config = await require_stack.awsClientConfig(credential, region);
1256
+ const endpoint = require_stack.awsEndpoint(process.env, "SNS");
1257
+ const sts = new STSClient({
1258
+ ...config,
1259
+ ...require_stack.awsEndpoint(process.env, "STS") ? { endpoint: require_stack.awsEndpoint(process.env, "STS") } : {}
1260
+ });
1261
+ const { Account } = await sts.send(new GetCallerIdentityCommand({}));
1262
+ sts.destroy();
1263
+ return {
1264
+ SNS,
1265
+ SQS,
1266
+ sns: new SNS.SNSClient({
1267
+ ...config,
1268
+ ...endpoint ? { endpoint } : {}
1269
+ }),
1270
+ sqs: new SQS.SQSClient({
1271
+ ...config,
1272
+ ...require_stack.awsEndpoint(process.env, "SQS") ? { endpoint: require_stack.awsEndpoint(process.env, "SQS") } : {}
1273
+ }),
1274
+ account: Account,
1275
+ region,
1276
+ ...endpoint ? { endpoint } : {}
1277
+ };
1278
+ };
1279
+ let makeEventsClients = defaultEventsClients;
1280
+ /** The stage's SNS, SQS and account, through the factory a test may replace. */
1281
+ function eventsClients(credential, region) {
1282
+ return makeEventsClients(credential, region);
1283
+ }
1284
+ function errorName$2(error) {
1285
+ const e = error;
1286
+ return e?.name ?? e?.Code ?? e?.code ?? "";
1287
+ }
1288
+ async function readOr$1(read, missing) {
1289
+ try {
1290
+ return await read();
1291
+ } catch (error) {
1292
+ if (missing.includes(errorName$2(error))) return void 0;
1293
+ throw error;
1294
+ }
1295
+ }
1296
+ /**
1297
+ * An SNS topic of the stage's, created where missing, whose policy lets
1298
+ * exactly one AWS service publish to it — put back where it drifted. A
1299
+ * watched bucket's topic is published to by S3; an inbox's by SES.
1300
+ */
1301
+ async function ensureTopic(ctx, clients, input) {
1302
+ const { SNS, sns, account, region } = clients;
1303
+ const { id, topicName } = input;
1304
+ const topicArn = `arn:aws:sns:${region}:${account}:${topicName}`;
1305
+ const topicEntry = {
1306
+ key: `${require_snsSubscriptions.TOPIC_TYPE}:${id}`,
1307
+ type: require_snsSubscriptions.TOPIC_TYPE
1308
+ };
1309
+ const topic = await readOr$1(() => sns.send(new SNS.GetTopicAttributesCommand({ TopicArn: topicArn })), ["NotFound", "NotFoundException"]);
1310
+ if (topic) await ctx.state.ready(topicEntry, topicArn);
1311
+ else await ctx.change({
1312
+ construct: id,
1313
+ resource: `SNS topic ${topicName}`,
1314
+ change: "create"
1315
+ }, async () => {
1316
+ await ctx.state.pending(topicEntry);
1317
+ await sns.send(new SNS.CreateTopicCommand({
1318
+ Name: topicName,
1319
+ Tags: require_iam.identityTags(ctx, id)
1320
+ }));
1321
+ await ctx.state.ready(topicEntry, topicArn);
1322
+ });
1323
+ const topicPolicy = input.policy(topicArn);
1324
+ const currentTopicPolicy = topic?.Attributes?.Policy;
1325
+ if (!currentTopicPolicy || require_iam.canonicalPolicy(JSON.parse(currentTopicPolicy)) !== require_iam.canonicalPolicy(topicPolicy)) await ctx.change({
1326
+ construct: id,
1327
+ resource: `SNS topic ${topicName}`,
1328
+ change: `publishable by ${input.publisher} only`
1329
+ }, async () => {
1330
+ await sns.send(new SNS.SetTopicAttributesCommand({
1331
+ TopicArn: topicArn,
1332
+ AttributeName: "Policy",
1333
+ AttributeValue: JSON.stringify(topicPolicy)
1334
+ }));
1335
+ });
1336
+ return topicArn;
1337
+ }
1338
+ /**
1339
+ * The topic, its policy, the dead-letter queue and the bucket's notification
1340
+ * entry for one watched bucket — created where missing, put back where they
1341
+ * drifted.
1342
+ */
1343
+ async function ensureBucketEvents(ctx, s3, input) {
1344
+ const { id, bucket, region } = input;
1345
+ const clients = await makeEventsClients(ctx.credential, region);
1346
+ const { SQS, sns, sqs, account } = clients;
1347
+ const topicName = eventsTopicName(bucket);
1348
+ const topicArn = await ensureTopic(ctx, clients, {
1349
+ id,
1350
+ topicName,
1351
+ publisher: `'${bucket}'`,
1352
+ policy: (arn) => eventsTopicPolicy(arn, bucket, account)
1353
+ });
1354
+ const queueName = eventsDeadLetterName(bucket);
1355
+ const deadLetterArn = `arn:aws:sqs:${region}:${account}:${queueName}`;
1356
+ const queueEntry = {
1357
+ key: `sqs-queue:${id}-events-dlq`,
1358
+ type: "sqs-queue"
1359
+ };
1360
+ const queue = await readOr$1(() => sqs.send(new SQS.GetQueueUrlCommand({ QueueName: queueName })), ["QueueDoesNotExist", "AWS.SimpleQueueService.NonExistentQueue"]);
1361
+ let queueUrl = queue?.QueueUrl;
1362
+ if (queueUrl) await ctx.state.ready(queueEntry, deadLetterArn);
1363
+ else await ctx.change({
1364
+ construct: id,
1365
+ resource: `SQS queue ${queueName}`,
1366
+ change: "create"
1367
+ }, async () => {
1368
+ await ctx.state.pending(queueEntry);
1369
+ queueUrl = (await sqs.send(new SQS.CreateQueueCommand({
1370
+ QueueName: queueName,
1371
+ Attributes: { MessageRetentionPeriod: "1209600" },
1372
+ tags: Object.fromEntries(require_iam.identityTags(ctx, id).map((t) => [t.Key, t.Value]))
1373
+ }))).QueueUrl;
1374
+ await ctx.state.ready(queueEntry, deadLetterArn);
1375
+ });
1376
+ const queuePolicy = eventsDeadLetterPolicy(deadLetterArn, topicArn);
1377
+ const currentQueuePolicy = queue?.QueueUrl ? (await sqs.send(new SQS.GetQueueAttributesCommand({
1378
+ QueueUrl: queue.QueueUrl,
1379
+ AttributeNames: ["Policy"]
1380
+ }))).Attributes?.Policy : void 0;
1381
+ if (!currentQueuePolicy || require_iam.canonicalPolicy(JSON.parse(currentQueuePolicy)) !== require_iam.canonicalPolicy(queuePolicy)) await ctx.change({
1382
+ construct: id,
1383
+ resource: `SQS queue ${queueName}`,
1384
+ change: `receives what ${topicName} cannot deliver`
1385
+ }, async () => {
1386
+ await sqs.send(new SQS.SetQueueAttributesCommand({
1387
+ QueueUrl: queueUrl,
1388
+ Attributes: { Policy: JSON.stringify(queuePolicy) }
1389
+ }));
1390
+ });
1391
+ const merged = mergedNotifications(await readOr$1(() => s3.s3.send(new s3.S3.GetBucketNotificationConfigurationCommand({ Bucket: bucket })), ["NoSuchBucket"]) ?? {}, id, topicArn);
1392
+ if (merged.changed) await ctx.change({
1393
+ construct: id,
1394
+ resource: `bucket ${bucket}`,
1395
+ change: `send object creates and deletes to ${topicName}`
1396
+ }, async () => {
1397
+ try {
1398
+ await s3.s3.send(new s3.S3.PutBucketNotificationConfigurationCommand({
1399
+ Bucket: bucket,
1400
+ NotificationConfiguration: merged.config
1401
+ }));
1402
+ } catch (error) {
1403
+ const message = error.message ?? "";
1404
+ if (/overlap/i.test(message)) throw new BucketNotificationsOverlap(bucket, message);
1405
+ throw error;
1406
+ }
1407
+ });
1408
+ sns.destroy();
1409
+ sqs.destroy();
1410
+ return {
1411
+ topicArn,
1412
+ deadLetterArn
1413
+ };
1414
+ }
1415
+ /**
1416
+ * A topic's connection string: its address, signed by the access key in a
1417
+ * bucket's URL — read off that URL, so a rotated key rotates this one with
1418
+ * it. A watched bucket's events key by default; an inbox's topic, signed by
1419
+ * its own bucket's key, otherwise.
1420
+ */
1421
+ async function ensureEventsKey(ctx, input) {
1422
+ const { id, topicArn, region } = input;
1423
+ const key = input.key ?? (0, _geekmidas_manifest.providedKeyFor)(id, "objects", "eventsConnectionString");
1424
+ const url = ctx.secrets[input.urlKey ?? (0, _geekmidas_manifest.providedKeyFor)(id, "objects", "connectionString")];
1425
+ let parsed;
1426
+ try {
1427
+ parsed = url ? _geekmidas_storage_s3_url.parse(url) : void 0;
1428
+ } catch {
1429
+ parsed = void 0;
1430
+ }
1431
+ if (!parsed?.accessKeyId || !parsed.secretAccessKey) {
1432
+ await ctx.change({
1433
+ construct: id,
1434
+ resource: key,
1435
+ change: "set to the topic’s address"
1436
+ }, async () => {});
1437
+ return;
1438
+ }
1439
+ const { snsUrl } = await import("@geekmidas/events/sns");
1440
+ const endpoint = require_stack.awsEndpoint(process.env, "SNS");
1441
+ const address = new URL(snsUrl.build({
1442
+ topicArn,
1443
+ region,
1444
+ ...endpoint ? { endpoint } : {}
1445
+ }));
1446
+ address.searchParams.set("accessKeyId", parsed.accessKeyId);
1447
+ address.searchParams.set("secretAccessKey", parsed.secretAccessKey);
1448
+ const value = address.toString();
1449
+ const entry = {
1450
+ key: `events-key:${id}`,
1451
+ type: "url"
1452
+ };
1453
+ if (ctx.secrets[key] === value) {
1454
+ await ctx.state.ready(entry, topicArn);
1455
+ return;
1456
+ }
1457
+ await ctx.change({
1458
+ construct: id,
1459
+ resource: key,
1460
+ change: `set to ${topicArn}`
1461
+ }, async () => {
1462
+ await ctx.writeSecrets({ [key]: value });
1463
+ await ctx.state.ready(entry, topicArn);
1464
+ });
1465
+ }
1466
+ /** Where SNS pushes to a worker: its own host on the stage's domain. */
1467
+ function workerPushHost(worker, domain) {
1468
+ return `${require_workspace.appKey(worker)}.${domain}`;
1469
+ }
1470
+ /**
1471
+ * One HTTP subscription per subscriber to the bucket's topic, at its route on
1472
+ * its worker's host, with the bucket's dead-letter queue — and each ARN
1473
+ * recorded, which is what the worker accepts deliveries under.
1474
+ *
1475
+ * Unfiltered: a bucket's notifications carry no `type` attribute, and the
1476
+ * subscriber's own filter — events, prefix, suffix — is what decides. Only a
1477
+ * compose stage pushes to a worker; any other is told so and left alone.
1478
+ */
1479
+ async function ensurePushSubscriptions(ctx, input) {
1480
+ const { id, events, region, watchers } = input;
1481
+ if (!require_stack.deploysWithCompose(ctx.workspace)) {
1482
+ ctx.log(` '${id}' is watched, and only a compose stage pushes a bucket's changes to a worker: its subscribers receive nothing on '${ctx.stage}'`);
1483
+ return;
1484
+ }
1485
+ if (watchers.length === 0) return;
1486
+ const domain = ctx.workspace.domains?.[ctx.stage];
1487
+ if (!domain) throw new require_credentials$1.NoDomainForStage(ctx.stage);
1488
+ const { SNSConnection, reconcileHttpSubscriptions } = await import("@geekmidas/events/sns");
1489
+ const { credentials } = await require_stack.awsClientConfig(ctx.credential, region);
1490
+ const endpoint = require_stack.awsEndpoint(process.env, "SNS");
1491
+ const byWorker = /* @__PURE__ */ new Map();
1492
+ for (const watcher of watchers) byWorker.set(watcher.worker, [...byWorker.get(watcher.worker) ?? [], watcher]);
1493
+ for (const [worker, own] of byWorker) {
1494
+ const host = workerPushHost(worker, domain);
1495
+ const endpoints = own.map(({ name }) => ({
1496
+ name,
1497
+ endpoint: `https://${host}${require_SubscriberGenerator.subscriberRoute(name)}`,
1498
+ deadLetterQueueArn: events.deadLetterArn
1499
+ }));
1500
+ const unrecorded = own.filter(({ name }) => ctx.state.record(require_snsSubscriptions.subscriptionKey(worker, name))?.status !== "ready");
1501
+ if (ctx.dryRun) {
1502
+ if (unrecorded.length > 0) await ctx.change({
1503
+ construct: id,
1504
+ resource: `SNS subscriptions on ${host}`,
1505
+ change: `subscribe ${unrecorded.map((w) => w.name).join(", ")}`
1506
+ }, async () => {});
1507
+ continue;
1508
+ }
1509
+ const connection = new SNSConnection({
1510
+ topicArn: events.topicArn,
1511
+ region,
1512
+ ...endpoint ? { endpoint } : {},
1513
+ ...credentials ? { credentials } : {}
1514
+ });
1515
+ const result = await reconcileHttpSubscriptions(connection, {
1516
+ endpoints,
1517
+ ownedHost: host
1518
+ });
1519
+ await connection.close();
1520
+ for (const spec of endpoints) {
1521
+ const arn = result.subscriptions[spec.name];
1522
+ const pending = result.pending.includes(spec.name);
1523
+ if (ctx.state.record(require_snsSubscriptions.subscriptionKey(worker, spec.name))?.id !== arn) ctx.log(` ✓ '${spec.name}' subscribed to ${events.topicArn.split(":").pop()} at ${spec.endpoint}`);
1524
+ const { key, type, data } = require_snsSubscriptions.subscriptionResource({
1525
+ worker,
1526
+ name: spec.name,
1527
+ topicArn: events.topicArn,
1528
+ endpoint: spec.endpoint,
1529
+ deadLetterQueueArn: events.deadLetterArn,
1530
+ pending
1531
+ }, arn);
1532
+ await ctx.state.ready({
1533
+ key,
1534
+ type,
1535
+ ...data ? { data } : {}
1536
+ }, arn);
1537
+ }
1538
+ for (const arn of result.removed) ctx.log(` – unsubscribed ${arn}: no subscriber wants it any more`);
1539
+ }
1540
+ }
1541
+ //#endregion
1542
+ //#region src/providers/s3/origins.ts
1543
+ /**
1544
+ * Which browser origins may call a bucket: the stage's sites that depend on
1545
+ * an API using it.
1546
+ *
1547
+ * The same reading of the graph an API's own CORS origins are — its callers —
1548
+ * taken one step further: a site that calls an API which hands it a presigned
1549
+ * upload URL is a site whose browser PUTs to the bucket. A site that reads the
1550
+ * bucket (or a file server over it) itself is one too. Nothing is written
1551
+ * down: add a site that calls the API and the next provision run allows it.
1552
+ */
1553
+ /**
1554
+ * The keys a reader of this bucket holds: its connection, where it signs its
1555
+ * links (all a site's plain edge to it holds), and each server's address over
1556
+ * it.
1557
+ */
1558
+ function bucketKeys(manifest, bucket) {
1559
+ return [
1560
+ (0, _geekmidas_manifest.providedKeyFor)(bucket, "objects", "connectionString"),
1561
+ (0, _geekmidas_manifest.providedKeyFor)(bucket, "objects", "signedOrigin"),
1562
+ ...Object.entries(manifest).filter(([, d]) => d.kind === "file-server" && d.of === bucket).map(([id]) => (0, _geekmidas_manifest.providedKeyFor)(id, "file-server", "url"))
1563
+ ];
1564
+ }
1565
+ function bucketOrigins(input) {
1566
+ const { manifest, workspace, stage } = input;
1567
+ const keys = bucketKeys(manifest, input.bucket);
1568
+ const readers = Object.entries(manifest).filter(([, d]) => d.kind === "rest-api" || d.kind === "websocket-api" || d.kind === "site").filter(([id]) => {
1569
+ const env = require_stack.appEnvKeys(manifest, require_workspace.appKey(id));
1570
+ return env !== void 0 && keys.some((key) => env.has(key));
1571
+ });
1572
+ const sites = /* @__PURE__ */ new Set();
1573
+ for (const [id, declaration] of readers) {
1574
+ if (declaration.kind === "site") {
1575
+ sites.add(id);
1576
+ continue;
1577
+ }
1578
+ for (const caller of (0, _geekmidas_manifest.dependentsOf)(manifest, id)) if (manifest[caller]?.kind === "site") sites.add(caller);
1579
+ }
1580
+ const origins = /* @__PURE__ */ new Set();
1581
+ const unresolved = [];
1582
+ for (const id of [...sites].sort()) {
1583
+ const name = require_workspace.appKey(id);
1584
+ const app = workspace.apps[name];
1585
+ if (!app) {
1586
+ unresolved.push(name);
1587
+ continue;
1588
+ }
1589
+ try {
1590
+ const host = require_credentials$1.resolveHost(name, app, stage, workspace.domains, require_credentials$1.isMainFrontendApp(name, app, workspace.apps));
1591
+ origins.add(`https://${host}`);
1592
+ } catch (error) {
1593
+ if (!(error instanceof require_credentials$1.NoDomainForStage)) throw error;
1594
+ unresolved.push(name);
1595
+ }
1596
+ }
1597
+ return {
1598
+ origins: [...origins].sort(),
1599
+ unresolved
1600
+ };
1601
+ }
1602
+ //#endregion
1603
+ //#region src/providers/s3/index.ts
1604
+ function bucketConstructs(manifest) {
1605
+ return Object.entries(manifest).filter(([, d]) => d.kind === "objects").map(([id, d]) => ({
1606
+ id,
1607
+ versioned: d.versioned === true,
1608
+ ...(0, _geekmidas_manifest.bucketExpiry)(manifest, id) ? { expire: (0, _geekmidas_manifest.bucketExpiry)(manifest, id) } : {},
1609
+ servers: Object.entries(manifest).filter(([, s]) => s.kind === "file-server" && s.of === id).map(([sid, s]) => ({
1610
+ id: sid,
1611
+ open: s.open ?? [],
1612
+ immutable: s.immutable ?? [],
1613
+ ...s.processors?.length ? { processors: [...new Set(s.processors.map((p) => p.prefix))].sort() } : {}
1614
+ })).sort((a, b) => a.id.localeCompare(b.id))
1615
+ })).sort((a, b) => a.id.localeCompare(b.id));
1616
+ }
1617
+ /**
1618
+ * The address a file server over `bucket` serves on: the bucket's regional
1619
+ * virtual-host endpoint, which is what `FileServer.url(key)` appends a key to
1620
+ * — `https://<bucket>.s3.<region>.amazonaws.com/<key>`. Against an emulator,
1621
+ * its path-style address.
1622
+ */
1623
+ function bucketPublicUrl(bucket, region, endpoint) {
1624
+ if (endpoint) return `${endpoint.replace(/\/+$/, "")}/${bucket}`;
1625
+ return `https://${bucket}.s3.${region}.amazonaws.com`;
1626
+ }
1627
+ /** What an AWS SDK error is called, whichever field carries it. */
1628
+ function errorName$1(error) {
1629
+ const e = error;
1630
+ return e?.Code ?? e?.name ?? "";
1631
+ }
1632
+ /** The answer an SDK call failed with. */
1633
+ function s3Answer(error) {
1634
+ const e = error;
1635
+ const headers = Object.fromEntries(Object.entries(e?.$response?.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
1636
+ const status = e?.$metadata?.httpStatusCode ?? e?.$response?.statusCode;
1637
+ const region = headers["x-amz-bucket-region"];
1638
+ const requestId = e?.$metadata?.requestId ?? headers["x-amz-request-id"];
1639
+ const id2 = e?.$metadata?.extendedRequestId ?? headers["x-amz-id-2"];
1640
+ return {
1641
+ ...status !== void 0 ? { status } : {},
1642
+ name: errorName$1(error) || "Error",
1643
+ message: e?.message ?? String(error),
1644
+ ...region ? { region } : {},
1645
+ ...requestId ? { requestId } : {},
1646
+ ...id2 ? { id2 } : {}
1647
+ };
1648
+ }
1649
+ /**
1650
+ * `HTTP 403 Unknown: UnknownError [x-amz-bucket-region: eu-west-1,
1651
+ * x-amz-request-id: …, x-amz-id-2: …]` — everything S3 said, for a message.
1652
+ */
1653
+ function describeAnswer(answer) {
1654
+ const said = answer.message && answer.message !== answer.name ? `${answer.name}: ${answer.message}` : answer.name;
1655
+ const headers = [
1656
+ answer.region && `x-amz-bucket-region: ${answer.region}`,
1657
+ answer.requestId && `x-amz-request-id: ${answer.requestId}`,
1658
+ answer.id2 && `x-amz-id-2: ${answer.id2}`
1659
+ ].filter(Boolean);
1660
+ return `${answer.status === void 0 ? "no response" : `HTTP ${answer.status}`} ${said}` + (headers.length > 0 ? ` [${headers.join(", ")}]` : "");
1661
+ }
1662
+ /** `HeadBucket`: the bucket's region when it answers, else what S3 said. */
1663
+ async function headBucket(S3, client, bucket) {
1664
+ try {
1665
+ const out = await client.send(new S3.HeadBucketCommand({ Bucket: bucket }));
1666
+ return {
1667
+ ok: true,
1668
+ ...out.BucketRegion ? { region: out.BucketRegion } : {}
1669
+ };
1670
+ } catch (error) {
1671
+ return {
1672
+ ok: false,
1673
+ ...s3Answer(error)
1674
+ };
1675
+ }
1676
+ }
1677
+ /** `GetBucketLocation`'s answer as a region: none is us-east-1, `EU` eu-west-1. */
1678
+ async function bucketLocation(S3, client, bucket) {
1679
+ try {
1680
+ const location = (await client.send(new S3.GetBucketLocationCommand({ Bucket: bucket }))).LocationConstraint;
1681
+ return { region: !location ? "us-east-1" : location === "EU" ? "eu-west-1" : location };
1682
+ } catch (error) {
1683
+ return { failed: s3Answer(error) };
1684
+ }
1685
+ }
1686
+ /**
1687
+ * Where `bucket` is: `HeadBucket`'s `x-amz-bucket-region` — on a 200, a 301
1688
+ * or a 400 alike — else `GetBucketLocation`.
1689
+ *
1690
+ * @throws {BucketRegionUnknown}
1691
+ */
1692
+ async function bucketRegion(clients, bucket) {
1693
+ const { S3, s3 } = clients;
1694
+ const head = await headBucket(S3, s3, bucket);
1695
+ if (head.region) return head.region;
1696
+ const location = await bucketLocation(S3, s3, bucket);
1697
+ if ("region" in location) return location.region;
1698
+ throw new require_workspace.BucketRegionUnknown(bucket, head.ok ? "HTTP 200 without x-amz-bucket-region" : describeAnswer(head), describeAnswer(location.failed));
1699
+ }
1700
+ /** A read whose "there is none" answer is one of `missing`. */
1701
+ async function readOr(read, missing) {
1702
+ try {
1703
+ return await read();
1704
+ } catch (error) {
1705
+ if (missing.includes(errorName$1(error))) return void 0;
1706
+ throw error;
1707
+ }
1708
+ }
1709
+ const defaultClients = async (credential, region) => {
1710
+ const S3 = await import("@aws-sdk/client-s3");
1711
+ const IAM = await import("@aws-sdk/client-iam");
1712
+ const config = await require_stack.awsClientConfig(credential, region);
1713
+ const endpoint = require_stack.awsEndpoint(process.env, "S3");
1714
+ return {
1715
+ S3,
1716
+ IAM,
1717
+ s3: new S3.S3Client({
1718
+ ...config,
1719
+ ...endpoint ? {
1720
+ endpoint,
1721
+ forcePathStyle: true
1722
+ } : {}
1723
+ }),
1724
+ iam: new IAM.IAMClient(config),
1725
+ region,
1726
+ ...endpoint ? { endpoint } : {}
1727
+ };
1728
+ };
1729
+ /** For tests: what makes the clients. */
1730
+ let makeClients = defaultClients;
1731
+ async function ensureS3(ctx) {
1732
+ const region = require_workspace.s3Region(ctx);
1733
+ const clients = await makeClients(ctx.credential, region);
1734
+ const watched = bucketWatchers(ctx.manifest);
1735
+ for (const construct of bucketConstructs(ctx.manifest)) await ensureBucket(ctx, clients, construct, watched.get(construct.id));
1736
+ }
1737
+ async function ensureBucket(ctx, stageClients, construct, watchers) {
1738
+ const { id } = construct;
1739
+ const nameInput = {
1740
+ scope: ctx.identity.scope,
1741
+ stage: ctx.stage,
1742
+ id: require_workspace.appKey(id)
1743
+ };
1744
+ const versioning = ctx.config.versioning ?? construct.versioned;
1745
+ const open = [...new Set(construct.servers.flatMap((s) => s.open))].sort();
1746
+ const located = await ensureBucketName(ctx, stageClients, id, require_workspace.bucketName(nameInput));
1747
+ const { bucket, exists } = located;
1748
+ let clients = stageClients;
1749
+ if (located.region !== stageClients.region) {
1750
+ clients = await makeClients(ctx.credential, located.region);
1751
+ ctx.log(` '${bucket}' is in ${located.region}, not ${stageClients.region}: '${id}' is reached and addressed there`);
1752
+ }
1753
+ const cdn = require_workspace.servesOnCdn(ctx.config) && construct.servers.length > 0 ? await ensureBucketCdn(ctx, {
1754
+ bucket,
1755
+ region: clients.region,
1756
+ servers: construct.servers,
1757
+ origins: bucketOrigins({
1758
+ workspace: ctx.workspace,
1759
+ manifest: ctx.manifest,
1760
+ stage: ctx.stage,
1761
+ bucket: id
1762
+ }).origins
1763
+ }) : void 0;
1764
+ await ensureBucketSettings(ctx, clients, {
1765
+ id,
1766
+ bucket,
1767
+ exists,
1768
+ versioning,
1769
+ open,
1770
+ ...cdn ? { cdn } : {},
1771
+ ...construct.expire ? { expire: construct.expire } : {}
1772
+ });
1773
+ const events = watchers ? await ensureBucketEvents(ctx, clients, {
1774
+ id,
1775
+ bucket,
1776
+ region: clients.region
1777
+ }) : void 0;
1778
+ const user = await require_iam.ensureIamUser(ctx, clients, {
1779
+ id,
1780
+ user: require_workspace.iamUserName(nameInput),
1781
+ policyName: require_workspace.IAM_POLICY_NAME,
1782
+ policy: require_iam.userPolicy(bucket, {
1783
+ versioning,
1784
+ ...events ? { eventsTopicArn: events.topicArn } : {}
1785
+ }),
1786
+ describe: "this bucket only"
1787
+ });
1788
+ await require_iam.ensureAccessKey(ctx, clients, {
1789
+ id,
1790
+ secret: require_iam.s3KeySecret(ctx, clients, {
1791
+ bucket,
1792
+ urlKey: (0, _geekmidas_manifest.providedKeyFor)(id, "objects", "connectionString")
1793
+ }),
1794
+ ...user
1795
+ });
1796
+ if (events && watchers) {
1797
+ await ensureEventsKey(ctx, {
1798
+ id,
1799
+ topicArn: events.topicArn,
1800
+ region: clients.region
1801
+ });
1802
+ await ensurePushSubscriptions(ctx, {
1803
+ id,
1804
+ events,
1805
+ region: clients.region,
1806
+ watchers
1807
+ });
1808
+ }
1809
+ const bucketUrl = bucketPublicUrl(bucket, clients.region, clients.endpoint);
1810
+ for (const server of construct.servers) {
1811
+ const publicUrl = cdn?.urls[server.id] ?? bucketUrl;
1812
+ const key = (0, _geekmidas_manifest.providedKeyFor)(server.id, "file-server", "url");
1813
+ const entry = {
1814
+ key: `file-server:${server.id}`,
1815
+ type: "url"
1816
+ };
1817
+ const recorded = ctx.state.record(entry.key)?.id;
1818
+ const current = ctx.secrets[key];
1819
+ if (current === publicUrl) {
1820
+ await ctx.state.ready(entry, publicUrl);
1821
+ continue;
1822
+ }
1823
+ if (current !== void 0 && current !== recorded) {
1824
+ ctx.log(` ${key} is set to ${current} by you, and kept — the bucket's own address is ${publicUrl}`);
1825
+ continue;
1826
+ }
1827
+ await ctx.change({
1828
+ construct: server.id,
1829
+ resource: key,
1830
+ change: `set to ${publicUrl}`
1831
+ }, async () => {
1832
+ await ctx.writeSecrets({ [key]: publicUrl });
1833
+ await ctx.state.ready(entry, publicUrl);
1834
+ });
1835
+ }
1836
+ }
1837
+ /**
1838
+ * The bucket's name: the recorded one, else the good name, else the good
1839
+ * name with a random suffix — up to {@link SUFFIX_ATTEMPTS} times.
1840
+ */
1841
+ /**
1842
+ * A private bucket a provider makes for a construct that owns one — an
1843
+ * inbox's — by the same steps as any of the stage's buckets: found or
1844
+ * created, its settings put back where they drifted, and reached by an IAM
1845
+ * user of its own whose key is written into `urlKey`. Nothing serves it and
1846
+ * nothing watches it.
1847
+ */
1848
+ async function ensureOwnedBucket(ctx, input) {
1849
+ const bucketCtx = ctx;
1850
+ const stageClients = await makeClients(ctx.credential, require_workspace.s3Region(bucketCtx));
1851
+ const nameInput = {
1852
+ scope: ctx.identity.scope,
1853
+ stage: ctx.stage,
1854
+ id: input.name
1855
+ };
1856
+ const located = await ensureBucketName(bucketCtx, stageClients, input.id, require_workspace.bucketName(nameInput));
1857
+ const clients = located.region === stageClients.region ? stageClients : await makeClients(ctx.credential, located.region);
1858
+ await ensureBucketSettings(bucketCtx, clients, {
1859
+ id: input.id,
1860
+ bucket: located.bucket,
1861
+ exists: located.exists,
1862
+ versioning: false,
1863
+ open: [],
1864
+ ...input.sesWrite ? { sesWrite: input.sesWrite } : {}
1865
+ });
1866
+ const user = await require_iam.ensureIamUser(bucketCtx, clients, {
1867
+ id: input.id,
1868
+ user: require_workspace.iamUserName(nameInput),
1869
+ policyName: require_workspace.IAM_POLICY_NAME,
1870
+ policy: require_iam.userPolicy(located.bucket, input.topicArn ? { eventsTopicArn: input.topicArn } : {}),
1871
+ describe: "this bucket only"
1872
+ });
1873
+ await require_iam.ensureAccessKey(bucketCtx, clients, {
1874
+ id: input.id,
1875
+ secret: require_iam.s3KeySecret(bucketCtx, clients, {
1876
+ bucket: located.bucket,
1877
+ urlKey: input.urlKey
1878
+ }),
1879
+ ...user
1880
+ });
1881
+ return {
1882
+ bucket: located.bucket,
1883
+ region: clients.region
1884
+ };
1885
+ }
1886
+ async function ensureBucketName(ctx, clients, id, good) {
1887
+ const { S3, s3, region } = clients;
1888
+ const key = `s3-bucket:${id}`;
1889
+ const record = ctx.state.record(key);
1890
+ const entry = (name, where) => ({
1891
+ key,
1892
+ type: "s3-bucket",
1893
+ data: {
1894
+ name,
1895
+ region: where
1896
+ }
1897
+ });
1898
+ /**
1899
+ * Whether this account holds `name`: yes, no, or someone else does. Read
1900
+ * by status — a `HEAD` has no body, so its error is named `Unknown` — and,
1901
+ * when S3 says the bucket is in another region, asked again there.
1902
+ */
1903
+ const probe = async (name) => {
1904
+ let head = await headBucket(S3, s3, name);
1905
+ if (!head.ok && head.region && head.region !== region && (head.status === 301 || head.status === 400)) {
1906
+ const there = await makeClients(ctx.credential, head.region);
1907
+ head = await headBucket(there.S3, there.s3, name);
1908
+ }
1909
+ if (head.ok) return "ours";
1910
+ if (head.status === 404) return "none";
1911
+ if (head.status === 403) return "taken";
1912
+ throw new require_workspace.BucketProbeFailed(name, describeAnswer(head));
1913
+ };
1914
+ /** Where the bucket is now — read, not assumed: it may be adopted. */
1915
+ const located = async (name, made) => ctx.dryRun && made === "created" ? region : bucketRegion(clients, name);
1916
+ const create = async (name) => {
1917
+ if (ctx.dryRun) {
1918
+ const found = await probe(name);
1919
+ if (found === "none") {
1920
+ await ctx.change({
1921
+ construct: id,
1922
+ resource: `bucket ${name}`,
1923
+ change: `create in ${region}`
1924
+ }, async () => {});
1925
+ return "created";
1926
+ }
1927
+ return found;
1928
+ }
1929
+ await ctx.state.pending(entry(name, region));
1930
+ try {
1931
+ await s3.send(new S3.CreateBucketCommand({
1932
+ Bucket: name,
1933
+ ...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
1934
+ }));
1935
+ } catch (error) {
1936
+ const code = errorName$1(error);
1937
+ if (code === "BucketAlreadyOwnedByYou") return "ours";
1938
+ if (code === "BucketAlreadyExists") return "taken";
1939
+ throw error;
1940
+ }
1941
+ await ctx.change({
1942
+ construct: id,
1943
+ resource: `bucket ${name}`,
1944
+ change: `create in ${region}`
1945
+ }, async () => {});
1946
+ return "created";
1947
+ };
1948
+ const adopt = async (name, where) => {
1949
+ const there = where === region ? clients : await makeClients(ctx.credential, where);
1950
+ const owner = (await readOr(() => there.s3.send(new there.S3.GetBucketTaggingCommand({ Bucket: name })), ["NoSuchTagSet", "NoSuchTagSetError"]))?.TagSet?.find((t) => t.Key === require_iam.TAG_PROJECT)?.Value;
1951
+ if (owner && owner !== ctx.identity.key) throw new require_workspace.BucketOwnedByAnotherProject(name, owner, ctx.identity.key);
1952
+ };
1953
+ if (record?.status === "ready" && record.id) {
1954
+ const found = await probe(record.id);
1955
+ if (found === "taken") throw new require_workspace.RecordedBucketUnreachable(id, record.id);
1956
+ const made = found === "ours" ? "ours" : await create(record.id);
1957
+ if (made === "taken") throw new require_workspace.RecordedBucketUnreachable(id, record.id);
1958
+ const where = await located(record.id, made);
1959
+ if (!ctx.dryRun) await ctx.state.ready(entry(record.id, where), record.id);
1960
+ return {
1961
+ bucket: record.id,
1962
+ exists: made === "ours",
1963
+ region: where
1964
+ };
1965
+ }
1966
+ const pending = record?.data?.name;
1967
+ const names = [
1968
+ ...typeof pending === "string" && pending !== good ? [pending] : [],
1969
+ good,
1970
+ ...Array.from({ length: 5 }, () => require_workspace.suffixedBucketName(good, require_workspace.randomSuffix()))
1971
+ ];
1972
+ const tried = [];
1973
+ for (const name of names) {
1974
+ tried.push(name);
1975
+ const made = await create(name);
1976
+ if (made === "taken") continue;
1977
+ const where = await located(name, made);
1978
+ if (made === "ours") await adopt(name, where);
1979
+ if (!ctx.dryRun) await ctx.state.ready(entry(name, where), name);
1980
+ if (name !== good) ctx.log(` '${good}' is taken by another account; '${id}' is '${name}', recorded in the stage's state`);
1981
+ return {
1982
+ bucket: name,
1983
+ exists: made === "ours",
1984
+ region: where
1985
+ };
1986
+ }
1987
+ throw new require_workspace.BucketNameUnavailable(id, tried.filter((n) => n !== pending));
1988
+ }
1989
+ /**
1990
+ * Tags, Block Public Access, encryption, policy, versioning, lifecycle and
1991
+ * CORS.
1992
+ */
1993
+ async function ensureBucketSettings(ctx, clients, input) {
1994
+ const { S3, s3 } = clients;
1995
+ const { id, bucket } = input;
1996
+ const Bucket = bucket;
1997
+ const fresh = ctx.dryRun && !input.exists;
1998
+ const read = async (fn, missing) => fresh ? void 0 : readOr(fn, missing);
1999
+ const set = (change, apply) => ctx.change({
2000
+ construct: id,
2001
+ resource: `bucket ${bucket}`,
2002
+ change
2003
+ }, () => apply().then(() => void 0));
2004
+ const tagged = await read(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket })), ["NoSuchTagSet", "NoSuchTagSetError"]);
2005
+ const ours = require_iam.identityTags(ctx, id);
2006
+ const others = (tagged?.TagSet ?? []).filter((t) => !ours.some((o) => o.Key === t.Key));
2007
+ if (ours.some((o) => !tagged?.TagSet?.some((t) => t.Key === o.Key && t.Value === o.Value))) await set("tag", () => s3.send(new S3.PutBucketTaggingCommand({
2008
+ Bucket,
2009
+ Tagging: { TagSet: [...others, ...ours].map((t) => ({
2010
+ Key: t.Key,
2011
+ Value: t.Value
2012
+ })) }
2013
+ })));
2014
+ const isOpen = input.open.length > 0 && !input.cdn;
2015
+ const block = require_iam.publicAccessBlock(isOpen);
2016
+ const ensureBlock = async () => {
2017
+ const now = (await read(() => s3.send(new S3.GetPublicAccessBlockCommand({ Bucket })), ["NoSuchPublicAccessBlockConfiguration"]))?.PublicAccessBlockConfiguration;
2018
+ 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({
2019
+ Bucket,
2020
+ PublicAccessBlockConfiguration: block
2021
+ })));
2022
+ };
2023
+ const policy = require_iam.bucketPolicy(bucket, input.open, {
2024
+ ...input.cdn ? { cdn: input.cdn } : {},
2025
+ ...input.sesWrite ? { sesWrite: input.sesWrite } : {}
2026
+ });
2027
+ const ensurePolicy = async () => {
2028
+ const current = await read(() => s3.send(new S3.GetBucketPolicyCommand({ Bucket })), ["NoSuchBucketPolicy"]);
2029
+ if (!(current?.Policy !== void 0 && require_iam.canonicalPolicy(JSON.parse(current.Policy)) === require_iam.canonicalPolicy(policy))) await set(isOpen ? `policy: TLS only, public read on ${input.open.join(", ")}` : input.cdn && input.open.length > 0 ? `policy: TLS only, CloudFront reads ${input.open.join(", ")}` : "policy: TLS only", () => s3.send(new S3.PutBucketPolicyCommand({
2030
+ Bucket,
2031
+ Policy: JSON.stringify(policy)
2032
+ })));
2033
+ };
2034
+ if (isOpen) {
2035
+ await ensureBlock();
2036
+ await ensurePolicy();
2037
+ } else {
2038
+ await ensurePolicy();
2039
+ await ensureBlock();
2040
+ }
2041
+ 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({
2042
+ Bucket,
2043
+ ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
2044
+ })));
2045
+ const status = (await read(() => s3.send(new S3.GetBucketVersioningCommand({ Bucket })), []))?.Status;
2046
+ if (input.versioning && status !== "Enabled") await set("enable versioning", () => s3.send(new S3.PutBucketVersioningCommand({
2047
+ Bucket,
2048
+ VersioningConfiguration: { Status: "Enabled" }
2049
+ })));
2050
+ else if (!input.versioning && status === "Enabled") await set("suspend versioning", () => s3.send(new S3.PutBucketVersioningCommand({
2051
+ Bucket,
2052
+ VersioningConfiguration: { Status: "Suspended" }
2053
+ })));
2054
+ const lifecycle = await read(() => s3.send(new S3.GetBucketLifecycleConfigurationCommand({ Bucket })), ["NoSuchLifecycleConfiguration"]);
2055
+ const merge = require_stack.mergeLifecycle(lifecycle?.Rules, input.expire);
2056
+ if (merge.changed) await set(merge.describe, () => merge.rules.length > 0 ? s3.send(new S3.PutBucketLifecycleConfigurationCommand({
2057
+ Bucket,
2058
+ LifecycleConfiguration: { Rules: merge.rules }
2059
+ })) : s3.send(new S3.DeleteBucketLifecycleCommand({ Bucket })));
2060
+ const { origins, unresolved } = bucketOrigins({
2061
+ workspace: ctx.workspace,
2062
+ manifest: ctx.manifest,
2063
+ stage: ctx.stage,
2064
+ bucket: id
2065
+ });
2066
+ 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`);
2067
+ if (origins.length === 0) return;
2068
+ const rule = require_iam.corsRule(origins);
2069
+ const cors = await read(() => s3.send(new S3.GetBucketCorsCommand({ Bucket })), ["NoSuchCORSConfiguration"]);
2070
+ if (!(cors?.CORSRules?.length === 1 && canonicalCors(cors.CORSRules[0]) === canonicalCors(rule))) await set(`CORS for ${origins.join(", ")}`, () => s3.send(new S3.PutBucketCorsCommand({
2071
+ Bucket,
2072
+ CORSConfiguration: { CORSRules: [rule] }
2073
+ })));
2074
+ }
2075
+ function canonicalCors(rule) {
2076
+ const sorted = (list) => [...list ?? []].sort();
2077
+ return JSON.stringify({
2078
+ AllowedMethods: sorted(rule.AllowedMethods),
2079
+ AllowedOrigins: sorted(rule.AllowedOrigins),
2080
+ AllowedHeaders: sorted(rule.AllowedHeaders),
2081
+ ExposeHeaders: sorted(rule.ExposeHeaders),
2082
+ MaxAgeSeconds: rule.MaxAgeSeconds ?? null
2083
+ });
2084
+ }
2085
+ /**
2086
+ * Each provisioned bucket answers `HeadBucket` to the key in the stage's
2087
+ * secrets — the one the apps will use. A bucket whose URL carries no key is
2088
+ * not one this provider wrote, and the deploy's own check covers a URL that
2089
+ * is missing.
2090
+ *
2091
+ * A failure is read by its status, never its name — a `HEAD` has no body,
2092
+ * so SDK v3 calls a 301, 400 or 403 `Unknown` — and the message carries
2093
+ * everything S3 said: status, error, region, request ids.
2094
+ *
2095
+ * @throws {BucketRegionMismatch} the bucket is in another region than its URL says
2096
+ * @throws {ProvisionedBucketUnreachable}
2097
+ */
2098
+ async function verifyS3(ctx) {
2099
+ const S3 = await import("@aws-sdk/client-s3");
2100
+ for (const { id } of bucketConstructs(ctx.manifest)) {
2101
+ const urlKey = (0, _geekmidas_manifest.providedKeyFor)(id, "objects", "connectionString");
2102
+ const url = ctx.secrets[urlKey];
2103
+ if (url === void 0) continue;
2104
+ const address = _geekmidas_storage_s3_url.parse(url);
2105
+ if (!address.accessKeyId || !address.secretAccessKey) continue;
2106
+ const asked = address.region ?? ctx.config.region ?? "us-east-1";
2107
+ const client = new S3.S3Client({
2108
+ region: asked,
2109
+ credentials: {
2110
+ accessKeyId: address.accessKeyId,
2111
+ secretAccessKey: address.secretAccessKey
2112
+ },
2113
+ ...address.endpoint ? { endpoint: address.endpoint } : {},
2114
+ ...address.forcePathStyle ? { forcePathStyle: true } : {}
2115
+ });
2116
+ try {
2117
+ const issuedAt = require_iam.issuedJustNow(ctx.resources, id, address.accessKeyId);
2118
+ const { answer: head, waited } = await require_iam.whileKeyIsNew(await headBucket(S3, client, address.bucket), {
2119
+ issuedAt,
2120
+ refused: (answer) => !answer.ok && answer.status === 403,
2121
+ ask: () => headBucket(S3, client, address.bucket),
2122
+ onWait: () => ctx.log?.(` ${id}: waiting for the new key ${address.accessKeyId} to become active…`)
2123
+ });
2124
+ if (head.ok) continue;
2125
+ const fail = (reason) => new require_workspace.ProvisionedBucketUnreachable(id, address.bucket, ctx.stage, reason);
2126
+ const said = describeAnswer(head);
2127
+ if (head.status === 301 || head.status === 400 && head.region && head.region !== asked) {
2128
+ let where = head.region;
2129
+ let located = "";
2130
+ if (!where) {
2131
+ const location = await bucketLocation(S3, client, address.bucket);
2132
+ if ("region" in location) where = location.region;
2133
+ else located = `; GetBucketLocation answered ${describeAnswer(location.failed)}`;
2134
+ }
2135
+ if (where && where !== asked) throw new require_workspace.BucketRegionMismatch(id, address.bucket, ctx.stage, urlKey, where, address.region, asked, said);
2136
+ throw fail(`S3 redirected the request (${said}${located})`);
2137
+ }
2138
+ if (head.status === 404) throw fail(`it does not exist (${said})`);
2139
+ if (head.status === 403) throw fail(`the key is refused — AccessDenied, or an invalid or not-yet-active key (${said})` + (issuedAt ? `. The key was issued at ${issuedAt} by this deploy, and IAM keys take seconds to become usable: it was still refused after waiting ${Math.round(waited / 1e3)}s` : ""));
2140
+ throw fail(said);
2141
+ } finally {
2142
+ client.destroy();
2143
+ }
2144
+ }
2145
+ }
2146
+ const s3Provider = {
2147
+ kind: "objects",
2148
+ name: "s3",
2149
+ check: require_workspace.checkS3Config,
2150
+ provisioning: require_workspace.S3_PROVISIONING,
2151
+ credentials: require_stack.awsProvisioningCredentials,
2152
+ runtimeKeys(manifest) {
2153
+ const watched = bucketWatchers(manifest);
2154
+ return bucketConstructs(manifest).flatMap((b) => [
2155
+ (0, _geekmidas_manifest.providedKeyFor)(b.id, "objects", "connectionString"),
2156
+ ...watched.has(b.id) ? [(0, _geekmidas_manifest.providedKeyFor)(b.id, "objects", "eventsConnectionString")] : [],
2157
+ ...b.servers.map((s) => (0, _geekmidas_manifest.providedKeyFor)(s.id, "file-server", "url"))
2158
+ ]);
2159
+ },
2160
+ ensure: ensureS3,
2161
+ verify: verifyS3
2162
+ };
2163
+ //#endregion
2164
+ //#region src/providers/ses/index.ts
2165
+ /**
2166
+ * The `ses` provider: what receives an inbox's mail on a deployed stage.
2167
+ *
2168
+ * `deploy.inbox.<stage> = { provider: 'ses', region? }` has the deploy create,
2169
+ * for each `Inbox`:
2170
+ *
2171
+ * - **its own bucket** — never one the stack or `deploy.objects` runs — by
2172
+ * the steps every bucket of the stage takes (`ensureOwnedBucket`), with SES
2173
+ * allowed to write under `messages/` and an IAM user of its own whose key
2174
+ * is the inbox's `<ID>_URL`;
2175
+ * - **its topic** on SNS, publishable by SES alone, whose `sns://` address —
2176
+ * signed by the same key — is the topic's connection string. That key may
2177
+ * only confirm a subscription: the deploy's push subscriptions for a topic
2178
+ * on SNS (`topicPushes`) subscribe each inbox subscriber at its worker's
2179
+ * route, unfiltered, with the deploy's own credentials, as a bucket's are;
2180
+ * - **the stage's domain as an SES identity**, verified through Easy DKIM's
2181
+ * CNAMEs, and **MX records** pointing the domain — or every subdomain of it,
2182
+ * with `subdomains: true` — at the region's inbound endpoint, both through
2183
+ * the stage's DNS;
2184
+ * - **a receipt rule** in the region's *active* rule set: the inbox's
2185
+ * recipients, stored under `messages/` and announced on its topic. Never a
2186
+ * new set made active over another — only one is active per region, and
2187
+ * switching would stop every other stage's and app's rules. A set is made
2188
+ * active only where none is.
2189
+ *
2190
+ * A removed inbox's rule is deleted on the next deploy, by its name; nothing
2191
+ * else this provider did not make is touched.
2192
+ */
2193
+ /**
2194
+ * The regions SES receives mail in, each at `inbound-smtp.<region>.amazonaws.com`
2195
+ * — the AWS General Reference's "Email Receiving endpoints".
2196
+ */
2197
+ const SES_RECEIVING_REGIONS = [
2198
+ "us-east-1",
2199
+ "us-east-2",
2200
+ "us-west-1",
2201
+ "us-west-2",
2202
+ "af-south-1",
2203
+ "ap-southeast-3",
2204
+ "ap-south-1",
2205
+ "ap-northeast-3",
2206
+ "ap-northeast-2",
2207
+ "ap-southeast-1",
2208
+ "ap-southeast-2",
2209
+ "ap-northeast-1",
2210
+ "ca-central-1",
2211
+ "eu-central-1",
2212
+ "eu-west-1",
2213
+ "eu-west-2",
2214
+ "eu-south-1",
2215
+ "eu-west-3",
2216
+ "eu-north-1",
2217
+ "il-central-1",
2218
+ "me-south-1",
2219
+ "sa-east-1"
2220
+ ];
2221
+ /** Where mail for a domain is delivered in `region`: its MX target. */
2222
+ function inboundEndpoint(region) {
2223
+ return `inbound-smtp.${region}.amazonaws.com`;
2224
+ }
2225
+ /** Every inbox in the manifest. */
2226
+ function inboxConstructs(manifest) {
2227
+ return Object.values(manifest).filter((d) => d.kind === "inbox").sort((a, b) => a.id.localeCompare(b.id));
2228
+ }
2229
+ /** The name an inbox's receipt rule has: the prefix it is found by, and its id. */
2230
+ function receiptRuleName(scope, stage, inbox) {
2231
+ return `${rulePrefix(scope, stage)}${require_workspace.appKey(inbox)}`.slice(0, 64);
2232
+ }
2233
+ /** What every rule this stage made is named with. */
2234
+ function rulePrefix(scope, stage) {
2235
+ return `gkm-${scope}-${stage}-`.replace(/[^A-Za-z0-9_.-]/g, "-");
2236
+ }
2237
+ /** The topic SES announces an inbox's mail on: publishable by SES, from this account. */
2238
+ function receiptTopicPolicy(topicArn, account) {
2239
+ return {
2240
+ Version: "2012-10-17",
2241
+ Statement: [{
2242
+ Sid: "GkmSesPublishes",
2243
+ Effect: "Allow",
2244
+ Principal: { Service: "ses.amazonaws.com" },
2245
+ Action: "sns:Publish",
2246
+ Resource: topicArn,
2247
+ Condition: { StringEquals: { "aws:SourceAccount": account } }
2248
+ }]
2249
+ };
2250
+ }
2251
+ const defaultSesClients = async (credential, region) => {
2252
+ const SES = await import("@aws-sdk/client-ses");
2253
+ const config = await require_stack.awsClientConfig(credential, region);
2254
+ const endpoint = require_stack.awsEndpoint(process.env, "SES");
2255
+ return {
2256
+ SES,
2257
+ ses: new SES.SESClient({
2258
+ ...config,
2259
+ ...endpoint ? { endpoint } : {}
2260
+ })
2261
+ };
2262
+ };
2263
+ let makeSesClients = defaultSesClients;
2264
+ /** The stage's SES, through the factory a test may replace. */
2265
+ function sesClients(credential, region) {
2266
+ return makeSesClients(credential, region);
2267
+ }
2268
+ function errorName(error) {
2269
+ const e = error;
2270
+ return e?.name ?? e?.Code ?? e?.code ?? "";
2271
+ }
2272
+ /** The stage's domain, which every inbox receives on. */
2273
+ function stageDomain(ctx) {
2274
+ const domain = ctx.workspace.domains?.[ctx.stage];
2275
+ if (!domain) throw new require_credentials$1.NoDomainForStage(ctx.stage);
2276
+ return domain;
2277
+ }
2278
+ async function ensureSes(ctx) {
2279
+ const region = require_workspace.s3Region(ctx);
2280
+ if (!SES_RECEIVING_REGIONS.includes(region)) throw new require_workspace.SesReceivingUnsupported(ctx.stage, region, SES_RECEIVING_REGIONS);
2281
+ const inboxes = inboxConstructs(ctx.manifest);
2282
+ const { SES, ses } = await makeSesClients(ctx.credential, region);
2283
+ try {
2284
+ const ruleSet = await activeRuleSet(ctx, {
2285
+ SES,
2286
+ ses
2287
+ }, inboxes.length > 0);
2288
+ if (inboxes.length > 0) {
2289
+ const domain = stageDomain(ctx);
2290
+ await ensureIdentity$1(ctx, {
2291
+ SES,
2292
+ ses
2293
+ }, domain);
2294
+ const events = await eventsClients(ctx.credential, region);
2295
+ try {
2296
+ for (const inbox of inboxes) await ensureInbox(ctx, {
2297
+ SES,
2298
+ ses
2299
+ }, events, {
2300
+ inbox,
2301
+ domain,
2302
+ region,
2303
+ ruleSet
2304
+ });
2305
+ } finally {
2306
+ events.sns.destroy();
2307
+ events.sqs.destroy();
2308
+ }
2309
+ await ensureMx(ctx, inboxes, domain, region);
2310
+ }
2311
+ if (ruleSet) await retireRules(ctx, {
2312
+ SES,
2313
+ ses
2314
+ }, ruleSet, inboxes);
2315
+ } finally {
2316
+ ses.destroy();
2317
+ }
2318
+ }
2319
+ /**
2320
+ * The region's active rule set. Made — and made active — only where none is
2321
+ * active and an inbox needs one: activating a set deactivates whichever was.
2322
+ */
2323
+ async function activeRuleSet(ctx, { SES, ses }, needed) {
2324
+ const name = (await ses.send(new SES.DescribeActiveReceiptRuleSetCommand({}))).Metadata?.Name;
2325
+ if (name || !needed) return name;
2326
+ await ctx.change({
2327
+ construct: "inbox",
2328
+ resource: `SES receipt rule set gkm`,
2329
+ change: "create and make active — the region has none"
2330
+ }, async () => {
2331
+ try {
2332
+ await ses.send(new SES.CreateReceiptRuleSetCommand({ RuleSetName: "gkm" }));
2333
+ } catch (error) {
2334
+ if (errorName(error) !== "AlreadyExistsException") throw error;
2335
+ }
2336
+ await ses.send(new SES.SetActiveReceiptRuleSetCommand({ RuleSetName: "gkm" }));
2337
+ });
2338
+ return "gkm";
2339
+ }
2340
+ /**
2341
+ * The stage's domain as an SES identity, verified by Easy DKIM: its three
2342
+ * CNAMEs, through the stage's DNS. Receiving requires a verified domain.
2343
+ */
2344
+ async function ensureIdentity$1(ctx, { SES, ses }, domain) {
2345
+ let tokens = [];
2346
+ await ctx.change({
2347
+ construct: "inbox",
2348
+ resource: `SES identity ${domain}`,
2349
+ change: "verify with DKIM"
2350
+ }, async () => {
2351
+ tokens = (await ses.send(new SES.VerifyDomainDkimCommand({ Domain: domain }))).DkimTokens ?? [];
2352
+ });
2353
+ if (tokens.length === 0) return;
2354
+ await ctx.writeDns(tokens.map((token) => ({
2355
+ host: `${token}._domainkey.${domain}`,
2356
+ type: "CNAME",
2357
+ value: `${token}.dkim.amazonses.com`
2358
+ })));
2359
+ }
2360
+ /** One inbox: its bucket, its topic and their keys, and its receipt rule. */
2361
+ async function ensureInbox(ctx, { SES, ses }, events, input) {
2362
+ const { inbox, domain, region, ruleSet } = input;
2363
+ const name = require_workspace.inboxBucketId(inbox.id);
2364
+ const urlKey = (0, _geekmidas_manifest.providedKeyFor)(inbox.id, inbox.kind, "url");
2365
+ const topicArn = await ensureTopic(ctx, events, {
2366
+ id: inbox.id,
2367
+ topicName: require_workspace.inboxTopicName(ctx.identity.scope, ctx.stage, inbox.id),
2368
+ publisher: "SES",
2369
+ policy: (arn) => receiptTopicPolicy(arn, events.account)
2370
+ });
2371
+ const { bucket } = await ensureOwnedBucket(ctx, {
2372
+ id: inbox.id,
2373
+ name,
2374
+ urlKey,
2375
+ sesWrite: {
2376
+ prefix: _geekmidas_manifest.INBOX_MESSAGES_PREFIX,
2377
+ account: events.account
2378
+ },
2379
+ topicArn
2380
+ });
2381
+ await ensureEventsKey(ctx, {
2382
+ id: inbox.id,
2383
+ topicArn,
2384
+ region,
2385
+ key: (0, _geekmidas_manifest.providedKeyFor)(inbox.topic, "topic", "publisherConnectionString"),
2386
+ urlKey
2387
+ });
2388
+ const rule = {
2389
+ Name: receiptRuleName(ctx.identity.scope, ctx.stage, inbox.id),
2390
+ Enabled: true,
2391
+ TlsPolicy: "Optional",
2392
+ ScanEnabled: true,
2393
+ Recipients: (0, _geekmidas_manifest.receiptRecipients)(inbox, domain),
2394
+ Actions: [{ S3Action: {
2395
+ BucketName: bucket,
2396
+ ObjectKeyPrefix: _geekmidas_manifest.INBOX_MESSAGES_PREFIX,
2397
+ TopicArn: topicArn
2398
+ } }]
2399
+ };
2400
+ const current = await ses.send(new SES.DescribeReceiptRuleCommand({
2401
+ RuleSetName: ruleSet,
2402
+ RuleName: rule.Name
2403
+ })).then((found) => found.Rule, (error) => {
2404
+ if (errorName(error) === "RuleDoesNotExistException") return void 0;
2405
+ throw error;
2406
+ });
2407
+ const entry = {
2408
+ key: `ses-receipt-rule:${inbox.id}`,
2409
+ type: "ses-receipt-rule"
2410
+ };
2411
+ if (current && sameRule(current, rule)) {
2412
+ await ctx.state.ready(entry, rule.Name);
2413
+ return;
2414
+ }
2415
+ await ctx.change({
2416
+ construct: inbox.id,
2417
+ resource: `SES receipt rule ${rule.Name}`,
2418
+ change: current ? `receive at ${rule.Recipients.join(", ")}` : `create, receiving at ${rule.Recipients.join(", ")}`
2419
+ }, async () => {
2420
+ await ctx.state.pending(entry);
2421
+ await ses.send(current ? new SES.UpdateReceiptRuleCommand({
2422
+ RuleSetName: ruleSet,
2423
+ Rule: rule
2424
+ }) : new SES.CreateReceiptRuleCommand({
2425
+ RuleSetName: ruleSet,
2426
+ Rule: rule
2427
+ }));
2428
+ await ctx.state.ready(entry, rule.Name);
2429
+ });
2430
+ }
2431
+ function sameRule(current, wanted) {
2432
+ const s3 = current.Actions?.[0]?.S3Action;
2433
+ const want = wanted.Actions[0].S3Action;
2434
+ return current.Enabled === wanted.Enabled && current.TlsPolicy === wanted.TlsPolicy && current.ScanEnabled === wanted.ScanEnabled && current.Actions?.length === 1 && s3?.BucketName === want.BucketName && s3?.ObjectKeyPrefix === want.ObjectKeyPrefix && s3?.TopicArn === want.TopicArn && [...current.Recipients ?? []].sort().join() === [...wanted.Recipients].sort().join();
2435
+ }
2436
+ /**
2437
+ * MX records for the stage's domain — and, for an inbox on its tenants'
2438
+ * subdomains, for every subdomain — at the region's inbound endpoint.
2439
+ */
2440
+ async function ensureMx(ctx, inboxes, domain, region) {
2441
+ const hosts = /* @__PURE__ */ new Set();
2442
+ for (const inbox of inboxes) hosts.add(inbox.subdomains ? `*.${domain}` : domain);
2443
+ await ctx.writeDns([...hosts].sort().map((host) => ({
2444
+ host,
2445
+ type: "MX",
2446
+ value: inboundEndpoint(region),
2447
+ priority: 10
2448
+ })));
2449
+ }
2450
+ /** Delete the rules this stage made for inboxes no longer declared — only those. */
2451
+ async function retireRules(ctx, { SES, ses }, ruleSet, inboxes) {
2452
+ const prefix = rulePrefix(ctx.identity.scope, ctx.stage);
2453
+ const kept = new Set(inboxes.map((inbox) => receiptRuleName(ctx.identity.scope, ctx.stage, inbox.id)));
2454
+ const set = await ses.send(new SES.DescribeReceiptRuleSetCommand({ RuleSetName: ruleSet }));
2455
+ for (const rule of set.Rules ?? []) {
2456
+ if (!rule.Name?.startsWith(prefix) || kept.has(rule.Name)) continue;
2457
+ await ctx.change({
2458
+ construct: "inbox",
2459
+ resource: `SES receipt rule ${rule.Name}`,
2460
+ change: "delete — its inbox is no longer declared"
2461
+ }, async () => {
2462
+ await ses.send(new SES.DeleteReceiptRuleCommand({
2463
+ RuleSetName: ruleSet,
2464
+ RuleName: rule.Name
2465
+ }));
2466
+ });
2467
+ }
2468
+ }
2469
+ /**
2470
+ * The cheap check every deploy runs: the region receives mail, the stage has
2471
+ * a domain, and each inbox's keys are in the stage's secrets.
2472
+ */
2473
+ async function verifySes(ctx) {
2474
+ const region = require_workspace.s3Region(ctx);
2475
+ if (!SES_RECEIVING_REGIONS.includes(region)) throw new require_workspace.SesReceivingUnsupported(ctx.stage, region, SES_RECEIVING_REGIONS);
2476
+ const inboxes = inboxConstructs(ctx.manifest);
2477
+ if (inboxes.length === 0) return;
2478
+ stageDomain(ctx);
2479
+ for (const inbox of inboxes) {
2480
+ const missing = [(0, _geekmidas_manifest.providedKeyFor)(inbox.id, inbox.kind, "url"), (0, _geekmidas_manifest.providedKeyFor)(inbox.topic, "topic", "publisherConnectionString")].filter((key) => ctx.secrets[key] === void 0);
2481
+ if (missing.length > 0) throw new require_workspace.InboxNotProvisioned(ctx.stage, inbox.id, missing);
2482
+ }
2483
+ }
2484
+ const sesProvider = {
2485
+ kind: "inbox",
2486
+ name: "ses",
2487
+ check: require_workspace.checkSesConfig,
2488
+ provisioning: require_workspace.SES_PROVISIONING,
2489
+ credentials: require_stack.awsProvisioningCredentials,
2490
+ runtimeKeys(manifest) {
2491
+ return inboxConstructs(manifest).flatMap((inbox) => [(0, _geekmidas_manifest.providedKeyFor)(inbox.id, inbox.kind, "url"), (0, _geekmidas_manifest.providedKeyFor)(inbox.topic, "topic", "publisherConnectionString")]);
2492
+ },
2493
+ ensure: ensureSes,
2494
+ verify: verifySes
2495
+ };
2496
+ //#endregion
2497
+ //#region src/providers/ses/smtp.ts
2498
+ /**
2499
+ * SES's SMTP interface: where it is, and the password an IAM access key signs
2500
+ * in with there.
2501
+ *
2502
+ * SES issues IAM credentials, not SMTP ones. The SMTP password is derived
2503
+ * from the key's secret and the region, by SigV4's key derivation over a
2504
+ * fixed date and the message `SendRawEmail` — the algorithm the SES
2505
+ * Developer Guide gives ("Obtaining Amazon SES SMTP credentials"). A
2506
+ * password works in that region only.
2507
+ */
2508
+ /** The SMTP endpoint of `region`. */
2509
+ function smtpHost(region) {
2510
+ return `email-smtp.${region}.amazonaws.com`;
2511
+ }
2512
+ /** The SMTP password for an access key's secret, in `region`. */
2513
+ function smtpPassword(secretAccessKey, region) {
2514
+ const sign = (key, message) => (0, node_crypto.createHmac)("sha256", key).update(message, "utf8").digest();
2515
+ let signature = sign(`AWS4${secretAccessKey}`, "11111111");
2516
+ for (const part of [
2517
+ region,
2518
+ "ses",
2519
+ "aws4_request",
2520
+ "SendRawEmail"
2521
+ ]) signature = sign(signature, part);
2522
+ return Buffer.concat([Buffer.from([4]), signature]).toString("base64");
2523
+ }
2524
+ /** `smtp://<key id>:<smtp password>@email-smtp.<region>.amazonaws.com:587`. */
2525
+ function smtpUrl(accessKeyId, secretAccessKey, region) {
2526
+ return `smtp://${encodeURIComponent(accessKeyId)}:${encodeURIComponent(smtpPassword(secretAccessKey, region))}@${smtpHost(region)}:587`;
2527
+ }
2528
+ /** The user an `smtp://` URL signs in as, whatever its host. */
2529
+ function smtpUser(value) {
2530
+ try {
2531
+ const url = new URL(value);
2532
+ return url.username ? decodeURIComponent(url.username) : void 0;
2533
+ } catch {
2534
+ return;
2535
+ }
2536
+ }
2537
+ /**
2538
+ * A mail construct's URL as a key's secret. A URL on another region's
2539
+ * endpoint holds no key this region can use — its password was derived for
2540
+ * that region — so it counts as holding none, and a new key is issued.
2541
+ */
2542
+ function smtpKeySecret(urlKey, region) {
2543
+ return {
2544
+ key: urlKey,
2545
+ keyIdOf(value) {
2546
+ try {
2547
+ return new URL(value).hostname === smtpHost(region) ? smtpUser(value) : void 0;
2548
+ } catch {
2549
+ return;
2550
+ }
2551
+ },
2552
+ value: (accessKeyId, secretAccessKey) => smtpUrl(accessKeyId, secretAccessKey, region)
2553
+ };
2554
+ }
2555
+ //#endregion
2556
+ //#region src/providers/ses/email.ts
2557
+ /**
2558
+ * The `ses` provider for mail: what sends an `Email` construct's mail on a
2559
+ * deployed stage.
2560
+ *
2561
+ * `deploy.email.<stage> = { provider: 'ses', region?, from? }` has the deploy
2562
+ * create, in the stage's AWS account:
2563
+ *
2564
+ * - **the sender's domain as an SES identity**, verified through Easy DKIM's
2565
+ * CNAMEs written through the stage's DNS — the same identity an inbox on
2566
+ * that domain uses: SES has one per domain, and neither provider deletes it;
2567
+ * - for each mail construct, **an IAM user** allowed `ses:SendRawEmail` from
2568
+ * that identity and nothing else, and **its access key**, written into the
2569
+ * stage's secrets as `<ID>_URL` — `smtp://<key id>:<smtp password>@
2570
+ * email-smtp.<region>.amazonaws.com:587`, the password derived from the key;
2571
+ * - **`<ID>_FROM`**: `from`, else what the secrets hold, else the construct's
2572
+ * local part (`noreply` without one) at the stage's domain.
2573
+ *
2574
+ * A `<ID>_URL` the stage's secrets already hold, and this provider did not
2575
+ * write, wins: the construct sends with it and nothing is created for it — an
2576
+ * identity that already has sending credentials is not given a second set.
2577
+ * Moving an existing stack onto compose stays a `secrets:import`.
2578
+ *
2579
+ * `--rotate-keys` issues each user a successor key, and with it a new
2580
+ * password, as every other provider's keys are rotated.
2581
+ */
2582
+ /** The inline policy each sending user is given. */
2583
+ const SEND_POLICY_NAME = "gkm-email";
2584
+ /**
2585
+ * The most a sandboxed account sends in a day. An account with no more is
2586
+ * taken to be in the sandbox, where SES delivers only to verified addresses.
2587
+ */
2588
+ const SANDBOX_DAILY_QUOTA = 200;
2589
+ /** Every mail construct in the manifest. */
2590
+ function emailConstructs(manifest) {
2591
+ return Object.values(manifest).filter((d) => d.kind === "email").sort((a, b) => a.id.localeCompare(b.id));
2592
+ }
2593
+ /** What a sending user may do: send as `identityArn`, and nothing else. */
2594
+ function sendPolicy(identityArn) {
2595
+ return {
2596
+ Version: "2012-10-17",
2597
+ Statement: [{
2598
+ Sid: "GkmSendEmail",
2599
+ Effect: "Allow",
2600
+ Action: "ses:SendRawEmail",
2601
+ Resource: identityArn
2602
+ }]
2603
+ };
2604
+ }
2605
+ /** The ARN of a domain's SES identity. */
2606
+ function identityArn(region, account, domain) {
2607
+ return `arn:aws:ses:${region}:${account}:identity/${domain}`;
2608
+ }
2609
+ /**
2610
+ * Whether the stage's secrets hold a URL for `email` that this provider did
2611
+ * not write — one set by hand, or imported — which it then leaves alone.
2612
+ */
2613
+ function urlSetElsewhere(ctx, email) {
2614
+ const given = ctx.secrets[(0, _geekmidas_manifest.providedKeyFor)(email, "email", "url")];
2615
+ if (given === void 0) return false;
2616
+ const record = ctx.state.record(`iam-access-key:${email}`);
2617
+ if (!record) return true;
2618
+ const user = smtpUser(given);
2619
+ return user !== record.id && user !== record.data?.previous;
2620
+ }
2621
+ /** The state entry of the address gkm last wrote as `email`'s sender. */
2622
+ function senderEntry(email) {
2623
+ return {
2624
+ key: `email-from:${email}`,
2625
+ type: "email-from"
2626
+ };
2627
+ }
2628
+ /**
2629
+ * The address `email` sends from: `from`; else one the stage's secrets hold
2630
+ * that gkm did not write — set by hand, or imported; else the construct's
2631
+ * local part at the stage's domain (`senderAddress`). An address gkm wrote
2632
+ * follows both: after a change of `domains.<stage>` or of the construct's
2633
+ * `from`, mail is sent as the new one.
2634
+ *
2635
+ * @returns the address, and whether it is gkm's to write and record
2636
+ * @throws {EmailSenderUnknown} with none of them
2637
+ */
2638
+ function senderOf(ctx, email) {
2639
+ if (ctx.config.from) return {
2640
+ address: ctx.config.from,
2641
+ ours: true
2642
+ };
2643
+ const held = ctx.secrets[(0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "from")];
2644
+ const wrote = ctx.state.record(senderEntry(email.id).key)?.id;
2645
+ const domain = ctx.workspace.domains?.[ctx.stage];
2646
+ const fallback = domain ? (0, _geekmidas_manifest.senderAddress)(email, domain) : void 0;
2647
+ const adopted = [fallback, domain && (0, _geekmidas_manifest.senderAddress)({}, domain)];
2648
+ if (held && held !== wrote && !adopted.includes(held)) return {
2649
+ address: held,
2650
+ ours: false
2651
+ };
2652
+ if (fallback) return {
2653
+ address: fallback,
2654
+ ours: true
2655
+ };
2656
+ if (held) return {
2657
+ address: held,
2658
+ ours: false
2659
+ };
2660
+ throw new require_workspace.EmailSenderUnknown(ctx.stage);
2661
+ }
2662
+ /** The domain of an address — `noreply@x.com` or `Acme <noreply@x.com>`. */
2663
+ function domainOf(address) {
2664
+ return address.slice(address.lastIndexOf("@") + 1).replace(/>\s*$/, "").trim().toLowerCase();
2665
+ }
2666
+ async function iamClients(credential, region) {
2667
+ const IAM = await import("@aws-sdk/client-iam");
2668
+ const { STSClient } = await import("@aws-sdk/client-sts");
2669
+ const config = await require_stack.awsClientConfig(credential, region);
2670
+ const stsEndpoint = require_stack.awsEndpoint(process.env, "STS");
2671
+ return {
2672
+ IAM,
2673
+ iam: new IAM.IAMClient(config),
2674
+ sts: new STSClient({
2675
+ ...config,
2676
+ ...stsEndpoint ? { endpoint: stsEndpoint } : {}
2677
+ }),
2678
+ region
2679
+ };
2680
+ }
2681
+ async function ensureSesEmail(ctx) {
2682
+ const owned = emailConstructs(ctx.manifest).filter((email) => {
2683
+ if (!urlSetElsewhere(ctx, email.id)) return true;
2684
+ ctx.log(` ${email.id}: ${(0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "url")} is set in the stage's secrets — it sends with that, and nothing is created for it`);
2685
+ return false;
2686
+ });
2687
+ if (owned.length === 0) return;
2688
+ const region = require_workspace.s3Region(ctx);
2689
+ const senders = new Map(owned.map((e) => [e.id, senderOf(ctx, e)]));
2690
+ const domains = [...new Set([...senders.values()].map((s) => domainOf(s.address)))].sort();
2691
+ const ses = await sesClients(ctx.credential, region);
2692
+ const clients = await iamClients(ctx.credential, region);
2693
+ try {
2694
+ const account = await require_projectBucket.callerAccountId(clients.sts);
2695
+ for (const domain of domains) await ensureIdentity(ctx, ses, domain);
2696
+ await noteSandbox(ctx, ses, region);
2697
+ for (const email of owned) {
2698
+ const { address: from, ours } = senders.get(email.id);
2699
+ const domain = domainOf(from);
2700
+ const user = await require_iam.ensureIamUser(ctx, clients, {
2701
+ id: email.id,
2702
+ user: require_workspace.emailUserName(ctx.identity.scope, ctx.stage, email.id),
2703
+ policyName: SEND_POLICY_NAME,
2704
+ policy: sendPolicy(identityArn(region, account, domain)),
2705
+ describe: `send as ${domain} only`
2706
+ });
2707
+ await require_iam.ensureAccessKey(ctx, clients, {
2708
+ id: email.id,
2709
+ secret: smtpKeySecret((0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "url"), region),
2710
+ ...user
2711
+ });
2712
+ const fromKey = (0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "from");
2713
+ if (ctx.secrets[fromKey] !== from) await ctx.change({
2714
+ construct: email.id,
2715
+ resource: fromKey,
2716
+ change: `set to ${from}`
2717
+ }, () => ctx.writeSecrets({ [fromKey]: from }));
2718
+ if (ours && ctx.state.record(senderEntry(email.id).key)?.id !== from) await ctx.state.ready(senderEntry(email.id), from);
2719
+ }
2720
+ } finally {
2721
+ ses.ses.destroy();
2722
+ clients.iam.destroy();
2723
+ clients.sts.destroy();
2724
+ }
2725
+ }
2726
+ /**
2727
+ * The domain as an SES identity that signs what it sends with Easy DKIM: its
2728
+ * three CNAMEs, through the stage's DNS.
2729
+ *
2730
+ * The check is DKIM's own status, not the domain's: a domain verified by its
2731
+ * older TXT record is verified, and sends unsigned until DKIM is set up on it.
2732
+ * One whose DKIM is verified is left as it is, signing turned back on if it
2733
+ * was turned off; any other — new, verified only by TXT, or created by
2734
+ * another stack and never finished — is asked for its tokens, which SES
2735
+ * answers without making a second identity.
2736
+ */
2737
+ async function ensureIdentity(ctx, { SES, ses }, domain) {
2738
+ const { DkimAttributes } = await ses.send(new SES.GetIdentityDkimAttributesCommand({ Identities: [domain] }));
2739
+ const dkim = DkimAttributes?.[domain];
2740
+ const verified = dkim?.DkimVerificationStatus === "Success";
2741
+ let tokens = dkim?.DkimTokens ?? [];
2742
+ if (verified && !dkim.DkimEnabled) await ctx.change({
2743
+ construct: "email",
2744
+ resource: `SES identity ${domain}`,
2745
+ change: "turn DKIM signing back on"
2746
+ }, async () => {
2747
+ await ses.send(new SES.SetIdentityDkimEnabledCommand({
2748
+ Identity: domain,
2749
+ DkimEnabled: true
2750
+ }));
2751
+ });
2752
+ if (!verified) await ctx.change({
2753
+ construct: "email",
2754
+ resource: `SES identity ${domain}`,
2755
+ change: "verify with DKIM"
2756
+ }, async () => {
2757
+ tokens = (await ses.send(new SES.VerifyDomainDkimCommand({ Domain: domain }))).DkimTokens ?? tokens;
2758
+ });
2759
+ if (tokens.length === 0) return;
2760
+ await ctx.writeDns(tokens.map((token) => ({
2761
+ host: `${token}._domainkey.${domain}`,
2762
+ type: "CNAME",
2763
+ value: `${token}.dkim.amazonses.com`
2764
+ })));
2765
+ if (verified) return;
2766
+ ctx.log(` ${domain}: SES sends as it once its DKIM records resolve — usually minutes, at most 72 hours`);
2767
+ }
2768
+ /** Say so when the account is in SES's sandbox, rather than fail on a send. */
2769
+ async function noteSandbox(ctx, { SES, ses }, region) {
2770
+ const quota = await ses.send(new SES.GetSendQuotaCommand({}));
2771
+ if ((quota.Max24HourSend ?? 0) > SANDBOX_DAILY_QUOTA) return;
2772
+ ctx.log(` ⚠️ SES in ${region} looks to be in the sandbox (${quota.Max24HourSend ?? 0} messages a day): it delivers only to addresses verified in SES. Request production access in the SES console before sending to anyone else.`);
2773
+ }
2774
+ /** The cheap check every deploy runs: each mail construct's keys are in the stage's secrets. */
2775
+ async function verifySesEmail(ctx) {
2776
+ for (const email of emailConstructs(ctx.manifest)) {
2777
+ const missing = [(0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "url"), (0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "from")].filter((key) => ctx.secrets[key] === void 0);
2778
+ if (missing.length > 0) throw new require_workspace.EmailNotProvisioned(ctx.stage, email.id, missing);
2779
+ }
2780
+ }
2781
+ const sesEmailProvider = {
2782
+ kind: "email",
2783
+ name: "ses",
2784
+ check: require_workspace.checkSesEmailConfig,
2785
+ provisioning: require_workspace.SES_PROVISIONING,
2786
+ credentials: require_stack.awsProvisioningCredentials,
2787
+ runtimeKeys(manifest) {
2788
+ return emailConstructs(manifest).flatMap((email) => [(0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "url"), (0, _geekmidas_manifest.providedKeyFor)(email.id, "email", "from")]);
2789
+ },
2790
+ ensure: ensureSesEmail,
2791
+ verify: verifySesEmail
2792
+ };
2793
+ //#endregion
2794
+ //#region src/providers/registry.ts
2795
+ /**
2796
+ * The providers gkm ships, by kind and name — registered the way a deploy
2797
+ * target's built-ins are (`target/builtins.ts`). A provider from a package is
2798
+ * one more entry here once there is a loading story for it.
2799
+ */
2800
+ const BUILTIN_PROVIDERS = {
2801
+ objects: { s3: s3Provider },
2802
+ inbox: { ses: sesProvider },
2803
+ email: { ses: sesEmailProvider }
2804
+ };
2805
+ /** The provider `kind` names `name`, if gkm has one. */
2806
+ function builtinProvider(kind, name) {
2807
+ return Object.hasOwn(BUILTIN_PROVIDERS[kind], name) ? BUILTIN_PROVIDERS[kind][name] : void 0;
2808
+ }
2809
+ //#endregion
2810
+ //#region src/providers/index.ts
2811
+ /** The constructs of a kind: `objects` is every bucket. */
2812
+ function constructsOf(manifest, kind) {
2813
+ return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
2814
+ }
2815
+ /**
2816
+ * What every deploy runs: each provider's `verify()` — the cheap check that
2817
+ * what it created is still there and the stage's key reaches it. Nothing on
2818
+ * the local stage, and nothing for a kind on `external` or `false` — a kind
2819
+ * the stage has none of is the deploy's readiness check's to refuse.
2820
+ */
2821
+ async function verifyStageProviders(input) {
2822
+ const verified = [];
2823
+ for (const kind of require_stack.PROVIDER_KINDS) {
2824
+ if (constructsOf(input.manifest, kind).length === 0) continue;
2825
+ const choice = require_workspace.stageProvider(input.workspace, kind, input.stage);
2826
+ if (choice.mode !== "provider") continue;
2827
+ const provider = builtinProvider(kind, choice.name);
2828
+ await provider.verify({
2829
+ workspace: input.workspace,
2830
+ manifest: input.manifest,
2831
+ stage: input.stage,
2832
+ config: choice.config,
2833
+ secrets: input.secrets,
2834
+ ...input.resources ? { resources: input.resources } : {},
2835
+ ...input.log ? { log: input.log } : {}
2836
+ });
2837
+ verified.push(`${kind}: ${provider.name}`);
2838
+ }
2839
+ if (await verifyStageBackups(input)) verified.push("backups: s3");
2840
+ return verified;
2841
+ }
2842
+ /**
2843
+ * A stage whose provider creates its resources, and no credentials to create
2844
+ * them with. Raised before anything is created, built or started.
2845
+ */
2846
+ var ProviderCredentialsMissing = class extends require_errors.GkmError {
2847
+ stage;
2848
+ kind;
2849
+ provider;
2850
+ ids;
2851
+ env;
2852
+ describe;
2853
+ login;
2854
+ constructor(stage, kind, provider, ids, env, describe, login) {
2855
+ super(`deploy.${kind}.${stage} is ${provider}, so the deploy creates what ${ids.join(", ")} ${ids.length === 1 ? "is" : "are"} backed by on '${stage}' and writes ${ids.length === 1 ? "its key" : "their keys"} into the stage's secrets — and it found no ${provider} credentials to do it with. On this machine, supply ${describe}` + (login ? `, or run gkm login --provider ${login}` : "") + `. In CI, the step that runs the deploy needs them: the '${stage}' environment's role (AWS_ROLE_ARN, from gkm deploy:github), assumed before that step. With the keys set by hand instead, set deploy.${kind}.${stage} to 'external'.`);
2856
+ this.stage = stage;
2857
+ this.kind = kind;
2858
+ this.provider = provider;
2859
+ this.ids = ids;
2860
+ this.env = env;
2861
+ this.describe = describe;
2862
+ this.login = login;
2863
+ this.name = "ProviderCredentialsMissing";
2864
+ }
2865
+ };
2866
+ /**
2867
+ * `ensure()` for every provider the stage configures — find or create, fix
2868
+ * drift, record in the stage's state, write the runtime keys into its
2869
+ * secrets. Run by the deploy, which holds the stage's lock. A provider with
2870
+ * no provisioning credentials stops the run with
2871
+ * {@link ProviderCredentialsMissing} before anything is created.
2872
+ */
2873
+ async function provisionStage(options) {
2874
+ const { workspace, stage, manifest } = options;
2875
+ const dryRun = options.dryRun === true;
2876
+ const env = options.env ?? process.env;
2877
+ const log = options.log ?? ((line) => console.log(line));
2878
+ const reports = [];
2879
+ const configured = [];
2880
+ for (const kind of require_stack.PROVIDER_KINDS) {
2881
+ const choice = require_workspace.stageProvider(workspace, kind, stage);
2882
+ if (choice.mode !== "provider") {
2883
+ reports.push({
2884
+ kind,
2885
+ mode: choice.mode,
2886
+ actions: [],
2887
+ planned: [],
2888
+ dns: []
2889
+ });
2890
+ continue;
2891
+ }
2892
+ const provider = builtinProvider(kind, choice.name);
2893
+ const report = {
2894
+ kind,
2895
+ mode: "provider",
2896
+ provider: provider.name,
2897
+ actions: [],
2898
+ planned: [],
2899
+ dns: []
2900
+ };
2901
+ reports.push(report);
2902
+ const ids = constructsOf(manifest, kind);
2903
+ const credential = await provider.credentials({
2904
+ stage,
2905
+ env,
2906
+ ...options.profile ? { profile: options.profile } : {},
2907
+ ...options.home ? { home: options.home } : {}
2908
+ });
2909
+ if (ids.length === 0 && credential === void 0) continue;
2910
+ if (credential === void 0) throw new ProviderCredentialsMissing(stage, kind, provider.name, ids, provider.provisioning.env, provider.provisioning.describe, provider.provisioning.login);
2911
+ configured.push({
2912
+ kind,
2913
+ provider,
2914
+ config: choice.config,
2915
+ credential,
2916
+ report
2917
+ });
2918
+ }
2919
+ const backups = require_stack.stageBackups(workspace, manifest, stage);
2920
+ if (configured.length === 0 && backups.mode !== "on") {
2921
+ if (backups.mode === "disabled") log(`💾 backups: off — deploy.backups.${stage} is false. Nothing is backed up, and nothing already backed up is deleted.`);
2922
+ return reports;
2923
+ }
2924
+ const identity = require_credentials.deployIdentity(workspace, stage);
2925
+ let secrets = (await options.secrets.read())?.custom ?? {};
2926
+ for (const entry of configured) entry.report.planned = entry.provider.runtimeKeys(manifest).filter((key) => secrets[key] === void 0);
2927
+ const journal = dryRun ? void 0 : await require_seeds.DeployJournal.open(options.state, stage, () => require_stack.deploysWithCompose(workspace) ? require_stack.createComposeState(stage) : require_stack.createEmptyState(stage, "", ""));
2928
+ const state = journal ? journalState(journal) : await readOnlyState(options.state, stage);
2929
+ const writeSecrets = async (values) => {
2930
+ if (dryRun) return;
2931
+ const stored = await options.secrets.read() ?? require_credentials.initStageSecrets(stage);
2932
+ const next = {
2933
+ ...stored,
2934
+ custom: {
2935
+ ...stored.custom,
2936
+ ...values
2937
+ },
2938
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2939
+ };
2940
+ await options.secrets.write(next);
2941
+ secrets = next.custom;
2942
+ };
2943
+ for (const entry of configured) {
2944
+ log(`☁️ ${entry.kind}: ${entry.provider.name}${dryRun ? " (dry run)" : ""}`);
2945
+ await entry.provider.ensure({
2946
+ workspace,
2947
+ manifest,
2948
+ ...options.subscribers ? { subscribers: options.subscribers } : {},
2949
+ stage,
2950
+ identity,
2951
+ config: entry.config,
2952
+ credential: entry.credential,
2953
+ get secrets() {
2954
+ return secrets;
2955
+ },
2956
+ state,
2957
+ dryRun,
2958
+ rotateKeys: options.rotateKeys === true,
2959
+ retireOldKeys: options.retireOldKeys === true,
2960
+ async change(action, apply) {
2961
+ if (!dryRun) await apply();
2962
+ entry.report.actions.push(action);
2963
+ log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
2964
+ },
2965
+ writeSecrets,
2966
+ writeDns: async (records) => {
2967
+ for (const record of records) entry.report.dns.push(require_seeds.dnsResourceKey(record.host.replace(/\.$/, ""), record.type));
2968
+ const written = await writeProviderDns(records, {
2969
+ workspace,
2970
+ stage,
2971
+ dryRun,
2972
+ credentials: options.credentials ?? require_credentials.storedCredentials({
2973
+ env,
2974
+ ...options.home ? { home: options.home } : {}
2975
+ }),
2976
+ ...options.dnsProviderFor ? { providerFor: options.dnsProviderFor } : {},
2977
+ log
2978
+ });
2979
+ if (journal) await recordProviderDns(journal, written);
2980
+ return { manual: written.manual };
2981
+ },
2982
+ log
2983
+ });
2984
+ if (entry.report.actions.length === 0) log(" up to date");
2985
+ }
2986
+ if (backups.mode === "on" || backups.mode === "disabled") {
2987
+ const report = {
2988
+ kind: "backups",
2989
+ mode: backups.mode === "on" ? "provider" : "none",
2990
+ actions: [],
2991
+ dns: [],
2992
+ planned: backups.mode === "on" ? [require_stack.BACKUPS_URL_KEY, ...backups.backups.pitr ? [require_stack.PITR_KEY] : []].filter((key) => secrets[key] === void 0) : []
2993
+ };
2994
+ reports.push(report);
2995
+ await ensureStageBackups({
2996
+ workspace,
2997
+ manifest,
2998
+ stage,
2999
+ ...options.profile ? { profile: options.profile } : {},
3000
+ ...options.home ? { home: options.home } : {},
3001
+ env,
3002
+ ctx: {
3003
+ identity,
3004
+ stage,
3005
+ state,
3006
+ dryRun,
3007
+ get secrets() {
3008
+ return secrets;
3009
+ },
3010
+ rotateKeys: options.rotateKeys === true,
3011
+ retireOldKeys: options.retireOldKeys === true,
3012
+ async change(action, apply) {
3013
+ if (!dryRun) await apply();
3014
+ report.actions.push(action);
3015
+ log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
3016
+ },
3017
+ writeSecrets,
3018
+ log
3019
+ }
3020
+ });
3021
+ if (backups.mode === "on" && report.actions.length === 0) log(" up to date");
3022
+ }
3023
+ return reports;
3024
+ }
3025
+ /**
3026
+ * What a provider's records came to, kept in the stage's state as `dns-record`
3027
+ * resources a provider asked for — so a deploy on which no provider asks for
3028
+ * one any more, after a change of domain, prunes it like a stack's record.
3029
+ * One found already right is kept too: its value is an AWS resource's own —
3030
+ * a DKIM token, a validation record, a distribution — and gkm made that.
3031
+ */
3032
+ async function recordProviderDns(journal, written) {
3033
+ for (const change of written.changes) {
3034
+ if (change.value === void 0) continue;
3035
+ if (change.action === "delete" || change.action === "manual") continue;
3036
+ await require_seeds.recordDnsResource(journal, {
3037
+ domain: change.domain,
3038
+ name: change.name,
3039
+ type: change.type,
3040
+ value: change.value,
3041
+ ttl: change.ttl ?? 0,
3042
+ source: "provider",
3043
+ ...written.providers[change.domain] ? { provider: written.providers[change.domain] } : {}
3044
+ });
3045
+ }
3046
+ }
3047
+ /** The journal as `ensure()` sees it. */
3048
+ function journalState(journal) {
3049
+ return {
3050
+ record: (key) => journal.record(key),
3051
+ pending: (entry) => journal.pending(entry),
3052
+ ready: (entry, id) => journal.ready(entry, id),
3053
+ lastDeployedAt: journal.existed ? journal.state.lastDeployedAt : void 0
3054
+ };
3055
+ }
3056
+ /** What a dry run reads, and the writes it does not make. */
3057
+ async function readOnlyState(store, stage) {
3058
+ const stored = await store.read(stage);
3059
+ return {
3060
+ record: (key) => stored?.resources[key],
3061
+ pending: async () => {},
3062
+ ready: async () => {},
3063
+ ...stored ? { lastDeployedAt: stored.state.lastDeployedAt } : {}
3064
+ };
3065
+ }
3066
+ //#endregion
3067
+ //#region src/secrets/bucketKeys.ts
3068
+ /**
3069
+ * The keys a bucket and a file server used to be stored under, moved to the
3070
+ * ones they are read from now.
3071
+ *
3072
+ * A bucket's connection was `<ID>_URL` and is `<ID>_CONNECTION_STRING`; a file
3073
+ * server's public address was `<ID>_SERVER_URL` and is `<ID>_URL`. A deployed
3074
+ * stage still holds the old names: written there by its provider, or set by
3075
+ * hand on an `external` one. Both are moved, in that order, the first time
3076
+ * the stage is deployed after the rename — the bucket's first, because the
3077
+ * name it leaves is the one the file server's address moves into.
3078
+ *
3079
+ * Moved rather than reissued: the provider reads its access key back out of
3080
+ * the stored connection, so finding nothing under the new name would issue
3081
+ * the bucket a second key.
3082
+ */
3083
+ /**
3084
+ * `custom` with each old bucket and file-server key moved to its new name,
3085
+ * and what was moved. A key whose new name is already set is left where it
3086
+ * is: the new one is what is read, and the old one is somebody's to delete.
3087
+ */
3088
+ function moveBucketKeys(manifest, custom) {
3089
+ const next = { ...custom };
3090
+ const moved = [];
3091
+ const move = (from, to, when = (_) => true) => {
3092
+ const value = next[from];
3093
+ if (from === to || value === void 0 || next[to] !== void 0) return;
3094
+ if (!when(value)) return;
3095
+ next[to] = value;
3096
+ delete next[from];
3097
+ moved.push({
3098
+ from,
3099
+ to
3100
+ });
3101
+ };
3102
+ const entries = Object.entries(manifest);
3103
+ for (const [id, declaration] of entries) {
3104
+ if (declaration.kind !== "objects") continue;
3105
+ move((0, _geekmidas_manifest.environmentCase)(`${id}_url`), (0, _geekmidas_manifest.providedKeyFor)(id, declaration.kind, "connectionString"), (value) => !/^https?:\/\//i.test(value));
3106
+ }
3107
+ for (const [id, declaration] of entries) {
3108
+ if (declaration.kind !== "file-server") continue;
3109
+ move((0, _geekmidas_manifest.environmentCase)(`${id}_url`), (0, _geekmidas_manifest.providedKeyFor)(id, "file-server", "url"));
3110
+ }
3111
+ return {
3112
+ custom: next,
3113
+ moved
3114
+ };
3115
+ }
3116
+ //#endregion
3117
+ //#region src/secrets/stale.ts
3118
+ /**
3119
+ * Stored secrets an older gkm generated that now shadow a derived value.
3120
+ *
3121
+ * Before constructs, initialising a stage wrote an address for each app into
3122
+ * its custom secrets: `<APP>_DATABASE_URL` as a `postgresql://…@localhost`
3123
+ * URL with a password of its own, and `http://localhost:<port>` for a site or
3124
+ * an auth server. Those keys are now a construct's — `database.schema('AuthDatabase')`
3125
+ * provides `AUTH_DATABASE_URL`, `new BetterAuth('Auth')` provides `AUTH_URL`
3126
+ * — and a deploy derives them. A value the stage holds is a value set by hand,
3127
+ * and set by hand wins: the container is handed `localhost`, where nothing
3128
+ * answers, with a password no role has.
3129
+ *
3130
+ * So a deploy refuses such a stage rather than run it, naming each key and
3131
+ * the command that removes it. Nothing is deleted for the user: the value is
3132
+ * theirs, and only they can say it is stale. A URL that names a real host — a
3133
+ * managed database — is a deliberate choice and still wins.
3134
+ */
3135
+ /** The kinds whose URL an older gkm wrote into a stage's secrets. */
3136
+ const ADDRESSED = /* @__PURE__ */ new Set([
3137
+ "database",
3138
+ "database-reader",
3139
+ "database-schema",
3140
+ "rest-api",
3141
+ "site"
3142
+ ]);
3143
+ /** Hosts that are this machine — never anything, inside a container. */
3144
+ const LOOPBACK = /* @__PURE__ */ new Set([
3145
+ "localhost",
3146
+ "127.0.0.1",
3147
+ "[::1]",
3148
+ "::1"
3149
+ ]);
3150
+ /**
3151
+ * A stage holds a construct's address as a custom secret, pointing at
3152
+ * `localhost` — what an older `gkm secrets:init`, `gkm setup` or `gkm init`
3153
+ * generated. Set by hand wins over derived, so the app would be handed it.
3154
+ */
3155
+ var StaleStageSecrets = class extends require_errors.GkmError {
3156
+ stage;
3157
+ stale;
3158
+ constructor(stage, stale) {
3159
+ const one = stale.length === 1;
3160
+ super(`The stage '${stage}' holds ${one ? "a value" : "values"} an older gkm generated for ${one ? "an address a construct" : "addresses constructs"} now ${one ? "provides" : "provide"}:\n` + stale.map((s) => ` ${s.key}: ${s.construct}'s, stored pointing at ${s.host}`).join("\n") + `
3161
+ A stored value wins over the derived one, so the app would be handed an address where nothing answers inside its container. Remove ${one ? "it" : "each"}, and the construct's own value is used:\n` + stale.map((s) => ` gkm secrets:unset ${s.key} --stage ${stage}`).join("\n") + "\nA managed service set with its real host is not affected.");
3162
+ this.stage = stage;
3163
+ this.stale = stale;
3164
+ this.name = "StaleStageSecrets";
3165
+ }
3166
+ };
3167
+ /** The host a stored value names, if it is a URL. */
3168
+ function hostOf(value) {
3169
+ try {
3170
+ return new URL(value).hostname;
3171
+ } catch {
3172
+ return;
3173
+ }
3174
+ }
3175
+ /**
3176
+ * Each stored key that a construct provides an address for, holding an
3177
+ * address on this machine.
3178
+ */
3179
+ function staleStageSecrets(manifest, supplied) {
3180
+ const stale = [];
3181
+ for (const [id, declaration] of Object.entries(manifest)) {
3182
+ if (!ADDRESSED.has(declaration.kind)) continue;
3183
+ const key = (0, _geekmidas_manifest.providedKeyFor)(id, declaration.kind, "url");
3184
+ const value = supplied[key];
3185
+ if (value === void 0) continue;
3186
+ const host = hostOf(value);
3187
+ if (host === void 0 || !LOOPBACK.has(host)) continue;
3188
+ stale.push({
3189
+ key,
3190
+ construct: id,
3191
+ host
3192
+ });
3193
+ }
3194
+ return stale.sort((a, b) => a.key.localeCompare(b.key));
3195
+ }
3196
+ /**
3197
+ * Refuse a stage whose stored secrets would shadow a construct's address with
3198
+ * `localhost`.
3199
+ *
3200
+ * @throws {StaleStageSecrets} naming each key and the command removing it
3201
+ */
3202
+ function assertNoStaleSecrets(options) {
3203
+ const stale = staleStageSecrets(options.manifest, options.supplied);
3204
+ if (stale.length > 0) throw new StaleStageSecrets(options.stage, stale);
3205
+ }
3206
+ //#endregion
3207
+ //#region src/deploy/readiness.ts
3208
+ /**
3209
+ * Whether a stage is ready to be deployed: the one check, run once by every
3210
+ * deploy through a server target — after the stage's providers have created
3211
+ * what they create and written its keys, and before the target touches
3212
+ * anything.
3213
+ *
3214
+ * A build is not a deploy. Images carry no stage's keys, so a build-only run
3215
+ * (`gkm compose --build --push`) never calls this: a key the deploy itself
3216
+ * writes — a provider's bucket URL — is not there yet when CI builds, and
3217
+ * must not stop the build.
3218
+ */
3219
+ /**
3220
+ * The stage has every key it needs, read from its secrets as the providers
3221
+ * left them:
3222
+ *
3223
+ * 1. no kind it declares is one the stage set to `false`;
3224
+ * 2. its mail and storage are its own — or a dev service, where allowed,
3225
+ * reported once, loudly;
3226
+ * 3. what its providers created is still there, and its key reaches it;
3227
+ * 4. no key holds an address an older gkm stored for what a construct now
3228
+ * provides;
3229
+ * 5. each third party's credentials match their construct's schema.
3230
+ *
3231
+ * The local stage derives its mail and storage, so only 4 and 5 apply to it.
3232
+ *
3233
+ * @throws {StageProviderDisabled}
3234
+ * @throws {ExternalServicesNotConfigured} naming every missing key at once
3235
+ * @throws {StaleStageSecrets}
3236
+ * @throws {CredentialsInvalid}
3237
+ */
3238
+ async function assertStageReady(ctx) {
3239
+ const { workspace, manifest, stage } = ctx;
3240
+ const supplied = (await ctx.secrets.read())?.custom ?? {};
3241
+ if (stage !== workspace.stages.local) {
3242
+ require_stack.assertStageProvidersEnabled(workspace, manifest, stage);
3243
+ const domain = workspace.domains?.[stage];
3244
+ const services = require_stack.externalServices({
3245
+ stage,
3246
+ declarations: require_stack.stageServiceDeclarations({ manifest }),
3247
+ supplied,
3248
+ allow: ctx.allowDevServices,
3249
+ ...domain ? { domain } : {},
3250
+ providers: require_stack.stageProviderNotes(workspace, stage)
3251
+ });
3252
+ if (services.missing.length > 0) throw new require_stack.ExternalServicesNotConfigured(stage, services.missing);
3253
+ require_stack.reportDevServices(ctx, require_stack.devServicesUsed(services));
3254
+ const verified = await verifyStageProviders({
3255
+ workspace,
3256
+ manifest,
3257
+ stage,
3258
+ secrets: supplied,
3259
+ resources: (await ctx.state.read(stage))?.resources ?? {},
3260
+ log: (line) => ctx.logger.info(line)
3261
+ });
3262
+ for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
3263
+ }
3264
+ assertNoStaleSecrets({
3265
+ manifest,
3266
+ stage,
3267
+ supplied
3268
+ });
3269
+ await require_credentialSchemas.assertStageCredentials({
3270
+ root: workspace.root,
3271
+ patterns: require_stack.constructGlobs(workspace),
3272
+ manifest,
3273
+ stage,
3274
+ supplied
3275
+ });
3276
+ }
3277
+ //#endregion
3278
+ //#region src/deploy/orchestrate.ts
3279
+ /**
3280
+ * The run around a target: what every deploy does whatever it deploys
3281
+ * through.
3282
+ *
3283
+ * It loads the workspace, resolves the target, works out the apps and the
3284
+ * identity, takes the stage's lock, and calls the target's phases in order,
3285
+ * reporting each as it starts, finishes or fails. Everything that is about
3286
+ * *where* the stage goes is the target's.
3287
+ */
3288
+ /** Apps were asked for by name that the workspace does not have. */
3289
+ var UnknownDeployApps = class extends require_errors.GkmError {
3290
+ apps;
3291
+ available;
3292
+ constructor(apps, available) {
3293
+ super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
3294
+ this.apps = apps;
3295
+ this.available = available;
3296
+ this.name = "UnknownDeployApps";
3297
+ }
3298
+ };
3299
+ /** Every app asked for deploys through some other target. */
3300
+ var NoDeployableApps = class extends require_errors.GkmError {
3301
+ stage;
3302
+ target;
3303
+ constructor(stage, target) {
3304
+ super(`No apps to deploy through "${target}": every selected app deploys somewhere else. Pick the target with --target, or set each app's deploy in gkm.config.ts.`);
3305
+ this.stage = stage;
3306
+ this.target = target;
3307
+ this.name = "NoDeployableApps";
3308
+ }
3309
+ };
3310
+ /** A build-only run through a target with no build phase. */
3311
+ var TargetBuildsNothing = class extends require_errors.GkmError {
3312
+ target;
3313
+ constructor(target) {
3314
+ super(`"${target}" has no build phase, so a build-only run would do nothing. Deploy it in full, or build through a target that builds images (compose).`);
3315
+ this.target = target;
3316
+ this.name = "TargetBuildsNothing";
3317
+ }
3318
+ };
3319
+ /** A failed rollback, after the failure that called for it. */
3320
+ var RollbackFailed = class extends Error {
3321
+ target;
3322
+ failure;
3323
+ constructor(target, failure, cause) {
3324
+ super(`Deploying through "${target}" failed, and so did rolling it back: ${cause instanceof Error ? cause.message : String(cause)}. The stage may be part-released; deploy again, or roll it back by hand. The first failure: ${failure instanceof Error ? failure.message : String(failure)}`, { cause });
3325
+ this.target = target;
3326
+ this.failure = failure;
3327
+ this.name = "RollbackFailed";
3328
+ }
3329
+ };
3330
+ /**
3331
+ * A release tag for a deploy given none: the moment it started. Each target
3332
+ * puts the stage on it for the images it builds (`stageTag`).
3333
+ */
3334
+ function generateTag() {
3335
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
3336
+ }
3337
+ /** Why an app that deploys through another target is left out. */
3338
+ function elsewhere(target, stage) {
3339
+ const instead = require_define.builtinTarget(target)?.instead?.(stage);
3340
+ if (instead) return `it deploys through "${target}" — ${instead}`;
3341
+ return `it deploys through "${target}" — run \`gkm deploy --target ${target} --stage ${stage}\``;
3342
+ }
3343
+ /**
3344
+ * Deploy a workspace's stage through its target.
3345
+ *
3346
+ * The engine under `deploy()` and `gkm deploy`. It never prompts and never
3347
+ * exits: credentials come from `ctx.credentials`, progress goes to
3348
+ * `ctx.emit` and to `output`, and every failure is thrown.
3349
+ *
3350
+ * @internal
3351
+ */
3352
+ async function runDeploy(source, request, ctx) {
3353
+ const { stage } = request;
3354
+ const redactor = ctx.redactor ?? new Redactor();
3355
+ const emit = (event) => ctx.emit(event.type === "log" ? {
3356
+ ...event,
3357
+ message: redactor.redact(event.message)
3358
+ } : event);
3359
+ /** Run one phase between its events. */
3360
+ const phase = async (name, body) => {
3361
+ ctx.signal?.throwIfAborted();
3362
+ emit({
3363
+ type: "phase.started",
3364
+ phase: name
3365
+ });
3366
+ try {
3367
+ const value = await body();
3368
+ emit({
3369
+ type: "phase.finished",
3370
+ phase: name
3371
+ });
3372
+ return value;
3373
+ } catch (error) {
3374
+ emit({
3375
+ type: "phase.failed",
3376
+ phase: name,
3377
+ error: require_sniffer.eventError(error)
3378
+ });
3379
+ throw error;
3380
+ }
3381
+ };
3382
+ ctx.signal?.throwIfAborted();
3383
+ emit({
3384
+ type: "phase.started",
3385
+ phase: "validate"
3386
+ });
3387
+ let prepared;
3388
+ try {
3389
+ prepared = await prepare(source, request, ctx, emit, redactor);
3390
+ } catch (error) {
3391
+ emit({
3392
+ type: "phase.failed",
3393
+ phase: "validate",
3394
+ error: require_sniffer.eventError(error)
3395
+ });
3396
+ throw error;
3397
+ }
3398
+ const { resolved, phaseCtx, store } = prepared;
3399
+ const { target } = resolved;
3400
+ const resources = !ctx.buildOnly && phaseCtx.stage !== phaseCtx.workspace.stages.local;
3401
+ const provision = async () => {
3402
+ if (!request.skipDns && resolved.target.runtime === "server") try {
3403
+ await require_snsSubscriptions.dnsCredentials(phaseCtx.stage, require_snsSubscriptions.stageDnsDomains(phaseCtx.stage, phaseCtx.workspace.domains, phaseCtx.workspace.dns), ctx.credentials);
3404
+ } catch (error) {
3405
+ emit({
3406
+ type: "phase.failed",
3407
+ phase: "validate",
3408
+ error: require_sniffer.eventError(error)
3409
+ });
3410
+ throw error;
3411
+ }
3412
+ await moveStoredBucketKeys(phaseCtx, ctx.dryRun);
3413
+ await provisionResources(phaseCtx, request, ctx, store, emit);
3414
+ };
3415
+ if (ctx.dryRun) {
3416
+ if (resources) await provision();
3417
+ const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
3418
+ await phase("plan", () => target.plan(phaseCtx, run));
3419
+ return target.result(phaseCtx, run);
3420
+ }
3421
+ if (ctx.buildOnly) {
3422
+ if (!target.build) throw new TargetBuildsNothing(resolved.name);
3423
+ const run = await validate(phaseCtx, emit, () => target.validate(phaseCtx));
3424
+ await phase("build", () => target.build(phaseCtx, run));
3425
+ return target.result(phaseCtx, run);
3426
+ }
3427
+ let lock;
3428
+ try {
3429
+ require_sniffer.assertStateOutlivesRun(phaseCtx.workspace, stage, "deploy");
3430
+ lock = await store.lock(stage, { operation: "deploy" });
3431
+ } catch (error) {
3432
+ emit({
3433
+ type: "phase.failed",
3434
+ phase: "validate",
3435
+ error: require_sniffer.eventError(error)
3436
+ });
3437
+ throw error;
3438
+ }
3439
+ try {
3440
+ try {
3441
+ await require_sniffer.assertStateRoom(store, stage);
3442
+ } catch (error) {
3443
+ emit({
3444
+ type: "phase.failed",
3445
+ phase: "validate",
3446
+ error: require_sniffer.eventError(error)
3447
+ });
3448
+ throw error;
3449
+ }
3450
+ if (resources) await provision();
3451
+ const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
3452
+ if (target.provision) await phase("provision", () => target.provision(phaseCtx, run));
3453
+ if (target.build) await phase("build", () => target.build(phaseCtx, run));
3454
+ let releasing = "release";
3455
+ try {
3456
+ await phase("release", () => target.release(phaseCtx, run));
3457
+ releasing = "verify";
3458
+ if (target.verify) await phase("verify", () => target.verify(phaseCtx, run));
3459
+ } catch (error) {
3460
+ if (ctx.signal?.aborted || !target.capabilities.rollback) throw error;
3461
+ if (!target.rollback) throw error;
3462
+ try {
3463
+ await phase("rollback", () => target.rollback(phaseCtx, run, {
3464
+ phase: releasing,
3465
+ error
3466
+ }));
3467
+ } catch (rollbackError) {
3468
+ throw new RollbackFailed(resolved.name, error, rollbackError);
3469
+ }
3470
+ throw error;
3471
+ }
3472
+ return await target.result(phaseCtx, run);
3473
+ } finally {
3474
+ await lock.release();
3475
+ }
3476
+ }
3477
+ /**
3478
+ * The stage's providers, run inside the validate phase. A dry run plans them
3479
+ * and, so the checks after it see the stage as the run would leave it, reads
3480
+ * the keys they would write as placeholders.
3481
+ */
3482
+ async function provisionResources(phaseCtx, request, ctx, store, emit) {
3483
+ try {
3484
+ const reports = await provisionStage({
3485
+ workspace: phaseCtx.workspace,
3486
+ stage: phaseCtx.stage,
3487
+ manifest: phaseCtx.manifest,
3488
+ ...phaseCtx.subscribers ? { subscribers: phaseCtx.subscribers } : {},
3489
+ secrets: phaseCtx.secrets,
3490
+ state: store,
3491
+ dryRun: ctx.dryRun,
3492
+ ...request.rotateKeys ? { rotateKeys: true } : {},
3493
+ ...request.retireOldKeys ? { retireOldKeys: true } : {},
3494
+ ...ctx.home ? { home: ctx.home } : {},
3495
+ credentials: ctx.credentials,
3496
+ log: (line) => phaseCtx.logger.info(line)
3497
+ });
3498
+ phaseCtx.providerDns = reports.flatMap((r) => r.dns);
3499
+ if (!ctx.dryRun) return;
3500
+ const planned = reports.flatMap((r) => r.planned);
3501
+ if (planned.length === 0) return;
3502
+ const secrets = phaseCtx.secrets;
3503
+ phaseCtx.secrets = {
3504
+ ...secrets,
3505
+ async read() {
3506
+ const stored = await secrets.read() ?? require_credentials.initStageSecrets(phaseCtx.stage);
3507
+ const custom = { ...stored.custom };
3508
+ for (const key of planned) custom[key] ??= PLANNED_BY_THE_DEPLOY;
3509
+ return {
3510
+ ...stored,
3511
+ custom
3512
+ };
3513
+ }
3514
+ };
3515
+ } catch (error) {
3516
+ emit({
3517
+ type: "phase.failed",
3518
+ phase: "validate",
3519
+ error: require_sniffer.eventError(error)
3520
+ });
3521
+ throw error;
3522
+ }
3523
+ }
3524
+ /**
3525
+ * The stage's bucket and file-server keys moved to the names they are read
3526
+ * from (`moveBucketKeys`), before its providers or its readiness check read
3527
+ * them. A dry run moves them in what it reads, and writes nothing.
3528
+ */
3529
+ async function moveStoredBucketKeys(phaseCtx, dryRun) {
3530
+ const secrets = phaseCtx.secrets;
3531
+ const stored = await secrets.read();
3532
+ if (!stored) return;
3533
+ const { custom, moved } = moveBucketKeys(phaseCtx.manifest, stored.custom);
3534
+ if (moved.length === 0) return;
3535
+ for (const { from, to } of moved) phaseCtx.logger.info(`🔑 ${from} → ${to}${dryRun ? " (dry run: not written)" : ""}`);
3536
+ if (!dryRun) {
3537
+ await secrets.write({
3538
+ ...stored,
3539
+ custom,
3540
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3541
+ });
3542
+ return;
3543
+ }
3544
+ phaseCtx.secrets = {
3545
+ ...secrets,
3546
+ async read() {
3547
+ const current = await secrets.read();
3548
+ return current ? {
3549
+ ...current,
3550
+ custom: moveBucketKeys(phaseCtx.manifest, current.custom).custom
3551
+ } : current;
3552
+ }
3553
+ };
3554
+ }
3555
+ /** What a dry run reads for a key its providers would write. */
3556
+ const PLANNED_BY_THE_DEPLOY = "s3://planned-by-this-deploy";
3557
+ /**
3558
+ * What a deploy validates: the stage ready to be deployed — every key it
3559
+ * needs, read as its providers left them — then what the target would run,
3560
+ * then whatever only the target checks. A build-only run validates the
3561
+ * target's run alone: it calls neither readiness check.
3562
+ */
3563
+ async function readyToDeploy(target, phaseCtx) {
3564
+ if (target.runtime === "server") await assertStageReady(phaseCtx);
3565
+ const run = await target.validate(phaseCtx);
3566
+ await target.ready?.(phaseCtx, run);
3567
+ return run;
3568
+ }
3569
+ /** `body`, then the run's `deploy.started`, inside the validate phase. */
3570
+ async function validate(phaseCtx, emit, body) {
3571
+ try {
3572
+ const run = await body();
3573
+ const skipped = new Set(phaseCtx.skipped.map((s) => s.app));
3574
+ emit({
3575
+ type: "deploy.started",
3576
+ stage: phaseCtx.stage,
3577
+ target: phaseCtx.target,
3578
+ identity: phaseCtx.identity.key,
3579
+ tag: phaseCtx.tag,
3580
+ apps: phaseCtx.apps.filter((app) => !skipped.has(app)),
3581
+ dryRun: phaseCtx.dryRun
3582
+ });
3583
+ emit({
3584
+ type: "phase.finished",
3585
+ phase: "validate"
3586
+ });
3587
+ return run;
3588
+ } catch (error) {
3589
+ emit({
3590
+ type: "phase.failed",
3591
+ phase: "validate",
3592
+ error: require_sniffer.eventError(error)
3593
+ });
3594
+ throw error;
3595
+ }
3596
+ }
3597
+ /** Everything the phases are handed, worked out before the first of them. */
3598
+ async function prepare(source, request, ctx, emit, redactor) {
3599
+ const { stage } = request;
3600
+ const configured = typeof source === "function" ? await source() : source;
3601
+ const local = stage === configured.stages.local;
3602
+ if (!local) require_workspace.assertDeployedStage(configured.stages, stage);
3603
+ const targetName = request.target ?? configured.deploy?.default ?? "dokploy";
3604
+ const resolved = await require_resolve.resolveTarget(targetName, {
3605
+ workspace: configured,
3606
+ stage,
3607
+ ...ctx.targets ? { host: ctx.targets } : {}
3608
+ });
3609
+ if (local && !resolved.target.capabilities.localStage) require_workspace.assertDeployedStage(configured.stages, stage);
3610
+ const options = await require_resolve.parseTargetOptions(resolved);
3611
+ const allowDevServices = request.allowDevServices === true;
3612
+ if (allowDevServices && resolved.target.runtime === "aws") throw new require_stack.DevServicesNeedServerTarget(targetName);
3613
+ const background = {};
3614
+ const subscribers = {};
3615
+ const manifest = await require_discover.discover({
3616
+ patterns: require_stack.constructGlobs(configured),
3617
+ cwd: configured.root,
3618
+ background,
3619
+ subscribers
3620
+ });
3621
+ require_workspace.resolveStageTelemetry({
3622
+ ...configured.deploy?.telemetry ? { telemetry: configured.deploy.telemetry } : {},
3623
+ stage,
3624
+ local,
3625
+ target: targetName,
3626
+ runtime: resolved.target.runtime,
3627
+ selfHosted: resolved.target.capabilities.selfHostedTelemetry === true,
3628
+ used: require_credentials$1.usesTelemetry(manifest)
3629
+ });
3630
+ const units = require_workspace.derivedApps(manifest, configured);
3631
+ const workspace = Object.keys(units).length > 0 ? {
3632
+ ...configured,
3633
+ apps: units
3634
+ } : configured;
3635
+ const identity = require_credentials.deployIdentity(workspace, stage);
3636
+ const tag = request.tag ?? (resolved.target.tag ? await resolved.target.tag({
3637
+ cwd: workspace.root,
3638
+ stage
3639
+ }) : generateTag());
3640
+ const buildOrder = require_workspace.getAppBuildOrder(workspace);
3641
+ let selected = buildOrder;
3642
+ if (request.apps && request.apps.length > 0) {
3643
+ const unknown = request.apps.filter((name) => !workspace.apps[name]);
3644
+ if (unknown.length > 0) throw new UnknownDeployApps(unknown, Object.keys(workspace.apps));
3645
+ selected = buildOrder.filter((name) => request.apps.includes(name));
3646
+ }
3647
+ const skipped = [];
3648
+ const skip = (app, reason) => {
3649
+ skipped.push({
3650
+ app,
3651
+ reason
3652
+ });
3653
+ emit({
3654
+ type: "app.skipped",
3655
+ app,
3656
+ reason
3657
+ });
3658
+ };
3659
+ const byDefault = configured.deploy?.default ?? "dokploy";
3660
+ const apps = selected.filter((name) => {
3661
+ const own = workspace.apps[name].resolvedDeployTarget;
3662
+ const deploysThrough = own === byDefault ? targetName : own;
3663
+ if (deploysThrough === targetName) return true;
3664
+ skip(name, elsewhere(deploysThrough, stage));
3665
+ return false;
3666
+ });
3667
+ if (apps.length === 0) throw new NoDeployableApps(stage, targetName);
3668
+ require_stack.assertSitePasswords(configured, manifest, stage, apps, resolved.target.name);
3669
+ const store = await require_sniffer.createStateStore({
3670
+ config: stage === workspace.stages.local ? void 0 : workspace.state,
3671
+ workspaceRoot: workspace.root,
3672
+ workspaceName: workspace.name,
3673
+ namespace: workspace.deploy?.namespace
3674
+ });
3675
+ const secrets = await deploySecrets(workspace, stage, redactor, { ...ctx.home ? { home: ctx.home } : {} });
3676
+ const line = (level) => (message) => emit({
3677
+ type: "log",
3678
+ level,
3679
+ message
3680
+ });
3681
+ const logger = {
3682
+ info: line("info"),
3683
+ warn: line("warn"),
3684
+ error: line("error")
3685
+ };
3686
+ return {
3687
+ resolved,
3688
+ phaseCtx: {
3689
+ target: targetName,
3690
+ cwd: workspace.root,
3691
+ stage,
3692
+ tag,
3693
+ tagGiven: request.tag !== void 0,
3694
+ apps,
3695
+ skipped,
3696
+ identity,
3697
+ workspace,
3698
+ manifest,
3699
+ background,
3700
+ subscribers,
3701
+ options,
3702
+ dryRun: ctx.dryRun,
3703
+ atomic: request.atomic ?? false,
3704
+ allowDevServices,
3705
+ ...request.skipDns ? { skipDns: true } : {},
3706
+ credentials: ctx.credentials,
3707
+ state: store,
3708
+ secrets,
3709
+ logger,
3710
+ signal: ctx.signal ?? new AbortController().signal,
3711
+ childOutput: ctx.childOutput ?? "inherit",
3712
+ emit,
3713
+ skip,
3714
+ name: (resource) => require_credentials.applicationName(identity, resource)
3715
+ },
3716
+ store
3717
+ };
3718
+ }
3719
+ //#endregion
3720
+ //#region src/deploy/deploy.ts
3721
+ /**
3722
+ * `deploy()`: a deploy as a library call.
3723
+ *
3724
+ * `gkm deploy` could only be driven from an interactive terminal: it prompted
3725
+ * for what it lacked and exited the process on failure, worked out of
3726
+ * `process.cwd()`, and reported progress by printing. Here the caller says
3727
+ * where the project is, hands over the credentials and a signal, and gets back
3728
+ * a run — events to iterate while it goes, and a structured result at the end.
3729
+ * Nothing below this asks a person anything or ends the process; `gkm deploy`
3730
+ * is a thin wrapper that does both.
3731
+ */
3732
+ /**
3733
+ * Every event a run emits, kept so that each iteration — however late it
3734
+ * starts — sees the run from its first event to its last.
3735
+ */
3736
+ var EventLog = class {
3737
+ events = [];
3738
+ closed = false;
3739
+ waiting = [];
3740
+ push(event) {
3741
+ this.events.push(event);
3742
+ this.wake();
3743
+ }
3744
+ close() {
3745
+ this.closed = true;
3746
+ this.wake();
3747
+ }
3748
+ wake() {
3749
+ const waiting = this.waiting;
3750
+ this.waiting = [];
3751
+ for (const resume of waiting) resume();
3752
+ }
3753
+ async *iterate() {
3754
+ let next = 0;
3755
+ while (true) if (next < this.events.length) yield this.events[next++];
3756
+ else if (this.closed) return;
3757
+ else await new Promise((resume) => this.waiting.push(resume));
3758
+ }
3759
+ };
3760
+ function forward(logger, level, message) {
3761
+ if (!logger) return;
3762
+ if (level === "info") logger.info(message);
3763
+ else if (level === "error" && logger.error) logger.error(message);
3764
+ else logger.warn(message);
3765
+ }
3766
+ /**
3767
+ * Deploy a project's stage.
3768
+ *
3769
+ * ```ts
3770
+ * import { deploy } from '@geekmidas/cli/deploy';
3771
+ *
3772
+ * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
3773
+ * for await (const event of run) {
3774
+ * if (event.type === 'app.deployed') console.log(event.app, event.url);
3775
+ * }
3776
+ * const result = await run.result;
3777
+ * ```
3778
+ *
3779
+ * The run starts at once; iterating it is optional, and an iteration started
3780
+ * late still sees every event from the first.
3781
+ */
3782
+ function deploy(input) {
3783
+ const log = new EventLog();
3784
+ const redactor = new Redactor();
3785
+ const emit = (event) => {
3786
+ const masked = event.type === "log" ? {
3787
+ ...event,
3788
+ message: redactor.redact(event.message)
3789
+ } : event;
3790
+ log.push(masked);
3791
+ if (masked.type === "log") forward(input.logger, masked.level, masked.message);
3792
+ };
3793
+ const ctx = {
3794
+ emit,
3795
+ credentials: input.credentials ?? require_credentials.storedCredentials({ home: input.home ?? require_credentials.gkmHome() }),
3796
+ dryRun: input.dryRun ?? false,
3797
+ ...input.buildOnly ? { buildOnly: true } : {},
3798
+ home: input.home ?? require_credentials.gkmHome(),
3799
+ redactor,
3800
+ ...input.signal ? { signal: input.signal } : {},
3801
+ ...input.childOutput ? { childOutput: input.childOutput } : {},
3802
+ ...input.targets ? { targets: input.targets } : {}
3803
+ };
3804
+ const result = require_discover.withOutput((level, message) => emit({
3805
+ type: "log",
3806
+ level,
3807
+ message
3808
+ }), async () => {
3809
+ try {
3810
+ input.signal?.throwIfAborted();
3811
+ const root = require_config.findWorkspaceRoot((0, node_path.resolve)(input.cwd));
3812
+ const sandbox = input.sandbox ?? new require_local.LocalSandbox({ root });
3813
+ const inRun = (fn) => input.config ? require_config.withLoadedConfig(root, input.config, fn) : fn();
3814
+ const deployed = await inRun(() => require_discover.withSandbox(sandbox, () => runDeploy(() => load(input, sandbox), {
3815
+ stage: input.stage,
3816
+ ...input.target ? { target: input.target } : {},
3817
+ ...input.tag ? { tag: input.tag } : {},
3818
+ ...input.apps ? { apps: input.apps } : {},
3819
+ ...input.atomic ? { atomic: true } : {},
3820
+ ...input.allowDevServices ? { allowDevServices: input.allowDevServices } : {},
3821
+ ...input.skipDns ? { skipDns: true } : {},
3822
+ ...input.rotateKeys ? { rotateKeys: true } : {},
3823
+ ...input.retireOldKeys ? { retireOldKeys: true } : {}
3824
+ }, ctx)));
3825
+ emit({
3826
+ type: "deploy.finished",
3827
+ result: deployed
3828
+ });
3829
+ return deployed;
3830
+ } catch (error) {
3831
+ emit({
3832
+ type: "deploy.failed",
3833
+ error: require_sniffer.eventError(error)
3834
+ });
3835
+ throw error;
3836
+ } finally {
3837
+ log.close();
3838
+ }
3839
+ });
3840
+ result.catch(() => {});
3841
+ return {
3842
+ result,
3843
+ [Symbol.asyncIterator]: () => log.iterate()
3844
+ };
3845
+ }
3846
+ /**
3847
+ * The workspace at `input.cwd`. The stage is checked by the run, once it
3848
+ * knows the target: one that runs on this machine may take the local stage.
3849
+ */
3850
+ async function load(input, sandbox) {
3851
+ const { workspace } = await require_config.loadWorkspaceConfig((0, node_path.resolve)(input.cwd), { sandbox });
3852
+ return workspace;
3853
+ }
3854
+ //#endregion
3855
+ Object.defineProperty(exports, "NoDeployableApps", {
3856
+ enumerable: true,
3857
+ get: function() {
3858
+ return NoDeployableApps;
3859
+ }
3860
+ });
3861
+ Object.defineProperty(exports, "RollbackFailed", {
3862
+ enumerable: true,
3863
+ get: function() {
3864
+ return RollbackFailed;
3865
+ }
3866
+ });
3867
+ Object.defineProperty(exports, "TargetBuildsNothing", {
3868
+ enumerable: true,
3869
+ get: function() {
3870
+ return TargetBuildsNothing;
3871
+ }
3872
+ });
3873
+ Object.defineProperty(exports, "UnknownDeployApps", {
3874
+ enumerable: true,
3875
+ get: function() {
3876
+ return UnknownDeployApps;
3877
+ }
3878
+ });
3879
+ Object.defineProperty(exports, "backupsUserName", {
3880
+ enumerable: true,
3881
+ get: function() {
3882
+ return backupsUserName;
3883
+ }
3884
+ });
3885
+ Object.defineProperty(exports, "cdnName", {
3886
+ enumerable: true,
3887
+ get: function() {
3888
+ return cdnName;
3889
+ }
3890
+ });
3891
+ Object.defineProperty(exports, "defaultCdnClients", {
3892
+ enumerable: true,
3893
+ get: function() {
3894
+ return defaultCdnClients;
3895
+ }
3896
+ });
3897
+ Object.defineProperty(exports, "defaultClients", {
3898
+ enumerable: true,
3899
+ get: function() {
3900
+ return defaultClients;
3901
+ }
3902
+ });
3903
+ Object.defineProperty(exports, "deploy", {
3904
+ enumerable: true,
3905
+ get: function() {
3906
+ return deploy;
3907
+ }
3908
+ });
3909
+
3910
+ //# sourceMappingURL=deploy-DpQ_4Pu1.cjs.map