@antelopejs/tooling-configs 0.2.6 → 0.2.7

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.
@@ -0,0 +1,119 @@
1
+ import { r as MEASURE_ENV, s as readCeilings } from "./ceilings-BSw9p4YB.mjs";
2
+ import { n as renamedPaths } from "./renames-BGO4dWJ8.mjs";
3
+ import { a as repositoryPath } from "./files-BMxKg5IR.mjs";
4
+ import { createRequire } from "node:module";
5
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+ //#region src/guardrails/oxlint.ts
9
+ function resolveOxlint(root) {
10
+ try {
11
+ const require = createRequire(join(root, "package.json"));
12
+ return join(dirname(require.resolve("oxlint/package.json")), "bin/oxlint");
13
+ } catch {
14
+ throw new Error("oxlint is not installed in this repository. Install dependencies first.");
15
+ }
16
+ }
17
+ function ruleId(code) {
18
+ const match = /^([^()]+)\(([^()]+)\)$/.exec(code);
19
+ if (!match) throw new Error(`Cannot measure oxlint diagnostic code ${JSON.stringify(code)}. Fix parser or configuration errors before recording a baseline.`);
20
+ const [, plugin, rule] = match;
21
+ return `${plugin === "typescript-eslint" ? "typescript" : plugin}/${rule}`;
22
+ }
23
+ function parseDiagnostics(text, root) {
24
+ const report = JSON.parse(text);
25
+ if (!Array.isArray(report?.diagnostics)) throw new Error("oxlint did not return a JSON diagnostics array.");
26
+ return report.diagnostics.map((item) => {
27
+ const file = repositoryPath(root, item.filename);
28
+ const span = item.labels?.[0]?.span;
29
+ return {
30
+ rule: ruleId(item.code),
31
+ file,
32
+ location: span ? `${file}:${span.line}:${span.column}` : file,
33
+ message: item.message,
34
+ line: span?.line,
35
+ help: item.help
36
+ };
37
+ });
38
+ }
39
+ function lintDiagnostics(root, config, files) {
40
+ const binary = resolveOxlint(root);
41
+ const temporary = config === void 0 ? void 0 : mkdtempSync(join(root, ".antelopejs-measure.generated."));
42
+ try {
43
+ const args = [
44
+ binary,
45
+ "-f",
46
+ "json"
47
+ ];
48
+ if (temporary) {
49
+ const path = join(temporary, "oxlint.config.ts");
50
+ writeFileSync(path, config ?? "");
51
+ args.push("--config", path, "--ignore-pattern", `${basename(temporary)}/**`);
52
+ }
53
+ if (files) args.push("--no-error-on-unmatched-pattern", "--", ...files);
54
+ const result = spawnSync(process.execPath, args, {
55
+ cwd: root,
56
+ encoding: "utf8",
57
+ env: {
58
+ ...process.env,
59
+ [MEASURE_ENV]: "1"
60
+ },
61
+ maxBuffer: 67108864
62
+ });
63
+ if (result.error) throw result.error;
64
+ if (result.status !== 0 && result.status !== 1) throw new Error(`oxlint failed (${result.status ?? result.signal}): ${result.stderr || result.stdout}`);
65
+ const diagnostics = parseDiagnostics(result.stdout, root);
66
+ if (result.status !== 0 && diagnostics.length === 0) throw new Error(`oxlint failed without diagnostics: ${result.stderr || result.stdout}`);
67
+ return diagnostics;
68
+ } finally {
69
+ if (temporary) rmSync(temporary, {
70
+ recursive: true,
71
+ force: true
72
+ });
73
+ }
74
+ }
75
+ //#endregion
76
+ //#region src/guardrails/staged-ratchet.ts
77
+ /** The line ranges each staged file adds against HEAD, following renames. */
78
+ function stagedAdditions(root, targets) {
79
+ const renames = renamedPaths(root, true);
80
+ const additions = /* @__PURE__ */ new Map();
81
+ for (const file of targets) {
82
+ const diff = execFileSync("git", [
83
+ "diff",
84
+ "--cached",
85
+ "--no-ext-diff",
86
+ "--no-color",
87
+ "--unified=0",
88
+ "--find-renames",
89
+ "--",
90
+ ...[renames.get(file), file].filter((path) => path !== void 0)
91
+ ], {
92
+ cwd: root,
93
+ encoding: "utf8"
94
+ });
95
+ additions.set(file, Array.from(diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm), ([, line, count]) => ({
96
+ start: Number(line),
97
+ end: Number(line) + Number(count ?? 1) - 1
98
+ })));
99
+ }
100
+ return additions;
101
+ }
102
+ function stagedRatchet(root, files) {
103
+ const targets = files ?? execFileSync("git", [
104
+ "diff",
105
+ "--cached",
106
+ "--name-only",
107
+ "--diff-filter=ACMR",
108
+ "-z"
109
+ ], {
110
+ cwd: root,
111
+ encoding: "utf8"
112
+ }).split("\0").filter(Boolean);
113
+ if (!targets.length) return [];
114
+ const additions = stagedAdditions(root, targets);
115
+ const ceilings = readCeilings(root);
116
+ return lintDiagnostics(root, void 0, targets).filter(({ rule, file, line }) => Object.hasOwn(ceilings.rules, rule) && line !== void 0 && additions.get(file)?.some(({ start, end }) => line >= start && line <= end)).map((diagnostic) => `${diagnostic.location}: ${diagnostic.message} [${diagnostic.rule}]\n Fix: ${diagnostic.help ?? "Resolve this finding on the added line; the ceiling covers only legacy findings on untouched lines."}`);
117
+ }
118
+ //#endregion
119
+ export { stagedRatchet as n, lintDiagnostics as r, stagedAdditions as t };
@@ -0,0 +1,144 @@
1
+ import { n as renamedPaths } from "./renames-BGO4dWJ8.mjs";
2
+ import { n as changedFiles } from "./files-BMxKg5IR.mjs";
3
+ import { t as stagedAdditions } from "./staged-ratchet-CJHjp2kx.mjs";
4
+ import { n as revisionSuppressions, r as worktreeSuppressions, t as countSuppressions } from "./suppressions-CgGa-kh7.mjs";
5
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+ //#region src/guardrails/suppression-budget.ts
9
+ /** The per-repository suppression budget, at the repository root. It is permanent: nothing deletes it, even at zero. */
10
+ const SUPPRESSIONS_FILE = "guardrails.suppressions.json";
11
+ /** What a failure tells the author to do. */
12
+ const SUPPRESSION_FIX = "Fix: fix the code, or remove another suppression of the same kind; a rule that keeps needing suppressions should be changed in the preset.";
13
+ const LABELS = {
14
+ tsExpectError: "`@ts-expect-error`",
15
+ tsIgnore: "`@ts-ignore`",
16
+ safety: "`SAFETY:` comments"
17
+ };
18
+ function labelOf(suppression) {
19
+ return suppression.kind === "rule" ? `lint rule \`${suppression.rule}\`` : LABELS[suppression.kind];
20
+ }
21
+ function limitOf(budget, suppression) {
22
+ return suppression.kind === "rule" ? budget.rules[suppression.rule] ?? 0 : budget[suppression.kind];
23
+ }
24
+ function count(value, source) {
25
+ if (value === void 0) throw new Error(`${source} is missing`);
26
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${source} must be a non-negative integer`);
27
+ return value;
28
+ }
29
+ /** Parses a budget, rejecting a missing field and anything but non-negative integer ceilings. */
30
+ function parseBudget(text, source) {
31
+ const parsed = JSON.parse(text);
32
+ if (parsed === null || Array.isArray(parsed)) throw new Error(`${source}: expected an object with "rules"`);
33
+ const rules = parsed.rules ?? {};
34
+ if (rules === null || Array.isArray(rules)) throw new Error(`${source}: rules must be an object of counts`);
35
+ return {
36
+ rules: Object.fromEntries(Object.entries(rules).map(([rule, limit]) => [rule, count(limit, `${source}: rules "${rule}"`)])),
37
+ tsExpectError: count(parsed.tsExpectError, `${source}: tsExpectError`),
38
+ tsIgnore: count(parsed.tsIgnore, `${source}: tsIgnore`),
39
+ safety: count(parsed.safety, `${source}: safety`)
40
+ };
41
+ }
42
+ /** Serializes a budget with sorted rules, zero ceilings kept, so rewriting an unchanged budget is a no-op. */
43
+ function formatBudget(budget) {
44
+ const rules = Object.fromEntries(Object.entries(budget.rules).sort(([a], [b]) => a.localeCompare(b)));
45
+ return `${JSON.stringify({
46
+ ...budget,
47
+ rules
48
+ }, null, 2)}\n`;
49
+ }
50
+ /** The budget sync writes at adoption: the committed one when the file was only deleted, so recreating it never raises a ceiling, else the current counts. */
51
+ function adoptedBudget(root) {
52
+ const committed = spawnSync("git", ["show", `HEAD:${SUPPRESSIONS_FILE}`], {
53
+ cwd: root,
54
+ encoding: "utf8"
55
+ });
56
+ if (committed.status === 0) return committed.stdout;
57
+ return formatBudget(countSuppressions(worktreeSuppressions(root)));
58
+ }
59
+ function groupByKey(suppressions) {
60
+ const groups = /* @__PURE__ */ new Map();
61
+ for (const suppression of suppressions) {
62
+ const key = labelOf(suppression);
63
+ groups.set(key, [...groups.get(key) ?? [], suppression]);
64
+ }
65
+ return groups;
66
+ }
67
+ function lowered(budget, current) {
68
+ return {
69
+ rules: Object.fromEntries(Object.entries(budget.rules).map(([rule, limit]) => [rule, Math.min(limit, current.rules[rule] ?? 0)])),
70
+ tsExpectError: Math.min(budget.tsExpectError, current.tsExpectError),
71
+ tsIgnore: Math.min(budget.tsIgnore, current.tsIgnore),
72
+ safety: Math.min(budget.safety, current.safety)
73
+ };
74
+ }
75
+ /**
76
+ * Fails each budget key whose count in the working tree is above its ceiling,
77
+ * listing the suppressions in the files this change touches (all of them when
78
+ * it touches none). `update` lowers every ceiling to its current count; no
79
+ * command ever raises one.
80
+ */
81
+ function checkSuppressions(root, update = false) {
82
+ const path = join(root, SUPPRESSIONS_FILE);
83
+ if (!existsSync(path)) throw new Error(`${SUPPRESSIONS_FILE} is missing. Run antelopejs-sync.`);
84
+ const budget = parseBudget(readFileSync(path, "utf8"), SUPPRESSIONS_FILE);
85
+ const suppressions = worktreeSuppressions(root);
86
+ const changed = changedFiles(root);
87
+ const failures = [];
88
+ for (const [key, found] of groupByKey(suppressions)) {
89
+ const limit = limitOf(budget, found[0]);
90
+ if (found.length <= limit) continue;
91
+ const inChanged = found.filter(({ file }) => changed.has(file));
92
+ const shown = inChanged.length ? inChanged : found;
93
+ failures.push(`${SUPPRESSIONS_FILE}: ${key}: ${found.length} exceeds ceiling ${limit}.`, ...shown.map(({ file, line }) => ` ${file}:${line}`), ...shown.length < found.length ? [` ...and ${found.length - shown.length} in files this change does not touch.`] : []);
94
+ }
95
+ if (update) writeFileSync(path, formatBudget(lowered(budget, countSuppressions(suppressions))));
96
+ return failures.length ? [...failures, SUPPRESSION_FIX] : [];
97
+ }
98
+ function budgetAt(root, revision) {
99
+ const result = spawnSync("git", ["show", `${revision}:${SUPPRESSIONS_FILE}`], {
100
+ cwd: root,
101
+ encoding: "utf8"
102
+ });
103
+ return result.status === 0 ? parseBudget(result.stdout, `${revision || "index"}:${SUPPRESSIONS_FILE}`) : void 0;
104
+ }
105
+ function stagedNames(root, filter) {
106
+ return execFileSync("git", [
107
+ "diff",
108
+ "--cached",
109
+ "--name-only",
110
+ "--find-renames",
111
+ `--diff-filter=${filter}`,
112
+ "-z"
113
+ ], {
114
+ cwd: root,
115
+ encoding: "utf8"
116
+ }).split("\0").filter(Boolean);
117
+ }
118
+ /**
119
+ * Compares the staged files' suppressions with those files at HEAD, rename
120
+ * sources and deleted files included, and fails each key that rises by more
121
+ * than the staged budget raises its ceiling. A commit that first adds the
122
+ * budget is not compared.
123
+ */
124
+ function stagedSuppressions(root) {
125
+ const head = budgetAt(root, "HEAD");
126
+ if (head === void 0) return [];
127
+ const index = budgetAt(root, "") ?? head;
128
+ const renames = renamedPaths(root, true);
129
+ const staged = stagedNames(root, "ACMR");
130
+ const previous = [...staged.map((file) => renames.get(file) ?? file), ...stagedNames(root, "D")];
131
+ const before = groupByKey(revisionSuppressions(root, "HEAD", previous));
132
+ const after = groupByKey(revisionSuppressions(root, "", staged));
133
+ const additions = stagedAdditions(root, [...new Set([...after.values()].flat().map(({ file }) => file))]);
134
+ const failures = [];
135
+ for (const [key, found] of after) {
136
+ const rise = found.length - (before.get(key)?.length ?? 0);
137
+ if (rise <= Math.max(0, limitOf(index, found[0]) - limitOf(head, found[0]))) continue;
138
+ const added = found.filter(({ file, line }) => additions.get(file)?.some(({ start, end }) => line >= start && line <= end));
139
+ failures.push(`${key}: this commit adds ${rise} to the staged files.`, ...(added.length ? added : found).map(({ file, line }) => ` ${file}:${line}`));
140
+ }
141
+ return failures.length ? [...failures, SUPPRESSION_FIX] : [];
142
+ }
143
+ //#endregion
144
+ export { stagedSuppressions as a, parseBudget as i, adoptedBudget as n, checkSuppressions as r, SUPPRESSIONS_FILE as t };
@@ -0,0 +1,184 @@
1
+ import { n as markerPattern, t as DEFAULT_SAFETY_MARKERS } from "./require-safety-comment-for-type-assertion-BBQ669kj.mjs";
2
+ import { i as gitFiles, r as generatedOutput } from "./files-BMxKg5IR.mjs";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ //#region src/guardrails/suppressions.ts
8
+ const CODE_FILE = /\.(?:[cm]?[jt]sx?|vue)$/u;
9
+ const CANDIDATE = /(?:oxlint|eslint)-disable|@ts-(?:expect-error|ignore)/u;
10
+ const LINT_DIRECTIVE = /^((?:oxlint|eslint)-disable(?:-line|-next-line)?)(?=\s|$)([\s\S]*)$/u;
11
+ const DESCRIPTION = /\s-{2,}\s|\s-{2,}$/u;
12
+ /** The comment `anti-slop/require-safety-comment-for-type-assertion` accepts as a justification. */
13
+ const SAFETY_COMMENT = markerPattern(DEFAULT_SAFETY_MARKERS);
14
+ const TS_DIRECTIVE = /^[/*\s]*@ts-(expect-error|ignore)(?![\w-])/u;
15
+ let compiler;
16
+ /** This package's own TypeScript 5, loaded on first use, so the count never depends on the compiler a repository installs (TypeScript 7 has no parser API). */
17
+ function typescript() {
18
+ compiler ??= createRequire(import.meta.url)("typescript");
19
+ return compiler;
20
+ }
21
+ function scriptKind(lang) {
22
+ const kinds = typescript().ScriptKind;
23
+ if (/^[cm]?tsx$/u.test(lang)) return kinds.TSX;
24
+ if (/^[cm]?ts$/u.test(lang)) return kinds.TS;
25
+ return lang.endsWith("x") ? kinds.JSX : kinds.JS;
26
+ }
27
+ /** Every comment the parser sees, so string, template and JSX text that only looks like a comment is never read. */
28
+ function scriptComments(text, kind, offset) {
29
+ const compiler = typescript();
30
+ const source = compiler.createSourceFile("suppressions", text, compiler.ScriptTarget.Latest, false, kind);
31
+ const ranges = /* @__PURE__ */ new Map();
32
+ const visit = (node) => {
33
+ if (node.kind === compiler.SyntaxKind.JsxText) return;
34
+ if (node.kind !== compiler.SyntaxKind.SyntaxList) for (const range of [...compiler.getTrailingCommentRanges(text, node.pos) ?? [], ...compiler.getLeadingCommentRanges(text, node.pos) ?? []]) ranges.set(range.pos, range);
35
+ for (const child of node.getChildren(source)) visit(child);
36
+ };
37
+ visit(source);
38
+ return [...ranges.values()].map((range) => {
39
+ const line = range.kind === compiler.SyntaxKind.SingleLineCommentTrivia;
40
+ return {
41
+ value: text.slice(range.pos + 2, line ? range.end : range.end - 2),
42
+ line,
43
+ start: offset + range.pos
44
+ };
45
+ });
46
+ }
47
+ function blank(text) {
48
+ return text.replaceAll(/[^\n]/gu, " ");
49
+ }
50
+ /** Script blocks are parsed; outside script and style blocks, HTML comments carry template directives. */
51
+ function vueComments(text) {
52
+ const comments = [];
53
+ let template = text;
54
+ for (const block of text.matchAll(/(<script\b([^>]*)>)([\s\S]*?)<\/script\s*>|<style\b[^>]*>[\s\S]*?<\/style\s*>/gu)) {
55
+ template = template.slice(0, block.index) + blank(block[0]) + template.slice(block.index + block[0].length);
56
+ if (block[1] === void 0) continue;
57
+ const lang = /\blang\s*=\s*["']?([\w-]+)/u.exec(block[2])?.[1] ?? "js";
58
+ comments.push(...scriptComments(block[3], scriptKind(lang), block.index + block[1].length));
59
+ }
60
+ for (const comment of template.matchAll(/<!--([\s\S]*?)-->/gu)) comments.push({
61
+ value: comment[1],
62
+ line: false,
63
+ start: comment.index
64
+ });
65
+ return comments;
66
+ }
67
+ function lintDirective(value) {
68
+ const text = value.replace(/^\s*\*?\s*/u, "");
69
+ const directive = LINT_DIRECTIVE.exec(text);
70
+ if (directive === null) return [];
71
+ const rules = directive[2].split(DESCRIPTION)[0].split(",").map((rule) => rule.trim()).filter(Boolean);
72
+ return (rules.length ? rules : ["*"]).map((rule) => ({
73
+ directive: directive[1],
74
+ rule
75
+ }));
76
+ }
77
+ /** TypeScript reads a directive from a line comment, or from the last line of a block comment. */
78
+ function tsDirective(comment) {
79
+ const text = comment.line ? comment.value : comment.value.slice(comment.value.lastIndexOf("\n") + 1);
80
+ const match = TS_DIRECTIVE.exec(text);
81
+ if (match === null) return void 0;
82
+ return match[1] === "ignore" ? "tsIgnore" : "tsExpectError";
83
+ }
84
+ /** The suppressions in one code file's text; `file` decides the language and labels each entry. */
85
+ function suppressionsIn(file, text) {
86
+ if (!CODE_FILE.test(file) || !(CANDIDATE.test(text) || SAFETY_COMMENT.test(text))) return [];
87
+ const comments = file.endsWith(".vue") ? vueComments(text) : scriptComments(text, scriptKind(file.slice(file.lastIndexOf(".") + 1)), 0);
88
+ const found = [];
89
+ for (const comment of comments.sort((a, b) => a.start - b.start)) {
90
+ const line = text.slice(0, comment.start).split("\n").length;
91
+ for (const { directive, rule } of lintDirective(comment.value)) found.push({
92
+ kind: "rule",
93
+ rule,
94
+ directive,
95
+ file,
96
+ line
97
+ });
98
+ const typeDirective = tsDirective(comment);
99
+ if (typeDirective !== void 0) found.push({
100
+ kind: typeDirective,
101
+ file,
102
+ line
103
+ });
104
+ if (SAFETY_COMMENT.test(comment.value)) found.push({
105
+ kind: "safety",
106
+ file,
107
+ line
108
+ });
109
+ }
110
+ return found;
111
+ }
112
+ function authoredCode(root, files) {
113
+ const generated = generatedOutput(root);
114
+ return files.filter((file) => CODE_FILE.test(file) && !generated(file));
115
+ }
116
+ /** Suppressions in the working tree's authored code files: tracked and untracked, ignored files and generated output left out. */
117
+ function worktreeSuppressions(root, files = gitFiles(root)) {
118
+ return authoredCode(root, files).flatMap((file) => {
119
+ const path = join(root, file);
120
+ if (!existsSync(path) || !lstatSync(path).isFile()) return [];
121
+ return suppressionsIn(file, readFileSync(path, "utf8"));
122
+ });
123
+ }
124
+ function blobs(root, specs) {
125
+ if (!specs.length) return [];
126
+ const output = execFileSync("git", ["cat-file", "--batch"], {
127
+ cwd: root,
128
+ input: `${specs.join("\n")}\n`,
129
+ maxBuffer: 1073741824
130
+ });
131
+ const texts = [];
132
+ let offset = 0;
133
+ for (let index = 0; index < specs.length; index++) {
134
+ const newline = output.indexOf(10, offset);
135
+ const [, type, size] = output.subarray(offset, newline).toString().split(" ");
136
+ offset = newline + 1;
137
+ if (size === void 0) {
138
+ texts.push(void 0);
139
+ continue;
140
+ }
141
+ const end = offset + Number(size);
142
+ texts.push(type === "blob" ? output.subarray(offset, end).toString() : void 0);
143
+ offset = end + 1;
144
+ }
145
+ return texts;
146
+ }
147
+ /**
148
+ * Suppressions in authored code files at a committed revision, or in the
149
+ * index when `revision` is the empty string. Without `files` every file of
150
+ * that tree is read.
151
+ */
152
+ function revisionSuppressions(root, revision, files) {
153
+ const code = authoredCode(root, files ?? execFileSync("git", revision === "" ? ["ls-files", "-z"] : [
154
+ "ls-tree",
155
+ "-r",
156
+ "-z",
157
+ "--name-only",
158
+ revision
159
+ ], {
160
+ cwd: root,
161
+ encoding: "utf8",
162
+ maxBuffer: 67108864
163
+ }).split("\0").filter(Boolean));
164
+ const texts = blobs(root, code.map((file) => `${revision}:${file}`));
165
+ return code.flatMap((file, index) => {
166
+ const text = texts[index];
167
+ return text === void 0 ? [] : suppressionsIn(file, text);
168
+ });
169
+ }
170
+ /** Totals by budget key, rules sorted by id. */
171
+ function countSuppressions(suppressions) {
172
+ const counts = {
173
+ rules: {},
174
+ tsExpectError: 0,
175
+ tsIgnore: 0,
176
+ safety: 0
177
+ };
178
+ for (const suppression of suppressions) if (suppression.kind === "rule") counts.rules[suppression.rule] = (counts.rules[suppression.rule] ?? 0) + 1;
179
+ else counts[suppression.kind]++;
180
+ counts.rules = Object.fromEntries(Object.entries(counts.rules).sort(([a], [b]) => a.localeCompare(b)));
181
+ return counts;
182
+ }
183
+ //#endregion
184
+ export { revisionSuppressions as n, worktreeSuppressions as r, countSuppressions as t };