@geekmidas/cli 10.0.0-alpha.98 → 10.0.0

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 (684) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/FUNCTION_CRON_SUPPORT.md +266 -0
  3. package/README.md +533 -382
  4. package/bin/gkm.mjs +2 -16
  5. package/dist/CachedStateProvider-BdX7klRc.cjs +3 -0
  6. package/dist/CachedStateProvider-CzyFct42.mjs +54 -0
  7. package/dist/CachedStateProvider-CzyFct42.mjs.map +1 -0
  8. package/dist/CachedStateProvider-GcGziXh1.mjs +3 -0
  9. package/dist/CachedStateProvider-klLWZXWF.cjs +60 -0
  10. package/dist/CachedStateProvider-klLWZXWF.cjs.map +1 -0
  11. package/dist/{HostingerProvider-BNpS9aRJ.mjs → HostingerProvider-B2ZYz7Yc.mjs} +26 -31
  12. package/dist/HostingerProvider-B2ZYz7Yc.mjs.map +1 -0
  13. package/dist/{HostingerProvider-DR1iws1P.cjs → HostingerProvider-CrHfsgz9.cjs} +26 -31
  14. package/dist/HostingerProvider-CrHfsgz9.cjs.map +1 -0
  15. package/dist/LocalStateProvider-CP49rjzt.mjs +42 -0
  16. package/dist/LocalStateProvider-CP49rjzt.mjs.map +1 -0
  17. package/dist/LocalStateProvider-CalzNfNA.cjs +43 -0
  18. package/dist/LocalStateProvider-CalzNfNA.cjs.map +1 -0
  19. package/dist/{Route53Provider-Bllus2NR.cjs → Route53Provider-DwgXiLxt.cjs} +22 -21
  20. package/dist/Route53Provider-DwgXiLxt.cjs.map +1 -0
  21. package/dist/{Route53Provider-QXxjkZO1.mjs → Route53Provider-tlgBzrRQ.mjs} +13 -13
  22. package/dist/Route53Provider-tlgBzrRQ.mjs.map +1 -0
  23. package/dist/SSMStateProvider-BlrTiV5m.mjs +66 -0
  24. package/dist/SSMStateProvider-BlrTiV5m.mjs.map +1 -0
  25. package/dist/SSMStateProvider-Bt6r8CTL.cjs +66 -0
  26. package/dist/SSMStateProvider-Bt6r8CTL.cjs.map +1 -0
  27. package/dist/{backup-provisioner-oDEsPj02.cjs → backup-provisioner-B3HBN-2k.cjs} +20 -22
  28. package/dist/backup-provisioner-B3HBN-2k.cjs.map +1 -0
  29. package/dist/{backup-provisioner-C8DnCmxK.mjs → backup-provisioner-Xunq-p_8.mjs} +9 -12
  30. package/dist/backup-provisioner-Xunq-p_8.mjs.map +1 -0
  31. package/dist/bundler-DkA4qzUD.mjs +135 -0
  32. package/dist/bundler-DkA4qzUD.mjs.map +1 -0
  33. package/dist/bundler-Dufq3uvI.cjs +136 -0
  34. package/dist/bundler-Dufq3uvI.cjs.map +1 -0
  35. package/dist/{rolldown-runtime-C0BPl7ul.cjs → chunk-CUT6urMc.cjs} +10 -23
  36. package/dist/chunk-Duj1WY3L.mjs +7 -0
  37. package/dist/config-Bbu1JKvf.mjs +211 -0
  38. package/dist/config-Bbu1JKvf.mjs.map +1 -0
  39. package/dist/config-DujV8DbR.cjs +253 -0
  40. package/dist/config-DujV8DbR.cjs.map +1 -0
  41. package/dist/config.cjs +10 -421
  42. package/dist/config.d.cts +120 -4
  43. package/dist/config.d.cts.map +1 -0
  44. package/dist/config.d.mts +120 -4
  45. package/dist/config.d.mts.map +1 -0
  46. package/dist/config.mjs +3 -405
  47. package/dist/credentials-C8DWtnMY.cjs +174 -0
  48. package/dist/credentials-C8DWtnMY.cjs.map +1 -0
  49. package/dist/credentials-s1kLcIzK.mjs +126 -0
  50. package/dist/credentials-s1kLcIzK.mjs.map +1 -0
  51. package/dist/deploy/sniffer-envkit-patch.cjs +10 -18
  52. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  53. package/dist/deploy/sniffer-envkit-patch.d.cts +2 -0
  54. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  55. package/dist/deploy/sniffer-envkit-patch.d.mts +2 -0
  56. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  57. package/dist/deploy/sniffer-envkit-patch.mjs +2 -10
  58. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  59. package/dist/deploy/sniffer-hooks.cjs +7 -13
  60. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  61. package/dist/deploy/sniffer-hooks.d.cts +2 -1
  62. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  63. package/dist/deploy/sniffer-hooks.d.mts +2 -1
  64. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  65. package/dist/deploy/sniffer-hooks.mjs +3 -10
  66. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  67. package/dist/deploy/sniffer-loader.cjs +7 -16
  68. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  69. package/dist/deploy/sniffer-loader.d.cts +1 -1
  70. package/dist/deploy/sniffer-loader.d.mts +1 -1
  71. package/dist/deploy/sniffer-loader.mjs +3 -14
  72. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  73. package/dist/deploy/sniffer-routes-worker.cjs +13 -17
  74. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  75. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  76. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  77. package/dist/deploy/sniffer-routes-worker.mjs +6 -10
  78. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  79. package/dist/deploy/sniffer-worker.cjs +6 -15
  80. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  81. package/dist/deploy/sniffer-worker.d.cts +3 -1
  82. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  83. package/dist/deploy/sniffer-worker.d.mts +3 -1
  84. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  85. package/dist/deploy/sniffer-worker.mjs +4 -15
  86. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  87. package/dist/dokploy-api-BPYkG-ZZ.cjs +3 -0
  88. package/dist/dokploy-api-BiSzWM4v.mjs +3 -0
  89. package/dist/dokploy-api-CqOIKHme.cjs +609 -0
  90. package/dist/dokploy-api-CqOIKHme.cjs.map +1 -0
  91. package/dist/dokploy-api-sfZFlWuE.mjs +597 -0
  92. package/dist/dokploy-api-sfZFlWuE.mjs.map +1 -0
  93. package/dist/encryption-BVS7Vmzs.cjs +4 -0
  94. package/dist/encryption-Bd_m4q3g.mjs +3 -0
  95. package/dist/encryption-CO5Q4Bhf.mjs +42 -0
  96. package/dist/encryption-CO5Q4Bhf.mjs.map +1 -0
  97. package/dist/encryption-MfXAiFTm.cjs +54 -0
  98. package/dist/encryption-MfXAiFTm.cjs.map +1 -0
  99. package/dist/fullstack-secrets-BYzi6Hwl.cjs +402 -0
  100. package/dist/fullstack-secrets-BYzi6Hwl.cjs.map +1 -0
  101. package/dist/fullstack-secrets-l8s3II_H.mjs +336 -0
  102. package/dist/fullstack-secrets-l8s3II_H.mjs.map +1 -0
  103. package/dist/index-CoVW_fFS.d.cts +1737 -0
  104. package/dist/index-CoVW_fFS.d.cts.map +1 -0
  105. package/dist/index-oWibAYQY.d.mts +1737 -0
  106. package/dist/index-oWibAYQY.d.mts.map +1 -0
  107. package/dist/index.cjs +11337 -10263
  108. package/dist/index.cjs.map +1 -1
  109. package/dist/index.d.cts +1 -1
  110. package/dist/index.d.mts +1 -1
  111. package/dist/index.mjs +11303 -10217
  112. package/dist/index.mjs.map +1 -1
  113. package/dist/openapi-BzNOC7_i.cjs +1931 -0
  114. package/dist/openapi-BzNOC7_i.cjs.map +1 -0
  115. package/dist/openapi-Cfwi0fqF.mjs +1883 -0
  116. package/dist/openapi-Cfwi0fqF.mjs.map +1 -0
  117. package/dist/openapi-react-query-C4iIvpPf.mjs +167 -0
  118. package/dist/openapi-react-query-C4iIvpPf.mjs.map +1 -0
  119. package/dist/openapi-react-query-CYWik72n.cjs +173 -0
  120. package/dist/openapi-react-query-CYWik72n.cjs.map +1 -0
  121. package/dist/openapi-react-query.cjs +4 -0
  122. package/dist/openapi-react-query.d.cts +11 -0
  123. package/dist/openapi-react-query.d.cts.map +1 -0
  124. package/dist/openapi-react-query.d.mts +11 -0
  125. package/dist/openapi-react-query.d.mts.map +1 -0
  126. package/dist/openapi-react-query.mjs +4 -0
  127. package/dist/openapi.cjs +7 -214
  128. package/dist/openapi.d.cts +15 -72
  129. package/dist/openapi.d.cts.map +1 -1
  130. package/dist/openapi.d.mts +15 -72
  131. package/dist/openapi.d.mts.map +1 -1
  132. package/dist/openapi.mjs +4 -208
  133. package/dist/{reconcile--I7V4Klj.mjs → reconcile-B2FoJE0a.mjs} +8 -6
  134. package/dist/reconcile-B2FoJE0a.mjs.map +1 -0
  135. package/dist/{reconcile-CuCQBa5-.cjs → reconcile-BzqKJ2Rt.cjs} +8 -6
  136. package/dist/reconcile-BzqKJ2Rt.cjs.map +1 -0
  137. package/dist/setup-DDXUXzzl.mjs +765 -0
  138. package/dist/setup-DDXUXzzl.mjs.map +1 -0
  139. package/dist/setup-DLwhfyt-.cjs +8 -0
  140. package/dist/setup-Dh-B7YTX.mjs +8 -0
  141. package/dist/setup-WZ-xqAQO.cjs +849 -0
  142. package/dist/setup-WZ-xqAQO.cjs.map +1 -0
  143. package/dist/storage-B1wvztiJ.cjs +363 -0
  144. package/dist/storage-B1wvztiJ.cjs.map +1 -0
  145. package/dist/storage-Cs4WBsc4.mjs +3 -0
  146. package/dist/storage-DOEtT2Hr.cjs +7 -0
  147. package/dist/storage-dbb9RyBl.mjs +297 -0
  148. package/dist/storage-dbb9RyBl.mjs.map +1 -0
  149. package/dist/sync-B5UHXwRM.mjs +3 -0
  150. package/dist/sync-BLA94rgC.cjs +4 -0
  151. package/dist/sync-CSooqRQ8.mjs +76 -0
  152. package/dist/sync-CSooqRQ8.mjs.map +1 -0
  153. package/dist/sync-o_CtEbvR.cjs +93 -0
  154. package/dist/sync-o_CtEbvR.cjs.map +1 -0
  155. package/dist/types-B3GQUg3k.d.mts +280 -0
  156. package/dist/types-B3GQUg3k.d.mts.map +1 -0
  157. package/dist/types-BWQDiooe.d.cts +280 -0
  158. package/dist/types-BWQDiooe.d.cts.map +1 -0
  159. package/dist/workspace/index.cjs +4 -12
  160. package/dist/workspace/index.d.cts +3 -3
  161. package/dist/workspace/index.d.mts +3 -3
  162. package/dist/workspace/index.mjs +3 -2
  163. package/dist/workspace-CQTT7HJQ.cjs +4361 -0
  164. package/dist/workspace-CQTT7HJQ.cjs.map +1 -0
  165. package/dist/workspace-D-37Ylqo.mjs +4236 -0
  166. package/dist/workspace-D-37Ylqo.mjs.map +1 -0
  167. package/docs/OPENAPI_TYPESCRIPT_DESIGN.md +408 -0
  168. package/docs/dev-server-resilience-design.md +189 -0
  169. package/docs/manifest-refactor-design.md +287 -0
  170. package/examples/cron-example.ts +45 -0
  171. package/examples/env.ts +33 -0
  172. package/examples/function-example.ts +40 -0
  173. package/examples/gkm.config.json +22 -0
  174. package/examples/gkm.config.ts +14 -0
  175. package/examples/gkm.minimal.config.json +7 -0
  176. package/examples/gkm.production.config.json +27 -0
  177. package/examples/logger.ts +10 -0
  178. package/package.json +37 -87
  179. package/scripts/sync-versions.ts +108 -0
  180. package/src/__tests__/EndpointGenerator.hooks.spec.ts +204 -0
  181. package/src/__tests__/config.spec.ts +422 -0
  182. package/src/__tests__/loadEnvFiles.spec.ts +131 -0
  183. package/src/__tests__/normalizeHooksConfig.spec.ts +63 -0
  184. package/src/__tests__/openapi-react-query.spec.ts +506 -0
  185. package/src/__tests__/openapi.spec.ts +625 -0
  186. package/src/__tests__/test-helpers.ts +180 -0
  187. package/src/auth/__tests__/credentials.spec.ts +331 -0
  188. package/src/auth/__tests__/index.spec.ts +237 -0
  189. package/src/auth/credentials.ts +286 -0
  190. package/src/auth/index.ts +233 -0
  191. package/src/build/__tests__/bundler.spec.ts +446 -0
  192. package/src/build/__tests__/endpoint-analyzer.spec.ts +623 -0
  193. package/src/build/__tests__/handler-templates.spec.ts +1287 -0
  194. package/src/build/__tests__/index-new.spec.ts +550 -0
  195. package/src/build/__tests__/manifests.spec.ts +583 -0
  196. package/src/build/__tests__/partitions.spec.ts +110 -0
  197. package/src/build/__tests__/workspace-build.spec.ts +215 -0
  198. package/src/build/bundler.ts +256 -0
  199. package/src/build/endpoint-analyzer.ts +236 -0
  200. package/src/build/handler-templates.ts +1253 -0
  201. package/src/build/index.ts +616 -0
  202. package/src/build/manifests.ts +285 -0
  203. package/src/build/partitions.ts +58 -0
  204. package/src/build/providerResolver.ts +184 -0
  205. package/src/build/types.ts +104 -0
  206. package/src/config.ts +330 -0
  207. package/src/credentials/__tests__/fullDockerPorts.spec.ts +144 -0
  208. package/src/credentials/__tests__/helpers.ts +112 -0
  209. package/src/credentials/__tests__/prepareEntryCredentials.spec.ts +125 -0
  210. package/src/credentials/__tests__/readonlyDockerPorts.spec.ts +190 -0
  211. package/src/credentials/__tests__/workspaceCredentials.spec.ts +209 -0
  212. package/src/credentials/index.ts +843 -0
  213. package/src/debug.ts +68 -0
  214. package/src/deploy/CachedStateProvider.ts +86 -0
  215. package/src/deploy/LocalStateProvider.ts +57 -0
  216. package/src/deploy/SSMStateProvider.ts +117 -0
  217. package/src/deploy/StateProvider.ts +175 -0
  218. package/src/deploy/__tests__/CachedStateProvider.spec.ts +235 -0
  219. package/src/deploy/__tests__/HostingerProvider.spec.ts +347 -0
  220. package/src/deploy/__tests__/LocalStateProvider.spec.ts +130 -0
  221. package/src/deploy/__tests__/Route53Provider.spec.ts +425 -0
  222. package/src/deploy/__tests__/SSMStateProvider.spec.ts +201 -0
  223. package/src/deploy/__tests__/__fixtures__/entry-apps/async-entry.ts +24 -0
  224. package/src/deploy/__tests__/__fixtures__/entry-apps/nested-config-entry.ts +24 -0
  225. package/src/deploy/__tests__/__fixtures__/entry-apps/no-env-entry.ts +12 -0
  226. package/src/deploy/__tests__/__fixtures__/entry-apps/simple-entry.ts +14 -0
  227. package/src/deploy/__tests__/__fixtures__/entry-apps/throwing-entry.ts +16 -0
  228. package/src/deploy/__tests__/__fixtures__/env-parsers/non-function-export.ts +10 -0
  229. package/src/deploy/__tests__/__fixtures__/env-parsers/optional-env-parser.ts +21 -0
  230. package/src/deploy/__tests__/__fixtures__/env-parsers/parseable-env-parser.ts +18 -0
  231. package/src/deploy/__tests__/__fixtures__/env-parsers/throwing-env-parser.ts +16 -0
  232. package/src/deploy/__tests__/__fixtures__/env-parsers/valid-env-parser.ts +16 -0
  233. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/auth.ts +16 -0
  234. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/health.ts +13 -0
  235. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/users.ts +15 -0
  236. package/src/deploy/__tests__/__fixtures__/route-apps/services.ts +55 -0
  237. package/src/deploy/__tests__/backup-provisioner.spec.ts +428 -0
  238. package/src/deploy/__tests__/createDnsProvider.spec.ts +195 -0
  239. package/src/deploy/__tests__/createStateProvider.spec.ts +126 -0
  240. package/src/deploy/__tests__/dns-orchestration.spec.ts +192 -0
  241. package/src/deploy/__tests__/dns-verification.spec.ts +229 -0
  242. package/src/deploy/__tests__/docker.spec.ts +149 -0
  243. package/src/deploy/__tests__/dokploy-api.spec.ts +697 -0
  244. package/src/deploy/__tests__/dokploy.spec.ts +435 -0
  245. package/src/deploy/__tests__/domain.spec.ts +235 -0
  246. package/src/deploy/__tests__/env-resolver.spec.ts +903 -0
  247. package/src/deploy/__tests__/index.spec.ts +1091 -0
  248. package/src/deploy/__tests__/init.spec.ts +793 -0
  249. package/src/deploy/__tests__/secrets.spec.ts +303 -0
  250. package/src/deploy/__tests__/sniffer.spec.ts +838 -0
  251. package/src/deploy/__tests__/state-e2e.spec.ts +387 -0
  252. package/src/deploy/__tests__/state.spec.ts +876 -0
  253. package/src/deploy/__tests__/undeploy.spec.ts +758 -0
  254. package/src/deploy/backup-provisioner.ts +316 -0
  255. package/src/deploy/dns/DnsProvider.ts +201 -0
  256. package/src/deploy/dns/HostingerProvider.ts +174 -0
  257. package/src/deploy/dns/Route53Provider.ts +340 -0
  258. package/src/deploy/dns/hostinger-api.ts +261 -0
  259. package/src/deploy/dns/index.ts +627 -0
  260. package/src/deploy/docker.ts +260 -0
  261. package/src/deploy/dokploy-api.ts +1101 -0
  262. package/src/deploy/dokploy.ts +177 -0
  263. package/src/deploy/domain.ts +134 -0
  264. package/src/deploy/env-resolver.ts +305 -0
  265. package/src/deploy/index.ts +2094 -0
  266. package/src/deploy/init.ts +427 -0
  267. package/src/deploy/secrets.ts +187 -0
  268. package/src/deploy/sniffer-envkit-patch.ts +61 -0
  269. package/src/deploy/sniffer-hooks.ts +57 -0
  270. package/src/deploy/sniffer-loader.ts +28 -0
  271. package/src/deploy/sniffer-routes-worker.ts +104 -0
  272. package/src/deploy/sniffer-worker.ts +75 -0
  273. package/src/deploy/sniffer.ts +578 -0
  274. package/src/deploy/state-commands.ts +274 -0
  275. package/src/deploy/state.ts +482 -0
  276. package/src/deploy/types.ts +102 -0
  277. package/src/deploy/undeploy.ts +407 -0
  278. package/src/dev/__tests__/entry-integration.spec.ts +347 -0
  279. package/src/dev/__tests__/entry.spec.ts +144 -0
  280. package/src/dev/__tests__/index.spec.ts +2084 -0
  281. package/src/dev/index.ts +1649 -0
  282. package/src/docker/__tests__/compose.spec.ts +1142 -0
  283. package/src/docker/__tests__/templates.spec.ts +694 -0
  284. package/src/docker/compose.ts +812 -0
  285. package/src/docker/index.ts +523 -0
  286. package/src/docker/templates.ts +1067 -0
  287. package/src/exec/index.ts +118 -0
  288. package/src/generators/CronGenerator.ts +105 -0
  289. package/src/generators/EndpointGenerator.ts +954 -0
  290. package/src/generators/FunctionGenerator.ts +117 -0
  291. package/src/generators/Generator.ts +147 -0
  292. package/src/generators/OpenApiTsGenerator.ts +821 -0
  293. package/src/generators/QueueGenerator.ts +245 -0
  294. package/src/generators/SubscriberGenerator.ts +282 -0
  295. package/src/generators/TopicGenerator.ts +45 -0
  296. package/src/generators/__tests__/CronGenerator.spec.ts +445 -0
  297. package/src/generators/__tests__/EndpointGenerator.spec.ts +544 -0
  298. package/src/generators/__tests__/FunctionGenerator.spec.ts +256 -0
  299. package/src/generators/__tests__/Generator.bustCache.spec.ts +72 -0
  300. package/src/generators/__tests__/OpenApiTsGenerator.registry.spec.ts +98 -0
  301. package/src/generators/__tests__/OpenApiTsGenerator.responseType.spec.ts +56 -0
  302. package/src/generators/__tests__/QueueGenerator.spec.ts +141 -0
  303. package/src/generators/__tests__/SubscriberGenerator.spec.ts +410 -0
  304. package/src/generators/index.ts +11 -0
  305. package/src/index.ts +972 -0
  306. package/src/init/__tests__/generators.spec.ts +1072 -0
  307. package/src/init/__tests__/init.spec.ts +577 -0
  308. package/src/init/__tests__/utils.spec.ts +104 -0
  309. package/src/init/generators/auth.ts +225 -0
  310. package/src/init/generators/config.ts +316 -0
  311. package/src/init/generators/docker.ts +388 -0
  312. package/src/init/generators/env.ts +62 -0
  313. package/src/init/generators/index.ts +6 -0
  314. package/src/init/generators/mobile-expo.ts +576 -0
  315. package/src/init/generators/models.ts +153 -0
  316. package/src/init/generators/monorepo.ts +475 -0
  317. package/src/init/generators/package.ts +95 -0
  318. package/src/init/generators/source.ts +15 -0
  319. package/src/init/generators/test.ts +178 -0
  320. package/src/init/generators/ui.ts +1473 -0
  321. package/src/init/generators/web-tanstack.ts +348 -0
  322. package/src/init/generators/web.ts +363 -0
  323. package/src/init/index.ts +542 -0
  324. package/src/init/templates/api.ts +404 -0
  325. package/src/init/templates/index.ts +342 -0
  326. package/src/init/templates/minimal.ts +207 -0
  327. package/src/init/templates/serverless.ts +148 -0
  328. package/src/init/templates/worker.ts +216 -0
  329. package/src/init/utils.ts +197 -0
  330. package/src/init/versions.ts +52 -0
  331. package/src/openapi-react-query.ts +288 -0
  332. package/src/openapi.ts +259 -0
  333. package/src/secrets/__tests__/encryption.spec.ts +226 -0
  334. package/src/secrets/__tests__/generator.spec.ts +575 -0
  335. package/src/secrets/__tests__/index.spec.ts +91 -0
  336. package/src/secrets/__tests__/reconcile.spec.ts +123 -0
  337. package/src/secrets/__tests__/storage.spec.ts +645 -0
  338. package/src/secrets/encryption.ts +91 -0
  339. package/src/secrets/generator.ts +329 -0
  340. package/src/secrets/index.ts +417 -0
  341. package/src/secrets/keystore.ts +144 -0
  342. package/src/secrets/reconcile.ts +53 -0
  343. package/src/secrets/storage.ts +337 -0
  344. package/src/secrets/sync.ts +136 -0
  345. package/src/secrets/types.ts +70 -0
  346. package/src/setup/__tests__/auto-setup.spec.ts +147 -0
  347. package/src/setup/__tests__/reconcile-secrets.spec.ts +439 -0
  348. package/src/setup/fullstack-secrets.ts +140 -0
  349. package/src/setup/index.ts +411 -0
  350. package/src/test/__tests__/__fixtures__/workspace.ts +104 -0
  351. package/src/test/__tests__/api.spec.ts +199 -0
  352. package/src/test/__tests__/auth.spec.ts +162 -0
  353. package/src/test/__tests__/index.spec.ts +502 -0
  354. package/src/test/__tests__/web.spec.ts +210 -0
  355. package/src/test/index.ts +198 -0
  356. package/src/types.ts +363 -0
  357. package/src/upgrade/__tests__/index.spec.ts +354 -0
  358. package/src/upgrade/index.ts +253 -0
  359. package/src/workspace/__tests__/client-generator.spec.ts +326 -0
  360. package/src/workspace/__tests__/index.spec.ts +766 -0
  361. package/src/workspace/__tests__/publicEnv.spec.ts +64 -0
  362. package/src/workspace/__tests__/schema.spec.ts +737 -0
  363. package/src/workspace/__tests__/type-inference.spec.ts +251 -0
  364. package/src/workspace/client-generator.ts +109 -0
  365. package/src/workspace/index.ts +433 -0
  366. package/src/workspace/publicEnv.ts +57 -0
  367. package/src/workspace/schema.ts +861 -0
  368. package/src/workspace/types.ts +943 -0
  369. package/tsconfig.json +9 -0
  370. package/tsdown.config.ts +22 -0
  371. package/bin/adjacent-tsconfig.mjs +0 -97
  372. package/bin/owning-tsconfig-jsx-register.mjs +0 -18
  373. package/bin/owning-tsconfig-jsx.mjs +0 -108
  374. package/dist/EndpointGenerator-Bor2tZCm.mjs +0 -1031
  375. package/dist/EndpointGenerator-Bor2tZCm.mjs.map +0 -1
  376. package/dist/EndpointGenerator-De03t1hd.cjs +0 -1090
  377. package/dist/EndpointGenerator-De03t1hd.cjs.map +0 -1
  378. package/dist/GoDaddyProvider-C2fK-zeQ.mjs +0 -388
  379. package/dist/GoDaddyProvider-C2fK-zeQ.mjs.map +0 -1
  380. package/dist/GoDaddyProvider-SLlyDwD1.cjs +0 -388
  381. package/dist/GoDaddyProvider-SLlyDwD1.cjs.map +0 -1
  382. package/dist/HostingerProvider-BNpS9aRJ.mjs.map +0 -1
  383. package/dist/HostingerProvider-DR1iws1P.cjs.map +0 -1
  384. package/dist/LegacyStateStore-CAvxM8U5.cjs +0 -124
  385. package/dist/LegacyStateStore-CAvxM8U5.cjs.map +0 -1
  386. package/dist/LegacyStateStore-D9QDWCst.mjs +0 -124
  387. package/dist/LegacyStateStore-D9QDWCst.mjs.map +0 -1
  388. package/dist/LocalStateStore-DPQSqkSb.mjs +0 -167
  389. package/dist/LocalStateStore-DPQSqkSb.mjs.map +0 -1
  390. package/dist/LocalStateStore-QcrdjCl6.cjs +0 -178
  391. package/dist/LocalStateStore-QcrdjCl6.cjs.map +0 -1
  392. package/dist/OpenApiTsGenerator-CS_RtWOz.cjs +0 -541
  393. package/dist/OpenApiTsGenerator-CS_RtWOz.cjs.map +0 -1
  394. package/dist/OpenApiTsGenerator-DWAF-7Fu.mjs +0 -536
  395. package/dist/OpenApiTsGenerator-DWAF-7Fu.mjs.map +0 -1
  396. package/dist/Route53Provider-Bllus2NR.cjs.map +0 -1
  397. package/dist/Route53Provider-QXxjkZO1.mjs.map +0 -1
  398. package/dist/S3StateStore-C16tVikU.cjs +0 -222
  399. package/dist/S3StateStore-C16tVikU.cjs.map +0 -1
  400. package/dist/S3StateStore-jorgKaee.mjs +0 -223
  401. package/dist/S3StateStore-jorgKaee.mjs.map +0 -1
  402. package/dist/SSMStateStore-Dvjt_INw.mjs +0 -205
  403. package/dist/SSMStateStore-Dvjt_INw.mjs.map +0 -1
  404. package/dist/SSMStateStore-mPAEr2P2.cjs +0 -204
  405. package/dist/SSMStateStore-mPAEr2P2.cjs.map +0 -1
  406. package/dist/SubscriberGenerator-CyN2VF5X.mjs +0 -449
  407. package/dist/SubscriberGenerator-CyN2VF5X.mjs.map +0 -1
  408. package/dist/SubscriberGenerator-Dvz7EzqK.cjs +0 -490
  409. package/dist/SubscriberGenerator-Dvz7EzqK.cjs.map +0 -1
  410. package/dist/add-CZIIsTcv.mjs +0 -718
  411. package/dist/add-CZIIsTcv.mjs.map +0 -1
  412. package/dist/add-SRk65Udu.cjs +0 -720
  413. package/dist/add-SRk65Udu.cjs.map +0 -1
  414. package/dist/appPorts-C9z9Pzn9.mjs +0 -223
  415. package/dist/appPorts-C9z9Pzn9.mjs.map +0 -1
  416. package/dist/appPorts-Cu79hJF6.cjs +0 -264
  417. package/dist/appPorts-Cu79hJF6.cjs.map +0 -1
  418. package/dist/aws-8QQ8n-t6.mjs +0 -89
  419. package/dist/aws-8QQ8n-t6.mjs.map +0 -1
  420. package/dist/aws-DY9NqQIT.cjs +0 -100
  421. package/dist/aws-DY9NqQIT.cjs.map +0 -1
  422. package/dist/awsStore-Bx5nCFnS.mjs +0 -121
  423. package/dist/awsStore-Bx5nCFnS.mjs.map +0 -1
  424. package/dist/awsStore-u3ehhMoY.cjs +0 -138
  425. package/dist/awsStore-u3ehhMoY.cjs.map +0 -1
  426. package/dist/backup-provisioner-C8DnCmxK.mjs.map +0 -1
  427. package/dist/backup-provisioner-oDEsPj02.cjs.map +0 -1
  428. package/dist/bundler-B0Pj5FXT.cjs +0 -169
  429. package/dist/bundler-B0Pj5FXT.cjs.map +0 -1
  430. package/dist/bundler-DxJ-cIEt.mjs +0 -169
  431. package/dist/bundler-DxJ-cIEt.mjs.map +0 -1
  432. package/dist/cli-CRDJWWmZ.cjs +0 -73
  433. package/dist/cli-CRDJWWmZ.cjs.map +0 -1
  434. package/dist/cli-CV85bY3-.mjs +0 -73
  435. package/dist/cli-CV85bY3-.mjs.map +0 -1
  436. package/dist/compose-CQQRRJC3.mjs +0 -1511
  437. package/dist/compose-CQQRRJC3.mjs.map +0 -1
  438. package/dist/compose-DMY4ouEk.cjs +0 -1558
  439. package/dist/compose-DMY4ouEk.cjs.map +0 -1
  440. package/dist/config-CS76CzXM.d.cts +0 -269
  441. package/dist/config-CS76CzXM.d.cts.map +0 -1
  442. package/dist/config-pBzLfNef.d.mts +0 -269
  443. package/dist/config-pBzLfNef.d.mts.map +0 -1
  444. package/dist/config.cjs.map +0 -1
  445. package/dist/config.mjs.map +0 -1
  446. package/dist/credentialSchemas-BJFvfkaz.mjs +0 -237
  447. package/dist/credentialSchemas-BJFvfkaz.mjs.map +0 -1
  448. package/dist/credentialSchemas-CAPKFkrG.cjs +0 -272
  449. package/dist/credentialSchemas-CAPKFkrG.cjs.map +0 -1
  450. package/dist/credentials-B5N5yKk6.mjs +0 -267
  451. package/dist/credentials-B5N5yKk6.mjs.map +0 -1
  452. package/dist/credentials-Zqr3QQYB.cjs +0 -350
  453. package/dist/credentials-Zqr3QQYB.cjs.map +0 -1
  454. package/dist/databases-BeGP5eDh.mjs +0 -495
  455. package/dist/databases-BeGP5eDh.mjs.map +0 -1
  456. package/dist/databases-DGALFDG3.cjs +0 -598
  457. package/dist/databases-DGALFDG3.cjs.map +0 -1
  458. package/dist/define-6poNqm5O.mjs +0 -106
  459. package/dist/define-6poNqm5O.mjs.map +0 -1
  460. package/dist/define-crmMcXFS.cjs +0 -153
  461. package/dist/define-crmMcXFS.cjs.map +0 -1
  462. package/dist/deploy/public.cjs +0 -211
  463. package/dist/deploy/public.cjs.map +0 -1
  464. package/dist/deploy/public.d.cts +0 -664
  465. package/dist/deploy/public.d.cts.map +0 -1
  466. package/dist/deploy/public.d.mts +0 -664
  467. package/dist/deploy/public.d.mts.map +0 -1
  468. package/dist/deploy/public.mjs +0 -144
  469. package/dist/deploy/public.mjs.map +0 -1
  470. package/dist/deploy/sniffer-envparser-worker.cjs +0 -54
  471. package/dist/deploy/sniffer-envparser-worker.cjs.map +0 -1
  472. package/dist/deploy/sniffer-envparser-worker.d.cts +0 -1
  473. package/dist/deploy/sniffer-envparser-worker.d.mts +0 -1
  474. package/dist/deploy/sniffer-envparser-worker.mjs +0 -55
  475. package/dist/deploy/sniffer-envparser-worker.mjs.map +0 -1
  476. package/dist/deploy-277jek46.cjs +0 -2068
  477. package/dist/deploy-277jek46.cjs.map +0 -1
  478. package/dist/deploy-Dw8g3sLY.mjs +0 -2019
  479. package/dist/deploy-Dw8g3sLY.mjs.map +0 -1
  480. package/dist/derive-B4vDpzgP.mjs +0 -150
  481. package/dist/derive-B4vDpzgP.mjs.map +0 -1
  482. package/dist/derive-DAbo49sm.cjs +0 -161
  483. package/dist/derive-DAbo49sm.cjs.map +0 -1
  484. package/dist/discover-CU1LjCOf.d.cts +0 -108
  485. package/dist/discover-CU1LjCOf.d.cts.map +0 -1
  486. package/dist/discover-DJCCgimv.d.mts +0 -108
  487. package/dist/discover-DJCCgimv.d.mts.map +0 -1
  488. package/dist/discover-DPgu-ScS.cjs +0 -600
  489. package/dist/discover-DPgu-ScS.cjs.map +0 -1
  490. package/dist/discover-qjFapetL.mjs +0 -527
  491. package/dist/discover-qjFapetL.mjs.map +0 -1
  492. package/dist/dns-4RAiVFa7.cjs +0 -55
  493. package/dist/dns-4RAiVFa7.cjs.map +0 -1
  494. package/dist/dns-CU22K_i0.mjs +0 -44
  495. package/dist/dns-CU22K_i0.mjs.map +0 -1
  496. package/dist/dns-Dhjbnjgl.cjs +0 -663
  497. package/dist/dns-Dhjbnjgl.cjs.map +0 -1
  498. package/dist/dns-LqWzPb8l.mjs +0 -610
  499. package/dist/dns-LqWzPb8l.mjs.map +0 -1
  500. package/dist/dokploy-D_uCbZQ7.mjs +0 -38
  501. package/dist/dokploy-D_uCbZQ7.mjs.map +0 -1
  502. package/dist/dokploy-Dw4oCXqR.cjs +0 -38
  503. package/dist/dokploy-Dw4oCXqR.cjs.map +0 -1
  504. package/dist/drivers-CTaWrA_L.mjs +0 -177
  505. package/dist/drivers-CTaWrA_L.mjs.map +0 -1
  506. package/dist/drivers-DDojgzz0.cjs +0 -200
  507. package/dist/drivers-DDojgzz0.cjs.map +0 -1
  508. package/dist/emit-C1e8qD08.mjs +0 -193
  509. package/dist/emit-C1e8qD08.mjs.map +0 -1
  510. package/dist/emit-Dmc1nvdS.cjs +0 -210
  511. package/dist/emit-Dmc1nvdS.cjs.map +0 -1
  512. package/dist/encryption-C0uKYE9v.mjs +0 -89
  513. package/dist/encryption-C0uKYE9v.mjs.map +0 -1
  514. package/dist/encryption-CtVPHWWq.cjs +0 -90
  515. package/dist/encryption-CtVPHWWq.cjs.map +0 -1
  516. package/dist/engine-BE5PdE8S.mjs +0 -3080
  517. package/dist/engine-BE5PdE8S.mjs.map +0 -1
  518. package/dist/engine-HI8aLw1M.cjs +0 -3193
  519. package/dist/engine-HI8aLw1M.cjs.map +0 -1
  520. package/dist/errors-D8Gwp5kU.mjs +0 -23
  521. package/dist/errors-D8Gwp5kU.mjs.map +0 -1
  522. package/dist/errors-DMC4Umsb.cjs +0 -34
  523. package/dist/errors-DMC4Umsb.cjs.map +0 -1
  524. package/dist/github-BCdfZ9zO.cjs +0 -818
  525. package/dist/github-BCdfZ9zO.cjs.map +0 -1
  526. package/dist/github-CT3X720_.mjs +0 -818
  527. package/dist/github-CT3X720_.mjs.map +0 -1
  528. package/dist/index-DKtB01YC.d.cts +0 -190
  529. package/dist/index-DKtB01YC.d.cts.map +0 -1
  530. package/dist/index-ZAUrXH6Q.d.mts +0 -190
  531. package/dist/index-ZAUrXH6Q.d.mts.map +0 -1
  532. package/dist/local-BwC2v2Y8.mjs +0 -224
  533. package/dist/local-BwC2v2Y8.mjs.map +0 -1
  534. package/dist/local-DNhnkugT.cjs +0 -241
  535. package/dist/local-DNhnkugT.cjs.map +0 -1
  536. package/dist/migrate-CCZUgxMK.mjs +0 -266
  537. package/dist/migrate-CCZUgxMK.mjs.map +0 -1
  538. package/dist/migrate-Cs7kQxD5.cjs +0 -271
  539. package/dist/migrate-Cs7kQxD5.cjs.map +0 -1
  540. package/dist/migrate-DBGyoBvZ.cjs +0 -181
  541. package/dist/migrate-DBGyoBvZ.cjs.map +0 -1
  542. package/dist/migrate-DH-lOK3j.mjs +0 -181
  543. package/dist/migrate-DH-lOK3j.mjs.map +0 -1
  544. package/dist/openapi.cjs.map +0 -1
  545. package/dist/openapi.mjs.map +0 -1
  546. package/dist/projectBucket-BjeDcAYy.cjs +0 -206
  547. package/dist/projectBucket-BjeDcAYy.cjs.map +0 -1
  548. package/dist/projectBucket-DrkEht-j.mjs +0 -177
  549. package/dist/projectBucket-DrkEht-j.mjs.map +0 -1
  550. package/dist/provider-BqpjG9QM.cjs +0 -57
  551. package/dist/provider-BqpjG9QM.cjs.map +0 -1
  552. package/dist/provider-CEOKk8NS.mjs +0 -46
  553. package/dist/provider-CEOKk8NS.mjs.map +0 -1
  554. package/dist/ready-D3PIjx3S.cjs +0 -403
  555. package/dist/ready-D3PIjx3S.cjs.map +0 -1
  556. package/dist/ready-naOSJpeJ.mjs +0 -374
  557. package/dist/ready-naOSJpeJ.mjs.map +0 -1
  558. package/dist/reconcile/public.cjs +0 -7
  559. package/dist/reconcile/public.d.cts +0 -49
  560. package/dist/reconcile/public.d.cts.map +0 -1
  561. package/dist/reconcile/public.d.mts +0 -49
  562. package/dist/reconcile/public.d.mts.map +0 -1
  563. package/dist/reconcile/public.mjs +0 -3
  564. package/dist/reconcile--I7V4Klj.mjs.map +0 -1
  565. package/dist/reconcile-CuCQBa5-.cjs.map +0 -1
  566. package/dist/resolve-CScrqgdC.cjs +0 -316
  567. package/dist/resolve-CScrqgdC.cjs.map +0 -1
  568. package/dist/resolve-OfLaxaxY.mjs +0 -263
  569. package/dist/resolve-OfLaxaxY.mjs.map +0 -1
  570. package/dist/rollback-D7p4wJNO.cjs +0 -165
  571. package/dist/rollback-D7p4wJNO.cjs.map +0 -1
  572. package/dist/rollback-DQBSN-i7.mjs +0 -136
  573. package/dist/rollback-DQBSN-i7.mjs.map +0 -1
  574. package/dist/rolldown-runtime-BhDjJH2R.mjs +0 -15
  575. package/dist/run-BJLIerMM.mjs +0 -133
  576. package/dist/run-BJLIerMM.mjs.map +0 -1
  577. package/dist/run-fVZ-rLnc.cjs +0 -174
  578. package/dist/run-fVZ-rLnc.cjs.map +0 -1
  579. package/dist/runtime-BlHOVx8L.d.cts +0 -82
  580. package/dist/runtime-BlHOVx8L.d.cts.map +0 -1
  581. package/dist/runtime-DMq9C3KB.d.mts +0 -82
  582. package/dist/runtime-DMq9C3KB.d.mts.map +0 -1
  583. package/dist/s3-CUKzBBae.mjs +0 -215
  584. package/dist/s3-CUKzBBae.mjs.map +0 -1
  585. package/dist/s3-QQi4sNOQ.cjs +0 -215
  586. package/dist/s3-QQi4sNOQ.cjs.map +0 -1
  587. package/dist/sandbox/config-worker.cjs +0 -43
  588. package/dist/sandbox/config-worker.cjs.map +0 -1
  589. package/dist/sandbox/config-worker.d.cts +0 -1
  590. package/dist/sandbox/config-worker.d.mts +0 -1
  591. package/dist/sandbox/config-worker.mjs +0 -44
  592. package/dist/sandbox/config-worker.mjs.map +0 -1
  593. package/dist/sandbox/credentials-worker.cjs +0 -54
  594. package/dist/sandbox/credentials-worker.cjs.map +0 -1
  595. package/dist/sandbox/credentials-worker.d.cts +0 -1
  596. package/dist/sandbox/credentials-worker.d.mts +0 -1
  597. package/dist/sandbox/credentials-worker.mjs +0 -55
  598. package/dist/sandbox/credentials-worker.mjs.map +0 -1
  599. package/dist/sandbox/discover-worker.cjs +0 -47
  600. package/dist/sandbox/discover-worker.cjs.map +0 -1
  601. package/dist/sandbox/discover-worker.d.cts +0 -1
  602. package/dist/sandbox/discover-worker.d.mts +0 -1
  603. package/dist/sandbox/discover-worker.mjs +0 -48
  604. package/dist/sandbox/discover-worker.mjs.map +0 -1
  605. package/dist/sandbox/migrate-worker.cjs +0 -75
  606. package/dist/sandbox/migrate-worker.cjs.map +0 -1
  607. package/dist/sandbox/migrate-worker.d.cts +0 -1
  608. package/dist/sandbox/migrate-worker.d.mts +0 -1
  609. package/dist/sandbox/migrate-worker.mjs +0 -76
  610. package/dist/sandbox/migrate-worker.mjs.map +0 -1
  611. package/dist/sandbox-ArJ_hEKk.d.cts +0 -104
  612. package/dist/sandbox-ArJ_hEKk.d.cts.map +0 -1
  613. package/dist/sandbox-CHv3OYXg.cjs +0 -165
  614. package/dist/sandbox-CHv3OYXg.cjs.map +0 -1
  615. package/dist/sandbox-CbVB7uOD.mjs +0 -118
  616. package/dist/sandbox-CbVB7uOD.mjs.map +0 -1
  617. package/dist/sandbox-Cm4X6HRh.d.mts +0 -104
  618. package/dist/sandbox-Cm4X6HRh.d.mts.map +0 -1
  619. package/dist/schemas-BObwxB_t.cjs +0 -6017
  620. package/dist/schemas-BObwxB_t.cjs.map +0 -1
  621. package/dist/schemas-D-xeKJDD.mjs +0 -5916
  622. package/dist/schemas-D-xeKJDD.mjs.map +0 -1
  623. package/dist/secrets-AA_tQUl-.mjs +0 -36
  624. package/dist/secrets-AA_tQUl-.mjs.map +0 -1
  625. package/dist/secrets-B_biKsKx.cjs +0 -47
  626. package/dist/secrets-B_biKsKx.cjs.map +0 -1
  627. package/dist/secretsManager-CQORubp9.mjs +0 -97
  628. package/dist/secretsManager-CQORubp9.mjs.map +0 -1
  629. package/dist/secretsManager-RAGcEDX1.cjs +0 -108
  630. package/dist/secretsManager-RAGcEDX1.cjs.map +0 -1
  631. package/dist/seeds-BvxWUGKJ.mjs +0 -8263
  632. package/dist/seeds-BvxWUGKJ.mjs.map +0 -1
  633. package/dist/seeds-Df4BI-T3.cjs +0 -9266
  634. package/dist/seeds-Df4BI-T3.cjs.map +0 -1
  635. package/dist/sniffer-BqjXvcaK.mjs +0 -1825
  636. package/dist/sniffer-BqjXvcaK.mjs.map +0 -1
  637. package/dist/sniffer-DZeQJKty.cjs +0 -1998
  638. package/dist/sniffer-DZeQJKty.cjs.map +0 -1
  639. package/dist/sst-CGdjHn2A.mjs +0 -441
  640. package/dist/sst-CGdjHn2A.mjs.map +0 -1
  641. package/dist/sst-DGuHDxVU.cjs +0 -464
  642. package/dist/sst-DGuHDxVU.cjs.map +0 -1
  643. package/dist/stack-A6MAFZ6u.mjs +0 -1201
  644. package/dist/stack-A6MAFZ6u.mjs.map +0 -1
  645. package/dist/stack-BpkZEEfB.cjs +0 -1308
  646. package/dist/stack-BpkZEEfB.cjs.map +0 -1
  647. package/dist/stages-6SEoRA4x.mjs +0 -190
  648. package/dist/stages-6SEoRA4x.mjs.map +0 -1
  649. package/dist/stages-DH5z89eT.cjs +0 -190
  650. package/dist/stages-DH5z89eT.cjs.map +0 -1
  651. package/dist/target/public.cjs +0 -15
  652. package/dist/target/public.d.cts +0 -28
  653. package/dist/target/public.d.cts.map +0 -1
  654. package/dist/target/public.d.mts +0 -28
  655. package/dist/target/public.d.mts.map +0 -1
  656. package/dist/target/public.mjs +0 -4
  657. package/dist/terminal-CPHuH4S1.cjs +0 -85
  658. package/dist/terminal-CPHuH4S1.cjs.map +0 -1
  659. package/dist/terminal-iNmAXXjs.mjs +0 -85
  660. package/dist/terminal-iNmAXXjs.mjs.map +0 -1
  661. package/dist/types-DipUP9zp.d.cts +0 -7606
  662. package/dist/types-DipUP9zp.d.cts.map +0 -1
  663. package/dist/types-Drpl9HX9.d.mts +0 -7605
  664. package/dist/types-Drpl9HX9.d.mts.map +0 -1
  665. package/dist/utils-D2Nk1Nv2.cjs +0 -205
  666. package/dist/utils-D2Nk1Nv2.cjs.map +0 -1
  667. package/dist/utils-D_fxUqvU.mjs +0 -156
  668. package/dist/utils-D_fxUqvU.mjs.map +0 -1
  669. package/dist/vitest.cjs +0 -65
  670. package/dist/vitest.cjs.map +0 -1
  671. package/dist/vitest.d.cts +0 -29
  672. package/dist/vitest.d.cts.map +0 -1
  673. package/dist/vitest.d.mts +0 -29
  674. package/dist/vitest.d.mts.map +0 -1
  675. package/dist/vitest.mjs +0 -65
  676. package/dist/vitest.mjs.map +0 -1
  677. package/dist/workerRuntime-BXfhbe13.cjs +0 -108
  678. package/dist/workerRuntime-BXfhbe13.cjs.map +0 -1
  679. package/dist/workerRuntime-CsOyBRx2.mjs +0 -79
  680. package/dist/workerRuntime-CsOyBRx2.mjs.map +0 -1
  681. package/dist/workspace-BBeT6Pil.mjs +0 -2088
  682. package/dist/workspace-BBeT6Pil.mjs.map +0 -1
  683. package/dist/workspace-BJ78Bgvm.cjs +0 -2494
  684. package/dist/workspace-BJ78Bgvm.cjs.map +0 -1
