@geekmidas/cli 10.0.0-alpha.16 → 10.0.0-alpha.161

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