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

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