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