@geekmidas/cli 10.0.0-alpha.17 → 10.0.0-alpha.171

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