@cubocicloide/stack-react-django 3.0.4

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 (289) hide show
  1. package/LICENSE +33 -0
  2. package/README.md +66 -0
  3. package/dist/commands/lint/checks/BE/001.d.ts +6 -0
  4. package/dist/commands/lint/checks/BE/001.js +94 -0
  5. package/dist/commands/lint/checks/BE/001.js.map +1 -0
  6. package/dist/commands/lint/checks/BE/002.d.ts +6 -0
  7. package/dist/commands/lint/checks/BE/002.js +136 -0
  8. package/dist/commands/lint/checks/BE/002.js.map +1 -0
  9. package/dist/commands/lint/checks/BE/003.d.ts +6 -0
  10. package/dist/commands/lint/checks/BE/003.js +89 -0
  11. package/dist/commands/lint/checks/BE/003.js.map +1 -0
  12. package/dist/commands/lint/checks/BE/004.d.ts +6 -0
  13. package/dist/commands/lint/checks/BE/004.js +68 -0
  14. package/dist/commands/lint/checks/BE/004.js.map +1 -0
  15. package/dist/commands/lint/checks/BE/005.d.ts +6 -0
  16. package/dist/commands/lint/checks/BE/005.js +55 -0
  17. package/dist/commands/lint/checks/BE/005.js.map +1 -0
  18. package/dist/commands/lint/checks/BE/006.d.ts +6 -0
  19. package/dist/commands/lint/checks/BE/006.js +95 -0
  20. package/dist/commands/lint/checks/BE/006.js.map +1 -0
  21. package/dist/commands/lint/checks/BE/007.d.ts +6 -0
  22. package/dist/commands/lint/checks/BE/007.js +53 -0
  23. package/dist/commands/lint/checks/BE/007.js.map +1 -0
  24. package/dist/commands/lint/checks/BE/008.d.ts +6 -0
  25. package/dist/commands/lint/checks/BE/008.js +70 -0
  26. package/dist/commands/lint/checks/BE/008.js.map +1 -0
  27. package/dist/commands/lint/checks/BE/009.d.ts +6 -0
  28. package/dist/commands/lint/checks/BE/009.js +112 -0
  29. package/dist/commands/lint/checks/BE/009.js.map +1 -0
  30. package/dist/commands/lint/checks/BE/010.d.ts +6 -0
  31. package/dist/commands/lint/checks/BE/010.js +76 -0
  32. package/dist/commands/lint/checks/BE/010.js.map +1 -0
  33. package/dist/commands/lint/checks/BE/011.d.ts +6 -0
  34. package/dist/commands/lint/checks/BE/011.js +76 -0
  35. package/dist/commands/lint/checks/BE/011.js.map +1 -0
  36. package/dist/commands/lint/checks/BE/012.d.ts +6 -0
  37. package/dist/commands/lint/checks/BE/012.js +61 -0
  38. package/dist/commands/lint/checks/BE/012.js.map +1 -0
  39. package/dist/commands/lint/checks/BE/013.d.ts +6 -0
  40. package/dist/commands/lint/checks/BE/013.js +98 -0
  41. package/dist/commands/lint/checks/BE/013.js.map +1 -0
  42. package/dist/commands/lint/checks/BE/014.d.ts +6 -0
  43. package/dist/commands/lint/checks/BE/014.js +64 -0
  44. package/dist/commands/lint/checks/BE/014.js.map +1 -0
  45. package/dist/commands/lint/checks/E2E/001.d.ts +6 -0
  46. package/dist/commands/lint/checks/E2E/001.js +35 -0
  47. package/dist/commands/lint/checks/E2E/001.js.map +1 -0
  48. package/dist/commands/lint/checks/E2E/002.d.ts +6 -0
  49. package/dist/commands/lint/checks/E2E/002.js +37 -0
  50. package/dist/commands/lint/checks/E2E/002.js.map +1 -0
  51. package/dist/commands/lint/checks/E2E/003.d.ts +6 -0
  52. package/dist/commands/lint/checks/E2E/003.js +42 -0
  53. package/dist/commands/lint/checks/E2E/003.js.map +1 -0
  54. package/dist/commands/lint/checks/E2E/004.d.ts +6 -0
  55. package/dist/commands/lint/checks/E2E/004.js +37 -0
  56. package/dist/commands/lint/checks/E2E/004.js.map +1 -0
  57. package/dist/commands/lint/checks/E2E/005.d.ts +6 -0
  58. package/dist/commands/lint/checks/E2E/005.js +47 -0
  59. package/dist/commands/lint/checks/E2E/005.js.map +1 -0
  60. package/dist/commands/lint/checks/E2E/006.d.ts +6 -0
  61. package/dist/commands/lint/checks/E2E/006.js +28 -0
  62. package/dist/commands/lint/checks/E2E/006.js.map +1 -0
  63. package/dist/commands/lint/checks/E2E/007.d.ts +6 -0
  64. package/dist/commands/lint/checks/E2E/007.js +47 -0
  65. package/dist/commands/lint/checks/E2E/007.js.map +1 -0
  66. package/dist/commands/lint/checks/FE/001.d.ts +6 -0
  67. package/dist/commands/lint/checks/FE/001.js +56 -0
  68. package/dist/commands/lint/checks/FE/001.js.map +1 -0
  69. package/dist/commands/lint/checks/FE/002.d.ts +6 -0
  70. package/dist/commands/lint/checks/FE/002.js +80 -0
  71. package/dist/commands/lint/checks/FE/002.js.map +1 -0
  72. package/dist/commands/lint/checks/FE/003.d.ts +6 -0
  73. package/dist/commands/lint/checks/FE/003.js +65 -0
  74. package/dist/commands/lint/checks/FE/003.js.map +1 -0
  75. package/dist/commands/lint/checks/FE/004.d.ts +6 -0
  76. package/dist/commands/lint/checks/FE/004.js +72 -0
  77. package/dist/commands/lint/checks/FE/004.js.map +1 -0
  78. package/dist/commands/lint/checks/FE/005.d.ts +6 -0
  79. package/dist/commands/lint/checks/FE/005.js +103 -0
  80. package/dist/commands/lint/checks/FE/005.js.map +1 -0
  81. package/dist/commands/lint/checks/FE/006.d.ts +6 -0
  82. package/dist/commands/lint/checks/FE/006.js +102 -0
  83. package/dist/commands/lint/checks/FE/006.js.map +1 -0
  84. package/dist/commands/lint/checks/FE/007.d.ts +6 -0
  85. package/dist/commands/lint/checks/FE/007.js +60 -0
  86. package/dist/commands/lint/checks/FE/007.js.map +1 -0
  87. package/dist/commands/lint/checks/FE/008.d.ts +6 -0
  88. package/dist/commands/lint/checks/FE/008.js +115 -0
  89. package/dist/commands/lint/checks/FE/008.js.map +1 -0
  90. package/dist/commands/lint/checks/FE/009.d.ts +6 -0
  91. package/dist/commands/lint/checks/FE/009.js +83 -0
  92. package/dist/commands/lint/checks/FE/009.js.map +1 -0
  93. package/dist/commands/lint/checks/FE/010.d.ts +6 -0
  94. package/dist/commands/lint/checks/FE/010.js +105 -0
  95. package/dist/commands/lint/checks/FE/010.js.map +1 -0
  96. package/dist/commands/lint/checks/FE/011.d.ts +6 -0
  97. package/dist/commands/lint/checks/FE/011.js +43 -0
  98. package/dist/commands/lint/checks/FE/011.js.map +1 -0
  99. package/dist/commands/lint/checks/FE/012.d.ts +6 -0
  100. package/dist/commands/lint/checks/FE/012.js +150 -0
  101. package/dist/commands/lint/checks/FE/012.js.map +1 -0
  102. package/dist/index.d.ts +5 -0
  103. package/dist/index.js +3436 -0
  104. package/dist/index.js.map +1 -0
  105. package/dude.stack.json +13 -0
  106. package/package.json +43 -0
  107. package/templates/aws-ecs/backend/Dockerfile.prod +34 -0
  108. package/templates/aws-ecs/docs/docs/deploy.md.hbs +54 -0
  109. package/templates/aws-ecs/frontend/Dockerfile.prod +28 -0
  110. package/templates/aws-ecs/frontend/nginx.conf +21 -0
  111. package/templates/aws-ecs/iac/README.md.hbs +75 -0
  112. package/templates/aws-ecs/iac/_gitignore +14 -0
  113. package/templates/aws-ecs/iac/runner/Dockerfile +35 -0
  114. package/templates/aws-ecs/iac/terraform/bootstrap/main.tf.hbs +102 -0
  115. package/templates/aws-ecs/iac/terraform/bootstrap/outputs.tf +19 -0
  116. package/templates/aws-ecs/iac/terraform/bootstrap/variables.tf.hbs +17 -0
  117. package/templates/aws-ecs/iac/terraform/environments/dev/backend.hcl.hbs +12 -0
  118. package/templates/aws-ecs/iac/terraform/environments/dev/terraform.tfvars.hbs +43 -0
  119. package/templates/aws-ecs/iac/terraform/main.tf.hbs +949 -0
  120. package/templates/aws-ecs/iac/terraform/outputs.tf.hbs +71 -0
  121. package/templates/aws-ecs/iac/terraform/providers.tf +19 -0
  122. package/templates/aws-ecs/iac/terraform/variables.tf.hbs +113 -0
  123. package/templates/aws-ecs/iac/terraform/versions.tf +19 -0
  124. package/templates/base/.claude/agents/issue-fixer.md +190 -0
  125. package/templates/base/.claude/agents/security-fixer.md +250 -0
  126. package/templates/base/.claude/rules/BE/001.md +19 -0
  127. package/templates/base/.claude/rules/BE/002.md +21 -0
  128. package/templates/base/.claude/rules/BE/003.md +19 -0
  129. package/templates/base/.claude/rules/BE/004.md +16 -0
  130. package/templates/base/.claude/rules/BE/005.md +23 -0
  131. package/templates/base/.claude/rules/BE/006.md +13 -0
  132. package/templates/base/.claude/rules/BE/007.md +24 -0
  133. package/templates/base/.claude/rules/BE/008.md +19 -0
  134. package/templates/base/.claude/rules/BE/009.md +18 -0
  135. package/templates/base/.claude/rules/BE/010.md +15 -0
  136. package/templates/base/.claude/rules/BE/011.md +17 -0
  137. package/templates/base/.claude/rules/BE/012.md +18 -0
  138. package/templates/base/.claude/rules/BE/013.md +22 -0
  139. package/templates/base/.claude/rules/BE/014.md +15 -0
  140. package/templates/base/.claude/rules/E2E/001.md +13 -0
  141. package/templates/base/.claude/rules/E2E/002.md +14 -0
  142. package/templates/base/.claude/rules/E2E/003.md +10 -0
  143. package/templates/base/.claude/rules/E2E/004.md +23 -0
  144. package/templates/base/.claude/rules/E2E/005.md +15 -0
  145. package/templates/base/.claude/rules/E2E/006.md +13 -0
  146. package/templates/base/.claude/rules/E2E/007.md +18 -0
  147. package/templates/base/.claude/rules/FE/001.md +22 -0
  148. package/templates/base/.claude/rules/FE/002.md +39 -0
  149. package/templates/base/.claude/rules/FE/003.md +19 -0
  150. package/templates/base/.claude/rules/FE/004.md +21 -0
  151. package/templates/base/.claude/rules/FE/005.md +33 -0
  152. package/templates/base/.claude/rules/FE/006.md +24 -0
  153. package/templates/base/.claude/rules/FE/007.md +19 -0
  154. package/templates/base/.claude/rules/FE/008.md +26 -0
  155. package/templates/base/.claude/rules/FE/009.md +30 -0
  156. package/templates/base/.claude/rules/FE/010.md +25 -0
  157. package/templates/base/.claude/rules/FE/011.md +22 -0
  158. package/templates/base/.claude/rules/FE/012.md +32 -0
  159. package/templates/base/.claude/settings.json +53 -0
  160. package/templates/base/.claude/skills/clean-branches/SKILL.md +100 -0
  161. package/templates/base/.claude/skills/create/SKILL.md +47 -0
  162. package/templates/base/.claude/skills/create-jira-issue/SKILL.md +174 -0
  163. package/templates/base/.claude/skills/create-page/SKILL.md +195 -0
  164. package/templates/base/.claude/skills/create-route/SKILL.md +156 -0
  165. package/templates/base/.claude/skills/draft-email/SKILL.md +104 -0
  166. package/templates/base/.claude/skills/fix-issues/SKILL.md +238 -0
  167. package/templates/base/.claude/skills/security-scan/SKILL.md +297 -0
  168. package/templates/base/.claude/skills/verify-security-fixes/SKILL.md +180 -0
  169. package/templates/base/.dude/commands/README.md +85 -0
  170. package/templates/base/.dude/commands/hello.ts +34 -0
  171. package/templates/base/.dude/lint/checks/PRJ/001.ts +26 -0
  172. package/templates/base/.dude/lint/checks/README.md +69 -0
  173. package/templates/base/.vscode/tasks.json +44 -0
  174. package/templates/base/.worktreeinclude +2 -0
  175. package/templates/base/CLAUDE.md.hbs +391 -0
  176. package/templates/base/README.md.hbs +188 -0
  177. package/templates/base/_env.example.hbs +39 -0
  178. package/templates/base/_env.hbs +35 -0
  179. package/templates/base/_gitignore +31 -0
  180. package/templates/base/_npmrc +2 -0
  181. package/templates/base/backend/Dockerfile +16 -0
  182. package/templates/base/backend/README.md.hbs +90 -0
  183. package/templates/base/backend/_dockerignore +12 -0
  184. package/templates/base/backend/apps/__init__.py +0 -0
  185. package/templates/base/backend/apps/core/__init__.py +0 -0
  186. package/templates/base/backend/apps/core/apps.py +6 -0
  187. package/templates/base/backend/apps/core/serializers.py +7 -0
  188. package/templates/base/backend/apps/core/tests/__init__.py +0 -0
  189. package/templates/base/backend/apps/core/tests/test_views.py +16 -0
  190. package/templates/base/backend/apps/core/urls.py +9 -0
  191. package/templates/base/backend/apps/core/views.py +24 -0
  192. package/templates/base/backend/apps/users/__init__.py +0 -0
  193. package/templates/base/backend/apps/users/admin.py +6 -0
  194. package/templates/base/backend/apps/users/apps.py +6 -0
  195. package/templates/base/backend/apps/users/migrations/0001_initial.py +41 -0
  196. package/templates/base/backend/apps/users/migrations/__init__.py +0 -0
  197. package/templates/base/backend/apps/users/models.py +15 -0
  198. package/templates/base/backend/apps/users/serializers.py +16 -0
  199. package/templates/base/backend/apps/users/services.py +25 -0
  200. package/templates/base/backend/apps/users/tests/__init__.py +0 -0
  201. package/templates/base/backend/apps/users/tests/test_models.py +30 -0
  202. package/templates/base/backend/apps/users/tests/test_views.py +55 -0
  203. package/templates/base/backend/apps/users/urls.py +10 -0
  204. package/templates/base/backend/apps/users/views.py +20 -0
  205. package/templates/base/backend/config/__init__.py.hbs +5 -0
  206. package/templates/base/backend/config/asgi.py +9 -0
  207. package/templates/base/backend/config/settings/__init__.py +0 -0
  208. package/templates/base/backend/config/settings/base.py.hbs +197 -0
  209. package/templates/base/backend/config/settings/local.py +31 -0
  210. package/templates/base/backend/config/settings/production.py.hbs +37 -0
  211. package/templates/base/backend/config/urls.py.hbs +22 -0
  212. package/templates/base/backend/config/wsgi.py +9 -0
  213. package/templates/base/backend/manage.py +23 -0
  214. package/templates/base/backend/pyproject.toml.hbs +48 -0
  215. package/templates/base/backend/start.sh +5 -0
  216. package/templates/base/docker-compose.yml.hbs +196 -0
  217. package/templates/base/docs/docs/api.md +21 -0
  218. package/templates/base/docs/docs/dude.md.hbs +305 -0
  219. package/templates/base/docs/docs/index.md.hbs +92 -0
  220. package/templates/base/docs/docs/mkdocs.md +231 -0
  221. package/templates/base/docs/mkdocs.yml.hbs +52 -0
  222. package/templates/base/e2e/.prettierrc.json +1 -0
  223. package/templates/base/e2e/_prettierignore +3 -0
  224. package/templates/base/e2e/cucumber.js +21 -0
  225. package/templates/base/e2e/eslint.config.mjs +14 -0
  226. package/templates/base/e2e/features/example.feature +13 -0
  227. package/templates/base/e2e/package.json.hbs +30 -0
  228. package/templates/base/e2e/pages/ExamplePage.ts +16 -0
  229. package/templates/base/e2e/playwright.config.ts +27 -0
  230. package/templates/base/e2e/steps/common.steps.ts +32 -0
  231. package/templates/base/e2e/steps/example.steps.ts +4 -0
  232. package/templates/base/e2e/support/hooks.ts +72 -0
  233. package/templates/base/e2e/support/world.ts +24 -0
  234. package/templates/base/e2e/tsconfig.json +22 -0
  235. package/templates/base/frontend/.prettierrc.json +6 -0
  236. package/templates/base/frontend/Dockerfile +10 -0
  237. package/templates/base/frontend/_dockerignore +4 -0
  238. package/templates/base/frontend/eslint.config.js +32 -0
  239. package/templates/base/frontend/index.html.hbs +13 -0
  240. package/templates/base/frontend/package.json.hbs +38 -0
  241. package/templates/base/frontend/public/favicon.svg +5 -0
  242. package/templates/base/frontend/src/$components/Layout/$assets/logo.svg +5 -0
  243. package/templates/base/frontend/src/$components/Layout/constants.tsx +8 -0
  244. package/templates/base/frontend/src/$components/Layout/index.tsx +80 -0
  245. package/templates/base/frontend/src/$components/Layout/types.tsx +9 -0
  246. package/templates/base/frontend/src/$components/index.tsx +1 -0
  247. package/templates/base/frontend/src/$hooks/index.tsx +2 -0
  248. package/templates/base/frontend/src/$hooks/useCounterStore/index.tsx +28 -0
  249. package/templates/base/frontend/src/$hooks/useCounterStore/types.tsx +7 -0
  250. package/templates/base/frontend/src/$hooks/usePageTitle/index.tsx +21 -0
  251. package/templates/base/frontend/src/$types/vite-env.d.ts +10 -0
  252. package/templates/base/frontend/src/App.tsx +36 -0
  253. package/templates/base/frontend/src/main.tsx +10 -0
  254. package/templates/base/frontend/src/openapi/utils/openapi.yaml.hbs +129 -0
  255. package/templates/base/frontend/src/pages/constants.tsx +31 -0
  256. package/templates/base/frontend/src/pages/index.tsx +192 -0
  257. package/templates/base/frontend/src/pages/types.tsx +6 -0
  258. package/templates/base/frontend/src/pages/users/[id]/index.tsx +53 -0
  259. package/templates/base/frontend/src/pages/users/index.tsx +57 -0
  260. package/templates/base/frontend/src/pages/users/types.tsx +4 -0
  261. package/templates/base/frontend/src/styles.module.css +7 -0
  262. package/templates/base/frontend/src/utils/constants.tsx +11 -0
  263. package/templates/base/frontend/src/utils/formatters/index.tsx +49 -0
  264. package/templates/base/frontend/src/utils/functions.tsx +70 -0
  265. package/templates/base/frontend/src/utils/index.tsx +3 -0
  266. package/templates/base/frontend/tsconfig.json +24 -0
  267. package/templates/base/frontend/vite.config.ts +20 -0
  268. package/templates/base/package.json.hbs +11 -0
  269. package/templates/base/security/baseline.json +4 -0
  270. package/templates/celery/backend/apps/core/tasks.py +14 -0
  271. package/templates/celery/backend/apps/core/tests/test_tasks.py +6 -0
  272. package/templates/celery/backend/config/celery.py.hbs +26 -0
  273. package/templates/celerybeat/backend/apps/core/tasks_scheduled.py +18 -0
  274. package/templates/celerybeat/backend/apps/core/tests/test_tasks_scheduled.py +6 -0
  275. package/templates/postgres/.dude/commands/reset.ts +83 -0
  276. package/templates/s3/backend/apps/files/__init__.py +0 -0
  277. package/templates/s3/backend/apps/files/admin.py +9 -0
  278. package/templates/s3/backend/apps/files/apps.py +6 -0
  279. package/templates/s3/backend/apps/files/migrations/0001_initial.py +29 -0
  280. package/templates/s3/backend/apps/files/migrations/__init__.py +0 -0
  281. package/templates/s3/backend/apps/files/models.py +21 -0
  282. package/templates/s3/backend/apps/files/serializers.py +27 -0
  283. package/templates/s3/backend/apps/files/services.py +19 -0
  284. package/templates/s3/backend/apps/files/tests/__init__.py +0 -0
  285. package/templates/s3/backend/apps/files/tests/test_models.py +10 -0
  286. package/templates/s3/backend/apps/files/tests/test_views.py +32 -0
  287. package/templates/s3/backend/apps/files/urls.py +10 -0
  288. package/templates/s3/backend/apps/files/views.py +29 -0
  289. package/templates/s3/frontend/src/openapi/utils/openapi.yaml.hbs +253 -0
