@whil/guardrails 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +222 -2
- package/catalog-assets/claude-hooks/guardrails-check.sh +37 -0
- package/catalog-assets/eslint-guardrails/config.mjs +21 -0
- package/catalog-assets/eslint-rules/_rule-tester.mjs +21 -0
- package/catalog-assets/eslint-rules/cache-policy-constant.mjs +35 -0
- package/catalog-assets/eslint-rules/client-imports-server.mjs +26 -0
- package/catalog-assets/eslint-rules/effects-in-hooks.mjs +46 -0
- package/catalog-assets/eslint-rules/env-through-config.mjs +26 -0
- package/catalog-assets/eslint-rules/hook-body-order.mjs +169 -0
- package/catalog-assets/eslint-rules/import-boundaries.mjs +97 -0
- package/catalog-assets/eslint-rules/no-comments.mjs +35 -0
- package/catalog-assets/eslint-rules/no-default-export.mjs +20 -0
- package/catalog-assets/eslint-rules/no-delete.mjs +16 -0
- package/catalog-assets/eslint-rules/no-enum.mjs +14 -0
- package/catalog-assets/eslint-rules/no-heavy-inline-styles.mjs +20 -0
- package/catalog-assets/eslint-rules/no-let.mjs +14 -0
- package/catalog-assets/eslint-rules/no-logic-in-jsx.mjs +23 -0
- package/catalog-assets/eslint-rules/no-manual-memoization.mjs +45 -0
- package/catalog-assets/eslint-rules/no-member-assignment.mjs +28 -0
- package/catalog-assets/eslint-rules/no-module-cache.mjs +40 -0
- package/catalog-assets/eslint-rules/no-mutating-array-methods.mjs +85 -0
- package/catalog-assets/eslint-rules/no-process-exit.mjs +15 -0
- package/catalog-assets/eslint-rules/no-state-mutation.mjs +62 -0
- package/catalog-assets/eslint-rules/no-unnecessary-use-client.mjs +40 -0
- package/catalog-assets/eslint-rules/pure-components.mjs +48 -0
- package/catalog-assets/eslint-rules/query-key-constant.mjs +54 -0
- package/catalog-assets/eslint-rules/require-disable-reason.mjs +29 -0
- package/catalog-assets/eslint-rules/restrict-timers.mjs +35 -0
- package/catalog-assets/eslint-rules/rules-of-hooks.mjs +51 -0
- package/catalog-assets/eslint-rules/thin-api-routes.mjs +18 -0
- package/catalog-assets/eslint-rules/thin-routes.mjs +18 -0
- package/catalog-assets/eslint-rules/virtualized-lists.mjs +32 -0
- package/catalog-assets/githooks/commit-msg +13 -0
- package/catalog-assets/githooks/pre-commit +26 -0
- package/catalog-assets/scripts/check-exact-deps.mjs +26 -0
- package/dist/cli.js +57 -0
- package/dist/config/runtime.js +15 -0
- package/dist/core/app/analysis.js +74 -0
- package/dist/core/app/args.js +46 -0
- package/dist/core/app/catalog.js +20 -0
- package/dist/core/app/ci-plan.js +14 -0
- package/dist/core/app/claude.js +37 -0
- package/dist/core/app/commands/add-rule.js +32 -0
- package/dist/core/app/commands/agents-md.js +13 -0
- package/dist/core/app/commands/apply.js +74 -0
- package/dist/core/app/commands/audit.js +38 -0
- package/dist/core/app/commands/check.js +33 -0
- package/dist/core/app/commands/detect.js +16 -0
- package/dist/core/app/commands/init.js +127 -0
- package/dist/core/app/commands/learn.js +48 -0
- package/dist/core/app/commands/plan.js +40 -0
- package/dist/core/app/commands/pr-status.js +66 -0
- package/dist/core/app/commands/self-check.js +20 -0
- package/dist/core/app/git.js +75 -0
- package/dist/core/app/github.js +146 -0
- package/dist/core/app/hooks-script.js +27 -0
- package/dist/core/app/output.js +17 -0
- package/dist/core/app/run.js +32 -0
- package/dist/core/app/session.js +18 -0
- package/dist/core/app/timing.js +11 -0
- package/dist/core/domain/agents-md.js +104 -0
- package/dist/core/domain/audit-report.js +7 -0
- package/dist/core/domain/changes.js +8 -0
- package/dist/core/domain/check-report.js +23 -0
- package/dist/core/domain/claude-settings.js +42 -0
- package/dist/core/domain/constraint.js +7 -0
- package/dist/core/domain/diagnostics.js +3 -0
- package/dist/core/domain/errors.js +21 -0
- package/dist/core/domain/facts.js +18 -0
- package/dist/core/domain/init-report.js +28 -0
- package/dist/core/domain/json.js +43 -0
- package/dist/core/domain/learn.js +78 -0
- package/dist/core/domain/log-parse.js +99 -0
- package/dist/core/domain/pack-defaults.js +17 -0
- package/dist/core/domain/pack.js +1 -0
- package/dist/core/domain/perf.js +65 -0
- package/dist/core/domain/pr-comment.js +45 -0
- package/dist/core/domain/pr-loop.js +85 -0
- package/dist/core/domain/profile.js +25 -0
- package/dist/core/domain/protection.js +43 -0
- package/dist/core/domain/ratchet.js +40 -0
- package/dist/core/domain/registry.js +32 -0
- package/dist/core/domain/remote.js +4 -0
- package/dist/core/domain/result.js +25 -0
- package/dist/core/domain/thresholds.js +9 -0
- package/dist/core/domain/types.js +1 -0
- package/dist/core/domain/workflows.js +252 -0
- package/dist/core/infra/assets.js +7 -0
- package/dist/core/infra/backup.js +31 -0
- package/dist/core/infra/baseline.js +8 -0
- package/dist/core/infra/changes.js +17 -0
- package/dist/core/infra/exec.js +15 -0
- package/dist/core/infra/facts.js +61 -0
- package/dist/core/infra/fs.js +87 -0
- package/dist/core/infra/gh.js +32 -0
- package/dist/core/infra/hash.js +10 -0
- package/dist/core/infra/hooks.js +31 -0
- package/dist/core/infra/learn-sources.js +40 -0
- package/dist/core/infra/lock.js +102 -0
- package/dist/core/infra/pr.js +48 -0
- package/dist/core/infra/result-cache.js +49 -0
- package/dist/packs/index.js +6 -0
- package/dist/packs/js-ts/app/add-rule.js +116 -0
- package/dist/packs/js-ts/app/analysis.js +111 -0
- package/dist/packs/js-ts/app/bootstrap.js +16 -0
- package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
- package/dist/packs/js-ts/app/eslint-files.js +56 -0
- package/dist/packs/js-ts/app/fixes.js +3 -0
- package/dist/packs/js-ts/app/pr-rules.js +30 -0
- package/dist/packs/js-ts/app/project.js +87 -0
- package/dist/packs/js-ts/app/tests.js +63 -0
- package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
- package/dist/packs/js-ts/domain/ci.js +47 -0
- package/dist/packs/js-ts/domain/data.js +34 -0
- package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
- package/dist/packs/js-ts/domain/disables.js +11 -0
- package/dist/packs/js-ts/domain/eslint-output.js +46 -0
- package/dist/packs/js-ts/domain/eslint-state.js +80 -0
- package/dist/packs/js-ts/domain/hooks.js +49 -0
- package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
- package/dist/packs/js-ts/domain/pr-tests.js +27 -0
- package/dist/packs/js-ts/domain/profile-pure.js +51 -0
- package/dist/packs/js-ts/domain/profile.js +112 -0
- package/dist/packs/js-ts/domain/report.js +74 -0
- package/dist/packs/js-ts/domain/rule-templates.js +44 -0
- package/dist/packs/js-ts/domain/signals.js +14 -0
- package/dist/packs/js-ts/domain/testing.js +33 -0
- package/dist/packs/js-ts/domain/ts-options.js +16 -0
- package/dist/packs/js-ts/index.js +50 -0
- package/dist/packs/js-ts/infra/eslint.js +50 -0
- package/dist/packs/js-ts/infra/scan.js +25 -0
- package/dist/packs/js-ts/infra/tsc.js +29 -0
- package/dist/packs/nextjs/domain/data.js +9 -0
- package/dist/packs/nextjs/domain/profile.js +21 -0
- package/dist/packs/nextjs/domain/specs.js +33 -0
- package/dist/packs/nextjs/index.js +23 -0
- package/dist/packs/node/domain/specs.js +23 -0
- package/dist/packs/node/index.js +26 -0
- package/dist/packs/react/domain/data.js +9 -0
- package/dist/packs/react/domain/specs.js +63 -0
- package/dist/packs/react/index.js +30 -0
- package/dist/packs/react-native/domain/specs.js +29 -0
- package/dist/packs/react-native/domain/testing.js +20 -0
- package/dist/packs/react-native/index.js +30 -0
- package/package.json +60 -4
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
const PRE_COMMIT = `if [ -f pnpm-lock.yaml ]; then pm=pnpm
|
|
2
|
+
elif [ -f yarn.lock ]; then pm=yarn
|
|
3
|
+
elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun
|
|
4
|
+
else pm=npm
|
|
5
|
+
fi
|
|
6
|
+
run_exec() { if [ "$pm" = npm ]; then npx --no-install "$@"; else "$pm" exec "$@"; fi; }
|
|
7
|
+
has_script() { node -e 'process.exit(require("./package.json").scripts?.[process.argv[1]] ? 0 : 1)' "$1" 2>/dev/null; }
|
|
8
|
+
|
|
9
|
+
if [ -f scripts/check-exact-deps.mjs ] && git diff --cached --name-only | grep -qx 'package.json'; then
|
|
10
|
+
node scripts/check-exact-deps.mjs || exit 1
|
|
11
|
+
fi
|
|
12
|
+
|
|
13
|
+
files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(src|app|scripts)/.*\\.(ts|tsx|js|jsx|mjs)$')
|
|
14
|
+
|
|
15
|
+
if [ -n "$files" ] && [ -f package.json ]; then
|
|
16
|
+
echo "pre-commit: eslint on staged files"
|
|
17
|
+
# shellcheck disable=SC2086
|
|
18
|
+
run_exec eslint $files || exit 1
|
|
19
|
+
fi
|
|
20
|
+
|
|
21
|
+
if has_script typecheck; then
|
|
22
|
+
echo "pre-commit: typecheck"
|
|
23
|
+
"$pm" run typecheck || exit 1
|
|
24
|
+
fi`;
|
|
25
|
+
const CLAUDE_EDIT = `if [ -f pnpm-lock.yaml ]; then pm=pnpm
|
|
26
|
+
elif [ -f yarn.lock ]; then pm=yarn
|
|
27
|
+
elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun
|
|
28
|
+
else pm=npm
|
|
29
|
+
fi
|
|
30
|
+
has_script() { node -e 'process.exit(require("./package.json").scripts?.[process.argv[1]] ? 0 : 1)' "$1" 2>/dev/null; }
|
|
31
|
+
|
|
32
|
+
if [ -x node_modules/.bin/eslint ]; then
|
|
33
|
+
if ! output=$(./node_modules/.bin/eslint "$file" 2>&1); then
|
|
34
|
+
printf 'guardrails: eslint found problems in %s. Fix the cause (each message says how). Do not add eslint-disable, @ts-ignore or any to silence it:\\n%s\\n' "$file" "$output" >&2
|
|
35
|
+
exit 2
|
|
36
|
+
fi
|
|
37
|
+
fi
|
|
38
|
+
|
|
39
|
+
if has_script typecheck; then
|
|
40
|
+
if ! output=$("$pm" run --silent typecheck 2>&1); then
|
|
41
|
+
printf 'guardrails: typecheck failed after editing %s. Fix the type errors below at their source:\\n%s\\n' "$file" "$output" >&2
|
|
42
|
+
exit 2
|
|
43
|
+
fi
|
|
44
|
+
fi`;
|
|
45
|
+
export const JS_TS_HOOKS = {
|
|
46
|
+
editPatterns: ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs"],
|
|
47
|
+
preCommit: () => PRE_COMMIT,
|
|
48
|
+
claudeEdit: () => CLAUDE_EDIT,
|
|
49
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { testCandidates } from "./pr-tests.js";
|
|
2
|
+
const base = { line: 1, column: 1, severity: "error", tool: "tests" };
|
|
3
|
+
export const MISSING_TEST_RULE = "test-next-to-logic";
|
|
4
|
+
export const COVERAGE_RULE = "coverage-floor";
|
|
5
|
+
export const COVERAGE_LOWERED_RULE = "coverage-floor-lowered";
|
|
6
|
+
export function missingTestDiagnostic(file) {
|
|
7
|
+
const [first] = testCandidates(file);
|
|
8
|
+
return {
|
|
9
|
+
...base,
|
|
10
|
+
file,
|
|
11
|
+
rule: MISSING_TEST_RULE,
|
|
12
|
+
message: `${file} changed in this PR and has no test next to it`,
|
|
13
|
+
fix: `Create ${first ?? "<name>.test.ts"} next to ${file} covering its exported functions. Components and styles are exempt; if this file is only wiring, move the logic to a pure module.`,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function coverageDiagnostic(floor, measured, file) {
|
|
17
|
+
return {
|
|
18
|
+
...base,
|
|
19
|
+
file,
|
|
20
|
+
rule: COVERAGE_RULE,
|
|
21
|
+
message: `line coverage ${String(measured)}% is below the floor ${String(floor)}%`,
|
|
22
|
+
fix: "Add tests for the code you changed until coverage is back at or above the floor. The floor only goes up: never lower it.",
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function loweredDiagnostic(before, after, file) {
|
|
26
|
+
return {
|
|
27
|
+
...base,
|
|
28
|
+
file,
|
|
29
|
+
rule: COVERAGE_LOWERED_RULE,
|
|
30
|
+
message: `the coverage floor went from ${String(before)}% to ${after === undefined ? "nothing" : `${String(after)}%`} in this PR`,
|
|
31
|
+
fix: `Restore "coverage": ${String(before)} (or higher) in ${file}. Raise coverage with tests instead of lowering the floor.`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const LOGIC_EXTENSIONS = ["ts", "mts", "cts", "js", "mjs", "cjs"];
|
|
2
|
+
const EXEMPT_DIRS = ["infra", "app", "node_modules", "dist", "scripts", "eslint", "catalog-assets", "fixtures", "__mocks__", "__tests__", ".guardrails", ".github", ".claude", ".githooks"];
|
|
3
|
+
const EXEMPT_NAMES = ["index", "cli", "main", "types", "styles", "style", "theme"];
|
|
4
|
+
const nameOf = (path) => path.slice(path.lastIndexOf("/") + 1);
|
|
5
|
+
const extensionOf = (name) => name.slice(name.lastIndexOf(".") + 1);
|
|
6
|
+
const stemOf = (name) => name.slice(0, name.indexOf("."));
|
|
7
|
+
function isExempt(path) {
|
|
8
|
+
const name = nameOf(path);
|
|
9
|
+
const stem = stemOf(name);
|
|
10
|
+
const dirs = path.split("/").slice(0, -1);
|
|
11
|
+
return (name.endsWith(".d.ts") ||
|
|
12
|
+
/\.(test|spec|config|types|styles|style)\./.test(name) ||
|
|
13
|
+
EXEMPT_NAMES.includes(stem) ||
|
|
14
|
+
dirs.some((dir) => EXEMPT_DIRS.includes(dir)));
|
|
15
|
+
}
|
|
16
|
+
export function isLogicFile(path) {
|
|
17
|
+
return LOGIC_EXTENSIONS.includes(extensionOf(nameOf(path))) && !isExempt(path);
|
|
18
|
+
}
|
|
19
|
+
export function testCandidates(path) {
|
|
20
|
+
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
|
|
21
|
+
const stem = nameOf(path).slice(0, nameOf(path).lastIndexOf("."));
|
|
22
|
+
return ["test", "spec"].flatMap((kind) => [...LOGIC_EXTENSIONS, "tsx", "jsx"].map((ext) => `${dir}${stem}.${kind}.${ext}`));
|
|
23
|
+
}
|
|
24
|
+
export const isTypeOnly = (source) => !/\b(function|class|const|let|var|enum)\b|=>/.test(source.replace(/^\s*import .*$/gm, ""));
|
|
25
|
+
export function missingTests(changed, present, source) {
|
|
26
|
+
return changed.filter((path) => isLogicFile(path) && !testCandidates(path).some(present) && !isTypeOnly(source(path)));
|
|
27
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
|
|
2
|
+
const EXACT_VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
|
|
3
|
+
const PROTOCOL_VERSION = /^(workspace|link|file|npm|catalog):/;
|
|
4
|
+
const ROOT_SOURCE_DIRS = ["app", "pages", "components", "lib", "hooks", "utils"];
|
|
5
|
+
export const HOOK_GLOBS = Object.freeze(["**/hooks/**", "**/use*.{ts,tsx}"]);
|
|
6
|
+
export function findLooseDependencies(pkg) {
|
|
7
|
+
return DEPENDENCY_FIELDS.flatMap((field) => {
|
|
8
|
+
const group = pkg[field];
|
|
9
|
+
if (typeof group !== "object" || group === null)
|
|
10
|
+
return [];
|
|
11
|
+
return Object.entries(group)
|
|
12
|
+
.filter(([, range]) => typeof range === "string" && !EXACT_VERSION.test(range) && !PROTOCOL_VERSION.test(range))
|
|
13
|
+
.map(([name, range]) => `${field}.${name}@${String(range)}`);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export function pickPackageManager(lockfiles, packageManagerField) {
|
|
17
|
+
if (lockfiles.includes("pnpm-lock.yaml"))
|
|
18
|
+
return "pnpm";
|
|
19
|
+
if (lockfiles.includes("yarn.lock"))
|
|
20
|
+
return "yarn";
|
|
21
|
+
if (lockfiles.includes("bun.lock") || lockfiles.includes("bun.lockb"))
|
|
22
|
+
return "bun";
|
|
23
|
+
if (lockfiles.includes("package-lock.json"))
|
|
24
|
+
return "npm";
|
|
25
|
+
const named = packageManagerField?.split("@")[0];
|
|
26
|
+
return named === "pnpm" || named === "yarn" || named === "bun" ? named : "npm";
|
|
27
|
+
}
|
|
28
|
+
export function cleanVersion(range) {
|
|
29
|
+
return range === undefined ? null : (/\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/.exec(range)?.[0] ?? null);
|
|
30
|
+
}
|
|
31
|
+
export function sourceGlobsFor(topLevelDirs) {
|
|
32
|
+
if (topLevelDirs.includes("src"))
|
|
33
|
+
return { srcDir: "src", globs: ["src/**/*.{ts,tsx}"] };
|
|
34
|
+
return { srcDir: null, globs: ROOT_SOURCE_DIRS.filter((dir) => topLevelDirs.includes(dir)).map((dir) => `${dir}/**/*.{ts,tsx}`) };
|
|
35
|
+
}
|
|
36
|
+
export function packageRunCommand(pm, script) {
|
|
37
|
+
return pm === "npm" ? `npm run ${script}` : `${pm} run ${script}`;
|
|
38
|
+
}
|
|
39
|
+
const INSTALL_DEV = Object.freeze({
|
|
40
|
+
pnpm: "pnpm add -D --save-exact",
|
|
41
|
+
yarn: "yarn add -D --exact",
|
|
42
|
+
bun: "bun add -d --exact",
|
|
43
|
+
npm: "npm install -D --save-exact",
|
|
44
|
+
});
|
|
45
|
+
export function installDevCommand(pm, packages) {
|
|
46
|
+
return `${INSTALL_DEV[pm]} ${packages.join(" ")}`;
|
|
47
|
+
}
|
|
48
|
+
export function execCommand(pm, bin, args) {
|
|
49
|
+
const prefix = { pnpm: "pnpm exec", yarn: "yarn", bun: "bun x", npm: "npx --no-install" };
|
|
50
|
+
return `${prefix[pm]} ${bin} ${args}`;
|
|
51
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { isRecord, objectAt } from "../../../core/domain/json.js";
|
|
2
|
+
import { HOOK_GLOBS, cleanVersion, findLooseDependencies, pickPackageManager, sourceGlobsFor } from "./profile-pure.js";
|
|
3
|
+
export const GUARDRAILS_CONFIG_IMPORT = "eslint/guardrails/config.mjs";
|
|
4
|
+
export const ESLINT_FLAT_CONFIGS = ["eslint.config.mjs", "eslint.config.js", "eslint.config.cjs", "eslint.config.ts", "eslint.config.mts", "eslint.config.cts"];
|
|
5
|
+
const ESLINT_LEGACY_CONFIGS = [".eslintrc", ".eslintrc.json", ".eslintrc.js", ".eslintrc.cjs", ".eslintrc.yml", ".eslintrc.yaml"];
|
|
6
|
+
const LOCKFILES = ["pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb", "package-lock.json"];
|
|
7
|
+
export const LAYERS_FILE = ".guardrails/layers.json";
|
|
8
|
+
const VERSION_PACKAGES = ["typescript", "eslint"];
|
|
9
|
+
export const JS_TS_PROBE = {
|
|
10
|
+
paths: [
|
|
11
|
+
"src", "app", "pages", "src/features", "scripts/check-exact-deps.mjs", "node_modules/.bin/eslint", "node_modules/.bin/guardrails", "node_modules/.bin/tsc",
|
|
12
|
+
...LOCKFILES, ...ESLINT_FLAT_CONFIGS, ...ESLINT_LEGACY_CONFIGS,
|
|
13
|
+
],
|
|
14
|
+
json: ["package.json", "tsconfig.json", LAYERS_FILE, ...VERSION_PACKAGES.map((name) => `node_modules/${name}/package.json`)],
|
|
15
|
+
text: ESLINT_FLAT_CONFIGS,
|
|
16
|
+
tree: [{ root: "src", depth: 3 }],
|
|
17
|
+
};
|
|
18
|
+
function stringRecord(value) {
|
|
19
|
+
if (!isRecord(value))
|
|
20
|
+
return {};
|
|
21
|
+
return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
|
|
22
|
+
}
|
|
23
|
+
export function installedVersion(facts, name) {
|
|
24
|
+
const version = facts.json[`node_modules/${name}/package.json`]?.["version"];
|
|
25
|
+
return typeof version === "string" ? version : null;
|
|
26
|
+
}
|
|
27
|
+
function typescriptOf(facts, deps) {
|
|
28
|
+
const tsconfig = facts.json["tsconfig.json"];
|
|
29
|
+
const options = tsconfig === undefined ? null : objectAt(tsconfig, "compilerOptions");
|
|
30
|
+
const strictValue = options?.["strict"];
|
|
31
|
+
const strict = typeof strictValue === "boolean" ? strictValue : tsconfig !== undefined && tsconfig["extends"] === undefined ? false : null;
|
|
32
|
+
return {
|
|
33
|
+
present: "typescript" in deps || tsconfig !== undefined,
|
|
34
|
+
version: installedVersion(facts, "typescript") ?? cleanVersion(deps["typescript"]),
|
|
35
|
+
tsconfig: tsconfig === undefined ? null : "tsconfig.json",
|
|
36
|
+
strict,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function eslintOf(facts, deps) {
|
|
40
|
+
const flat = ESLINT_FLAT_CONFIGS.find((file) => facts.present.includes(file)) ?? null;
|
|
41
|
+
const legacy = ESLINT_LEGACY_CONFIGS.find((file) => facts.present.includes(file)) ?? null;
|
|
42
|
+
const configText = flat === null ? "" : (facts.text[flat] ?? "");
|
|
43
|
+
return {
|
|
44
|
+
installed: facts.present.includes("node_modules/.bin/eslint"),
|
|
45
|
+
version: installedVersion(facts, "eslint") ?? cleanVersion(deps["eslint"]),
|
|
46
|
+
config: flat ?? legacy,
|
|
47
|
+
flat: flat !== null,
|
|
48
|
+
typescriptPlugin: ["typescript-eslint", "@typescript-eslint/eslint-plugin", "eslint-config-next"].some((name) => name in deps),
|
|
49
|
+
typescriptEslintPackage: "typescript-eslint" in deps,
|
|
50
|
+
guardrailsWired: configText.includes(GUARDRAILS_CONFIG_IMPORT),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function layerRoots(tree) {
|
|
54
|
+
const roots = tree.filter((dir) => dir.endsWith("/domain")).map((dir) => dir.slice(0, -"/domain".length));
|
|
55
|
+
return roots.filter((root) => tree.includes(`${root}/app`) && tree.includes(`${root}/infra`));
|
|
56
|
+
}
|
|
57
|
+
function layerRulesOf(facts) {
|
|
58
|
+
const rules = facts.json[LAYERS_FILE]?.["forbid"];
|
|
59
|
+
if (!Array.isArray(rules))
|
|
60
|
+
return [];
|
|
61
|
+
return rules.flatMap((rule) => {
|
|
62
|
+
if (!isRecord(rule))
|
|
63
|
+
return [];
|
|
64
|
+
const { files, source, message } = rule;
|
|
65
|
+
return typeof files === "string" && typeof source === "string" && typeof message === "string" ? [{ files, source, message }] : [];
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function pathsOf(facts) {
|
|
69
|
+
const globs = sourceGlobsFor(facts.topLevel);
|
|
70
|
+
return {
|
|
71
|
+
srcDir: globs.srcDir,
|
|
72
|
+
featuresDir: facts.present.includes("src/features") ? "src/features" : null,
|
|
73
|
+
layerRoots: layerRoots(facts.tree),
|
|
74
|
+
sourceGlobs: globs.globs,
|
|
75
|
+
routeGlobs: ["**/*.config.{ts,mjs,js,cjs,mts}"],
|
|
76
|
+
hookGlobs: HOOK_GLOBS,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
export function deriveJsTs(facts) {
|
|
80
|
+
const pkg = facts.json["package.json"] ?? {};
|
|
81
|
+
const deps = { ...stringRecord(pkg["dependencies"]), ...stringRecord(pkg["devDependencies"]) };
|
|
82
|
+
const scripts = stringRecord(pkg["scripts"]);
|
|
83
|
+
const loose = findLooseDependencies(pkg);
|
|
84
|
+
return {
|
|
85
|
+
name: typeof pkg["name"] === "string" ? pkg["name"] : "unnamed",
|
|
86
|
+
packageManager: pickPackageManager(facts.topLevel.filter((name) => LOCKFILES.includes(name)), typeof pkg["packageManager"] === "string" ? pkg["packageManager"] : null),
|
|
87
|
+
packageManagerPinned: typeof pkg["packageManager"] === "string",
|
|
88
|
+
typescript: typescriptOf(facts, deps),
|
|
89
|
+
eslint: eslintOf(facts, deps),
|
|
90
|
+
dependencies: Object.keys(deps),
|
|
91
|
+
tests: { runner: "vitest" in deps ? "vitest" : "jest" in deps ? "jest" : null },
|
|
92
|
+
paths: pathsOf(facts),
|
|
93
|
+
scripts: { lint: "lint" in scripts, typecheck: "typecheck" in scripts, test: "test" in scripts, build: "build" in scripts },
|
|
94
|
+
guardrails: { installed: "@whil/guardrails" in deps || facts.present.includes("node_modules/.bin/guardrails") },
|
|
95
|
+
exactDeps: { ok: loose.length === 0, loose, script: facts.present.includes("scripts/check-exact-deps.mjs") },
|
|
96
|
+
layerRules: layerRulesOf(facts),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
export function describeJsTs(data) {
|
|
100
|
+
return [
|
|
101
|
+
`${data.name}: ${data.packageManager}, typescript ${data.typescript.present ? `${data.typescript.version ?? "?"}, strict ${String(data.typescript.strict)}` : "absent"}`,
|
|
102
|
+
`eslint: ${data.eslint.config ?? "no config"}${data.eslint.flat ? "" : " (not flat config)"}${data.eslint.installed ? "" : ", not installed"}`,
|
|
103
|
+
`exact deps: ${data.exactDeps.ok ? "ok" : `${data.exactDeps.loose.length} loose`}`,
|
|
104
|
+
];
|
|
105
|
+
}
|
|
106
|
+
export function dependenciesOf(facts) {
|
|
107
|
+
const pkg = facts.json["package.json"] ?? {};
|
|
108
|
+
return new Set([...Object.keys(stringRecord(pkg["dependencies"])), ...Object.keys(stringRecord(pkg["devDependencies"])), ...Object.keys(stringRecord(pkg["peerDependencies"]))]);
|
|
109
|
+
}
|
|
110
|
+
export function packageField(facts, field) {
|
|
111
|
+
return facts.json["package.json"]?.[field];
|
|
112
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { eslintDiagnostic, tscDiagnostic } from "./diagnostics-js.js";
|
|
2
|
+
import { installDevCommand } from "./profile-pure.js";
|
|
3
|
+
export const EXACT_DEPS_RULE = "exact-deps";
|
|
4
|
+
export const REASON_RULE = "guardrails/require-disable-reason";
|
|
5
|
+
export function skippedTools(lint, tsc) {
|
|
6
|
+
const eslint = lint === null ? [{ tool: "eslint", reason: "eslint is not installed" }] : lint.ran ? [] : [{ tool: "eslint", reason: lint.error ?? "eslint failed to run" }];
|
|
7
|
+
const types = tsc === null ? [{ tool: "tsc", reason: "TypeScript not detected" }] : tsc.ran ? [] : [{ tool: "tsc", reason: tsc.error ?? "tsc failed to run" }];
|
|
8
|
+
return [...eslint, ...types];
|
|
9
|
+
}
|
|
10
|
+
export function dependencyDiagnostics(data) {
|
|
11
|
+
if (!data.exactDeps.script)
|
|
12
|
+
return [];
|
|
13
|
+
return data.exactDeps.loose.map((entry) => ({
|
|
14
|
+
file: "package.json",
|
|
15
|
+
line: 0,
|
|
16
|
+
column: 0,
|
|
17
|
+
tool: "exact-deps",
|
|
18
|
+
rule: EXACT_DEPS_RULE,
|
|
19
|
+
message: `${entry} is not an exact version`,
|
|
20
|
+
severity: "warn",
|
|
21
|
+
fix: `Pin it to the exact version in the lockfile (no ^ or ~): ${installDevCommand(data.packageManager, ["<pkg>@<exact version>"])}.`,
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
export function disableDiagnostics(findings, handled) {
|
|
25
|
+
return findings
|
|
26
|
+
.filter((found) => !found.hasReason && !handled.has(`${found.file}:${found.line}`))
|
|
27
|
+
.map((found) => ({
|
|
28
|
+
file: found.file,
|
|
29
|
+
line: found.line,
|
|
30
|
+
column: 1,
|
|
31
|
+
tool: "disable-reason",
|
|
32
|
+
rule: "eslint-disable-without-reason",
|
|
33
|
+
message: "eslint-disable without a reason",
|
|
34
|
+
severity: "error",
|
|
35
|
+
fix: "Write `eslint-disable-next-line <rule> -- <why the rule cannot be satisfied here>`, or fix the code so no disable is needed.",
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
export function toolDiagnostics(lint, tsc, fixes) {
|
|
39
|
+
const eslint = lint?.ran === true ? [...lint.violations, ...lint.fatal].map((violation) => eslintDiagnostic(violation, fixes)) : [];
|
|
40
|
+
const types = tsc?.ran === true ? tsc.diagnostics.map(tscDiagnostic) : [];
|
|
41
|
+
return [...eslint, ...types];
|
|
42
|
+
}
|
|
43
|
+
export function topRules(violations) {
|
|
44
|
+
const counts = violations.reduce((acc, violation) => ({ ...acc, [violation.rule]: (acc[violation.rule] ?? 0) + 1 }), {});
|
|
45
|
+
return Object.entries(counts)
|
|
46
|
+
.toSorted((a, b) => b[1] - a[1])
|
|
47
|
+
.slice(0, 15)
|
|
48
|
+
.map(([rule, count]) => ({ rule, count }));
|
|
49
|
+
}
|
|
50
|
+
export function rulesAt(state, level) {
|
|
51
|
+
return Object.entries(state.rules)
|
|
52
|
+
.filter(([, entry]) => entry.level === level)
|
|
53
|
+
.map(([name]) => name);
|
|
54
|
+
}
|
|
55
|
+
export function failingReasons(input) {
|
|
56
|
+
return [
|
|
57
|
+
...(input.errors > 0 ? [`${input.errors} lint errors`] : []),
|
|
58
|
+
...input.regressions.map((entry) => `ratchet: ${entry}`),
|
|
59
|
+
...(input.disablesWithoutReason > 0 ? [`${input.disablesWithoutReason} eslint-disable without a reason`] : []),
|
|
60
|
+
...(input.typeErrors !== null && input.typeErrors > 0 ? [`${input.typeErrors} type errors`] : []),
|
|
61
|
+
];
|
|
62
|
+
}
|
|
63
|
+
export function ratchetDiagnostic(entry) {
|
|
64
|
+
return {
|
|
65
|
+
file: "eslint/guardrails/rules.json",
|
|
66
|
+
line: 0,
|
|
67
|
+
column: 0,
|
|
68
|
+
tool: "ratchet",
|
|
69
|
+
rule: `ratchet/${entry.rule}`,
|
|
70
|
+
message: `${entry.rule} has ${String(entry.count)} violations, the baseline allows ${String(entry.baseline)}. Violations of a rule at warn can only go down.`,
|
|
71
|
+
severity: "error",
|
|
72
|
+
fix: `Fix the new ${entry.rule} violations listed above (they are the warnings for this rule). When the count reaches 0 the rule is promoted to error by itself.`,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export const UNIMPLEMENTED_MARKER = "IMPLEMENTED = false";
|
|
2
|
+
export function renderRule(spec) {
|
|
3
|
+
const message = JSON.stringify(spec.message);
|
|
4
|
+
if (spec.selector === null) {
|
|
5
|
+
return [
|
|
6
|
+
"const IMPLEMENTED = false;",
|
|
7
|
+
"",
|
|
8
|
+
"export const rule = {",
|
|
9
|
+
' meta: { type: "problem", schema: [], messages: { violation: ' + message + " } },",
|
|
10
|
+
" create() {",
|
|
11
|
+
" return IMPLEMENTED ? {} : {};",
|
|
12
|
+
" },",
|
|
13
|
+
"};",
|
|
14
|
+
"",
|
|
15
|
+
].join("\n");
|
|
16
|
+
}
|
|
17
|
+
return [
|
|
18
|
+
"export const rule = {",
|
|
19
|
+
' meta: { type: "problem", schema: [], messages: { violation: ' + message + " } },",
|
|
20
|
+
" create(context) {",
|
|
21
|
+
" return {",
|
|
22
|
+
` ${JSON.stringify(spec.selector)}: (node) => context.report({ node, messageId: "violation" }),`,
|
|
23
|
+
" };",
|
|
24
|
+
" },",
|
|
25
|
+
"};",
|
|
26
|
+
"",
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
29
|
+
export function renderRuleTest(spec) {
|
|
30
|
+
const valid = JSON.stringify(spec.good ?? "export const ok = 1;\n");
|
|
31
|
+
const invalid = spec.bad === null ? "" : `\n { code: ${JSON.stringify(spec.bad)}, errors: [{ messageId: "violation" }] },\n `;
|
|
32
|
+
return [
|
|
33
|
+
'import { rule } from "./' + spec.name + '.mjs";',
|
|
34
|
+
'import { makeTester } from "./_rule-tester.mjs";',
|
|
35
|
+
"",
|
|
36
|
+
"const tester = await makeTester();",
|
|
37
|
+
"",
|
|
38
|
+
`tester.run(${JSON.stringify(spec.name)}, rule, {`,
|
|
39
|
+
` valid: [{ code: ${valid} }],`,
|
|
40
|
+
` invalid: [${invalid}],`,
|
|
41
|
+
"});",
|
|
42
|
+
"",
|
|
43
|
+
].join("\n");
|
|
44
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const JS_TS_SIGNALS = [
|
|
2
|
+
{ pattern: "\\bany\\b|as any", constraint: "no-any" },
|
|
3
|
+
{ pattern: "non-null|null assertion|cannot read propert|undefined is not|of undefined|of null", constraint: "no-non-null-assertion" },
|
|
4
|
+
{ pattern: "floating promise|unhandled (promise|rejection)|missing await|forgot to await|\\bawait\\b", constraint: "no-floating-promises" },
|
|
5
|
+
{ pattern: "mutat|in place|side effect", constraint: "no-mutation" },
|
|
6
|
+
{ pattern: "console\\.(log|error)|leftover log|debug log", constraint: "no-console" },
|
|
7
|
+
{ pattern: "ts-ignore|ts-expect-error|suppress", constraint: "no-ts-ignore" },
|
|
8
|
+
{ pattern: "type error|TS\\d{4}|typecheck|tsc", constraint: "ts-strict-max" },
|
|
9
|
+
{ pattern: "circular|cyclic|import cycle|layer|boundar", constraint: "import-boundaries" },
|
|
10
|
+
{ pattern: "default export", constraint: "no-default-export" },
|
|
11
|
+
{ pattern: "too long|too complex|split (this|the) function|refactor.*function", constraint: "max-function-length" },
|
|
12
|
+
{ pattern: "eslint-disable", constraint: "require-disable-reason" },
|
|
13
|
+
{ pattern: "\\benum\\b", constraint: "no-enum" },
|
|
14
|
+
];
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { isRecord, parseStrictJson } from "../../../core/domain/json.js";
|
|
2
|
+
import { jsTs } from "./data.js";
|
|
3
|
+
export const VITEST_SPEC = {
|
|
4
|
+
runner: "vitest",
|
|
5
|
+
packages: ["vitest", "@vitest/coverage-v8"],
|
|
6
|
+
configFile: "vitest.config.ts",
|
|
7
|
+
script: "vitest run --coverage",
|
|
8
|
+
coverageSummary: "coverage/coverage-summary.json",
|
|
9
|
+
config: (profile) => {
|
|
10
|
+
const dir = jsTs(profile).paths.srcDir ?? ".";
|
|
11
|
+
return [
|
|
12
|
+
'import { defineConfig } from "vitest/config";',
|
|
13
|
+
"",
|
|
14
|
+
"export default defineConfig({",
|
|
15
|
+
" test: {",
|
|
16
|
+
` include: ["${dir}/**/*.test.{ts,tsx}"],`,
|
|
17
|
+
` coverage: { provider: "v8", reporter: ["json-summary", "text-summary"], reportsDirectory: "coverage", include: ["${dir}/**/*.{ts,tsx}"] },`,
|
|
18
|
+
" },",
|
|
19
|
+
"});",
|
|
20
|
+
"",
|
|
21
|
+
].join("\n");
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
export function pickTesting(packs) {
|
|
25
|
+
return packs.flatMap((pack) => (pack.testing === undefined ? [] : [pack.testing])).at(-1) ?? null;
|
|
26
|
+
}
|
|
27
|
+
export function measuredLines(summary) {
|
|
28
|
+
const parsed = summary === null ? null : parseStrictJson(summary);
|
|
29
|
+
const total = parsed !== null && parsed.ok && isRecord(parsed.value) ? parsed.value["total"] : null;
|
|
30
|
+
const lines = isRecord(total) ? total["lines"] : null;
|
|
31
|
+
const pct = isRecord(lines) ? lines["pct"] : null;
|
|
32
|
+
return typeof pct === "number" ? pct : null;
|
|
33
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export const STRICT_OPTIONS = Object.freeze({
|
|
2
|
+
strict: true,
|
|
3
|
+
noUncheckedIndexedAccess: true,
|
|
4
|
+
exactOptionalPropertyTypes: true,
|
|
5
|
+
noImplicitOverride: true,
|
|
6
|
+
noImplicitReturns: true,
|
|
7
|
+
noFallthroughCasesInSwitch: true,
|
|
8
|
+
});
|
|
9
|
+
export function missingStrictOptions(compilerOptions) {
|
|
10
|
+
return Object.entries(STRICT_OPTIONS)
|
|
11
|
+
.filter(([name, value]) => compilerOptions[name] !== value)
|
|
12
|
+
.map(([name]) => name);
|
|
13
|
+
}
|
|
14
|
+
export function tscArgs(buildInfoFile) {
|
|
15
|
+
return ["--noEmit", "--pretty", "false", "--incremental", "--tsBuildInfoFile", buildInfoFile];
|
|
16
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { addRuleJsTs } from "./app/add-rule.js";
|
|
2
|
+
import { analyzeJsTs } from "./app/analysis.js";
|
|
3
|
+
import { JS_TS_BOOTSTRAP } from "./app/bootstrap.js";
|
|
4
|
+
import { eslintConstraint, unusedDisableDirectives } from "./app/eslint-constraints.js";
|
|
5
|
+
import { exactDeps, pkgScripts, tsStrictMax } from "./app/project.js";
|
|
6
|
+
import { testsConstraint } from "./app/tests.js";
|
|
7
|
+
import { JS_TS_CI, JS_TS_COMMANDS } from "./domain/ci.js";
|
|
8
|
+
import { fixesOf, JS_TS_SPECS } from "./domain/catalog-specs.js";
|
|
9
|
+
import { jsTs } from "./domain/data.js";
|
|
10
|
+
import { JS_TS_SIGNALS } from "./domain/signals.js";
|
|
11
|
+
import { JS_TS_HOOKS } from "./domain/hooks.js";
|
|
12
|
+
import { JS_TS_PROBE, deriveJsTs, describeJsTs } from "./domain/profile.js";
|
|
13
|
+
import { packageRunCommand } from "./domain/profile-pure.js";
|
|
14
|
+
import { VITEST_SPEC } from "./domain/testing.js";
|
|
15
|
+
const script = (name) => (profile) => {
|
|
16
|
+
const data = jsTs(profile);
|
|
17
|
+
return data.scripts[name] ? packageRunCommand(data.packageManager, name) : null;
|
|
18
|
+
};
|
|
19
|
+
const detect = (facts) => {
|
|
20
|
+
const hasPackage = facts.json["package.json"] !== undefined;
|
|
21
|
+
const hasTypescript = facts.json["tsconfig.json"] !== undefined;
|
|
22
|
+
return {
|
|
23
|
+
confidence: hasPackage ? (hasTypescript ? 1 : 0.6) : 0,
|
|
24
|
+
evidence: [...(hasPackage ? ["package.json"] : []), ...(hasTypescript ? ["tsconfig.json"] : [])],
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
export const jsTsPack = {
|
|
28
|
+
id: "js-ts",
|
|
29
|
+
title: "JavaScript and TypeScript: strict tsconfig, ESLint with the guardrails plugin, immutability, no any, no comments",
|
|
30
|
+
extends: [],
|
|
31
|
+
probe: JS_TS_PROBE,
|
|
32
|
+
detect,
|
|
33
|
+
profile: (facts) => ({ ...deriveJsTs(facts) }),
|
|
34
|
+
constraints: [pkgScripts, tsStrictMax, ...JS_TS_SPECS.map(eslintConstraint), unusedDisableDirectives, exactDeps, testsConstraint],
|
|
35
|
+
fixes: fixesOf(JS_TS_SPECS),
|
|
36
|
+
signals: JS_TS_SIGNALS,
|
|
37
|
+
tools: {
|
|
38
|
+
linter: { id: "eslint", command: script("lint") },
|
|
39
|
+
typecheck: { id: "tsc", command: script("typecheck") },
|
|
40
|
+
formatter: null,
|
|
41
|
+
test: { id: "vitest", command: script("test") },
|
|
42
|
+
},
|
|
43
|
+
commands: JS_TS_COMMANDS,
|
|
44
|
+
ci: JS_TS_CI,
|
|
45
|
+
hooks: { ...JS_TS_HOOKS, bootstrap: JS_TS_BOOTSTRAP },
|
|
46
|
+
testing: VITEST_SPEC,
|
|
47
|
+
analyze: analyzeJsTs,
|
|
48
|
+
addRule: addRuleJsTs,
|
|
49
|
+
describe: (profile) => describeJsTs(jsTs(profile)),
|
|
50
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { LINT_NOT_RUN, parseEslintJson } from "../domain/eslint-output.js";
|
|
3
|
+
import { isRecord, parseStrictJson } from "../../../core/domain/json.js";
|
|
4
|
+
import { exists, removeFile, writeTemp } from "../../../core/infra/fs.js";
|
|
5
|
+
import { runAsync, runSync } from "../../../core/infra/exec.js";
|
|
6
|
+
function bin(root) {
|
|
7
|
+
return join(root, "node_modules", ".bin", "eslint");
|
|
8
|
+
}
|
|
9
|
+
export function hasEslint(root) {
|
|
10
|
+
return exists(root, "node_modules/.bin/eslint");
|
|
11
|
+
}
|
|
12
|
+
function lintArgs(data, paths) {
|
|
13
|
+
const targets = paths.length > 0 ? paths : data.paths.sourceGlobs.length > 0 ? data.paths.sourceGlobs : ["."];
|
|
14
|
+
return [...targets, "--format", "json", "--no-error-on-unmatched-pattern"];
|
|
15
|
+
}
|
|
16
|
+
function toOutcome(root, result) {
|
|
17
|
+
const parsed = result.status <= 1 ? parseEslintJson(root, result.stdout) : null;
|
|
18
|
+
if (parsed === null)
|
|
19
|
+
return LINT_NOT_RUN((result.stderr || result.stdout).trim().split("\n").slice(0, 6).join("\n"));
|
|
20
|
+
return { ran: true, error: null, ...parsed };
|
|
21
|
+
}
|
|
22
|
+
export function lintRepo(root, data, paths = []) {
|
|
23
|
+
return hasEslint(root) ? toOutcome(root, runSync(bin(root), lintArgs(data, paths), root)) : LINT_NOT_RUN("eslint is not installed in node_modules");
|
|
24
|
+
}
|
|
25
|
+
export async function lintRepoAsync(root, data, paths = []) {
|
|
26
|
+
return hasEslint(root) ? toOutcome(root, await runAsync(bin(root), lintArgs(data, paths), root)) : LINT_NOT_RUN("eslint is not installed in node_modules");
|
|
27
|
+
}
|
|
28
|
+
export function probeRules(root, filename, code) {
|
|
29
|
+
const unusable = { rules: new Set(), usable: false };
|
|
30
|
+
if (!writeTemp(root, filename, code))
|
|
31
|
+
return unusable;
|
|
32
|
+
try {
|
|
33
|
+
const result = runSync(bin(root), [filename, "--format", "json"], root);
|
|
34
|
+
const parsed = result.status <= 1 ? parseEslintJson(root, result.stdout) : null;
|
|
35
|
+
if (parsed === null || parsed.fatal.length > 0)
|
|
36
|
+
return unusable;
|
|
37
|
+
return { rules: new Set(parsed.violations.map((violation) => violation.rule)), usable: true };
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
removeFile(root, filename);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function printConfigRules(root, filename) {
|
|
44
|
+
const result = runSync(bin(root), ["--print-config", filename], root);
|
|
45
|
+
if (result.status !== 0)
|
|
46
|
+
return null;
|
|
47
|
+
const parsed = parseStrictJson(result.stdout);
|
|
48
|
+
const rules = parsed.ok && isRecord(parsed.value) ? parsed.value["rules"] : null;
|
|
49
|
+
return isRecord(rules) ? rules : null;
|
|
50
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { findDisableDirectives } from "../domain/disables.js";
|
|
4
|
+
const SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
|
|
5
|
+
const SKIPPED_DIRS = ["node_modules", ".next", "dist", "build", "out", ".git", "coverage"];
|
|
6
|
+
function walk(root, rel) {
|
|
7
|
+
const stat = statSync(join(root, rel), { throwIfNoEntry: false });
|
|
8
|
+
if (stat === undefined)
|
|
9
|
+
return [];
|
|
10
|
+
if (stat.isFile())
|
|
11
|
+
return SOURCE_EXTENSIONS.some((extension) => rel.endsWith(extension)) ? [rel] : [];
|
|
12
|
+
return readdirSync(join(root, rel))
|
|
13
|
+
.filter((name) => !SKIPPED_DIRS.includes(name))
|
|
14
|
+
.toSorted()
|
|
15
|
+
.flatMap((name) => walk(root, rel === "" ? name : `${rel}/${name}`));
|
|
16
|
+
}
|
|
17
|
+
export function sourceRoots(data) {
|
|
18
|
+
const roots = data.paths.sourceGlobs.map((glob) => glob.split("/**")[0] ?? "");
|
|
19
|
+
return roots.length > 0 ? [...new Set(roots)] : [""];
|
|
20
|
+
}
|
|
21
|
+
export function scanDisableDirectives(root, data) {
|
|
22
|
+
return sourceRoots(data)
|
|
23
|
+
.flatMap((dir) => walk(root, dir))
|
|
24
|
+
.flatMap((file) => findDisableDirectives(readFileSync(join(root, file), "utf8")).map((found) => ({ file, ...found })));
|
|
25
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { readRuntime } from "../../../config/runtime.js";
|
|
4
|
+
import { repoKey } from "../../../core/infra/hash.js";
|
|
5
|
+
import { tscArgs } from "../domain/ts-options.js";
|
|
6
|
+
import { parseTscOutput } from "../domain/diagnostics-js.js";
|
|
7
|
+
import { exists } from "../../../core/infra/fs.js";
|
|
8
|
+
import { runAsync, runSync } from "../../../core/infra/exec.js";
|
|
9
|
+
const MISSING = Object.freeze({ ran: false, diagnostics: [], error: "tsc is not installed in node_modules" });
|
|
10
|
+
function bin(root) {
|
|
11
|
+
return join(root, "node_modules", ".bin", "tsc");
|
|
12
|
+
}
|
|
13
|
+
function toOutcome(result) {
|
|
14
|
+
const diagnostics = parseTscOutput(`${result.stdout}\n${result.stderr}`);
|
|
15
|
+
if (result.status !== 0 && diagnostics.length === 0)
|
|
16
|
+
return { ran: false, diagnostics, error: (result.stdout || result.stderr).trim().slice(0, 500) };
|
|
17
|
+
return { ran: true, diagnostics, error: null };
|
|
18
|
+
}
|
|
19
|
+
function buildInfoFile(root) {
|
|
20
|
+
const file = join(readRuntime().cacheDir, "tsbuildinfo", repoKey(root), "tsc.tsbuildinfo");
|
|
21
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
22
|
+
return file;
|
|
23
|
+
}
|
|
24
|
+
export function runTsc(root) {
|
|
25
|
+
return exists(root, "node_modules/.bin/tsc") ? toOutcome(runSync(bin(root), tscArgs(buildInfoFile(root)), root)) : MISSING;
|
|
26
|
+
}
|
|
27
|
+
export async function runTscAsync(root) {
|
|
28
|
+
return exists(root, "node_modules/.bin/tsc") ? toOutcome(await runAsync(bin(root), tscArgs(buildInfoFile(root)), root)) : MISSING;
|
|
29
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { isRecord } from "../../../core/domain/json.js";
|
|
2
|
+
const EMPTY = { version: null, router: null, pageGlobs: [], apiGlobs: [], routeGlobs: [] };
|
|
3
|
+
function isNextData(value) {
|
|
4
|
+
return isRecord(value) && Array.isArray(value["pageGlobs"]) && Array.isArray(value["apiGlobs"]);
|
|
5
|
+
}
|
|
6
|
+
export function nextOf(profile) {
|
|
7
|
+
const value = profile.stack["nextjs"];
|
|
8
|
+
return isNextData(value) ? value : EMPTY;
|
|
9
|
+
}
|