@@ -1,2019 +0,0 @@
1
- import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
- import { s as gkmHome } from "./run-BJLIerMM.mjs";
3
- import { r as storedCredentials } from "./credentials-B5N5yKk6.mjs";
4
- import { f as withOutput, r as discover } from "./discover-qjFapetL.mjs";
5
- import { c as withSandbox } from "./sandbox-CbVB7uOD.mjs";
6
- import { n as derivedApps, t as appKey } from "./derive-B4vDpzgP.mjs";
7
- import { $ as IamUserNotOwned, G as checkS3Config, J as BucketNameUnavailable, K as AccessKeyLimit, L as resolveStageTelemetry, N as assertDeployedStage, Q as BucketRegionUnknown, U as stageProvider, W as S3_PROVISIONING, X as BucketProbeFailed, Y as BucketOwnedByAnotherProject, Z as BucketRegionMismatch, et as ProvisionedBucketUnreachable, nt as RotationInProgress, q as BucketKeySetElsewhere, rt as S3RegionRequired, tt as RecordedBucketUnreachable, u as getAppBuildOrder } from "./workspace-BBeT6Pil.mjs";
8
- import { o as builtinTarget } from "./define-6poNqm5O.mjs";
9
- import { findWorkspaceRoot, loadWorkspaceConfig } from "./config.mjs";
10
- import { E as reportDevServices, F as DeployJournal, H as createComposeState, In as applicationName, It as appEnvKeys, Ln as deployIdentity, N as stageProviderNotes, O as stageServiceDeclarations, On as secretsStoreFor, P as PROVIDER_KINDS, T as externalServices, U as createEmptyState, Wn as initStageSecrets, b as DevServicesNeedServerTarget, ct as constructGlobs, fn as usesTelemetry, j as assertStageProvidersEnabled, nr as isMainFrontendApp, rr as resolveHost, tr as NoDomainForStage, w as devServicesUsed, x as ExternalServicesNotConfigured } from "./seeds-BvxWUGKJ.mjs";
11
- import { a as parseTargetOptions, o as resolveTarget } from "./resolve-OfLaxaxY.mjs";
12
- import { t as LocalSandbox } from "./local-BwC2v2Y8.mjs";
13
- import { E as eventError, S as createStateStore, v as assertStateOutlivesRun, y as assertStateRoom } from "./sniffer-BqjXvcaK.mjs";
14
- import { c as stageDnsDomains, n as dnsCredentials } from "./dns-LqWzPb8l.mjs";
15
- import { t as deploysWithCompose } from "./dns-CU22K_i0.mjs";
16
- import { n as assertStageCredentials } from "./credentialSchemas-BJFvfkaz.mjs";
17
- import { resolve } from "node:path";
18
- import { dependentsOf, kebabCase, provideKey, providedKeyFor } from "@geekmidas/manifest";
19
- import { randomInt } from "node:crypto";
20
- import * as s3Url from "@geekmidas/storage/s3-url";
21
- //#region src/target/secrets.ts
22
- /**
23
- * A stage's secrets as a target sees them: read and written through the
24
- * stage's own store, and masked in everything the run prints once read.
25
- */
26
- /**
27
- * Shorter values are left alone: what a progress line legitimately prints —
28
- * a port, a stage, an app name — would otherwise come out as `***` wherever
29
- * a secret happened to share it.
30
- */
31
- const SHORTEST_MASKED = 6;
32
- /** The values a run must never print, and the rewrite that keeps it so. */
33
- var Redactor = class {
34
- values = /* @__PURE__ */ new Set();
35
- add(value) {
36
- if (value && value.length >= SHORTEST_MASKED) this.values.add(value);
37
- }
38
- /** `text` with every masked value replaced by `***`, longest first. */
39
- redact(text) {
40
- if (this.values.size === 0) return text;
41
- let out = text;
42
- const longestFirst = [...this.values].sort((a, b) => b.length - a.length);
43
- for (const value of longestFirst) out = out.replaceAll(value, "***");
44
- return out;
45
- }
46
- };
47
- /** Every value in `secrets` that is a secret rather than a label. */
48
- function secretValues(secrets) {
49
- return [
50
- secrets.seed,
51
- ...Object.values(secrets.custom ?? {}),
52
- ...Object.values(secrets.urls ?? {}),
53
- ...Object.values(secrets.services ?? {}).map((service) => service?.password)
54
- ].filter((value) => typeof value === "string");
55
- }
56
- /**
57
- * The stage's secrets through the store `secrets.store` names for it. Opening
58
- * one builds a client and makes no request, so a target that never reads them
59
- * costs nothing.
60
- */
61
- async function deploySecrets(workspace, stage, redactor, options = {}) {
62
- const store = await secretsStoreFor(workspace, stage, options);
63
- const mask = (secrets) => {
64
- for (const value of secretValues(secrets)) redactor.add(value);
65
- };
66
- return {
67
- store: store.name,
68
- async read() {
69
- const secrets = await store.read(stage);
70
- if (secrets) mask(secrets);
71
- return secrets;
72
- },
73
- async write(secrets) {
74
- mask(secrets);
75
- await store.write(stage, secrets);
76
- },
77
- mask: (value) => redactor.add(value)
78
- };
79
- }
80
- //#endregion
81
- //#region src/providers/aws.ts
82
- /**
83
- * The AWS account a provider provisions in — the stage's, found the way the
84
- * SSM and Secrets Manager stores find it.
85
- *
86
- * 1. `--profile`, resolved on its own: exported keys left over from another
87
- * account never win over a profile someone named.
88
- * 2. `AWS_PROFILE`, else `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` — the
89
- * deploy's own `aws` credential kind (`storedCredentials`).
90
- * 3. The SDK's default chain: `~/.aws` default profile, SSO, a role. In CI,
91
- * whatever `aws-actions/configure-aws-credentials` exported.
92
- *
93
- * None of them: the provider has no provisioning credentials, and the stage
94
- * is treated as `external`.
95
- */
96
- async function awsProvisioningCredentials(lookup) {
97
- const region = lookup.env.AWS_REGION ?? lookup.env.AWS_DEFAULT_REGION;
98
- const where = region ? { region } : {};
99
- if (lookup.profile) return {
100
- profile: lookup.profile,
101
- ...where
102
- };
103
- const stored = await storedCredentials({
104
- env: lookup.env,
105
- ...lookup.home ? { home: lookup.home } : {}
106
- }).get({
107
- kind: "aws",
108
- stage: lookup.stage
109
- });
110
- if (stored) return stored;
111
- try {
112
- const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
113
- await fromNodeProviderChain({
114
- timeout: 1e3,
115
- maxRetries: 0
116
- })();
117
- return {
118
- chain: true,
119
- ...where
120
- };
121
- } catch {
122
- return;
123
- }
124
- }
125
- /**
126
- * An S3-compatible endpoint the environment points the SDK at — the AWS
127
- * emulator in tests. The SDK reads it itself; it is read here too, because
128
- * an emulator takes path-style requests, and a key written for one has to
129
- * say where it is.
130
- */
131
- function awsEndpoint(env, service) {
132
- return env[`AWS_ENDPOINT_URL_${service}`] ?? env.AWS_ENDPOINT_URL;
133
- }
134
- /** An SDK client's config for a provisioning credential. */
135
- async function awsClientConfig(credential, region) {
136
- if ("profile" in credential) {
137
- const { fromIni } = await import("@aws-sdk/credential-providers");
138
- return {
139
- region,
140
- credentials: fromIni({ profile: credential.profile })
141
- };
142
- }
143
- if ("accessKeyId" in credential) return {
144
- region,
145
- credentials: {
146
- accessKeyId: credential.accessKeyId,
147
- secretAccessKey: credential.secretAccessKey,
148
- ...credential.sessionToken ? { sessionToken: credential.sessionToken } : {}
149
- }
150
- };
151
- return { region };
152
- }
153
- const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
154
- /** A name that S3 would refuse — what the name builder never returns. */
155
- var InvalidBucketName = class extends GkmError {
156
- bucket;
157
- reason;
158
- constructor(bucket, reason) {
159
- 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.`);
160
- this.bucket = bucket;
161
- this.reason = reason;
162
- this.name = "InvalidBucketName";
163
- }
164
- };
165
- /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
166
- function part(value) {
167
- return kebabCase(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
168
- }
169
- /**
170
- * `parts` joined by `-`, shortened to `max` characters by trimming the longest
171
- * part one character at a time — so a long construct id gives way before a
172
- * short stage name does, and every part keeps its start.
173
- */
174
- function fitParts(parts, max) {
175
- const kept = parts.map(part).filter(Boolean);
176
- const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
177
- while (length() > max) {
178
- let longest = 0;
179
- for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
180
- if (kept[longest].length <= 1) break;
181
- kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
182
- }
183
- return kept.join("-");
184
- }
185
- /** Why `name` is not a valid bucket name, or undefined when it is. */
186
- function bucketNameProblem(name) {
187
- if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
188
- if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
189
- if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
190
- if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
191
- if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
192
- }
193
- /**
194
- * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
195
- * dots, shortened to leave room for a clash's suffix.
196
- *
197
- * @throws {InvalidBucketName} when nothing usable is left
198
- */
199
- function bucketName(input) {
200
- const name = fitParts([
201
- input.scope,
202
- input.stage,
203
- input.id
204
- ], 56);
205
- const problem = bucketNameProblem(name);
206
- if (problem) throw new InvalidBucketName(name, problem);
207
- return name;
208
- }
209
- /** Six random `[a-z0-9]` characters. */
210
- function randomSuffix(random = randomInt) {
211
- let suffix = "";
212
- for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
213
- return suffix;
214
- }
215
- /** The good name with a clash's suffix. */
216
- function suffixedBucketName(good, suffix) {
217
- return `${good}-${suffix}`;
218
- }
219
- /**
220
- * The IAM user a bucket is reached with on a stage:
221
- * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
222
- */
223
- function iamUserName(input) {
224
- return fitParts([
225
- "gkm",
226
- input.scope,
227
- input.stage,
228
- input.id
229
- ], 64);
230
- }
231
- /** The path every user gkm creates is under, so it finds its own. */
232
- const IAM_USER_PATH = "/gkm/";
233
- /** The inline policy each user is given. */
234
- const IAM_POLICY_NAME = "gkm-bucket";
235
- //#endregion
236
- //#region src/providers/s3/origins.ts
237
- /**
238
- * Which browser origins may call a bucket: the stage's sites that depend on
239
- * an API using it.
240
- *
241
- * The same reading of the graph an API's own CORS origins are — its callers —
242
- * taken one step further: a site that calls an API which hands it a presigned
243
- * upload URL is a site whose browser PUTs to the bucket. A site that reads the
244
- * bucket (or a file server over it) itself is one too. Nothing is written
245
- * down: add a site that calls the API and the next provision run allows it.
246
- */
247
- /** The keys a reader of this bucket holds: its URL, and each server's over it. */
248
- function bucketKeys(manifest, bucket) {
249
- return [provideKey(bucket, "url"), ...Object.entries(manifest).filter(([, d]) => d.kind === "file-server" && d.of === bucket).map(([id]) => provideKey(id, "url"))];
250
- }
251
- function bucketOrigins(input) {
252
- const { manifest, workspace, stage } = input;
253
- const keys = bucketKeys(manifest, input.bucket);
254
- const readers = Object.entries(manifest).filter(([, d]) => d.kind === "rest-api" || d.kind === "site").filter(([id]) => {
255
- const env = appEnvKeys(manifest, appKey(id), input.runnables);
256
- return env !== void 0 && keys.some((key) => env.has(key));
257
- });
258
- const sites = /* @__PURE__ */ new Set();
259
- for (const [id, declaration] of readers) {
260
- if (declaration.kind === "site") {
261
- sites.add(id);
262
- continue;
263
- }
264
- for (const caller of dependentsOf(manifest, id)) if (manifest[caller]?.kind === "site") sites.add(caller);
265
- }
266
- const origins = /* @__PURE__ */ new Set();
267
- const unresolved = [];
268
- for (const id of [...sites].sort()) {
269
- const name = appKey(id);
270
- const app = workspace.apps[name];
271
- if (!app) {
272
- unresolved.push(name);
273
- continue;
274
- }
275
- try {
276
- const host = resolveHost(name, app, stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
277
- origins.add(`https://${host}`);
278
- } catch (error) {
279
- if (!(error instanceof NoDomainForStage)) throw error;
280
- unresolved.push(name);
281
- }
282
- }
283
- return {
284
- origins: [...origins].sort(),
285
- unresolved
286
- };
287
- }
288
- //#endregion
289
- //#region src/providers/s3/policy.ts
290
- const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
291
- /**
292
- * What the app's key may do: objects in this bucket, and listing it — and
293
- * nothing else in the account.
294
- *
295
- * Multipart uploads are in it because a presigned upload of a large file is
296
- * one, and an abandoned one is cleaned up by the app. Reading old versions is
297
- * added only when the bucket keeps them.
298
- */
299
- function userPolicy(bucket, options = {}) {
300
- return {
301
- Version: "2012-10-17",
302
- Statement: [{
303
- Sid: "GkmObjects",
304
- Effect: "Allow",
305
- Action: [
306
- "s3:GetObject",
307
- "s3:PutObject",
308
- "s3:DeleteObject",
309
- "s3:AbortMultipartUpload",
310
- "s3:ListMultipartUploadParts",
311
- ...options.versioning ? ["s3:GetObjectVersion"] : []
312
- ],
313
- Resource: `${bucketArn(bucket)}/*`
314
- }, {
315
- Sid: "GkmBucket",
316
- Effect: "Allow",
317
- Action: [
318
- "s3:ListBucket",
319
- "s3:GetBucketLocation",
320
- "s3:ListBucketMultipartUploads"
321
- ],
322
- Resource: bucketArn(bucket)
323
- }]
324
- };
325
- }
326
- /**
327
- * One open pattern as the resource it is public on. A `**` is S3's `*`; a
328
- * single `*` is too, which crosses `/` where the construct's own check does
329
- * not — the construct is the stricter of the two (see `bucketPolicy` in
330
- * reconcile, which the local MinIO is given the same way).
331
- */
332
- function openResource(bucket, pattern) {
333
- const path = pattern.replace(/^\/+/, "").replace(/\*\*/g, "*");
334
- return `${bucketArn(bucket)}/${path}`;
335
- }
336
- /**
337
- * The bucket's own policy: every request refused unless it came over TLS,
338
- * and — only when a file server opens paths on it — anonymous `s3:GetObject`
339
- * on exactly those prefixes.
340
- */
341
- function bucketPolicy(bucket, open = []) {
342
- const statements = [{
343
- Sid: "GkmDenyInsecureTransport",
344
- Effect: "Deny",
345
- Principal: "*",
346
- Action: "s3:*",
347
- Resource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],
348
- Condition: { Bool: { "aws:SecureTransport": "false" } }
349
- }];
350
- if (open.length > 0) statements.push({
351
- Sid: "GkmOpenPaths",
352
- Effect: "Allow",
353
- Principal: "*",
354
- Action: "s3:GetObject",
355
- Resource: [...new Set(open.map((p) => openResource(bucket, p)))].sort()
356
- });
357
- return {
358
- Version: "2012-10-17",
359
- Statement: statements
360
- };
361
- }
362
- /**
363
- * Block Public Access. All four flags on, unless the bucket has open paths:
364
- * then a *policy* may make it public (`BlockPublicPolicy`,
365
- * `RestrictPublicBuckets` off), and ACLs still may not.
366
- */
367
- function publicAccessBlock(open) {
368
- return {
369
- BlockPublicAcls: true,
370
- IgnorePublicAcls: true,
371
- BlockPublicPolicy: !open,
372
- RestrictPublicBuckets: !open
373
- };
374
- }
375
- function corsRule(origins) {
376
- return {
377
- AllowedMethods: [
378
- "GET",
379
- "HEAD",
380
- "POST",
381
- "PUT"
382
- ],
383
- AllowedOrigins: [...new Set(origins)].sort(),
384
- AllowedHeaders: ["*"],
385
- ExposeHeaders: ["ETag"],
386
- MaxAgeSeconds: 3e3
387
- };
388
- }
389
- /**
390
- * A policy document in one canonical form — keys sorted, a lone string a
391
- * one-element list, lists sorted — so one AWS reformatted reads as the same
392
- * document rather than as drift.
393
- */
394
- function canonicalPolicy(value) {
395
- return JSON.stringify(canonical(value));
396
- }
397
- function canonical(value, key) {
398
- if (Array.isArray(value)) {
399
- const items = value.map((v) => canonical(v));
400
- return key === "Statement" ? items : items.map((v) => JSON.stringify(v)).sort();
401
- }
402
- if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => {
403
- const v = value[k];
404
- return [k, canonical(k === "Action" || k === "Resource" || k === "AWS" ? Array.isArray(v) ? v : [v] : v, k)];
405
- }));
406
- return value;
407
- }
408
- //#endregion
409
- //#region src/providers/s3/index.ts
410
- /** The tags gkm finds its own buckets and users by. */
411
- const TAG_PROJECT = "gkm:project";
412
- const TAG_STAGE = "gkm:stage";
413
- const TAG_CONSTRUCT = "gkm:construct";
414
- function bucketConstructs(manifest) {
415
- return Object.entries(manifest).filter(([, d]) => d.kind === "objects").map(([id, d]) => ({
416
- id,
417
- versioned: d.versioned === true,
418
- servers: Object.entries(manifest).filter(([, s]) => s.kind === "file-server" && s.of === id).map(([sid, s]) => ({
419
- id: sid,
420
- open: s.open ?? []
421
- })).sort((a, b) => a.id.localeCompare(b.id))
422
- })).sort((a, b) => a.id.localeCompare(b.id));
423
- }
424
- /**
425
- * The region the stage's buckets are created in: the entry's, the secrets
426
- * store's when it is in AWS, the credential's, `AWS_REGION`.
427
- */
428
- function s3Region(ctx, env = process.env) {
429
- const store = ctx.workspace.secrets?.store;
430
- const storeRegion = store && typeof store === "object" && "region" in store ? store.region : void 0;
431
- const region = ctx.config.region ?? storeRegion ?? ctx.credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
432
- if (!region) throw new S3RegionRequired(ctx.stage);
433
- return region;
434
- }
435
- /**
436
- * The address a file server over `bucket` serves on: the bucket's regional
437
- * virtual-host endpoint, which is what `FileServer.url(key)` appends a key to
438
- * — `https://<bucket>.s3.<region>.amazonaws.com/<key>`. Against an emulator,
439
- * its path-style address.
440
- */
441
- function bucketPublicUrl(bucket, region, endpoint) {
442
- if (endpoint) return `${endpoint.replace(/\/+$/, "")}/${bucket}`;
443
- return `https://${bucket}.s3.${region}.amazonaws.com`;
444
- }
445
- /** What an AWS SDK error is called, whichever field carries it. */
446
- function errorName(error) {
447
- const e = error;
448
- return e?.Code ?? e?.name ?? "";
449
- }
450
- /** The answer an SDK call failed with. */
451
- function s3Answer(error) {
452
- const e = error;
453
- const headers = Object.fromEntries(Object.entries(e?.$response?.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
454
- const status = e?.$metadata?.httpStatusCode ?? e?.$response?.statusCode;
455
- const region = headers["x-amz-bucket-region"];
456
- const requestId = e?.$metadata?.requestId ?? headers["x-amz-request-id"];
457
- const id2 = e?.$metadata?.extendedRequestId ?? headers["x-amz-id-2"];
458
- return {
459
- ...status !== void 0 ? { status } : {},
460
- name: errorName(error) || "Error",
461
- message: e?.message ?? String(error),
462
- ...region ? { region } : {},
463
- ...requestId ? { requestId } : {},
464
- ...id2 ? { id2 } : {}
465
- };
466
- }
467
- /**
468
- * `HTTP 403 Unknown: UnknownError [x-amz-bucket-region: eu-west-1,
469
- * x-amz-request-id: …, x-amz-id-2: …]` — everything S3 said, for a message.
470
- */
471
- function describeAnswer(answer) {
472
- const said = answer.message && answer.message !== answer.name ? `${answer.name}: ${answer.message}` : answer.name;
473
- const headers = [
474
- answer.region && `x-amz-bucket-region: ${answer.region}`,
475
- answer.requestId && `x-amz-request-id: ${answer.requestId}`,
476
- answer.id2 && `x-amz-id-2: ${answer.id2}`
477
- ].filter(Boolean);
478
- return `${answer.status === void 0 ? "no response" : `HTTP ${answer.status}`} ${said}` + (headers.length > 0 ? ` [${headers.join(", ")}]` : "");
479
- }
480
- /** `HeadBucket`: the bucket's region when it answers, else what S3 said. */
481
- async function headBucket(S3, client, bucket) {
482
- try {
483
- const out = await client.send(new S3.HeadBucketCommand({ Bucket: bucket }));
484
- return {
485
- ok: true,
486
- ...out.BucketRegion ? { region: out.BucketRegion } : {}
487
- };
488
- } catch (error) {
489
- return {
490
- ok: false,
491
- ...s3Answer(error)
492
- };
493
- }
494
- }
495
- /** `GetBucketLocation`'s answer as a region: none is us-east-1, `EU` eu-west-1. */
496
- async function bucketLocation(S3, client, bucket) {
497
- try {
498
- const location = (await client.send(new S3.GetBucketLocationCommand({ Bucket: bucket }))).LocationConstraint;
499
- return { region: !location ? "us-east-1" : location === "EU" ? "eu-west-1" : location };
500
- } catch (error) {
501
- return { failed: s3Answer(error) };
502
- }
503
- }
504
- /**
505
- * Where `bucket` is: `HeadBucket`'s `x-amz-bucket-region` — on a 200, a 301
506
- * or a 400 alike — else `GetBucketLocation`.
507
- *
508
- * @throws {BucketRegionUnknown}
509
- */
510
- async function bucketRegion(clients, bucket) {
511
- const { S3, s3 } = clients;
512
- const head = await headBucket(S3, s3, bucket);
513
- if (head.region) return head.region;
514
- const location = await bucketLocation(S3, s3, bucket);
515
- if ("region" in location) return location.region;
516
- throw new BucketRegionUnknown(bucket, head.ok ? "HTTP 200 without x-amz-bucket-region" : describeAnswer(head), describeAnswer(location.failed));
517
- }
518
- /** A read whose "there is none" answer is one of `missing`. */
519
- async function readOr(read, missing) {
520
- try {
521
- return await read();
522
- } catch (error) {
523
- if (missing.includes(errorName(error))) return void 0;
524
- throw error;
525
- }
526
- }
527
- const defaultClients = async (credential, region) => {
528
- const S3 = await import("@aws-sdk/client-s3");
529
- const IAM = await import("@aws-sdk/client-iam");
530
- const config = await awsClientConfig(credential, region);
531
- const endpoint = awsEndpoint(process.env, "S3");
532
- return {
533
- S3,
534
- IAM,
535
- s3: new S3.S3Client({
536
- ...config,
537
- ...endpoint ? {
538
- endpoint,
539
- forcePathStyle: true
540
- } : {}
541
- }),
542
- iam: new IAM.IAMClient(config),
543
- region,
544
- ...endpoint ? { endpoint } : {}
545
- };
546
- };
547
- /** For tests: what makes the clients. */
548
- let makeClients = defaultClients;
549
- async function ensureS3(ctx) {
550
- const region = s3Region(ctx);
551
- const clients = await makeClients(ctx.credential, region);
552
- for (const construct of bucketConstructs(ctx.manifest)) await ensureBucket(ctx, clients, construct);
553
- }
554
- /** The keys gkm tags a bucket and a user with. */
555
- function identityTags(ctx, id) {
556
- return [
557
- {
558
- Key: TAG_PROJECT,
559
- Value: ctx.identity.key
560
- },
561
- {
562
- Key: TAG_STAGE,
563
- Value: ctx.stage
564
- },
565
- {
566
- Key: TAG_CONSTRUCT,
567
- Value: id
568
- }
569
- ];
570
- }
571
- async function ensureBucket(ctx, stageClients, construct) {
572
- const { id } = construct;
573
- const nameInput = {
574
- scope: ctx.identity.scope,
575
- stage: ctx.stage,
576
- id: appKey(id)
577
- };
578
- const versioning = ctx.config.versioning ?? construct.versioned;
579
- const open = [...new Set(construct.servers.flatMap((s) => s.open))].sort();
580
- const located = await ensureBucketName(ctx, stageClients, id, bucketName(nameInput));
581
- const { bucket, exists } = located;
582
- let clients = stageClients;
583
- if (located.region !== stageClients.region) {
584
- clients = await makeClients(ctx.credential, located.region);
585
- ctx.log(` '${bucket}' is in ${located.region}, not ${stageClients.region}: '${id}' is reached and addressed there`);
586
- }
587
- await ensureBucketSettings(ctx, clients, {
588
- id,
589
- bucket,
590
- exists,
591
- versioning,
592
- open
593
- });
594
- const user = await ensureUser(ctx, clients, id, iamUserName(nameInput), userPolicy(bucket, { versioning }));
595
- await ensureAccessKey(ctx, clients, {
596
- id,
597
- bucket,
598
- ...user
599
- });
600
- const publicUrl = bucketPublicUrl(bucket, clients.region, clients.endpoint);
601
- for (const server of construct.servers) {
602
- const key = provideKey(server.id, "url");
603
- const entry = {
604
- key: `file-server:${server.id}`,
605
- type: "url"
606
- };
607
- const recorded = ctx.state.record(entry.key)?.id;
608
- const current = ctx.secrets[key];
609
- if (current === publicUrl) {
610
- await ctx.state.ready(entry, publicUrl);
611
- continue;
612
- }
613
- if (current !== void 0 && current !== recorded) {
614
- ctx.log(` ${key} is set to ${current} by you, and kept — the bucket's own address is ${publicUrl}`);
615
- continue;
616
- }
617
- await ctx.change({
618
- construct: server.id,
619
- resource: key,
620
- change: `set to ${publicUrl}`
621
- }, async () => {
622
- await ctx.writeSecrets({ [key]: publicUrl });
623
- await ctx.state.ready(entry, publicUrl);
624
- });
625
- }
626
- }
627
- /**
628
- * The bucket's name: the recorded one, else the good name, else the good
629
- * name with a random suffix — up to {@link SUFFIX_ATTEMPTS} times.
630
- */
631
- async function ensureBucketName(ctx, clients, id, good) {
632
- const { S3, s3, region } = clients;
633
- const key = `s3-bucket:${id}`;
634
- const record = ctx.state.record(key);
635
- const entry = (name, where) => ({
636
- key,
637
- type: "s3-bucket",
638
- data: {
639
- name,
640
- region: where
641
- }
642
- });
643
- /**
644
- * Whether this account holds `name`: yes, no, or someone else does. Read
645
- * by status — a `HEAD` has no body, so its error is named `Unknown` — and,
646
- * when S3 says the bucket is in another region, asked again there.
647
- */
648
- const probe = async (name) => {
649
- let head = await headBucket(S3, s3, name);
650
- if (!head.ok && head.region && head.region !== region && (head.status === 301 || head.status === 400)) {
651
- const there = await makeClients(ctx.credential, head.region);
652
- head = await headBucket(there.S3, there.s3, name);
653
- }
654
- if (head.ok) return "ours";
655
- if (head.status === 404) return "none";
656
- if (head.status === 403) return "taken";
657
- throw new BucketProbeFailed(name, describeAnswer(head));
658
- };
659
- /** Where the bucket is now — read, not assumed: it may be adopted. */
660
- const located = async (name, made) => ctx.dryRun && made === "created" ? region : bucketRegion(clients, name);
661
- const create = async (name) => {
662
- if (ctx.dryRun) {
663
- const found = await probe(name);
664
- if (found === "none") {
665
- await ctx.change({
666
- construct: id,
667
- resource: `bucket ${name}`,
668
- change: `create in ${region}`
669
- }, async () => {});
670
- return "created";
671
- }
672
- return found;
673
- }
674
- await ctx.state.pending(entry(name, region));
675
- try {
676
- await s3.send(new S3.CreateBucketCommand({
677
- Bucket: name,
678
- ...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
679
- }));
680
- } catch (error) {
681
- const code = errorName(error);
682
- if (code === "BucketAlreadyOwnedByYou") return "ours";
683
- if (code === "BucketAlreadyExists") return "taken";
684
- throw error;
685
- }
686
- await ctx.change({
687
- construct: id,
688
- resource: `bucket ${name}`,
689
- change: `create in ${region}`
690
- }, async () => {});
691
- return "created";
692
- };
693
- const adopt = async (name, where) => {
694
- const there = where === region ? clients : await makeClients(ctx.credential, where);
695
- const owner = (await readOr(() => there.s3.send(new there.S3.GetBucketTaggingCommand({ Bucket: name })), ["NoSuchTagSet", "NoSuchTagSetError"]))?.TagSet?.find((t) => t.Key === TAG_PROJECT)?.Value;
696
- if (owner && owner !== ctx.identity.key) throw new BucketOwnedByAnotherProject(name, owner, ctx.identity.key);
697
- };
698
- if (record?.status === "ready" && record.id) {
699
- const found = await probe(record.id);
700
- if (found === "taken") throw new RecordedBucketUnreachable(id, record.id);
701
- const made = found === "ours" ? "ours" : await create(record.id);
702
- if (made === "taken") throw new RecordedBucketUnreachable(id, record.id);
703
- const where = await located(record.id, made);
704
- if (!ctx.dryRun) await ctx.state.ready(entry(record.id, where), record.id);
705
- return {
706
- bucket: record.id,
707
- exists: made === "ours",
708
- region: where
709
- };
710
- }
711
- const pending = record?.data?.name;
712
- const names = [
713
- ...typeof pending === "string" && pending !== good ? [pending] : [],
714
- good,
715
- ...Array.from({ length: 5 }, () => suffixedBucketName(good, randomSuffix()))
716
- ];
717
- const tried = [];
718
- for (const name of names) {
719
- tried.push(name);
720
- const made = await create(name);
721
- if (made === "taken") continue;
722
- const where = await located(name, made);
723
- if (made === "ours") await adopt(name, where);
724
- if (!ctx.dryRun) await ctx.state.ready(entry(name, where), name);
725
- if (name !== good) ctx.log(` '${good}' is taken by another account; '${id}' is '${name}', recorded in the stage's state`);
726
- return {
727
- bucket: name,
728
- exists: made === "ours",
729
- region: where
730
- };
731
- }
732
- throw new BucketNameUnavailable(id, tried.filter((n) => n !== pending));
733
- }
734
- /** Tags, Block Public Access, encryption, policy, versioning and CORS. */
735
- async function ensureBucketSettings(ctx, clients, input) {
736
- const { S3, s3 } = clients;
737
- const { id, bucket } = input;
738
- const Bucket = bucket;
739
- const fresh = ctx.dryRun && !input.exists;
740
- const read = async (fn, missing) => fresh ? void 0 : readOr(fn, missing);
741
- const set = (change, apply) => ctx.change({
742
- construct: id,
743
- resource: `bucket ${bucket}`,
744
- change
745
- }, () => apply().then(() => void 0));
746
- const tagged = await read(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket })), ["NoSuchTagSet", "NoSuchTagSetError"]);
747
- const ours = identityTags(ctx, id);
748
- const others = (tagged?.TagSet ?? []).filter((t) => !ours.some((o) => o.Key === t.Key));
749
- if (ours.some((o) => !tagged?.TagSet?.some((t) => t.Key === o.Key && t.Value === o.Value))) await set("tag", () => s3.send(new S3.PutBucketTaggingCommand({
750
- Bucket,
751
- Tagging: { TagSet: [...others, ...ours].map((t) => ({
752
- Key: t.Key,
753
- Value: t.Value
754
- })) }
755
- })));
756
- const isOpen = input.open.length > 0;
757
- const block = publicAccessBlock(isOpen);
758
- const ensureBlock = async () => {
759
- const now = (await read(() => s3.send(new S3.GetPublicAccessBlockCommand({ Bucket })), ["NoSuchPublicAccessBlockConfiguration"]))?.PublicAccessBlockConfiguration;
760
- 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({
761
- Bucket,
762
- PublicAccessBlockConfiguration: block
763
- })));
764
- };
765
- const policy = bucketPolicy(bucket, input.open);
766
- const ensurePolicy = async () => {
767
- const current = await read(() => s3.send(new S3.GetBucketPolicyCommand({ Bucket })), ["NoSuchBucketPolicy"]);
768
- if (!(current?.Policy !== void 0 && canonicalPolicy(JSON.parse(current.Policy)) === canonicalPolicy(policy))) await set(isOpen ? `policy: TLS only, public read on ${input.open.join(", ")}` : "policy: TLS only", () => s3.send(new S3.PutBucketPolicyCommand({
769
- Bucket,
770
- Policy: JSON.stringify(policy)
771
- })));
772
- };
773
- if (isOpen) {
774
- await ensureBlock();
775
- await ensurePolicy();
776
- } else {
777
- await ensurePolicy();
778
- await ensureBlock();
779
- }
780
- 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({
781
- Bucket,
782
- ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
783
- })));
784
- const status = (await read(() => s3.send(new S3.GetBucketVersioningCommand({ Bucket })), []))?.Status;
785
- if (input.versioning && status !== "Enabled") await set("enable versioning", () => s3.send(new S3.PutBucketVersioningCommand({
786
- Bucket,
787
- VersioningConfiguration: { Status: "Enabled" }
788
- })));
789
- else if (!input.versioning && status === "Enabled") await set("suspend versioning", () => s3.send(new S3.PutBucketVersioningCommand({
790
- Bucket,
791
- VersioningConfiguration: { Status: "Suspended" }
792
- })));
793
- const { origins, unresolved } = bucketOrigins({
794
- workspace: ctx.workspace,
795
- manifest: ctx.manifest,
796
- runnables: ctx.runnables,
797
- stage: ctx.stage,
798
- bucket: id
799
- });
800
- 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`);
801
- if (origins.length === 0) return;
802
- const rule = corsRule(origins);
803
- const cors = await read(() => s3.send(new S3.GetBucketCorsCommand({ Bucket })), ["NoSuchCORSConfiguration"]);
804
- if (!(cors?.CORSRules?.length === 1 && canonicalCors(cors.CORSRules[0]) === canonicalCors(rule))) await set(`CORS for ${origins.join(", ")}`, () => s3.send(new S3.PutBucketCorsCommand({
805
- Bucket,
806
- CORSConfiguration: { CORSRules: [rule] }
807
- })));
808
- }
809
- function canonicalCors(rule) {
810
- const sorted = (list) => [...list ?? []].sort();
811
- return JSON.stringify({
812
- AllowedMethods: sorted(rule.AllowedMethods),
813
- AllowedOrigins: sorted(rule.AllowedOrigins),
814
- AllowedHeaders: sorted(rule.AllowedHeaders),
815
- ExposeHeaders: sorted(rule.ExposeHeaders),
816
- MaxAgeSeconds: rule.MaxAgeSeconds ?? null
817
- });
818
- }
819
- /** The bucket's IAM user and its inline policy. */
820
- async function ensureUser(ctx, clients, id, user, policy) {
821
- const { IAM, iam } = clients;
822
- const entry = {
823
- key: `iam-user:${id}`,
824
- type: "iam-user"
825
- };
826
- const found = await readOr(() => iam.send(new IAM.GetUserCommand({ UserName: user })), ["NoSuchEntity", "NoSuchEntityException"]);
827
- if (found?.User) {
828
- const tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
829
- const tag = (key) => tags.Tags?.find((t) => t.Key === key)?.Value;
830
- if (found.User.Path !== "/gkm/" || tag("gkm:project") !== ctx.identity.key || tag("gkm:stage") !== ctx.stage) throw new IamUserNotOwned(user, ctx.identity.key, ctx.stage);
831
- await ctx.state.ready(entry, user);
832
- } else await ctx.change({
833
- construct: id,
834
- resource: `IAM user ${user}`,
835
- change: `create under ${IAM_USER_PATH}`
836
- }, async () => {
837
- await ctx.state.pending(entry);
838
- await iam.send(new IAM.CreateUserCommand({
839
- UserName: user,
840
- Path: IAM_USER_PATH,
841
- Tags: identityTags(ctx, id)
842
- }));
843
- await ctx.state.ready(entry, user);
844
- });
845
- const exists = Boolean(found?.User) || !ctx.dryRun;
846
- const current = exists ? await readOr(() => iam.send(new IAM.GetUserPolicyCommand({
847
- UserName: user,
848
- PolicyName: IAM_POLICY_NAME
849
- })), ["NoSuchEntity", "NoSuchEntityException"]) : void 0;
850
- const document = current?.PolicyDocument ? JSON.parse(decodePolicy(current.PolicyDocument)) : void 0;
851
- if (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) await ctx.change({
852
- construct: id,
853
- resource: `IAM user ${user}`,
854
- change: `policy ${IAM_POLICY_NAME}: this bucket only`
855
- }, async () => {
856
- await iam.send(new IAM.PutUserPolicyCommand({
857
- UserName: user,
858
- PolicyName: IAM_POLICY_NAME,
859
- PolicyDocument: JSON.stringify(policy)
860
- }));
861
- });
862
- return {
863
- user,
864
- exists
865
- };
866
- }
867
- /** IAM returns a policy document URL-encoded; an emulator may not. */
868
- function decodePolicy(document) {
869
- try {
870
- return decodeURIComponent(document);
871
- } catch {
872
- return document;
873
- }
874
- }
875
- /**
876
- * The user's access key, in the stage's secrets as the bucket's URL.
877
- *
878
- * - First run: one key, written into the stage's secrets.
879
- * - `--rotate-keys`: a second key, written in place of the first; the first
880
- * stays active until the stage has deployed with the second, and the next
881
- * run after that deploy — or `--retire-old-keys` — deletes it.
882
- * - A key the secrets no longer hold (a store emptied by hand): replaced the
883
- * same way, since its secret cannot be read back.
884
- */
885
- async function ensureAccessKey(ctx, clients, input) {
886
- const { IAM, iam } = clients;
887
- const { id, bucket, user } = input;
888
- const urlKey = provideKey(id, "url");
889
- const entryKey = `iam-access-key:${id}`;
890
- const record = ctx.state.record(entryKey);
891
- const given = ctx.secrets[urlKey];
892
- let inUrl;
893
- let parsed;
894
- if (given !== void 0) {
895
- try {
896
- parsed = s3Url.parse(given);
897
- } catch {
898
- parsed = void 0;
899
- }
900
- if (parsed?.bucket !== bucket) throw new BucketKeySetElsewhere(urlKey, bucket, parsed?.bucket ?? given.replace(/\/\/[^@]*@/, "//"), ctx.stage);
901
- inUrl = parsed.accessKeyId;
902
- }
903
- const listed = input.exists ? (await iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))).AccessKeyMetadata?.map((k) => k.AccessKeyId) ?? [] : [];
904
- let current = record?.status === "ready" ? record.id : void 0;
905
- let previous = typeof record?.data?.previous === "string" ? record.data.previous : void 0;
906
- const rotatedAt = typeof record?.data?.rotatedAt === "string" ? record.data.rotatedAt : void 0;
907
- const entry = (data = {}) => ({
908
- key: entryKey,
909
- type: "iam-access-key",
910
- data: {
911
- user,
912
- ...data
913
- }
914
- });
915
- if (previous && current) {
916
- const deployed = rotatedAt !== void 0 && ctx.state.lastDeployedAt !== void 0 && ctx.state.lastDeployedAt > rotatedAt;
917
- if (ctx.retireOldKeys || deployed) {
918
- const old = previous;
919
- const keep = current;
920
- await ctx.change({
921
- construct: id,
922
- resource: `IAM user ${user}`,
923
- change: `delete the rotated-out access key ${old}`
924
- }, async () => {
925
- if (listed.includes(old)) await iam.send(new IAM.DeleteAccessKeyCommand({
926
- UserName: user,
927
- AccessKeyId: old
928
- }));
929
- await ctx.state.ready(entry(), keep);
930
- });
931
- previous = void 0;
932
- } 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)`);
933
- }
934
- if (!current && inUrl && listed.includes(inUrl)) {
935
- await ctx.state.ready(entry(), inUrl);
936
- current = inUrl;
937
- }
938
- if (current !== void 0 && listed.includes(current) && inUrl === current && !ctx.rotateKeys) {
939
- if (parsed && parsed.region !== clients.region) {
940
- const address = parsed;
941
- await ctx.change({
942
- construct: id,
943
- resource: urlKey,
944
- change: `name ${clients.region}, the bucket's region (it said ${address.region ?? "none"})`
945
- }, () => ctx.writeSecrets({ [urlKey]: s3Url.build({
946
- ...address,
947
- region: clients.region
948
- }) }));
949
- }
950
- return;
951
- }
952
- if (ctx.rotateKeys && previous) throw new RotationInProgress(id, previous, ctx.stage);
953
- const outgoing = current && listed.includes(current) ? current : void 0;
954
- if (listed.length >= 2) throw new AccessKeyLimit(user, listed);
955
- 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)";
956
- await ctx.change({
957
- construct: id,
958
- resource: `IAM user ${user}`,
959
- change: why
960
- }, async () => {
961
- await ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));
962
- const key = (await iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }))).AccessKey;
963
- await ctx.writeSecrets({ [urlKey]: s3Url.build({
964
- bucket,
965
- region: clients.region,
966
- ...clients.endpoint ? {
967
- endpoint: clients.endpoint,
968
- forcePathStyle: true
969
- } : {},
970
- accessKeyId: key.AccessKeyId,
971
- secretAccessKey: key.SecretAccessKey
972
- }) });
973
- const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
974
- await ctx.state.ready(entry(outgoing ? {
975
- previous: outgoing,
976
- rotatedAt: issuedAt,
977
- issuedAt
978
- } : { issuedAt }), key.AccessKeyId);
979
- });
980
- 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}`);
981
- }
982
- /** How long a key issued this recently counts as new to IAM. */
983
- const NEW_KEY_WINDOW_MS = 6e5;
984
- /** The waits between asks while a new key becomes usable: about a minute. */
985
- let newKeyWaits = [
986
- 2e3,
987
- 4e3,
988
- 8e3,
989
- 15e3,
990
- 15e3,
991
- 15e3
992
- ];
993
- /** When the key in the URL was issued, if the stage's state says it was just now. */
994
- function issuedJustNow(ctx, id, accessKeyId) {
995
- const record = ctx.resources?.[`iam-access-key:${id}`];
996
- const issuedAt = record?.data?.issuedAt;
997
- if (record?.id !== accessKeyId || typeof issuedAt !== "string") return;
998
- const age = Date.now() - Date.parse(issuedAt);
999
- return age >= 0 && age < NEW_KEY_WINDOW_MS ? issuedAt : void 0;
1000
- }
1001
- /**
1002
- * Each provisioned bucket answers `HeadBucket` to the key in the stage's
1003
- * secrets — the one the apps will use. A bucket whose URL carries no key is
1004
- * not one this provider wrote, and the deploy's own check covers a URL that
1005
- * is missing.
1006
- *
1007
- * A failure is read by its status, never its name — a `HEAD` has no body,
1008
- * so SDK v3 calls a 301, 400 or 403 `Unknown` — and the message carries
1009
- * everything S3 said: status, error, region, request ids.
1010
- *
1011
- * @throws {BucketRegionMismatch} the bucket is in another region than its URL says
1012
- * @throws {ProvisionedBucketUnreachable}
1013
- */
1014
- async function verifyS3(ctx) {
1015
- const S3 = await import("@aws-sdk/client-s3");
1016
- for (const { id } of bucketConstructs(ctx.manifest)) {
1017
- const urlKey = provideKey(id, "url");
1018
- const url = ctx.secrets[urlKey];
1019
- if (url === void 0) continue;
1020
- const address = s3Url.parse(url);
1021
- if (!address.accessKeyId || !address.secretAccessKey) continue;
1022
- const asked = address.region ?? ctx.config.region ?? "us-east-1";
1023
- const client = new S3.S3Client({
1024
- region: asked,
1025
- credentials: {
1026
- accessKeyId: address.accessKeyId,
1027
- secretAccessKey: address.secretAccessKey
1028
- },
1029
- ...address.endpoint ? { endpoint: address.endpoint } : {},
1030
- ...address.forcePathStyle ? { forcePathStyle: true } : {}
1031
- });
1032
- try {
1033
- let head = await headBucket(S3, client, address.bucket);
1034
- const issuedAt = issuedJustNow(ctx, id, address.accessKeyId);
1035
- let waited = 0;
1036
- if (!head.ok && head.status === 403 && issuedAt) {
1037
- ctx.log?.(` ${id}: waiting for the new key ${address.accessKeyId} to become active…`);
1038
- for (const wait of newKeyWaits) {
1039
- await new Promise((resolve) => setTimeout(resolve, wait));
1040
- waited += wait;
1041
- head = await headBucket(S3, client, address.bucket);
1042
- if (head.ok || head.status !== 403) break;
1043
- }
1044
- }
1045
- if (head.ok) continue;
1046
- const fail = (reason) => new ProvisionedBucketUnreachable(id, address.bucket, ctx.stage, reason);
1047
- const said = describeAnswer(head);
1048
- if (head.status === 301 || head.status === 400 && head.region && head.region !== asked) {
1049
- let where = head.region;
1050
- let located = "";
1051
- if (!where) {
1052
- const location = await bucketLocation(S3, client, address.bucket);
1053
- if ("region" in location) where = location.region;
1054
- else located = `; GetBucketLocation answered ${describeAnswer(location.failed)}`;
1055
- }
1056
- if (where && where !== asked) throw new BucketRegionMismatch(id, address.bucket, ctx.stage, urlKey, where, address.region, asked, said);
1057
- throw fail(`S3 redirected the request (${said}${located})`);
1058
- }
1059
- if (head.status === 404) throw fail(`it does not exist (${said})`);
1060
- 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` : ""));
1061
- throw fail(said);
1062
- } finally {
1063
- client.destroy();
1064
- }
1065
- }
1066
- }
1067
- //#endregion
1068
- //#region src/providers/registry.ts
1069
- /**
1070
- * The providers gkm ships, by kind and name — registered the way a deploy
1071
- * target's built-ins are (`target/builtins.ts`). A provider from a package is
1072
- * one more entry here once there is a loading story for it.
1073
- */
1074
- const BUILTIN_PROVIDERS = { objects: { s3: {
1075
- kind: "objects",
1076
- name: "s3",
1077
- check: checkS3Config,
1078
- provisioning: S3_PROVISIONING,
1079
- credentials: awsProvisioningCredentials,
1080
- runtimeKeys(manifest) {
1081
- return bucketConstructs(manifest).flatMap((b) => [provideKey(b.id, "url"), ...b.servers.map((s) => provideKey(s.id, "url"))]);
1082
- },
1083
- ensure: ensureS3,
1084
- verify: verifyS3
1085
- } } };
1086
- /** The provider `kind` names `name`, if gkm has one. */
1087
- function builtinProvider(kind, name) {
1088
- return Object.hasOwn(BUILTIN_PROVIDERS[kind], name) ? BUILTIN_PROVIDERS[kind][name] : void 0;
1089
- }
1090
- //#endregion
1091
- //#region src/providers/index.ts
1092
- /** The constructs of a kind: `objects` is every bucket. */
1093
- function constructsOf(manifest, kind) {
1094
- return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
1095
- }
1096
- /**
1097
- * What every deploy runs: each provider's `verify()` — the cheap check that
1098
- * what it created is still there and the stage's key reaches it. Nothing on
1099
- * the local stage, and nothing for a kind on `external` or `false` — a kind
1100
- * the stage has none of is the deploy's readiness check's to refuse.
1101
- */
1102
- async function verifyStageProviders(input) {
1103
- const verified = [];
1104
- for (const kind of PROVIDER_KINDS) {
1105
- if (constructsOf(input.manifest, kind).length === 0) continue;
1106
- const choice = stageProvider(input.workspace, kind, input.stage);
1107
- if (choice.mode !== "provider") continue;
1108
- const provider = builtinProvider(kind, choice.name);
1109
- await provider.verify({
1110
- workspace: input.workspace,
1111
- manifest: input.manifest,
1112
- stage: input.stage,
1113
- config: choice.config,
1114
- secrets: input.secrets,
1115
- ...input.resources ? { resources: input.resources } : {},
1116
- ...input.log ? { log: input.log } : {}
1117
- });
1118
- verified.push(`${kind}: ${provider.name}`);
1119
- }
1120
- return verified;
1121
- }
1122
- /**
1123
- * A stage whose provider creates its resources, and no credentials to create
1124
- * them with. Raised before anything is created, built or started.
1125
- */
1126
- var ProviderCredentialsMissing = class extends GkmError {
1127
- stage;
1128
- kind;
1129
- provider;
1130
- ids;
1131
- env;
1132
- describe;
1133
- login;
1134
- constructor(stage, kind, provider, ids, env, describe, login) {
1135
- 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 (or gkm deploy --resources-only) 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'.`);
1136
- this.stage = stage;
1137
- this.kind = kind;
1138
- this.provider = provider;
1139
- this.ids = ids;
1140
- this.env = env;
1141
- this.describe = describe;
1142
- this.login = login;
1143
- this.name = "ProviderCredentialsMissing";
1144
- }
1145
- };
1146
- /**
1147
- * `ensure()` for every provider the stage configures — find or create, fix
1148
- * drift, record in the stage's state, write the runtime keys into its
1149
- * secrets. Run by the deploy, which holds the stage's lock. A provider with
1150
- * no provisioning credentials stops the run with
1151
- * {@link ProviderCredentialsMissing} before anything is created.
1152
- */
1153
- async function provisionStage(options) {
1154
- const { workspace, stage, manifest } = options;
1155
- const dryRun = options.dryRun === true;
1156
- const env = options.env ?? process.env;
1157
- const log = options.log ?? ((line) => console.log(line));
1158
- const runnables = options.runnables ?? {};
1159
- const reports = [];
1160
- const configured = [];
1161
- for (const kind of PROVIDER_KINDS) {
1162
- const choice = stageProvider(workspace, kind, stage);
1163
- if (choice.mode !== "provider") {
1164
- reports.push({
1165
- kind,
1166
- mode: choice.mode,
1167
- actions: [],
1168
- planned: []
1169
- });
1170
- continue;
1171
- }
1172
- const provider = builtinProvider(kind, choice.name);
1173
- const report = {
1174
- kind,
1175
- mode: "provider",
1176
- provider: provider.name,
1177
- actions: [],
1178
- planned: []
1179
- };
1180
- reports.push(report);
1181
- const ids = constructsOf(manifest, kind);
1182
- if (ids.length === 0) continue;
1183
- const credential = await provider.credentials({
1184
- stage,
1185
- env,
1186
- ...options.profile ? { profile: options.profile } : {},
1187
- ...options.home ? { home: options.home } : {}
1188
- });
1189
- if (credential === void 0) throw new ProviderCredentialsMissing(stage, kind, provider.name, ids, provider.provisioning.env, provider.provisioning.describe, provider.provisioning.login);
1190
- configured.push({
1191
- kind,
1192
- provider,
1193
- config: choice.config,
1194
- credential,
1195
- report
1196
- });
1197
- }
1198
- if (configured.length === 0) return reports;
1199
- const identity = deployIdentity(workspace, stage);
1200
- let secrets = (await options.secrets.read())?.custom ?? {};
1201
- for (const entry of configured) entry.report.planned = entry.provider.runtimeKeys(manifest).filter((key) => secrets[key] === void 0);
1202
- const state = dryRun ? await readOnlyState(options.state, stage) : journalState(await DeployJournal.open(options.state, stage, () => deploysWithCompose(workspace) ? createComposeState(stage) : createEmptyState(stage, "", "")));
1203
- const writeSecrets = async (values) => {
1204
- if (dryRun) return;
1205
- const stored = await options.secrets.read() ?? initStageSecrets(stage);
1206
- const next = {
1207
- ...stored,
1208
- custom: {
1209
- ...stored.custom,
1210
- ...values
1211
- },
1212
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1213
- };
1214
- await options.secrets.write(next);
1215
- secrets = next.custom;
1216
- };
1217
- for (const entry of configured) {
1218
- log(`☁️ ${entry.kind}: ${entry.provider.name}${dryRun ? " (dry run)" : ""}`);
1219
- await entry.provider.ensure({
1220
- workspace,
1221
- manifest,
1222
- runnables,
1223
- stage,
1224
- identity,
1225
- config: entry.config,
1226
- credential: entry.credential,
1227
- get secrets() {
1228
- return secrets;
1229
- },
1230
- state,
1231
- dryRun,
1232
- rotateKeys: options.rotateKeys === true,
1233
- retireOldKeys: options.retireOldKeys === true,
1234
- async change(action, apply) {
1235
- if (!dryRun) await apply();
1236
- entry.report.actions.push(action);
1237
- log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
1238
- },
1239
- writeSecrets,
1240
- log
1241
- });
1242
- if (entry.report.actions.length === 0) log(" up to date");
1243
- }
1244
- return reports;
1245
- }
1246
- /** The journal as `ensure()` sees it. */
1247
- function journalState(journal) {
1248
- return {
1249
- record: (key) => journal.record(key),
1250
- pending: (entry) => journal.pending(entry),
1251
- ready: (entry, id) => journal.ready(entry, id),
1252
- lastDeployedAt: journal.existed ? journal.state.lastDeployedAt : void 0
1253
- };
1254
- }
1255
- /** What a dry run reads, and the writes it does not make. */
1256
- async function readOnlyState(store, stage) {
1257
- const stored = await store.read(stage);
1258
- return {
1259
- record: (key) => stored?.resources[key],
1260
- pending: async () => {},
1261
- ready: async () => {},
1262
- ...stored ? { lastDeployedAt: stored.state.lastDeployedAt } : {}
1263
- };
1264
- }
1265
- //#endregion
1266
- //#region src/secrets/stale.ts
1267
- /**
1268
- * Stored secrets an older gkm generated that now shadow a derived value.
1269
- *
1270
- * Before constructs, initialising a stage wrote an address for each app into
1271
- * its custom secrets: `<APP>_DATABASE_URL` as a `postgresql://…@localhost`
1272
- * URL with a password of its own, and `http://localhost:<port>` for a site or
1273
- * an auth server. Those keys are now a construct's — `database.schema('AuthDatabase')`
1274
- * provides `AUTH_DATABASE_URL`, `new BetterAuth('Auth')` provides `AUTH_URL`
1275
- * — and a deploy derives them. A value the stage holds is a value set by hand,
1276
- * and set by hand wins: the container is handed `localhost`, where nothing
1277
- * answers, with a password no role has.
1278
- *
1279
- * So a deploy refuses such a stage rather than run it, naming each key and
1280
- * the command that removes it. Nothing is deleted for the user: the value is
1281
- * theirs, and only they can say it is stale. A URL that names a real host — a
1282
- * managed database — is a deliberate choice and still wins.
1283
- */
1284
- /** The kinds whose URL an older gkm wrote into a stage's secrets. */
1285
- const ADDRESSED = /* @__PURE__ */ new Set([
1286
- "database",
1287
- "database-reader",
1288
- "database-schema",
1289
- "rest-api",
1290
- "site"
1291
- ]);
1292
- /** Hosts that are this machine — never anything, inside a container. */
1293
- const LOOPBACK = /* @__PURE__ */ new Set([
1294
- "localhost",
1295
- "127.0.0.1",
1296
- "[::1]",
1297
- "::1"
1298
- ]);
1299
- /**
1300
- * A stage holds a construct's address as a custom secret, pointing at
1301
- * `localhost` — what an older `gkm secrets:init`, `gkm setup` or `gkm init`
1302
- * generated. Set by hand wins over derived, so the app would be handed it.
1303
- */
1304
- var StaleStageSecrets = class extends GkmError {
1305
- stage;
1306
- stale;
1307
- constructor(stage, stale) {
1308
- const one = stale.length === 1;
1309
- 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") + `
1310
- 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.");
1311
- this.stage = stage;
1312
- this.stale = stale;
1313
- this.name = "StaleStageSecrets";
1314
- }
1315
- };
1316
- /** The host a stored value names, if it is a URL. */
1317
- function hostOf(value) {
1318
- try {
1319
- return new URL(value).hostname;
1320
- } catch {
1321
- return;
1322
- }
1323
- }
1324
- /**
1325
- * Each stored key that a construct provides an address for, holding an
1326
- * address on this machine.
1327
- */
1328
- function staleStageSecrets(manifest, supplied) {
1329
- const stale = [];
1330
- for (const [id, declaration] of Object.entries(manifest)) {
1331
- if (!ADDRESSED.has(declaration.kind)) continue;
1332
- const key = providedKeyFor(id, declaration.kind, "url");
1333
- const value = supplied[key];
1334
- if (value === void 0) continue;
1335
- const host = hostOf(value);
1336
- if (host === void 0 || !LOOPBACK.has(host)) continue;
1337
- stale.push({
1338
- key,
1339
- construct: id,
1340
- host
1341
- });
1342
- }
1343
- return stale.sort((a, b) => a.key.localeCompare(b.key));
1344
- }
1345
- /**
1346
- * Refuse a stage whose stored secrets would shadow a construct's address with
1347
- * `localhost`.
1348
- *
1349
- * @throws {StaleStageSecrets} naming each key and the command removing it
1350
- */
1351
- function assertNoStaleSecrets(options) {
1352
- const stale = staleStageSecrets(options.manifest, options.supplied);
1353
- if (stale.length > 0) throw new StaleStageSecrets(options.stage, stale);
1354
- }
1355
- //#endregion
1356
- //#region src/deploy/readiness.ts
1357
- /**
1358
- * Whether a stage is ready to be deployed: the one check, run once by every
1359
- * deploy through a server target — after the stage's providers have created
1360
- * what they create and written its keys, and before the target touches
1361
- * anything.
1362
- *
1363
- * A build is not a deploy. Images carry no stage's keys, so a build-only run
1364
- * (`gkm compose --build --push`) never calls this: a key the deploy itself
1365
- * writes — a provider's bucket URL — is not there yet when CI builds, and
1366
- * must not stop the build.
1367
- */
1368
- /**
1369
- * The stage has every key it needs, read from its secrets as the providers
1370
- * left them:
1371
- *
1372
- * 1. no kind it declares is one the stage set to `false`;
1373
- * 2. its mail and storage are its own — or a dev service, where allowed,
1374
- * reported once, loudly;
1375
- * 3. what its providers created is still there, and its key reaches it;
1376
- * 4. no key holds an address an older gkm stored for what a construct now
1377
- * provides;
1378
- * 5. each third party's credentials match their construct's schema.
1379
- *
1380
- * The local stage derives its mail and storage, so only 4 and 5 apply to it.
1381
- *
1382
- * @throws {StageProviderDisabled}
1383
- * @throws {ExternalServicesNotConfigured} naming every missing key at once
1384
- * @throws {StaleStageSecrets}
1385
- * @throws {CredentialsInvalid}
1386
- */
1387
- async function assertStageReady(ctx) {
1388
- const { workspace, manifest, stage } = ctx;
1389
- const supplied = (await ctx.secrets.read())?.custom ?? {};
1390
- if (stage !== workspace.stages.local) {
1391
- assertStageProvidersEnabled(workspace, manifest, stage);
1392
- const domain = workspace.domains?.[stage];
1393
- const services = externalServices({
1394
- stage,
1395
- declarations: stageServiceDeclarations({
1396
- manifest,
1397
- ...ctx.runnables ? { runnables: ctx.runnables } : {}
1398
- }),
1399
- supplied,
1400
- allow: ctx.allowDevServices,
1401
- ...domain ? { domain } : {},
1402
- providers: stageProviderNotes(workspace, stage)
1403
- });
1404
- if (services.missing.length > 0) throw new ExternalServicesNotConfigured(stage, services.missing);
1405
- reportDevServices(ctx, devServicesUsed(services));
1406
- const verified = await verifyStageProviders({
1407
- workspace,
1408
- manifest,
1409
- stage,
1410
- secrets: supplied,
1411
- resources: (await ctx.state.read(stage))?.resources ?? {},
1412
- log: (line) => ctx.logger.info(line)
1413
- });
1414
- for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
1415
- }
1416
- assertNoStaleSecrets({
1417
- manifest,
1418
- stage,
1419
- supplied
1420
- });
1421
- await assertStageCredentials({
1422
- root: workspace.root,
1423
- patterns: constructGlobs(workspace),
1424
- manifest,
1425
- stage,
1426
- supplied
1427
- });
1428
- }
1429
- //#endregion
1430
- //#region src/deploy/orchestrate.ts
1431
- /**
1432
- * The run around a target: what every deploy does whatever it deploys
1433
- * through.
1434
- *
1435
- * It loads the workspace, resolves the target, works out the apps and the
1436
- * identity, takes the stage's lock, and calls the target's phases in order,
1437
- * reporting each as it starts, finishes or fails. Everything that is about
1438
- * *where* the stage goes is the target's.
1439
- */
1440
- /** `--resources-only` with `--skip-resources`: the one asks for what the other skips. */
1441
- var ResourcesOnlyAndSkipped = class extends GkmError {
1442
- constructor() {
1443
- super("--resources-only creates the stage's resources and nothing else, and --skip-resources deploys without creating them. Run the first where the cloud credentials are (a CI runner), then the second where the stack runs.");
1444
- this.name = "ResourcesOnlyAndSkipped";
1445
- }
1446
- };
1447
- /** Apps were asked for by name that the workspace does not have. */
1448
- var UnknownDeployApps = class extends GkmError {
1449
- apps;
1450
- available;
1451
- constructor(apps, available) {
1452
- super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
1453
- this.apps = apps;
1454
- this.available = available;
1455
- this.name = "UnknownDeployApps";
1456
- }
1457
- };
1458
- /** Every app asked for deploys through some other target. */
1459
- var NoDeployableApps = class extends GkmError {
1460
- stage;
1461
- target;
1462
- constructor(stage, target) {
1463
- 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.`);
1464
- this.stage = stage;
1465
- this.target = target;
1466
- this.name = "NoDeployableApps";
1467
- }
1468
- };
1469
- /** A build-only run through a target with no build phase. */
1470
- var TargetBuildsNothing = class extends GkmError {
1471
- target;
1472
- constructor(target) {
1473
- 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).`);
1474
- this.target = target;
1475
- this.name = "TargetBuildsNothing";
1476
- }
1477
- };
1478
- /** A failed rollback, after the failure that called for it. */
1479
- var RollbackFailed = class extends Error {
1480
- target;
1481
- failure;
1482
- constructor(target, failure, cause) {
1483
- 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 });
1484
- this.target = target;
1485
- this.failure = failure;
1486
- this.name = "RollbackFailed";
1487
- }
1488
- };
1489
- /**
1490
- * Generate image tag from stage and timestamp
1491
- */
1492
- function generateTag(stage) {
1493
- return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
1494
- }
1495
- /** Why an app that deploys through another target is left out. */
1496
- function elsewhere(target, stage) {
1497
- const instead = builtinTarget(target)?.instead?.(stage);
1498
- if (instead) return `it deploys through "${target}" — ${instead}`;
1499
- return `it deploys through "${target}" — run \`gkm deploy --target ${target} --stage ${stage}\``;
1500
- }
1501
- /**
1502
- * Deploy a workspace's stage through its target.
1503
- *
1504
- * The engine under `deploy()` and `gkm deploy`. It never prompts and never
1505
- * exits: credentials come from `ctx.credentials`, progress goes to
1506
- * `ctx.emit` and to `output`, and every failure is thrown.
1507
- *
1508
- * @internal
1509
- */
1510
- async function runDeploy(source, request, ctx) {
1511
- const { stage } = request;
1512
- const redactor = ctx.redactor ?? new Redactor();
1513
- const emit = (event) => ctx.emit(event.type === "log" ? {
1514
- ...event,
1515
- message: redactor.redact(event.message)
1516
- } : event);
1517
- /** Run one phase between its events. */
1518
- const phase = async (name, body) => {
1519
- ctx.signal?.throwIfAborted();
1520
- emit({
1521
- type: "phase.started",
1522
- phase: name
1523
- });
1524
- try {
1525
- const value = await body();
1526
- emit({
1527
- type: "phase.finished",
1528
- phase: name
1529
- });
1530
- return value;
1531
- } catch (error) {
1532
- emit({
1533
- type: "phase.failed",
1534
- phase: name,
1535
- error: eventError(error)
1536
- });
1537
- throw error;
1538
- }
1539
- };
1540
- ctx.signal?.throwIfAborted();
1541
- emit({
1542
- type: "phase.started",
1543
- phase: "validate"
1544
- });
1545
- let prepared;
1546
- try {
1547
- prepared = await prepare(source, request, ctx, emit, redactor);
1548
- } catch (error) {
1549
- emit({
1550
- type: "phase.failed",
1551
- phase: "validate",
1552
- error: eventError(error)
1553
- });
1554
- throw error;
1555
- }
1556
- const { resolved, phaseCtx, store } = prepared;
1557
- const { target } = resolved;
1558
- const resources = !ctx.buildOnly && !request.skipResources && phaseCtx.stage !== phaseCtx.workspace.stages.local;
1559
- const provision = async () => {
1560
- if (!request.skipDns && resolved.target.runtime === "server") try {
1561
- await dnsCredentials(phaseCtx.stage, stageDnsDomains(phaseCtx.stage, phaseCtx.workspace.domains, phaseCtx.workspace.dns), ctx.credentials);
1562
- } catch (error) {
1563
- emit({
1564
- type: "phase.failed",
1565
- phase: "validate",
1566
- error: eventError(error)
1567
- });
1568
- throw error;
1569
- }
1570
- await provisionResources(phaseCtx, request, ctx, store, emit);
1571
- };
1572
- if (ctx.dryRun) {
1573
- if (resources) await provision();
1574
- if (request.resourcesOnly) return resourcesOnly(target, phaseCtx, emit);
1575
- const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
1576
- await phase("plan", () => target.plan(phaseCtx, run));
1577
- return target.result(phaseCtx, run);
1578
- }
1579
- if (ctx.buildOnly) {
1580
- if (!target.build) throw new TargetBuildsNothing(resolved.name);
1581
- const run = await validate(phaseCtx, emit, () => target.validate(phaseCtx));
1582
- await phase("build", () => target.build(phaseCtx, run));
1583
- return target.result(phaseCtx, run);
1584
- }
1585
- let lock;
1586
- try {
1587
- assertStateOutlivesRun(phaseCtx.workspace, stage, "deploy");
1588
- lock = await store.lock(stage, { operation: "deploy" });
1589
- } catch (error) {
1590
- emit({
1591
- type: "phase.failed",
1592
- phase: "validate",
1593
- error: eventError(error)
1594
- });
1595
- throw error;
1596
- }
1597
- try {
1598
- try {
1599
- await assertStateRoom(store, stage);
1600
- } catch (error) {
1601
- emit({
1602
- type: "phase.failed",
1603
- phase: "validate",
1604
- error: eventError(error)
1605
- });
1606
- throw error;
1607
- }
1608
- if (resources) await provision();
1609
- if (request.resourcesOnly) return resourcesOnly(target, phaseCtx, emit);
1610
- const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
1611
- if (target.provision) await phase("provision", () => target.provision(phaseCtx, run));
1612
- if (target.build) await phase("build", () => target.build(phaseCtx, run));
1613
- let releasing = "release";
1614
- try {
1615
- await phase("release", () => target.release(phaseCtx, run));
1616
- releasing = "verify";
1617
- if (target.verify) await phase("verify", () => target.verify(phaseCtx, run));
1618
- } catch (error) {
1619
- if (ctx.signal?.aborted || !target.capabilities.rollback) throw error;
1620
- if (!target.rollback) throw error;
1621
- try {
1622
- await phase("rollback", () => target.rollback(phaseCtx, run, {
1623
- phase: releasing,
1624
- error
1625
- }));
1626
- } catch (rollbackError) {
1627
- throw new RollbackFailed(resolved.name, error, rollbackError);
1628
- }
1629
- throw error;
1630
- }
1631
- return await target.result(phaseCtx, run);
1632
- } finally {
1633
- await lock.release();
1634
- }
1635
- }
1636
- /**
1637
- * The stage's providers, run inside the validate phase. A dry run plans them
1638
- * and, so the checks after it see the stage as the run would leave it, reads
1639
- * the keys they would write as placeholders.
1640
- */
1641
- async function provisionResources(phaseCtx, request, ctx, store, emit) {
1642
- try {
1643
- const reports = await provisionStage({
1644
- workspace: phaseCtx.workspace,
1645
- stage: phaseCtx.stage,
1646
- manifest: phaseCtx.manifest,
1647
- runnables: phaseCtx.runnables ?? {},
1648
- secrets: phaseCtx.secrets,
1649
- state: store,
1650
- dryRun: ctx.dryRun,
1651
- ...request.rotateKeys ? { rotateKeys: true } : {},
1652
- ...request.retireOldKeys ? { retireOldKeys: true } : {},
1653
- ...ctx.home ? { home: ctx.home } : {},
1654
- log: (line) => phaseCtx.logger.info(line)
1655
- });
1656
- if (!ctx.dryRun) return;
1657
- const planned = reports.flatMap((r) => r.planned);
1658
- if (planned.length === 0) return;
1659
- const secrets = phaseCtx.secrets;
1660
- phaseCtx.secrets = {
1661
- ...secrets,
1662
- async read() {
1663
- const stored = await secrets.read() ?? initStageSecrets(phaseCtx.stage);
1664
- const custom = { ...stored.custom };
1665
- for (const key of planned) custom[key] ??= PLANNED_BY_THE_DEPLOY;
1666
- return {
1667
- ...stored,
1668
- custom
1669
- };
1670
- }
1671
- };
1672
- } catch (error) {
1673
- emit({
1674
- type: "phase.failed",
1675
- phase: "validate",
1676
- error: eventError(error)
1677
- });
1678
- throw error;
1679
- }
1680
- }
1681
- /** What a dry run reads for a key its providers would write. */
1682
- const PLANNED_BY_THE_DEPLOY = "s3://planned-by-this-deploy";
1683
- /** `--resources-only`: the target's own resources, and nothing else. */
1684
- async function resourcesOnly(target, phaseCtx, emit) {
1685
- try {
1686
- if (target.resources) await target.resources(phaseCtx);
1687
- } catch (error) {
1688
- emit({
1689
- type: "phase.failed",
1690
- phase: "validate",
1691
- error: eventError(error)
1692
- });
1693
- throw error;
1694
- }
1695
- emit({
1696
- type: "phase.finished",
1697
- phase: "validate"
1698
- });
1699
- return resourcesResult(phaseCtx);
1700
- }
1701
- /** A `--resources-only` run: no app was deployed. */
1702
- function resourcesResult(phaseCtx) {
1703
- return {
1704
- apps: [],
1705
- projectId: "",
1706
- successCount: 0,
1707
- failedCount: 0,
1708
- stage: phaseCtx.stage,
1709
- identity: phaseCtx.identity.key,
1710
- tag: phaseCtx.tag,
1711
- dryRun: phaseCtx.dryRun,
1712
- environmentId: "",
1713
- skipped: [...phaseCtx.skipped],
1714
- urls: {},
1715
- changes: []
1716
- };
1717
- }
1718
- /**
1719
- * What a deploy validates: the stage ready to be deployed — every key it
1720
- * needs, read as its providers left them — then what the target would run,
1721
- * then whatever only the target checks. A build-only run validates the
1722
- * target's run alone: it calls neither readiness check.
1723
- */
1724
- async function readyToDeploy(target, phaseCtx) {
1725
- if (target.runtime === "server") await assertStageReady(phaseCtx);
1726
- const run = await target.validate(phaseCtx);
1727
- await target.ready?.(phaseCtx, run);
1728
- return run;
1729
- }
1730
- /** `body`, then the run's `deploy.started`, inside the validate phase. */
1731
- async function validate(phaseCtx, emit, body) {
1732
- try {
1733
- const run = await body();
1734
- const skipped = new Set(phaseCtx.skipped.map((s) => s.app));
1735
- emit({
1736
- type: "deploy.started",
1737
- stage: phaseCtx.stage,
1738
- target: phaseCtx.target,
1739
- identity: phaseCtx.identity.key,
1740
- tag: phaseCtx.tag,
1741
- apps: phaseCtx.apps.filter((app) => !skipped.has(app)),
1742
- dryRun: phaseCtx.dryRun
1743
- });
1744
- emit({
1745
- type: "phase.finished",
1746
- phase: "validate"
1747
- });
1748
- return run;
1749
- } catch (error) {
1750
- emit({
1751
- type: "phase.failed",
1752
- phase: "validate",
1753
- error: eventError(error)
1754
- });
1755
- throw error;
1756
- }
1757
- }
1758
- /** Everything the phases are handed, worked out before the first of them. */
1759
- async function prepare(source, request, ctx, emit, redactor) {
1760
- const { stage } = request;
1761
- if (request.resourcesOnly && request.skipResources) throw new ResourcesOnlyAndSkipped();
1762
- const configured = typeof source === "function" ? await source() : source;
1763
- const local = stage === configured.stages.local;
1764
- if (!local) assertDeployedStage(configured.stages, stage);
1765
- const targetName = request.target ?? configured.deploy?.default ?? "dokploy";
1766
- const resolved = await resolveTarget(targetName, {
1767
- workspace: configured,
1768
- stage,
1769
- ...ctx.targets ? { host: ctx.targets } : {}
1770
- });
1771
- if (local && !resolved.target.capabilities.localStage) assertDeployedStage(configured.stages, stage);
1772
- const options = await parseTargetOptions(resolved);
1773
- const allowDevServices = request.allowDevServices === true;
1774
- if (allowDevServices && resolved.target.runtime === "aws") throw new DevServicesNeedServerTarget(targetName);
1775
- const runnables = {};
1776
- const background = {};
1777
- const manifest = await discover({
1778
- patterns: constructGlobs(configured),
1779
- cwd: configured.root,
1780
- runnables,
1781
- background
1782
- });
1783
- resolveStageTelemetry({
1784
- ...configured.deploy?.telemetry ? { telemetry: configured.deploy.telemetry } : {},
1785
- stage,
1786
- local,
1787
- target: targetName,
1788
- runtime: resolved.target.runtime,
1789
- selfHosted: resolved.target.capabilities.selfHostedTelemetry === true,
1790
- used: usesTelemetry(manifest)
1791
- });
1792
- const units = derivedApps(manifest, configured);
1793
- const workspace = Object.keys(units).length > 0 ? {
1794
- ...configured,
1795
- apps: units
1796
- } : configured;
1797
- const identity = deployIdentity(workspace, stage);
1798
- const tag = request.tag ?? (resolved.target.tag ? await resolved.target.tag({
1799
- cwd: workspace.root,
1800
- stage
1801
- }) : generateTag(stage));
1802
- const buildOrder = getAppBuildOrder(workspace);
1803
- let selected = buildOrder;
1804
- if (request.apps && request.apps.length > 0) {
1805
- const unknown = request.apps.filter((name) => !workspace.apps[name]);
1806
- if (unknown.length > 0) throw new UnknownDeployApps(unknown, Object.keys(workspace.apps));
1807
- selected = buildOrder.filter((name) => request.apps.includes(name));
1808
- }
1809
- const skipped = [];
1810
- const skip = (app, reason) => {
1811
- skipped.push({
1812
- app,
1813
- reason
1814
- });
1815
- emit({
1816
- type: "app.skipped",
1817
- app,
1818
- reason
1819
- });
1820
- };
1821
- const byDefault = configured.deploy?.default ?? "dokploy";
1822
- const apps = selected.filter((name) => {
1823
- const own = workspace.apps[name].resolvedDeployTarget;
1824
- const deploysThrough = own === byDefault ? targetName : own;
1825
- if (deploysThrough === targetName) return true;
1826
- skip(name, elsewhere(deploysThrough, stage));
1827
- return false;
1828
- });
1829
- if (apps.length === 0) throw new NoDeployableApps(stage, targetName);
1830
- const store = await createStateStore({
1831
- config: workspace.state,
1832
- workspaceRoot: workspace.root,
1833
- workspaceName: workspace.name,
1834
- namespace: workspace.deploy?.namespace
1835
- });
1836
- const secrets = await deploySecrets(workspace, stage, redactor, { ...ctx.home ? { home: ctx.home } : {} });
1837
- const line = (level) => (message) => emit({
1838
- type: "log",
1839
- level,
1840
- message
1841
- });
1842
- const logger = {
1843
- info: line("info"),
1844
- warn: line("warn"),
1845
- error: line("error")
1846
- };
1847
- return {
1848
- resolved,
1849
- phaseCtx: {
1850
- target: targetName,
1851
- cwd: workspace.root,
1852
- stage,
1853
- tag,
1854
- tagGiven: request.tag !== void 0,
1855
- apps,
1856
- skipped,
1857
- identity,
1858
- workspace,
1859
- manifest,
1860
- runnables,
1861
- background,
1862
- options,
1863
- dryRun: ctx.dryRun,
1864
- atomic: request.atomic ?? false,
1865
- allowDevServices,
1866
- ...request.skipDns ? { skipDns: true } : {},
1867
- ...request.skipResources ? { skipResources: true } : {},
1868
- credentials: ctx.credentials,
1869
- state: store,
1870
- secrets,
1871
- logger,
1872
- signal: ctx.signal ?? new AbortController().signal,
1873
- childOutput: ctx.childOutput ?? "inherit",
1874
- emit,
1875
- skip,
1876
- name: (resource) => applicationName(identity, resource)
1877
- },
1878
- store
1879
- };
1880
- }
1881
- //#endregion
1882
- //#region src/deploy/deploy.ts
1883
- /**
1884
- * `deploy()`: a deploy as a library call.
1885
- *
1886
- * `gkm deploy` could only be driven from an interactive terminal: it prompted
1887
- * for what it lacked and exited the process on failure, worked out of
1888
- * `process.cwd()`, and reported progress by printing. Here the caller says
1889
- * where the project is, hands over the credentials and a signal, and gets back
1890
- * a run — events to iterate while it goes, and a structured result at the end.
1891
- * Nothing below this asks a person anything or ends the process; `gkm deploy`
1892
- * is a thin wrapper that does both.
1893
- */
1894
- /**
1895
- * Every event a run emits, kept so that each iteration — however late it
1896
- * starts — sees the run from its first event to its last.
1897
- */
1898
- var EventLog = class {
1899
- events = [];
1900
- closed = false;
1901
- waiting = [];
1902
- push(event) {
1903
- this.events.push(event);
1904
- this.wake();
1905
- }
1906
- close() {
1907
- this.closed = true;
1908
- this.wake();
1909
- }
1910
- wake() {
1911
- const waiting = this.waiting;
1912
- this.waiting = [];
1913
- for (const resume of waiting) resume();
1914
- }
1915
- async *iterate() {
1916
- let next = 0;
1917
- while (true) if (next < this.events.length) yield this.events[next++];
1918
- else if (this.closed) return;
1919
- else await new Promise((resume) => this.waiting.push(resume));
1920
- }
1921
- };
1922
- function forward(logger, level, message) {
1923
- if (!logger) return;
1924
- if (level === "info") logger.info(message);
1925
- else if (level === "error" && logger.error) logger.error(message);
1926
- else logger.warn(message);
1927
- }
1928
- /**
1929
- * Deploy a project's stage.
1930
- *
1931
- * ```ts
1932
- * import { deploy } from '@geekmidas/cli/deploy';
1933
- *
1934
- * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
1935
- * for await (const event of run) {
1936
- * if (event.type === 'app.deployed') console.log(event.app, event.url);
1937
- * }
1938
- * const result = await run.result;
1939
- * ```
1940
- *
1941
- * The run starts at once; iterating it is optional, and an iteration started
1942
- * late still sees every event from the first.
1943
- */
1944
- function deploy(input) {
1945
- const log = new EventLog();
1946
- const redactor = new Redactor();
1947
- const emit = (event) => {
1948
- const masked = event.type === "log" ? {
1949
- ...event,
1950
- message: redactor.redact(event.message)
1951
- } : event;
1952
- log.push(masked);
1953
- if (masked.type === "log") forward(input.logger, masked.level, masked.message);
1954
- };
1955
- const ctx = {
1956
- emit,
1957
- credentials: input.credentials ?? storedCredentials({ home: input.home ?? gkmHome() }),
1958
- dryRun: input.dryRun ?? false,
1959
- ...input.buildOnly ? { buildOnly: true } : {},
1960
- home: input.home ?? gkmHome(),
1961
- redactor,
1962
- ...input.signal ? { signal: input.signal } : {},
1963
- ...input.childOutput ? { childOutput: input.childOutput } : {},
1964
- ...input.targets ? { targets: input.targets } : {}
1965
- };
1966
- const result = withOutput((level, message) => emit({
1967
- type: "log",
1968
- level,
1969
- message
1970
- }), async () => {
1971
- try {
1972
- input.signal?.throwIfAborted();
1973
- const sandbox = input.sandbox ?? new LocalSandbox({ root: findWorkspaceRoot(resolve(input.cwd)) });
1974
- const deployed = await withSandbox(sandbox, () => runDeploy(() => load(input, sandbox), {
1975
- stage: input.stage,
1976
- ...input.target ? { target: input.target } : {},
1977
- ...input.tag ? { tag: input.tag } : {},
1978
- ...input.apps ? { apps: input.apps } : {},
1979
- ...input.atomic ? { atomic: true } : {},
1980
- ...input.allowDevServices ? { allowDevServices: input.allowDevServices } : {},
1981
- ...input.skipDns ? { skipDns: true } : {},
1982
- ...input.resourcesOnly ? { resourcesOnly: true } : {},
1983
- ...input.skipResources ? { skipResources: true } : {},
1984
- ...input.rotateKeys ? { rotateKeys: true } : {},
1985
- ...input.retireOldKeys ? { retireOldKeys: true } : {}
1986
- }, ctx));
1987
- emit({
1988
- type: "deploy.finished",
1989
- result: deployed
1990
- });
1991
- return deployed;
1992
- } catch (error) {
1993
- emit({
1994
- type: "deploy.failed",
1995
- error: eventError(error)
1996
- });
1997
- throw error;
1998
- } finally {
1999
- log.close();
2000
- }
2001
- });
2002
- result.catch(() => {});
2003
- return {
2004
- result,
2005
- [Symbol.asyncIterator]: () => log.iterate()
2006
- };
2007
- }
2008
- /**
2009
- * The workspace at `input.cwd`. The stage is checked by the run, once it
2010
- * knows the target: one that runs on this machine may take the local stage.
2011
- */
2012
- async function load(input, sandbox) {
2013
- const { workspace } = await loadWorkspaceConfig(resolve(input.cwd), { sandbox });
2014
- return workspace;
2015
- }
2016
- //#endregion
2017
- export { UnknownDeployApps as a, iamUserName as c, TargetBuildsNothing as i, NoDeployableApps as n, IAM_USER_PATH as o, RollbackFailed as r, bucketName as s, deploy as t };
2018
-
2019
- //# sourceMappingURL=deploy-Dw8g3sLY.mjs.map