package/dist/index.js ADDED
@@ -0,0 +1,3436 @@
1
+ // src/index.ts
2
+ import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
3
+ import path16 from "pathe";
4
+ import yaml2 from "yaml";
5
+ import { defineStack, renderTemplateTree } from "@cubocicloide/dude";
6
+
7
+ // src/commands/api/index.ts
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "fs";
9
+ import path from "pathe";
10
+ import yaml from "yaml";
11
+ import openapiTS, { astToString } from "openapi-typescript";
12
+ var NO_OVERRIDE = "// openapi-no-override";
13
+ var banner = `// This file is auto-generated by \`dude api sync\`.
14
+ // Manual changes will be overwritten on the next run.
15
+ // To keep your edits, add \`// openapi-no-override\` as the very first line.
16
+ `;
17
+ function shouldWrite(filePath) {
18
+ if (!existsSync(filePath)) return true;
19
+ return !(readFileSync(filePath, "utf8").split("\n")[0] ?? "").startsWith(NO_OVERRIDE);
20
+ }
21
+ function safeWrite(filePath, content) {
22
+ if (!shouldWrite(filePath)) return false;
23
+ mkdirSync(path.dirname(filePath), { recursive: true });
24
+ writeFileSync(filePath, content, "utf8");
25
+ return true;
26
+ }
27
+ function routeToSegments(route) {
28
+ return route.split("/").filter(Boolean).map((s) => s.replace(/{(.+?)}/g, "[$1]"));
29
+ }
30
+ function cap(s) {
31
+ return s.charAt(0).toUpperCase() + s.slice(1);
32
+ }
33
+ function toUtils(depth) {
34
+ return "../".repeat(depth) + "utils/openapi.types";
35
+ }
36
+ function walkAll(dir) {
37
+ const results = [];
38
+ if (!existsSync(dir)) return results;
39
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
40
+ const full = path.join(dir, entry.name);
41
+ if (entry.isDirectory()) {
42
+ results.push(full, ...walkAll(full));
43
+ } else {
44
+ results.push(full);
45
+ }
46
+ }
47
+ return results;
48
+ }
49
+ function generateTypesFile(route, methods, depth) {
50
+ const imports = /* @__PURE__ */ new Set();
51
+ let body = "";
52
+ for (const [method, details] of Object.entries(methods)) {
53
+ const M = cap(method);
54
+ body += `// ${method.toUpperCase()}
55
+ `;
56
+ if (details.parameters?.some((p) => p.in === "query")) {
57
+ imports.add("paths");
58
+ body += `export type ${M}Parameters = paths['${route}']['${method}']['parameters']['query']
59
+ `;
60
+ }
61
+ if (details.requestBody?.content) {
62
+ const content = details.requestBody.content;
63
+ const schema = content["application/json"]?.schema ?? content["multipart/form-data"]?.schema ?? content["application/x-www-form-urlencoded"]?.schema;
64
+ if (schema?.$ref) {
65
+ const name = schema.$ref.split("/").pop();
66
+ imports.add("components");
67
+ body += `export type ${M}RequestBody = components['schemas']['${name}']
68
+ `;
69
+ } else {
70
+ body += `export type ${M}RequestBody = unknown
71
+ `;
72
+ }
73
+ }
74
+ const firstCode = details.responses ? Object.keys(details.responses)[0] : void 0;
75
+ const responseContent = firstCode ? details.responses[firstCode]?.content : void 0;
76
+ if (responseContent) {
77
+ const schema = responseContent["application/json"]?.schema;
78
+ if (schema?.$ref) {
79
+ const name = schema.$ref.split("/").pop();
80
+ imports.add("components");
81
+ body += `export type ${M}Response = components['schemas']['${name}']
82
+ `;
83
+ } else if (schema?.type === "array" && schema.items?.$ref) {
84
+ const name = schema.items.$ref.split("/").pop();
85
+ imports.add("components");
86
+ body += `export type ${M}Response = components['schemas']['${name}'][]
87
+ `;
88
+ } else {
89
+ body += `export type ${M}Response = unknown
90
+ `;
91
+ }
92
+ } else {
93
+ body += `export type ${M}Response = void
94
+ `;
95
+ }
96
+ body += "\n";
97
+ }
98
+ let out = banner;
99
+ if (imports.size > 0) {
100
+ out += `import type { ${[...imports].join(", ")} } from '${toUtils(depth)}'
101
+
102
+ `;
103
+ }
104
+ return out + body;
105
+ }
106
+ function generateIndexFile(route, methods) {
107
+ const pathParams = (route.match(/{(.+?)}/g) ?? []).map((m) => m.slice(1, -1));
108
+ const importedTypes = /* @__PURE__ */ new Set();
109
+ let body = "";
110
+ for (const [method, details] of Object.entries(methods)) {
111
+ const M = cap(method);
112
+ const args = [];
113
+ if (pathParams.length > 0) args.push(pathParams.map((p) => `${p}: string`).join(", "));
114
+ const hasQuery = details.parameters?.some((p) => p.in === "query") ?? false;
115
+ const hasBody = !!details.requestBody;
116
+ if (hasQuery) {
117
+ args.push(`params: ${M}Parameters`);
118
+ importedTypes.add(`${M}Parameters`);
119
+ }
120
+ if (hasBody) {
121
+ args.push(`body: ${M}RequestBody`);
122
+ importedTypes.add(`${M}RequestBody`);
123
+ }
124
+ importedTypes.add(`${M}Response`);
125
+ const urlExpr = pathParams.length > 0 ? `\`${route.replace(/{(.+?)}/g, (_, p) => `\${${p}}`)}\`` : `'${route}'`;
126
+ const fetchOpts = [];
127
+ if (method !== "get") fetchOpts.push(`method: '${method.toUpperCase()}'`);
128
+ if (hasBody) {
129
+ fetchOpts.push(`headers: { 'Content-Type': 'application/json' }`);
130
+ fetchOpts.push(`body: JSON.stringify(body)`);
131
+ }
132
+ const optsStr = fetchOpts.length > 0 ? `, { ${fetchOpts.join(", ")} }` : "";
133
+ const urlStr = hasQuery ? `uri + '?' + new URLSearchParams(params as Record<string, string>)` : `uri`;
134
+ body += `export const $${method} = (${args.join(", ")}): Promise<${M}Response> => {
135
+ `;
136
+ body += ` const uri = ${urlExpr}
137
+ `;
138
+ body += ` return fetch(${urlStr}${optsStr}).then(r => r.json() as Promise<${M}Response>)
139
+ `;
140
+ body += `}
141
+
142
+ `;
143
+ }
144
+ let out = banner;
145
+ if (importedTypes.size > 0) {
146
+ out += `import type { ${[...importedTypes].join(", ")} } from './types'
147
+
148
+ `;
149
+ }
150
+ return out + body;
151
+ }
152
+ async function generateClientFromSpec(spec, outDir, root, log) {
153
+ mkdirSync(path.join(outDir, "utils"), { recursive: true });
154
+ const typesPath = path.join(outDir, "utils", "openapi.types.ts");
155
+ if (shouldWrite(typesPath)) {
156
+ const ast = await openapiTS(spec);
157
+ writeFileSync(typesPath, astToString(ast), "utf8");
158
+ log?.(`Saved ${path.relative(root, typesPath)}
159
+ `);
160
+ } else {
161
+ log?.(`Skipped (no-override) ${path.relative(root, typesPath)}
162
+ `);
163
+ }
164
+ const specPaths = spec.paths ?? {};
165
+ let written = 0;
166
+ let skipped = 0;
167
+ for (const [route, methods] of Object.entries(specPaths)) {
168
+ const segments = routeToSegments(route);
169
+ const folderPath = path.join(outDir, ...segments);
170
+ mkdirSync(folderPath, { recursive: true });
171
+ const depth = segments.length;
172
+ const typesFile = path.join(folderPath, "types.ts");
173
+ if (safeWrite(typesFile, generateTypesFile(route, methods, depth))) {
174
+ log?.(`Saved ${path.relative(root, typesFile)}
175
+ `);
176
+ written++;
177
+ } else {
178
+ log?.(`Skipped (no-override) ${path.relative(root, typesFile)}
179
+ `);
180
+ skipped++;
181
+ }
182
+ const indexFile = path.join(folderPath, "index.ts");
183
+ if (safeWrite(indexFile, generateIndexFile(route, methods))) {
184
+ log?.(`Saved ${path.relative(root, indexFile)}
185
+ `);
186
+ written++;
187
+ } else {
188
+ log?.(`Skipped (no-override) ${path.relative(root, indexFile)}
189
+ `);
190
+ skipped++;
191
+ }
192
+ }
193
+ return { written, skipped };
194
+ }
195
+ var syncCommand = {
196
+ description: "Fetch the OpenAPI schema from the Django backend (drf-spectacular) and generate a typed client in frontend/src/openapi/.",
197
+ args: {
198
+ url: { type: "string", description: "Backend base URL.", default: "http://localhost:8000" },
199
+ out: {
200
+ type: "string",
201
+ description: "Output directory relative to root.",
202
+ default: "frontend/src/openapi"
203
+ }
204
+ },
205
+ async run({ projectRoot: root, args }) {
206
+ const url = args.url ?? "http://localhost:8000";
207
+ const out = args.out ?? "frontend/src/openapi";
208
+ const outDir = path.join(root, out);
209
+ const utilsDir = path.join(outDir, "utils");
210
+ const specUrl = `${url.replace(/\/$/, "")}/api/schema/`;
211
+ process.stdout.write(`Fetching spec from ${specUrl}\u2026
212
+ `);
213
+ let spec;
214
+ try {
215
+ const res = await fetch(specUrl);
216
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
217
+ const body = await res.text();
218
+ spec = body.trimStart().startsWith("{") ? JSON.parse(body) : yaml.parse(body);
219
+ } catch (err) {
220
+ process.stderr.write(`error: could not fetch OpenAPI spec \u2014 ${err.message}
221
+ `);
222
+ process.stderr.write(`Make sure the Django backend is running at ${url}
223
+ `);
224
+ process.exit(1);
225
+ }
226
+ mkdirSync(utilsDir, { recursive: true });
227
+ const yamlPath = path.join(utilsDir, "openapi.yaml");
228
+ writeFileSync(yamlPath, yaml.stringify(spec), "utf8");
229
+ process.stdout.write(`Saved ${path.relative(root, yamlPath)}
230
+ `);
231
+ const { written, skipped } = await generateClientFromSpec(
232
+ spec,
233
+ outDir,
234
+ root,
235
+ (msg) => process.stdout.write(msg)
236
+ );
237
+ process.stdout.write(`
238
+ ${written} file(s) written, ${skipped} skipped (no-override).
239
+ `);
240
+ }
241
+ };
242
+ var reviewCommand = {
243
+ description: "Validate the frontend/src/openapi/ tree against the saved OpenAPI spec.",
244
+ args: {
245
+ out: {
246
+ type: "string",
247
+ description: "Generated openapi directory relative to root.",
248
+ default: "frontend/src/openapi"
249
+ }
250
+ },
251
+ async run({ projectRoot: root, args }) {
252
+ const out = args.out ?? "frontend/src/openapi";
253
+ const outDir = path.join(root, out);
254
+ const yamlPath = path.join(outDir, "utils", "openapi.yaml");
255
+ const isTTY = process.stdout.isTTY;
256
+ if (!existsSync(yamlPath)) {
257
+ process.stderr.write(
258
+ `error: ${path.relative(root, yamlPath)} not found.
259
+ Run \`dude api sync\` first to fetch the spec.
260
+ `
261
+ );
262
+ process.exit(1);
263
+ }
264
+ const spec = yaml.parse(readFileSync(yamlPath, "utf8"));
265
+ const specPaths = spec.paths ?? {};
266
+ const expectedFolders = /* @__PURE__ */ new Set();
267
+ const expectedFiles = /* @__PURE__ */ new Set();
268
+ for (const route of Object.keys(specPaths)) {
269
+ const segments = routeToSegments(route);
270
+ for (let i = 1; i <= segments.length; i++) {
271
+ expectedFolders.add(path.join(outDir, ...segments.slice(0, i)));
272
+ }
273
+ const leafDir = path.join(outDir, ...segments);
274
+ expectedFiles.add(path.join(leafDir, "types.ts"));
275
+ expectedFiles.add(path.join(leafDir, "index.ts"));
276
+ }
277
+ const utilsDir = path.join(outDir, "utils");
278
+ expectedFolders.add(utilsDir);
279
+ expectedFiles.add(path.join(utilsDir, "openapi.yaml"));
280
+ expectedFiles.add(path.join(utilsDir, "openapi.types.ts"));
281
+ const actual = walkAll(outDir);
282
+ const issues = [];
283
+ for (const item of actual) {
284
+ const isDir = statSync(item).isDirectory();
285
+ if (isDir) {
286
+ if (!expectedFolders.has(item) && item !== outDir) issues.push({ kind: "unexpected", item });
287
+ } else {
288
+ if (!expectedFiles.has(item)) issues.push({ kind: "unexpected", item });
289
+ }
290
+ }
291
+ for (const f of [...expectedFolders, ...expectedFiles]) {
292
+ if (!existsSync(f)) issues.push({ kind: "missing", item: f });
293
+ }
294
+ if (issues.length === 0) {
295
+ process.stdout.write("No issues found.\n");
296
+ return;
297
+ }
298
+ const colorize = (s, kind) => isTTY ? kind === "unexpected" ? `\x1B[31m${s}\x1B[0m` : `\x1B[33m${s}\x1B[0m` : s;
299
+ let errors = 0;
300
+ let warnings = 0;
301
+ for (const { kind, item } of issues) {
302
+ const rel = path.relative(root, item);
303
+ if (kind === "unexpected") {
304
+ process.stdout.write(
305
+ colorize(`${rel}: error: unexpected file/folder (not in OpenAPI spec)`, kind) + "\n"
306
+ );
307
+ errors++;
308
+ } else {
309
+ process.stdout.write(
310
+ colorize(
311
+ `${rel}: warning: expected by spec but not found \u2014 run \`dude api sync\``,
312
+ kind
313
+ ) + "\n"
314
+ );
315
+ warnings++;
316
+ }
317
+ }
318
+ const summary = [
319
+ errors > 0 ? `${errors} error${errors > 1 ? "s" : ""}` : "",
320
+ warnings > 0 ? `${warnings} warning${warnings > 1 ? "s" : ""}` : ""
321
+ ].filter(Boolean).join(", ");
322
+ process.stderr.write(`
323
+ ${summary}
324
+ `);
325
+ process.exit(errors > 0 ? 1 : 0);
326
+ }
327
+ };
328
+
329
+ // src/commands/db/index.ts
330
+ import { spawnSync } from "child_process";
331
+ import { existsSync as existsSync2 } from "fs";
332
+ import path2 from "pathe";
333
+ function hasManagePy(projectRoot) {
334
+ return existsSync2(path2.join(projectRoot, "backend", "manage.py"));
335
+ }
336
+ function requiresManagePy(projectRoot) {
337
+ if (!hasManagePy(projectRoot)) {
338
+ process.stderr.write(
339
+ "\n \u2717 No Django manage.py found (expected backend/manage.py).\n Run this command from the root of a project scaffolded with the react-django stack.\n\n"
340
+ );
341
+ return false;
342
+ }
343
+ return true;
344
+ }
345
+ function manage(projectRoot, manageArgs) {
346
+ const result = spawnSync(
347
+ "docker",
348
+ ["compose", "exec", "backend", "uv", "run", "python", "manage.py", ...manageArgs],
349
+ { cwd: projectRoot, stdio: "inherit" }
350
+ );
351
+ if (result.error != null) {
352
+ process.stderr.write(
353
+ `error: could not run docker \u2014 ${result.error.message}
354
+ Make sure Docker is installed and running.
355
+ `
356
+ );
357
+ process.exit(1);
358
+ }
359
+ if (result.status !== 0) {
360
+ process.stderr.write(
361
+ "\nhint: if the backend container is not running, start the stack first with `dude up`.\n"
362
+ );
363
+ process.exit(result.status ?? 1);
364
+ }
365
+ }
366
+ var makemigrationCommand = {
367
+ available: hasManagePy,
368
+ description: "Generate new Django migrations from model changes (manage.py makemigrations, runs inside the backend container).",
369
+ args: {
370
+ name: {
371
+ type: "string",
372
+ description: "Migration name (passed as --name to makemigrations).",
373
+ required: false
374
+ },
375
+ app: {
376
+ type: "string",
377
+ description: "Limit migration generation to one app label (e.g. users).",
378
+ required: false
379
+ }
380
+ },
381
+ async run({ projectRoot, args }) {
382
+ if (!requiresManagePy(projectRoot)) process.exit(1);
383
+ const app = typeof args.app === "string" && args.app ? args.app : null;
384
+ const name = typeof args.name === "string" && args.name ? args.name : null;
385
+ const cmd = ["makemigrations"];
386
+ if (app) cmd.push(app);
387
+ if (name) cmd.push("--name", name);
388
+ manage(projectRoot, cmd);
389
+ }
390
+ };
391
+ var migrateCommand = {
392
+ available: hasManagePy,
393
+ description: "Apply pending Django migrations (manage.py migrate, runs inside the backend container).",
394
+ args: {
395
+ app: {
396
+ type: "string",
397
+ description: "Migrate a single app label (e.g. users).",
398
+ required: false
399
+ },
400
+ revision: {
401
+ type: "string",
402
+ description: "Target migration (e.g. 0001 or zero). Requires --app.",
403
+ required: false
404
+ }
405
+ },
406
+ async run({ projectRoot, args }) {
407
+ if (!requiresManagePy(projectRoot)) process.exit(1);
408
+ const app = typeof args.app === "string" && args.app ? args.app : null;
409
+ const revision = typeof args.revision === "string" && args.revision ? args.revision : null;
410
+ if (revision && !app) {
411
+ process.stderr.write(
412
+ "error: --revision requires --app (Django targets migrations per app).\nExample: dude db migrate --app users --revision 0001\n"
413
+ );
414
+ process.exit(1);
415
+ }
416
+ const cmd = ["migrate"];
417
+ if (app) cmd.push(app);
418
+ if (revision) cmd.push(revision);
419
+ cmd.push("--noinput");
420
+ manage(projectRoot, cmd);
421
+ }
422
+ };
423
+ var rollbackCommand = {
424
+ available: hasManagePy,
425
+ description: "Roll back an app to an earlier migration (manage.py migrate <app> <target>, runs inside the backend container).",
426
+ args: {
427
+ app: {
428
+ type: "string",
429
+ description: "App label to roll back (e.g. users).",
430
+ required: true
431
+ },
432
+ to: {
433
+ type: "string",
434
+ description: "Target migration to roll back to (e.g. 0001, or zero to unapply all).",
435
+ required: true
436
+ }
437
+ },
438
+ async run({ projectRoot, args }) {
439
+ if (!requiresManagePy(projectRoot)) process.exit(1);
440
+ const app = typeof args.app === "string" && args.app ? args.app : null;
441
+ const to = typeof args.to === "string" && args.to ? args.to : null;
442
+ if (!app || !to) {
443
+ process.stderr.write(
444
+ "error: both --app and --to are required.\nRoll back to a specific migration: dude db rollback --app users --to 0001\nUnapply all migrations of an app: dude db rollback --app users --to zero\n"
445
+ );
446
+ process.exit(1);
447
+ }
448
+ manage(projectRoot, ["migrate", app, to, "--noinput"]);
449
+ }
450
+ };
451
+ var superuserCommand = {
452
+ available: hasManagePy,
453
+ description: "Create a Django admin superuser interactively (manage.py createsuperuser, runs inside the backend container).",
454
+ args: {},
455
+ async run({ projectRoot }) {
456
+ if (!requiresManagePy(projectRoot)) process.exit(1);
457
+ manage(projectRoot, ["createsuperuser"]);
458
+ }
459
+ };
460
+
461
+ // src/commands/docs/index.ts
462
+ import { spawn, spawnSync as spawnSync2 } from "child_process";
463
+ import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
464
+ import path3 from "pathe";
465
+ async function regenerateApiDoc(projectRoot, docsDir) {
466
+ try {
467
+ const dude = await import("@cubocicloide/dude");
468
+ if (typeof dude.generateApiDoc !== "function") return;
469
+ const md = await dude.generateApiDoc(projectRoot, "md");
470
+ writeFileSync2(path3.join(docsDir, "docs", "api.md"), md);
471
+ process.stdout.write("[docs] Regenerated docs/api.md from the live command catalog.\n");
472
+ } catch (e) {
473
+ process.stderr.write(
474
+ `[docs] Could not regenerate api.md (${e.message}); using the existing file.
475
+ `
476
+ );
477
+ }
478
+ }
479
+ function isDockerRunning() {
480
+ const r = spawnSync2("docker", ["info"], { stdio: "ignore" });
481
+ return r.error == null && r.status === 0;
482
+ }
483
+ function openBrowser(url) {
484
+ if (process.platform === "win32") {
485
+ spawnSync2("cmd", ["/c", "start", "", url], { stdio: "ignore" });
486
+ return;
487
+ }
488
+ const opener = process.platform === "darwin" ? "open" : "xdg-open";
489
+ spawnSync2(opener, [url], { stdio: "ignore" });
490
+ }
491
+ var docsCommand = {
492
+ description: "Serve the project documentation in dev mode (live-reload) at http://localhost:8001.",
493
+ args: {
494
+ port: {
495
+ type: "string",
496
+ description: "Host port to expose the docs site on (default: 8001).",
497
+ default: "8001"
498
+ }
499
+ },
500
+ async run({ projectRoot, args }) {
501
+ const docsDir = path3.join(projectRoot, "docs");
502
+ const port = String(args.port ?? "8001");
503
+ const url = `http://localhost:${port}`;
504
+ if (!existsSync3(docsDir)) {
505
+ process.stderr.write(
506
+ "[docs] No docs/ folder found in the project root. Make sure you ran `dude init`.\n"
507
+ );
508
+ process.exit(1);
509
+ }
510
+ await regenerateApiDoc(projectRoot, docsDir);
511
+ if (!isDockerRunning()) {
512
+ process.stderr.write("[docs] Docker is not running. Start Docker Desktop and retry.\n");
513
+ process.exit(1);
514
+ }
515
+ process.stdout.write(`[docs] Starting MkDocs at ${url} (Ctrl+C to stop)
516
+ `);
517
+ const child = spawn(
518
+ "docker",
519
+ [
520
+ "run",
521
+ "--rm",
522
+ "-i",
523
+ "-p",
524
+ `${port}:8000`,
525
+ "-v",
526
+ `${docsDir}:/docs`,
527
+ "squidfunk/mkdocs-material",
528
+ "serve",
529
+ "--dev-addr=0.0.0.0:8000"
530
+ ],
531
+ { stdio: ["inherit", "pipe", "pipe"] }
532
+ );
533
+ if (child.pid == null) {
534
+ process.stderr.write("[docs] Failed to start Docker container.\n");
535
+ process.exit(1);
536
+ }
537
+ let browserOpened = false;
538
+ function watchChunk(chunk) {
539
+ if (!browserOpened && chunk.toString().includes("Serving on")) {
540
+ browserOpened = true;
541
+ process.stdout.write(`[docs] Opening ${url}
542
+ `);
543
+ openBrowser(url);
544
+ }
545
+ }
546
+ child.stdout?.on("data", (chunk) => {
547
+ process.stdout.write(chunk);
548
+ watchChunk(chunk);
549
+ });
550
+ child.stderr?.on("data", (chunk) => {
551
+ process.stderr.write(chunk);
552
+ watchChunk(chunk);
553
+ });
554
+ await new Promise((resolve) => child.on("close", resolve));
555
+ }
556
+ };
557
+
558
+ // src/commands/iac/providers/aws-ecs/lib/terraform.ts
559
+ import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync4 } from "fs";
560
+ import path6 from "pathe";
561
+
562
+ // src/commands/iac/shared.ts
563
+ import { spawnSync as spawnSync3 } from "child_process";
564
+ import { readFileSync as readFileSync2 } from "fs";
565
+ import path4 from "pathe";
566
+ function shouldUseShell() {
567
+ return process.platform === "win32";
568
+ }
569
+ function childEnv(profile) {
570
+ return profile ? { ...process.env, AWS_PROFILE: profile } : process.env;
571
+ }
572
+ function run(cmd, args, cwd, profile) {
573
+ const r = spawnSync3(cmd, args, {
574
+ cwd,
575
+ stdio: "inherit",
576
+ env: childEnv(profile),
577
+ shell: shouldUseShell()
578
+ });
579
+ if (r.error) {
580
+ const code = r.error.code;
581
+ if (code === "ENOENT") {
582
+ process.stderr.write(`
583
+ \u2717 \`${cmd}\` not found on PATH. Install it and retry.
584
+
585
+ `);
586
+ } else {
587
+ process.stderr.write(`
588
+ \u2717 failed to run ${cmd}: ${r.error.message}
589
+
590
+ `);
591
+ }
592
+ return 1;
593
+ }
594
+ return r.status ?? 1;
595
+ }
596
+ function capture(cmd, args, cwd, profile) {
597
+ const r = spawnSync3(cmd, args, {
598
+ cwd,
599
+ encoding: "utf8",
600
+ env: childEnv(profile),
601
+ shell: shouldUseShell()
602
+ });
603
+ return { status: r.status ?? 1, stdout: r.stdout ?? "" };
604
+ }
605
+ function readAnswers(projectRoot) {
606
+ try {
607
+ const j = JSON.parse(readFileSync2(path4.join(projectRoot, "dude.json"), "utf8"));
608
+ return j.answers ?? {};
609
+ } catch {
610
+ return {};
611
+ }
612
+ }
613
+ function projectName(projectRoot) {
614
+ const name = readAnswers(projectRoot).projectName;
615
+ return typeof name === "string" && name ? name : "app";
616
+ }
617
+ function hclScalar(text, key) {
618
+ const m = text.match(new RegExp(`^\\s*${key}\\s*=\\s*"([^"]*)"`, "m"));
619
+ return m?.[1] ?? "";
620
+ }
621
+ function sleepMs(ms) {
622
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
623
+ }
624
+
625
+ // src/commands/iac/providers/aws-ecs/lib/exec.ts
626
+ import { spawnSync as spawnSync5 } from "child_process";
627
+
628
+ // src/commands/iac/providers/aws-ecs/lib/runner.ts
629
+ import { spawnSync as spawnSync4 } from "child_process";
630
+ import { createHash } from "crypto";
631
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
632
+ import os from "os";
633
+ import path5 from "pathe";
634
+ var RUNNER_DOCKERFILE = path5.join("iac", "runner", "Dockerfile");
635
+ var CONTAINERIZED = /* @__PURE__ */ new Set(["terraform"]);
636
+ function findDockerfile(cwd) {
637
+ let dir = path5.resolve(cwd);
638
+ for (; ; ) {
639
+ const candidate = path5.join(dir, RUNNER_DOCKERFILE);
640
+ if (existsSync4(candidate)) return candidate;
641
+ const parent = path5.dirname(dir);
642
+ if (parent === dir) return "";
643
+ dir = parent;
644
+ }
645
+ }
646
+ function imageTag(dockerfile) {
647
+ const hash = createHash("sha256").update(readFileSync3(dockerfile)).digest("hex").slice(0, 12);
648
+ return `dude-iac-runner:${hash}`;
649
+ }
650
+ var dockerChecked;
651
+ var ensured = /* @__PURE__ */ new Set();
652
+ function dockerAvailable() {
653
+ if (dockerChecked !== void 0) return dockerChecked;
654
+ const r = spawnSync4("docker", ["version", "--format", "{{.Server.Version}}"], {
655
+ encoding: "utf8"
656
+ });
657
+ dockerChecked = r.status === 0 && !!r.stdout.trim();
658
+ return dockerChecked;
659
+ }
660
+ function useRunner(cwd) {
661
+ if (process.env.DUDE_IAC_RUNNER === "host") return false;
662
+ return dockerAvailable() && !!findDockerfile(cwd);
663
+ }
664
+ function ensureImage(dockerfile, tag) {
665
+ if (ensured.has(tag)) return;
666
+ const exists = spawnSync4("docker", ["image", "inspect", tag], { stdio: "ignore" }).status === 0;
667
+ if (!exists) {
668
+ process.stderr.write(
669
+ `
670
+ \u2192 Building the IaC runner image (${tag}). First run only \u2014 a minute or two\u2026
671
+
672
+ `
673
+ );
674
+ const build = spawnSync4(
675
+ "docker",
676
+ ["build", "-t", tag, "-f", dockerfile, path5.dirname(dockerfile)],
677
+ { stdio: "inherit" }
678
+ );
679
+ if (build.status !== 0) {
680
+ process.stderr.write("\n \u2717 Failed to build the IaC runner image.\n\n");
681
+ process.exit(build.status ?? 1);
682
+ }
683
+ }
684
+ ensured.add(tag);
685
+ }
686
+ function baseDockerArgs(cwd, profile, tty) {
687
+ const args = ["run", "--rm", tty ? "-it" : "-i"];
688
+ args.push("-v", `${cwd}:/work`, "-w", "/work");
689
+ const home = os.homedir();
690
+ args.push("-v", `${path5.join(home, ".aws")}:/root/.aws:ro`);
691
+ if (profile) args.push("-e", `AWS_PROFILE=${profile}`);
692
+ return args;
693
+ }
694
+ function dockerRunArgs(cmd, toolArgs, cwd, profile, opts = {}) {
695
+ const dockerfile = findDockerfile(cwd);
696
+ const tag = imageTag(dockerfile);
697
+ ensureImage(dockerfile, tag);
698
+ const base = baseDockerArgs(cwd, profile, !!opts.tty);
699
+ return [...base, tag, cmd, ...toolArgs];
700
+ }
701
+ function dockerShellArgs(projectRoot, profile) {
702
+ const dockerfile = findDockerfile(projectRoot);
703
+ const tag = imageTag(dockerfile);
704
+ ensureImage(dockerfile, tag);
705
+ const base = baseDockerArgs(projectRoot, profile, true);
706
+ return [...base, tag, "bash"];
707
+ }
708
+ function hasRunnerDockerfile(cwd) {
709
+ return !!findDockerfile(cwd);
710
+ }
711
+
712
+ // src/commands/iac/providers/aws-ecs/lib/exec.ts
713
+ function routed(cmd, cwd) {
714
+ return CONTAINERIZED.has(cmd) && useRunner(cwd);
715
+ }
716
+ function run2(cmd, args, cwd, profile) {
717
+ if (!routed(cmd, cwd)) return run(cmd, args, cwd, profile);
718
+ const dargs = dockerRunArgs(cmd, args, cwd, profile, { tty: !!process.stdin.isTTY });
719
+ const r = spawnSync5("docker", dargs, { stdio: "inherit" });
720
+ if (r.error) {
721
+ process.stderr.write(`
722
+ \u2717 failed to run docker: ${r.error.message}
723
+
724
+ `);
725
+ return 1;
726
+ }
727
+ return r.status ?? 1;
728
+ }
729
+ function capture2(cmd, args, cwd, profile) {
730
+ if (!routed(cmd, cwd)) return capture(cmd, args, cwd, profile);
731
+ const dargs = dockerRunArgs(cmd, args, cwd, profile, { tty: false });
732
+ const r = spawnSync5("docker", dargs, { encoding: "utf8" });
733
+ return { status: r.status ?? 1, stdout: r.stdout ?? "" };
734
+ }
735
+
736
+ // src/commands/iac/providers/aws-ecs/lib/terraform.ts
737
+ var TF_DIR = path6.join("iac", "terraform");
738
+ var TF_BOOTSTRAP_DIR = path6.join(TF_DIR, "bootstrap");
739
+ var TF_ENVIRONMENTS_DIR = path6.join(TF_DIR, "environments");
740
+ function hasIac(projectRoot) {
741
+ return existsSync5(path6.join(projectRoot, "iac", "terraform"));
742
+ }
743
+ function requireIac(projectRoot) {
744
+ if (!hasIac(projectRoot)) {
745
+ process.stderr.write(
746
+ "\n \u2717 No IaC configuration found (iac/terraform).\n This project was not initialised with an IaC target.\n Re-scaffold with `--iac aws-ecs` to enable it.\n\n"
747
+ );
748
+ return false;
749
+ }
750
+ return true;
751
+ }
752
+ function tf(projectRoot, args, profile) {
753
+ return run2("terraform", [`-chdir=${TF_DIR}`, ...args], projectRoot, profile);
754
+ }
755
+ function tfOutputRaw(projectRoot, name, profile) {
756
+ const r = capture2("terraform", [`-chdir=${TF_DIR}`, "output", "-raw", name], projectRoot, profile);
757
+ const value = r.stdout.trim();
758
+ return r.status === 0 && value && !/\s/.test(value) ? value : "";
759
+ }
760
+ function backendConfig(env) {
761
+ return `-backend-config=environments/${env}/backend.hcl`;
762
+ }
763
+ function varFile(env) {
764
+ return `-var-file=environments/${env}/terraform.tfvars`;
765
+ }
766
+ function tfBoot(projectRoot, args, profile) {
767
+ return run2("terraform", args, path6.join(projectRoot, TF_BOOTSTRAP_DIR), profile);
768
+ }
769
+ function captureBootstrap(projectRoot, args, profile) {
770
+ return capture2("terraform", args, path6.join(projectRoot, TF_BOOTSTRAP_DIR), profile);
771
+ }
772
+ function resolveProfile(projectRoot, args, env) {
773
+ if (args.profile) return String(args.profile);
774
+ if (process.env.AWS_PROFILE) return process.env.AWS_PROFILE;
775
+ return `${projectName(projectRoot)}-${env}`;
776
+ }
777
+ function tfvarsValue(projectRoot, env, key) {
778
+ try {
779
+ return hclScalar(
780
+ readFileSync4(path6.join(projectRoot, TF_DIR, "environments", env, "terraform.tfvars"), "utf8"),
781
+ key
782
+ );
783
+ } catch {
784
+ return "";
785
+ }
786
+ }
787
+ function readBackend(projectRoot, env) {
788
+ try {
789
+ const txt = readFileSync4(
790
+ path6.join(projectRoot, TF_DIR, "environments", env, "backend.hcl"),
791
+ "utf8"
792
+ );
793
+ return {
794
+ bucket: hclScalar(txt, "bucket"),
795
+ key: hclScalar(txt, "key"),
796
+ table: hclScalar(txt, "dynamodb_table"),
797
+ region: hclScalar(txt, "region")
798
+ };
799
+ } catch {
800
+ return { bucket: "", key: "", table: "", region: "" };
801
+ }
802
+ }
803
+ var envArg = {
804
+ env: {
805
+ type: "string",
806
+ description: "Target environment (required) \u2014 one of iac/terraform/environments/*."
807
+ },
808
+ profile: {
809
+ type: "string",
810
+ description: "AWS profile to use (default: <project>-<env>, or $AWS_PROFILE)."
811
+ }
812
+ };
813
+ function listEnvironments(projectRoot) {
814
+ const base = path6.join(projectRoot, TF_ENVIRONMENTS_DIR);
815
+ try {
816
+ return readdirSync2(base, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).filter(
817
+ (name) => existsSync5(path6.join(base, name, "backend.hcl")) && existsSync5(path6.join(base, name, "terraform.tfvars"))
818
+ ).sort();
819
+ } catch {
820
+ return [];
821
+ }
822
+ }
823
+ function requireEnv(projectRoot, args) {
824
+ const envs = listEnvironments(projectRoot);
825
+ const available = envs.length ? envs.join(", ") : "(none \u2014 create one first)";
826
+ const raw = args.env == null ? "" : String(args.env);
827
+ if (!raw) {
828
+ process.stderr.write(
829
+ `
830
+ \u2717 --env is required.
831
+ Available environments: ${available}
832
+ Create a new one with: dude iac new-env --env <name>
833
+
834
+ `
835
+ );
836
+ process.exit(1);
837
+ }
838
+ if (!/^[a-z][a-z0-9-]*$/.test(raw)) {
839
+ process.stderr.write(`
840
+ \u2717 invalid --env "${raw}" (expected lowercase kebab-case).
841
+
842
+ `);
843
+ process.exit(1);
844
+ }
845
+ if (!envs.includes(raw)) {
846
+ process.stderr.write(
847
+ `
848
+ \u2717 environment "${raw}" does not exist.
849
+ An environment is a folder iac/terraform/environments/<name>/ with a
850
+ backend.hcl and a terraform.tfvars. Available: ${available}
851
+ Create it with: dude iac new-env --env ${raw}
852
+
853
+ `
854
+ );
855
+ process.exit(1);
856
+ }
857
+ return raw;
858
+ }
859
+
860
+ // src/commands/iac/providers/aws-ecs/commands/apply/index.ts
861
+ var iacApplyCommand = {
862
+ available: hasIac,
863
+ description: "Provision/update the infrastructure for an environment.",
864
+ args: {
865
+ ...envArg,
866
+ yes: { type: "boolean", description: "Skip the interactive approval (-auto-approve)." }
867
+ },
868
+ async run({ projectRoot, args }) {
869
+ if (!requireIac(projectRoot)) process.exit(1);
870
+ const env = requireEnv(projectRoot, args);
871
+ const profile = resolveProfile(projectRoot, args, env);
872
+ const extra = args.yes ? ["-auto-approve"] : [];
873
+ process.exit(tf(projectRoot, ["apply", varFile(env), ...extra], profile));
874
+ }
875
+ };
876
+
877
+ // src/commands/iac/providers/aws-ecs/commands/bootstrap/index.ts
878
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
879
+ import path7 from "pathe";
880
+ var iacBootstrapCommand = {
881
+ available: hasIac,
882
+ description: "One-time: create the S3 state bucket + DynamoDB lock table + shared ECR repository, then write the values into backend.hcl.",
883
+ args: {
884
+ region: {
885
+ type: "string",
886
+ description: "AWS region for the state resources.",
887
+ default: "eu-west-1"
888
+ },
889
+ "state-bucket-prefix": {
890
+ type: "string",
891
+ description: "Prefix for the S3 bucket name \u2014 must be globally unique (e.g. your org slug).",
892
+ required: true
893
+ },
894
+ env: { type: "string", description: "Environment whose backend.hcl to update (required)." },
895
+ profile: {
896
+ type: "string",
897
+ description: "AWS profile to use (default: <project>-<env>, or $AWS_PROFILE)."
898
+ },
899
+ yes: { type: "boolean", description: "Skip the interactive approval (-auto-approve)." }
900
+ },
901
+ async run({ projectRoot, args }) {
902
+ if (!requireIac(projectRoot)) process.exit(1);
903
+ const env = requireEnv(projectRoot, args);
904
+ const profile = resolveProfile(projectRoot, args, env);
905
+ const prefix = String(args["state-bucket-prefix"] ?? "");
906
+ if (!prefix) {
907
+ process.stderr.write(
908
+ "\n \u2717 --state-bucket-prefix is required (e.g. your org slug, must be globally unique).\n\n"
909
+ );
910
+ process.exit(1);
911
+ }
912
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(prefix)) {
913
+ process.stderr.write(
914
+ `
915
+ \u2717 invalid --state-bucket-prefix "${prefix}" (expected lowercase alphanumeric / hyphens).
916
+
917
+ `
918
+ );
919
+ process.exit(1);
920
+ }
921
+ const region = String(args.region ?? "eu-west-1");
922
+ if (!/^[a-z]{2}-[a-z]+-\d$/.test(region)) {
923
+ process.stderr.write(`
924
+ \u2717 invalid --region "${region}" (expected e.g. eu-west-1).
925
+
926
+ `);
927
+ process.exit(1);
928
+ }
929
+ const name = projectName(projectRoot);
930
+ let status = tfBoot(projectRoot, ["init", "-reconfigure"], profile);
931
+ if (status !== 0) process.exit(status);
932
+ const extra = args.yes ? ["-auto-approve"] : [];
933
+ status = tfBoot(
934
+ projectRoot,
935
+ [
936
+ "apply",
937
+ `-var=project_name=${name}`,
938
+ `-var=region=${region}`,
939
+ `-var=state_bucket_prefix=${prefix}`,
940
+ ...extra
941
+ ],
942
+ profile
943
+ );
944
+ if (status !== 0) process.exit(status);
945
+ const out = captureBootstrap(projectRoot, ["output", "-json"], profile);
946
+ if (out.status !== 0) {
947
+ process.stderr.write("\n \u2717 Could not read bootstrap outputs.\n\n");
948
+ process.exit(1);
949
+ }
950
+ let stateBucket = "";
951
+ let lockTable = "";
952
+ try {
953
+ const o = JSON.parse(out.stdout);
954
+ stateBucket = o.state_bucket?.value ?? "";
955
+ lockTable = o.lock_table?.value ?? "";
956
+ } catch {
957
+ }
958
+ if (!stateBucket || !lockTable) {
959
+ process.stderr.write("\n \u2717 Bootstrap outputs `state_bucket` / `lock_table` not found.\n\n");
960
+ process.exit(1);
961
+ }
962
+ const backendHclPath = path7.join(projectRoot, TF_DIR, "environments", env, "backend.hcl");
963
+ try {
964
+ let hcl = readFileSync5(backendHclPath, "utf8");
965
+ hcl = hcl.replace(/^bucket\s*=\s*".*"$/m, `bucket = "${stateBucket}"`);
966
+ hcl = hcl.replace(/^dynamodb_table\s*=\s*".*"$/m, `dynamodb_table = "${lockTable}"`);
967
+ writeFileSync3(backendHclPath, hcl);
968
+ } catch {
969
+ process.stderr.write(`
970
+ \u2717 Could not update ${backendHclPath}.
971
+
972
+ `);
973
+ process.exit(1);
974
+ }
975
+ process.stdout.write(
976
+ `
977
+ \u2713 Bootstrap complete.
978
+ state_bucket: ${stateBucket}
979
+ lock_table: ${lockTable}
980
+ Updated: iac/terraform/environments/${env}/backend.hcl
981
+
982
+ Next: dude iac init --env ${env}
983
+
984
+ `
985
+ );
986
+ }
987
+ };
988
+
989
+ // src/commands/iac/providers/aws-ecs/lib/images.ts
990
+ import { spawnSync as spawnSync6 } from "child_process";
991
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
992
+ import path8 from "pathe";
993
+ var tagArg = {
994
+ tag: {
995
+ type: "string",
996
+ description: "Image tag (default: git short SHA, with -dirty if uncommitted changes)."
997
+ }
998
+ };
999
+ var platformArg = {
1000
+ platform: {
1001
+ type: "string",
1002
+ description: "Docker build platform (default linux/amd64, to match Fargate x86)."
1003
+ }
1004
+ };
1005
+ function readEcsTarget(projectRoot, profile) {
1006
+ const out = capture2("terraform", [`-chdir=${TF_DIR}`, "output", "-json"], projectRoot, profile);
1007
+ if (out.status !== 0) return null;
1008
+ try {
1009
+ const o = JSON.parse(out.stdout);
1010
+ const backendRepo = o.ecr_backend_repository_url?.value ?? "";
1011
+ const frontendRepo = o.ecr_frontend_repository_url?.value ?? "";
1012
+ const region = o.region?.value ?? "";
1013
+ const cluster = o.cluster_name?.value ?? "";
1014
+ const backendService = o.backend_service_name?.value ?? "";
1015
+ const frontendService = o.frontend_service_name?.value ?? "";
1016
+ if (!backendRepo || !frontendRepo || !region || !cluster || !backendService) return null;
1017
+ return {
1018
+ images: [
1019
+ {
1020
+ name: "backend",
1021
+ repository: backendRepo,
1022
+ dockerfile: "backend/Dockerfile.prod",
1023
+ context: "backend"
1024
+ },
1025
+ {
1026
+ name: "frontend",
1027
+ repository: frontendRepo,
1028
+ dockerfile: "frontend/Dockerfile.prod",
1029
+ context: "frontend"
1030
+ }
1031
+ ],
1032
+ registryHost: backendRepo.split("/")[0] ?? backendRepo,
1033
+ region,
1034
+ cluster,
1035
+ backendService,
1036
+ frontendService,
1037
+ appUrl: o.app_url?.value || void 0
1038
+ };
1039
+ } catch {
1040
+ return null;
1041
+ }
1042
+ }
1043
+ function requireEcsTarget(projectRoot, profile) {
1044
+ const target = readEcsTarget(projectRoot, profile);
1045
+ if (!target) {
1046
+ process.stderr.write(
1047
+ "error: could not read Terraform outputs (ecr_backend_repository_url, cluster_name, \u2026) \u2014 run `dude iac apply` first.\n"
1048
+ );
1049
+ process.exit(1);
1050
+ }
1051
+ return target;
1052
+ }
1053
+ function resolveTag(projectRoot, args) {
1054
+ if (args.tag) {
1055
+ const t = String(args.tag);
1056
+ if (!/^[\w][\w.-]{0,127}$/.test(t)) {
1057
+ process.stderr.write(`
1058
+ \u2717 invalid --tag "${t}" (not a valid Docker tag).
1059
+
1060
+ `);
1061
+ return null;
1062
+ }
1063
+ return t;
1064
+ }
1065
+ const sha = capture2("git", ["rev-parse", "--short=12", "HEAD"], projectRoot);
1066
+ if (sha.status !== 0 || !sha.stdout.trim()) {
1067
+ process.stderr.write(
1068
+ "\n \u2717 Could not derive a git SHA for the image tag.\n Pass --tag <tag>, or run inside a git repo with at least one commit.\n\n"
1069
+ );
1070
+ return null;
1071
+ }
1072
+ let tag = sha.stdout.trim();
1073
+ const status = capture2("git", ["status", "--porcelain"], projectRoot);
1074
+ if (status.status === 0 && status.stdout.trim() !== "") tag += "-dirty";
1075
+ return tag;
1076
+ }
1077
+ function dockerLogin(host, region, projectRoot, profile) {
1078
+ const pw = capture2("aws", ["ecr", "get-login-password", "--region", region], projectRoot, profile);
1079
+ if (pw.status !== 0 || !pw.stdout.trim()) {
1080
+ process.stderr.write("\n \u2717 Could not obtain an ECR login password (check your AWS auth).\n\n");
1081
+ return 1;
1082
+ }
1083
+ const r = spawnSync6("docker", ["login", "--username", "AWS", "--password-stdin", host], {
1084
+ cwd: projectRoot,
1085
+ input: pw.stdout.trim(),
1086
+ stdio: ["pipe", "inherit", "inherit"],
1087
+ env: childEnv(profile)
1088
+ });
1089
+ if (r.error) {
1090
+ const code = r.error.code;
1091
+ process.stderr.write(
1092
+ code === "ENOENT" ? "\n \u2717 `docker` not found on PATH. Install it and retry.\n\n" : `
1093
+ \u2717 failed to run docker: ${r.error.message}
1094
+
1095
+ `
1096
+ );
1097
+ return 1;
1098
+ }
1099
+ return r.status ?? 1;
1100
+ }
1101
+ function doBuild(projectRoot, profile, tag, target, platform) {
1102
+ for (const image of target.images) {
1103
+ process.stdout.write(`
1104
+ \u2192 building ${image.name} ${image.repository}:${tag} (${platform})
1105
+ `);
1106
+ const code = run2(
1107
+ "docker",
1108
+ [
1109
+ "build",
1110
+ "--platform",
1111
+ platform,
1112
+ "-f",
1113
+ image.dockerfile,
1114
+ "-t",
1115
+ `${image.repository}:${tag}`,
1116
+ image.context
1117
+ ],
1118
+ projectRoot,
1119
+ profile
1120
+ );
1121
+ if (code !== 0) return code;
1122
+ }
1123
+ return 0;
1124
+ }
1125
+ function doPush(projectRoot, profile, tag, target) {
1126
+ const code = dockerLogin(target.registryHost, target.region, projectRoot, profile);
1127
+ if (code !== 0) return code;
1128
+ for (const image of target.images) {
1129
+ process.stdout.write(`
1130
+ \u2192 pushing ${image.repository}:${tag}
1131
+ `);
1132
+ const pushCode = run2("docker", ["push", `${image.repository}:${tag}`], projectRoot, profile);
1133
+ if (pushCode !== 0) return pushCode;
1134
+ }
1135
+ return 0;
1136
+ }
1137
+ function doDeploy(projectRoot, profile, env, tag, target) {
1138
+ const tfvarsPath = path8.join(projectRoot, TF_DIR, "environments", env, "terraform.tfvars");
1139
+ try {
1140
+ let tfvars = readFileSync6(tfvarsPath, "utf8");
1141
+ if (/^\s*image_tag\s*=/m.test(tfvars)) {
1142
+ tfvars = tfvars.replace(/^(\s*image_tag\s*=\s*).*$/m, `$1"${tag}"`);
1143
+ } else {
1144
+ tfvars += `
1145
+ image_tag = "${tag}"
1146
+ `;
1147
+ }
1148
+ writeFileSync4(tfvarsPath, tfvars);
1149
+ } catch {
1150
+ process.stderr.write(`
1151
+ \u2717 Could not update ${tfvarsPath}.
1152
+
1153
+ `);
1154
+ return 1;
1155
+ }
1156
+ process.stdout.write(`
1157
+ \u2192 deploying :${tag} to "${env}"\u2026
1158
+ `);
1159
+ const code = tf(projectRoot, ["apply", varFile(env), "-auto-approve"], profile);
1160
+ if (code === 0) {
1161
+ process.stdout.write(
1162
+ `
1163
+ \u2713 Task definitions updated to :${tag} \u2014 ECS is rolling the services now
1164
+ (auto-rollback on failure). Watch them with: dude iac status --env ${env}
1165
+ Remember to apply pending Django migrations: dude iac migrate --env ${env}
1166
+ ` + (target.appUrl ? ` App URL: ${target.appUrl}
1167
+ ` : "")
1168
+ );
1169
+ }
1170
+ return code;
1171
+ }
1172
+
1173
+ // src/commands/iac/providers/aws-ecs/commands/build/index.ts
1174
+ var iacBuildCommand = {
1175
+ available: hasIac,
1176
+ description: "Build the backend + frontend production images (Dockerfile.prod), tagged for the shared ECR repos.",
1177
+ args: { ...envArg, ...tagArg, ...platformArg },
1178
+ async run({ projectRoot, args }) {
1179
+ if (!requireIac(projectRoot)) process.exit(1);
1180
+ const env = requireEnv(projectRoot, args);
1181
+ const profile = resolveProfile(projectRoot, args, env);
1182
+ const tag = resolveTag(projectRoot, args);
1183
+ if (!tag) process.exit(1);
1184
+ const target = requireEcsTarget(projectRoot, profile);
1185
+ const platform = String(args.platform ?? "linux/amd64");
1186
+ process.exit(doBuild(projectRoot, profile, tag, target, platform));
1187
+ }
1188
+ };
1189
+
1190
+ // src/commands/iac/providers/aws-ecs/commands/deploy/index.ts
1191
+ var iacDeployCommand = {
1192
+ available: hasIac,
1193
+ description: "Deploy the server: record the image tag in terraform.tfvars and roll the ECS service onto it (terraform apply).",
1194
+ args: { ...envArg, ...tagArg },
1195
+ async run({ projectRoot, args }) {
1196
+ if (!requireIac(projectRoot)) process.exit(1);
1197
+ const env = requireEnv(projectRoot, args);
1198
+ const profile = resolveProfile(projectRoot, args, env);
1199
+ const tag = resolveTag(projectRoot, args);
1200
+ if (!tag) process.exit(1);
1201
+ const target = requireEcsTarget(projectRoot, profile);
1202
+ process.exit(doDeploy(projectRoot, profile, env, tag, target));
1203
+ }
1204
+ };
1205
+
1206
+ // src/commands/iac/providers/aws-ecs/lib/aws.ts
1207
+ function emptyVersionedBucket(bucket, region, projectRoot, profile) {
1208
+ const regionFlag = region ? ["--region", region] : [];
1209
+ for (let i = 0; i < 100; i++) {
1210
+ const list = capture(
1211
+ "aws",
1212
+ [
1213
+ "s3api",
1214
+ "list-object-versions",
1215
+ "--bucket",
1216
+ bucket,
1217
+ "--max-items",
1218
+ "1000",
1219
+ "--query",
1220
+ "[Versions[].{Key:Key,VersionId:VersionId}, DeleteMarkers[].{Key:Key,VersionId:VersionId}][]",
1221
+ "--output",
1222
+ "json",
1223
+ ...regionFlag
1224
+ ],
1225
+ projectRoot,
1226
+ profile
1227
+ );
1228
+ if (list.status !== 0) return;
1229
+ let objects = [];
1230
+ try {
1231
+ objects = JSON.parse(list.stdout) ?? [];
1232
+ } catch {
1233
+ return;
1234
+ }
1235
+ if (!objects.length) return;
1236
+ capture(
1237
+ "aws",
1238
+ [
1239
+ "s3api",
1240
+ "delete-objects",
1241
+ "--bucket",
1242
+ bucket,
1243
+ "--delete",
1244
+ JSON.stringify({ Objects: objects.slice(0, 1e3), Quiet: true }),
1245
+ ...regionFlag
1246
+ ],
1247
+ projectRoot,
1248
+ profile
1249
+ );
1250
+ }
1251
+ }
1252
+ function envStateLiveness(bucket, key, region, projectRoot, profile) {
1253
+ if (!bucket || !key) return { live: false, reason: "no remote state configured" };
1254
+ const regionFlag = region ? ["--region", region] : [];
1255
+ const r = capture("aws", ["s3", "cp", `s3://${bucket}/${key}`, "-", ...regionFlag], projectRoot, profile);
1256
+ if (r.status !== 0) {
1257
+ return { live: false, reason: "no state object (never applied, or already removed)" };
1258
+ }
1259
+ try {
1260
+ const state = JSON.parse(r.stdout);
1261
+ const n = Array.isArray(state.resources) ? state.resources.length : 0;
1262
+ return n > 0 ? { live: true, reason: `${n} resource(s) still in state` } : { live: false, reason: "state is empty (already destroyed)" };
1263
+ } catch {
1264
+ return { live: true, reason: "state present but unreadable \u2014 keeping to be safe" };
1265
+ }
1266
+ }
1267
+
1268
+ // src/commands/iac/providers/aws-ecs/commands/destroy/index.ts
1269
+ var iacDestroyCommand = {
1270
+ available: hasIac,
1271
+ description: "Tear down everything for an environment: destroy the Terraform infrastructure, then empty + destroy the state backend (S3 bucket + DynamoDB table) and the shared ECR repository. Use --keep-backend to preserve the shared bootstrap.",
1272
+ args: {
1273
+ ...envArg,
1274
+ yes: { type: "boolean", description: "Skip the interactive approval (-auto-approve)." },
1275
+ "keep-backend": {
1276
+ type: "boolean",
1277
+ description: "Keep the shared bootstrap (S3 state bucket + DynamoDB lock table + ECR repository). It is kept automatically while any other environment still uses the same bucket; pass this to force-keep it even when destroying the last environment."
1278
+ },
1279
+ "skip-tf": {
1280
+ type: "boolean",
1281
+ description: "Skip the Terraform destroy of the environment \u2014 only run the backend teardown (unless --keep-backend)."
1282
+ }
1283
+ },
1284
+ async run({ projectRoot, args }) {
1285
+ if (!requireIac(projectRoot)) process.exit(1);
1286
+ const env = requireEnv(projectRoot, args);
1287
+ const profile = resolveProfile(projectRoot, args, env);
1288
+ const extra = args.yes ? ["-auto-approve"] : [];
1289
+ const region = tfOutputRaw(projectRoot, "region", profile) || tfvarsValue(projectRoot, env, "region");
1290
+ if (!args["skip-tf"]) {
1291
+ const code = tf(projectRoot, ["destroy", varFile(env), ...extra], profile);
1292
+ if (code !== 0) process.exit(code);
1293
+ }
1294
+ if (args["keep-backend"]) {
1295
+ process.stdout.write(" \u21B7 Keeping the Terraform state backend (--keep-backend). Done.\n\n");
1296
+ process.exit(0);
1297
+ }
1298
+ const backend = readBackend(projectRoot, env);
1299
+ const stateBucket = backend.bucket;
1300
+ const lockTable = backend.table;
1301
+ const backendRegion = backend.region || region;
1302
+ if (!stateBucket && !lockTable) {
1303
+ process.stdout.write(" \u21B7 No state backend configured to tear down. Done.\n\n");
1304
+ process.exit(0);
1305
+ }
1306
+ if (stateBucket) {
1307
+ const siblings = listEnvironments(projectRoot).filter(
1308
+ (e) => e !== env && readBackend(projectRoot, e).bucket === stateBucket
1309
+ );
1310
+ const live = [];
1311
+ if (siblings.length) {
1312
+ process.stdout.write(` \u2192 checking sibling environments on this backend\u2026
1313
+ `);
1314
+ for (const e of siblings) {
1315
+ const b = readBackend(projectRoot, e);
1316
+ const { live: isLive, reason } = envStateLiveness(
1317
+ b.bucket,
1318
+ b.key,
1319
+ b.region || region,
1320
+ projectRoot,
1321
+ profile
1322
+ );
1323
+ process.stdout.write(` \u2022 ${e}: ${isLive ? "still live" : "not live"} \u2014 ${reason}
1324
+ `);
1325
+ if (isLive) live.push(e);
1326
+ }
1327
+ }
1328
+ if (live.length) {
1329
+ process.stdout.write(
1330
+ `
1331
+ \u21B7 Keeping the shared backend + ECR \u2014 still used by: ${live.join(", ")}.
1332
+ Destroying it would wipe their state and registry. Destroy those
1333
+ environments first, or pass --keep-backend. Done.
1334
+
1335
+ `
1336
+ );
1337
+ process.exit(0);
1338
+ }
1339
+ }
1340
+ process.stdout.write(
1341
+ `
1342
+ \u2192 tearing down the shared bootstrap (S3 + DynamoDB + ECR)\u2026
1343
+ bucket: ${stateBucket || "(none)"} lock table: ${lockTable || "(none)"}
1344
+ `
1345
+ );
1346
+ if (stateBucket) {
1347
+ process.stdout.write(` \u2192 emptying state bucket ${stateBucket}\u2026
1348
+ `);
1349
+ emptyVersionedBucket(stateBucket, backendRegion, projectRoot, profile);
1350
+ }
1351
+ tfBoot(projectRoot, ["init", "-input=false"], profile);
1352
+ const bootCode = tfBoot(projectRoot, ["destroy", ...extra], profile);
1353
+ const regionFlag = backendRegion ? ["--region", backendRegion] : [];
1354
+ if (stateBucket) {
1355
+ emptyVersionedBucket(stateBucket, backendRegion, projectRoot, profile);
1356
+ capture("aws", ["s3api", "delete-bucket", "--bucket", stateBucket, ...regionFlag], projectRoot, profile);
1357
+ }
1358
+ if (lockTable) {
1359
+ capture("aws", ["dynamodb", "delete-table", "--table-name", lockTable, ...regionFlag], projectRoot, profile);
1360
+ }
1361
+ const bucketGone = !stateBucket || capture("aws", ["s3api", "head-bucket", "--bucket", stateBucket, ...regionFlag], projectRoot, profile).status !== 0;
1362
+ const tableGone = !lockTable || capture("aws", ["dynamodb", "describe-table", "--table-name", lockTable, ...regionFlag], projectRoot, profile).status !== 0;
1363
+ if (bucketGone && tableGone) {
1364
+ process.stdout.write(" \u2713 State backend removed.\n\n");
1365
+ process.exit(0);
1366
+ }
1367
+ process.stderr.write(
1368
+ " \u2717 Some state-backend resources could not be removed. Check the AWS console:\n" + (bucketGone ? "" : ` S3 bucket: ${stateBucket}
1369
+ `) + (tableGone ? "" : ` DynamoDB table: ${lockTable}
1370
+
1371
+ `)
1372
+ );
1373
+ process.exit(bootCode || 1);
1374
+ }
1375
+ };
1376
+
1377
+ // src/commands/iac/providers/aws-ecs/commands/fmt/index.ts
1378
+ var iacFmtCommand = {
1379
+ available: hasIac,
1380
+ description: "Format all Terraform files (terraform fmt -recursive).",
1381
+ async run({ projectRoot }) {
1382
+ if (!requireIac(projectRoot)) process.exit(1);
1383
+ process.exit(tf(projectRoot, ["fmt", "-recursive"]));
1384
+ }
1385
+ };
1386
+
1387
+ // src/commands/iac/providers/aws-ecs/commands/init/index.ts
1388
+ var iacInitCommand = {
1389
+ available: hasIac,
1390
+ description: "Initialise Terraform for an environment (configures the S3 remote backend).",
1391
+ args: { ...envArg },
1392
+ async run({ projectRoot, args }) {
1393
+ if (!requireIac(projectRoot)) process.exit(1);
1394
+ const env = requireEnv(projectRoot, args);
1395
+ const profile = resolveProfile(projectRoot, args, env);
1396
+ process.exit(tf(projectRoot, ["init", "-reconfigure", backendConfig(env)], profile));
1397
+ }
1398
+ };
1399
+
1400
+ // src/commands/iac/providers/aws-ecs/commands/login/index.ts
1401
+ var iacLoginCommand = {
1402
+ available: hasIac,
1403
+ description: "Configure/verify AWS credentials for an environment (maps --env to an AWS profile).",
1404
+ args: { ...envArg },
1405
+ async run({ projectRoot, args }) {
1406
+ if (!requireIac(projectRoot)) process.exit(1);
1407
+ const env = requireEnv(projectRoot, args);
1408
+ const profile = resolveProfile(projectRoot, args, env);
1409
+ const list = capture("aws", ["configure", "list-profiles"], projectRoot);
1410
+ const known = list.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
1411
+ const exists = list.status === 0 && known.includes(profile);
1412
+ const ssoStart = exists ? capture("aws", ["configure", "get", "sso_start_url", "--profile", profile], projectRoot) : { status: 1, stdout: "" };
1413
+ const ssoSession = exists ? capture("aws", ["configure", "get", "sso_session", "--profile", profile], projectRoot) : { status: 1, stdout: "" };
1414
+ const isSso = ssoStart.stdout.trim() !== "" || ssoSession.stdout.trim() !== "";
1415
+ if (!exists) {
1416
+ process.stdout.write(
1417
+ `
1418
+ Profile "${profile}" is not configured yet. Setting it up interactively.
1419
+ (For SSO instead, cancel and run: aws configure sso --profile ${profile})
1420
+
1421
+ `
1422
+ );
1423
+ const code = run("aws", ["configure", "--profile", profile], projectRoot);
1424
+ if (code !== 0) process.exit(code);
1425
+ } else if (isSso) {
1426
+ const code = run("aws", ["sso", "login", "--profile", profile], projectRoot);
1427
+ if (code !== 0) process.exit(code);
1428
+ }
1429
+ const who = capture(
1430
+ "aws",
1431
+ ["sts", "get-caller-identity", "--profile", profile, "--output", "json"],
1432
+ projectRoot
1433
+ );
1434
+ if (who.status !== 0) {
1435
+ process.stderr.write(
1436
+ `
1437
+ \u2717 Credentials for profile "${profile}" are not valid.
1438
+ ` + (isSso ? ` Try: aws sso login --profile ${profile}
1439
+
1440
+ ` : ` Try: aws configure --profile ${profile}
1441
+
1442
+ `)
1443
+ );
1444
+ process.exit(1);
1445
+ }
1446
+ let account = "";
1447
+ let arn = "";
1448
+ try {
1449
+ const o = JSON.parse(who.stdout);
1450
+ account = o.Account ?? "";
1451
+ arn = o.Arn ?? "";
1452
+ } catch {
1453
+ }
1454
+ process.stdout.write(
1455
+ `
1456
+ \u2713 Authenticated for env "${env}".
1457
+ profile: ${profile}
1458
+ account: ${account}
1459
+ arn: ${arn}
1460
+
1461
+ Now: dude iac plan --env ${env}
1462
+
1463
+ `
1464
+ );
1465
+ }
1466
+ };
1467
+
1468
+ // src/commands/iac/providers/aws-ecs/commands/logs/index.ts
1469
+ var SERVICES = ["backend", "frontend", "worker", "beat"];
1470
+ var iacLogsCommand = {
1471
+ available: hasIac,
1472
+ description: "Tail a service's CloudWatch logs (aws logs tail).",
1473
+ args: {
1474
+ ...envArg,
1475
+ service: {
1476
+ type: "string",
1477
+ description: "Which service to tail: backend (default), frontend, worker, beat."
1478
+ },
1479
+ since: {
1480
+ type: "string",
1481
+ description: "How far back to start (e.g. 15m, 2h, 1d). Default: 15m."
1482
+ },
1483
+ follow: { type: "boolean", description: "Keep streaming new log events (like tail -f)." }
1484
+ },
1485
+ async run({ projectRoot, args }) {
1486
+ if (!requireIac(projectRoot)) process.exit(1);
1487
+ const env = requireEnv(projectRoot, args);
1488
+ const profile = resolveProfile(projectRoot, args, env);
1489
+ const which = String(args.service ?? "backend");
1490
+ if (!SERVICES.includes(which)) {
1491
+ process.stderr.write(`
1492
+ \u2717 Unknown --service "${which}" (use: ${SERVICES.join(", ")}).
1493
+
1494
+ `);
1495
+ process.exit(1);
1496
+ }
1497
+ const group = `/ecs/${projectName(projectRoot)}-${env}-${which}`;
1498
+ const region = tfOutputRaw(projectRoot, "region", profile) || tfvarsValue(projectRoot, env, "region");
1499
+ const cliArgs = ["logs", "tail", group, "--since", String(args.since ?? "15m")];
1500
+ if (args.follow) cliArgs.push("--follow");
1501
+ if (region) cliArgs.push("--region", region);
1502
+ process.exit(run("aws", cliArgs, projectRoot, profile));
1503
+ }
1504
+ };
1505
+
1506
+ // src/commands/iac/providers/aws-ecs/commands/migrate/index.ts
1507
+ function readMigrateTarget(projectRoot, profile) {
1508
+ const out = capture2("terraform", [`-chdir=${TF_DIR}`, "output", "-json"], projectRoot, profile);
1509
+ if (out.status !== 0) return null;
1510
+ try {
1511
+ const o = JSON.parse(out.stdout);
1512
+ const cluster = String(o.cluster_name?.value ?? "");
1513
+ const taskDefinition = String(o.migrate_task_definition?.value ?? "");
1514
+ const subnets = Array.isArray(o.public_subnet_ids?.value) ? o.public_subnet_ids.value : [];
1515
+ const securityGroup = String(o.backend_security_group_id?.value ?? "");
1516
+ const region = String(o.region?.value ?? "");
1517
+ if (!cluster || !taskDefinition || !subnets.length || !securityGroup || !region) return null;
1518
+ return { cluster, taskDefinition, subnets, securityGroup, region };
1519
+ } catch {
1520
+ return null;
1521
+ }
1522
+ }
1523
+ var iacMigrateCommand = {
1524
+ available: hasIac,
1525
+ description: "Run Django migrations (manage.py migrate) as a one-off ECS Fargate task.",
1526
+ args: { ...envArg },
1527
+ async run({ projectRoot, args }) {
1528
+ if (!requireIac(projectRoot)) process.exit(1);
1529
+ const env = requireEnv(projectRoot, args);
1530
+ const profile = resolveProfile(projectRoot, args, env);
1531
+ const target = readMigrateTarget(projectRoot, profile);
1532
+ if (!target) {
1533
+ process.stderr.write(
1534
+ "error: could not read Terraform outputs (migrate_task_definition, cluster_name, \u2026) \u2014 run `dude iac apply` first.\n"
1535
+ );
1536
+ process.exit(1);
1537
+ }
1538
+ process.stdout.write(`
1539
+ \u2192 running migrations on "${env}" (${target.taskDefinition})\u2026
1540
+ `);
1541
+ const netConf = `awsvpcConfiguration={subnets=[${target.subnets.join(",")}],securityGroups=[${target.securityGroup}],assignPublicIp=ENABLED}`;
1542
+ const started = capture(
1543
+ "aws",
1544
+ [
1545
+ "ecs",
1546
+ "run-task",
1547
+ "--cluster",
1548
+ target.cluster,
1549
+ "--task-definition",
1550
+ target.taskDefinition,
1551
+ "--launch-type",
1552
+ "FARGATE",
1553
+ "--count",
1554
+ "1",
1555
+ "--network-configuration",
1556
+ netConf,
1557
+ "--region",
1558
+ target.region,
1559
+ "--output",
1560
+ "json"
1561
+ ],
1562
+ projectRoot,
1563
+ profile
1564
+ );
1565
+ if (started.status !== 0) {
1566
+ process.stderr.write("\n \u2717 aws ecs run-task failed.\n\n");
1567
+ process.exit(1);
1568
+ }
1569
+ let taskArn = "";
1570
+ try {
1571
+ const parsed = JSON.parse(started.stdout);
1572
+ taskArn = parsed.tasks?.[0]?.taskArn ?? "";
1573
+ if (!taskArn) {
1574
+ const reason = parsed.failures?.[0]?.reason ?? "unknown";
1575
+ process.stderr.write(`
1576
+ \u2717 Task did not start (${reason}).
1577
+
1578
+ `);
1579
+ process.exit(1);
1580
+ }
1581
+ } catch {
1582
+ process.stderr.write("\n \u2717 Could not parse the run-task response.\n\n");
1583
+ process.exit(1);
1584
+ }
1585
+ process.stdout.write(` task ${taskArn.split("/").pop()} started \u2014 waiting\u2026
1586
+ `);
1587
+ for (; ; ) {
1588
+ sleepMs(5e3);
1589
+ const described = capture(
1590
+ "aws",
1591
+ [
1592
+ "ecs",
1593
+ "describe-tasks",
1594
+ "--cluster",
1595
+ target.cluster,
1596
+ "--tasks",
1597
+ taskArn,
1598
+ "--region",
1599
+ target.region,
1600
+ "--output",
1601
+ "json"
1602
+ ],
1603
+ projectRoot,
1604
+ profile
1605
+ );
1606
+ if (described.status !== 0) continue;
1607
+ let task;
1608
+ try {
1609
+ task = JSON.parse(described.stdout).tasks?.[0];
1610
+ } catch {
1611
+ continue;
1612
+ }
1613
+ if (!task) continue;
1614
+ if (task.lastStatus !== "STOPPED") {
1615
+ process.stdout.write(` ${task.lastStatus ?? "\u2026"}
1616
+ `);
1617
+ continue;
1618
+ }
1619
+ const exitCode = task.containers?.[0]?.exitCode;
1620
+ if (exitCode === 0) {
1621
+ process.stdout.write("\n \u2713 Migrations applied.\n\n");
1622
+ process.exit(0);
1623
+ }
1624
+ process.stderr.write(
1625
+ `
1626
+ \u2717 Migration task failed (exit ${exitCode ?? "?"}) \u2014 ${task.stoppedReason ?? task.containers?.[0]?.reason ?? "no reason reported"}.
1627
+ Inspect the logs with: dude iac logs --env ${env} --service backend
1628
+
1629
+ `
1630
+ );
1631
+ process.exit(typeof exitCode === "number" && exitCode > 0 ? exitCode : 1);
1632
+ }
1633
+ }
1634
+ };
1635
+
1636
+ // src/commands/iac/providers/aws-ecs/commands/new-env/index.ts
1637
+ import { cpSync, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
1638
+ import path9 from "pathe";
1639
+ var iacNewEnvCommand = {
1640
+ available: hasIac,
1641
+ description: "Scaffold a new environment (iac/terraform/environments/<name>) by copying an existing one.",
1642
+ args: {
1643
+ env: {
1644
+ type: "string",
1645
+ description: "Name of the new environment to create (lowercase kebab-case).",
1646
+ required: true
1647
+ },
1648
+ from: {
1649
+ type: "string",
1650
+ description: "Existing environment to copy as a starting point (default: dev)."
1651
+ }
1652
+ },
1653
+ async run({ projectRoot, args }) {
1654
+ if (!requireIac(projectRoot)) process.exit(1);
1655
+ const name = args.env == null ? "" : String(args.env);
1656
+ if (!name) {
1657
+ process.stderr.write("\n \u2717 --env is required (the name of the environment to create).\n\n");
1658
+ process.exit(1);
1659
+ }
1660
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
1661
+ process.stderr.write(`
1662
+ \u2717 invalid --env "${name}" (expected lowercase kebab-case).
1663
+
1664
+ `);
1665
+ process.exit(1);
1666
+ }
1667
+ const envs = listEnvironments(projectRoot);
1668
+ if (envs.includes(name)) {
1669
+ process.stderr.write(`
1670
+ \u2717 environment "${name}" already exists.
1671
+
1672
+ `);
1673
+ process.exit(1);
1674
+ }
1675
+ if (!envs.length) {
1676
+ process.stderr.write(
1677
+ "\n \u2717 no existing environment to copy from (expected at least iac/terraform/environments/dev).\n\n"
1678
+ );
1679
+ process.exit(1);
1680
+ }
1681
+ const from = args.from == null ? "dev" : String(args.from);
1682
+ if (!envs.includes(from)) {
1683
+ process.stderr.write(`
1684
+ \u2717 --from "${from}" does not exist. Available: ${envs.join(", ")}
1685
+
1686
+ `);
1687
+ process.exit(1);
1688
+ }
1689
+ const base = path9.join(projectRoot, TF_ENVIRONMENTS_DIR);
1690
+ const dst = path9.join(base, name);
1691
+ cpSync(path9.join(base, from), dst, { recursive: true });
1692
+ const tfvarsPath = path9.join(dst, "terraform.tfvars");
1693
+ writeFileSync5(
1694
+ tfvarsPath,
1695
+ readFileSync7(tfvarsPath, "utf8").replace(/^(\s*environment\s*=\s*).*$/m, `$1"${name}"`)
1696
+ );
1697
+ const backendPath = path9.join(dst, "backend.hcl");
1698
+ writeFileSync5(
1699
+ backendPath,
1700
+ readFileSync7(backendPath, "utf8").replace(
1701
+ /^(\s*key\s*=\s*).*$/m,
1702
+ `$1"${projectName(projectRoot)}/${name}/terraform.tfstate"`
1703
+ )
1704
+ );
1705
+ process.stdout.write(
1706
+ `
1707
+ \u2713 Created environment "${name}" (copied from "${from}").
1708
+ iac/terraform/environments/${name}/{backend.hcl,terraform.tfvars}
1709
+
1710
+ Next:
1711
+ 1. Review iac/terraform/environments/${name}/terraform.tfvars (sizing, domain, allowed_cidrs, \u2026).
1712
+ 2. First env on a brand-new state backend? Run:
1713
+ dude iac bootstrap --env ${name} --state-bucket-prefix <prefix>
1714
+ Otherwise it reuses the existing bucket \u2014 skip bootstrap.
1715
+ 3. dude iac init --env ${name} && dude iac apply --env ${name}
1716
+
1717
+ `
1718
+ );
1719
+ }
1720
+ };
1721
+
1722
+ // src/commands/iac/providers/aws-ecs/commands/output/index.ts
1723
+ var iacOutputCommand = {
1724
+ available: hasIac,
1725
+ description: "Print Terraform outputs for an environment (app URL, ECR URLs, cluster/services\u2026).",
1726
+ args: {
1727
+ ...envArg,
1728
+ json: { type: "boolean", description: "Emit machine-readable JSON." }
1729
+ },
1730
+ async run({ projectRoot, args }) {
1731
+ if (!requireIac(projectRoot)) process.exit(1);
1732
+ const env = requireEnv(projectRoot, args);
1733
+ const profile = resolveProfile(projectRoot, args, env);
1734
+ const extra = args.json ? ["-json"] : [];
1735
+ process.exit(tf(projectRoot, ["output", ...extra], profile));
1736
+ }
1737
+ };
1738
+
1739
+ // src/commands/iac/providers/aws-ecs/commands/plan/index.ts
1740
+ var iacPlanCommand = {
1741
+ available: hasIac,
1742
+ description: "Show the infrastructure changes Terraform would apply for an environment.",
1743
+ args: { ...envArg },
1744
+ async run({ projectRoot, args }) {
1745
+ if (!requireIac(projectRoot)) process.exit(1);
1746
+ const env = requireEnv(projectRoot, args);
1747
+ const profile = resolveProfile(projectRoot, args, env);
1748
+ process.exit(tf(projectRoot, ["plan", varFile(env)], profile));
1749
+ }
1750
+ };
1751
+
1752
+ // src/commands/iac/providers/aws-ecs/commands/push/index.ts
1753
+ var iacPushCommand = {
1754
+ available: hasIac,
1755
+ description: "Log in to ECR and push the server image (build it first).",
1756
+ args: { ...envArg, ...tagArg },
1757
+ async run({ projectRoot, args }) {
1758
+ if (!requireIac(projectRoot)) process.exit(1);
1759
+ const env = requireEnv(projectRoot, args);
1760
+ const profile = resolveProfile(projectRoot, args, env);
1761
+ const tag = resolveTag(projectRoot, args);
1762
+ if (!tag) process.exit(1);
1763
+ const target = requireEcsTarget(projectRoot, profile);
1764
+ process.exit(doPush(projectRoot, profile, tag, target));
1765
+ }
1766
+ };
1767
+
1768
+ // src/commands/iac/providers/aws-ecs/commands/shell/index.ts
1769
+ import { spawnSync as spawnSync7 } from "child_process";
1770
+ var iacShellCommand = {
1771
+ available: hasIac,
1772
+ description: "Open an interactive shell in the IaC runner container (terraform, aws) scoped to an environment.",
1773
+ args: { ...envArg },
1774
+ async run({ projectRoot, args }) {
1775
+ if (!requireIac(projectRoot)) process.exit(1);
1776
+ if (!dockerAvailable()) {
1777
+ process.stderr.write(
1778
+ "\n \u2717 Docker is required for `dude iac shell` (it runs the IaC toolchain in a container).\n Start Docker and retry.\n\n"
1779
+ );
1780
+ process.exit(1);
1781
+ }
1782
+ if (!hasRunnerDockerfile(projectRoot)) {
1783
+ process.stderr.write(
1784
+ `
1785
+ \u2717 No runner Dockerfile found (iac/runner/Dockerfile).
1786
+ Re-scaffold with \`--iac aws-ecs\` or add it to enable the runner.
1787
+
1788
+ `
1789
+ );
1790
+ process.exit(1);
1791
+ }
1792
+ const env = requireEnv(projectRoot, args);
1793
+ const profile = resolveProfile(projectRoot, args, env);
1794
+ process.stdout.write(
1795
+ `
1796
+ \u2192 Entering the IaC runner for env "${env}" (profile "${profile}").
1797
+ The project is mounted at /work. Type "exit" to leave.
1798
+
1799
+ `
1800
+ );
1801
+ const r = spawnSync7("docker", dockerShellArgs(projectRoot, profile), {
1802
+ stdio: "inherit",
1803
+ cwd: projectRoot
1804
+ });
1805
+ process.exit(r.status ?? 1);
1806
+ }
1807
+ };
1808
+
1809
+ // src/commands/iac/providers/aws-ecs/commands/ship/index.ts
1810
+ var iacShipCommand = {
1811
+ available: hasIac,
1812
+ description: "Build, push, and deploy in one step (the local inner loop).",
1813
+ args: { ...envArg, ...tagArg, ...platformArg },
1814
+ async run({ projectRoot, args }) {
1815
+ if (!requireIac(projectRoot)) process.exit(1);
1816
+ const env = requireEnv(projectRoot, args);
1817
+ const profile = resolveProfile(projectRoot, args, env);
1818
+ const tag = resolveTag(projectRoot, args);
1819
+ if (!tag) process.exit(1);
1820
+ const target = requireEcsTarget(projectRoot, profile);
1821
+ const platform = String(args.platform ?? "linux/amd64");
1822
+ const project = projectName(projectRoot);
1823
+ let code = doBuild(projectRoot, profile, tag, target, platform);
1824
+ if (code !== 0) process.exit(code);
1825
+ code = doPush(projectRoot, profile, tag, target);
1826
+ if (code !== 0) process.exit(code);
1827
+ code = doDeploy(projectRoot, profile, env, tag, target);
1828
+ if (code === 0) {
1829
+ process.stdout.write(`
1830
+ \u2713 Shipped ${project}:${tag} to "${env}".
1831
+
1832
+ `);
1833
+ }
1834
+ process.exit(code);
1835
+ }
1836
+ };
1837
+
1838
+ // src/commands/iac/providers/aws-ecs/commands/status/index.ts
1839
+ var SERVICES2 = ["backend", "frontend", "worker", "beat"];
1840
+ var iacStatusCommand = {
1841
+ available: hasIac,
1842
+ description: "Show an ECS service state, running tasks and recent deployment events.",
1843
+ args: {
1844
+ ...envArg,
1845
+ service: {
1846
+ type: "string",
1847
+ description: "Which service to inspect: backend (default), frontend, worker, beat."
1848
+ }
1849
+ },
1850
+ async run({ projectRoot, args }) {
1851
+ if (!requireIac(projectRoot)) process.exit(1);
1852
+ const env = requireEnv(projectRoot, args);
1853
+ const profile = resolveProfile(projectRoot, args, env);
1854
+ const which = String(args.service ?? "backend");
1855
+ if (!SERVICES2.includes(which)) {
1856
+ process.stderr.write(`
1857
+ \u2717 Unknown --service "${which}" (use: ${SERVICES2.join(", ")}).
1858
+
1859
+ `);
1860
+ process.exit(1);
1861
+ }
1862
+ const conventional = `${projectName(projectRoot)}-${env}-${which}`;
1863
+ const cluster = tfOutputRaw(projectRoot, "cluster_name", profile) || `${projectName(projectRoot)}-${env}`;
1864
+ const service = tfOutputRaw(projectRoot, `${which}_service_name`, profile) || conventional;
1865
+ const region = tfOutputRaw(projectRoot, "region", profile) || tfvarsValue(projectRoot, env, "region");
1866
+ const regionFlag = region ? ["--region", region] : [];
1867
+ const r = capture(
1868
+ "aws",
1869
+ [
1870
+ "ecs",
1871
+ "describe-services",
1872
+ "--cluster",
1873
+ cluster,
1874
+ "--services",
1875
+ service,
1876
+ "--output",
1877
+ "json",
1878
+ ...regionFlag
1879
+ ],
1880
+ projectRoot,
1881
+ profile
1882
+ );
1883
+ if (r.status !== 0) {
1884
+ process.stderr.write(
1885
+ `
1886
+ \u2717 Could not describe service "${service}" on cluster "${cluster}".
1887
+ Is the environment provisioned? Try: dude iac apply --env ${env}
1888
+
1889
+ `
1890
+ );
1891
+ process.exit(1);
1892
+ }
1893
+ let svc;
1894
+ try {
1895
+ svc = JSON.parse(r.stdout).services?.[0];
1896
+ } catch {
1897
+ }
1898
+ if (!svc) {
1899
+ process.stderr.write(`
1900
+ \u2717 Service "${service}" not found on cluster "${cluster}".
1901
+
1902
+ `);
1903
+ process.exit(1);
1904
+ }
1905
+ process.stdout.write(
1906
+ `
1907
+ Service ${service} (cluster ${cluster})
1908
+ status: ${svc.status ?? "UNKNOWN"}
1909
+ tasks: ${svc.runningCount ?? 0} running / ${svc.pendingCount ?? 0} pending / ${svc.desiredCount ?? 0} desired
1910
+ `
1911
+ );
1912
+ for (const d of svc.deployments ?? []) {
1913
+ const taskDef = d.taskDefinition?.split("/").pop() ?? "";
1914
+ process.stdout.write(
1915
+ ` deploy: ${d.status ?? ""} ${d.rolloutState ?? ""} ${taskDef} (${d.runningCount ?? 0}/${d.desiredCount ?? 0})
1916
+ `
1917
+ );
1918
+ }
1919
+ const events = (svc.events ?? []).slice(0, 5);
1920
+ if (events.length) {
1921
+ process.stdout.write(`
1922
+ Recent events:
1923
+ `);
1924
+ for (const e of events) {
1925
+ process.stdout.write(` ${e.createdAt ?? ""} ${e.message ?? ""}
1926
+ `);
1927
+ }
1928
+ }
1929
+ const appUrl = tfOutputRaw(projectRoot, "app_url", profile);
1930
+ if (appUrl) process.stdout.write(`
1931
+ App URL: ${appUrl}
1932
+ `);
1933
+ process.stdout.write("\n");
1934
+ }
1935
+ };
1936
+
1937
+ // src/commands/iac/providers/aws-ecs/commands/validate/index.ts
1938
+ var iacValidateCommand = {
1939
+ available: hasIac,
1940
+ description: "Validate the Terraform configuration.",
1941
+ async run({ projectRoot }) {
1942
+ if (!requireIac(projectRoot)) process.exit(1);
1943
+ process.exit(tf(projectRoot, ["validate"]));
1944
+ }
1945
+ };
1946
+
1947
+ // src/commands/iac/providers/aws-ecs/index.ts
1948
+ var awsEcsProvider = {
1949
+ id: "aws-ecs",
1950
+ label: "AWS ECS Fargate (Terraform)",
1951
+ detect: hasIac,
1952
+ commands: {
1953
+ login: iacLoginCommand,
1954
+ "new-env": iacNewEnvCommand,
1955
+ bootstrap: iacBootstrapCommand,
1956
+ init: iacInitCommand,
1957
+ plan: iacPlanCommand,
1958
+ apply: iacApplyCommand,
1959
+ destroy: iacDestroyCommand,
1960
+ output: iacOutputCommand,
1961
+ fmt: iacFmtCommand,
1962
+ validate: iacValidateCommand,
1963
+ build: iacBuildCommand,
1964
+ push: iacPushCommand,
1965
+ deploy: iacDeployCommand,
1966
+ ship: iacShipCommand,
1967
+ migrate: iacMigrateCommand,
1968
+ status: iacStatusCommand,
1969
+ logs: iacLogsCommand,
1970
+ shell: iacShellCommand
1971
+ }
1972
+ };
1973
+
1974
+ // src/commands/iac/index.ts
1975
+ var iacProviders = [awsEcsProvider];
1976
+ function activeIacProvider(projectRoot = process.cwd()) {
1977
+ return iacProviders.find((p) => p.detect(projectRoot));
1978
+ }
1979
+ var provider = activeIacProvider() ?? iacProviders[0];
1980
+ var iacCommands = provider?.commands ?? {};
1981
+
1982
+ // src/commands/_docker.ts
1983
+ import { spawnSync as spawnSync8 } from "child_process";
1984
+ function dc(args) {
1985
+ const result = spawnSync8("docker", ["compose", ...args], { stdio: "inherit" });
1986
+ process.exit(result.status ?? 0);
1987
+ }
1988
+
1989
+ // src/commands/down/index.ts
1990
+ var downCommand = {
1991
+ description: "Stop and remove all service containers (docker compose down).",
1992
+ args: {},
1993
+ async run() {
1994
+ dc(["down"]);
1995
+ }
1996
+ };
1997
+
1998
+ // src/commands/format/index.ts
1999
+ import { spawnSync as spawnSync9 } from "child_process";
2000
+ import { existsSync as existsSync6 } from "fs";
2001
+ import path10 from "pathe";
2002
+ function shouldUseShell2() {
2003
+ return process.platform === "win32";
2004
+ }
2005
+ function isAvailable(cmd) {
2006
+ const r = spawnSync9(cmd, ["--version"], { stdio: "ignore", shell: shouldUseShell2() });
2007
+ return r.error == null;
2008
+ }
2009
+ function exec(cmd, args, cwd) {
2010
+ const result = spawnSync9(cmd, args, { cwd, stdio: "inherit", shell: shouldUseShell2() });
2011
+ if (result.error) {
2012
+ process.stderr.write(`error: failed to run ${cmd}: ${result.error.message}
2013
+ `);
2014
+ return false;
2015
+ }
2016
+ return result.status === 0;
2017
+ }
2018
+ function hasLocalExecutable(dir, executable) {
2019
+ const localBin = path10.join(dir, "node_modules", ".bin", executable);
2020
+ return existsSync6(localBin);
2021
+ }
2022
+ function ensureNodeModules(dir, executable) {
2023
+ const nodeModulesDir = path10.join(dir, "node_modules");
2024
+ const hasDeps = existsSync6(nodeModulesDir);
2025
+ const hasExecutable = executable == null || hasLocalExecutable(dir, executable);
2026
+ if (hasDeps && hasExecutable) return true;
2027
+ process.stdout.write(
2028
+ hasDeps ? `${executable ?? "required dependency"} not found \u2014 running npm install\u2026
2029
+ ` : "node_modules not found \u2014 running npm install\u2026\n"
2030
+ );
2031
+ return exec("npm", ["install", "--prefix", dir, "--silent"], dir);
2032
+ }
2033
+ function ensureVenv(dir) {
2034
+ const venvRuff = path10.join(dir, ".venv", "bin", "ruff");
2035
+ if (existsSync6(venvRuff)) return true;
2036
+ process.stdout.write(".venv not found \u2014 running uv sync\u2026\n");
2037
+ return exec("uv", ["sync"], dir);
2038
+ }
2039
+ function isDockerServiceRunning(service, cwd) {
2040
+ const r = spawnSync9("docker", ["compose", "ps", "--status", "running", "-q", service], {
2041
+ stdio: "pipe",
2042
+ cwd
2043
+ });
2044
+ return r.status === 0 && r.stdout != null && r.stdout.toString().trim().length > 0;
2045
+ }
2046
+ var formatCommand = {
2047
+ description: "Format backend (ruff) and frontend (prettier) source files.",
2048
+ args: {
2049
+ check: {
2050
+ type: "boolean",
2051
+ description: "Check formatting without writing changes (exits 1 if any file would change).",
2052
+ default: false
2053
+ }
2054
+ },
2055
+ async run({ projectRoot, args }) {
2056
+ const check = Boolean(args.check);
2057
+ const backendDir = path10.join(projectRoot, "backend");
2058
+ const frontendDir = path10.join(projectRoot, "frontend");
2059
+ const e2eDir = path10.join(projectRoot, "e2e");
2060
+ const backendExists = existsSync6(backendDir);
2061
+ const backendContainerUp = backendExists && isDockerServiceRunning("backend", projectRoot);
2062
+ const missing = [];
2063
+ if (backendExists && !backendContainerUp && !isAvailable("uv"))
2064
+ missing.push("uv \u2192 https://docs.astral.sh/uv/getting-started/installation/");
2065
+ if ((existsSync6(frontendDir) || existsSync6(e2eDir)) && !isAvailable("pnpm"))
2066
+ missing.push("pnpm \u2192 https://pnpm.io/installation");
2067
+ if (missing.length > 0) {
2068
+ process.stderr.write(
2069
+ "error: the following tools are required but were not found on your PATH:\n\n"
2070
+ );
2071
+ for (const m of missing) process.stderr.write(` \u2022 ${m}
2072
+ `);
2073
+ process.stderr.write("\n");
2074
+ process.exit(1);
2075
+ }
2076
+ let ok = true;
2077
+ if (backendExists) {
2078
+ process.stdout.write(check ? "Checking backend formatting\u2026\n" : "Formatting backend\u2026\n");
2079
+ if (backendContainerUp) {
2080
+ ok = exec(
2081
+ "docker",
2082
+ [
2083
+ "compose",
2084
+ "exec",
2085
+ "backend",
2086
+ "uv",
2087
+ "run",
2088
+ "ruff",
2089
+ "format",
2090
+ ...check ? ["--check"] : [],
2091
+ "."
2092
+ ],
2093
+ projectRoot
2094
+ ) && ok;
2095
+ ok = exec(
2096
+ "docker",
2097
+ [
2098
+ "compose",
2099
+ "exec",
2100
+ "backend",
2101
+ "uv",
2102
+ "run",
2103
+ "ruff",
2104
+ "check",
2105
+ "--select",
2106
+ "I",
2107
+ ...check ? [] : ["--fix"],
2108
+ "."
2109
+ ],
2110
+ projectRoot
2111
+ ) && ok;
2112
+ } else {
2113
+ const venvReady = ensureVenv(backendDir);
2114
+ if (!venvReady) {
2115
+ process.stderr.write("error: uv sync failed in backend/\n");
2116
+ ok = false;
2117
+ }
2118
+ if (venvReady) {
2119
+ ok = exec("uv", ["run", "ruff", "format", ...check ? ["--check"] : [], "."], backendDir) && ok;
2120
+ ok = exec(
2121
+ "uv",
2122
+ ["run", "ruff", "check", "--select", "I", ...check ? [] : ["--fix"], "."],
2123
+ backendDir
2124
+ ) && ok;
2125
+ }
2126
+ }
2127
+ }
2128
+ if (existsSync6(frontendDir)) {
2129
+ process.stdout.write(check ? "Checking frontend formatting\u2026\n" : "Formatting frontend\u2026\n");
2130
+ const prettierBin = path10.join(frontendDir, "node_modules", ".bin", "prettier");
2131
+ if (!existsSync6(prettierBin)) {
2132
+ ensureNodeModules(frontendDir, "prettier");
2133
+ }
2134
+ if (!existsSync6(prettierBin)) {
2135
+ process.stderr.write(" prettier not found \u2014 run: cd frontend && npm install\n");
2136
+ ok = false;
2137
+ } else {
2138
+ ok = exec(prettierBin, [...check ? ["--check"] : ["--write"], "src/"], frontendDir) && ok;
2139
+ }
2140
+ }
2141
+ if (existsSync6(e2eDir)) {
2142
+ process.stdout.write(check ? "Checking e2e formatting\u2026\n" : "Formatting e2e\u2026\n");
2143
+ const prettierBin = path10.join(e2eDir, "node_modules", ".bin", "prettier");
2144
+ if (!existsSync6(prettierBin)) {
2145
+ ensureNodeModules(e2eDir, "prettier");
2146
+ }
2147
+ if (!existsSync6(prettierBin)) {
2148
+ process.stderr.write(" prettier not found \u2014 run: cd e2e && npm install\n");
2149
+ ok = false;
2150
+ } else {
2151
+ ok = exec(
2152
+ prettierBin,
2153
+ [
2154
+ ...check ? ["--check"] : ["--write"],
2155
+ "**/*.{ts,json}",
2156
+ "--ignore-path",
2157
+ ".prettierignore"
2158
+ ],
2159
+ e2eDir
2160
+ ) && ok;
2161
+ }
2162
+ }
2163
+ if (!ok) process.exit(1);
2164
+ }
2165
+ };
2166
+
2167
+ // src/commands/lint/index.ts
2168
+ import { defineLintCommand } from "@cubocicloide/dude";
2169
+ var lintCommand = defineLintCommand();
2170
+
2171
+ // src/commands/logs/index.ts
2172
+ var logsCommand = {
2173
+ description: "Follow service logs (docker compose logs -f [service]).",
2174
+ args: {
2175
+ service: {
2176
+ type: "string",
2177
+ description: "Service name (omit to follow all services).",
2178
+ required: false
2179
+ }
2180
+ },
2181
+ async run({ args }) {
2182
+ const svc = typeof args.service === "string" && args.service ? args.service : null;
2183
+ dc(svc ? ["logs", "-f", svc] : ["logs", "-f"]);
2184
+ }
2185
+ };
2186
+
2187
+ // src/commands/review/index.ts
2188
+ import { spawnSync as spawnSync10 } from "child_process";
2189
+ import { existsSync as existsSync7 } from "fs";
2190
+ import path11 from "pathe";
2191
+ import { runLint, formatDiagnostic } from "@cubocicloide/dude";
2192
+ function shouldUseShell3() {
2193
+ return process.platform === "win32";
2194
+ }
2195
+ function isAvailable2(cmd) {
2196
+ const r = spawnSync10(cmd, ["--version"], { stdio: "ignore", shell: shouldUseShell3() });
2197
+ return r.error == null;
2198
+ }
2199
+ function exec2(cmd, args, cwd) {
2200
+ const r = spawnSync10(cmd, args, { cwd, stdio: "inherit", shell: shouldUseShell3() });
2201
+ if (r.error) {
2202
+ process.stderr.write(`error: failed to run ${cmd}: ${r.error.message}
2203
+ `);
2204
+ return false;
2205
+ }
2206
+ return r.status === 0;
2207
+ }
2208
+ function section(title) {
2209
+ const isTTY = process.stdout.isTTY;
2210
+ const line = "\u2500".repeat(Math.max(0, 52 - title.length));
2211
+ const header = `\u2500\u2500 ${title} ${line}`;
2212
+ process.stdout.write(isTTY ? `
2213
+ \x1B[1m${header}\x1B[0m
2214
+ ` : `
2215
+ ${header}
2216
+ `);
2217
+ }
2218
+ var reviewCommand2 = {
2219
+ description: "Run all checks: custom lint, ESLint, and API contract review.",
2220
+ async run({ projectRoot, stackRoot }) {
2221
+ const frontendDir = path11.join(projectRoot, "frontend");
2222
+ const e2eDir = path11.join(projectRoot, "e2e");
2223
+ const isTTY = process.stdout.isTTY;
2224
+ let ok = true;
2225
+ const missing = [];
2226
+ if ((existsSync7(frontendDir) || existsSync7(e2eDir)) && !isAvailable2("pnpm"))
2227
+ missing.push("pnpm \u2192 https://pnpm.io/installation");
2228
+ if (missing.length > 0) {
2229
+ process.stderr.write("error: required tools not found on your PATH:\n\n");
2230
+ for (const m of missing) process.stderr.write(` \u2022 ${m}
2231
+ `);
2232
+ process.stderr.write("\n");
2233
+ process.exit(1);
2234
+ }
2235
+ section("dude lint");
2236
+ const { diagnostics, errorCount } = await runLint(projectRoot, stackRoot);
2237
+ if (diagnostics.length === 0) {
2238
+ process.stdout.write("No issues found.\n");
2239
+ } else {
2240
+ const colorize = (s, severity) => isTTY ? severity === "error" ? `\x1B[31m${s}\x1B[0m` : `\x1B[33m${s}\x1B[0m` : s;
2241
+ for (const d of diagnostics) {
2242
+ process.stdout.write(colorize(formatDiagnostic(d), d.severity) + "\n");
2243
+ }
2244
+ }
2245
+ ok = errorCount === 0 && ok;
2246
+ if (existsSync7(frontendDir)) {
2247
+ section("eslint");
2248
+ const eslintBin = path11.join(frontendDir, "node_modules", ".bin", "eslint");
2249
+ if (!existsSync7(eslintBin)) {
2250
+ process.stderr.write(" eslint not found \u2014 run: cd frontend && pnpm install\n");
2251
+ ok = false;
2252
+ } else {
2253
+ ok = exec2(eslintBin, ["src/"], frontendDir) && ok;
2254
+ }
2255
+ }
2256
+ if (existsSync7(e2eDir)) {
2257
+ section("eslint (e2e)");
2258
+ const eslintBin = path11.join(e2eDir, "node_modules", ".bin", "eslint");
2259
+ if (!existsSync7(eslintBin)) {
2260
+ process.stderr.write(" eslint not found \u2014 run: cd e2e && pnpm install\n");
2261
+ ok = false;
2262
+ } else {
2263
+ ok = exec2(eslintBin, ["."], e2eDir) && ok;
2264
+ }
2265
+ }
2266
+ section("api review");
2267
+ ok = exec2("dude", ["api", "review"], projectRoot) && ok;
2268
+ process.stdout.write("\n");
2269
+ if (ok) {
2270
+ process.stdout.write(isTTY ? "\x1B[32mAll checks passed.\x1B[0m\n" : "All checks passed.\n");
2271
+ } else {
2272
+ process.stderr.write(isTTY ? "\x1B[31mReview failed.\x1B[0m\n" : "Review failed.\n");
2273
+ process.exit(1);
2274
+ }
2275
+ }
2276
+ };
2277
+
2278
+ // src/commands/security/index.ts
2279
+ import { spawnSync as spawnSync11 } from "child_process";
2280
+ import { cpSync as cpSync2, existsSync as existsSync9, mkdirSync as mkdirSync3, readFileSync as readFileSync9, rmSync, writeFileSync as writeFileSync7 } from "fs";
2281
+ import path14 from "pathe";
2282
+
2283
+ // src/commands/security/models.ts
2284
+ import { createHash as createHash2 } from "crypto";
2285
+ var SEV_LABEL = {
2286
+ [0 /* UNKNOWN */]: "UNKNOWN",
2287
+ [1 /* INFO */]: "INFO",
2288
+ [2 /* LOW */]: "LOW",
2289
+ [3 /* MEDIUM */]: "MEDIUM",
2290
+ [4 /* HIGH */]: "HIGH",
2291
+ [5 /* CRITICAL */]: "CRITICAL"
2292
+ };
2293
+ function fingerprint(f) {
2294
+ const raw = [f.tool, f.ruleId, f.file, f.title.trim().toLowerCase()].join("|");
2295
+ return createHash2("sha256").update(raw, "utf8").digest("hex").slice(0, 16);
2296
+ }
2297
+ function findingToRecord(f) {
2298
+ return {
2299
+ tool: f.tool,
2300
+ rule_id: f.ruleId,
2301
+ severity: SEV_LABEL[f.severity],
2302
+ title: f.title,
2303
+ message: f.message,
2304
+ file: f.file,
2305
+ line: f.line,
2306
+ component: f.component,
2307
+ extra: f.extra,
2308
+ fingerprint: fingerprint(f)
2309
+ };
2310
+ }
2311
+
2312
+ // src/commands/security/baseline.ts
2313
+ import { existsSync as existsSync8, readFileSync as readFileSync8, writeFileSync as writeFileSync6, mkdirSync as mkdirSync2 } from "fs";
2314
+ import path12 from "pathe";
2315
+ var Baseline = class _Baseline {
2316
+ constructor(entries = /* @__PURE__ */ new Map()) {
2317
+ this.entries = entries;
2318
+ }
2319
+ entries;
2320
+ static load(filePath) {
2321
+ if (!existsSync8(filePath)) return new _Baseline();
2322
+ const raw = readFileSync8(filePath, "utf8") || "{}";
2323
+ const data = JSON.parse(raw);
2324
+ const entries = /* @__PURE__ */ new Map();
2325
+ for (const [fp, row] of Object.entries(data.entries ?? {})) {
2326
+ entries.set(fp, {
2327
+ fingerprint: fp,
2328
+ tool: row["tool"] ?? "",
2329
+ ruleId: row["rule_id"] ?? "",
2330
+ severity: row["severity"] ?? "",
2331
+ file: row["file"] ?? "",
2332
+ title: row["title"] ?? "",
2333
+ firstSeen: row["first_seen"] ?? "",
2334
+ notes: row["notes"] ?? ""
2335
+ });
2336
+ }
2337
+ return new _Baseline(entries);
2338
+ }
2339
+ save(filePath) {
2340
+ mkdirSync2(path12.dirname(filePath), { recursive: true });
2341
+ const sorted = [...this.entries.entries()].sort(([a], [b]) => a.localeCompare(b));
2342
+ const payload = {
2343
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
2344
+ entries: Object.fromEntries(
2345
+ sorted.map(([fp, e]) => [
2346
+ fp,
2347
+ {
2348
+ tool: e.tool,
2349
+ rule_id: e.ruleId,
2350
+ severity: e.severity,
2351
+ file: e.file,
2352
+ title: e.title,
2353
+ first_seen: e.firstSeen,
2354
+ notes: e.notes
2355
+ }
2356
+ ])
2357
+ )
2358
+ };
2359
+ writeFileSync6(filePath, JSON.stringify(payload, null, 2) + "\n");
2360
+ }
2361
+ updateFrom(findings) {
2362
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2363
+ for (const f of findings) {
2364
+ const fp = fingerprint(f);
2365
+ if (this.entries.has(fp)) continue;
2366
+ this.entries.set(fp, {
2367
+ fingerprint: fp,
2368
+ tool: f.tool,
2369
+ ruleId: f.ruleId,
2370
+ severity: SEV_LABEL[f.severity],
2371
+ file: f.file,
2372
+ title: f.title,
2373
+ firstSeen: now,
2374
+ notes: ""
2375
+ });
2376
+ }
2377
+ }
2378
+ classify(findings) {
2379
+ const currentFps = new Set(findings.map(fingerprint));
2380
+ const newFindings = findings.filter((f) => !this.entries.has(fingerprint(f)));
2381
+ const knownFindings = findings.filter((f) => this.entries.has(fingerprint(f)));
2382
+ const resolved = [...this.entries.keys()].filter((fp) => !currentFps.has(fp)).sort();
2383
+ return { newFindings, knownFindings, resolved };
2384
+ }
2385
+ };
2386
+
2387
+ // src/commands/security/adapters.ts
2388
+ import path13 from "pathe";
2389
+ function reportInContainer(projectRoot, runDir, name) {
2390
+ return `/src/${path13.relative(projectRoot, path13.join(runDir, `${name}.json`))}`;
2391
+ }
2392
+ var BANDIT_SEV = {
2393
+ UNDEFINED: 0 /* UNKNOWN */,
2394
+ LOW: 2 /* LOW */,
2395
+ MEDIUM: 3 /* MEDIUM */,
2396
+ HIGH: 4 /* HIGH */
2397
+ };
2398
+ function banditComponent(filePath) {
2399
+ return filePath.startsWith("backend/") ? "backend" : "repo";
2400
+ }
2401
+ var banditAdapter = {
2402
+ name: "bandit",
2403
+ buildCommand(projectRoot, runDir, opts) {
2404
+ const report = reportInContainer(projectRoot, runDir, "bandit");
2405
+ const banditCmd = `pip install --quiet --disable-pip-version-check bandit[toml]==1.7.9 && bandit -r backend -f json -o ${report} --exclude 'backend/tests'`;
2406
+ return [
2407
+ "docker",
2408
+ "run",
2409
+ "--rm",
2410
+ "-v",
2411
+ `${projectRoot}:/src`,
2412
+ "-v",
2413
+ `${opts.cachePrefix}-pip-cache:/root/.cache/pip`,
2414
+ "-w",
2415
+ "/src",
2416
+ "python:3.12-slim",
2417
+ "sh",
2418
+ "-c",
2419
+ banditCmd
2420
+ ];
2421
+ },
2422
+ parse(data) {
2423
+ if (typeof data !== "object" || data === null) return [];
2424
+ const results = data["results"];
2425
+ if (!Array.isArray(results)) return [];
2426
+ const findings = [];
2427
+ for (const item of results) {
2428
+ if (typeof item !== "object" || item === null) continue;
2429
+ const r = item;
2430
+ const filePath = String(r["filename"] ?? "").replace(/^\.\//, "");
2431
+ const sevKey = String(r["issue_severity"] ?? "").toUpperCase();
2432
+ const ruleId = String(r["test_id"] ?? "BANDIT");
2433
+ const cweObj = r["issue_cwe"];
2434
+ findings.push({
2435
+ tool: "bandit",
2436
+ ruleId,
2437
+ severity: BANDIT_SEV[sevKey] ?? 0 /* UNKNOWN */,
2438
+ title: String(r["test_name"] ?? ruleId),
2439
+ message: String(r["issue_text"] ?? ""),
2440
+ file: filePath,
2441
+ line: Number(r["line_number"] ?? 0) || 0,
2442
+ component: banditComponent(filePath),
2443
+ extra: {
2444
+ confidence: String(r["issue_confidence"] ?? ""),
2445
+ cwe: String(cweObj?.["id"] ?? ""),
2446
+ more_info: String(r["more_info"] ?? "")
2447
+ }
2448
+ });
2449
+ }
2450
+ return findings;
2451
+ }
2452
+ };
2453
+ var SEMGREP_IMAGE = "returntocorp/semgrep:1.86.0";
2454
+ var SEMGREP_CONFIGS = [
2455
+ "p/security-audit",
2456
+ "p/python",
2457
+ "p/django",
2458
+ "p/javascript",
2459
+ "p/typescript",
2460
+ "p/react",
2461
+ "p/dockerfile"
2462
+ ];
2463
+ var SEMGREP_SEV = {
2464
+ INFO: 1 /* INFO */,
2465
+ WARNING: 3 /* MEDIUM */,
2466
+ ERROR: 4 /* HIGH */
2467
+ };
2468
+ function semgrepComponent(filePath) {
2469
+ if (filePath.startsWith("backend/")) return "backend";
2470
+ if (filePath.startsWith("frontend/")) return "frontend";
2471
+ if (filePath.endsWith("Dockerfile") || filePath.includes("docker-compose")) return "docker";
2472
+ return "repo";
2473
+ }
2474
+ var semgrepAdapter = {
2475
+ name: "semgrep",
2476
+ buildCommand(projectRoot, runDir, _opts) {
2477
+ const report = reportInContainer(projectRoot, runDir, "semgrep");
2478
+ const cmd = [
2479
+ "docker",
2480
+ "run",
2481
+ "--rm",
2482
+ "-v",
2483
+ `${projectRoot}:/src`,
2484
+ "-w",
2485
+ "/src",
2486
+ SEMGREP_IMAGE,
2487
+ "semgrep",
2488
+ "scan",
2489
+ "--json",
2490
+ "--output",
2491
+ report,
2492
+ "--error",
2493
+ "--exclude",
2494
+ "node_modules",
2495
+ "--exclude",
2496
+ "staticfiles",
2497
+ "--exclude",
2498
+ "private",
2499
+ "--exclude",
2500
+ "e2e/reports",
2501
+ "--exclude",
2502
+ ".venv",
2503
+ "--exclude",
2504
+ "migrations"
2505
+ ];
2506
+ for (const cfg of SEMGREP_CONFIGS) {
2507
+ cmd.push("--config", cfg);
2508
+ }
2509
+ cmd.push("backend", "frontend/src");
2510
+ return cmd;
2511
+ },
2512
+ parse(data) {
2513
+ if (typeof data !== "object" || data === null) return [];
2514
+ const results = data["results"];
2515
+ if (!Array.isArray(results)) return [];
2516
+ const findings = [];
2517
+ for (const item of results) {
2518
+ if (typeof item !== "object" || item === null) continue;
2519
+ const r = item;
2520
+ const extra = r["extra"] ?? {};
2521
+ const metadata = extra["metadata"] ?? {};
2522
+ const rawSev = String(extra["severity"] ?? "").toUpperCase();
2523
+ const filePath = String(r["path"] ?? "");
2524
+ const checkId = String(r["check_id"] ?? "SEMGREP");
2525
+ const shortlink = String(metadata["shortlink"] ?? "");
2526
+ const title = (shortlink ? shortlink.split("/").at(-1) ?? "" : "") || checkId;
2527
+ const cwe = metadata["cwe"];
2528
+ const owasp = metadata["owasp"];
2529
+ const start = r["start"];
2530
+ findings.push({
2531
+ tool: "semgrep",
2532
+ ruleId: checkId,
2533
+ severity: SEMGREP_SEV[rawSev] ?? 0 /* UNKNOWN */,
2534
+ title,
2535
+ message: String(extra["message"] ?? "").trim(),
2536
+ file: filePath,
2537
+ line: Number(start?.["line"] ?? 0) || 0,
2538
+ component: semgrepComponent(filePath),
2539
+ extra: {
2540
+ cwe: Array.isArray(cwe) ? cwe.join(",") : "",
2541
+ owasp: Array.isArray(owasp) ? owasp.join(",") : "",
2542
+ category: String(metadata["category"] ?? "")
2543
+ }
2544
+ });
2545
+ }
2546
+ return findings;
2547
+ }
2548
+ };
2549
+ var TRIVY_IMAGE = "aquasec/trivy:0.52.2";
2550
+ var TRIVY_SEV = {
2551
+ UNKNOWN: 0 /* UNKNOWN */,
2552
+ LOW: 2 /* LOW */,
2553
+ MEDIUM: 3 /* MEDIUM */,
2554
+ HIGH: 4 /* HIGH */,
2555
+ CRITICAL: 5 /* CRITICAL */
2556
+ };
2557
+ function trivyComponent(filePath) {
2558
+ if (filePath.startsWith("backend/")) return "backend";
2559
+ if (filePath.startsWith("frontend/")) return "frontend";
2560
+ if (filePath.endsWith("Dockerfile") || filePath.includes("docker-compose")) return "docker";
2561
+ return "deps";
2562
+ }
2563
+ var trivyFsAdapter = {
2564
+ name: "trivy-fs",
2565
+ buildCommand(projectRoot, runDir, opts) {
2566
+ const report = reportInContainer(projectRoot, runDir, "trivy-fs");
2567
+ return [
2568
+ "docker",
2569
+ "run",
2570
+ "--rm",
2571
+ "-v",
2572
+ `${projectRoot}:/src`,
2573
+ "-v",
2574
+ `${opts.cachePrefix}-trivy-cache:/root/.cache/`,
2575
+ "-w",
2576
+ "/src",
2577
+ TRIVY_IMAGE,
2578
+ "fs",
2579
+ "--scanners",
2580
+ "vuln,misconfig,secret",
2581
+ "--format",
2582
+ "json",
2583
+ "--output",
2584
+ report,
2585
+ "--skip-dirs",
2586
+ "node_modules,private,staticfiles,e2e/reports,.venv",
2587
+ "."
2588
+ ];
2589
+ },
2590
+ parse(data) {
2591
+ if (typeof data !== "object" || data === null) return [];
2592
+ const results = data["Results"];
2593
+ if (!Array.isArray(results)) return [];
2594
+ const findings = [];
2595
+ for (const item of results) {
2596
+ if (typeof item !== "object" || item === null) continue;
2597
+ const r = item;
2598
+ const target = String(r["Target"] ?? "");
2599
+ for (const v of Array.isArray(r["Vulnerabilities"]) ? r["Vulnerabilities"] : []) {
2600
+ if (typeof v !== "object" || v === null) continue;
2601
+ const vr = v;
2602
+ const ruleId = String(vr["VulnerabilityID"] ?? "CVE-UNKNOWN");
2603
+ const pkg = String(vr["PkgName"] ?? "");
2604
+ const installed = String(vr["InstalledVersion"] ?? "");
2605
+ findings.push({
2606
+ tool: "trivy-fs",
2607
+ ruleId,
2608
+ severity: TRIVY_SEV[String(vr["Severity"] ?? "").toUpperCase()] ?? 0 /* UNKNOWN */,
2609
+ title: `${ruleId} in ${pkg} ${installed}`.trim(),
2610
+ message: String(vr["Title"] ?? vr["Description"] ?? "").trim(),
2611
+ file: target,
2612
+ line: 0,
2613
+ component: trivyComponent(target),
2614
+ extra: {
2615
+ package: pkg,
2616
+ installed_version: installed,
2617
+ fixed_version: String(vr["FixedVersion"] ?? ""),
2618
+ primary_url: String(vr["PrimaryURL"] ?? "")
2619
+ }
2620
+ });
2621
+ }
2622
+ for (const m of Array.isArray(r["Misconfigurations"]) ? r["Misconfigurations"] : []) {
2623
+ if (typeof m !== "object" || m === null) continue;
2624
+ const mr = m;
2625
+ const cause = mr["CauseMetadata"] ?? {};
2626
+ const ruleId = String(mr["ID"] ?? "MISCONFIG");
2627
+ findings.push({
2628
+ tool: "trivy-fs",
2629
+ ruleId,
2630
+ severity: TRIVY_SEV[String(mr["Severity"] ?? "").toUpperCase()] ?? 0 /* UNKNOWN */,
2631
+ title: String(mr["Title"] ?? ruleId),
2632
+ message: String(mr["Description"] ?? "").trim(),
2633
+ file: target,
2634
+ line: Number(cause["StartLine"] ?? 0) || 0,
2635
+ component: trivyComponent(target),
2636
+ extra: {
2637
+ resolution: String(mr["Resolution"] ?? ""),
2638
+ primary_url: String(mr["PrimaryURL"] ?? ""),
2639
+ service: String(mr["Type"] ?? "")
2640
+ }
2641
+ });
2642
+ }
2643
+ for (const s of Array.isArray(r["Secrets"]) ? r["Secrets"] : []) {
2644
+ if (typeof s !== "object" || s === null) continue;
2645
+ const sr = s;
2646
+ const ruleId = String(sr["RuleID"] ?? "SECRET");
2647
+ findings.push({
2648
+ tool: "trivy-fs",
2649
+ ruleId,
2650
+ severity: TRIVY_SEV[String(sr["Severity"] ?? "").toUpperCase()] ?? 4 /* HIGH */,
2651
+ title: String(sr["Title"] ?? ruleId),
2652
+ message: String(sr["Match"] ?? "").trim(),
2653
+ file: target,
2654
+ line: Number(sr["StartLine"] ?? 0) || 0,
2655
+ component: trivyComponent(target),
2656
+ extra: { category: String(sr["Category"] ?? "") }
2657
+ });
2658
+ }
2659
+ }
2660
+ return findings;
2661
+ }
2662
+ };
2663
+ var trivyImageAdapter = {
2664
+ name: "trivy-image",
2665
+ buildCommand(projectRoot, runDir, opts) {
2666
+ const report = reportInContainer(projectRoot, runDir, "trivy-image");
2667
+ const targetImage = opts.targetImage ?? process.env["TRIVY_TARGET_IMAGE"] ?? `${opts.cachePrefix}-web:latest`;
2668
+ return [
2669
+ "docker",
2670
+ "run",
2671
+ "--rm",
2672
+ "-v",
2673
+ "/var/run/docker.sock:/var/run/docker.sock",
2674
+ "-v",
2675
+ `${projectRoot}:/src`,
2676
+ "-v",
2677
+ `${opts.cachePrefix}-trivy-cache:/root/.cache/`,
2678
+ TRIVY_IMAGE,
2679
+ "image",
2680
+ "--format",
2681
+ "json",
2682
+ "--output",
2683
+ report,
2684
+ "--severity",
2685
+ "MEDIUM,HIGH,CRITICAL",
2686
+ targetImage
2687
+ ];
2688
+ },
2689
+ parse(data) {
2690
+ if (typeof data !== "object" || data === null) return [];
2691
+ const results = data["Results"];
2692
+ if (!Array.isArray(results)) return [];
2693
+ const findings = [];
2694
+ for (const item of results) {
2695
+ if (typeof item !== "object" || item === null) continue;
2696
+ const r = item;
2697
+ const target = String(r["Target"] ?? "");
2698
+ for (const v of Array.isArray(r["Vulnerabilities"]) ? r["Vulnerabilities"] : []) {
2699
+ if (typeof v !== "object" || v === null) continue;
2700
+ const vr = v;
2701
+ const ruleId = String(vr["VulnerabilityID"] ?? "CVE-UNKNOWN");
2702
+ const pkg = String(vr["PkgName"] ?? "");
2703
+ const installed = String(vr["InstalledVersion"] ?? "");
2704
+ findings.push({
2705
+ tool: "trivy-image",
2706
+ ruleId,
2707
+ severity: TRIVY_SEV[String(vr["Severity"] ?? "").toUpperCase()] ?? 0 /* UNKNOWN */,
2708
+ title: `${ruleId} in ${pkg} ${installed}`.trim(),
2709
+ message: String(vr["Title"] ?? vr["Description"] ?? "").trim(),
2710
+ file: target,
2711
+ line: 0,
2712
+ component: trivyComponent(target),
2713
+ extra: {
2714
+ package: pkg,
2715
+ installed_version: installed,
2716
+ fixed_version: String(vr["FixedVersion"] ?? ""),
2717
+ primary_url: String(vr["PrimaryURL"] ?? "")
2718
+ }
2719
+ });
2720
+ }
2721
+ }
2722
+ return findings;
2723
+ }
2724
+ };
2725
+ var ALL_ADAPTERS = {
2726
+ bandit: banditAdapter,
2727
+ semgrep: semgrepAdapter,
2728
+ "trivy-fs": trivyFsAdapter,
2729
+ "trivy-image": trivyImageAdapter
2730
+ };
2731
+ var DEFAULT_ADAPTERS = ["bandit", "semgrep", "trivy-fs", "trivy-image"];
2732
+
2733
+ // src/commands/security/index.ts
2734
+ function section2(title) {
2735
+ const isTTY = process.stdout.isTTY;
2736
+ const line = "\u2500".repeat(Math.max(0, 52 - title.length));
2737
+ const header = `\u2500\u2500 ${title} ${line}`;
2738
+ process.stdout.write(isTTY ? `
2739
+ \x1B[1m${header}\x1B[0m
2740
+ ` : `
2741
+ ${header}
2742
+ `);
2743
+ }
2744
+ function parseAdapters(only) {
2745
+ if (!only) return [...DEFAULT_ADAPTERS];
2746
+ return only.split(",").map((s) => s.trim()).filter(Boolean);
2747
+ }
2748
+ function parseSeverityArg(value, fallback) {
2749
+ if (!value) return fallback;
2750
+ const map = {
2751
+ INFO: 1 /* INFO */,
2752
+ LOW: 2 /* LOW */,
2753
+ MEDIUM: 3 /* MEDIUM */,
2754
+ HIGH: 4 /* HIGH */,
2755
+ CRITICAL: 5 /* CRITICAL */
2756
+ };
2757
+ return map[value.trim().toUpperCase()] ?? fallback;
2758
+ }
2759
+ function ensureDocker() {
2760
+ const r = spawnSync11("docker", ["info"], { stdio: "ignore" });
2761
+ if (r.error != null || r.status !== 0) {
2762
+ process.stderr.write(
2763
+ "[security] docker is required but is not available or the daemon is not running.\n"
2764
+ );
2765
+ process.exit(2);
2766
+ }
2767
+ }
2768
+ var MAX_MESSAGE_LEN = 500;
2769
+ function truncate(text) {
2770
+ const cleaned = text.trim().replace(/\n/g, " ");
2771
+ return cleaned.length > MAX_MESSAGE_LEN ? cleaned.slice(0, MAX_MESSAGE_LEN - 1) + "\u2026" : cleaned;
2772
+ }
2773
+ function writeFindingsJson(findings, filePath) {
2774
+ mkdirSync3(path14.dirname(filePath), { recursive: true });
2775
+ const payload = {
2776
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
2777
+ count: findings.length,
2778
+ findings: findings.map(findingToRecord)
2779
+ };
2780
+ writeFileSync7(filePath, JSON.stringify(payload, null, 2) + "\n");
2781
+ }
2782
+ function writeMarkdownSummary(newFindings, knownFindings, resolved, filePath, minSeverity) {
2783
+ const lines = [];
2784
+ lines.push("# Security scan summary", "");
2785
+ lines.push(`_Generated: ${(/* @__PURE__ */ new Date()).toISOString()}_`, "");
2786
+ const sevOrder = [
2787
+ 5 /* CRITICAL */,
2788
+ 4 /* HIGH */,
2789
+ 3 /* MEDIUM */,
2790
+ 2 /* LOW */,
2791
+ 1 /* INFO */,
2792
+ 0 /* UNKNOWN */
2793
+ ];
2794
+ const buckets = {};
2795
+ for (const sev of sevOrder) buckets[sev] = { new: 0, known: 0 };
2796
+ for (const f of newFindings) (buckets[f.severity] ??= { new: 0, known: 0 }).new++;
2797
+ for (const f of knownFindings) (buckets[f.severity] ??= { new: 0, known: 0 }).known++;
2798
+ lines.push("| Severity | New | Known (baseline) |", "| --- | --- | --- |");
2799
+ for (const sev of sevOrder) {
2800
+ const b = buckets[sev] ?? { new: 0, known: 0 };
2801
+ if (sev === 0 /* UNKNOWN */ && b.new + b.known === 0) continue;
2802
+ lines.push(`| ${SEV_LABEL[sev]} | ${b.new} | ${b.known} |`);
2803
+ }
2804
+ lines.push(`| **Resolved** | ${resolved.length} | \u2014 |`, "");
2805
+ lines.push(
2806
+ "The table below lists **new findings** only (not present in the baseline). Run `dude security accept` to absorb triaged findings into the baseline.",
2807
+ ""
2808
+ );
2809
+ const actionable = newFindings.filter((f) => f.severity >= minSeverity).sort(
2810
+ (a, b) => b.severity - a.severity || a.component.localeCompare(b.component) || a.file.localeCompare(b.file)
2811
+ );
2812
+ if (actionable.length === 0) {
2813
+ lines.push(`No new findings at severity \u2265 ${SEV_LABEL[minSeverity]}.`);
2814
+ } else {
2815
+ lines.push(`## New findings (severity \u2265 ${SEV_LABEL[minSeverity]})`, "");
2816
+ const CTX_KEYS = [
2817
+ "package",
2818
+ "installed_version",
2819
+ "fixed_version",
2820
+ "cwe",
2821
+ "owasp",
2822
+ "primary_url"
2823
+ ];
2824
+ for (const f of actionable) {
2825
+ const loc = f.file && f.line ? `${f.file}:${f.line}` : f.file || "\u2014";
2826
+ lines.push(`### [${SEV_LABEL[f.severity]}] ${f.title}`);
2827
+ lines.push(`- **Tool**: ${f.tool} **Rule**: \`${f.ruleId}\` **Component**: ${f.component}`);
2828
+ lines.push(`- **Location**: ${loc}`);
2829
+ if (f.message) lines.push(`- **Message**: ${truncate(f.message)}`);
2830
+ for (const k of CTX_KEYS) {
2831
+ if (f.extra[k]) lines.push(`- **${k}**: ${f.extra[k]}`);
2832
+ }
2833
+ lines.push("");
2834
+ }
2835
+ }
2836
+ if (resolved.length > 0) {
2837
+ lines.push(
2838
+ "",
2839
+ `## Resolved since last baseline (${resolved.length})`,
2840
+ "",
2841
+ "The following baseline fingerprints are no longer produced by the current scan.",
2842
+ "Run `dude security accept` to prune them.",
2843
+ ""
2844
+ );
2845
+ for (const fp of resolved.slice(0, 50)) lines.push(`- \`${fp}\``);
2846
+ if (resolved.length > 50) lines.push(`- \u2026 and ${resolved.length - 50} more`);
2847
+ }
2848
+ mkdirSync3(path14.dirname(filePath), { recursive: true });
2849
+ writeFileSync7(filePath, lines.join("\n").trimEnd() + "\n");
2850
+ }
2851
+ function runScan(config) {
2852
+ ensureDocker();
2853
+ const now = /* @__PURE__ */ new Date();
2854
+ const pad = (n) => String(n).padStart(2, "0");
2855
+ const timestamp = `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}T${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}Z`;
2856
+ const runDir = path14.join(config.reportsRoot, timestamp);
2857
+ const latestDir = path14.join(config.reportsRoot, "latest");
2858
+ mkdirSync3(runDir, { recursive: true });
2859
+ const cachePrefix = path14.basename(config.projectRoot);
2860
+ const opts = { cachePrefix };
2861
+ const findings = [];
2862
+ for (const name of config.adapterNames) {
2863
+ const adapter = ALL_ADAPTERS[name];
2864
+ if (!adapter) {
2865
+ process.stderr.write(
2866
+ `[security] unknown adapter: ${name}. Available: ${Object.keys(ALL_ADAPTERS).join(", ")}
2867
+ `
2868
+ );
2869
+ continue;
2870
+ }
2871
+ const cmd = adapter.buildCommand(config.projectRoot, runDir, opts);
2872
+ const [bin, ...cmdArgs] = cmd;
2873
+ process.stderr.write(`[security] running ${name}: ${cmd.join(" ")}
2874
+ `);
2875
+ const result = spawnSync11(bin ?? "docker", cmdArgs, {
2876
+ cwd: config.projectRoot,
2877
+ stdio: ["ignore", "pipe", "pipe"]
2878
+ });
2879
+ const reportPath = path14.join(runDir, `${name}.json`);
2880
+ if (!existsSync9(reportPath)) {
2881
+ const stdout = result.stdout?.toString() ?? "";
2882
+ const stderr = result.stderr?.toString() ?? "";
2883
+ process.stderr.write(
2884
+ `[security] WARNING: ${name} produced no report (exit=${result.status ?? "null"}).
2885
+ stdout: ${stdout.slice(0, 400)}
2886
+ stderr: ${stderr.slice(0, 400)}
2887
+ `
2888
+ );
2889
+ continue;
2890
+ }
2891
+ try {
2892
+ const data = JSON.parse(readFileSync9(reportPath, "utf8") || "{}");
2893
+ findings.push(...adapter.parse(data));
2894
+ } catch (err) {
2895
+ process.stderr.write(`[security] ${name}: invalid JSON (${String(err)})
2896
+ `);
2897
+ }
2898
+ }
2899
+ const baseline = Baseline.load(config.baselinePath);
2900
+ const { newFindings, knownFindings, resolved } = baseline.classify(findings);
2901
+ writeFindingsJson(findings, path14.join(runDir, "findings.json"));
2902
+ writeFindingsJson(newFindings, path14.join(runDir, "findings.new.json"));
2903
+ writeMarkdownSummary(
2904
+ newFindings,
2905
+ knownFindings,
2906
+ resolved,
2907
+ path14.join(runDir, "summary.md"),
2908
+ config.minSeverity
2909
+ );
2910
+ if (existsSync9(latestDir)) rmSync(latestDir, { recursive: true, force: true });
2911
+ cpSync2(runDir, latestDir, { recursive: true });
2912
+ if (config.updateBaseline) {
2913
+ baseline.updateFrom(findings);
2914
+ for (const fp of resolved) baseline.entries.delete(fp);
2915
+ baseline.save(config.baselinePath);
2916
+ }
2917
+ const blockingCount = newFindings.filter((f) => f.severity >= config.failOn).length;
2918
+ return {
2919
+ findings,
2920
+ newFindings,
2921
+ knownFindings,
2922
+ resolved,
2923
+ runDir,
2924
+ latestDir,
2925
+ exitCode: blockingCount > 0 ? 1 : 0
2926
+ };
2927
+ }
2928
+ var ADAPTER_CHOICES = Object.keys(ALL_ADAPTERS).join(", ");
2929
+ var SEV_CHOICES = "INFO, LOW, MEDIUM, HIGH, CRITICAL";
2930
+ var securityScanCommand = {
2931
+ description: "Run SAST scanners (Bandit, Semgrep, Trivy FS, Trivy Image) and produce a findings summary.",
2932
+ args: {
2933
+ only: {
2934
+ type: "string",
2935
+ description: `Comma-separated subset of adapters to run (choices: ${ADAPTER_CHOICES}). Default: all.`
2936
+ },
2937
+ "min-severity": {
2938
+ type: "string",
2939
+ description: `Lowest severity shown in the Markdown summary (${SEV_CHOICES}). Default: MEDIUM.`,
2940
+ default: "MEDIUM"
2941
+ },
2942
+ "fail-on": {
2943
+ type: "string",
2944
+ description: `Exit non-zero when a new finding at this severity or above exists (${SEV_CHOICES}). Default: HIGH.`,
2945
+ default: "HIGH"
2946
+ },
2947
+ "update-baseline": {
2948
+ type: "boolean",
2949
+ description: "Absorb every current finding into the baseline.",
2950
+ default: false
2951
+ }
2952
+ },
2953
+ async run({ projectRoot, args }) {
2954
+ const reportsRoot = path14.join(projectRoot, "private", "sast-reports");
2955
+ const baselinePath = path14.join(projectRoot, "security", "baseline.json");
2956
+ section2("security scan");
2957
+ const result = runScan({
2958
+ projectRoot,
2959
+ reportsRoot,
2960
+ baselinePath,
2961
+ adapterNames: parseAdapters(args["only"]),
2962
+ minSeverity: parseSeverityArg(args["min-severity"], 3 /* MEDIUM */),
2963
+ failOn: parseSeverityArg(args["fail-on"], 4 /* HIGH */),
2964
+ updateBaseline: Boolean(args["update-baseline"])
2965
+ });
2966
+ process.stderr.write(
2967
+ `[security] done. run_dir=${result.runDir} total=${result.findings.length} new=${result.newFindings.length} known=${result.knownFindings.length} resolved=${result.resolved.length}
2968
+ `
2969
+ );
2970
+ const summaryPath = path14.join(result.latestDir, "summary.md");
2971
+ if (existsSync9(summaryPath)) {
2972
+ process.stdout.write(readFileSync9(summaryPath, "utf8"));
2973
+ }
2974
+ if (result.exitCode !== 0) process.exit(result.exitCode);
2975
+ }
2976
+ };
2977
+ var securityAcceptCommand = {
2978
+ description: "Re-scan and absorb all current findings into the baseline. Use after triaging to silence known findings on subsequent scans.",
2979
+ args: {
2980
+ only: {
2981
+ type: "string",
2982
+ description: `Comma-separated subset of adapters to run (choices: ${ADAPTER_CHOICES}). Default: all.`
2983
+ }
2984
+ },
2985
+ async run({ projectRoot, args }) {
2986
+ const reportsRoot = path14.join(projectRoot, "private", "sast-reports");
2987
+ const baselinePath = path14.join(projectRoot, "security", "baseline.json");
2988
+ section2("security accept");
2989
+ const result = runScan({
2990
+ projectRoot,
2991
+ reportsRoot,
2992
+ baselinePath,
2993
+ adapterNames: parseAdapters(args["only"]),
2994
+ minSeverity: 3 /* MEDIUM */,
2995
+ failOn: 4 /* HIGH */,
2996
+ updateBaseline: true
2997
+ });
2998
+ process.stderr.write(
2999
+ `[security] done. Baseline updated with ${result.findings.length} finding(s).
3000
+ `
3001
+ );
3002
+ process.stdout.write(`Baseline saved to ${baselinePath}.
3003
+ Review and commit the change.
3004
+ `);
3005
+ }
3006
+ };
3007
+ var securityVerifyCommand = {
3008
+ description: "Re-scan and check whether specific findings have been resolved. A finding is resolved when it was in the baseline but absent from the current scan.",
3009
+ args: {
3010
+ "rule-id": {
3011
+ type: "string",
3012
+ description: "Comma-separated rule identifiers to verify (e.g. B105,CVE-2026-33750). Omit to report on all resolved/unresolved baseline entries."
3013
+ },
3014
+ only: {
3015
+ type: "string",
3016
+ description: `Comma-separated subset of adapters to run (choices: ${ADAPTER_CHOICES}). Default: all.`
3017
+ },
3018
+ "remove-resolved": {
3019
+ type: "boolean",
3020
+ description: "Remove resolved findings from the baseline file after confirming the fix.",
3021
+ default: false
3022
+ }
3023
+ },
3024
+ async run({ projectRoot, args }) {
3025
+ const reportsRoot = path14.join(projectRoot, "private", "sast-reports");
3026
+ const baselinePath = path14.join(projectRoot, "security", "baseline.json");
3027
+ const isTTY = process.stdout.isTTY;
3028
+ section2("security verify");
3029
+ const result = runScan({
3030
+ projectRoot,
3031
+ reportsRoot,
3032
+ baselinePath,
3033
+ adapterNames: parseAdapters(args["only"]),
3034
+ minSeverity: 3 /* MEDIUM */,
3035
+ failOn: 4 /* HIGH */,
3036
+ updateBaseline: false
3037
+ });
3038
+ const baseline = Baseline.load(baselinePath);
3039
+ const { newFindings, knownFindings, resolved } = baseline.classify(result.findings);
3040
+ const ruleIdArg = args["rule-id"];
3041
+ const ruleIds = ruleIdArg ? ruleIdArg.split(",").map((s) => s.trim()).filter(Boolean) : [];
3042
+ function matches(candidate, ruleId) {
3043
+ return ruleId === candidate || candidate.includes(ruleId);
3044
+ }
3045
+ let allFixed = true;
3046
+ if (ruleIds.length === 0) {
3047
+ process.stdout.write(`
3048
+ Resolved fingerprints : ${resolved.length}
3049
+ `);
3050
+ process.stdout.write(`Still present (known) : ${knownFindings.length}
3051
+ `);
3052
+ process.stdout.write(`New (not in baseline) : ${newFindings.length}
3053
+ `);
3054
+ allFixed = resolved.length > 0 && knownFindings.length === 0;
3055
+ } else {
3056
+ for (const ruleId of ruleIds) {
3057
+ const ruleResolved = resolved.filter(
3058
+ (fp) => matches(baseline.entries.get(fp)?.ruleId ?? "", ruleId)
3059
+ );
3060
+ const ruleStillPresent = knownFindings.filter((f) => matches(f.ruleId, ruleId));
3061
+ const isFixed = ruleResolved.length > 0 && ruleStillPresent.length === 0;
3062
+ allFixed = allFixed && isFixed;
3063
+ const badge = isFixed ? isTTY ? "\x1B[32m\u2713 RESOLVED\x1B[0m" : "\u2713 RESOLVED" : isTTY ? "\x1B[31m\u2717 STILL PRESENT\x1B[0m" : "\u2717 STILL PRESENT";
3064
+ process.stdout.write(`
3065
+ [${ruleId}] ${badge}
3066
+ `);
3067
+ if (ruleResolved.length > 0) {
3068
+ process.stdout.write(` Resolved fingerprints: ${ruleResolved.join(", ")}
3069
+ `);
3070
+ }
3071
+ if (ruleStillPresent.length > 0) {
3072
+ process.stdout.write(` Still present (${ruleStillPresent.length} finding(s)):
3073
+ `);
3074
+ for (const f of ruleStillPresent) {
3075
+ const loc = f.file && f.line ? `${f.file}:${f.line}` : f.file || "\u2014";
3076
+ process.stdout.write(` - ${loc} \u2014 ${f.title}
3077
+ `);
3078
+ }
3079
+ }
3080
+ }
3081
+ }
3082
+ if (Boolean(args["remove-resolved"]) && resolved.length > 0) {
3083
+ const toRemove = ruleIds.length === 0 ? resolved : resolved.filter(
3084
+ (fp) => ruleIds.some((rid) => matches(baseline.entries.get(fp)?.ruleId ?? "", rid))
3085
+ );
3086
+ if (toRemove.length > 0) {
3087
+ const fresh = Baseline.load(baselinePath);
3088
+ for (const fp of toRemove) fresh.entries.delete(fp);
3089
+ fresh.save(baselinePath);
3090
+ process.stdout.write(
3091
+ `
3092
+ Baseline updated: ${toRemove.length} entry/entries removed from ${baselinePath}.
3093
+ Review and commit the change.
3094
+ `
3095
+ );
3096
+ }
3097
+ }
3098
+ if (!allFixed) process.exit(1);
3099
+ }
3100
+ };
3101
+
3102
+ // src/commands/shell/index.ts
3103
+ import { spawnSync as spawnSync12 } from "child_process";
3104
+ var shellCommand = {
3105
+ description: "Open an interactive shell in a service container.",
3106
+ args: {
3107
+ service: {
3108
+ type: "string",
3109
+ description: "Service name (e.g. backend, frontend).",
3110
+ required: true
3111
+ }
3112
+ },
3113
+ async run({ args }) {
3114
+ const svc = String(args.service);
3115
+ const bash = spawnSync12("docker", ["compose", "exec", svc, "/bin/bash"], { stdio: "inherit" });
3116
+ if (bash.status !== 0) {
3117
+ dc(["exec", svc, "/bin/sh"]);
3118
+ } else {
3119
+ process.exit(bash.status ?? 0);
3120
+ }
3121
+ }
3122
+ };
3123
+
3124
+ // src/commands/test/index.ts
3125
+ import { spawnSync as spawnSync13 } from "child_process";
3126
+ import { existsSync as existsSync10 } from "fs";
3127
+ import path15 from "pathe";
3128
+ function shouldUseShell4() {
3129
+ return process.platform === "win32";
3130
+ }
3131
+ function isAvailable3(cmd) {
3132
+ const r = spawnSync13(cmd, ["--version"], { stdio: "ignore", shell: shouldUseShell4() });
3133
+ return r.error == null;
3134
+ }
3135
+ function exec3(cmd, args, cwd, env) {
3136
+ const r = spawnSync13(cmd, args, {
3137
+ cwd,
3138
+ stdio: "inherit",
3139
+ env: { ...process.env, ...env },
3140
+ shell: shouldUseShell4()
3141
+ });
3142
+ if (r.error) {
3143
+ process.stderr.write(`error: failed to run ${cmd}: ${r.error.message}
3144
+ `);
3145
+ return false;
3146
+ }
3147
+ return r.status === 0;
3148
+ }
3149
+ function section3(title) {
3150
+ const isTTY = process.stdout.isTTY;
3151
+ const line = "\u2500".repeat(Math.max(0, 52 - title.length));
3152
+ const header = `\u2500\u2500 ${title} ${line}`;
3153
+ process.stdout.write(isTTY ? `
3154
+ \x1B[1m${header}\x1B[0m
3155
+ ` : `
3156
+ ${header}
3157
+ `);
3158
+ }
3159
+ var testCommand = {
3160
+ description: "Run tests: pytest for the backend and/or Playwright+Cucumber for e2e. When no filter flag is given all available suites are run.",
3161
+ args: {
3162
+ backend: {
3163
+ type: "boolean",
3164
+ description: "Run backend unit/integration tests (pytest).",
3165
+ default: false
3166
+ },
3167
+ e2e: {
3168
+ type: "boolean",
3169
+ description: "Run end-to-end tests (Playwright + Cucumber.js).",
3170
+ default: false
3171
+ },
3172
+ headed: {
3173
+ type: "boolean",
3174
+ description: "Run e2e tests in a visible browser window (sets HEADED=true).",
3175
+ default: false
3176
+ },
3177
+ report: {
3178
+ type: "boolean",
3179
+ description: "Generate HTML and JSON reports for e2e tests (written to e2e/reports/).",
3180
+ default: false
3181
+ }
3182
+ },
3183
+ async run({ projectRoot, args }) {
3184
+ const backendDir = path15.join(projectRoot, "backend");
3185
+ const e2eDir = path15.join(projectRoot, "e2e");
3186
+ const flagBackend = Boolean(args.backend);
3187
+ const flagE2e = Boolean(args.e2e);
3188
+ const headed = Boolean(args.headed);
3189
+ const report = Boolean(args.report);
3190
+ const runAll = !flagBackend && !flagE2e;
3191
+ const runBackend = flagBackend || runAll;
3192
+ const runE2e = flagE2e || runAll;
3193
+ const hasBackend = existsSync10(backendDir);
3194
+ const hasE2e = existsSync10(e2eDir);
3195
+ const missing = [];
3196
+ if (runBackend && hasBackend && !isAvailable3("uv"))
3197
+ missing.push("uv \u2192 https://docs.astral.sh/uv/getting-started/installation/");
3198
+ if (runE2e && hasE2e && !isAvailable3("pnpm"))
3199
+ missing.push("pnpm \u2192 https://pnpm.io/installation");
3200
+ if (missing.length > 0) {
3201
+ process.stderr.write(
3202
+ "error: the following tools are required but were not found on your PATH:\n\n"
3203
+ );
3204
+ for (const m of missing) process.stderr.write(` \u2022 ${m}
3205
+ `);
3206
+ process.stderr.write("\n");
3207
+ process.exit(1);
3208
+ }
3209
+ if (runBackend && !hasBackend)
3210
+ process.stderr.write(
3211
+ "warn: --backend requested but backend/ directory not found, skipping.\n"
3212
+ );
3213
+ if (runE2e && !hasE2e)
3214
+ process.stderr.write("warn: --e2e requested but e2e/ directory not found, skipping.\n");
3215
+ let ok = true;
3216
+ if (runBackend && hasBackend) {
3217
+ section3("pytest");
3218
+ ok = exec3("uv", ["run", "pytest"], backendDir) && ok;
3219
+ }
3220
+ if (runE2e && hasE2e) {
3221
+ const script = report ? "test:report" : "test";
3222
+ section3(`cucumber${headed ? " (headed)" : ""}${report ? " + report" : ""}`);
3223
+ const nmDir = path15.join(e2eDir, "node_modules");
3224
+ if (!existsSync10(nmDir)) {
3225
+ process.stdout.write("node_modules not found \u2014 running pnpm install\u2026\n");
3226
+ const installed = exec3("pnpm", ["install"], e2eDir);
3227
+ if (!installed) {
3228
+ process.stderr.write("error: pnpm install failed in e2e/\n");
3229
+ ok = false;
3230
+ }
3231
+ if (ok) {
3232
+ process.stdout.write("Installing Playwright browsers\u2026\n");
3233
+ const browsersInstalled = exec3("pnpm", ["exec", "playwright", "install"], e2eDir);
3234
+ if (!browsersInstalled) {
3235
+ process.stderr.write("error: playwright install failed in e2e/\n");
3236
+ ok = false;
3237
+ }
3238
+ }
3239
+ }
3240
+ if (ok) {
3241
+ ok = exec3("pnpm", ["run", script], e2eDir, headed ? { HEADED: "true" } : void 0) && ok;
3242
+ }
3243
+ }
3244
+ const isTTY = process.stdout.isTTY;
3245
+ process.stdout.write("\n");
3246
+ if (ok) {
3247
+ process.stdout.write(isTTY ? "\x1B[32mAll tests passed.\x1B[0m\n" : "All tests passed.\n");
3248
+ } else {
3249
+ process.stderr.write(isTTY ? "\x1B[31mTests failed.\x1B[0m\n" : "Tests failed.\n");
3250
+ process.exit(1);
3251
+ }
3252
+ }
3253
+ };
3254
+
3255
+ // src/commands/up/index.ts
3256
+ var upCommand = {
3257
+ description: "Start all services (docker compose up -d). Use --build to rebuild images.",
3258
+ args: {
3259
+ build: {
3260
+ type: "boolean",
3261
+ description: "Rebuild images before starting.",
3262
+ default: false
3263
+ }
3264
+ },
3265
+ async run({ args }) {
3266
+ dc(Boolean(args.build) ? ["up", "--build"] : ["up", "-d"]);
3267
+ }
3268
+ };
3269
+
3270
+ // src/index.ts
3271
+ var src_default = defineStack({
3272
+ name: "react-django",
3273
+ version: "0.1.0",
3274
+ minDudeVersion: "0.1.0",
3275
+ description: "React (Vite + TypeScript) frontend with a Django REST Framework backend.",
3276
+ variables: [
3277
+ {
3278
+ name: "projectName",
3279
+ type: "string",
3280
+ prompt: "Project name",
3281
+ pattern: "^[a-z][a-z0-9-]*$",
3282
+ default: "my-app"
3283
+ },
3284
+ {
3285
+ name: "database",
3286
+ type: "select",
3287
+ prompt: "Database (none = SQLite file, fine for dev)",
3288
+ choices: ["none", "postgres"],
3289
+ default: "none"
3290
+ },
3291
+ {
3292
+ name: "storage",
3293
+ type: "select",
3294
+ prompt: "File storage (s3 = S3-compatible object storage; MinIO locally)",
3295
+ choices: ["none", "s3"],
3296
+ default: "none"
3297
+ },
3298
+ {
3299
+ name: "celery",
3300
+ type: "boolean",
3301
+ prompt: "Add Celery worker?",
3302
+ default: false
3303
+ },
3304
+ {
3305
+ name: "celeryBeat",
3306
+ type: "boolean",
3307
+ prompt: "Add Celery Beat scheduler? (requires Celery \u2014 auto-enabled)",
3308
+ default: false
3309
+ },
3310
+ {
3311
+ name: "iac",
3312
+ type: "select",
3313
+ prompt: "Infrastructure-as-Code (Terraform, AWS ECS Fargate)",
3314
+ choices: ["none", "aws-ecs"],
3315
+ default: "none"
3316
+ }
3317
+ ],
3318
+ async scaffold(ctx) {
3319
+ const { answers, dest, stackRoot, dudeVersion, stackVersion } = ctx;
3320
+ const withPostgres = answers.database === "postgres";
3321
+ const withS3 = answers.storage === "s3";
3322
+ const withCeleryBeat = Boolean(answers.celeryBeat);
3323
+ const withCelery = Boolean(answers.celery) || withCeleryBeat;
3324
+ const withRedis = withCelery;
3325
+ const withIac = answers.iac === "aws-ecs";
3326
+ const data = {
3327
+ ...answers,
3328
+ withPostgres,
3329
+ withS3,
3330
+ withCelery,
3331
+ withCeleryBeat,
3332
+ withRedis,
3333
+ withIac,
3334
+ dudeVersion,
3335
+ stackVersion
3336
+ };
3337
+ const templates = path16.join(stackRoot, "templates");
3338
+ await renderTemplateTree({ src: path16.join(templates, "base"), dest, data });
3339
+ if (withPostgres) {
3340
+ await renderTemplateTree({ src: path16.join(templates, "postgres"), dest, data });
3341
+ }
3342
+ if (withS3) {
3343
+ await renderTemplateTree({ src: path16.join(templates, "s3"), dest, data });
3344
+ }
3345
+ if (withCelery) {
3346
+ await renderTemplateTree({ src: path16.join(templates, "celery"), dest, data });
3347
+ }
3348
+ if (withCeleryBeat) {
3349
+ await renderTemplateTree({ src: path16.join(templates, "celerybeat"), dest, data });
3350
+ }
3351
+ if (withIac) {
3352
+ await renderTemplateTree({ src: path16.join(templates, "aws-ecs"), dest, data });
3353
+ }
3354
+ const openapiYamlPath = path16.join(dest, "frontend", "src", "openapi", "utils", "openapi.yaml");
3355
+ if (existsSync11(openapiYamlPath)) {
3356
+ const spec = yaml2.parse(readFileSync10(openapiYamlPath, "utf8"));
3357
+ await generateClientFromSpec(spec, path16.join(dest, "frontend", "src", "openapi"), dest);
3358
+ }
3359
+ },
3360
+ hooks: {
3361
+ async postInit(ctx) {
3362
+ const name = String(ctx.answers.projectName ?? "your-project");
3363
+ const withS3 = ctx.answers.storage === "s3";
3364
+ const withCelery = Boolean(ctx.answers.celery) || Boolean(ctx.answers.celeryBeat);
3365
+ const withIac = ctx.answers.iac === "aws-ecs";
3366
+ ctx.logger.info("Project scaffolded. Next steps:");
3367
+ ctx.logger.info("");
3368
+ ctx.logger.info(" 1. Install the dude launcher once (globally), then provision the project:");
3369
+ ctx.logger.info(" npm install -g @cubocicloide/dude-launcher");
3370
+ ctx.logger.info(` cd ${name} && pnpm install`);
3371
+ ctx.logger.info(" From now on `dude <cmd>` runs this project\u2019s pinned CLI + stack.");
3372
+ ctx.logger.info("");
3373
+ ctx.logger.info(" 2. Start the stack (migrations run automatically on boot):");
3374
+ ctx.logger.info(" dude up --build");
3375
+ ctx.logger.info("");
3376
+ ctx.logger.info(" 3. Create an admin account for /admin/ (optional):");
3377
+ ctx.logger.info(" dude db superuser");
3378
+ ctx.logger.info("");
3379
+ if (withCelery) {
3380
+ ctx.logger.info(" Celery workers are started automatically by docker compose.");
3381
+ ctx.logger.info(" To monitor tasks, open http://localhost:5555 (Flower).");
3382
+ ctx.logger.info("");
3383
+ }
3384
+ ctx.logger.info(" Endpoints:");
3385
+ ctx.logger.info(" Frontend: http://localhost:5173");
3386
+ ctx.logger.info(" Backend: http://localhost:8000/api/health/");
3387
+ ctx.logger.info(" Users: http://localhost:8000/api/users/");
3388
+ ctx.logger.info(" API schema: http://localhost:8000/api/docs/ (Swagger UI)");
3389
+ ctx.logger.info(" Admin: http://localhost:8000/admin/");
3390
+ if (withS3) {
3391
+ ctx.logger.info(" Files: http://localhost:8000/api/files/");
3392
+ ctx.logger.info(" MinIO UI: http://localhost:9001 (minioadmin / minioadmin)");
3393
+ }
3394
+ if (withIac) {
3395
+ ctx.logger.info("");
3396
+ ctx.logger.info(" Deploy to AWS ECS Fargate (Terraform) \u2014 see iac/README.md:");
3397
+ ctx.logger.info(" dude iac login --env dev");
3398
+ ctx.logger.info(" dude iac bootstrap --state-bucket-prefix <your-org> --env dev --yes");
3399
+ ctx.logger.info(" dude iac init --env dev && dude iac apply --env dev");
3400
+ ctx.logger.info(" dude iac ship --env dev && dude iac migrate --env dev");
3401
+ }
3402
+ }
3403
+ },
3404
+ rules: [],
3405
+ commands: {
3406
+ up: upCommand,
3407
+ down: downCommand,
3408
+ logs: logsCommand,
3409
+ shell: shellCommand,
3410
+ lint: lintCommand,
3411
+ format: formatCommand,
3412
+ review: reviewCommand2,
3413
+ test: testCommand,
3414
+ docs: docsCommand,
3415
+ security: {
3416
+ scan: securityScanCommand,
3417
+ accept: securityAcceptCommand,
3418
+ verify: securityVerifyCommand
3419
+ },
3420
+ api: {
3421
+ sync: syncCommand,
3422
+ review: reviewCommand
3423
+ },
3424
+ db: {
3425
+ makemigration: makemigrationCommand,
3426
+ migrate: migrateCommand,
3427
+ rollback: rollbackCommand,
3428
+ superuser: superuserCommand
3429
+ },
3430
+ iac: iacCommands
3431
+ }
3432
+ });
3433
+ export {
3434
+ src_default as default
3435
+ };
3436
+ //# sourceMappingURL=index.js.map