@geekmidas/cli 10.0.0-alpha.13 → 10.0.0-alpha.130

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