lintmax 0.1.83

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/dist/cli.mjs ADDED
@@ -0,0 +1,2629 @@
1
+ #!/usr/bin/env bun
2
+ import { S as OXLINT_CLI_ALLOW, b as DEFAULT_SHARED_IGNORE_PATTERNS, i as joinPath, l as isRecord, n as fromFileUrl, t as dirnamePath, w as PARSE_DIALECTS, x as ESLINT_TEST_FILE_PATTERNS } from "./path-BJn_2Ond.mjs";
3
+ import { _ as resolveBin, a as PRETTIER_MD_ARGS, b as usage, c as cwd, d as envValue, f as lintmaxRoot, g as readVersion, h as readRequiredJson, i as CliExitError, l as decodeText, m as readJson, o as bunEnv, p as pathExists, r as sync, s as cacheDir, u as ensureDirectory, v as run, y as runCapture } from "./src-Dd1x9nto.mjs";
4
+ import { $, Glob, env, file, write } from "bun";
5
+ import { lstat, unlink } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { parseSync } from "oxc-parser";
8
+ import { createHash } from "node:crypto";
9
+ import { homedir, platform, tmpdir } from "node:os";
10
+ //#region src/rule-equivalence.ts
11
+ const equivalenceGroups = [
12
+ [
13
+ "lint/suspicious/noExplicitAny",
14
+ "@typescript-eslint/no-explicit-any",
15
+ "typescript-eslint(no-explicit-any)"
16
+ ],
17
+ [
18
+ "lint/correctness/noUnusedVariables",
19
+ "@typescript-eslint/no-unused-vars",
20
+ "eslint(no-unused-vars)"
21
+ ],
22
+ [
23
+ "lint/suspicious/noDebugger",
24
+ "no-debugger",
25
+ "eslint(no-debugger)"
26
+ ],
27
+ [
28
+ "lint/correctness/noUnreachable",
29
+ "no-unreachable",
30
+ "eslint(no-unreachable)"
31
+ ],
32
+ [
33
+ "lint/suspicious/noDoubleEquals",
34
+ "eqeqeq",
35
+ "eslint(eqeqeq)"
36
+ ],
37
+ [
38
+ "lint/suspicious/noDuplicateCase",
39
+ "no-duplicate-case",
40
+ "eslint(no-duplicate-case)"
41
+ ],
42
+ [
43
+ "lint/suspicious/noFallthroughSwitchClause",
44
+ "no-fallthrough",
45
+ "eslint(no-fallthrough)"
46
+ ],
47
+ [
48
+ "lint/suspicious/noRedeclare",
49
+ "@typescript-eslint/no-redeclare",
50
+ "typescript-eslint(no-redeclare)"
51
+ ],
52
+ [
53
+ "lint/suspicious/noShadowRestrictedNames",
54
+ "no-shadow-restricted-names",
55
+ "eslint(no-shadow-restricted-names)"
56
+ ],
57
+ [
58
+ "lint/correctness/useIsNan",
59
+ "use-isnan",
60
+ "eslint(use-isnan)"
61
+ ],
62
+ [
63
+ "lint/correctness/noConstAssign",
64
+ "no-const-assign",
65
+ "eslint(no-const-assign)"
66
+ ],
67
+ [
68
+ "lint/correctness/noNewSymbol",
69
+ "no-new-symbol",
70
+ "eslint(no-new-symbol)"
71
+ ],
72
+ [
73
+ "lint/correctness/noUndeclaredVariables",
74
+ "no-undef",
75
+ "eslint(no-undef)"
76
+ ],
77
+ [
78
+ "lint/suspicious/noEmptyBlockStatements",
79
+ "no-empty",
80
+ "eslint(no-empty)"
81
+ ],
82
+ [
83
+ "lint/suspicious/noSelfCompare",
84
+ "no-self-compare",
85
+ "eslint(no-self-compare)"
86
+ ],
87
+ [
88
+ "lint/complexity/noUselessConstructor",
89
+ "@typescript-eslint/no-useless-constructor",
90
+ "eslint(no-useless-constructor)"
91
+ ],
92
+ [
93
+ "lint/suspicious/noArrayIndexKey",
94
+ "react/no-array-index-key",
95
+ "eslint-plugin-react(no-array-index-key)"
96
+ ],
97
+ [
98
+ "lint/correctness/useExhaustiveDependencies",
99
+ "react-hooks/exhaustive-deps",
100
+ "react-hooks(exhaustive-deps)"
101
+ ],
102
+ [
103
+ "lint/correctness/useHookAtTopLevel",
104
+ "react-hooks/rules-of-hooks",
105
+ "react-hooks(rules-of-hooks)"
106
+ ]
107
+ ];
108
+ const ruleToCanonical = /* @__PURE__ */ new Map();
109
+ for (const group of equivalenceGroups) {
110
+ const canonical = group[0] ?? "";
111
+ for (const rule of group) ruleToCanonical.set(rule, canonical);
112
+ }
113
+ const getCanonicalRule = (rule) => ruleToCanonical.get(rule) ?? rule;
114
+ //#endregion
115
+ //#region src/aggregate.ts
116
+ const LINTER_PRIORITY = {
117
+ biome: 0,
118
+ eslint: 2,
119
+ oxlint: 1,
120
+ prettier: 3,
121
+ "sort-package-json": 4
122
+ };
123
+ const cwdPrefix = `${process.cwd()}/`;
124
+ const normalizePath = (filePath) => {
125
+ if (filePath.startsWith(cwdPrefix)) return filePath.slice(cwdPrefix.length);
126
+ return filePath;
127
+ };
128
+ const parseBiomeDiagnostics = ({ stdout }) => {
129
+ let parsed;
130
+ try {
131
+ parsed = JSON.parse(stdout);
132
+ } catch {
133
+ return [];
134
+ }
135
+ if (!Array.isArray(parsed.diagnostics)) return [];
136
+ const results = [];
137
+ for (const d of parsed.diagnostics) {
138
+ const filePath = d.location?.path;
139
+ const { category } = d;
140
+ if (filePath && category) {
141
+ const line = d.location?.start?.line ?? 0;
142
+ results.push({
143
+ file: normalizePath(filePath),
144
+ line,
145
+ linter: "biome",
146
+ rule: category
147
+ });
148
+ }
149
+ }
150
+ return results;
151
+ };
152
+ const parseOxlintDiagnostics = ({ stdout }) => {
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(stdout);
156
+ } catch {
157
+ return [];
158
+ }
159
+ if (!Array.isArray(parsed.diagnostics)) return [];
160
+ const results = [];
161
+ for (const d of parsed.diagnostics) {
162
+ const filePath = d.filename ?? "";
163
+ const rule = d.code;
164
+ if (rule) {
165
+ const line = d.labels?.[0]?.span?.line ?? 0;
166
+ results.push({
167
+ file: filePath.length > 0 ? normalizePath(filePath) : "<unknown>",
168
+ line,
169
+ linter: "oxlint",
170
+ rule
171
+ });
172
+ }
173
+ }
174
+ return results;
175
+ };
176
+ const eslintRuleOf = (msg) => msg.ruleId ?? (msg.severity === 2 || msg.fatal ? `parse-error: ${msg.message?.slice(0, 80) ?? "unknown"}` : null);
177
+ const eslintDiagnosticsForFile = (fileEntry) => {
178
+ const { filePath } = fileEntry;
179
+ if (!(filePath && Array.isArray(fileEntry.messages))) return [];
180
+ const results = [];
181
+ for (const msg of fileEntry.messages) {
182
+ const rule = eslintRuleOf(msg);
183
+ if (rule) results.push({
184
+ file: normalizePath(filePath),
185
+ line: msg.line ?? 0,
186
+ linter: "eslint",
187
+ rule
188
+ });
189
+ }
190
+ return results;
191
+ };
192
+ const parseEslintDiagnostics = ({ stdout }) => {
193
+ let parsed;
194
+ try {
195
+ parsed = JSON.parse(stdout);
196
+ } catch {
197
+ return [];
198
+ }
199
+ if (!Array.isArray(parsed)) return [];
200
+ const results = [];
201
+ for (const fileEntry of parsed) results.push(...eslintDiagnosticsForFile(fileEntry));
202
+ return results;
203
+ };
204
+ const parsePrettierOutput = ({ stdout }) => {
205
+ const results = [];
206
+ const lines = stdout.trim().split("\n");
207
+ for (const line of lines) {
208
+ const filePath = line.trim();
209
+ if (filePath.length > 0) results.push({
210
+ file: normalizePath(filePath),
211
+ line: 0,
212
+ linter: "prettier",
213
+ rule: "unformatted"
214
+ });
215
+ }
216
+ return results;
217
+ };
218
+ const parseSortPackageJsonOutput = ({ exitCode, stdout }) => {
219
+ if (exitCode === 0) return [];
220
+ const results = [];
221
+ const lines = stdout.trim().split("\n");
222
+ for (const line of lines) {
223
+ const filePath = line.trim();
224
+ if (filePath.length > 0 && filePath.endsWith(".json")) results.push({
225
+ file: normalizePath(filePath),
226
+ line: 0,
227
+ linter: "sort-package-json",
228
+ rule: "unsorted"
229
+ });
230
+ }
231
+ return results;
232
+ };
233
+ const dedup = (diagnostics) => {
234
+ const seen = /* @__PURE__ */ new Map();
235
+ for (const d of diagnostics) if (d.line === 0) {
236
+ const key = `${d.file}\0${d.linter}\0${d.rule}`;
237
+ seen.set(key, d);
238
+ } else {
239
+ const canonical = getCanonicalRule(d.rule);
240
+ const key = `${d.file}\0${d.line}\0${canonical}`;
241
+ const existing = seen.get(key);
242
+ if (!existing || (LINTER_PRIORITY[d.linter] ?? 99) < (LINTER_PRIORITY[existing.linter] ?? 99)) seen.set(key, d);
243
+ }
244
+ return [...seen.values()];
245
+ };
246
+ const linterSort = (a, b) => (LINTER_PRIORITY[a] ?? 99) - (LINTER_PRIORITY[b] ?? 99);
247
+ const aggregate = ({ diagnostics }) => {
248
+ const deduped = dedup(diagnostics);
249
+ const fileMap = /* @__PURE__ */ new Map();
250
+ for (const d of deduped) {
251
+ let linterMap = fileMap.get(d.file);
252
+ if (!linterMap) {
253
+ linterMap = /* @__PURE__ */ new Map();
254
+ fileMap.set(d.file, linterMap);
255
+ }
256
+ let ruleMap = linterMap.get(d.linter);
257
+ if (!ruleMap) {
258
+ ruleMap = /* @__PURE__ */ new Map();
259
+ linterMap.set(d.linter, ruleMap);
260
+ }
261
+ let lines = ruleMap.get(d.rule);
262
+ if (!lines) {
263
+ lines = [];
264
+ ruleMap.set(d.rule, lines);
265
+ }
266
+ if (d.line > 0) lines.push(d.line);
267
+ }
268
+ const files = [];
269
+ const sortedFiles = [...fileMap.keys()].toSorted((a, b) => a.localeCompare(b));
270
+ for (const filePath of sortedFiles) {
271
+ const linterMap = fileMap.get(filePath) ?? /* @__PURE__ */ new Map();
272
+ const linters = [];
273
+ const sortedLinters = [...linterMap.keys()].toSorted(linterSort);
274
+ for (const linterName of sortedLinters) {
275
+ const ruleMap = linterMap.get(linterName) ?? /* @__PURE__ */ new Map();
276
+ const rules = [];
277
+ const sortedRules = [...ruleMap.keys()].toSorted((a, b) => a.localeCompare(b));
278
+ for (const ruleName of sortedRules) {
279
+ const lines = ruleMap.get(ruleName) ?? [];
280
+ const uniqueLines = [...new Set(lines)].toSorted((a, b) => a - b);
281
+ rules.push({
282
+ lines: uniqueLines,
283
+ rule: ruleName
284
+ });
285
+ }
286
+ linters.push({
287
+ linter: linterName,
288
+ rules
289
+ });
290
+ }
291
+ files.push({
292
+ file: filePath,
293
+ linters
294
+ });
295
+ }
296
+ return files;
297
+ };
298
+ //#endregion
299
+ //#region src/parse-source.ts
300
+ const parseAnyDialect = ({ label, sourceText }) => {
301
+ let firstError;
302
+ for (const dialect of PARSE_DIALECTS) {
303
+ const parsed = parseSync(dialect, sourceText);
304
+ const [parseError] = parsed.errors;
305
+ if (!parseError) return parsed;
306
+ firstError ??= parseError.message;
307
+ }
308
+ throw new Error(`${label} cannot parse the source: ${firstError ?? "unknown parse failure"}`);
309
+ };
310
+ //#endregion
311
+ //#region src/class-name.ts
312
+ const CN_NAMES = /* @__PURE__ */ new Set(["cn"]);
313
+ const BANNED_CALLEE_NAMES = /* @__PURE__ */ new Set([
314
+ "classnames",
315
+ "clsx",
316
+ "cx",
317
+ "twMerge"
318
+ ]);
319
+ const asNode = (v) => v && typeof v === "object" && typeof v.type === "string" ? v : null;
320
+ const strName = (n) => typeof n?.name === "string" ? n.name : "";
321
+ const lineAt$1 = (sourceText, offset) => {
322
+ let line = 1;
323
+ for (let i = 0; i < offset && i < sourceText.length; i += 1) if (sourceText[i] === "\n") line += 1;
324
+ return line;
325
+ };
326
+ const isClassNameAttr = (n) => {
327
+ const name = asNode(n?.name);
328
+ return n?.type === "JSXAttribute" && name?.type === "JSXIdentifier" && strName(name) === "className";
329
+ };
330
+ const isCallToCn = (n) => n.type === "CallExpression" && n.callee?.type === "Identifier" && CN_NAMES.has(strName(n.callee));
331
+ const isJoinCall = (n) => {
332
+ const property = asNode(n.callee?.property);
333
+ return n.type === "CallExpression" && n.callee?.type === "MemberExpression" && property?.type === "Identifier" && strName(property) === "join";
334
+ };
335
+ const isBannedCallee = (n) => n.type === "CallExpression" && n.callee?.type === "Identifier" && BANNED_CALLEE_NAMES.has(strName(n.callee));
336
+ const isStringLiteral = (n) => n.type === "Literal" && typeof n.value === "string" || n.type === "TemplateLiteral" && Array.isArray(n.expressions) && n.expressions.length === 0;
337
+ const classNameExprRule = (expr) => {
338
+ if (isStringLiteral(expr) || isCallToCn(expr)) return null;
339
+ if (expr.type === "TemplateLiteral") return "cn/no-template-literal";
340
+ if (expr.type === "ConditionalExpression") return "cn/no-ternary";
341
+ if (expr.type === "BinaryExpression" && expr.operator === "+") return "cn/no-concatenation";
342
+ if (isBannedCallee(expr)) return "cn/no-banned-callee";
343
+ if (isJoinCall(expr)) return "cn/no-join";
344
+ return null;
345
+ };
346
+ const collectClassNameAttrViolation = (node, sourceText, violations) => {
347
+ const container = node.value;
348
+ if (isClassNameAttr(node) && container?.type === "JSXExpressionContainer" && container.expression) {
349
+ const rule = classNameExprRule(container.expression);
350
+ if (rule) violations.push({
351
+ line: lineAt$1(sourceText, container.expression.start),
352
+ rule
353
+ });
354
+ }
355
+ };
356
+ const collectBannedCalleeViolation = ({ grand, node, parent, sourceText, violations }) => {
357
+ if (isBannedCallee(node) && (parent?.type !== "JSXExpressionContainer" || !isClassNameAttr(grand))) violations.push({
358
+ line: lineAt$1(sourceText, node.start),
359
+ rule: "cn/no-banned-callee"
360
+ });
361
+ };
362
+ const findClassNameViolations = ({ sourceText }) => {
363
+ const { program } = parseAnyDialect({
364
+ label: "className check",
365
+ sourceText
366
+ });
367
+ const violations = [];
368
+ const visit = (raw, parent, grand) => {
369
+ if (Array.isArray(raw)) {
370
+ for (const child of raw) visit(child, parent, grand);
371
+ return;
372
+ }
373
+ const node = asNode(raw);
374
+ if (!node) {
375
+ if (raw && typeof raw === "object") for (const key of Object.keys(raw)) visit(raw[key], parent, grand);
376
+ return;
377
+ }
378
+ collectClassNameAttrViolation(node, sourceText, violations);
379
+ collectBannedCalleeViolation({
380
+ grand,
381
+ node,
382
+ parent,
383
+ sourceText,
384
+ violations
385
+ });
386
+ for (const key of Object.keys(node)) if (key !== "type") visit(node[key], node, parent);
387
+ };
388
+ visit(program, null, null);
389
+ return violations;
390
+ };
391
+ const TSX_EXTENSIONS = /* @__PURE__ */ new Set([".tsx"]);
392
+ const isTsxFile = (path) => {
393
+ const dot = path.lastIndexOf(".");
394
+ return dot > path.lastIndexOf("/") && TSX_EXTENSIONS.has(path.slice(dot));
395
+ };
396
+ const checkClassNameFile = async (filePath) => {
397
+ if (!isTsxFile(filePath)) return [];
398
+ const f = file(filePath);
399
+ if (!await f.exists()) return [];
400
+ const sourceText = await f.text();
401
+ return findClassNameViolations({ sourceText }).map((v) => ({
402
+ file: filePath,
403
+ line: v.line,
404
+ linter: "cn",
405
+ rule: v.rule
406
+ }));
407
+ };
408
+ const checkClassName = async ({ root }) => {
409
+ const glob = new Glob("**/*.tsx");
410
+ const allDiagnostics = [];
411
+ for await (const path of glob.scan({
412
+ absolute: true,
413
+ cwd: root,
414
+ dot: false
415
+ })) if (!(path.includes("node_modules") || path.includes("readonly") || path.includes(".next") || path.includes("dist"))) {
416
+ const diagnostics = await checkClassNameFile(path);
417
+ allDiagnostics.push(...diagnostics);
418
+ }
419
+ return allDiagnostics;
420
+ };
421
+ //#endregion
422
+ //#region src/rules.ts
423
+ const extractBiomeRules = async () => {
424
+ const pkgPath = fromFileUrl(import.meta.resolve("@biomejs/biome/configuration_schema.json"));
425
+ const defs = JSON.parse(await file(pkgPath).text()).$defs ?? {};
426
+ const categories = [
427
+ "a11y",
428
+ "complexity",
429
+ "correctness",
430
+ "nursery",
431
+ "performance",
432
+ "security",
433
+ "style",
434
+ "suspicious"
435
+ ];
436
+ const results = [];
437
+ for (const cat of categories) {
438
+ const key = cat.charAt(0).toUpperCase() + cat.slice(1);
439
+ const rules = Object.keys(defs[key]?.properties ?? {});
440
+ for (const rule of rules) results.push({
441
+ fixable: false,
442
+ linter: "biome",
443
+ rule: `lint/${cat}/${rule}`
444
+ });
445
+ }
446
+ return results;
447
+ };
448
+ /** Reads oxlint's own resolved config. `--rules` prints nothing on current oxlint while still exiting 0 and still being listed in its help, so parsing that table yielded an empty oxlint section — and an empty section renders exactly like a linter that contributes nothing. It contributes 726 of the roughly 1738 rules this gate runs, so the command answering "what is enforced?" was wrong by more than a third while looking complete. */
449
+ const extractOxlintRules = async () => {
450
+ const configPath = joinPath(cwd, "node_modules/.cache/lintmax/.oxlintrc.json");
451
+ const result = await $`bun ${await resolveBin({
452
+ bin: "oxlint",
453
+ pkg: "oxlint"
454
+ })} -c ${configPath} --print-config`.cwd(cwd).quiet().nothrow();
455
+ if (result.exitCode !== 0) throw new Error(`oxlint --print-config failed, so its rule set is unknown: ${result.stderr.toString().trim()}`);
456
+ const parsed = JSON.parse(result.stdout.toString());
457
+ if (!isRecord(parsed)) throw new Error("oxlint --print-config returned no document");
458
+ const { rules } = parsed;
459
+ if (!isRecord(rules)) throw new Error("oxlint --print-config returned no rules map");
460
+ const results = [];
461
+ for (const [rule, value] of Object.entries(rules)) if ((Array.isArray(value) ? value[0] : value) === "deny") results.push({
462
+ fixable: false,
463
+ linter: "oxlint",
464
+ rule
465
+ });
466
+ if (results.length === 0) throw new Error("oxlint reports zero enabled rules — the gate runs it, so that cannot be right");
467
+ return results;
468
+ };
469
+ const extractEslintRules = async () => {
470
+ const eslintBin = await resolveBin({
471
+ bin: "eslint",
472
+ pkg: "eslint"
473
+ });
474
+ const configPath = joinPath(cwd, "node_modules/.cache/lintmax/eslint.generated.mjs");
475
+ const dummyFile = joinPath(cwd, "_lintmax_dummy.ts");
476
+ await write(dummyFile, "export {}\n");
477
+ const result = await $`bun ${eslintBin} --config ${configPath} --print-config ${dummyFile}`.cwd(cwd).quiet().nothrow();
478
+ await unlink(dummyFile).catch(() => void 0);
479
+ if (result.exitCode !== 0) throw new Error(`eslint --print-config failed, so its rule set is unknown: ${result.stderr.toString().trim()}`);
480
+ let parsed;
481
+ try {
482
+ parsed = JSON.parse(result.stdout.toString());
483
+ } catch (error) {
484
+ throw new Error(`eslint --print-config returned unreadable JSON: ${error instanceof Error ? error.message : ""}`, { cause: error });
485
+ }
486
+ const allRules = parsed.rules ?? {};
487
+ const results = [];
488
+ for (const [rule, config] of Object.entries(allRules)) {
489
+ const level = Array.isArray(config) ? config[0] : config;
490
+ if (level !== 0 && level !== "off") results.push({
491
+ fixable: false,
492
+ linter: "eslint",
493
+ rule
494
+ });
495
+ }
496
+ return results;
497
+ };
498
+ const extractAllRules = async () => {
499
+ const [oxlint, biome, eslint] = await Promise.all([
500
+ extractOxlintRules(),
501
+ extractBiomeRules(),
502
+ extractEslintRules()
503
+ ]);
504
+ return [
505
+ ...biome,
506
+ ...oxlint,
507
+ ...eslint
508
+ ].toSorted((a, b) => {
509
+ const linterCmp = a.linter.localeCompare(b.linter);
510
+ if (linterCmp !== 0) return linterCmp;
511
+ return a.rule.localeCompare(b.rule);
512
+ });
513
+ };
514
+ const formatRulesCompact = (rules) => {
515
+ const byLinter = /* @__PURE__ */ new Map();
516
+ for (const r of rules) {
517
+ let list = byLinter.get(r.linter);
518
+ if (!list) {
519
+ list = [];
520
+ byLinter.set(r.linter, list);
521
+ }
522
+ list.push(r.rule);
523
+ }
524
+ const parts = [];
525
+ for (const [linter, ruleList] of byLinter) {
526
+ parts.push(`${linter} (${ruleList.length})`);
527
+ for (const rule of ruleList) parts.push(` ${rule}`);
528
+ }
529
+ return parts.join("\n");
530
+ };
531
+ const formatRulesHuman = (rules) => {
532
+ const header = "Linter Rule";
533
+ const separator = "─".repeat(60);
534
+ const lines = [header, separator];
535
+ for (const r of rules) lines.push(`${r.linter.padEnd(16)}${r.rule}`);
536
+ lines.push(separator, `Total: ${rules.length} rules`);
537
+ return lines.join("\n");
538
+ };
539
+ //#endregion
540
+ //#region src/clean-ignores.ts
541
+ /** biome-ignore-all lint/performance/noAwaitInLoops: sequential file writes */
542
+ /** biome-ignore-all lint/nursery/useNamedCaptureGroup: not needed */
543
+ const eslintLineRe = /^(\s*(?:\/\/|\/\*)\s*eslint-disable(?:-next-line)?\s+)(\S(?:[^*]*[^\s*])?)(\s*\*\/)?$/v;
544
+ const oxlintLineRe = /^(\s*(?:\/\/|\/\*)\s*oxlint-disable(?:-next-line)?\s+)(\S(?:[^*]*[^\s*])?)(\s*\*\/)?$/v;
545
+ const biomeLineRe = /^\s*(?:\/\/|\/\*\*)\s*biome-ignore(?:-all)?\s+(?<rule>[\w\/]+)/v;
546
+ const OXLINT_PREFIXES = [
547
+ "eslint",
548
+ "eslint-plugin-jsx-a11y",
549
+ "eslint-plugin-promise",
550
+ "eslint-plugin-react",
551
+ "eslint-plugin-react-perf",
552
+ "eslint-plugin-unicorn",
553
+ "import",
554
+ "jest",
555
+ "jsdoc",
556
+ "jsx-a11y",
557
+ "jsx_a11y",
558
+ "next",
559
+ "nextjs",
560
+ "oxc",
561
+ "promise",
562
+ "react",
563
+ "react-hooks",
564
+ "react-perf",
565
+ "react_hooks",
566
+ "react_perf",
567
+ "typescript-eslint",
568
+ "typescript_eslint",
569
+ "unicorn",
570
+ "vitest",
571
+ "@next/next",
572
+ "@typescript-eslint",
573
+ "@eslint-react"
574
+ ];
575
+ const OXLINT_SEPARATORS = [
576
+ "(",
577
+ "/",
578
+ "\\"
579
+ ];
580
+ /** The prefix+separator a rule id starts with, or undefined — a plain-string scan replacing a 27-branch alternation. Order-independent: the separator requirement disambiguates a short prefix from a longer one (`react-hooks/x` never matches `react` because `-` is not a separator). */
581
+ const oxlintPrefixMatch = (rule) => {
582
+ for (const prefix of OXLINT_PREFIXES) for (const sep of OXLINT_SEPARATORS) if (rule.startsWith(`${prefix}${sep}`)) return `${prefix}${sep}`;
583
+ };
584
+ const trailingParenRe = /\)$/v;
585
+ const trailingSepRe = /[(/\\]$/u;
586
+ const eslintPluginPrefixRe = /^eslint-plugin-/v;
587
+ /** The oxlint-prefixed variants for a rule whose id starts with `oxMatch` (prefix+separator) — bare id plus canonical/short-plugin spellings. */
588
+ const buildOxlintVariants = (rule, oxMatch) => {
589
+ const variants = [];
590
+ const bare = rule.slice(oxMatch.length).replace(trailingParenRe, "");
591
+ variants.push(bare);
592
+ const prefix = oxMatch.replace(trailingSepRe, "");
593
+ variants.push(`${prefix}/${bare}`, `${prefix}(${bare})`);
594
+ if (prefix === "eslint") variants.push(bare);
595
+ if (prefix === "typescript-eslint") variants.push(`@typescript-eslint/${bare}`);
596
+ if (prefix.startsWith("eslint-plugin-")) {
597
+ const short = prefix.replace(eslintPluginPrefixRe, "");
598
+ variants.push(`${short}/${bare}`, `${short}(${bare})`);
599
+ }
600
+ return variants;
601
+ };
602
+ /** The underscore↔dash spelling twins of each variant — a `_` id also spelled with `-` and vice versa. */
603
+ const expandUnderscoreDash = (variants) => {
604
+ const extra = [];
605
+ for (const v of variants) {
606
+ if (v.includes("_")) extra.push(v.replaceAll("_", "-"));
607
+ if (v.includes("-")) extra.push(v.replaceAll("-", "_"));
608
+ }
609
+ return extra;
610
+ };
611
+ const normalizeRule = (rule) => {
612
+ const variants = [rule];
613
+ const oxMatch = oxlintPrefixMatch(rule);
614
+ if (oxMatch !== void 0) variants.push(...buildOxlintVariants(rule, oxMatch));
615
+ if (rule.startsWith("@typescript-eslint/")) variants.push(`typescript-eslint(${rule.slice(19)})`);
616
+ if (rule.startsWith("@next/next/")) variants.push(`nextjs(${rule.slice(11)})`);
617
+ if (rule.startsWith("@eslint-react/")) variants.push(`react(${rule.slice(14)})`);
618
+ for (const e of expandUnderscoreDash(variants)) variants.push(e);
619
+ return variants;
620
+ };
621
+ const loadOxlintOffRules = async () => {
622
+ const config = await readRequiredJson({ path: joinPath(process.cwd(), cacheDir, ".oxlintrc.json") }).catch(() => null);
623
+ if (!config) return /* @__PURE__ */ new Set();
624
+ const off = /* @__PURE__ */ new Set();
625
+ for (const [rule, val] of Object.entries(config.rules ?? {})) if ((Array.isArray(val) ? String(val[0]) : val) === "off") {
626
+ off.add(rule);
627
+ for (const v of normalizeRule(rule)) off.add(v);
628
+ }
629
+ for (const rule of OXLINT_CLI_ALLOW) {
630
+ off.add(rule);
631
+ for (const v of normalizeRule(rule)) off.add(v);
632
+ }
633
+ return off;
634
+ };
635
+ const buildActiveRuleSet = async () => {
636
+ const rules = await extractAllRules();
637
+ const active = /* @__PURE__ */ new Set();
638
+ for (const r of rules) {
639
+ active.add(r.rule);
640
+ for (const v of normalizeRule(r.rule)) active.add(v);
641
+ }
642
+ return active;
643
+ };
644
+ const isRuleActive = (rule, active, oxlintOff) => {
645
+ if (oxlintOff?.has(rule)) return false;
646
+ if (oxlintOff) {
647
+ for (const v of normalizeRule(rule)) if (oxlintOff.has(v)) return false;
648
+ }
649
+ if (active.has(rule)) return true;
650
+ for (const v of normalizeRule(rule)) if (active.has(v)) return true;
651
+ if (!oxlintOff) return false;
652
+ return true;
653
+ };
654
+ const splitCsvRules = (ruleList) => ruleList.split(",").map((r) => r.trim()).filter(Boolean);
655
+ const splitDirective = (str) => {
656
+ const closeAt = str.lastIndexOf("*/");
657
+ const body = closeAt === -1 ? str : str.slice(0, closeAt).trimEnd();
658
+ const dashAt = body.indexOf("--");
659
+ if (dashAt === -1) return {
660
+ reason: "",
661
+ rules: splitCsvRules(body)
662
+ };
663
+ let reasonAt = dashAt;
664
+ while (reasonAt > 0 && (body[reasonAt - 1] === " " || body[reasonAt - 1] === " ")) reasonAt -= 1;
665
+ return {
666
+ reason: body.slice(reasonAt),
667
+ rules: splitCsvRules(body.slice(0, reasonAt))
668
+ };
669
+ };
670
+ const processMultiRuleLine = ({ active, isOxlint, line, match, oxlintOff, result }) => {
671
+ const prefix = match[1] ?? "";
672
+ const rulesStr = match[2] ?? "";
673
+ const suffix = match[3] ?? "";
674
+ const { reason, rules } = splitDirective(rulesStr);
675
+ const kept = rules.filter((r) => isRuleActive(r, active, isOxlint ? oxlintOff : void 0));
676
+ if (kept.length === 0) return rules.length;
677
+ if (kept.length < rules.length) {
678
+ result.push(`${prefix}${kept.join(", ")}${reason}${suffix}`);
679
+ return rules.length - kept.length;
680
+ }
681
+ result.push(line);
682
+ return 0;
683
+ };
684
+ /** Process one source line: keep-or-rewrite it into `result` and return how many disabled rules were removed. */
685
+ const processIgnoreLine = ({ active, line, oxlintOff, result }) => {
686
+ eslintLineRe.lastIndex = 0;
687
+ oxlintLineRe.lastIndex = 0;
688
+ biomeLineRe.lastIndex = 0;
689
+ const eslintMatch = eslintLineRe.exec(line);
690
+ if (eslintMatch) return processMultiRuleLine({
691
+ active,
692
+ line,
693
+ match: eslintMatch,
694
+ result
695
+ });
696
+ const oxlintMatch = oxlintLineRe.exec(line);
697
+ if (oxlintMatch) return processMultiRuleLine({
698
+ active,
699
+ isOxlint: true,
700
+ line,
701
+ match: oxlintMatch,
702
+ oxlintOff,
703
+ result
704
+ });
705
+ const biomeMatch = biomeLineRe.exec(line);
706
+ if (biomeMatch && !isRuleActive(biomeMatch.groups?.rule ?? "", active)) return 1;
707
+ result.push(line);
708
+ return 0;
709
+ };
710
+ const cleanFileIgnores = async (filePath, active, oxlintOff) => {
711
+ const f = file(filePath);
712
+ if (!await f.exists()) return 0;
713
+ const lines = (await f.text()).split("\n");
714
+ const result = [];
715
+ let removed = 0;
716
+ for (const line of lines) removed += processIgnoreLine({
717
+ active,
718
+ line,
719
+ oxlintOff,
720
+ result
721
+ });
722
+ if (removed > 0) await write(filePath, result.join("\n"));
723
+ return removed;
724
+ };
725
+ const cleanIgnores = async (filePaths) => {
726
+ const active = await buildActiveRuleSet();
727
+ const oxlintOff = await loadOxlintOffRules();
728
+ let cleaned = 0;
729
+ const files = [];
730
+ for (const fp of filePaths) {
731
+ const count = await cleanFileIgnores(fp, active, oxlintOff);
732
+ if (count > 0) {
733
+ cleaned += count;
734
+ files.push(fp);
735
+ }
736
+ }
737
+ return {
738
+ cleaned,
739
+ files
740
+ };
741
+ };
742
+ //#endregion
743
+ //#region src/comments.ts
744
+ const lineAt = (sourceText, offset) => {
745
+ let line = 1;
746
+ for (let i = 0; i < offset && i < sourceText.length; i += 1) if (sourceText[i] === "\n") line += 1;
747
+ return line;
748
+ };
749
+ const KEEP_PATTERN = /biome-ignore|eslint-disable|oxlint-disable|@ts-nocheck|@ts-expect-error|@ts-ignore|@refresh|@flow|c8 ignore|istanbul ignore|noinspection|nolint|prettier-ignore|webpackChunkName|@jsx|@license|@preserve|type-coverage:ignore/v;
750
+ const WHITESPACE_ONLY = /^\s*$/v;
751
+ const WS_CHAR = /\s/v;
752
+ const COMMENT_EXTENSIONS = /* @__PURE__ */ new Set([
753
+ ".cjs",
754
+ ".js",
755
+ ".jsx",
756
+ ".mjs",
757
+ ".mts",
758
+ ".ts",
759
+ ".tsx"
760
+ ]);
761
+ const extOf = (path) => {
762
+ const dot = path.lastIndexOf(".");
763
+ return dot > path.lastIndexOf("/") ? path.slice(dot) : "";
764
+ };
765
+ const isCommentCandidate = (path) => COMMENT_EXTENSIONS.has(extOf(path));
766
+ const isBlockOnlyComment = (sourceText, comments, c) => {
767
+ const inComment = (idx) => comments.some((o) => idx >= o.start && idx < o.end);
768
+ let before = c.start - 1;
769
+ while (before >= 0 && (WS_CHAR.test(sourceText[before] ?? "") || inComment(before))) before -= 1;
770
+ let after = c.end;
771
+ while (after < sourceText.length && (WS_CHAR.test(sourceText[after] ?? "") || inComment(after))) after += 1;
772
+ return sourceText[before] === "{" && sourceText[after] === "}";
773
+ };
774
+ const findDeletableComments = ({ sourceText }) => {
775
+ const { comments } = parseAnyDialect({
776
+ label: "comment strip",
777
+ sourceText
778
+ });
779
+ const deletable = [];
780
+ for (const c of comments) {
781
+ const text = sourceText.slice(c.start, c.end);
782
+ if (!(text.startsWith("#!") || text.startsWith("/**") || text.startsWith("/// <") || KEEP_PATTERN.test(text) || isBlockOnlyComment(sourceText, comments, c))) deletable.push({
783
+ end: c.end,
784
+ line: lineAt(sourceText, c.start),
785
+ start: c.start
786
+ });
787
+ }
788
+ deletable.sort((a, b) => a.start - b.start);
789
+ return deletable;
790
+ };
791
+ const deleteComments = ({ sourceText }) => {
792
+ const comments = findDeletableComments({ sourceText });
793
+ if (comments.length === 0) return sourceText;
794
+ const parts = [];
795
+ let cursor = 0;
796
+ for (const c of comments) {
797
+ const beforeChunk = sourceText.slice(cursor, c.start);
798
+ const lineStart = beforeChunk.lastIndexOf("\n") + 1;
799
+ const indent = beforeChunk.slice(lineStart);
800
+ let afterEnd = c.end;
801
+ if (sourceText[afterEnd] === "\n") afterEnd += 1;
802
+ else if (sourceText[afterEnd] === "\r" && sourceText[afterEnd + 1] === "\n") afterEnd += 2;
803
+ if (WHITESPACE_ONLY.test(indent) && afterEnd <= sourceText.length) {
804
+ parts.push(beforeChunk.slice(0, lineStart));
805
+ cursor = afterEnd;
806
+ } else {
807
+ parts.push(beforeChunk);
808
+ cursor = c.end;
809
+ }
810
+ }
811
+ parts.push(sourceText.slice(cursor));
812
+ return parts.join("");
813
+ };
814
+ const processFile = async (filePath) => {
815
+ if (!isCommentCandidate(filePath)) return {
816
+ diagnostics: [],
817
+ modified: false
818
+ };
819
+ const f = file(filePath);
820
+ if (!await f.exists()) return {
821
+ diagnostics: [],
822
+ modified: false
823
+ };
824
+ const sourceText = await f.text();
825
+ const comments = findDeletableComments({ sourceText });
826
+ const diagnostics = [];
827
+ for (const c of comments) diagnostics.push({
828
+ file: filePath,
829
+ line: c.line,
830
+ linter: "comments",
831
+ rule: "deletable"
832
+ });
833
+ return {
834
+ diagnostics,
835
+ modified: false
836
+ };
837
+ };
838
+ const processFileForFix = async (filePath) => {
839
+ if (!isCommentCandidate(filePath)) return false;
840
+ const f = file(filePath);
841
+ if (!await f.exists()) return false;
842
+ const sourceText = await f.text();
843
+ const result = deleteComments({ sourceText });
844
+ if (result !== sourceText) {
845
+ await write(filePath, result);
846
+ return true;
847
+ }
848
+ return false;
849
+ };
850
+ const checkComments = async ({ files }) => {
851
+ return (await Promise.all(files.map(async (f) => processFile(f)))).flatMap((r) => r.diagnostics);
852
+ };
853
+ const fixComments = async ({ files }) => {
854
+ return (await Promise.all(files.map(async (f) => processFileForFix(f)))).filter(Boolean).length;
855
+ };
856
+ //#endregion
857
+ //#region src/compact.ts
858
+ const isSymlinkSafe = async (p) => {
859
+ try {
860
+ return (await lstat(p)).isSymbolicLink();
861
+ } catch {
862
+ return false;
863
+ }
864
+ };
865
+ const COMPACT_REGEX = /(?:\r?\n){2,}/gv;
866
+ const compactBasenames = /* @__PURE__ */ new Set([
867
+ ".env.example",
868
+ ".gitignore",
869
+ ".npmrc",
870
+ ".prettierignore",
871
+ "Dockerfile",
872
+ "Makefile"
873
+ ]);
874
+ const compactExtensions = /* @__PURE__ */ new Set([
875
+ ".cjs",
876
+ ".css",
877
+ ".gql",
878
+ ".graphql",
879
+ ".html",
880
+ ".js",
881
+ ".json",
882
+ ".jsonc",
883
+ ".jsx",
884
+ ".mjs",
885
+ ".mts",
886
+ ".scss",
887
+ ".sql",
888
+ ".ts",
889
+ ".tsx",
890
+ ".txt",
891
+ ".yaml",
892
+ ".yml"
893
+ ]);
894
+ const basename = ({ path }) => {
895
+ const index = path.lastIndexOf("/");
896
+ if (index === -1) return path;
897
+ return path.slice(index + 1);
898
+ };
899
+ const extension = ({ path }) => {
900
+ const slashIndex = path.lastIndexOf("/");
901
+ const dotIndex = path.lastIndexOf(".");
902
+ return dotIndex > slashIndex ? path.slice(dotIndex) : "";
903
+ };
904
+ const compactContent = ({ content }) => content.replace(COMPACT_REGEX, "\n");
905
+ const isCompactCandidate = ({ relativePath }) => {
906
+ const fileName = basename({ path: relativePath });
907
+ if (compactBasenames.has(fileName)) return true;
908
+ return compactExtensions.has(extension({ path: relativePath }));
909
+ };
910
+ const isBinary = ({ bytes }) => {
911
+ for (const byte of bytes) if (byte === 0) return true;
912
+ return false;
913
+ };
914
+ const listCompactFiles = async ({ env, root }) => {
915
+ const result = await $`git -C ${root} ls-files -z --cached --others --exclude-standard`.env(env).quiet().nothrow();
916
+ if (result.exitCode !== 0) {
917
+ const stderr = result.stderr.toString().trim();
918
+ if (stderr.toLowerCase().includes("not a git repository")) return [];
919
+ throw new CliExitError({
920
+ code: result.exitCode,
921
+ message: stderr.length > 0 ? stderr : "Failed to list files for compact step"
922
+ });
923
+ }
924
+ const entries = result.stdout.toString().split("\0").filter((e) => e.length > 0 && e !== "bun.lock");
925
+ const symlinkFlags = await Promise.all(entries.map(async (e) => isSymlinkSafe(join(root, e))));
926
+ return entries.filter((_e, index) => !symlinkFlags[index]);
927
+ };
928
+ const runCompact = async ({ env, human = false, mode, root }) => {
929
+ const files = await listCompactFiles({
930
+ env,
931
+ root
932
+ });
933
+ const results = await Promise.all(files.map(async (relativePath) => {
934
+ if (!isCompactCandidate({ relativePath })) return {
935
+ changed: false,
936
+ relativePath,
937
+ scanned: false
938
+ };
939
+ const absolutePath = joinPath(root, relativePath);
940
+ const source = file(absolutePath);
941
+ if (!await source.exists()) return {
942
+ changed: false,
943
+ relativePath,
944
+ scanned: false
945
+ };
946
+ const bytes = new Uint8Array(await source.arrayBuffer());
947
+ if (isBinary({ bytes })) return {
948
+ changed: false,
949
+ relativePath,
950
+ scanned: true
951
+ };
952
+ const content = decodeText(bytes);
953
+ const compacted = compactContent({ content });
954
+ if (content === compacted) return {
955
+ changed: false,
956
+ relativePath,
957
+ scanned: true
958
+ };
959
+ if (mode === "fix") await write(absolutePath, compacted);
960
+ return {
961
+ changed: true,
962
+ relativePath,
963
+ scanned: true
964
+ };
965
+ }));
966
+ const changed = [];
967
+ let scanned = 0;
968
+ for (const result of results) {
969
+ if (result.scanned) scanned += 1;
970
+ if (result.changed) changed.push(result.relativePath);
971
+ }
972
+ if (mode === "fix") {
973
+ if (human) {
974
+ process.stdout.write(`[compact] Scanned ${scanned} files\n`);
975
+ process.stdout.write(`[compact] Updated ${changed.length} files\n`);
976
+ }
977
+ return;
978
+ }
979
+ if (changed.length === 0) return;
980
+ const shown = changed.slice(0, 10);
981
+ const suffix = changed.length > shown.length ? `\n...and ${changed.length - shown.length} more` : "";
982
+ throw new CliExitError({
983
+ code: 1,
984
+ message: `[compact]\nFiles requiring compaction:\n${shown.join("\n")}${suffix}\nRun: lintmax fix`
985
+ });
986
+ };
987
+ //#endregion
988
+ //#region src/extra-coverage.ts
989
+ const DOCKERFILE_RE = /(?:^|\/)Dockerfile(?:\.[\w\-.]+)?$/v;
990
+ const SHELLCHECK_LINE_RE = /^(?<file>.+?):(?<line>\d+):\d+:\s+(?:error|note|style|warning):\s+(?:\S.*)?\[(?<rule>[^\]\[]+)\]$/v;
991
+ const isShell = (filePath) => filePath.endsWith(".sh") || filePath.endsWith(".bash");
992
+ const isToml = (filePath) => filePath.endsWith(".toml");
993
+ const isDockerfile = (filePath) => DOCKERFILE_RE.test(filePath);
994
+ const collectExtraTargets = (gitFiles) => ({
995
+ dockerfiles: gitFiles.filter(isDockerfile),
996
+ shell: gitFiles.filter(isShell),
997
+ toml: gitFiles.filter(isToml)
998
+ });
999
+ const resolveDprintPluginPath = () => {
1000
+ try {
1001
+ return import.meta.resolve("@dprint/dockerfile/plugin.wasm").replace("file://", "");
1002
+ } catch {
1003
+ return null;
1004
+ }
1005
+ };
1006
+ const whichTool = async (env, tool) => {
1007
+ const result = await $`which ${tool}`.env(env).quiet().nothrow();
1008
+ if (result.exitCode !== 0) return null;
1009
+ const path = result.stdout.toString().trim();
1010
+ return path.length > 0 ? path : null;
1011
+ };
1012
+ const failureDiagnostic = (linter, files) => ({
1013
+ file: files[0] ?? "",
1014
+ line: 0,
1015
+ linter,
1016
+ rule: linter
1017
+ });
1018
+ const parseShellcheckLine = (line) => {
1019
+ const groups = SHELLCHECK_LINE_RE.exec(line)?.groups;
1020
+ if (groups?.file && groups.line && groups.rule) return {
1021
+ file: groups.file,
1022
+ line: Number(groups.line),
1023
+ linter: "shellcheck",
1024
+ rule: groups.rule
1025
+ };
1026
+ return null;
1027
+ };
1028
+ const runShfmtStep = async ({ bin, command, env, files }) => {
1029
+ if (command === "fix") await runCapture({
1030
+ args: ["-w", ...files],
1031
+ command: bin,
1032
+ env,
1033
+ label: "shfmt"
1034
+ });
1035
+ const fmtCheck = await runCapture({
1036
+ args: ["-d", ...files],
1037
+ command: bin,
1038
+ env,
1039
+ label: "shfmt"
1040
+ });
1041
+ if (fmtCheck.exitCode !== 0 || fmtCheck.stdout.trim().length > 0) return [failureDiagnostic("shfmt", files)];
1042
+ return [];
1043
+ };
1044
+ const runShellcheckStep = async ({ bin, env, files }) => {
1045
+ const result = await runCapture({
1046
+ args: [
1047
+ "-f",
1048
+ "gcc",
1049
+ ...files
1050
+ ],
1051
+ command: bin,
1052
+ env,
1053
+ label: "shellcheck"
1054
+ });
1055
+ const diagnostics = [];
1056
+ for (const line of result.stdout.split("\n")) {
1057
+ const diagnostic = parseShellcheckLine(line);
1058
+ if (diagnostic !== null) diagnostics.push(diagnostic);
1059
+ }
1060
+ if (result.exitCode !== 0 && diagnostics.length === 0) diagnostics.push(failureDiagnostic("shellcheck", files));
1061
+ return diagnostics;
1062
+ };
1063
+ const runShell = async ({ command, env, files }) => {
1064
+ if (files.length === 0) return {
1065
+ diagnostics: [],
1066
+ notes: []
1067
+ };
1068
+ const shellcheck = await whichTool(env, "shellcheck");
1069
+ const shfmt = await whichTool(env, "shfmt");
1070
+ const notes = [];
1071
+ if (shellcheck === null || shfmt === null) notes.push("shellcheck/shfmt not on PATH — shell files unchecked (install: brew install shellcheck shfmt)");
1072
+ const diagnostics = [];
1073
+ if (shfmt !== null) diagnostics.push(...await runShfmtStep({
1074
+ bin: shfmt,
1075
+ command,
1076
+ env,
1077
+ files
1078
+ }));
1079
+ if (shellcheck !== null) diagnostics.push(...await runShellcheckStep({
1080
+ bin: shellcheck,
1081
+ env,
1082
+ files
1083
+ }));
1084
+ return {
1085
+ diagnostics,
1086
+ notes
1087
+ };
1088
+ };
1089
+ const runTombi = async ({ bin, command, env, files }) => {
1090
+ if (files.length === 0) return [];
1091
+ if (command === "fix") await runCapture({
1092
+ args: [
1093
+ bin,
1094
+ "format",
1095
+ ...files
1096
+ ],
1097
+ command: "bun",
1098
+ env,
1099
+ label: "tombi"
1100
+ });
1101
+ const lint = await runCapture({
1102
+ args: [
1103
+ bin,
1104
+ "lint",
1105
+ ...files
1106
+ ],
1107
+ command: "bun",
1108
+ env,
1109
+ label: "tombi"
1110
+ });
1111
+ const fmtCheck = await runCapture({
1112
+ args: [
1113
+ bin,
1114
+ "format",
1115
+ "--check",
1116
+ ...files
1117
+ ],
1118
+ command: "bun",
1119
+ env,
1120
+ label: "tombi"
1121
+ });
1122
+ if (lint.exitCode === 0 && fmtCheck.exitCode === 0) return [];
1123
+ return [failureDiagnostic("tombi", files)];
1124
+ };
1125
+ const runDprintDockerfile = async ({ bin, command, env, files, pluginPath }) => {
1126
+ if (files.length === 0 || pluginPath === null) return [];
1127
+ const configArgs = [
1128
+ "--plugins",
1129
+ pluginPath,
1130
+ "--config",
1131
+ "/dev/null"
1132
+ ];
1133
+ if (command === "fix") await runCapture({
1134
+ args: [
1135
+ "fmt",
1136
+ ...configArgs,
1137
+ ...files
1138
+ ],
1139
+ command: bin,
1140
+ env,
1141
+ label: "dprint"
1142
+ });
1143
+ if ((await runCapture({
1144
+ args: [
1145
+ "check",
1146
+ ...configArgs,
1147
+ ...files
1148
+ ],
1149
+ command: bin,
1150
+ env,
1151
+ label: "dprint"
1152
+ })).exitCode === 0) return [];
1153
+ return [failureDiagnostic("dprint", files)];
1154
+ };
1155
+ const runExtraCoverage = async ({ bins, command, env, gitFiles }) => {
1156
+ const targets = collectExtraTargets(gitFiles);
1157
+ const pluginPath = resolveDprintPluginPath();
1158
+ const [shell, tombi, dprint] = await Promise.all([
1159
+ runShell({
1160
+ command,
1161
+ env,
1162
+ files: targets.shell
1163
+ }),
1164
+ runTombi({
1165
+ bin: bins.tombi,
1166
+ command,
1167
+ env,
1168
+ files: targets.toml
1169
+ }),
1170
+ runDprintDockerfile({
1171
+ bin: bins.dprint,
1172
+ command,
1173
+ env,
1174
+ files: targets.dockerfiles,
1175
+ pluginPath
1176
+ })
1177
+ ]);
1178
+ return {
1179
+ diagnostics: [
1180
+ ...tombi,
1181
+ ...dprint,
1182
+ ...shell.diagnostics
1183
+ ],
1184
+ notes: shell.notes
1185
+ };
1186
+ };
1187
+ //#endregion
1188
+ //#region src/format.ts
1189
+ const formatGrouped = ({ files }) => {
1190
+ if (files.length === 0) return "";
1191
+ const parts = [];
1192
+ for (const f of files) {
1193
+ parts.push(f.file);
1194
+ for (const l of f.linters) {
1195
+ parts.push(` ${l.linter}`);
1196
+ for (const r of l.rules) {
1197
+ const lineStr = r.lines.length > 0 ? r.lines.join(",") : "";
1198
+ parts.push(` ${lineStr}${lineStr.length > 0 ? " " : ""}${r.rule}`);
1199
+ }
1200
+ }
1201
+ }
1202
+ return parts.join("\n");
1203
+ };
1204
+ //#endregion
1205
+ //#region src/ignores.ts
1206
+ /** biome-ignore-all lint/nursery/useNamedCaptureGroup: not needed */
1207
+ const eslintDisableRe = /eslint-disable(?:-next-line)?\s+([^\n]*)/gv;
1208
+ const oxlintDisableRe$1 = /oxlint-disable(?:-next-line)?\s+([^\n]*)/gv;
1209
+ const biomeIgnoreRe = /biome-ignore(?:-all)?\s+([\w/]+)/gu;
1210
+ const tsIgnoreRe = /@ts-(?:expect-error|ignore|nocheck)/gv;
1211
+ /** Strip a trailing `-- reason` and a trailing block-comment close from one split rule. indexOf is linear where the leading-whitespace regexes backtrack. */
1212
+ const stripRuleTail = (rule) => {
1213
+ const dash = rule.indexOf("--");
1214
+ const noComment = dash === -1 ? rule : rule.slice(0, dash);
1215
+ const close = noComment.indexOf("*/");
1216
+ return (close === -1 ? noComment : noComment.slice(0, close)).trim();
1217
+ };
1218
+ const tsInlineRe = /@ts-(?:expect-error|ignore|nocheck)/v;
1219
+ const DANGEROUS_PATTERNS = [
1220
+ "no-unsafe-argument",
1221
+ "no-unsafe-assignment",
1222
+ "no-unsafe-call",
1223
+ "no-unsafe-member-access",
1224
+ "no-unsafe-return",
1225
+ "no-non-null-assertion",
1226
+ "@ts-ignore",
1227
+ "@ts-nocheck",
1228
+ "noNonNullAssertion"
1229
+ ];
1230
+ const DANGEROUS_NON_TEST_PATTERNS = [
1231
+ "@ts-expect-error",
1232
+ "no-explicit-any",
1233
+ "noExplicitAny"
1234
+ ];
1235
+ const isTestFile = (f) => ESLINT_TEST_FILE_PATTERNS.some((p) => new Glob(p).match(f));
1236
+ const parseRules = (line, re) => {
1237
+ const rules = [];
1238
+ re.lastIndex = 0;
1239
+ let match = re.exec(line);
1240
+ while (match) {
1241
+ const raw = match[1];
1242
+ if (raw) for (const r of raw.split(",")) {
1243
+ const trimmed = stripRuleTail(r);
1244
+ if (trimmed) rules.push(trimmed);
1245
+ }
1246
+ match = re.exec(line);
1247
+ }
1248
+ return rules;
1249
+ };
1250
+ const isDangerousRule = (rule, file) => {
1251
+ if (DANGEROUS_PATTERNS.some((p) => rule.includes(p))) return true;
1252
+ if (DANGEROUS_NON_TEST_PATTERNS.some((p) => rule.includes(p))) return !isTestFile(file);
1253
+ return false;
1254
+ };
1255
+ const parseRipgrepLine = (raw, cwd) => {
1256
+ const firstColon = raw.indexOf(":");
1257
+ const secondColon = raw.indexOf(":", firstColon + 1);
1258
+ if (secondColon <= firstColon) return;
1259
+ return {
1260
+ content: raw.slice(secondColon + 1),
1261
+ file: raw.slice(0, firstColon).replace(`${cwd}/`, ""),
1262
+ lineNum: Number(raw.slice(firstColon + 1, secondColon))
1263
+ };
1264
+ };
1265
+ const rulesFromContent = (content) => {
1266
+ const rules = [
1267
+ ...parseRules(content, eslintDisableRe),
1268
+ ...parseRules(content, oxlintDisableRe$1),
1269
+ ...parseRules(content, biomeIgnoreRe)
1270
+ ];
1271
+ tsIgnoreRe.lastIndex = 0;
1272
+ if (tsIgnoreRe.test(content)) {
1273
+ const tsMatch = tsInlineRe.exec(content);
1274
+ if (tsMatch) rules.push(tsMatch[0]);
1275
+ }
1276
+ return rules;
1277
+ };
1278
+ const findDangerousSuppressions = async (cwd) => {
1279
+ const result = await $`rg -n "^\s*//\s*eslint-disable|^\s*/\*\s*eslint-disable|^\s*//\s*oxlint-disable|^\s*/\*\s*oxlint-disable|^\s*/\*\*\s*biome-ignore|^\s*//\s*@ts-ignore|^\s*//\s*@ts-expect-error|^\s*//\s*@ts-nocheck|^\s*/\*\s*@ts-nocheck" ${cwd} -g '*.ts' -g '*.tsx' -g '!node_modules' -g '!*.d.ts' ${DEFAULT_SHARED_IGNORE_PATTERNS.flatMap((p) => ["-g", `!${p}`])}`.quiet().nothrow();
1280
+ const out = [];
1281
+ for (const raw of result.stdout.toString().trim().split("\n").filter(Boolean)) {
1282
+ const parsed = parseRipgrepLine(raw, cwd);
1283
+ if (parsed) {
1284
+ const { content, file, lineNum } = parsed;
1285
+ for (const rule of rulesFromContent(content)) if (isDangerousRule(rule, file)) out.push({
1286
+ file,
1287
+ line: lineNum,
1288
+ rule
1289
+ });
1290
+ }
1291
+ }
1292
+ return out;
1293
+ };
1294
+ //#endregion
1295
+ //#region src/jsx-extension.ts
1296
+ const containsJsxNode = (program) => {
1297
+ let found = false;
1298
+ const visit = (node) => {
1299
+ if (found || !node || typeof node !== "object") return;
1300
+ if (Array.isArray(node)) {
1301
+ for (const child of node) visit(child);
1302
+ return;
1303
+ }
1304
+ const typed = node;
1305
+ if (typed.type === "JSXElement" || typed.type === "JSXFragment") {
1306
+ found = true;
1307
+ return;
1308
+ }
1309
+ for (const key of Object.keys(node)) if (key !== "type") visit(node[key]);
1310
+ };
1311
+ visit(program);
1312
+ return found;
1313
+ };
1314
+ const hasJsx = (sourceText) => {
1315
+ if (parseSync("file.ts", sourceText).errors.length === 0) return false;
1316
+ const asTsx = parseSync("file.tsx", sourceText);
1317
+ return containsJsxNode(asTsx.program);
1318
+ };
1319
+ const checkJsxExtension = async ({ root }) => {
1320
+ const glob = new Glob("**/*.ts");
1321
+ const ignoreGlobs = DEFAULT_SHARED_IGNORE_PATTERNS.map((p) => new Glob(p));
1322
+ const isIgnored = (p) => p.includes("node_modules") || p.endsWith(".d.ts") || ignoreGlobs.some((g) => g.match(p));
1323
+ const diagnostics = [];
1324
+ for await (const path of glob.scan({
1325
+ absolute: false,
1326
+ cwd: root,
1327
+ dot: false
1328
+ })) if (!isIgnored(path)) {
1329
+ const content = await file(`${root}/${path}`).text();
1330
+ if (hasJsx(content)) diagnostics.push({
1331
+ file: `${root}/${path}`,
1332
+ line: 1,
1333
+ linter: "lintmax",
1334
+ rule: "jsx-requires-tsx-extension"
1335
+ });
1336
+ }
1337
+ return diagnostics;
1338
+ };
1339
+ //#endregion
1340
+ //#region src/unused-suppressions.ts
1341
+ /** biome-ignore-all lint/performance/noAwaitInLoops: sequential file io */
1342
+ /** biome-ignore-all lint/style/noProcessEnv: linter env passthrough */
1343
+ const oxlintDisableRe = /^(?<prefix>\s*\/\*\s*oxlint-disable\s+)(?<rules>\S(?:[^*]*[^\s*])?)(?<close>\s*\*\/)?$/v;
1344
+ const oxlintDisablePresentRe = /\/\*\s*oxlint-disable\s/v;
1345
+ const biomeIgnoreAllRe = /^\s*\/\*\*\s*biome-ignore-all\s+(?<first>[\w\/]+)(?<rest>(?:[^\w\/*][^*]*)?)\*\/\s*$/v;
1346
+ const biomeIgnoreAllLineRe = /^\s*\/\/\s*biome-ignore-all\s+(?<first>[\w\/]+)(?<rest>(?:[^\w\/].*)?)$/v;
1347
+ /** Both scan for a fixed delimiter, which a regex does by retrying at every start position — super-linear on a long line for a job `indexOf` does in one pass. */
1348
+ const stripTrailingComment = (str) => {
1349
+ const at = str.indexOf("--");
1350
+ return at === -1 ? str : str.slice(0, at).trimEnd();
1351
+ };
1352
+ const biomeReasonOf = (line) => {
1353
+ const colon = line.indexOf(":");
1354
+ if (colon === -1) return;
1355
+ const close = line.indexOf("*/", colon);
1356
+ return close === -1 ? void 0 : line.slice(colon + 1, close).trim();
1357
+ };
1358
+ const leadingWhitespaceRe = /^\s*/v;
1359
+ const buildEnv = () => ({ ...process.env });
1360
+ const extractJson = (stdout) => {
1361
+ const start = stdout.indexOf("{");
1362
+ if (start === -1) return stdout;
1363
+ return stdout.slice(start);
1364
+ };
1365
+ const absFile = (p) => p.startsWith("/") ? p : joinPath(cwd, p);
1366
+ const collectFileData = async (files, parseDirectives) => {
1367
+ const out = [];
1368
+ for (const filePath of files) {
1369
+ const f = file(filePath);
1370
+ if (await f.exists()) {
1371
+ const orig = await f.text();
1372
+ const lines = orig.split("\n");
1373
+ const directiveLines = parseDirectives(lines);
1374
+ if (directiveLines.length > 0) {
1375
+ const directiveIndexes = new Set(directiveLines.map((d) => d.index));
1376
+ const stripped = lines.filter((_, index) => !directiveIndexes.has(index)).join("\n");
1377
+ out.push({
1378
+ directiveLines,
1379
+ filePath,
1380
+ lines,
1381
+ orig,
1382
+ stripped
1383
+ });
1384
+ }
1385
+ }
1386
+ }
1387
+ return out;
1388
+ };
1389
+ const batchStripRestore = async ({ data, lint }) => {
1390
+ await Promise.all(data.map(async (d) => write(d.filePath, d.stripped)));
1391
+ try {
1392
+ return await lint();
1393
+ } finally {
1394
+ await Promise.all(data.map(async (d) => write(d.filePath, d.orig)));
1395
+ }
1396
+ };
1397
+ const splitOxlintRules = (str) => str.split(",").map((r) => stripTrailingComment(r.trim())).filter(Boolean);
1398
+ const splitBiomeRest = (rest) => {
1399
+ return (rest.split(":")[0] ?? "").split(",").map((r) => r.trim()).filter((r) => r.startsWith("lint/"));
1400
+ };
1401
+ const rebuildBiomeLine = ({ line, rules }) => {
1402
+ const reason = biomeReasonOf(line) ?? "suppressed";
1403
+ return `${leadingWhitespaceRe.exec(line)?.[0] ?? ""}/** biome-ignore-all ${rules.join(", ")}: ${reason} */`;
1404
+ };
1405
+ const firedOxlintByFile = async ({ configPath, files, oxlintBin }) => {
1406
+ const result = await runCapture({
1407
+ args: [
1408
+ oxlintBin,
1409
+ "-c",
1410
+ configPath,
1411
+ "-f",
1412
+ "json",
1413
+ ...files
1414
+ ],
1415
+ command: "bun",
1416
+ env: buildEnv(),
1417
+ label: "oxlint-unused"
1418
+ });
1419
+ const diagnostics = parseOxlintDiagnostics({ stdout: extractJson(result.stdout) });
1420
+ const byFile = /* @__PURE__ */ new Map();
1421
+ for (const d of diagnostics) {
1422
+ const key = absFile(d.file);
1423
+ const set = byFile.get(key) ?? /* @__PURE__ */ new Set();
1424
+ set.add(d.rule);
1425
+ for (const v of normalizeRule(d.rule)) set.add(v);
1426
+ byFile.set(key, set);
1427
+ }
1428
+ return byFile;
1429
+ };
1430
+ const isOxlintRuleFired = (rule, fired) => {
1431
+ if (fired.has(rule)) return true;
1432
+ for (const v of normalizeRule(rule)) if (fired.has(v)) return true;
1433
+ return false;
1434
+ };
1435
+ const parseOxlintDirectiveLines = (lines) => {
1436
+ const directiveLines = [];
1437
+ for (let index = 0; index < lines.length; index += 1) {
1438
+ const line = lines[index] ?? "";
1439
+ oxlintDisableRe.lastIndex = 0;
1440
+ const match = oxlintDisableRe.exec(line);
1441
+ if (match) directiveLines.push({
1442
+ index,
1443
+ rules: splitOxlintRules(match.groups?.rules ?? "")
1444
+ });
1445
+ }
1446
+ return directiveLines;
1447
+ };
1448
+ const partitionOxlintRules = ({ directive, filePath, fired, index }) => {
1449
+ const kept = [];
1450
+ const diagnostics = [];
1451
+ for (const rule of directive.rules) if (isOxlintRuleFired(rule, fired)) kept.push(rule);
1452
+ else diagnostics.push({
1453
+ col: 1,
1454
+ file: filePath,
1455
+ line: index + 1,
1456
+ rule
1457
+ });
1458
+ return {
1459
+ diagnostics,
1460
+ kept
1461
+ };
1462
+ };
1463
+ const rebuildOxlintDirectiveLine = ({ directive, filePath, fired, index, line }) => {
1464
+ oxlintDisableRe.lastIndex = 0;
1465
+ const match = oxlintDisableRe.exec(line);
1466
+ const prefix = match?.groups?.prefix ?? "/* oxlint-disable ";
1467
+ const suffix = match?.groups?.close ?? " */";
1468
+ const { diagnostics, kept } = partitionOxlintRules({
1469
+ directive,
1470
+ filePath,
1471
+ fired,
1472
+ index
1473
+ });
1474
+ if (kept.length === directive.rules.length) return {
1475
+ diagnostics,
1476
+ emitted: [line]
1477
+ };
1478
+ if (kept.length > 0) return {
1479
+ diagnostics,
1480
+ emitted: [`${prefix}${kept.join(", ")}${suffix}`]
1481
+ };
1482
+ return {
1483
+ diagnostics,
1484
+ emitted: []
1485
+ };
1486
+ };
1487
+ const rebuildOxlintFile = async ({ data, dryRun, fired }) => {
1488
+ const result = [];
1489
+ const diagnostics = [];
1490
+ let removed = 0;
1491
+ for (let index = 0; index < data.lines.length; index += 1) {
1492
+ const line = data.lines[index] ?? "";
1493
+ const directive = data.directiveLines.find((d) => d.index === index);
1494
+ if (directive) {
1495
+ const outcome = rebuildOxlintDirectiveLine({
1496
+ directive,
1497
+ filePath: data.filePath,
1498
+ fired,
1499
+ index,
1500
+ line
1501
+ });
1502
+ removed += outcome.diagnostics.length;
1503
+ diagnostics.push(...outcome.diagnostics);
1504
+ result.push(...outcome.emitted);
1505
+ } else result.push(line);
1506
+ }
1507
+ if (removed > 0 && !dryRun) await write(data.filePath, result.join("\n"));
1508
+ return {
1509
+ diagnostics,
1510
+ removed
1511
+ };
1512
+ };
1513
+ const findOxlintDisableFiles = async (filePaths) => {
1514
+ const out = [];
1515
+ for (const fp of filePaths) {
1516
+ const f = file(fp);
1517
+ if (await f.exists()) {
1518
+ const content = await f.text();
1519
+ if (oxlintDisablePresentRe.test(content)) out.push(fp);
1520
+ }
1521
+ }
1522
+ return out;
1523
+ };
1524
+ const findBiomeIgnoreAllFiles = async (filePaths) => {
1525
+ const out = [];
1526
+ for (const fp of filePaths) {
1527
+ const f = file(fp);
1528
+ if (await f.exists()) {
1529
+ if ((await f.text()).includes("biome-ignore-all")) out.push(fp);
1530
+ }
1531
+ }
1532
+ return out;
1533
+ };
1534
+ const firedBiomeByFile = async ({ biomeBin, configDir, files }) => {
1535
+ const result = await runCapture({
1536
+ args: [
1537
+ biomeBin,
1538
+ "lint",
1539
+ "--reporter=json",
1540
+ "--config-path",
1541
+ configDir,
1542
+ ...files
1543
+ ],
1544
+ command: "bun",
1545
+ env: buildEnv(),
1546
+ label: "biome-unused"
1547
+ });
1548
+ const diagnostics = parseBiomeDiagnostics({ stdout: extractJson(result.stdout) });
1549
+ const byFile = /* @__PURE__ */ new Map();
1550
+ for (const d of diagnostics) {
1551
+ const key = absFile(d.file);
1552
+ const set = byFile.get(key) ?? /* @__PURE__ */ new Set();
1553
+ set.add(d.rule);
1554
+ byFile.set(key, set);
1555
+ }
1556
+ return byFile;
1557
+ };
1558
+ const parseBiomeDirectiveLines = (lines) => {
1559
+ const directiveLines = [];
1560
+ for (let index = 0; index < lines.length; index += 1) {
1561
+ const line = lines[index] ?? "";
1562
+ biomeIgnoreAllRe.lastIndex = 0;
1563
+ biomeIgnoreAllLineRe.lastIndex = 0;
1564
+ const match = biomeIgnoreAllRe.exec(line) ?? biomeIgnoreAllLineRe.exec(line);
1565
+ if (match) {
1566
+ const first = match.groups?.first ?? "";
1567
+ const rest = match.groups?.rest ?? "";
1568
+ directiveLines.push({
1569
+ index,
1570
+ rules: [first, ...splitBiomeRest(rest)]
1571
+ });
1572
+ }
1573
+ }
1574
+ return directiveLines;
1575
+ };
1576
+ const partitionBiomeRules = ({ directive, filePath, fired, index }) => {
1577
+ const kept = [];
1578
+ const diagnostics = [];
1579
+ for (const rule of directive.rules) if (fired.has(rule)) kept.push(rule);
1580
+ else diagnostics.push({
1581
+ col: 1,
1582
+ file: filePath,
1583
+ line: index + 1,
1584
+ rule
1585
+ });
1586
+ return {
1587
+ diagnostics,
1588
+ kept
1589
+ };
1590
+ };
1591
+ const rebuildBiomeDirectiveLine = ({ directive, filePath, fired, index, line }) => {
1592
+ const { diagnostics, kept } = partitionBiomeRules({
1593
+ directive,
1594
+ filePath,
1595
+ fired,
1596
+ index
1597
+ });
1598
+ if (kept.length === directive.rules.length) return {
1599
+ diagnostics,
1600
+ emitted: [line]
1601
+ };
1602
+ if (kept.length > 0) return {
1603
+ diagnostics,
1604
+ emitted: [rebuildBiomeLine({
1605
+ line,
1606
+ rules: kept
1607
+ })]
1608
+ };
1609
+ return {
1610
+ diagnostics,
1611
+ emitted: []
1612
+ };
1613
+ };
1614
+ const rebuildBiomeFile = async ({ data, dryRun, fired }) => {
1615
+ const result = [];
1616
+ const diagnostics = [];
1617
+ let removed = 0;
1618
+ for (let index = 0; index < data.lines.length; index += 1) {
1619
+ const line = data.lines[index] ?? "";
1620
+ const directive = data.directiveLines.find((d) => d.index === index);
1621
+ if (directive) {
1622
+ const outcome = rebuildBiomeDirectiveLine({
1623
+ directive,
1624
+ filePath: data.filePath,
1625
+ fired,
1626
+ index,
1627
+ line
1628
+ });
1629
+ removed += outcome.diagnostics.length;
1630
+ diagnostics.push(...outcome.diagnostics);
1631
+ result.push(...outcome.emitted);
1632
+ } else result.push(line);
1633
+ }
1634
+ if (removed > 0 && !dryRun) await write(data.filePath, result.join("\n"));
1635
+ return {
1636
+ diagnostics,
1637
+ removed
1638
+ };
1639
+ };
1640
+ const removeUnusedSuppressions = async ({ dryRun = false, filePaths, root }) => {
1641
+ const targets = filePaths ?? [];
1642
+ if (targets.length === 0) return {
1643
+ diagnostics: [],
1644
+ files: [],
1645
+ removed: 0
1646
+ };
1647
+ const configDir = joinPath(root, cacheDir);
1648
+ const oxlintConfigPath = joinPath(configDir, ".oxlintrc.json");
1649
+ const [oxlintBin, biomeBin] = await Promise.all([resolveBin({
1650
+ bin: "oxlint",
1651
+ pkg: "oxlint"
1652
+ }), resolveBin({
1653
+ bin: "biome",
1654
+ pkg: "@biomejs/biome"
1655
+ })]);
1656
+ const changedFiles = /* @__PURE__ */ new Set();
1657
+ const diagnostics = [];
1658
+ let removed = 0;
1659
+ const oxlintData = await collectFileData(await findOxlintDisableFiles(targets), parseOxlintDirectiveLines);
1660
+ if (oxlintData.length > 0) {
1661
+ const firedByFile = await batchStripRestore({
1662
+ data: oxlintData,
1663
+ lint: async () => firedOxlintByFile({
1664
+ configPath: oxlintConfigPath,
1665
+ files: oxlintData.map((d) => d.filePath),
1666
+ oxlintBin
1667
+ })
1668
+ });
1669
+ for (const data of oxlintData) {
1670
+ const outcome = await rebuildOxlintFile({
1671
+ data,
1672
+ dryRun,
1673
+ fired: firedByFile.get(absFile(data.filePath)) ?? /* @__PURE__ */ new Set()
1674
+ });
1675
+ if (outcome.removed > 0) {
1676
+ removed += outcome.removed;
1677
+ changedFiles.add(data.filePath);
1678
+ }
1679
+ diagnostics.push(...outcome.diagnostics);
1680
+ }
1681
+ }
1682
+ const biomeData = await collectFileData(await findBiomeIgnoreAllFiles(targets), parseBiomeDirectiveLines);
1683
+ if (biomeData.length > 0) {
1684
+ const firedByFile = await batchStripRestore({
1685
+ data: biomeData,
1686
+ lint: async () => firedBiomeByFile({
1687
+ biomeBin,
1688
+ configDir,
1689
+ files: biomeData.map((d) => d.filePath)
1690
+ })
1691
+ });
1692
+ for (const data of biomeData) {
1693
+ const outcome = await rebuildBiomeFile({
1694
+ data,
1695
+ dryRun,
1696
+ fired: firedByFile.get(absFile(data.filePath)) ?? /* @__PURE__ */ new Set()
1697
+ });
1698
+ if (outcome.removed > 0) {
1699
+ removed += outcome.removed;
1700
+ changedFiles.add(data.filePath);
1701
+ }
1702
+ diagnostics.push(...outcome.diagnostics);
1703
+ }
1704
+ }
1705
+ return {
1706
+ diagnostics,
1707
+ files: [...changedFiles],
1708
+ removed
1709
+ };
1710
+ };
1711
+ //#endregion
1712
+ //#region src/pipeline.ts
1713
+ /** biome-ignore-all lint/performance/noAwaitInLoops: sequential pipeline fix steps mutate files in order */
1714
+ const emitExtra = (result) => {
1715
+ for (const note of result.notes) process.stderr.write(`lintmax: ${note}\n`);
1716
+ return result.diagnostics;
1717
+ };
1718
+ const formatFailureDetails = (failures) => failures.map((item) => {
1719
+ const messageLine = item.message ? `\n${item.message}` : "";
1720
+ return `- ${item.label} (exit ${item.code})${messageLine}`;
1721
+ }).join("\n");
1722
+ const createStepExecutor = ({ env, failures, root }) => {
1723
+ const runContinue = async (opts) => {
1724
+ try {
1725
+ await run(opts);
1726
+ } catch (error) {
1727
+ if (error instanceof CliExitError) {
1728
+ failures.push({
1729
+ code: error.code,
1730
+ label: opts.label,
1731
+ message: error.message.length > 0 ? error.message : void 0
1732
+ });
1733
+ return;
1734
+ }
1735
+ throw error;
1736
+ }
1737
+ };
1738
+ const runCompactContinue = async ({ human = false, mode }) => {
1739
+ try {
1740
+ await runCompact({
1741
+ env,
1742
+ human,
1743
+ mode,
1744
+ root
1745
+ });
1746
+ } catch (error) {
1747
+ if (error instanceof CliExitError) {
1748
+ failures.push({
1749
+ code: error.code,
1750
+ label: "compact",
1751
+ message: error.message.length > 0 ? error.message : void 0
1752
+ });
1753
+ return;
1754
+ }
1755
+ throw error;
1756
+ }
1757
+ };
1758
+ const runSteps = async ({ steps }) => {
1759
+ for (const step of steps) {
1760
+ const opts = {
1761
+ args: step.args,
1762
+ command: step.command ?? "bun",
1763
+ env,
1764
+ label: step.label,
1765
+ silent: step.silent
1766
+ };
1767
+ await runContinue(opts);
1768
+ }
1769
+ };
1770
+ const runStepsSilent = async ({ steps }) => {
1771
+ for (const step of steps) {
1772
+ const result = await runCapture({
1773
+ args: step.args,
1774
+ command: step.command ?? "bun",
1775
+ env,
1776
+ label: step.label
1777
+ });
1778
+ if (result.exitCode !== 0) failures.push({
1779
+ code: result.exitCode,
1780
+ label: step.label,
1781
+ message: result.stderr.length > 0 ? result.stderr.trim() : void 0
1782
+ });
1783
+ }
1784
+ };
1785
+ const clearFailures = () => {
1786
+ failures.length = 0;
1787
+ };
1788
+ const throwIfFailures = () => {
1789
+ if (failures.length === 0) return;
1790
+ const details = formatFailureDetails(failures);
1791
+ throw new CliExitError({
1792
+ code: failures[0]?.code ?? 1,
1793
+ message: `One or more steps failed:\n${details}`
1794
+ });
1795
+ };
1796
+ return {
1797
+ clearFailures,
1798
+ runCompactContinue,
1799
+ runSteps,
1800
+ runStepsSilent,
1801
+ throwIfFailures
1802
+ };
1803
+ };
1804
+ const createCheckSteps = ({ biomeBin, dir, eslintArgs, eslintBin, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson }) => {
1805
+ const oxlintCliAllow = [...OXLINT_CLI_ALLOW.flatMap((r) => ["--allow", r]), ...oxlintIgnorePatterns.flatMap((p) => ["--ignore-pattern", p])];
1806
+ const steps = [
1807
+ {
1808
+ args: [
1809
+ sortPkgJson,
1810
+ "--check",
1811
+ "**/package.json",
1812
+ "--ignore",
1813
+ "**/node_modules/**"
1814
+ ],
1815
+ label: "sort-package-json"
1816
+ },
1817
+ {
1818
+ args: [
1819
+ biomeBin,
1820
+ "ci",
1821
+ "--config-path",
1822
+ dir,
1823
+ "--diagnostic-level=error"
1824
+ ],
1825
+ label: "biome"
1826
+ },
1827
+ {
1828
+ args: [
1829
+ oxlintBin,
1830
+ "-c",
1831
+ joinPath(dir, ".oxlintrc.json"),
1832
+ "--quiet",
1833
+ "--no-error-on-unmatched-pattern",
1834
+ ...oxlintCliAllow
1835
+ ],
1836
+ label: "oxlint"
1837
+ },
1838
+ {
1839
+ args: [
1840
+ eslintBin,
1841
+ "--no-error-on-unmatched-pattern",
1842
+ ...eslintArgs
1843
+ ],
1844
+ label: "eslint"
1845
+ }
1846
+ ];
1847
+ if (prettierMarkdownTargets.length > 0) steps.push({
1848
+ args: [
1849
+ prettierBin,
1850
+ ...PRETTIER_MD_ARGS,
1851
+ "--check",
1852
+ "--no-error-on-unmatched-pattern",
1853
+ ...prettierMarkdownTargets
1854
+ ],
1855
+ label: "prettier"
1856
+ });
1857
+ return steps;
1858
+ };
1859
+ const createFixSteps = ({ biomeBin, dir, eslintArgs, eslintBin, hasFlowmark, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson }) => {
1860
+ const oxlintCliAllow = [...OXLINT_CLI_ALLOW.flatMap((r) => ["--allow", r]), ...oxlintIgnorePatterns.flatMap((p) => ["--ignore-pattern", p])];
1861
+ const steps = [
1862
+ {
1863
+ args: [
1864
+ sortPkgJson,
1865
+ "**/package.json",
1866
+ "--ignore",
1867
+ "**/node_modules/**"
1868
+ ],
1869
+ label: "sort-package-json",
1870
+ silent: true
1871
+ },
1872
+ {
1873
+ args: [
1874
+ biomeBin,
1875
+ "check",
1876
+ "--config-path",
1877
+ dir,
1878
+ "--fix",
1879
+ "--diagnostic-level=error"
1880
+ ],
1881
+ label: "biome",
1882
+ silent: true
1883
+ },
1884
+ {
1885
+ args: [
1886
+ oxlintBin,
1887
+ "-c",
1888
+ joinPath(dir, ".oxlintrc.json"),
1889
+ "--fix",
1890
+ "--fix-suggestions",
1891
+ "--quiet",
1892
+ "--no-error-on-unmatched-pattern",
1893
+ ...oxlintCliAllow
1894
+ ],
1895
+ label: "oxlint",
1896
+ silent: true
1897
+ },
1898
+ {
1899
+ args: [
1900
+ eslintBin,
1901
+ ...eslintArgs,
1902
+ "--fix"
1903
+ ],
1904
+ label: "eslint",
1905
+ silent: true
1906
+ },
1907
+ {
1908
+ args: [
1909
+ biomeBin,
1910
+ "check",
1911
+ "--config-path",
1912
+ dir,
1913
+ "--fix",
1914
+ "--diagnostic-level=error"
1915
+ ],
1916
+ label: "biome",
1917
+ silent: true
1918
+ }
1919
+ ];
1920
+ if (hasFlowmark) steps.push({
1921
+ args: [
1922
+ "-w",
1923
+ "0",
1924
+ "--auto",
1925
+ "."
1926
+ ],
1927
+ command: "flowmark",
1928
+ label: "flowmark",
1929
+ silent: true
1930
+ });
1931
+ if (prettierMarkdownTargets.length > 0) steps.push({
1932
+ args: [
1933
+ prettierBin,
1934
+ ...PRETTIER_MD_ARGS,
1935
+ "--write",
1936
+ "--no-error-on-unmatched-pattern",
1937
+ ...prettierMarkdownTargets
1938
+ ],
1939
+ label: "prettier",
1940
+ silent: true
1941
+ });
1942
+ return steps;
1943
+ };
1944
+ const captureAndParse = async ({ env, failures, label, opts, parser }) => {
1945
+ const result = await runCapture({
1946
+ args: opts.args,
1947
+ command: opts.command,
1948
+ env,
1949
+ label
1950
+ });
1951
+ if (result.exitCode === 0) return [];
1952
+ const diagnostics = parser(result);
1953
+ if (diagnostics.length > 0) return diagnostics;
1954
+ const stderr = result.stderr.trim();
1955
+ const stdout = result.stdout.trim();
1956
+ const stdoutFirst = stdout.split("\n", 1)[0]?.trimStart() ?? "";
1957
+ const stdoutMessage = stdoutFirst.startsWith("[") || stdoutFirst.startsWith("{") ? void 0 : stdout || void 0;
1958
+ const message = stderr.length > 0 ? stderr : stdoutMessage;
1959
+ failures.push({
1960
+ code: result.exitCode,
1961
+ label,
1962
+ message
1963
+ });
1964
+ return [];
1965
+ };
1966
+ const runAgentCheck = async ({ biomeBin, dir, env, eslintArgs, eslintBin, failures, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson }) => {
1967
+ const oxlintCliAllow = [...OXLINT_CLI_ALLOW.flatMap((r) => ["--allow", r]), ...oxlintIgnorePatterns.flatMap((p) => ["--ignore-pattern", p])];
1968
+ const allDiagnostics = [];
1969
+ const push = (d) => {
1970
+ if (d.length > 0) allDiagnostics.push(...d);
1971
+ };
1972
+ push(await captureAndParse({
1973
+ env,
1974
+ failures,
1975
+ label: "sort-package-json",
1976
+ opts: {
1977
+ args: [
1978
+ sortPkgJson,
1979
+ "--check",
1980
+ "**/package.json",
1981
+ "--ignore",
1982
+ "**/node_modules/**"
1983
+ ],
1984
+ command: "bun"
1985
+ },
1986
+ parser: parseSortPackageJsonOutput
1987
+ }));
1988
+ push(await captureAndParse({
1989
+ env,
1990
+ failures,
1991
+ label: "biome",
1992
+ opts: {
1993
+ args: [
1994
+ biomeBin,
1995
+ "check",
1996
+ "--config-path",
1997
+ dir,
1998
+ "--reporter=json"
1999
+ ],
2000
+ command: "bun"
2001
+ },
2002
+ parser: ({ stdout }) => parseBiomeDiagnostics({ stdout })
2003
+ }));
2004
+ push(await captureAndParse({
2005
+ env,
2006
+ failures,
2007
+ label: "oxlint",
2008
+ opts: {
2009
+ args: [
2010
+ oxlintBin,
2011
+ "-c",
2012
+ joinPath(dir, ".oxlintrc.json"),
2013
+ "--quiet",
2014
+ "--no-error-on-unmatched-pattern",
2015
+ "-f",
2016
+ "json",
2017
+ ...oxlintCliAllow
2018
+ ],
2019
+ command: "bun"
2020
+ },
2021
+ parser: ({ stdout }) => parseOxlintDiagnostics({ stdout })
2022
+ }));
2023
+ push(await captureAndParse({
2024
+ env,
2025
+ failures,
2026
+ label: "eslint",
2027
+ opts: {
2028
+ args: [
2029
+ eslintBin,
2030
+ "--no-error-on-unmatched-pattern",
2031
+ ...eslintArgs,
2032
+ "-f",
2033
+ "json"
2034
+ ],
2035
+ command: "bun"
2036
+ },
2037
+ parser: ({ stdout }) => parseEslintDiagnostics({ stdout })
2038
+ }));
2039
+ if (prettierMarkdownTargets.length > 0) push(await captureAndParse({
2040
+ env,
2041
+ failures,
2042
+ label: "prettier",
2043
+ opts: {
2044
+ args: [
2045
+ prettierBin,
2046
+ ...PRETTIER_MD_ARGS,
2047
+ "--list-different",
2048
+ "--no-error-on-unmatched-pattern",
2049
+ ...prettierMarkdownTargets
2050
+ ],
2051
+ command: "bun"
2052
+ },
2053
+ parser: ({ stdout }) => parsePrettierOutput({ stdout })
2054
+ }));
2055
+ return allDiagnostics;
2056
+ };
2057
+ const unusedToDiagnostics = ({ root, unused }) => {
2058
+ const prefix = `${root}/`;
2059
+ const out = [];
2060
+ for (const u of unused) out.push({
2061
+ file: u.file.startsWith(prefix) ? u.file.slice(prefix.length) : u.file,
2062
+ line: u.line,
2063
+ linter: "unused-suppression",
2064
+ rule: u.rule ?? "unused-disable-directive"
2065
+ });
2066
+ return out;
2067
+ };
2068
+ const dangerousToDiagnostics = (items) => items.map((d) => ({
2069
+ file: d.file,
2070
+ line: d.line,
2071
+ linter: "forbidden-suppression",
2072
+ rule: d.rule
2073
+ }));
2074
+ const isGitWorkTree = async ({ env, root }) => (await $`git -C ${root} rev-parse --is-inside-work-tree`.env(env).quiet().nothrow()).exitCode === 0;
2075
+ const PRETTIER_EXTENSIONS = [
2076
+ ".md",
2077
+ ".yml",
2078
+ ".yaml"
2079
+ ];
2080
+ const isPrettierTarget = (filePath) => PRETTIER_EXTENSIONS.some((ext) => filePath.endsWith(ext));
2081
+ const scanPrettierTargets = async ({ isIgnored, root }) => {
2082
+ const found = [];
2083
+ const glob = new Glob(`**/*{${PRETTIER_EXTENSIONS.join(",")}}`);
2084
+ for await (const path of glob.scan({
2085
+ absolute: false,
2086
+ cwd: root,
2087
+ dot: false
2088
+ })) if (!(path.includes("node_modules") || isIgnored(path))) found.push(path);
2089
+ return found;
2090
+ };
2091
+ const createPrettierMarkdownTargets = async ({ gitFiles, gitWorkTree, isIgnored, root }) => {
2092
+ if (gitWorkTree) return gitFiles.filter((f) => isPrettierTarget(f) && !isIgnored(f));
2093
+ return await scanPrettierTargets({
2094
+ isIgnored,
2095
+ root
2096
+ });
2097
+ };
2098
+ const throwAgentResults = ({ diagnostics, failures }) => {
2099
+ if (diagnostics.length === 0 && failures.length === 0) return;
2100
+ const output = formatGrouped({ files: aggregate({ diagnostics }) });
2101
+ if (output.length > 0) process.stdout.write(`${output}\n`);
2102
+ if (failures.length > 0) {
2103
+ const details = formatFailureDetails(failures);
2104
+ process.stderr.write(`${details}\n`);
2105
+ }
2106
+ throw new CliExitError({ code: 1 });
2107
+ };
2108
+ const readOxlintIgnorePatterns = async ({ dir }) => {
2109
+ const generated = file(joinPath(dir, ".oxlintrc.json"));
2110
+ if (!await generated.exists()) return [...DEFAULT_SHARED_IGNORE_PATTERNS];
2111
+ const patterns = (await generated.json()).ignorePatterns;
2112
+ if (!Array.isArray(patterns)) return [...DEFAULT_SHARED_IGNORE_PATTERNS];
2113
+ return patterns.filter((x) => typeof x === "string");
2114
+ };
2115
+ const collectAgentDiagnostics = async (ctx) => {
2116
+ const allDiagnostics = await runAgentCheck(ctx.agentParams);
2117
+ if (ctx.shouldComments) allDiagnostics.push(...await checkComments({ files: ctx.sourceFiles }));
2118
+ allDiagnostics.push(...await checkClassName({ root: cwd }), ...await checkJsxExtension({ root: cwd }));
2119
+ return allDiagnostics;
2120
+ };
2121
+ const runFixHuman = async (ctx) => {
2122
+ await ctx.runSteps({ steps: ctx.checkSteps });
2123
+ const extraHuman = emitExtra(await runExtraCoverage({
2124
+ bins: ctx.extraBins,
2125
+ command: "fix",
2126
+ env: ctx.env,
2127
+ gitFiles: ctx.allGitFiles
2128
+ }));
2129
+ if (extraHuman.length > 0) {
2130
+ const output = formatGrouped({ files: aggregate({ diagnostics: extraHuman }) });
2131
+ if (output.length > 0) process.stdout.write(`${output}\n`);
2132
+ ctx.failures.push({
2133
+ code: 1,
2134
+ label: "extra-coverage"
2135
+ });
2136
+ }
2137
+ ctx.throwIfFailures();
2138
+ };
2139
+ const runFixAgent = async (ctx) => {
2140
+ const allDiagnostics = await collectAgentDiagnostics(ctx);
2141
+ allDiagnostics.push(...emitExtra(await runExtraCoverage({
2142
+ bins: ctx.extraBins,
2143
+ command: "fix",
2144
+ env: ctx.env,
2145
+ gitFiles: ctx.allGitFiles
2146
+ })));
2147
+ throwAgentResults({
2148
+ diagnostics: allDiagnostics,
2149
+ failures: ctx.failures
2150
+ });
2151
+ };
2152
+ const runCheckHuman = async (ctx) => {
2153
+ await ctx.runSteps({ steps: ctx.checkSteps });
2154
+ const cnDiagsHuman = await checkClassName({ root: cwd });
2155
+ const jsxDiagsHuman = await checkJsxExtension({ root: cwd });
2156
+ const unusedHuman = ctx.sourceFiles.length > 0 ? await removeUnusedSuppressions({
2157
+ dryRun: true,
2158
+ filePaths: ctx.sourceFiles.map((f) => joinPath(cwd, f)),
2159
+ root: cwd
2160
+ }) : {
2161
+ diagnostics: [],
2162
+ files: [],
2163
+ removed: 0
2164
+ };
2165
+ const humanCustomDiags = [
2166
+ ...cnDiagsHuman,
2167
+ ...jsxDiagsHuman,
2168
+ ...unusedToDiagnostics({
2169
+ root: cwd,
2170
+ unused: unusedHuman.diagnostics
2171
+ }),
2172
+ ...dangerousToDiagnostics(await findDangerousSuppressions(cwd)),
2173
+ ...emitExtra(await runExtraCoverage({
2174
+ bins: ctx.extraBins,
2175
+ command: "check",
2176
+ env: ctx.env,
2177
+ gitFiles: ctx.allGitFiles
2178
+ }))
2179
+ ];
2180
+ if (humanCustomDiags.length > 0) {
2181
+ const output = formatGrouped({ files: aggregate({ diagnostics: humanCustomDiags }) });
2182
+ if (output.length > 0) process.stdout.write(`${output}\n`);
2183
+ ctx.failures.push({
2184
+ code: 1,
2185
+ label: "cn"
2186
+ });
2187
+ }
2188
+ ctx.throwIfFailures();
2189
+ };
2190
+ const runCheckAgent = async (ctx) => {
2191
+ const allDiagnostics = await collectAgentDiagnostics(ctx);
2192
+ if (ctx.sourceFiles.length > 0) {
2193
+ const unusedAgent = await removeUnusedSuppressions({
2194
+ dryRun: true,
2195
+ filePaths: ctx.sourceFiles.map((f) => joinPath(cwd, f)),
2196
+ root: cwd
2197
+ });
2198
+ allDiagnostics.push(...unusedToDiagnostics({
2199
+ root: cwd,
2200
+ unused: unusedAgent.diagnostics
2201
+ }));
2202
+ }
2203
+ allDiagnostics.push(...dangerousToDiagnostics(await findDangerousSuppressions(cwd)), ...emitExtra(await runExtraCoverage({
2204
+ bins: ctx.extraBins,
2205
+ command: "check",
2206
+ env: ctx.env,
2207
+ gitFiles: ctx.allGitFiles
2208
+ })));
2209
+ if (allDiagnostics.length > 0 || ctx.failures.length > 0) {
2210
+ const output = formatGrouped({ files: aggregate({ diagnostics: allDiagnostics }) });
2211
+ if (output.length > 0) process.stdout.write(`${output}\n`);
2212
+ if (ctx.failures.length > 0) process.stderr.write(`${formatFailureDetails(ctx.failures)}\n`);
2213
+ throw new CliExitError({ code: 1 });
2214
+ }
2215
+ };
2216
+ const buildLintEnv = () => {
2217
+ const bundledBinA = joinPath(lintmaxRoot, "node_modules", ".bin");
2218
+ const bundledBinB = joinPath(dirnamePath(lintmaxRoot), ".bin");
2219
+ const cwdBinDir = joinPath(cwd, "node_modules", ".bin");
2220
+ return {
2221
+ ...env,
2222
+ PATH: `${bundledBinA}:${bundledBinB}:${cwdBinDir}:${env.PATH ?? ""}`
2223
+ };
2224
+ };
2225
+ const synchronizeConfig = async ({ configPath, env }) => {
2226
+ await (await pathExists({ path: configPath }) ? run({
2227
+ args: ["-e", `const m = await import('${configPath}'); const { sync: s } = await import('lintmax'); await s(m.default);`],
2228
+ command: "bun",
2229
+ env,
2230
+ label: "config",
2231
+ silent: true
2232
+ }) : sync());
2233
+ };
2234
+ const resolveAllBins = async () => {
2235
+ return await Promise.all([
2236
+ resolveBin({
2237
+ bin: "sort-package-json",
2238
+ pkg: "sort-package-json"
2239
+ }),
2240
+ resolveBin({
2241
+ bin: "biome",
2242
+ pkg: "@biomejs/biome"
2243
+ }),
2244
+ resolveBin({
2245
+ bin: "oxlint",
2246
+ pkg: "oxlint"
2247
+ }),
2248
+ resolveBin({
2249
+ bin: "eslint",
2250
+ pkg: "eslint"
2251
+ }),
2252
+ resolveBin({
2253
+ bin: "prettier",
2254
+ pkg: "prettier"
2255
+ }),
2256
+ resolveBin({
2257
+ bin: "tombi",
2258
+ pkg: "tombi"
2259
+ }),
2260
+ resolveBin({
2261
+ bin: "dprint",
2262
+ pkg: "dprint"
2263
+ })
2264
+ ]);
2265
+ };
2266
+ const runFixCommand = async ({ clearFailures, ctx, fixSteps, human, runStepsSilent }) => {
2267
+ if (ctx.shouldComments) await fixComments({ files: ctx.sourceFiles });
2268
+ if (ctx.sourceFiles.length > 0) await cleanIgnores(ctx.sourceFiles.map((f) => joinPath(cwd, f)));
2269
+ await (human ? ctx.runSteps({ steps: fixSteps }) : runStepsSilent({ steps: fixSteps }));
2270
+ clearFailures();
2271
+ if (ctx.sourceFiles.length > 0) await removeUnusedSuppressions({
2272
+ filePaths: ctx.sourceFiles.map((f) => joinPath(cwd, f)),
2273
+ root: cwd
2274
+ });
2275
+ await (human ? runFixHuman(ctx) : runFixAgent(ctx));
2276
+ };
2277
+ const runLint = async ({ command, human = false }) => {
2278
+ const dir = joinPath(cwd, cacheDir);
2279
+ await ensureDirectory({ directory: dir });
2280
+ const configPath = joinPath(cwd, "lintmax.config.ts");
2281
+ const runtimePath = joinPath(dir, "lintmax.json");
2282
+ const env = buildLintEnv();
2283
+ await synchronizeConfig({
2284
+ configPath,
2285
+ env
2286
+ });
2287
+ const runtime = await readJson({ path: runtimePath });
2288
+ const failures = [];
2289
+ const { clearFailures, runCompactContinue, runSteps, runStepsSilent, throwIfFailures } = createStepExecutor({
2290
+ env,
2291
+ failures,
2292
+ root: cwd
2293
+ });
2294
+ if (command === "fix" && runtime.compact === true) await runCompactContinue({
2295
+ human,
2296
+ mode: "fix"
2297
+ });
2298
+ const eslintArgs = ["--config", joinPath(dir, "eslint.generated.mjs")];
2299
+ const [sortPkgJson, biomeBin, oxlintBin, eslintBin, prettierBin, tombiBin, dprintBin] = await resolveAllBins();
2300
+ const extraBins = {
2301
+ dprint: dprintBin,
2302
+ tombi: tombiBin
2303
+ };
2304
+ const hasFlowmark = (await $`which flowmark`.env(env).quiet().nothrow()).exitCode === 0;
2305
+ const gitWorkTree = await isGitWorkTree({
2306
+ env,
2307
+ root: cwd
2308
+ });
2309
+ const allGitFiles = gitWorkTree ? await listCompactFiles({
2310
+ env,
2311
+ root: cwd
2312
+ }) : [];
2313
+ const oxlintIgnorePatterns = await readOxlintIgnorePatterns({ dir });
2314
+ const ignoreGlobs = oxlintIgnorePatterns.map((p) => new Glob(p));
2315
+ const isIgnored = (filePath) => ignoreGlobs.some((g) => g.match(filePath));
2316
+ const prettierMarkdownTargets = await createPrettierMarkdownTargets({
2317
+ gitFiles: allGitFiles,
2318
+ gitWorkTree,
2319
+ isIgnored,
2320
+ root: cwd
2321
+ });
2322
+ const checkSteps = createCheckSteps({
2323
+ biomeBin,
2324
+ dir,
2325
+ eslintArgs,
2326
+ eslintBin,
2327
+ oxlintBin,
2328
+ oxlintIgnorePatterns,
2329
+ prettierBin,
2330
+ prettierMarkdownTargets,
2331
+ sortPkgJson
2332
+ });
2333
+ const shouldComments = runtime.comments !== false;
2334
+ const sourceFiles = allGitFiles.filter((f) => !isIgnored(f));
2335
+ const ctx = {
2336
+ agentParams: {
2337
+ biomeBin,
2338
+ dir,
2339
+ env,
2340
+ eslintArgs,
2341
+ eslintBin,
2342
+ failures,
2343
+ oxlintBin,
2344
+ oxlintIgnorePatterns,
2345
+ prettierBin,
2346
+ prettierMarkdownTargets,
2347
+ sortPkgJson
2348
+ },
2349
+ allGitFiles,
2350
+ checkSteps,
2351
+ env,
2352
+ extraBins,
2353
+ failures,
2354
+ runSteps,
2355
+ shouldComments,
2356
+ sourceFiles,
2357
+ throwIfFailures
2358
+ };
2359
+ if (command === "fix") {
2360
+ const fixSteps = createFixSteps({
2361
+ biomeBin,
2362
+ dir,
2363
+ eslintArgs,
2364
+ eslintBin,
2365
+ hasFlowmark,
2366
+ oxlintBin,
2367
+ oxlintIgnorePatterns,
2368
+ prettierBin,
2369
+ prettierMarkdownTargets,
2370
+ sortPkgJson
2371
+ });
2372
+ await runFixCommand({
2373
+ clearFailures,
2374
+ ctx,
2375
+ fixSteps,
2376
+ human,
2377
+ runStepsSilent
2378
+ });
2379
+ return;
2380
+ }
2381
+ await (human ? runCheckHuman(ctx) : runCheckAgent(ctx));
2382
+ };
2383
+ //#endregion
2384
+ //#region src/state.ts
2385
+ const appDir = "lintmax";
2386
+ const fileName = "state.json";
2387
+ const userCacheDir = () => {
2388
+ const home = homedir();
2389
+ if (platform() === "darwin") return joinPath(home, "Library", "Caches");
2390
+ if (platform() === "win32") return env.LOCALAPPDATA ?? joinPath(home, "AppData", "Local");
2391
+ return env.XDG_CACHE_HOME ?? joinPath(home, ".cache");
2392
+ };
2393
+ const statePath = () => {
2394
+ const base = userCacheDir();
2395
+ if (base.length === 0) return joinPath(tmpdir(), appDir, fileName);
2396
+ return joinPath(base, appDir, fileName);
2397
+ };
2398
+ const emptyState = () => ({
2399
+ lastCheck: 0,
2400
+ lastGreenByCwd: {},
2401
+ staleIssues: [],
2402
+ versions: {}
2403
+ });
2404
+ const coerceStaleIssues = (value) => {
2405
+ if (!Array.isArray(value)) return [];
2406
+ const out = [];
2407
+ for (const raw of value) if (isRecord(raw) && typeof raw.name === "string" && typeof raw.ageDays === "number") out.push({
2408
+ ageDays: raw.ageDays,
2409
+ name: raw.name
2410
+ });
2411
+ return out;
2412
+ };
2413
+ const coerceStringMap = (value) => {
2414
+ if (!isRecord(value)) return {};
2415
+ const out = {};
2416
+ for (const [key, raw] of Object.entries(value)) if (typeof raw === "string") out[key] = raw;
2417
+ return out;
2418
+ };
2419
+ const loadState = async () => {
2420
+ const path = statePath();
2421
+ try {
2422
+ const handle = file(path);
2423
+ if (!await handle.exists()) return emptyState();
2424
+ const parsed = JSON.parse(await handle.text());
2425
+ if (!isRecord(parsed)) return emptyState();
2426
+ return {
2427
+ lastCheck: typeof parsed.lastCheck === "number" ? parsed.lastCheck : 0,
2428
+ lastGreenByCwd: coerceStringMap(parsed.lastGreenByCwd),
2429
+ staleIssues: coerceStaleIssues(parsed.staleIssues),
2430
+ versions: coerceStringMap(parsed.versions)
2431
+ };
2432
+ } catch {
2433
+ return emptyState();
2434
+ }
2435
+ };
2436
+ const saveState = async (state) => {
2437
+ const path = statePath();
2438
+ try {
2439
+ await write(path, `${JSON.stringify(state, null, 2)}\n`);
2440
+ } catch {
2441
+ process.exitCode ??= 0;
2442
+ }
2443
+ };
2444
+ const compare = (left, right) => {
2445
+ if (left < right) return -1;
2446
+ return left > right ? 1 : 0;
2447
+ };
2448
+ const hashTree = async ({ files, root, version }) => {
2449
+ const hash = createHash("sha256");
2450
+ hash.update(`lintmax:${version}\n`);
2451
+ const sorted = [...files].toSorted(compare);
2452
+ const digests = await Promise.all(sorted.map(async (relativePath) => {
2453
+ try {
2454
+ const digest = createHash("sha256");
2455
+ digest.update(await file(joinPath(root, relativePath)).bytes());
2456
+ return `${relativePath}:${digest.digest("hex")}\n`;
2457
+ } catch {
2458
+ return `${relativePath}:unreadable\n`;
2459
+ }
2460
+ }));
2461
+ for (const line of digests) hash.update(line);
2462
+ return hash.digest("hex");
2463
+ };
2464
+ //#endregion
2465
+ //#region src/staleness.ts
2466
+ const httpTimeoutMs = 15e3;
2467
+ const cacheTtlMs = 1440 * 60 * 1e3;
2468
+ const sixMonthsMs = 4392 * 60 * 60 * 1e3;
2469
+ const envSkip = "LINTMAX_SKIP_STALENESS";
2470
+ const envForce = "LINTMAX_STALENESS_FORCE";
2471
+ /** Every linter this ships, read from the manifest that declares them. A hand-kept list beside the real one watches whatever it happened to name on the day it was written: it held eight of twenty-four, and the dep pinning the whole fleet to an old eslint major sat outside it, stale for well over a year, unseen. */
2472
+ const trackedPackages = async () => {
2473
+ const deps = (await readJson({ path: joinPath(lintmaxRoot, "package.json") })).dependencies;
2474
+ return isRecord(deps) ? Object.keys(deps).toSorted((a, b) => a.localeCompare(b)) : [];
2475
+ };
2476
+ /** Resolves a package's newest publish time, or throws. The abbreviated packument (`application/vnd.npm.install-v1+json`) carries no `time`, so asking for it and then requiring `time` yielded "unknown" for every package on every run — and "unknown" was being read as "fresh". An unanswerable lookup is reported, never folded into the same value as a healthy one. */
2477
+ const fetchLatestPublish = async (name) => {
2478
+ const response = await fetch(`https://registry.npmjs.org/${name}`, { signal: AbortSignal.timeout(httpTimeoutMs) });
2479
+ if (!response.ok) throw new Error(`registry answered ${String(response.status)} for ${name}`);
2480
+ const body = await response.json();
2481
+ if (!isRecord(body)) throw new Error(`registry sent no document for ${name}`);
2482
+ const distTags = body["dist-tags"];
2483
+ const { time } = body;
2484
+ if (!isRecord(distTags)) throw new Error(`no dist-tags for ${name}`);
2485
+ if (!isRecord(time)) throw new Error(`no publish times for ${name} — the abbreviated packument omits them`);
2486
+ const { latest } = distTags;
2487
+ if (typeof latest !== "string") throw new Error(`no latest tag for ${name}`);
2488
+ const published = time[latest];
2489
+ if (typeof published !== "string") throw new Error(`no publish time for ${name}@${latest}`);
2490
+ const parsed = Date.parse(published);
2491
+ if (Number.isNaN(parsed)) throw new Error(`unparsable publish time for ${name}@${latest}: ${published}`);
2492
+ return parsed;
2493
+ };
2494
+ /** Age alone cannot tell a rotting package from a finished one, so a package leaves the gate ONLY with a reason and the trigger that ends the exception — never by being quietly dropped from the tracked set, which reads identically to "fresh" forever. Each entry is re-argued whenever this list is touched: an inherited exception is not a justified one. */
2495
+ const staleExceptions = {
2496
+ "@types/react-dom": {
2497
+ reason: "DefinitelyTyped publishes actively (@types/react ships within weeks) and react-dom bundles no types of its own, so this is the only type source and its age means the surface is settled, not abandoned",
2498
+ revisitWhen: "react-dom ships bundled types, or @types/react-dom publishes again"
2499
+ },
2500
+ "eslint-plugin-react": {
2501
+ reason: "it is the sole dep still pinning eslint to ^9, and replacing it COSTS coverage: of its 83 active rules oxlint re-owns 49 and @eslint-react/perfectionist re-own 5, 20 are obsolete under the new JSX transform or the propTypes era, 7 belong to the formatter, and 6 have no home anywhere — destructuring-assignment, no-invalid-html-attribute, no-adjacent-inline-elements, plus the class-only no-arrow-function-lifecycle, static-property-placement and require-optimization. Strictness is monotonic-up, so the gate carries a stale dep rather than drop six enforced rules",
2502
+ revisitWhen: "a maintained plugin covers those 6 ids, or every class component is gone (retiring the 3 class-only ones) and the other 3 are re-homed — then drop this dep and take eslint 10"
2503
+ }
2504
+ };
2505
+ const toIssue = (name, publishedAt) => {
2506
+ if (name in staleExceptions) return null;
2507
+ const age = Date.now() - publishedAt;
2508
+ if (age < sixMonthsMs) return null;
2509
+ return {
2510
+ ageDays: Math.floor(age / (1440 * 60 * 1e3)),
2511
+ name
2512
+ };
2513
+ };
2514
+ const scanStaleness = async (force = false) => {
2515
+ if (envValue(envSkip) === "1") return [];
2516
+ const ci = envValue("CI") === "true" || envValue("CI") === "1";
2517
+ const forced = force || ci || envValue(envForce) === "1";
2518
+ const state = await loadState();
2519
+ if (!forced && state.lastCheck > 0 && Date.now() - state.lastCheck < cacheTtlMs) return state.staleIssues;
2520
+ const names = await trackedPackages();
2521
+ const issues = (await Promise.all(names.map(async (name) => {
2522
+ const publishedAt = await fetchLatestPublish(name);
2523
+ return toIssue(name, publishedAt);
2524
+ }))).filter((issue) => issue !== null);
2525
+ await saveState({
2526
+ ...state,
2527
+ lastCheck: Date.now(),
2528
+ staleIssues: issues
2529
+ });
2530
+ return issues;
2531
+ };
2532
+ const formatStaleness = (issues) => {
2533
+ if (issues.length === 0) return "";
2534
+ return `lintmax: stale linter deps (advisory):\n${issues.map((issue) => ` ${issue.name} latest release ${issue.ageDays}d old (>6mo)`).join("\n")}`;
2535
+ };
2536
+ //#endregion
2537
+ //#region src/gate.ts
2538
+ const envNoCache = "LINTMAX_NO_CACHE";
2539
+ const listTrackedFiles = async () => {
2540
+ if ((await $`git -C ${cwd} rev-parse --is-inside-work-tree`.env(bunEnv).quiet().nothrow()).exitCode !== 0) return null;
2541
+ const result = await $`git -C ${cwd} ls-files -z --cached --others --exclude-standard`.env(bunEnv).quiet().nothrow();
2542
+ if (result.exitCode !== 0) return null;
2543
+ return result.stdout.toString().split("\0").filter((entry) => entry.length > 0);
2544
+ };
2545
+ const computeGreenKey = async (version) => {
2546
+ if (envValue(envNoCache) === "1") return null;
2547
+ const files = await listTrackedFiles();
2548
+ if (files === null) return null;
2549
+ return hashTree({
2550
+ files,
2551
+ root: cwd,
2552
+ version
2553
+ });
2554
+ };
2555
+ const tryCached = async (greenKey) => {
2556
+ if (greenKey === null) return false;
2557
+ if ((await loadState()).lastGreenByCwd[cwd] !== greenKey) return false;
2558
+ process.stdout.write("ok (cached)\n");
2559
+ return true;
2560
+ };
2561
+ const persistGreen = async (greenKey) => {
2562
+ if (greenKey === null) return;
2563
+ const state = await loadState();
2564
+ state.lastGreenByCwd[cwd] = greenKey;
2565
+ await saveState(state);
2566
+ };
2567
+ /** A stale dep FAILS the gate: the baseline is clean, so every finding here is a new one, and a warning nobody has to act on is how the check sat broken for its whole life while printing nothing. A dep leaves the gate through `staleExceptions` with its reason and trigger, never by being tolerated in the output. A scan that cannot reach the registry is reported and does NOT fail — an offline developer is never blocked by it, but the silence that once read as clean is gone. */
2568
+ const emitStaleness = async () => {
2569
+ try {
2570
+ const formatted = formatStaleness(await scanStaleness());
2571
+ if (formatted.length > 0) {
2572
+ process.stderr.write(`${formatted}\n`);
2573
+ process.exitCode = 1;
2574
+ }
2575
+ } catch (error) {
2576
+ const reason = error instanceof Error ? error.message : String(error);
2577
+ process.stderr.write(`lintmax: staleness scan could not complete, so dep freshness is UNKNOWN: ${reason}\n`);
2578
+ }
2579
+ };
2580
+ const runGate = async ({ command, human, version }) => {
2581
+ const startKey = await computeGreenKey(version);
2582
+ if (await tryCached(startKey)) return;
2583
+ const stalePromise = emitStaleness();
2584
+ await runLint({
2585
+ command,
2586
+ human
2587
+ });
2588
+ await persistGreen(await computeGreenKey(version));
2589
+ await stalePromise;
2590
+ process.stdout.write("ok\n");
2591
+ };
2592
+ //#endregion
2593
+ //#region src/cli.ts
2594
+ const command = process.argv[2];
2595
+ const main = async () => {
2596
+ const version = await readVersion();
2597
+ if (command === "--version" || command === "-v" || command === "version") {
2598
+ process.stdout.write(`${version}\n`);
2599
+ return;
2600
+ }
2601
+ if (command === "rules") {
2602
+ const human = process.argv.includes("--human");
2603
+ const rules = await extractAllRules();
2604
+ const output = human ? formatRulesHuman(rules) : formatRulesCompact(rules);
2605
+ process.stdout.write(`${output}\n`);
2606
+ return;
2607
+ }
2608
+ if (command !== "fix" && command !== "check") {
2609
+ usage({ version });
2610
+ if (command === "--help" || command === "-h") return;
2611
+ throw new CliExitError({ code: 1 });
2612
+ }
2613
+ const human = process.argv.includes("--human");
2614
+ await runGate({
2615
+ command,
2616
+ human,
2617
+ version
2618
+ });
2619
+ };
2620
+ try {
2621
+ await main();
2622
+ } catch (error) {
2623
+ if (error instanceof CliExitError) {
2624
+ if (error.message.length > 0) process.stderr.write(`${error.message}\n`);
2625
+ process.exitCode = error.code;
2626
+ } else throw error;
2627
+ }
2628
+ //#endregion
2629
+ export {};