@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,102 @@
|
|
|
1
|
+
import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { appError } from "../domain/errors.js";
|
|
4
|
+
import { parseLockInfo, renderLockInfo, waitingMessage } from "../domain/perf.js";
|
|
5
|
+
import { err, ok } from "../domain/result.js";
|
|
6
|
+
export function pidAlive(pid) {
|
|
7
|
+
try {
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch (cause) {
|
|
12
|
+
return cause.code === "EPERM";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function readText(path) {
|
|
16
|
+
try {
|
|
17
|
+
return readFileSync(path, "utf8");
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function removeQuietly(path) {
|
|
24
|
+
try {
|
|
25
|
+
unlinkSync(path);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function create(path, text, pid) {
|
|
32
|
+
const temp = `${path}.${String(pid)}.${String(Math.random()).slice(2)}.tmp`;
|
|
33
|
+
writeFileSync(temp, text);
|
|
34
|
+
try {
|
|
35
|
+
linkSync(temp, path);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
removeQuietly(temp);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function staleText(path, isAlive) {
|
|
46
|
+
const text = readText(path);
|
|
47
|
+
if (text === null)
|
|
48
|
+
return "";
|
|
49
|
+
const info = parseLockInfo(text);
|
|
50
|
+
return info === null || !isAlive(info.pid) ? text : null;
|
|
51
|
+
}
|
|
52
|
+
function tryTake(path, text, options) {
|
|
53
|
+
if (create(path, text, options.pid))
|
|
54
|
+
return true;
|
|
55
|
+
const stale = staleText(path, options.isAlive);
|
|
56
|
+
if (stale === null)
|
|
57
|
+
return false;
|
|
58
|
+
if (stale !== "" && readText(path) === stale)
|
|
59
|
+
removeQuietly(path);
|
|
60
|
+
return create(path, text, options.pid);
|
|
61
|
+
}
|
|
62
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
63
|
+
async function takeAny(paths, text, options, deadline, announced) {
|
|
64
|
+
const taken = paths.find((path) => tryTake(path, text, options));
|
|
65
|
+
if (taken !== undefined)
|
|
66
|
+
return { path: taken };
|
|
67
|
+
if (Date.now() >= deadline)
|
|
68
|
+
return { path: null };
|
|
69
|
+
if (!announced) {
|
|
70
|
+
const holder = paths.map((path) => readText(path)).flatMap((content) => (content === null ? [] : [parseLockInfo(content)]))[0] ?? null;
|
|
71
|
+
options.log(waitingMessage(holder, options.repo));
|
|
72
|
+
}
|
|
73
|
+
await sleep(options.pollMs);
|
|
74
|
+
return takeAny(paths, text, options, deadline, true);
|
|
75
|
+
}
|
|
76
|
+
function busy(options) {
|
|
77
|
+
return appError("busy", `another guardrails run held the lock on ${options.repo} for ${String(Math.round(options.timeoutMs / 1000))}s`, {
|
|
78
|
+
fix: "Do not start another run while one is in progress: wait for it, then run `guardrails check <paths...>` on your folder. To wait longer, raise GUARDRAILS_LOCK_TIMEOUT_MS or pass --lock-timeout <seconds>.",
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
export async function acquireLease(options) {
|
|
82
|
+
mkdirSync(options.dir, { recursive: true });
|
|
83
|
+
const info = { pid: options.pid, repo: options.repo, startedAt: Date.now() };
|
|
84
|
+
const text = renderLockInfo(info);
|
|
85
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
86
|
+
const repoLock = await takeAny([join(options.dir, `repo-${options.repoKey}.lock`)], text, options, deadline, false);
|
|
87
|
+
if (repoLock.path === null)
|
|
88
|
+
return err(busy(options));
|
|
89
|
+
const slots = Array.from({ length: options.maxJobs }, (_unused, index) => join(options.dir, `machine-${String(index)}.lock`));
|
|
90
|
+
const slot = await takeAny(slots, text, options, deadline, false);
|
|
91
|
+
const held = slot.path === null ? [repoLock.path] : [repoLock.path, slot.path];
|
|
92
|
+
const release = () => {
|
|
93
|
+
held.filter((path) => readText(path) === text).forEach((path) => {
|
|
94
|
+
removeQuietly(path);
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
if (slot.path === null) {
|
|
98
|
+
release();
|
|
99
|
+
return err(busy(options));
|
|
100
|
+
}
|
|
101
|
+
return ok({ release });
|
|
102
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { relative, resolve } from "node:path";
|
|
2
|
+
import { appError } from "../domain/errors.js";
|
|
3
|
+
import { parseStrictJson, stringifyJson } from "../domain/json.js";
|
|
4
|
+
import { EMPTY_STATE, MARKER, parseState, parsePr } from "../domain/pr-loop.js";
|
|
5
|
+
import { err, ok } from "../domain/result.js";
|
|
6
|
+
import { runAsync, runSync } from "./exec.js";
|
|
7
|
+
import { readText, writeManaged } from "./fs.js";
|
|
8
|
+
const LOG_LIMIT = 400000;
|
|
9
|
+
const FIELDS = "number,url,headRefOid,headRefName,baseRefName,statusCheckRollup";
|
|
10
|
+
const ghMissing = (detail) => appError("missing-dependency", `gh could not read the pull request: ${detail}`, { fix: "Run from the PR branch with `gh auth status` green, or pass --pr <number>." });
|
|
11
|
+
export function readPr(root, number) {
|
|
12
|
+
const result = runSync("gh", ["pr", "view", ...(number === undefined ? [] : [number]), "--json", FIELDS], root);
|
|
13
|
+
if (result.status !== 0)
|
|
14
|
+
return err(ghMissing(result.stderr.trim() || "no pull request for this branch"));
|
|
15
|
+
const parsed = parseStrictJson(result.stdout);
|
|
16
|
+
const pr = parsed.ok ? parsePr(parsed.value) : null;
|
|
17
|
+
return pr === null ? err(ghMissing("unexpected gh output")) : ok(pr);
|
|
18
|
+
}
|
|
19
|
+
export function jobLog(root, jobId) {
|
|
20
|
+
const result = runSync("gh", ["api", "--allow-escape-sequences", `repos/{owner}/{repo}/actions/jobs/${jobId}/logs`], root);
|
|
21
|
+
return result.status === 0 ? result.stdout.slice(-LOG_LIMIT) : `could not download the log of job ${jobId}: ${result.stderr.trim()}`;
|
|
22
|
+
}
|
|
23
|
+
export async function waitForChecks(root, number) {
|
|
24
|
+
await runAsync("gh", ["pr", "checks", String(number), "--watch"], root);
|
|
25
|
+
}
|
|
26
|
+
function commentId(root, number) {
|
|
27
|
+
const query = `.[] | select(.body | contains("${MARKER}")) | .id`;
|
|
28
|
+
const result = runSync("gh", ["api", `repos/{owner}/{repo}/issues/${String(number)}/comments`, "--paginate", "--jq", query], root);
|
|
29
|
+
return result.status === 0 ? (result.stdout.split("\n").find((line) => line.trim() !== "")?.trim() ?? null) : null;
|
|
30
|
+
}
|
|
31
|
+
export function upsertComment(root, number, body) {
|
|
32
|
+
const id = commentId(root, number);
|
|
33
|
+
const target = id === null ? `repos/{owner}/{repo}/issues/${String(number)}/comments` : `repos/{owner}/{repo}/issues/comments/${id}`;
|
|
34
|
+
return runSync("gh", ["api", "--method", id === null ? "POST" : "PATCH", target, "--input", "-"], root, JSON.stringify({ body })).status === 0;
|
|
35
|
+
}
|
|
36
|
+
function statePath(root) {
|
|
37
|
+
const result = runSync("git", ["rev-parse", "--git-path", "guardrails-pr-loop.json"], root);
|
|
38
|
+
return result.status === 0 ? relative(root, resolve(root, result.stdout.trim())) : null;
|
|
39
|
+
}
|
|
40
|
+
export function readLoopState(root) {
|
|
41
|
+
const path = statePath(root);
|
|
42
|
+
return path === null ? EMPTY_STATE : parseState(readText(root, path));
|
|
43
|
+
}
|
|
44
|
+
export function writeLoopState(root, state) {
|
|
45
|
+
const path = statePath(root);
|
|
46
|
+
if (path !== null)
|
|
47
|
+
writeManaged(root, path, stringifyJson(state));
|
|
48
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { isRecord, parseStrictJson } from "../domain/json.js";
|
|
4
|
+
import { parseStoredResults } from "../domain/perf.js";
|
|
5
|
+
import { runSync } from "./exec.js";
|
|
6
|
+
import { sha256 } from "./hash.js";
|
|
7
|
+
const EXCLUDED = new Set([".guardrails/history.jsonl", ".guardrails/profile.json"]);
|
|
8
|
+
const LARGE_FILE_BYTES = 2 * 1024 * 1024;
|
|
9
|
+
const EXTRA_FILES = ["coverage/coverage-summary.json", "node_modules/.modules.yaml", "node_modules/.package-lock.json", "node_modules/.yarn-state.yml"];
|
|
10
|
+
function fileFingerprint(root, rel) {
|
|
11
|
+
const path = join(root, rel);
|
|
12
|
+
if (!existsSync(path))
|
|
13
|
+
return `${rel}\0missing`;
|
|
14
|
+
const stat = statSync(path);
|
|
15
|
+
if (!stat.isFile())
|
|
16
|
+
return `${rel}\0special`;
|
|
17
|
+
return stat.size > LARGE_FILE_BYTES ? `${rel}\0${String(stat.size)}\0${String(stat.mtimeMs)}` : sha256([`${rel}\0`, readFileSync(path, "latin1")]);
|
|
18
|
+
}
|
|
19
|
+
function gitLine(root, args) {
|
|
20
|
+
const result = runSync("git", args, root);
|
|
21
|
+
return result.status === 0 ? result.stdout.trim() : "";
|
|
22
|
+
}
|
|
23
|
+
export function treeKey(root, extra, baseBranch) {
|
|
24
|
+
const listed = runSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], root);
|
|
25
|
+
if (listed.status !== 0)
|
|
26
|
+
return null;
|
|
27
|
+
const files = [...new Set(listed.stdout.split("\0").filter((file) => file !== "" && !EXCLUDED.has(file)))].toSorted();
|
|
28
|
+
const refs = [gitLine(root, ["rev-parse", "HEAD"]), gitLine(root, ["rev-parse", "--verify", "--quiet", `origin/${baseBranch}`]), gitLine(root, ["rev-parse", "--verify", "--quiet", baseBranch])];
|
|
29
|
+
return sha256([...extra, ...refs, ...[...files, ...EXTRA_FILES].map((file) => fileFingerprint(root, file))].map((part) => `${part}\n`));
|
|
30
|
+
}
|
|
31
|
+
function slotPath(slot) {
|
|
32
|
+
return join(slot.dir, "results", slot.repoKey, `${slot.scopeKey}.json`);
|
|
33
|
+
}
|
|
34
|
+
export function readCached(slot, key) {
|
|
35
|
+
const path = slotPath(slot);
|
|
36
|
+
if (!existsSync(path))
|
|
37
|
+
return null;
|
|
38
|
+
const parsed = parseStrictJson(readFileSync(path, "utf8"));
|
|
39
|
+
if (!parsed.ok || !isRecord(parsed.value) || parsed.value["key"] !== key)
|
|
40
|
+
return null;
|
|
41
|
+
return parseStoredResults(parsed.value["results"]);
|
|
42
|
+
}
|
|
43
|
+
export function writeCached(slot, key, results) {
|
|
44
|
+
const path = slotPath(slot);
|
|
45
|
+
mkdirSync(join(slot.dir, "results", slot.repoKey), { recursive: true });
|
|
46
|
+
const temp = `${path}.${String(process.pid)}.tmp`;
|
|
47
|
+
writeFileSync(temp, JSON.stringify({ key, results }));
|
|
48
|
+
renameSync(temp, path);
|
|
49
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { jsTsPack } from "./js-ts/index.js";
|
|
2
|
+
import { nextjsPack } from "./nextjs/index.js";
|
|
3
|
+
import { nodePack } from "./node/index.js";
|
|
4
|
+
import { reactPack } from "./react/index.js";
|
|
5
|
+
import { reactNativePack } from "./react-native/index.js";
|
|
6
|
+
export const PACKS = Object.freeze([jsTsPack, nodePack, reactPack, reactNativePack, nextjsPack]);
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { OWN_PREFIX } from "../domain/catalog-specs.js";
|
|
2
|
+
import { capped } from "../../../core/domain/diagnostics.js";
|
|
3
|
+
import { eslintDiagnostic } from "../domain/diagnostics-js.js";
|
|
4
|
+
import { violationsOf } from "../domain/eslint-output.js";
|
|
5
|
+
import { PLUGIN_DIR, withLevel, withRule } from "../domain/eslint-state.js";
|
|
6
|
+
import { appError, EXIT } from "../../../core/domain/errors.js";
|
|
7
|
+
import { mergeChanges } from "../../../core/domain/changes.js";
|
|
8
|
+
import { UNIMPLEMENTED_MARKER, renderRule, renderRuleTest } from "../domain/rule-templates.js";
|
|
9
|
+
import { andThen, err, ok } from "../../../core/domain/result.js";
|
|
10
|
+
import { readAsset } from "../../../core/infra/assets.js";
|
|
11
|
+
import { hasEslint, lintRepo } from "../infra/eslint.js";
|
|
12
|
+
import { exists, readText, writeManaged } from "../../../core/infra/fs.js";
|
|
13
|
+
import { runNodeTest } from "../../../core/infra/hooks.js";
|
|
14
|
+
import { jsTs } from "../domain/data.js";
|
|
15
|
+
import { fixesFor } from "./fixes.js";
|
|
16
|
+
import { readState, wireEslintConfig, writeIndexAndConfig, writeState } from "./eslint-files.js";
|
|
17
|
+
const VIOLATION_LIMIT = 100;
|
|
18
|
+
function requireEslint(root) {
|
|
19
|
+
return hasEslint(root) ? null : appError("missing-dependency", "eslint is not installed in node_modules", { file: "package.json", fix: "Install eslint and typescript-eslint as exact devDependencies, then run add-rule again." });
|
|
20
|
+
}
|
|
21
|
+
function readSpec(request) {
|
|
22
|
+
const { name } = request;
|
|
23
|
+
const message = request.message === "" ? request.from : request.message;
|
|
24
|
+
if (message === undefined || message === "") {
|
|
25
|
+
return err(appError("usage", "add-rule needs --message <how to fix> (or --from <the correction you were given>)", {
|
|
26
|
+
rule: name,
|
|
27
|
+
fix: 'Example: guardrails add-rule no-fetch-in-components --selector "CallExpression[callee.name=\'fetch\']" --message "Call the API through the service layer" --bad "fetch(url);" --good "getUser(id);"',
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
const orNull = (value) => (value === "" ? null : value);
|
|
31
|
+
return ok({ name, message, selector: orNull(request.selector), bad: orNull(request.bad), good: orNull(request.good) });
|
|
32
|
+
}
|
|
33
|
+
function finish(ctx, name, changes, level, extra) {
|
|
34
|
+
const key = `${OWN_PREFIX}${name}`;
|
|
35
|
+
const { root, profile } = ctx;
|
|
36
|
+
return andThen(ok(profile), () => {
|
|
37
|
+
const lint = lintRepo(root, jsTs(profile));
|
|
38
|
+
if (!lint.ran)
|
|
39
|
+
return err(appError("verify-failed", `eslint could not run: ${lint.error ?? "unknown error"}`, { file: jsTs(profile).eslint.config ?? "eslint.config.mjs", rule: key, fix: "Fix the ESLint error above, then run add-rule again." }));
|
|
40
|
+
return andThen(readState(root), (state) => {
|
|
41
|
+
const violations = violationsOf(lint, key).map((violation) => eslintDiagnostic(violation, fixesFor(ctx.packs)));
|
|
42
|
+
const final = state.rules[key] === undefined || level === "off" ? level : violations.length === 0 ? "error" : "warn";
|
|
43
|
+
const written = state.rules[key] === undefined ? [] : [writeState(root, withLevel(state, key, final))];
|
|
44
|
+
const shown = capped(violations, VIOLATION_LIMIT);
|
|
45
|
+
return ok({
|
|
46
|
+
exit: violations.length > 0 ? EXIT.findings : EXIT.ok,
|
|
47
|
+
data: {
|
|
48
|
+
rule: key,
|
|
49
|
+
level: final,
|
|
50
|
+
changes: mergeChanges([...changes, ...written]),
|
|
51
|
+
violations: { count: violations.length, truncated: shown.truncated, items: shown.items },
|
|
52
|
+
...extra,
|
|
53
|
+
next: violations.length > 0 ? `Fix the ${violations.length} violations, then run \`guardrails add-rule ${name} --promote\`.` : "guardrails check --json",
|
|
54
|
+
},
|
|
55
|
+
text: [`${key}: level ${final}, ${violations.length} existing violations`, ...shown.items.slice(0, 10).map((item) => ` ${item.file}:${item.line} ${item.message}`)].join("\n"),
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function promote(ctx, name) {
|
|
61
|
+
const { root } = ctx;
|
|
62
|
+
const key = `${OWN_PREFIX}${name}`;
|
|
63
|
+
const missing = requireEslint(root);
|
|
64
|
+
if (missing !== null)
|
|
65
|
+
return err(missing);
|
|
66
|
+
return andThen(readState(root), (state) => {
|
|
67
|
+
if (state.rules[key] === undefined)
|
|
68
|
+
return err(appError("unknown-constraint", `${key} is not installed`, { rule: key, fix: `Create it first: guardrails add-rule ${name} --message "<how to fix>" --selector "<esquery>"` }));
|
|
69
|
+
if ((readText(root, `${PLUGIN_DIR}/rules/${name}.mjs`) ?? "").includes(UNIMPLEMENTED_MARKER)) {
|
|
70
|
+
return err(appError("not-applicable", `${key} is still a skeleton`, { file: `${PLUGIN_DIR}/rules/${name}.mjs`, rule: key, fix: "Implement create() or pass --selector when creating it; then add --bad/--good cases to its test." }));
|
|
71
|
+
}
|
|
72
|
+
const test = runNodeTest(root, `${PLUGIN_DIR}/rules/${name}.test.mjs`);
|
|
73
|
+
if (!test.ok)
|
|
74
|
+
return err(appError("verify-failed", `the rule test for ${key} fails`, { file: `${PLUGIN_DIR}/rules/${name}.test.mjs`, rule: key, fix: `Fix the rule or its test until \`node --test ${PLUGIN_DIR}/rules/${name}.test.mjs\` passes.\n${test.output}` }));
|
|
75
|
+
writeState(root, withLevel(state, key, "warn"));
|
|
76
|
+
return finish(ctx, name, [], "warn", { ruleTest: { ok: true } });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function create(ctx, request) {
|
|
80
|
+
const { root, profile } = ctx;
|
|
81
|
+
const { name } = request;
|
|
82
|
+
const ruleFile = `${PLUGIN_DIR}/rules/${name}.mjs`;
|
|
83
|
+
const key = `${OWN_PREFIX}${name}`;
|
|
84
|
+
if (exists(root, ruleFile)) {
|
|
85
|
+
return err(appError("conflict", `${ruleFile} already exists`, { file: ruleFile, rule: key, fix: `Edit the rule in place, or run \`guardrails add-rule ${name} --promote\` to re-check and promote it. guardrails never overwrites a rule.` }));
|
|
86
|
+
}
|
|
87
|
+
return andThen(readSpec(request), (spec) => andThen(readState(root), (state) => {
|
|
88
|
+
const files = request.files.map((glob) => glob.trim()).filter((glob) => glob !== "");
|
|
89
|
+
const entry = { level: spec.selector === null ? "off" : "warn", files: files.length > 0 ? files : jsTs(profile).paths.sourceGlobs };
|
|
90
|
+
const written = [
|
|
91
|
+
writeManaged(root, ruleFile, renderRule(spec)),
|
|
92
|
+
writeManaged(root, `${PLUGIN_DIR}/rules/${name}.test.mjs`, renderRuleTest(spec)),
|
|
93
|
+
writeManaged(root, `${PLUGIN_DIR}/rules/_rule-tester.mjs`, readAsset("eslint-rules/_rule-tester.mjs")),
|
|
94
|
+
writeState(root, withRule(state, key, entry)),
|
|
95
|
+
...writeIndexAndConfig(root),
|
|
96
|
+
];
|
|
97
|
+
return andThen(wireEslintConfig(ctx), (wiring) => {
|
|
98
|
+
const test = runNodeTest(root, `${PLUGIN_DIR}/rules/${name}.test.mjs`);
|
|
99
|
+
if (!test.ok) {
|
|
100
|
+
return err(appError("verify-failed", `the generated rule test fails: ${PLUGIN_DIR}/rules/${name}.test.mjs`, { file: `${PLUGIN_DIR}/rules/${name}.test.mjs`, rule: key, fix: `Make --selector match the --bad snippet and not the --good one, then edit the rule or its test.\n${test.output}` }));
|
|
101
|
+
}
|
|
102
|
+
const skeleton = spec.selector === null;
|
|
103
|
+
return finish(ctx, name, [...written, ...wiring], entry.level, {
|
|
104
|
+
status: skeleton ? "skeleton" : "created",
|
|
105
|
+
ruleTest: { ok: true },
|
|
106
|
+
needs: skeleton ? [`Implement create() in ${ruleFile} (pass --selector to generate it), then add --bad/--good cases to its test.`] : [],
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
export function addRuleJsTs(ctx, request) {
|
|
112
|
+
if (request.promote)
|
|
113
|
+
return promote(ctx, request.name);
|
|
114
|
+
const missing = requireEslint(ctx.root);
|
|
115
|
+
return missing !== null ? err(missing) : create(ctx, request);
|
|
116
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { objectAt } from "../../../core/domain/json.js";
|
|
2
|
+
import { readRuntime } from "../../../config/runtime.js";
|
|
3
|
+
import { scopeItems } from "../../../core/domain/perf.js";
|
|
4
|
+
import { timed, timedSync } from "../../../core/app/timing.js";
|
|
5
|
+
import { readJsonRecord, exists } from "../../../core/infra/fs.js";
|
|
6
|
+
import { jsTs } from "../domain/data.js";
|
|
7
|
+
import { EXACT_DEPS_RULE, REASON_RULE, dependencyDiagnostics, disableDiagnostics, failingReasons, ratchetDiagnostic, rulesAt, skippedTools, toolDiagnostics, topRules } from "../domain/report.js";
|
|
8
|
+
import { withLevel } from "../domain/eslint-state.js";
|
|
9
|
+
import { evaluateRatchet } from "../../../core/domain/ratchet.js";
|
|
10
|
+
import { readBaseline, writeBaseline } from "../../../core/infra/baseline.js";
|
|
11
|
+
import { missingStrictOptions } from "../domain/ts-options.js";
|
|
12
|
+
import { hasEslint, lintRepoAsync } from "../infra/eslint.js";
|
|
13
|
+
import { scanDisableDirectives } from "../infra/scan.js";
|
|
14
|
+
import { runTscAsync } from "../infra/tsc.js";
|
|
15
|
+
import { fixesFor } from "./fixes.js";
|
|
16
|
+
import { prRuleDiagnostics } from "./pr-rules.js";
|
|
17
|
+
import { readState, writeState } from "./eslint-files.js";
|
|
18
|
+
import { installDevCommand } from "../domain/profile-pure.js";
|
|
19
|
+
function missingFix(data) {
|
|
20
|
+
return `Install the tools (${installDevCommand(data.packageManager, ["eslint", "typescript-eslint", "typescript"])}) and run \`guardrails plan\` to see which constraints to apply.`;
|
|
21
|
+
}
|
|
22
|
+
async function runTools(root, data, paths) {
|
|
23
|
+
const lintTask = () => timed(() => (hasEslint(root) ? lintRepoAsync(root, data, paths) : Promise.resolve(null)));
|
|
24
|
+
const tscTask = async () => {
|
|
25
|
+
const run = await timed(() => (data.typescript.present ? runTscAsync(root) : Promise.resolve(null)));
|
|
26
|
+
return { ...run, value: run.value === null ? null : { ...run.value, diagnostics: scopeItems(run.value.diagnostics, paths) } };
|
|
27
|
+
};
|
|
28
|
+
if (readRuntime().maxJobs >= 2) {
|
|
29
|
+
const [lint, tsc] = await Promise.all([lintTask(), tscTask()]);
|
|
30
|
+
return { lint, tsc };
|
|
31
|
+
}
|
|
32
|
+
const lint = await lintTask();
|
|
33
|
+
const tsc = await tscTask();
|
|
34
|
+
return { lint, tsc };
|
|
35
|
+
}
|
|
36
|
+
function typeMetric(root, runs) {
|
|
37
|
+
const tsc = runs.tsc.value;
|
|
38
|
+
const options = exists(root, "tsconfig.json") ? objectAt(readJsonRecord(root, "tsconfig.json") ?? {}, "compilerOptions") : null;
|
|
39
|
+
return { errors: tsc?.ran === true ? tsc.diagnostics.length : null, missingStrictOptions: options === null ? [] : missingStrictOptions(options) };
|
|
40
|
+
}
|
|
41
|
+
function lintMetric(runs) {
|
|
42
|
+
const lint = runs.lint.value;
|
|
43
|
+
const violations = lint?.violations ?? [];
|
|
44
|
+
const errors = violations.filter((item) => item.severity === "error").length;
|
|
45
|
+
return { ran: lint?.ran === true, errors, warnings: violations.length - errors, byRule: topRules(violations), skipped: lint === null ? "eslint is not installed" : lint.error };
|
|
46
|
+
}
|
|
47
|
+
function ratchetOf(ctx, runs) {
|
|
48
|
+
const state = readState(ctx.root);
|
|
49
|
+
const data = jsTs(ctx.profile);
|
|
50
|
+
const baseline = readBaseline(ctx.root);
|
|
51
|
+
const loose = data.exactDeps.script ? data.exactDeps.loose.length : 0;
|
|
52
|
+
const exact = loose > 0 || baseline.rules[EXACT_DEPS_RULE] !== undefined ? [EXACT_DEPS_RULE] : [];
|
|
53
|
+
const warnRules = [...(state.ok ? rulesAt(state.value, "warn") : []), ...exact];
|
|
54
|
+
const lintCounts = (runs.lint.value?.violations ?? []).reduce((acc, item) => ({ ...acc, [item.rule]: (acc[item.rule] ?? 0) + 1 }), {});
|
|
55
|
+
const counts = { ...lintCounts, [EXACT_DEPS_RULE]: loose };
|
|
56
|
+
return { counts, warnRules, result: evaluateRatchet({ baseline, counts, warnRules }) };
|
|
57
|
+
}
|
|
58
|
+
function settle(ctx, runs, paths, ratchet) {
|
|
59
|
+
if (paths.length > 0 || runs.lint.value?.ran !== true)
|
|
60
|
+
return [];
|
|
61
|
+
const state = readState(ctx.root);
|
|
62
|
+
const promoted = ratchet.result.promotable.filter((rule) => state.ok && state.value.rules[rule] !== undefined);
|
|
63
|
+
if (state.ok && promoted.length > 0)
|
|
64
|
+
writeState(ctx.root, promoted.reduce((next, rule) => withLevel(next, rule, "error"), state.value));
|
|
65
|
+
const before = readBaseline(ctx.root);
|
|
66
|
+
const changed = JSON.stringify(before.rules) !== JSON.stringify(ratchet.result.next.rules);
|
|
67
|
+
if (changed && ctx.readOnly !== true)
|
|
68
|
+
writeBaseline(ctx.root, ratchet.result.next);
|
|
69
|
+
return promoted;
|
|
70
|
+
}
|
|
71
|
+
function metricsOf(ctx, runs, scan, ratchet, promoted) {
|
|
72
|
+
const lint = lintMetric(runs);
|
|
73
|
+
const types = typeMetric(ctx.root, runs);
|
|
74
|
+
const withoutReason = scan.filter((item) => !item.hasReason);
|
|
75
|
+
const debtCount = ratchet.warnRules.reduce((sum, rule) => sum + (ratchet.counts[rule] ?? 0), 0);
|
|
76
|
+
const regressions = ratchet.result.regressions.map((entry) => `${entry.rule} ${String(entry.count)} > baseline ${String(entry.baseline)}`);
|
|
77
|
+
return {
|
|
78
|
+
failing: failingReasons({ errors: lint.errors, regressions, disablesWithoutReason: withoutReason.length, typeErrors: types.errors }),
|
|
79
|
+
metrics: {
|
|
80
|
+
lint,
|
|
81
|
+
eslintDisables: { total: scan.length, withoutReason: withoutReason.length, locations: withoutReason.slice(0, 50).map((item) => `${item.file}:${item.line}`) },
|
|
82
|
+
ratchet: { rulesAtWarn: ratchet.warnRules, debt: debtCount, regressions: ratchet.result.regressions, tolerated: ratchet.result.tolerated, promoted },
|
|
83
|
+
types,
|
|
84
|
+
},
|
|
85
|
+
lines: [
|
|
86
|
+
`lint: ${lint.errors} errors, ${lint.warnings} warnings`,
|
|
87
|
+
`eslint-disable: ${scan.length} total, ${withoutReason.length} without reason`,
|
|
88
|
+
`ratchet: ${ratchet.warnRules.length} rules at warn, ${debtCount} violations of debt${promoted.length > 0 ? `, promoted to error: ${promoted.join(", ")}` : ""}`,
|
|
89
|
+
`types: ${types.errors === null ? "not checked" : `${types.errors} errors`}`,
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export async function analyzeJsTs(ctx, paths) {
|
|
94
|
+
const data = jsTs(ctx.profile);
|
|
95
|
+
const runs = await runTools(ctx.root, data, paths);
|
|
96
|
+
const scan = timedSync(() => scopeItems(scanDisableDirectives(ctx.root, data), paths));
|
|
97
|
+
const base = toolDiagnostics(runs.lint.value, runs.tsc.value, fixesFor(ctx.packs));
|
|
98
|
+
const handled = new Set(base.filter((item) => item.rule === REASON_RULE).map((item) => `${item.file}:${item.line}`));
|
|
99
|
+
const ratchet = ratchetOf(ctx, runs);
|
|
100
|
+
const promoted = settle(ctx, runs, paths, ratchet);
|
|
101
|
+
return {
|
|
102
|
+
pack: "js-ts",
|
|
103
|
+
ran: runs.lint.value?.ran === true || runs.tsc.value?.ran === true,
|
|
104
|
+
debt: Object.fromEntries(ratchet.warnRules.map((rule) => [rule, ratchet.counts[rule] ?? 0])),
|
|
105
|
+
diagnostics: [...base, ...ratchet.result.regressions.map(ratchetDiagnostic), ...prRuleDiagnostics(ctx, paths), ...scopeItems(dependencyDiagnostics(data), paths), ...disableDiagnostics(scan.value, handled)],
|
|
106
|
+
skipped: skippedTools(runs.lint.value, runs.tsc.value),
|
|
107
|
+
missingFix: missingFix(data),
|
|
108
|
+
phasesMs: { eslint: runs.lint.ms, tsc: runs.tsc.ms, scan: scan.ms },
|
|
109
|
+
...metricsOf(ctx, runs, scan.value, ratchet, promoted),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { objectAt } from "../../../core/domain/json.js";
|
|
2
|
+
import { map, ok } from "../../../core/domain/result.js";
|
|
3
|
+
import { editJsonFile, readJsonRecord } from "../../../core/infra/fs.js";
|
|
4
|
+
const PREPARE = "git config core.hooksPath .githooks || true";
|
|
5
|
+
const prepareOf = (root) => objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts")["prepare"];
|
|
6
|
+
export const JS_TS_BOOTSTRAP = {
|
|
7
|
+
active: ({ root }) => {
|
|
8
|
+
const prepare = prepareOf(root);
|
|
9
|
+
return typeof prepare === "string" && prepare.includes("core.hooksPath");
|
|
10
|
+
},
|
|
11
|
+
ensure: ({ root }) => {
|
|
12
|
+
if (typeof prepareOf(root) === "string")
|
|
13
|
+
return ok([]);
|
|
14
|
+
return map(editJsonFile(root, "package.json", (value) => ({ ...value, scripts: { ...objectAt(value, "scripts"), prepare: PREPARE } }), false), (change) => [change]);
|
|
15
|
+
},
|
|
16
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { OWN_PREFIX, sampleFile } from "../domain/catalog-specs.js";
|
|
2
|
+
import { UNUSED_DIRECTIVE_RULE, severityOf, violationsOf } from "../domain/eslint-output.js";
|
|
3
|
+
import { RULES_JSON, userConfigHasTypedParser, withRule } from "../domain/eslint-state.js";
|
|
4
|
+
import { appError } from "../../../core/domain/errors.js";
|
|
5
|
+
import { isRecord } from "../../../core/domain/json.js";
|
|
6
|
+
import { andThen, err, ok } from "../../../core/domain/result.js";
|
|
7
|
+
import { jsTs } from "../domain/data.js";
|
|
8
|
+
import { hasEslint, lintRepo, printConfigRules, probeRules } from "../infra/eslint.js";
|
|
9
|
+
import { readText } from "../../../core/infra/fs.js";
|
|
10
|
+
import { copyOwnRule, readState, wireEslintConfig, writeIndexAndConfig, writeState } from "./eslint-files.js";
|
|
11
|
+
const isOwn = (name) => name.startsWith(OWN_PREFIX);
|
|
12
|
+
const ownId = (def) => def.name.slice(OWN_PREFIX.length);
|
|
13
|
+
function baseNotApplicable(profile) {
|
|
14
|
+
if (!jsTs(profile).typescript.present)
|
|
15
|
+
return "TypeScript not detected";
|
|
16
|
+
return jsTs(profile).eslint.config !== null && !jsTs(profile).eslint.flat ? "legacy .eslintrc config; guardrails needs ESLint flat config (eslint.config.*)" : null;
|
|
17
|
+
}
|
|
18
|
+
function probeFilename(profile, def) {
|
|
19
|
+
const scoped = def?.files?.(profile)[0];
|
|
20
|
+
if (scoped !== undefined)
|
|
21
|
+
return sampleFile(scoped);
|
|
22
|
+
const first = jsTs(profile).paths.sourceGlobs[0];
|
|
23
|
+
return `${first === undefined ? "." : (first.split("/**")[0] ?? ".")}/__guardrails_probe__.ts`;
|
|
24
|
+
}
|
|
25
|
+
function requirements(profile, usesTypescriptEslint) {
|
|
26
|
+
const { eslint } = jsTs(profile);
|
|
27
|
+
const needsPlugin = usesTypescriptEslint ? !eslint.typescriptPlugin : eslint.config === null && !eslint.typescriptEslintPackage;
|
|
28
|
+
return [
|
|
29
|
+
...(eslint.installed ? [] : [{ pkg: "eslint", reason: "guardrails rules run through ESLint" }]),
|
|
30
|
+
...(needsPlugin ? [{ pkg: "typescript-eslint", reason: "TypeScript parser and @typescript-eslint rules" }] : []),
|
|
31
|
+
];
|
|
32
|
+
}
|
|
33
|
+
function entryFor(def, profile, level) {
|
|
34
|
+
const options = def.options?.(profile);
|
|
35
|
+
const ignores = def.ignores?.(profile);
|
|
36
|
+
return {
|
|
37
|
+
level,
|
|
38
|
+
files: def.files?.(profile) ?? jsTs(profile).paths.sourceGlobs,
|
|
39
|
+
...(ignores === undefined || ignores.length === 0 ? {} : { ignores }),
|
|
40
|
+
...(options === undefined ? {} : { options }),
|
|
41
|
+
...(def.typed === true ? { typed: true } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function warnState(ctx, current, defs, linterWarn) {
|
|
45
|
+
const config = jsTs(ctx.profile).eslint.config;
|
|
46
|
+
const configText = config === null ? "" : (readText(ctx.root, config) ?? "");
|
|
47
|
+
const typedParser = current.typedParser || (defs.some((def) => def.typed === true) && !userConfigHasTypedParser(configText));
|
|
48
|
+
const rules = defs.reduce((state, def) => withRule(state, def.name, entryFor(def, ctx.profile, current.rules[def.name]?.level === "error" ? "error" : "warn")), { ...current, typedParser });
|
|
49
|
+
const unused = linterWarn && current.linterOptions.reportUnusedDisableDirectives === undefined ? { reportUnusedDisableDirectives: "warn" } : current.linterOptions;
|
|
50
|
+
return { ...rules, linterOptions: unused };
|
|
51
|
+
}
|
|
52
|
+
function promote(ctx, defs, linterWarn, base, lint) {
|
|
53
|
+
const levels = Object.fromEntries(defs.map((def) => [def.name, violationsOf(lint, def.name).length === 0 ? "error" : "warn"]));
|
|
54
|
+
const withLevels = defs.reduce((state, def) => withRule(state, def.name, entryFor(def, ctx.profile, levels[def.name] === "error" ? "error" : "warn")), base);
|
|
55
|
+
const unusedClean = violationsOf(lint, UNUSED_DIRECTIVE_RULE).length === 0;
|
|
56
|
+
const linterOptions = linterWarn ? { reportUnusedDisableDirectives: unusedClean ? "error" : "warn" } : withLevels.linterOptions;
|
|
57
|
+
return { state: { ...withLevels, linterOptions }, levels };
|
|
58
|
+
}
|
|
59
|
+
export function installEslintRules(ctx, defs, linterWarn) {
|
|
60
|
+
const { root } = ctx;
|
|
61
|
+
if (!hasEslint(root)) {
|
|
62
|
+
return err(appError("missing-dependency", "eslint is not installed in node_modules", { file: "package.json", fix: "Install eslint (and typescript-eslint) as exact devDependencies with the package manager, then run apply again." }));
|
|
63
|
+
}
|
|
64
|
+
return andThen(readState(root), (current) => {
|
|
65
|
+
const base = warnState(ctx, current, defs, linterWarn);
|
|
66
|
+
const written = [...defs.filter((def) => isOwn(def.name)).flatMap((def) => copyOwnRule(root, ownId(def))), writeState(root, base), ...writeIndexAndConfig(root)];
|
|
67
|
+
return andThen(wireEslintConfig(ctx), (wiring) => finalize(ctx, defs, linterWarn, base, [...written, ...wiring]));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function finalize(ctx, defs, linterWarn, base, changes) {
|
|
71
|
+
const lint = lintRepo(ctx.root, jsTs(ctx.profile));
|
|
72
|
+
if (!lint.ran) {
|
|
73
|
+
return err(appError("verify-failed", `eslint could not run after installing the rules: ${lint.error ?? "unknown error"}`, { file: jsTs(ctx.profile).eslint.config ?? "eslint.config.mjs", fix: "Fix the ESLint configuration error above (missing plugin or parser is the usual cause), then run apply again. Files written so far were kept." }));
|
|
74
|
+
}
|
|
75
|
+
const promoted = promote(ctx, defs, linterWarn, base, lint);
|
|
76
|
+
const pending = defs.filter((def) => promoted.levels[def.name] === "warn").map((def) => def.name);
|
|
77
|
+
return ok({
|
|
78
|
+
changes: [...changes, writeState(ctx.root, promoted.state)],
|
|
79
|
+
notes: pending.length === 0 ? [] : [`${pending.join(", ")} stay at warn until violations reach 0: fix them (guardrails check), then run the same apply again to promote them to error.`],
|
|
80
|
+
violations: defs.flatMap((def) => violationsOf(lint, def.name)),
|
|
81
|
+
levels: promoted.levels,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function registeredCheck(def, state) {
|
|
85
|
+
const entry = state.rules[def.name];
|
|
86
|
+
return { name: `${def.name} registered`, ok: entry !== undefined, detail: entry === undefined ? `missing from ${RULES_JSON}` : `level ${entry.level}` };
|
|
87
|
+
}
|
|
88
|
+
function activeCheck(def, configured) {
|
|
89
|
+
const severity = configured === null ? null : severityOf(configured[def.name]);
|
|
90
|
+
return { name: `${def.name} active in ESLint`, ok: severity !== null && severity !== "off", detail: severity === null ? "eslint --print-config failed; fix the ESLint config" : `eslint resolves it as ${severity}` };
|
|
91
|
+
}
|
|
92
|
+
function probeCheck(ctx, def) {
|
|
93
|
+
if (def.probe === undefined || ctx.gradual === true || !hasEslint(ctx.root))
|
|
94
|
+
return [];
|
|
95
|
+
const probe = probeRules(ctx.root, probeFilename(ctx.profile, def), def.probe);
|
|
96
|
+
if (!probe.usable)
|
|
97
|
+
return [];
|
|
98
|
+
return [{ name: `${def.name} fires on a violating snippet`, ok: probe.rules.has(def.name), detail: probe.rules.has(def.name) ? "probe reported the rule" : "probe did not report the rule" }];
|
|
99
|
+
}
|
|
100
|
+
function ruleChecks(ctx, def, state, configured) {
|
|
101
|
+
return [registeredCheck(def, state), activeCheck(def, configured), ...probeCheck(ctx, def)];
|
|
102
|
+
}
|
|
103
|
+
export function verifyEslintRules(ctx, defs) {
|
|
104
|
+
const state = readState(ctx.root);
|
|
105
|
+
if (!state.ok)
|
|
106
|
+
return [{ name: RULES_JSON, ok: false, detail: state.error.message }];
|
|
107
|
+
const files = [...new Set(defs.map((def) => probeFilename(ctx.profile, def)))];
|
|
108
|
+
const configs = Object.fromEntries(files.map((file) => [file, hasEslint(ctx.root) ? printConfigRules(ctx.root, file) : null]));
|
|
109
|
+
return defs.flatMap((def) => ruleChecks(ctx, def, state.value, configs[probeFilename(ctx.profile, def)] ?? null));
|
|
110
|
+
}
|
|
111
|
+
function isBatchPayload(value) {
|
|
112
|
+
return isRecord(value) && Array.isArray(value["defs"]) && typeof value["linterWarn"] === "boolean";
|
|
113
|
+
}
|
|
114
|
+
function runBatch(ctx, payloads) {
|
|
115
|
+
const items = payloads.filter(isBatchPayload);
|
|
116
|
+
return installEslintRules(ctx, items.flatMap((item) => item.defs), items.some((item) => item.linterWarn));
|
|
117
|
+
}
|
|
118
|
+
const batchOf = (payload) => ({ id: "eslint", payload, run: runBatch });
|
|
119
|
+
export function eslintConstraint(spec) {
|
|
120
|
+
const usesTs = spec.rules.some((def) => def.name.startsWith("@typescript-eslint/"));
|
|
121
|
+
return {
|
|
122
|
+
batch: batchOf({ defs: spec.rules, linterWarn: false }),
|
|
123
|
+
id: spec.id,
|
|
124
|
+
title: spec.title,
|
|
125
|
+
layer: "lint",
|
|
126
|
+
why: spec.why,
|
|
127
|
+
notApplicable: (profile) => baseNotApplicable(profile) ?? spec.applies?.(profile) ?? null,
|
|
128
|
+
requires: (profile) => requirements(profile, usesTs),
|
|
129
|
+
isInstalled: ({ root }) => {
|
|
130
|
+
const state = readState(root);
|
|
131
|
+
return state.ok && spec.rules.every((def) => state.value.rules[def.name] !== undefined);
|
|
132
|
+
},
|
|
133
|
+
install: (ctx) => installEslintRules(ctx, spec.rules, false),
|
|
134
|
+
verify: (ctx) => verifyEslintRules(ctx, spec.rules),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export const unusedDisableDirectives = {
|
|
138
|
+
batch: batchOf({ defs: [], linterWarn: true }),
|
|
139
|
+
id: "unused-disable-directives",
|
|
140
|
+
title: "Unused eslint-disable directives fail the lint",
|
|
141
|
+
layer: "lint",
|
|
142
|
+
why: "A disable that no longer suppresses anything hides that the code was fixed; the directive should be deleted.",
|
|
143
|
+
notApplicable: baseNotApplicable,
|
|
144
|
+
requires: (profile) => requirements(profile, false),
|
|
145
|
+
isInstalled: ({ root }) => {
|
|
146
|
+
const state = readState(root);
|
|
147
|
+
return state.ok && state.value.linterOptions.reportUnusedDisableDirectives !== undefined;
|
|
148
|
+
},
|
|
149
|
+
install: (ctx) => installEslintRules(ctx, [], true),
|
|
150
|
+
verify: ({ root }) => {
|
|
151
|
+
const state = readState(root);
|
|
152
|
+
const level = state.ok ? state.value.linterOptions.reportUnusedDisableDirectives : undefined;
|
|
153
|
+
return [{ name: "reportUnusedDisableDirectives set", ok: level !== undefined, detail: level ?? `missing from ${RULES_JSON}` }];
|
|
154
|
+
},
|
|
155
|
+
};
|