lintmax 0.1.106 → 0.1.108

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 CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env bun
2
- import { B as OXLINT_CLI_ALLOW, D as isRecord, H as PARSE_DIALECTS, R as DEFAULT_SHARED_IGNORE_PATTERNS, S as joinPath, _ as runCapture, a as cacheDir, b as fromFileUrl, c as ensureDirectory, d as pathExists, f as readJson, g as run, h as resolveBin, i as PRETTIER_MD_ARGS, l as envValue, m as readVersion, n as listProjectFiles, o as cwd, p as readRequiredJson, r as CliExitError, s as decodeText, t as escapeGlobPath, u as lintmaxRoot, v as usage, y as dirnamePath, z as ESLINT_TEST_FILE_PATTERNS } from "./project-files-C4cvEhY7.mjs";
3
- import { r as sync } from "./src-DDkinCyR.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 { homedir, platform, tmpdir } from "node:os";
2
+ import { B as ESLINT_TEST_FILE_PATTERNS, C as joinPath, O as isRecord, U as PARSE_DIALECTS, V as OXLINT_CLI_ALLOW, _ as run, a as PRETTIER_MD_ARGS, b as dirnamePath, c as decodeText, d as envValue, f as lintmaxRoot, g as resolveBin, h as readVersion, i as CliExitError, l as doesPathExist, m as readRequiredJson, n as listProjectFiles, o as cacheDir, p as readJson, r as doesMatchGlob, s as cwd, t as escapeGlobPath, u as ensureDirectory, v as runCapture, x as fromFileUrl, y as usage, z as DEFAULT_SHARED_IGNORE_PATTERNS } from "./project-files-DkcnsKmB.mjs";
3
+ import { $, Glob, env, file, which, write } from "bun";
8
4
  import { Buffer } from "node:buffer";
9
- import { parseSync } from "oxc-parser";
5
+ import { homedir, platform, tmpdir } from "node:os";
6
+ import { parse } from "oxc-parser";
10
7
  import { ESLint } from "eslint";
8
+ import { lstat, unlink } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { r as sync } from "./src-Cu2vOuEp.mjs";
11
11
  import { createHash } from "node:crypto";
12
- //#region src/rule-equivalence.ts
12
+ // src/rule-equivalence.ts
13
13
  const equivalenceGroups = [
14
14
  [
15
15
  "lint/suspicious/noExplicitAny",
@@ -113,8 +113,7 @@ for (const group of equivalenceGroups) {
113
113
  for (const rule of group) ruleToCanonical.set(rule, canonical);
114
114
  }
115
115
  const getCanonicalRule = (rule) => ruleToCanonical.get(rule) ?? rule;
116
- //#endregion
117
- //#region src/aggregate.ts
116
+ // src/aggregate.ts
118
117
  const LINTER_PRIORITY = {
119
118
  biome: 0,
120
119
  eslint: 2,
@@ -127,6 +126,16 @@ const normalizePath = (filePath) => {
127
126
  if (filePath.startsWith(cwdPrefix)) return filePath.slice(cwdPrefix.length);
128
127
  return filePath;
129
128
  };
129
+ const biomeEntries = (diagnostics) => diagnostics.flatMap((d) => {
130
+ const filePath = d.location?.path;
131
+ const { category } = d;
132
+ return filePath && category ? [{
133
+ file: normalizePath(filePath),
134
+ line: d.location?.start?.line ?? 0,
135
+ linter: "biome",
136
+ rule: category
137
+ }] : [];
138
+ });
130
139
  const parseBiomeDiagnostics = ({ stdout }) => {
131
140
  let parsed;
132
141
  try {
@@ -135,22 +144,18 @@ const parseBiomeDiagnostics = ({ stdout }) => {
135
144
  return [];
136
145
  }
137
146
  if (!Array.isArray(parsed.diagnostics)) return [];
138
- const results = [];
139
- for (const d of parsed.diagnostics) {
140
- const filePath = d.location?.path;
141
- const { category } = d;
142
- if (filePath && category) {
143
- const line = d.location?.start?.line ?? 0;
144
- results.push({
145
- file: normalizePath(filePath),
146
- line,
147
- linter: "biome",
148
- rule: category
149
- });
150
- }
151
- }
152
- return results;
153
- };
147
+ return biomeEntries(parsed.diagnostics);
148
+ };
149
+ const oxlintEntries = (diagnostics) => diagnostics.flatMap((d) => {
150
+ const filePath = d.filename ?? "";
151
+ const rule = d.code;
152
+ return rule ? [{
153
+ file: filePath.length > 0 ? normalizePath(filePath) : "<unknown>",
154
+ line: d.labels?.[0]?.span?.line ?? 0,
155
+ linter: "oxlint",
156
+ rule
157
+ }] : [];
158
+ });
154
159
  const parseOxlintDiagnostics = ({ stdout }) => {
155
160
  let parsed;
156
161
  try {
@@ -159,23 +164,9 @@ const parseOxlintDiagnostics = ({ stdout }) => {
159
164
  return [];
160
165
  }
161
166
  if (!Array.isArray(parsed.diagnostics)) return [];
162
- const results = [];
163
- for (const d of parsed.diagnostics) {
164
- const filePath = d.filename ?? "";
165
- const rule = d.code;
166
- if (rule) {
167
- const line = d.labels?.[0]?.span?.line ?? 0;
168
- results.push({
169
- file: filePath.length > 0 ? normalizePath(filePath) : "<unknown>",
170
- line,
171
- linter: "oxlint",
172
- rule
173
- });
174
- }
175
- }
176
- return results;
167
+ return oxlintEntries(parsed.diagnostics);
177
168
  };
178
- const eslintRuleOf = (msg) => msg.ruleId ?? (msg.severity === 2 || msg.fatal ? `parse-error: ${msg.message?.slice(0, 80) ?? "unknown"}` : null);
169
+ const eslintRuleOf = (msg) => msg.ruleId ?? (msg.severity === 2 || msg.fatal ? `parse-error: ${msg.message?.slice(0, 80) ?? "unknown"}` : void 0);
179
170
  const eslintDiagnosticsForFile = (fileEntry) => {
180
171
  const { filePath } = fileEntry;
181
172
  if (!(filePath && Array.isArray(fileEntry.messages))) return [];
@@ -246,50 +237,57 @@ const dedup = (diagnostics) => {
246
237
  return [...seen.values()];
247
238
  };
248
239
  const linterSort = (a, b) => (LINTER_PRIORITY[a] ?? 99) - (LINTER_PRIORITY[b] ?? 99);
249
- const aggregate = ({ diagnostics }) => {
240
+ const getOrCreate = (map, key, create) => {
241
+ const existing = map.get(key);
242
+ if (existing !== void 0) return existing;
243
+ const value = create();
244
+ map.set(key, value);
245
+ return value;
246
+ };
247
+ const appendDiagnostic = (fileMap, d) => {
248
+ const linterMap = getOrCreate(fileMap, d.file, () => /* @__PURE__ */ new Map());
249
+ const ruleMap = getOrCreate(linterMap, d.linter, () => /* @__PURE__ */ new Map());
250
+ const lines = getOrCreate(ruleMap, d.rule, () => []);
251
+ if (d.line > 0) lines.push(d.line);
252
+ };
253
+ const groupDiagnostics = (diagnostics) => {
250
254
  const deduped = dedup(diagnostics);
251
255
  const fileMap = /* @__PURE__ */ new Map();
252
- for (const d of deduped) {
253
- let linterMap = fileMap.get(d.file);
254
- if (!linterMap) {
255
- linterMap = /* @__PURE__ */ new Map();
256
- fileMap.set(d.file, linterMap);
257
- }
258
- let ruleMap = linterMap.get(d.linter);
259
- if (!ruleMap) {
260
- ruleMap = /* @__PURE__ */ new Map();
261
- linterMap.set(d.linter, ruleMap);
262
- }
263
- let lines = ruleMap.get(d.rule);
264
- if (!lines) {
265
- lines = [];
266
- ruleMap.set(d.rule, lines);
267
- }
268
- if (d.line > 0) lines.push(d.line);
256
+ for (const d of deduped) appendDiagnostic(fileMap, d);
257
+ return fileMap;
258
+ };
259
+ const sortedGroupedRules = (ruleMap) => {
260
+ const rules = [];
261
+ const sortedRules = [...ruleMap.keys()].toSorted((a, b) => a.localeCompare(b));
262
+ for (const ruleName of sortedRules) {
263
+ const lines = ruleMap.get(ruleName) ?? [];
264
+ const uniqueLines = [...new Set(lines)].toSorted((a, b) => a - b);
265
+ rules.push({
266
+ lines: uniqueLines,
267
+ rule: ruleName
268
+ });
269
+ }
270
+ return rules;
271
+ };
272
+ const sortedGroupedLinters = (linterMap) => {
273
+ const linters = [];
274
+ const sortedLinters = [...linterMap.keys()].toSorted(linterSort);
275
+ for (const linterName of sortedLinters) {
276
+ const ruleMap = linterMap.get(linterName) ?? /* @__PURE__ */ new Map();
277
+ const rules = sortedGroupedRules(ruleMap);
278
+ linters.push({
279
+ linter: linterName,
280
+ rules
281
+ });
269
282
  }
283
+ return linters;
284
+ };
285
+ const aggregate = ({ diagnostics }) => {
286
+ const fileMap = groupDiagnostics(diagnostics);
270
287
  const files = [];
271
288
  const sortedFiles = [...fileMap.keys()].toSorted((a, b) => a.localeCompare(b));
272
289
  for (const filePath of sortedFiles) {
273
- const linterMap = fileMap.get(filePath) ?? /* @__PURE__ */ new Map();
274
- const linters = [];
275
- const sortedLinters = [...linterMap.keys()].toSorted(linterSort);
276
- for (const linterName of sortedLinters) {
277
- const ruleMap = linterMap.get(linterName) ?? /* @__PURE__ */ new Map();
278
- const rules = [];
279
- const sortedRules = [...ruleMap.keys()].toSorted((a, b) => a.localeCompare(b));
280
- for (const ruleName of sortedRules) {
281
- const lines = ruleMap.get(ruleName) ?? [];
282
- const uniqueLines = [...new Set(lines)].toSorted((a, b) => a - b);
283
- rules.push({
284
- lines: uniqueLines,
285
- rule: ruleName
286
- });
287
- }
288
- linters.push({
289
- linter: linterName,
290
- rules
291
- });
292
- }
290
+ const linters = sortedGroupedLinters(fileMap.get(filePath) ?? /* @__PURE__ */ new Map());
293
291
  files.push({
294
292
  file: filePath,
295
293
  linters
@@ -297,20 +295,18 @@ const aggregate = ({ diagnostics }) => {
297
295
  }
298
296
  return files;
299
297
  };
300
- //#endregion
301
- //#region src/parse-source.ts
302
- const parseAnyDialect = ({ label, sourceText }) => {
298
+ // src/parse-source.ts
299
+ const parseAnyDialect = async ({ label, sourceText }) => {
303
300
  let firstError;
304
- for (const dialect of PARSE_DIALECTS) {
305
- const parsed = parseSync(dialect, sourceText);
301
+ const results = await Promise.all(PARSE_DIALECTS.map(async (dialect) => parse(dialect, sourceText)));
302
+ for (const parsed of results) {
306
303
  const [parseError] = parsed.errors;
307
304
  if (!parseError) return parsed;
308
305
  firstError ??= parseError.message;
309
306
  }
310
307
  throw new Error(`${label} cannot parse the source: ${firstError ?? "unknown parse failure"}`);
311
308
  };
312
- //#endregion
313
- //#region src/class-name.ts
309
+ // src/class-name.ts
314
310
  const CN_NAMES = /* @__PURE__ */ new Set(["cn"]);
315
311
  const BANNED_CALLEE_NAMES = /* @__PURE__ */ new Set([
316
312
  "classnames",
@@ -319,7 +315,7 @@ const BANNED_CALLEE_NAMES = /* @__PURE__ */ new Set([
319
315
  "twMerge"
320
316
  ]);
321
317
  const asNode = (v) => {
322
- if (!v || typeof v !== "object" || !("type" in v) || typeof v.type !== "string") return null;
318
+ if (!v || typeof v !== "object" || !("type" in v) || typeof v.type !== "string") return;
323
319
  /** biome-ignore lint/nursery/noUnsafeTypeAssertion: external parser AST node is narrowed only at this boundary */
324
320
  return v;
325
321
  };
@@ -341,13 +337,12 @@ const isJoinCall = (n) => {
341
337
  const isBannedCallee = (n) => n.type === "CallExpression" && n.callee?.type === "Identifier" && BANNED_CALLEE_NAMES.has(strName(n.callee));
342
338
  const isStringLiteral = (n) => n.type === "Literal" && typeof n.value === "string" || n.type === "TemplateLiteral" && Array.isArray(n.expressions) && n.expressions.length === 0;
343
339
  const classNameExprRule = (expr) => {
344
- if (isStringLiteral(expr) || isCallToCn(expr)) return null;
340
+ if (isStringLiteral(expr) || isCallToCn(expr)) return;
345
341
  if (expr.type === "TemplateLiteral") return "cn/no-template-literal";
346
342
  if (expr.type === "ConditionalExpression") return "cn/no-ternary";
347
343
  if (expr.type === "BinaryExpression" && expr.operator === "+") return "cn/no-concatenation";
348
344
  if (isBannedCallee(expr)) return "cn/no-banned-callee";
349
345
  if (isJoinCall(expr)) return "cn/no-join";
350
- return null;
351
346
  };
352
347
  const collectClassNameAttrViolation = (node, sourceText, violations) => {
353
348
  const container = node.value;
@@ -365,8 +360,8 @@ const collectBannedCalleeViolation = ({ grand, node, parent, sourceText, violati
365
360
  rule: "cn/no-banned-callee"
366
361
  });
367
362
  };
368
- const findClassNameViolations = ({ sourceText }) => {
369
- const { program } = parseAnyDialect({
363
+ const findClassNameViolations = async ({ sourceText }) => {
364
+ const { program } = await parseAnyDialect({
370
365
  label: "className check",
371
366
  sourceText
372
367
  });
@@ -391,7 +386,7 @@ const findClassNameViolations = ({ sourceText }) => {
391
386
  });
392
387
  for (const key of Object.keys(node)) if (key !== "type") visit(node[key], node, parent);
393
388
  };
394
- visit(program, null, null);
389
+ visit(program, void 0, void 0);
395
390
  return violations;
396
391
  };
397
392
  const TSX_EXTENSIONS = /* @__PURE__ */ new Set([".tsx"]);
@@ -404,7 +399,7 @@ const checkClassNameFile = async (filePath) => {
404
399
  const f = file(filePath);
405
400
  if (!await f.exists()) return [];
406
401
  const sourceText = await f.text();
407
- return findClassNameViolations({ sourceText }).map((v) => ({
402
+ return (await findClassNameViolations({ sourceText })).map((v) => ({
408
403
  file: filePath,
409
404
  line: v.line,
410
405
  linter: "cn",
@@ -415,8 +410,7 @@ const checkClassName = async ({ root }) => {
415
410
  const paths = (await listProjectFiles({ root })).filter((path) => isTsxFile(path) && !(path.includes("node_modules") || path.includes("readonly") || path.includes(".next") || path.includes("dist")));
416
411
  return (await Promise.all(paths.map(async (path) => checkClassNameFile(joinPath(root, path))))).flat();
417
412
  };
418
- //#endregion
419
- //#region src/rules.ts
413
+ // src/rules.ts
420
414
  const extractBiomeRules = async () => {
421
415
  const pkgPath = fromFileUrl(import.meta.resolve("@biomejs/biome/configuration_schema.json"));
422
416
  const defs = readRequiredJson(await file(pkgPath).text()).$defs ?? {};
@@ -442,46 +436,45 @@ const extractBiomeRules = async () => {
442
436
  }
443
437
  return results;
444
438
  };
445
- /** 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. */
446
- const extractOxlintRules = async () => {
447
- const configPath = joinPath(cwd, "node_modules/.cache/lintmax/.oxlintrc.json");
448
- const bin = await resolveBin({
449
- bin: "oxlint",
450
- pkg: "oxlint"
451
- });
452
- const result = await $`bun ${bin} -c ${configPath} --print-config`.cwd(cwd).quiet().nothrow();
453
- if (result.exitCode !== 0) throw new Error(`oxlint --print-config failed, so its rule set is unknown: ${result.stderr.toString().trim()}`);
454
- const parsed = JSON.parse(result.stdout.toString());
455
- if (!isRecord(parsed)) throw new Error("oxlint --print-config returned no document");
456
- const { rules } = parsed;
457
- if (!isRecord(rules)) throw new Error("oxlint --print-config returned no rules map");
439
+ const enabledOxlintRules = (rules) => {
458
440
  const results = [];
459
441
  for (const [rule, value] of Object.entries(rules)) if ((Array.isArray(value) ? value[0] : value) === "deny") results.push({
460
442
  fixable: false,
461
443
  linter: "oxlint",
462
444
  rule
463
445
  });
446
+ return results;
447
+ };
448
+ const parseOxlintRules = (stdout) => {
449
+ const parsed = JSON.parse(stdout);
450
+ if (!isRecord(parsed)) throw new Error("oxlint --print-config returned no document");
451
+ const { rules } = parsed;
452
+ if (!isRecord(rules)) throw new Error("oxlint --print-config returned no rules map");
453
+ const results = enabledOxlintRules(rules);
464
454
  if (results.length === 0) throw new Error("oxlint reports zero enabled rules — the gate runs it, so that cannot be right");
465
455
  return results;
466
456
  };
467
- const extractEslintRules = async () => {
468
- const eslintBin = await resolveBin({
469
- bin: "eslint",
470
- pkg: "eslint"
457
+ const extractOxlintRules = async () => {
458
+ const configPath = joinPath(cwd, "node_modules/.cache/lintmax/.oxlintrc.json");
459
+ const bin = await resolveBin({
460
+ bin: "oxlint",
461
+ pkg: "oxlint"
471
462
  });
472
- const configPath = joinPath(cwd, "node_modules/.cache/lintmax/eslint.generated.mjs");
473
- const dummyFile = joinPath(cwd, "_lintmax_dummy.ts");
474
- await write(dummyFile, "export {}\n");
475
- const result = await $`bun ${eslintBin} --config ${configPath} --print-config ${dummyFile}`.cwd(cwd).quiet().nothrow();
476
- await unlink(dummyFile).catch(() => void 0);
477
- if (result.exitCode !== 0) throw new Error(`eslint --print-config failed, so its rule set is unknown: ${result.stderr.toString().trim()}`);
463
+ const result = await $`bun ${bin} -c ${configPath} --print-config`.cwd(cwd).quiet().nothrow();
464
+ if (result.exitCode !== 0) throw new Error(`oxlint --print-config failed, so its rule set is unknown: ${result.stderr.toString().trim()}`);
465
+ return parseOxlintRules(result.stdout.toString());
466
+ };
467
+ const readEslintDocument = (stdout) => {
478
468
  let parsed;
479
469
  try {
480
- parsed = readRequiredJson(result.stdout.toString());
470
+ parsed = readRequiredJson(stdout);
481
471
  } catch (error) {
482
472
  throw new Error(`eslint --print-config returned unreadable JSON: ${error instanceof Error ? error.message : ""}`, { cause: error });
483
473
  }
484
- const allRules = parsed.rules ?? {};
474
+ return parsed;
475
+ };
476
+ const parseEslintRules = (stdout) => {
477
+ const allRules = readEslintDocument(stdout).rules ?? {};
485
478
  const results = [];
486
479
  for (const [rule, config] of Object.entries(allRules)) {
487
480
  const level = Array.isArray(config) ? config[0] : config;
@@ -493,6 +486,19 @@ const extractEslintRules = async () => {
493
486
  }
494
487
  return results;
495
488
  };
489
+ const extractEslintRules = async () => {
490
+ const eslintBin = await resolveBin({
491
+ bin: "eslint",
492
+ pkg: "eslint"
493
+ });
494
+ const configPath = joinPath(cwd, "node_modules/.cache/lintmax/eslint.generated.mjs");
495
+ const dummyFile = joinPath(cwd, "_lintmax_dummy.ts");
496
+ await write(dummyFile, "export {}\n");
497
+ const result = await $`bun ${eslintBin} --config ${configPath} --print-config ${dummyFile}`.cwd(cwd).quiet().nothrow();
498
+ await unlink(dummyFile).catch(() => void 0);
499
+ if (result.exitCode !== 0) throw new Error(`eslint --print-config failed, so its rule set is unknown: ${result.stderr.toString().trim()}`);
500
+ return parseEslintRules(result.stdout.toString());
501
+ };
496
502
  const extractAllRules = async () => {
497
503
  const [oxlint, biome, eslint] = await Promise.all([
498
504
  extractOxlintRules(),
@@ -509,6 +515,14 @@ const extractAllRules = async () => {
509
515
  return a.rule.localeCompare(b.rule);
510
516
  });
511
517
  };
518
+ const formatLinterRuleGroups = (byLinter) => {
519
+ const parts = [];
520
+ for (const [linter, ruleList] of byLinter) {
521
+ parts.push(`${linter} (${ruleList.length})`);
522
+ for (const rule of ruleList) parts.push(` ${rule}`);
523
+ }
524
+ return parts.join("\n");
525
+ };
512
526
  const formatRulesCompact = (rules) => {
513
527
  const byLinter = /* @__PURE__ */ new Map();
514
528
  for (const r of rules) {
@@ -519,12 +533,7 @@ const formatRulesCompact = (rules) => {
519
533
  }
520
534
  list.push(r.rule);
521
535
  }
522
- const parts = [];
523
- for (const [linter, ruleList] of byLinter) {
524
- parts.push(`${linter} (${ruleList.length})`);
525
- for (const rule of ruleList) parts.push(` ${rule}`);
526
- }
527
- return parts.join("\n");
536
+ return formatLinterRuleGroups(byLinter);
528
537
  };
529
538
  const formatRulesHuman = (rules) => {
530
539
  const header = "Linter Rule";
@@ -534,8 +543,7 @@ const formatRulesHuman = (rules) => {
534
543
  lines.push(separator, `Total: ${rules.length} rules`);
535
544
  return lines.join("\n");
536
545
  };
537
- //#endregion
538
- //#region src/clean-ignores.ts
546
+ // src/clean-ignores.ts
539
547
  const eslintLineRe = /^(?<prefix>\s*(?:\/\/|\/\*)\s*eslint-disable(?:-next-line)?\s+)(?<rules>\S(?:[^*]*[^\s*])?)(?<suffix>\s*\*\/)?$/v;
540
548
  const oxlintLineRe = /^(?<prefix>\s*(?:\/\/|\/\*)\s*oxlint-disable(?:-next-line)?\s+)(?<rules>\S(?:[^*]*[^\s*])?)(?<suffix>\s*\*\/)?$/v;
541
549
  const biomeLineRe = /^\s*(?:\/\/|\/\*\*)\s*biome-ignore(?:-all)?\s+(?<rule>[\w\/]+)/v;
@@ -573,29 +581,33 @@ const OXLINT_SEPARATORS = [
573
581
  "/",
574
582
  "\\"
575
583
  ];
576
- /** 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). */
577
584
  const oxlintPrefixMatch = (rule) => {
578
585
  for (const prefix of OXLINT_PREFIXES) for (const sep of OXLINT_SEPARATORS) if (rule.startsWith(`${prefix}${sep}`)) return `${prefix}${sep}`;
579
586
  };
580
587
  const trailingParenRe = /\)$/v;
581
588
  const trailingSepRe = /[(/\\]$/u;
582
589
  const eslintPluginPrefixRe = /^eslint-plugin-/v;
583
- /** The oxlint-prefixed variants for a rule whose id starts with `oxMatch` (prefix+separator) — bare id plus canonical/short-plugin spellings. */
584
- const buildOxlintVariants = (rule, oxMatch) => {
585
- const variants = [];
586
- const bare = rule.slice(oxMatch.length).replace(trailingParenRe, "");
587
- variants.push(bare);
588
- const prefix = oxMatch.replace(trailingSepRe, "");
589
- variants.push(`${prefix}/${bare}`, `${prefix}(${bare})`);
590
+ const appendPluginVariants = ({ bare, prefix, variants }) => {
590
591
  if (prefix === "eslint") variants.push(bare);
591
592
  if (prefix === "typescript-eslint") variants.push(`@typescript-eslint/${bare}`);
592
593
  if (prefix.startsWith("eslint-plugin-")) {
593
594
  const short = prefix.replace(eslintPluginPrefixRe, "");
594
595
  variants.push(`${short}/${bare}`, `${short}(${bare})`);
595
596
  }
597
+ };
598
+ const buildOxlintVariants = (rule, oxMatch) => {
599
+ const variants = [];
600
+ const bare = rule.slice(oxMatch.length).replace(trailingParenRe, "");
601
+ variants.push(bare);
602
+ const prefix = oxMatch.replace(trailingSepRe, "");
603
+ variants.push(`${prefix}/${bare}`, `${prefix}(${bare})`);
604
+ appendPluginVariants({
605
+ bare,
606
+ prefix,
607
+ variants
608
+ });
596
609
  return variants;
597
610
  };
598
- /** The underscore↔dash spelling twins of each variant — a `_` id also spelled with `-` and vice versa. */
599
611
  const expandUnderscoreDash = (variants) => {
600
612
  const extra = [];
601
613
  for (const v of variants) {
@@ -604,17 +616,21 @@ const expandUnderscoreDash = (variants) => {
604
616
  }
605
617
  return extra;
606
618
  };
619
+ const appendNamespaceVariants = (rule, variants) => {
620
+ if (rule.startsWith("@typescript-eslint/")) variants.push(`typescript-eslint(${rule.slice(19)})`);
621
+ if (rule.startsWith("@next/next/")) variants.push(`nextjs(${rule.slice(11)})`);
622
+ if (rule.startsWith("@eslint-react/")) variants.push(`react(${rule.slice(14)})`);
623
+ };
607
624
  const normalizeRule = (rule) => {
608
625
  const variants = [rule];
609
626
  const oxMatch = oxlintPrefixMatch(rule);
610
627
  if (oxMatch !== void 0) variants.push(...buildOxlintVariants(rule, oxMatch));
611
- if (rule.startsWith("@typescript-eslint/")) variants.push(`typescript-eslint(${rule.slice(19)})`);
612
- if (rule.startsWith("@next/next/")) variants.push(`nextjs(${rule.slice(11)})`);
613
- if (rule.startsWith("@eslint-react/")) variants.push(`react(${rule.slice(14)})`);
614
- for (const e of expandUnderscoreDash(variants)) variants.push(e);
628
+ appendNamespaceVariants(rule, variants);
629
+ const expandedVariants = expandUnderscoreDash(variants);
630
+ for (const e of expandedVariants) variants.push(e);
615
631
  return variants;
616
632
  };
617
- const loadOxlintOffRules = async () => {
633
+ const readOxlintConfig = async () => {
618
634
  const configPath = joinPath(process.cwd(), cacheDir, ".oxlintrc.json");
619
635
  if (!await file(configPath).exists()) throw new Error(`clean-ignores: the generated config is absent at ${configPath}, so no rule reads as off and every directive for an off rule would be kept. The stage that writes it did not run.`);
620
636
  let config;
@@ -623,21 +639,28 @@ const loadOxlintOffRules = async () => {
623
639
  } catch (error) {
624
640
  throw new Error(`clean-ignores: the generated config at ${configPath} carries no parseable JSON. Refusing rather than reading it as "no rule is off", which would silently keep every directive.`, { cause: error });
625
641
  }
626
- const off = /* @__PURE__ */ new Set();
627
- for (const [rule, val] of Object.entries(config.rules ?? {})) if ((Array.isArray(val) ? String(val[0]) : val) === "off") {
628
- off.add(rule);
629
- for (const v of normalizeRule(rule)) off.add(v);
630
- }
631
- for (const rule of OXLINT_CLI_ALLOW) {
642
+ return config;
643
+ };
644
+ const addRuleVariants = (rule, target) => {
645
+ const variants = normalizeRule(rule);
646
+ for (const variant of variants) target.add(variant);
647
+ };
648
+ const loadOxlintOffRules = async () => {
649
+ const config = await readOxlintConfig();
650
+ const off = new Set(OXLINT_CLI_ALLOW);
651
+ const offRules = Object.entries(config.rules ?? {}).filter(([, val]) => (Array.isArray(val) ? String(val[0]) : val) === "off");
652
+ for (const [rule] of offRules) {
632
653
  off.add(rule);
633
- for (const v of normalizeRule(rule)) off.add(v);
654
+ addRuleVariants(rule, off);
634
655
  }
656
+ for (const rule of OXLINT_CLI_ALLOW) addRuleVariants(rule, off);
635
657
  return off;
636
658
  };
637
659
  const buildActiveRuleSet = async ({ excludeEslint = false } = {}) => {
638
660
  const rules = await extractAllRules();
639
661
  const active = /* @__PURE__ */ new Set();
640
- for (const r of rules.filter((rule) => !excludeEslint || rule.linter !== "eslint")) {
662
+ const includedRules = rules.filter((rule) => !excludeEslint || rule.linter !== "eslint");
663
+ for (const r of includedRules) {
641
664
  active.add(r.rule);
642
665
  for (const v of normalizeRule(r.rule)) active.add(v);
643
666
  }
@@ -650,8 +673,7 @@ const isRuleActive = (rule, active, oxlintOff) => {
650
673
  }
651
674
  if (active.has(rule)) return true;
652
675
  for (const v of normalizeRule(rule)) if (active.has(v)) return true;
653
- if (!oxlintOff) return false;
654
- return true;
676
+ return Boolean(oxlintOff);
655
677
  };
656
678
  const splitCsvRules = (ruleList) => ruleList.split(",").map((r) => r.trim()).filter(Boolean);
657
679
  const splitDirective = (str) => {
@@ -670,27 +692,21 @@ const splitDirective = (str) => {
670
692
  };
671
693
  };
672
694
  const processMultiRuleLine = ({ active, isOxlint, line, match, oxlintOff, result }) => {
673
- const prefix = match.prefix ?? "";
674
- const rulesStr = match.rules ?? "";
675
- const suffix = match.suffix ?? "";
676
- const { reason, rules } = splitDirective(rulesStr);
695
+ const { reason, rules } = splitDirective(match.rules ?? "");
677
696
  const kept = rules.filter((r) => isRuleActive(r, active, isOxlint ? oxlintOff : void 0));
678
697
  if (kept.length === 0) return rules.length;
679
698
  if (kept.length < rules.length) {
680
- result.push(`${prefix}${kept.join(", ")}${reason}${suffix}`);
699
+ result.push(`${match.prefix ?? ""}${kept.join(", ")}${reason}${match.suffix ?? ""}`);
681
700
  return rules.length - kept.length;
682
701
  }
683
702
  result.push(line);
684
703
  return 0;
685
704
  };
686
- /** Process one source line: keep-or-rewrite it into `result` and return how many disabled rules were removed. */
687
- const processIgnoreLine = ({ active, eslintActive, line, oxlintOff, result }) => {
705
+ const processEslintLine = ({ active, line, result }) => {
688
706
  eslintLineRe.lastIndex = 0;
689
- oxlintLineRe.lastIndex = 0;
690
- biomeLineRe.lastIndex = 0;
691
707
  const eslintMatch = eslintLineRe.exec(line);
692
708
  if (eslintMatch) return processMultiRuleLine({
693
- active: eslintActive ?? active,
709
+ active,
694
710
  line,
695
711
  match: {
696
712
  prefix: eslintMatch.groups?.prefix,
@@ -699,6 +715,8 @@ const processIgnoreLine = ({ active, eslintActive, line, oxlintOff, result }) =>
699
715
  },
700
716
  result
701
717
  });
718
+ };
719
+ const processOxlintLine = ({ active, line, oxlintOff, result }) => {
702
720
  const oxlintMatch = oxlintLineRe.exec(line);
703
721
  if (oxlintMatch) return processMultiRuleLine({
704
722
  active,
@@ -712,6 +730,19 @@ const processIgnoreLine = ({ active, eslintActive, line, oxlintOff, result }) =>
712
730
  oxlintOff,
713
731
  result
714
732
  });
733
+ };
734
+ const processIgnoreLine = ({ active, eslintActive, line, oxlintOff, result }) => {
735
+ const matchedResult = processEslintLine({
736
+ active: eslintActive ?? active,
737
+ line,
738
+ result
739
+ }) ?? processOxlintLine({
740
+ active,
741
+ line,
742
+ oxlintOff,
743
+ result
744
+ });
745
+ if (matchedResult !== void 0) return matchedResult;
715
746
  const biomeMatch = biomeLineRe.exec(line);
716
747
  if (biomeMatch && !isRuleActive(biomeMatch.groups?.rule ?? "", active)) return 1;
717
748
  result.push(line);
@@ -771,8 +802,7 @@ const cleanIgnores = async (filePaths) => {
771
802
  files: filePaths.filter((_, index) => (counts[index] ?? 0) > 0)
772
803
  };
773
804
  };
774
- //#endregion
775
- //#region src/comments.ts
805
+ // src/comments.ts
776
806
  const lineAt = (sourceText, offset) => {
777
807
  let line = 1;
778
808
  for (let i = 0; i < offset && i < sourceText.length; i += 1) if (sourceText[i] === "\n") line += 1;
@@ -796,15 +826,15 @@ const extOf = (path) => {
796
826
  };
797
827
  const isCommentCandidate = (path) => COMMENT_EXTENSIONS.has(extOf(path));
798
828
  const isBlockOnlyComment = (sourceText, comments, c) => {
799
- const inComment = (idx) => comments.some((o) => idx >= o.start && idx < o.end);
829
+ const isInComment = (idx) => comments.some((o) => idx >= o.start && idx < o.end);
800
830
  let before = c.start - 1;
801
- while (before >= 0 && (WS_CHAR.test(sourceText[before] ?? "") || inComment(before))) before -= 1;
831
+ while (before >= 0 && (WS_CHAR.test(sourceText[before] ?? "") || isInComment(before))) before -= 1;
802
832
  let after = c.end;
803
- while (after < sourceText.length && (WS_CHAR.test(sourceText[after] ?? "") || inComment(after))) after += 1;
833
+ while (after < sourceText.length && (WS_CHAR.test(sourceText[after] ?? "") || isInComment(after))) after += 1;
804
834
  return sourceText[before] === "{" && sourceText[after] === "}";
805
835
  };
806
- const findDeletableComments = ({ sourceText }) => {
807
- const { comments } = parseAnyDialect({
836
+ const findDeletableComments = async ({ sourceText }) => {
837
+ const { comments } = await parseAnyDialect({
808
838
  label: "comment strip",
809
839
  sourceText
810
840
  });
@@ -820,26 +850,34 @@ const findDeletableComments = ({ sourceText }) => {
820
850
  deletable.sort((a, b) => a.start - b.start);
821
851
  return deletable;
822
852
  };
823
- const deleteComments = ({ sourceText }) => {
824
- const comments = findDeletableComments({ sourceText });
853
+ const skipLineEnding = (sourceText, end) => {
854
+ if (sourceText[end] === "\n") return end + 1;
855
+ if (sourceText[end] === "\r" && sourceText[end + 1] === "\n") return end + 2;
856
+ return end;
857
+ };
858
+ const appendWithoutComment = ({ comment, cursor, parts, sourceText }) => {
859
+ const beforeChunk = sourceText.slice(cursor, comment.start);
860
+ const lineStart = beforeChunk.lastIndexOf("\n") + 1;
861
+ const indent = beforeChunk.slice(lineStart);
862
+ const afterEnd = skipLineEnding(sourceText, comment.end);
863
+ if (WHITESPACE_ONLY.test(indent) && afterEnd <= sourceText.length) {
864
+ parts.push(beforeChunk.slice(0, lineStart));
865
+ return afterEnd;
866
+ }
867
+ parts.push(beforeChunk);
868
+ return comment.end;
869
+ };
870
+ const deleteComments = async ({ sourceText }) => {
871
+ const comments = await findDeletableComments({ sourceText });
825
872
  if (comments.length === 0) return sourceText;
826
873
  const parts = [];
827
874
  let cursor = 0;
828
- for (const c of comments) {
829
- const beforeChunk = sourceText.slice(cursor, c.start);
830
- const lineStart = beforeChunk.lastIndexOf("\n") + 1;
831
- const indent = beforeChunk.slice(lineStart);
832
- let afterEnd = c.end;
833
- if (sourceText[afterEnd] === "\n") afterEnd += 1;
834
- else if (sourceText[afterEnd] === "\r" && sourceText[afterEnd + 1] === "\n") afterEnd += 2;
835
- if (WHITESPACE_ONLY.test(indent) && afterEnd <= sourceText.length) {
836
- parts.push(beforeChunk.slice(0, lineStart));
837
- cursor = afterEnd;
838
- } else {
839
- parts.push(beforeChunk);
840
- cursor = c.end;
841
- }
842
- }
875
+ for (const c of comments) cursor = appendWithoutComment({
876
+ comment: c,
877
+ cursor,
878
+ parts,
879
+ sourceText
880
+ });
843
881
  parts.push(sourceText.slice(cursor));
844
882
  return parts.join("");
845
883
  };
@@ -854,7 +892,7 @@ const processFile = async (filePath) => {
854
892
  modified: false
855
893
  };
856
894
  const sourceText = await f.text();
857
- const comments = findDeletableComments({ sourceText });
895
+ const comments = await findDeletableComments({ sourceText });
858
896
  const diagnostics = [];
859
897
  for (const c of comments) diagnostics.push({
860
898
  file: filePath,
@@ -867,12 +905,12 @@ const processFile = async (filePath) => {
867
905
  modified: false
868
906
  };
869
907
  };
870
- const processFileForFix = async (filePath) => {
908
+ const didStripCommentsInFile = async (filePath) => {
871
909
  if (!isCommentCandidate(filePath)) return false;
872
910
  const f = file(filePath);
873
911
  if (!await f.exists()) return false;
874
912
  const sourceText = await f.text();
875
- const result = deleteComments({ sourceText });
913
+ const result = await deleteComments({ sourceText });
876
914
  if (result !== sourceText) {
877
915
  await write(filePath, result);
878
916
  return true;
@@ -883,10 +921,9 @@ const checkComments = async ({ files }) => {
883
921
  return (await Promise.all(files.map(async (f) => processFile(f)))).flatMap((r) => r.diagnostics);
884
922
  };
885
923
  const fixComments = async ({ files }) => {
886
- return (await Promise.all(files.map(async (f) => processFileForFix(f)))).filter(Boolean).length;
924
+ return (await Promise.all(files.map(async (f) => didStripCommentsInFile(f)))).filter(Boolean).length;
887
925
  };
888
- //#endregion
889
- //#region src/compact.ts
926
+ // src/compact.ts
890
927
  const isSymlinkSafe = async (p) => {
891
928
  try {
892
929
  return (await lstat(p)).isSymbolicLink();
@@ -933,7 +970,7 @@ const extension = ({ path }) => {
933
970
  const dotIndex = path.lastIndexOf(".");
934
971
  return dotIndex > slashIndex ? path.slice(dotIndex) : "";
935
972
  };
936
- const compactContent = ({ content }) => content.replace(COMPACT_REGEX, "\n");
973
+ const compactContent = ({ content }) => content.replaceAll(COMPACT_REGEX, "\n");
937
974
  const isCompactCandidate = ({ relativePath }) => {
938
975
  const fileName = basename({ path: relativePath });
939
976
  if (compactBasenames.has(fileName)) return true;
@@ -951,56 +988,55 @@ const listCompactFiles = async ({ env, root }) => {
951
988
  const symlinkFlags = await Promise.all(entries.map(async (e) => isSymlinkSafe(join(root, e))));
952
989
  return entries.filter((_e, index) => !symlinkFlags[index]);
953
990
  };
954
- const runCompact = async ({ env, human = false, isIgnored, mode, root }) => {
955
- const listed = await listCompactFiles({
956
- env,
957
- root
991
+ const compactFileContent = async ({ absolutePath, bytes, mode, relativePath }) => {
992
+ if (isBinary({ bytes })) return {
993
+ changed: false,
994
+ relativePath,
995
+ scanned: true
996
+ };
997
+ const content = decodeText(bytes);
998
+ const compacted = compactContent({ content });
999
+ if (content === compacted) return {
1000
+ changed: false,
1001
+ relativePath,
1002
+ scanned: true
1003
+ };
1004
+ if (mode === "fix") await write(absolutePath, compacted);
1005
+ return {
1006
+ changed: true,
1007
+ relativePath,
1008
+ scanned: true
1009
+ };
1010
+ };
1011
+ const compactFile = async (relativePath, root, mode) => {
1012
+ if (!isCompactCandidate({ relativePath })) return {
1013
+ changed: false,
1014
+ relativePath,
1015
+ scanned: false
1016
+ };
1017
+ const absolutePath = joinPath(root, relativePath);
1018
+ const source = file(absolutePath);
1019
+ if (!await source.exists()) return {
1020
+ changed: false,
1021
+ relativePath,
1022
+ scanned: false
1023
+ };
1024
+ return compactFileContent({
1025
+ absolutePath,
1026
+ bytes: new Uint8Array(await source.arrayBuffer()),
1027
+ mode,
1028
+ relativePath
958
1029
  });
959
- const files = isIgnored === void 0 ? listed : listed.filter((one) => !isIgnored(one));
960
- const results = await Promise.all(files.map(async (relativePath) => {
961
- if (!isCompactCandidate({ relativePath })) return {
962
- changed: false,
963
- relativePath,
964
- scanned: false
965
- };
966
- const absolutePath = joinPath(root, relativePath);
967
- const source = file(absolutePath);
968
- if (!await source.exists()) return {
969
- changed: false,
970
- relativePath,
971
- scanned: false
972
- };
973
- const bytes = new Uint8Array(await source.arrayBuffer());
974
- if (isBinary({ bytes })) return {
975
- changed: false,
976
- relativePath,
977
- scanned: true
978
- };
979
- const content = decodeText(bytes);
980
- const compacted = compactContent({ content });
981
- if (content === compacted) return {
982
- changed: false,
983
- relativePath,
984
- scanned: true
985
- };
986
- if (mode === "fix") await write(absolutePath, compacted);
987
- return {
988
- changed: true,
989
- relativePath,
990
- scanned: true
991
- };
992
- }));
993
- const changed = [];
994
- let scanned = 0;
995
- for (const result of results) {
996
- if (result.scanned) scanned += 1;
997
- if (result.changed) changed.push(result.relativePath);
998
- }
1030
+ };
1031
+ const printCompactCounts = (results, changed) => {
1032
+ const scanned = results.filter((result) => result.scanned).length;
1033
+ process.stdout.write(`[compact] Scanned ${scanned} files\n`);
1034
+ process.stdout.write(`[compact] Updated ${changed.length} files\n`);
1035
+ };
1036
+ const reportCompact = (results, mode, isHuman) => {
1037
+ const changed = results.filter((result) => result.changed).map((result) => result.relativePath);
999
1038
  if (mode === "fix") {
1000
- if (human) {
1001
- process.stdout.write(`[compact] Scanned ${scanned} files\n`);
1002
- process.stdout.write(`[compact] Updated ${changed.length} files\n`);
1003
- }
1039
+ if (isHuman) printCompactCounts(results, changed);
1004
1040
  return;
1005
1041
  }
1006
1042
  if (changed.length === 0) return;
@@ -1011,8 +1047,16 @@ const runCompact = async ({ env, human = false, isIgnored, mode, root }) => {
1011
1047
  message: `[compact]\nFiles requiring compaction:\n${shown.join("\n")}${suffix}\nRun: lintmax fix`
1012
1048
  });
1013
1049
  };
1014
- //#endregion
1015
- //#region src/extra-coverage.ts
1050
+ const runCompact = async ({ env, human = false, isIgnored, mode, root }) => {
1051
+ const listed = await listCompactFiles({
1052
+ env,
1053
+ root
1054
+ });
1055
+ const files = isIgnored === void 0 ? listed : listed.filter((one) => !isIgnored(one));
1056
+ const results = await Promise.all(files.map(async (relativePath) => compactFile(relativePath, root, mode)));
1057
+ reportCompact(results, mode, human);
1058
+ };
1059
+ // src/extra-coverage.ts
1016
1060
  const DOCKERFILE_RE = /(?:^|\/)Dockerfile(?:\.[\w\-.]+)?$/v;
1017
1061
  const SHELLCHECK_LINE_RE = /^(?<file>.+?):(?<line>\d+):\d+:\s+(?:error|note|style|warning):\s+(?:\S.*)?\[(?<rule>[^\]\[]+)\]$/v;
1018
1062
  const isShell = (filePath) => filePath.endsWith(".sh") || filePath.endsWith(".bash");
@@ -1027,14 +1071,14 @@ const resolveDprintPluginPath = () => {
1027
1071
  try {
1028
1072
  return import.meta.resolve("@dprint/dockerfile/plugin.wasm").replace("file://", "");
1029
1073
  } catch {
1030
- return null;
1074
+ return;
1031
1075
  }
1032
1076
  };
1033
1077
  const whichTool = async (env, tool) => {
1034
1078
  const result = await $`which ${tool}`.env(env).quiet().nothrow();
1035
- if (result.exitCode !== 0) return null;
1079
+ if (result.exitCode !== 0) return;
1036
1080
  const path = result.stdout.toString().trim();
1037
- return path.length > 0 ? path : null;
1081
+ return path.length > 0 ? path : void 0;
1038
1082
  };
1039
1083
  const failureDiagnostic = (linter, files) => ({
1040
1084
  file: files[0] ?? "",
@@ -1050,7 +1094,6 @@ const parseShellcheckLine = (line) => {
1050
1094
  linter: "shellcheck",
1051
1095
  rule: groups.rule
1052
1096
  };
1053
- return null;
1054
1097
  };
1055
1098
  const SHFMT_FLAGS = [
1056
1099
  "-s",
@@ -1105,7 +1148,7 @@ const runShellcheckStep = async ({ bin, env, files }) => {
1105
1148
  const diagnostics = [];
1106
1149
  for (const line of result.stdout.split("\n")) {
1107
1150
  const diagnostic = parseShellcheckLine(line);
1108
- if (diagnostic !== null) diagnostics.push(diagnostic);
1151
+ if (diagnostic !== void 0) diagnostics.push(diagnostic);
1109
1152
  }
1110
1153
  if (result.exitCode !== 0 && diagnostics.length === 0) diagnostics.push(failureDiagnostic("shellcheck", files));
1111
1154
  return diagnostics;
@@ -1118,15 +1161,15 @@ const runShell = async ({ command, env, files }) => {
1118
1161
  const shellcheck = await whichTool(env, "shellcheck");
1119
1162
  const shfmt = await whichTool(env, "shfmt");
1120
1163
  const notes = [];
1121
- if (shellcheck === null || shfmt === null) notes.push("shellcheck/shfmt not on PATH — shell files unchecked (install: brew install shellcheck shfmt)");
1164
+ if (shellcheck === void 0 || shfmt === void 0) notes.push("shellcheck/shfmt not on PATH — shell files unchecked (install: brew install shellcheck shfmt)");
1122
1165
  const diagnostics = [];
1123
- if (shfmt !== null) diagnostics.push(...await runShfmtStep({
1166
+ if (shfmt !== void 0) diagnostics.push(...await runShfmtStep({
1124
1167
  bin: shfmt,
1125
1168
  command,
1126
1169
  env,
1127
1170
  files
1128
1171
  }));
1129
- if (shellcheck !== null) diagnostics.push(...await runShellcheckStep({
1172
+ if (shellcheck !== void 0) diagnostics.push(...await runShellcheckStep({
1130
1173
  bin: shellcheck,
1131
1174
  env,
1132
1175
  files
@@ -1173,7 +1216,7 @@ const runTombi = async ({ bin, command, env, files }) => {
1173
1216
  return [failureDiagnostic("tombi", files)];
1174
1217
  };
1175
1218
  const runDprintDockerfile = async ({ bin, command, env, files, pluginPath }) => {
1176
- if (files.length === 0 || pluginPath === null) return [];
1219
+ if (files.length === 0 || pluginPath === void 0) return [];
1177
1220
  const configArgs = [
1178
1221
  "--plugins",
1179
1222
  pluginPath,
@@ -1234,8 +1277,7 @@ const runExtraCoverage = async ({ bins, command, env, gitFiles }) => {
1234
1277
  notes: shell.notes
1235
1278
  };
1236
1279
  };
1237
- //#endregion
1238
- //#region src/format.ts
1280
+ // src/format.ts
1239
1281
  const formatGrouped = ({ files }) => {
1240
1282
  if (files.length === 0) return "";
1241
1283
  const parts = [];
@@ -1251,12 +1293,10 @@ const formatGrouped = ({ files }) => {
1251
1293
  }
1252
1294
  return parts.join("\n");
1253
1295
  };
1254
- //#endregion
1255
- //#region src/ignores.ts
1256
- /** biome-ignore-all lint/nursery/useNamedCaptureGroup: not needed */
1257
- const eslintDisableRe = /eslint-disable(?:-next-line)?\s+([^\n]*)/gv;
1258
- const oxlintDisableRe$1 = /oxlint-disable(?:-next-line)?\s+([^\n]*)/gv;
1259
- const biomeIgnoreRe = /biome-ignore(?:-all)?\s+([\w/]+)/gu;
1296
+ // src/ignores.ts
1297
+ const eslintDisableRe = /eslint-disable(?:-next-line)?\s+(?<rules>[^\n]*)/gv;
1298
+ const oxlintDisableRe$1 = /oxlint-disable(?:-next-line)?\s+(?<rules>[^\n]*)/gv;
1299
+ const biomeIgnoreRe = /biome-ignore(?:-all)?\s+(?<rules>[\w/]+)/gu;
1260
1300
  const tsIgnoreRe = /@ts-(?:expect-error|ignore|nocheck)/gv;
1261
1301
  const stripRuleTail = (rule) => {
1262
1302
  const dash = rule.indexOf("--");
@@ -1282,13 +1322,13 @@ const DANGEROUS_NON_TEST_PATTERNS = [
1282
1322
  "no-explicit-any",
1283
1323
  "noExplicitAny"
1284
1324
  ];
1285
- const isTestFile = (f) => ESLINT_TEST_FILE_PATTERNS.some((p) => new Glob(p).match(f));
1325
+ const isTestFile = (f) => ESLINT_TEST_FILE_PATTERNS.some((p) => doesMatchGlob(new Glob(p), f));
1286
1326
  const parseRules = (line, re) => {
1287
1327
  const rules = [];
1288
1328
  re.lastIndex = 0;
1289
1329
  let match = re.exec(line);
1290
1330
  while (match) {
1291
- const raw = match[1];
1331
+ const raw = match.groups?.rules ?? match[1];
1292
1332
  if (raw) for (const r of raw.split(",")) {
1293
1333
  const trimmed = stripRuleTail(r);
1294
1334
  if (trimmed) rules.push(trimmed);
@@ -1317,7 +1357,7 @@ const rulesFromContent = (content) => {
1317
1357
  };
1318
1358
  const findDangerousSuppressions = async (cwd) => {
1319
1359
  const ignoreGlobs = DEFAULT_SHARED_IGNORE_PATTERNS.map((p) => new Glob(p));
1320
- const files = (await listProjectFiles({ root: cwd })).filter((p) => (p.endsWith(".ts") || p.endsWith(".tsx")) && !p.endsWith(".d.ts") && !ignoreGlobs.some((g) => g.match(p)));
1360
+ const files = (await listProjectFiles({ root: cwd })).filter((p) => (p.endsWith(".ts") || p.endsWith(".tsx")) && !p.endsWith(".d.ts") && ignoreGlobs.every((g) => !doesMatchGlob(g, p)));
1321
1361
  return (await Promise.all(files.map(async (relativePath) => {
1322
1362
  const lines = (await file(joinPath(cwd, relativePath)).text()).split("\n");
1323
1363
  const findings = [];
@@ -1331,29 +1371,28 @@ const findDangerousSuppressions = async (cwd) => {
1331
1371
  return findings;
1332
1372
  }))).flat();
1333
1373
  };
1334
- //#endregion
1335
- //#region src/jsx-extension.ts
1336
- const containsJsxNode = (program) => {
1337
- let found = false;
1374
+ // src/jsx-extension.ts
1375
+ const hasJsxNode = (program) => {
1376
+ let isFound = false;
1338
1377
  const visit = (node) => {
1339
- if (found || !node || typeof node !== "object") return;
1378
+ if (isFound || !node || typeof node !== "object") return;
1340
1379
  if (Array.isArray(node)) {
1341
1380
  for (const child of node) visit(child);
1342
1381
  return;
1343
1382
  }
1344
1383
  if ("type" in node && (node.type === "JSXElement" || node.type === "JSXFragment")) {
1345
- found = true;
1384
+ isFound = true;
1346
1385
  return;
1347
1386
  }
1348
1387
  for (const [key, child] of Object.entries(node)) if (key !== "type") visit(child);
1349
1388
  };
1350
1389
  visit(program);
1351
- return found;
1390
+ return isFound;
1352
1391
  };
1353
- const hasJsx = (sourceText) => {
1354
- if (parseSync("file.ts", sourceText).errors.length === 0) return false;
1355
- const asTsx = parseSync("file.tsx", sourceText);
1356
- return containsJsxNode(asTsx.program);
1392
+ const hasJsx = async (sourceText) => {
1393
+ if ((await parse("file.ts", sourceText)).errors.length === 0) return false;
1394
+ const asTsx = await parse("file.tsx", sourceText);
1395
+ return hasJsxNode(asTsx.program);
1357
1396
  };
1358
1397
  const checkJsxExtension = async ({ root }) => {
1359
1398
  const ignoreGlobs = DEFAULT_SHARED_IGNORE_PATTERNS.map((p) => new Glob(p));
@@ -1361,7 +1400,7 @@ const checkJsxExtension = async ({ root }) => {
1361
1400
  const paths = (await listProjectFiles({ root })).filter((p) => p.endsWith(".ts") && !isIgnored(p));
1362
1401
  return (await Promise.all(paths.map(async (path) => {
1363
1402
  const content = await file(`${root}/${path}`).text();
1364
- if (!hasJsx(content)) return [];
1403
+ if (!await hasJsx(content)) return [];
1365
1404
  return [{
1366
1405
  file: `${root}/${path}`,
1367
1406
  line: 1,
@@ -1370,15 +1409,13 @@ const checkJsxExtension = async ({ root }) => {
1370
1409
  }];
1371
1410
  }))).flat();
1372
1411
  };
1373
- //#endregion
1374
- //#region src/unused-suppressions.ts
1412
+ // src/unused-suppressions.ts
1375
1413
  /** biome-ignore-all lint/performance/noAwaitInLoops: sequential file io */
1376
1414
  /** biome-ignore-all lint/style/noProcessEnv: linter env passthrough */
1377
1415
  const oxlintDisableRe = /^(?<prefix>\s*\/\*\s*oxlint-disable\s+)(?<rules>\S(?:[^*]*[^\s*])?)(?<close>\s*\*\/)?$/v;
1378
1416
  const oxlintDisablePresentRe = /\/\*\s*oxlint-disable\s/v;
1379
1417
  const biomeIgnoreAllRe = /^\s*\/\*\*\s*biome-ignore-all\s+(?<first>[\w\/]+)(?<rest>(?:[^\w\/*][^*]*)?)\*\/\s*$/v;
1380
1418
  const biomeIgnoreAllLineRe = /^\s*\/\/\s*biome-ignore-all\s+(?<first>[\w\/]+)(?<rest>(?:[^\w\/].*)?)$/v;
1381
- /** 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. */
1382
1419
  const stripTrailingComment = (str) => {
1383
1420
  const at = str.indexOf("--");
1384
1421
  return at === -1 ? str : str.slice(0, at).trimEnd();
@@ -1397,28 +1434,25 @@ const extractJson = (stdout) => {
1397
1434
  return stdout.slice(start);
1398
1435
  };
1399
1436
  const absFile = (p) => p.startsWith("/") ? p : joinPath(cwd, p);
1437
+ const buildFileData = (filePath, orig, parseDirectives) => {
1438
+ const lines = orig.split("\n");
1439
+ const directiveLines = parseDirectives(lines);
1440
+ if (directiveLines.length === 0) return;
1441
+ const directiveIndexes = new Set(directiveLines.map((d) => d.index));
1442
+ return {
1443
+ directiveLines,
1444
+ filePath,
1445
+ lines,
1446
+ orig,
1447
+ stripped: lines.filter((_, index) => !directiveIndexes.has(index)).join("\n")
1448
+ };
1449
+ };
1400
1450
  const collectFileData = async (files, parseDirectives) => {
1401
- const out = [];
1402
- for (const filePath of files) {
1403
- const f = file(filePath);
1404
- if (await f.exists()) {
1405
- const orig = await f.text();
1406
- const lines = orig.split("\n");
1407
- const directiveLines = parseDirectives(lines);
1408
- if (directiveLines.length > 0) {
1409
- const directiveIndexes = new Set(directiveLines.map((d) => d.index));
1410
- const stripped = lines.filter((_, index) => !directiveIndexes.has(index)).join("\n");
1411
- out.push({
1412
- directiveLines,
1413
- filePath,
1414
- lines,
1415
- orig,
1416
- stripped
1417
- });
1418
- }
1419
- }
1420
- }
1421
- return out;
1451
+ return (await Promise.all(files.map(async (filePath) => {
1452
+ const source = file(filePath);
1453
+ if (!await source.exists()) return;
1454
+ return buildFileData(filePath, await source.text(), parseDirectives);
1455
+ }))).filter((result) => result !== void 0);
1422
1456
  };
1423
1457
  const batchStripRestore = async ({ data, lint }) => {
1424
1458
  await Promise.all(data.map(async (d) => write(d.filePath, d.stripped)));
@@ -1436,13 +1470,6 @@ const rebuildBiomeLine = ({ line, rules }) => {
1436
1470
  const reason = biomeReasonOf(line) ?? "suppressed";
1437
1471
  return `${leadingWhitespaceRe.exec(line)?.[0] ?? ""}/** biome-ignore-all ${rules.join(", ")}: ${reason} */`;
1438
1472
  };
1439
- /**
1440
- * A lint run that could not ANSWER must refuse, never resolve to an empty fired set. An empty map reads as
1441
- * `no rule fired anywhere`, which marks EVERY directive in the tree unused — MEASURED on one CI lane, 35 of 35
1442
- * directives reported while each one was genuinely needed. A clean run is not this shape: both linters emit
1443
- * `{"diagnostics": []}` and exit 0 when they find nothing, so requiring a parsed diagnostics array refuses a
1444
- * crash without ever refusing a clean tree.
1445
- */
1446
1473
  const oxlintUnusedArgs = ({ configPath, files, oxlintBin }) => [
1447
1474
  oxlintBin,
1448
1475
  "-c",
@@ -1472,6 +1499,17 @@ const requireLintAnswer = ({ exitCode, label, stderr, stdout }) => {
1472
1499
  if (exitCode !== 0 && parsed.diagnostics.length === 0) refuse("failed with zero diagnostics");
1473
1500
  return json;
1474
1501
  };
1502
+ const groupOxlintDiagnostics = (diagnostics) => {
1503
+ const byFile = /* @__PURE__ */ new Map();
1504
+ for (const d of diagnostics) {
1505
+ const key = absFile(d.file);
1506
+ const set = byFile.get(key) ?? /* @__PURE__ */ new Set();
1507
+ set.add(d.rule);
1508
+ for (const v of normalizeRule(d.rule)) set.add(v);
1509
+ byFile.set(key, set);
1510
+ }
1511
+ return byFile;
1512
+ };
1475
1513
  const firedOxlintByFile = async ({ configPath, files, oxlintBin }) => {
1476
1514
  if (!await file(configPath).exists()) throw new Error(`oxlint-unused: the generated config is absent at ${configPath}, so no rule can fire and every directive would read as unused. The stage that writes it did not run.`);
1477
1515
  const result = await runCapture({
@@ -1490,15 +1528,7 @@ const firedOxlintByFile = async ({ configPath, files, oxlintBin }) => {
1490
1528
  stderr: result.stderr,
1491
1529
  stdout: result.stdout
1492
1530
  }) });
1493
- const byFile = /* @__PURE__ */ new Map();
1494
- for (const d of diagnostics) {
1495
- const key = absFile(d.file);
1496
- const set = byFile.get(key) ?? /* @__PURE__ */ new Set();
1497
- set.add(d.rule);
1498
- for (const v of normalizeRule(d.rule)) set.add(v);
1499
- byFile.set(key, set);
1500
- }
1501
- return byFile;
1531
+ return groupOxlintDiagnostics(diagnostics);
1502
1532
  };
1503
1533
  const isOxlintRuleFired = (rule, fired) => {
1504
1534
  if (fired.has(rule)) return true;
@@ -1557,40 +1587,34 @@ const rebuildOxlintDirectiveLine = ({ directive, filePath, fired, index, line })
1557
1587
  emitted: []
1558
1588
  };
1559
1589
  };
1560
- const rebuildOxlintFile = async ({ data, dryRun, fired }) => {
1561
- const result = [];
1562
- const diagnostics = [];
1563
- let removed = 0;
1564
- for (let index = 0; index < data.lines.length; index += 1) {
1565
- const line = data.lines[index] ?? "";
1590
+ const rebuildFile = async ({ data, dryRun, fired }, rebuildLine) => {
1591
+ const outcomes = data.lines.map((line, index) => {
1566
1592
  const directive = data.directiveLines.find((d) => d.index === index);
1567
- if (directive) {
1568
- const outcome = rebuildOxlintDirectiveLine({
1569
- directive,
1570
- filePath: data.filePath,
1571
- fired,
1572
- index,
1573
- line
1574
- });
1575
- removed += outcome.diagnostics.length;
1576
- diagnostics.push(...outcome.diagnostics);
1577
- result.push(...outcome.emitted);
1578
- } else result.push(line);
1579
- }
1580
- if (removed > 0 && !dryRun) await write(data.filePath, result.join("\n"));
1593
+ return directive ? rebuildLine({
1594
+ directive,
1595
+ filePath: data.filePath,
1596
+ fired,
1597
+ index,
1598
+ line
1599
+ }) : {
1600
+ diagnostics: [],
1601
+ emitted: [line]
1602
+ };
1603
+ });
1604
+ const diagnostics = outcomes.flatMap((outcome) => outcome.diagnostics);
1605
+ if (diagnostics.length > 0 && !dryRun) await write(data.filePath, outcomes.flatMap((outcome) => outcome.emitted).join("\n"));
1581
1606
  return {
1582
1607
  diagnostics,
1583
- removed
1608
+ removed: diagnostics.length
1584
1609
  };
1585
1610
  };
1611
+ const rebuildOxlintFile = async (input) => rebuildFile(input, rebuildOxlintDirectiveLine);
1586
1612
  const findOxlintDisableFiles = async (filePaths) => {
1587
1613
  const out = [];
1588
1614
  for (const fp of filePaths) {
1589
1615
  const f = file(fp);
1590
- if (await f.exists()) {
1591
- const content = await f.text();
1592
- if (oxlintDisablePresentRe.test(content)) out.push(fp);
1593
- }
1616
+ const content = await f.exists() ? await f.text() : "";
1617
+ if (oxlintDisablePresentRe.test(content)) out.push(fp);
1594
1618
  }
1595
1619
  return out;
1596
1620
  };
@@ -1598,9 +1622,7 @@ const findBiomeIgnoreAllFiles = async (filePaths) => {
1598
1622
  const out = [];
1599
1623
  for (const fp of filePaths) {
1600
1624
  const f = file(fp);
1601
- if (await f.exists()) {
1602
- if ((await f.text()).includes("biome-ignore-all")) out.push(fp);
1603
- }
1625
+ if ((await f.exists() ? await f.text() : "").includes("biome-ignore-all")) out.push(fp);
1604
1626
  }
1605
1627
  return out;
1606
1628
  };
@@ -1633,21 +1655,27 @@ const firedBiomeByFile = async ({ biomeBin, configDir, files }) => {
1633
1655
  }
1634
1656
  return byFile;
1635
1657
  };
1658
+ const matchBiomeDirective = (line) => {
1659
+ biomeIgnoreAllRe.lastIndex = 0;
1660
+ biomeIgnoreAllLineRe.lastIndex = 0;
1661
+ return biomeIgnoreAllRe.exec(line) ?? biomeIgnoreAllLineRe.exec(line);
1662
+ };
1636
1663
  const parseBiomeDirectiveLines = (lines) => {
1637
1664
  const directiveLines = [];
1638
- for (let index = 0; index < lines.length; index += 1) {
1639
- const line = lines[index] ?? "";
1640
- biomeIgnoreAllRe.lastIndex = 0;
1641
- biomeIgnoreAllLineRe.lastIndex = 0;
1642
- const match = biomeIgnoreAllRe.exec(line) ?? biomeIgnoreAllLineRe.exec(line);
1643
- if (match) {
1644
- const first = match.groups?.first ?? "";
1645
- const rest = match.groups?.rest ?? "";
1646
- directiveLines.push({
1647
- index,
1648
- rules: [first, ...splitBiomeRest(rest)]
1649
- });
1650
- }
1665
+ const matched = lines.flatMap((line, index) => {
1666
+ const match = matchBiomeDirective(line);
1667
+ return match ? [{
1668
+ index,
1669
+ match
1670
+ }] : [];
1671
+ });
1672
+ for (const { index, match } of matched) {
1673
+ const first = match.groups?.first ?? "";
1674
+ const rest = match.groups?.rest ?? "";
1675
+ directiveLines.push({
1676
+ index,
1677
+ rules: [first, ...splitBiomeRest(rest)]
1678
+ });
1651
1679
  }
1652
1680
  return directiveLines;
1653
1681
  };
@@ -1689,51 +1717,24 @@ const rebuildBiomeDirectiveLine = ({ directive, filePath, fired, index, line })
1689
1717
  emitted: []
1690
1718
  };
1691
1719
  };
1692
- const rebuildBiomeFile = async ({ data, dryRun, fired }) => {
1693
- const result = [];
1694
- const diagnostics = [];
1695
- let removed = 0;
1696
- for (let index = 0; index < data.lines.length; index += 1) {
1697
- const line = data.lines[index] ?? "";
1698
- const directive = data.directiveLines.find((d) => d.index === index);
1699
- if (directive) {
1700
- const outcome = rebuildBiomeDirectiveLine({
1701
- directive,
1702
- filePath: data.filePath,
1703
- fired,
1704
- index,
1705
- line
1706
- });
1707
- removed += outcome.diagnostics.length;
1708
- diagnostics.push(...outcome.diagnostics);
1709
- result.push(...outcome.emitted);
1710
- } else result.push(line);
1711
- }
1712
- if (removed > 0 && !dryRun) await write(data.filePath, result.join("\n"));
1720
+ const rebuildBiomeFile = async (input) => rebuildFile(input, rebuildBiomeDirectiveLine);
1721
+ const rebuildBatch = async ({ dryRun, files, firedByFile, rebuild }) => {
1722
+ const outcomes = await Promise.all(files.map(async (data) => ({
1723
+ filePath: data.filePath,
1724
+ outcome: await rebuild({
1725
+ data,
1726
+ dryRun,
1727
+ fired: firedByFile.get(absFile(data.filePath)) ?? /* @__PURE__ */ new Set()
1728
+ })
1729
+ })));
1730
+ const diagnostics = outcomes.flatMap((result) => result.outcome.diagnostics);
1713
1731
  return {
1714
1732
  diagnostics,
1715
- removed
1733
+ files: outcomes.filter((result) => result.outcome.removed > 0).map((result) => result.filePath),
1734
+ removed: diagnostics.length
1716
1735
  };
1717
1736
  };
1718
- const removeUnusedSuppressions = async ({ dryRun = false, filePaths, root }) => {
1719
- const targets = filePaths ?? [];
1720
- if (targets.length === 0) return {
1721
- diagnostics: [],
1722
- files: [],
1723
- removed: 0
1724
- };
1725
- const configDir = joinPath(root, cacheDir);
1726
- const oxlintConfigPath = joinPath(configDir, ".oxlintrc.json");
1727
- const [oxlintBin, biomeBin] = await Promise.all([resolveBin({
1728
- bin: "oxlint",
1729
- pkg: "oxlint"
1730
- }), resolveBin({
1731
- bin: "biome",
1732
- pkg: "@biomejs/biome"
1733
- })]);
1734
- const changedFiles = /* @__PURE__ */ new Set();
1735
- const diagnostics = [];
1736
- let removed = 0;
1737
+ const removeOxlintSuppressions = async ({ dryRun, oxlintBin, oxlintConfigPath, targets }) => {
1737
1738
  const oxlintData = await collectFileData(await findOxlintDisableFiles(targets), parseOxlintDirectiveLines);
1738
1739
  if (oxlintData.length > 0) {
1739
1740
  const firedByFile = await batchStripRestore({
@@ -1744,19 +1745,20 @@ const removeUnusedSuppressions = async ({ dryRun = false, filePaths, root }) =>
1744
1745
  oxlintBin
1745
1746
  })
1746
1747
  });
1747
- for (const data of oxlintData) {
1748
- const outcome = await rebuildOxlintFile({
1749
- data,
1750
- dryRun,
1751
- fired: firedByFile.get(absFile(data.filePath)) ?? /* @__PURE__ */ new Set()
1752
- });
1753
- if (outcome.removed > 0) {
1754
- removed += outcome.removed;
1755
- changedFiles.add(data.filePath);
1756
- }
1757
- diagnostics.push(...outcome.diagnostics);
1758
- }
1748
+ return rebuildBatch({
1749
+ dryRun,
1750
+ files: oxlintData,
1751
+ firedByFile,
1752
+ rebuild: rebuildOxlintFile
1753
+ });
1759
1754
  }
1755
+ return {
1756
+ diagnostics: [],
1757
+ files: [],
1758
+ removed: 0
1759
+ };
1760
+ };
1761
+ const removeBiomeSuppressions = async ({ biomeBin, configDir, dryRun, targets }) => {
1760
1762
  const biomeData = await collectFileData(await findBiomeIgnoreAllFiles(targets), parseBiomeDirectiveLines);
1761
1763
  if (biomeData.length > 0) {
1762
1764
  const firedByFile = await batchStripRestore({
@@ -1767,27 +1769,54 @@ const removeUnusedSuppressions = async ({ dryRun = false, filePaths, root }) =>
1767
1769
  files: biomeData.map((d) => d.filePath)
1768
1770
  })
1769
1771
  });
1770
- for (const data of biomeData) {
1771
- const outcome = await rebuildBiomeFile({
1772
- data,
1773
- dryRun,
1774
- fired: firedByFile.get(absFile(data.filePath)) ?? /* @__PURE__ */ new Set()
1775
- });
1776
- if (outcome.removed > 0) {
1777
- removed += outcome.removed;
1778
- changedFiles.add(data.filePath);
1779
- }
1780
- diagnostics.push(...outcome.diagnostics);
1781
- }
1772
+ return rebuildBatch({
1773
+ dryRun,
1774
+ files: biomeData,
1775
+ firedByFile,
1776
+ rebuild: rebuildBiomeFile
1777
+ });
1782
1778
  }
1783
1779
  return {
1784
- diagnostics,
1785
- files: [...changedFiles],
1786
- removed
1780
+ diagnostics: [],
1781
+ files: [],
1782
+ removed: 0
1783
+ };
1784
+ };
1785
+ const removeUnusedSuppressions = async ({ dryRun = false, filePaths, root }) => {
1786
+ const targets = filePaths ?? [];
1787
+ if (targets.length === 0) return {
1788
+ diagnostics: [],
1789
+ files: [],
1790
+ removed: 0
1791
+ };
1792
+ const configDir = joinPath(root, cacheDir);
1793
+ const oxlintConfigPath = joinPath(configDir, ".oxlintrc.json");
1794
+ const [oxlintBin, biomeBin] = await Promise.all([resolveBin({
1795
+ bin: "oxlint",
1796
+ pkg: "oxlint"
1797
+ }), resolveBin({
1798
+ bin: "biome",
1799
+ pkg: "@biomejs/biome"
1800
+ })]);
1801
+ const oxlint = await removeOxlintSuppressions({
1802
+ dryRun,
1803
+ oxlintBin,
1804
+ oxlintConfigPath,
1805
+ targets
1806
+ });
1807
+ const biome = await removeBiomeSuppressions({
1808
+ biomeBin,
1809
+ configDir,
1810
+ dryRun,
1811
+ targets
1812
+ });
1813
+ return {
1814
+ diagnostics: [...oxlint.diagnostics, ...biome.diagnostics],
1815
+ files: [.../* @__PURE__ */ new Set([...oxlint.files, ...biome.files])],
1816
+ removed: oxlint.removed + biome.removed
1787
1817
  };
1788
1818
  };
1789
- //#endregion
1790
- //#region src/pipeline.ts
1819
+ // src/pipeline.ts
1791
1820
  /** biome-ignore-all lint/performance/noAwaitInLoops: sequential pipeline fix steps mutate files in order */
1792
1821
  const emitExtra = (result) => {
1793
1822
  for (const note of result.notes) process.stderr.write(`lintmax: ${note}\n`);
@@ -1797,6 +1826,20 @@ const formatFailureDetails = (failures) => failures.map((item) => {
1797
1826
  const messageLine = item.message ? `\n${item.message}` : "";
1798
1827
  return `- ${item.label} (exit ${item.code})${messageLine}`;
1799
1828
  }).join("\n");
1829
+ const recordFlowmarkResult = (result, failures) => {
1830
+ const { exitCode, stderr, stdout } = result;
1831
+ if (exitCode === 0) return;
1832
+ const output = [stdout.trim(), stderr.trim()].filter(Boolean).join("\n");
1833
+ failures.push({
1834
+ code: exitCode,
1835
+ label: "flowmark",
1836
+ message: output || "Flowmark failed without reporting details"
1837
+ });
1838
+ };
1839
+ const runFlowmark = async (opts, failures) => {
1840
+ const result = await runCapture(opts);
1841
+ recordFlowmarkResult(result, failures);
1842
+ };
1800
1843
  const createStepExecutor = ({ env, failures, root }) => {
1801
1844
  const runContinue = async (opts) => {
1802
1845
  try {
@@ -1843,7 +1886,7 @@ const createStepExecutor = ({ env, failures, root }) => {
1843
1886
  label: step.label,
1844
1887
  silent: step.silent
1845
1888
  };
1846
- await runContinue(opts);
1889
+ await (step.label === "flowmark" ? runFlowmark(opts, failures) : runContinue(opts));
1847
1890
  }
1848
1891
  };
1849
1892
  const runStepsSilent = async ({ steps }) => {
@@ -1854,7 +1897,8 @@ const createStepExecutor = ({ env, failures, root }) => {
1854
1897
  env,
1855
1898
  label: step.label
1856
1899
  });
1857
- if (result.exitCode !== 0) failures.push({
1900
+ if (step.label === "flowmark") recordFlowmarkResult(result, failures);
1901
+ else if (result.exitCode !== 0) failures.push({
1858
1902
  code: result.exitCode,
1859
1903
  label: step.label,
1860
1904
  message: result.stderr.length > 0 ? result.stderr.trim() : void 0
@@ -1862,7 +1906,7 @@ const createStepExecutor = ({ env, failures, root }) => {
1862
1906
  }
1863
1907
  };
1864
1908
  const clearFailures = () => {
1865
- failures.length = 0;
1909
+ failures.splice(0, failures.length, ...failures.filter((step) => step.label === "flowmark"));
1866
1910
  };
1867
1911
  const throwIfFailures = () => {
1868
1912
  if (failures.length === 0) return;
@@ -1881,7 +1925,7 @@ const createStepExecutor = ({ env, failures, root }) => {
1881
1925
  throwIfFailures
1882
1926
  };
1883
1927
  };
1884
- const createCheckSteps = ({ biomeBin, dir, eslintArgs, eslintBin, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson, targets }) => {
1928
+ const createCheckSteps = ({ biomeBin, dir, eslintArgs, eslintBin, flowmarkStep, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson, targets }) => {
1885
1929
  const oxlintCliAllow = [...OXLINT_CLI_ALLOW.flatMap((r) => ["--allow", r]), ...oxlintIgnorePatterns.flatMap((p) => ["--ignore-pattern", p])];
1886
1930
  const steps = [
1887
1931
  {
@@ -1924,6 +1968,7 @@ const createCheckSteps = ({ biomeBin, dir, eslintArgs, eslintBin, oxlintBin, oxl
1924
1968
  label: "eslint"
1925
1969
  }
1926
1970
  ];
1971
+ if (flowmarkStep) steps.push(flowmarkStep);
1927
1972
  if (prettierMarkdownTargets.length > 0) steps.push({
1928
1973
  args: [
1929
1974
  prettierBin,
@@ -1943,7 +1988,7 @@ const createCheckSteps = ({ biomeBin, dir, eslintArgs, eslintBin, oxlintBin, oxl
1943
1988
  });
1944
1989
  };
1945
1990
  const DESTRUCTIVE_FIX_OVERRIDES = ["--rule", "{\"@eslint-react/no-missing-context-display-name\":\"off\"}"];
1946
- const createFixSteps = ({ biomeBin, dir, eslintArgs, eslintBin, hasFlowmark, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson, targets }) => {
1991
+ const createFixSteps = ({ biomeBin, dir, eslintArgs, eslintBin, flowmarkStep, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson, targets }) => {
1947
1992
  const oxlintCliAllow = [...OXLINT_CLI_ALLOW.flatMap((r) => ["--allow", r]), ...oxlintIgnorePatterns.flatMap((p) => ["--ignore-pattern", p])];
1948
1993
  const steps = [
1949
1994
  {
@@ -2003,17 +2048,7 @@ const createFixSteps = ({ biomeBin, dir, eslintArgs, eslintBin, hasFlowmark, oxl
2003
2048
  silent: true
2004
2049
  }
2005
2050
  ];
2006
- if (hasFlowmark) for (const target of prettierMarkdownTargets.filter((p) => p.endsWith(".md"))) steps.push({
2007
- args: [
2008
- "-w",
2009
- "0",
2010
- "--auto",
2011
- target
2012
- ],
2013
- command: "flowmark",
2014
- label: "flowmark",
2015
- silent: true
2016
- });
2051
+ if (flowmarkStep) steps.push(flowmarkStep);
2017
2052
  if (prettierMarkdownTargets.length > 0) steps.push({
2018
2053
  args: [
2019
2054
  prettierBin,
@@ -2033,44 +2068,79 @@ const createFixSteps = ({ biomeBin, dir, eslintArgs, eslintBin, hasFlowmark, oxl
2033
2068
  return true;
2034
2069
  });
2035
2070
  };
2036
- const captureAndParse = async ({ env, failures, label, opts, parser }) => {
2037
- const result = await runCapture({
2038
- args: opts.args,
2039
- command: opts.command,
2040
- env,
2041
- label
2071
+ const recordEmptyCapture = ({ byteCount, failures, label, result }) => {
2072
+ const stderr = result.stderr.trim();
2073
+ const stdout = result.stdout.trim();
2074
+ const stdoutFirst = stdout.split("\n", 1)[0]?.trimStart() ?? "";
2075
+ const stdoutMessage = stdoutFirst.startsWith("[") || stdoutFirst.startsWith("{") ? void 0 : stdout || void 0;
2076
+ const detail = stderr.length > 0 ? stderr : stdoutMessage;
2077
+ const message = `Output parsed to zero diagnostics (${byteCount} bytes)${detail ? `\n${detail}` : ""}`;
2078
+ failures.push({
2079
+ code: result.exitCode,
2080
+ label,
2081
+ message
2042
2082
  });
2043
- if (result.exitCode === 0) return [];
2083
+ };
2084
+ const recordCaptureParseFailure = ({ failures, label, parseError, result }) => {
2044
2085
  const byteCount = Buffer.byteLength(result.stdout);
2045
2086
  const stderrDetail = result.stderr ? `\n${result.stderr.trim()}` : "";
2087
+ const detail = parseError instanceof Error ? parseError.message : String(parseError);
2088
+ failures.push({
2089
+ code: result.exitCode,
2090
+ label,
2091
+ message: `Output parse error (${byteCount} bytes): ${detail}${stderrDetail}`
2092
+ });
2093
+ };
2094
+ const parseCaptureDiagnostics = ({ failures, label, parser, result }) => {
2046
2095
  let diagnostics;
2047
2096
  try {
2048
2097
  if (label === "eslint" || label === "biome" || label === "oxlint") readRequiredJson(result.stdout);
2049
2098
  diagnostics = parser(result);
2050
2099
  } catch (parseError) {
2051
- const detail = parseError instanceof Error ? parseError.message : String(parseError);
2052
- failures.push({
2053
- code: result.exitCode,
2100
+ recordCaptureParseFailure({
2101
+ failures,
2054
2102
  label,
2055
- message: `Output parse error (${byteCount} bytes): ${detail}${stderrDetail}`
2103
+ parseError,
2104
+ result
2056
2105
  });
2057
- return [];
2106
+ return;
2058
2107
  }
2108
+ return diagnostics;
2109
+ };
2110
+ const parseCaptureResult = ({ failures, label, parser, result }) => {
2111
+ const byteCount = Buffer.byteLength(result.stdout);
2112
+ const diagnostics = parseCaptureDiagnostics({
2113
+ failures,
2114
+ label,
2115
+ parser,
2116
+ result
2117
+ });
2118
+ if (diagnostics === void 0) return [];
2059
2119
  if (diagnostics.length > 0) return diagnostics;
2060
- const stderr = result.stderr.trim();
2061
- const stdout = result.stdout.trim();
2062
- const stdoutFirst = stdout.split("\n", 1)[0]?.trimStart() ?? "";
2063
- const stdoutMessage = stdoutFirst.startsWith("[") || stdoutFirst.startsWith("{") ? void 0 : stdout || void 0;
2064
- const detail = stderr.length > 0 ? stderr : stdoutMessage;
2065
- const message = `Output parsed to zero diagnostics (${byteCount} bytes)${detail ? `\n${detail}` : ""}`;
2066
- failures.push({
2067
- code: result.exitCode,
2120
+ recordEmptyCapture({
2121
+ byteCount,
2122
+ failures,
2068
2123
  label,
2069
- message
2124
+ result
2070
2125
  });
2071
2126
  return [];
2072
2127
  };
2073
- const runAgentCheck = async ({ biomeBin, dir, env, eslintArgs, eslintBin, failures, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson, targets }) => {
2128
+ const captureAndParse = async ({ env, failures, label, opts, parser }) => {
2129
+ const result = await runCapture({
2130
+ args: opts.args,
2131
+ command: opts.command,
2132
+ env,
2133
+ label
2134
+ });
2135
+ if (result.exitCode === 0) return [];
2136
+ return parseCaptureResult({
2137
+ failures,
2138
+ label,
2139
+ parser,
2140
+ result
2141
+ });
2142
+ };
2143
+ const runAgentCheck = async ({ biomeBin, dir, env, eslintArgs, eslintBin, failures, flowmarkStep, oxlintBin, oxlintIgnorePatterns, prettierBin, prettierMarkdownTargets, sortPkgJson, targets }) => {
2074
2144
  const oxlintCliAllow = [...OXLINT_CLI_ALLOW.flatMap((r) => ["--allow", r]), ...oxlintIgnorePatterns.flatMap((p) => ["--ignore-pattern", p])];
2075
2145
  const allDiagnostics = [];
2076
2146
  const push = (d) => {
@@ -2143,6 +2213,10 @@ const runAgentCheck = async ({ biomeBin, dir, env, eslintArgs, eslintBin, failur
2143
2213
  },
2144
2214
  parser: ({ stdout }) => parseEslintDiagnostics({ stdout })
2145
2215
  }));
2216
+ if (flowmarkStep) await runFlowmark({
2217
+ ...flowmarkStep,
2218
+ env
2219
+ }, failures);
2146
2220
  if (prettierMarkdownTargets.length > 0) push(await captureAndParse({
2147
2221
  env,
2148
2222
  failures,
@@ -2255,8 +2329,7 @@ const runFixAgent = async (ctx) => {
2255
2329
  failures: ctx.failures
2256
2330
  });
2257
2331
  };
2258
- const runCheckHuman = async (ctx) => {
2259
- await ctx.runSteps({ steps: ctx.checkSteps });
2332
+ const collectHumanCustomDiagnostics = async (ctx) => {
2260
2333
  const cnDiagsHuman = await checkClassName({ root: cwd });
2261
2334
  const jsxDiagsHuman = await checkJsxExtension({ root: cwd });
2262
2335
  const unusedHuman = ctx.sourceFiles.length > 0 ? await removeUnusedSuppressions({
@@ -2268,7 +2341,7 @@ const runCheckHuman = async (ctx) => {
2268
2341
  files: [],
2269
2342
  removed: 0
2270
2343
  };
2271
- const humanCustomDiags = [
2344
+ return [
2272
2345
  ...cnDiagsHuman,
2273
2346
  ...jsxDiagsHuman,
2274
2347
  ...unusedToDiagnostics({
@@ -2283,6 +2356,10 @@ const runCheckHuman = async (ctx) => {
2283
2356
  gitFiles: ctx.allGitFiles
2284
2357
  }))
2285
2358
  ];
2359
+ };
2360
+ const runCheckHuman = async (ctx) => {
2361
+ await ctx.runSteps({ steps: ctx.checkSteps });
2362
+ const humanCustomDiags = await collectHumanCustomDiagnostics(ctx);
2286
2363
  if (humanCustomDiags.length > 0) {
2287
2364
  const grouped = aggregate({ diagnostics: humanCustomDiags });
2288
2365
  const output = formatGrouped({ files: grouped });
@@ -2313,13 +2390,10 @@ const runCheckAgent = async (ctx) => {
2313
2390
  env: ctx.env,
2314
2391
  gitFiles: ctx.allGitFiles
2315
2392
  })));
2316
- if (allDiagnostics.length > 0 || ctx.failures.length > 0) {
2317
- const grouped = aggregate({ diagnostics: allDiagnostics });
2318
- const output = formatGrouped({ files: grouped });
2319
- if (output.length > 0) process.stdout.write(`${output}\n`);
2320
- if (ctx.failures.length > 0) process.stderr.write(`${formatFailureDetails(ctx.failures)}\n`);
2321
- throw new CliExitError({ code: 1 });
2322
- }
2393
+ throwAgentResults({
2394
+ diagnostics: allDiagnostics,
2395
+ failures: ctx.failures
2396
+ });
2323
2397
  };
2324
2398
  const buildLintEnv = () => {
2325
2399
  const bundledBinA = joinPath(lintmaxRoot, "node_modules", ".bin");
@@ -2331,7 +2405,7 @@ const buildLintEnv = () => {
2331
2405
  };
2332
2406
  };
2333
2407
  const synchronizeConfig = async ({ configPath, env }) => {
2334
- await (await pathExists({ path: configPath }) ? run({
2408
+ await (await doesPathExist({ path: configPath }) ? run({
2335
2409
  args: ["-e", `const m = await import('${configPath}'); const { sync: s } = await import('lintmax'); await s(m.default);`],
2336
2410
  command: "bun",
2337
2411
  env,
@@ -2371,6 +2445,46 @@ const resolveAllBins = async () => {
2371
2445
  })
2372
2446
  ]);
2373
2447
  };
2448
+ const runUvInstaller = async (env, installDir, message) => {
2449
+ try {
2450
+ return await runCapture({
2451
+ args: ["-c", "curl -LsSf https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 sh"],
2452
+ command: "sh",
2453
+ env: {
2454
+ ...env,
2455
+ UV_INSTALL_DIR: installDir
2456
+ },
2457
+ label: "uv installer",
2458
+ timeoutMs: 12e4
2459
+ });
2460
+ } catch (installError) {
2461
+ const detail = installError instanceof Error ? installError.message : String(installError);
2462
+ const error = new CliExitError({
2463
+ code: 1,
2464
+ message: `${message}\n${detail}`
2465
+ });
2466
+ throw Object.assign(error, { cause: installError });
2467
+ }
2468
+ };
2469
+ const installUvx = async (env, installDir) => {
2470
+ const message = `Cannot find uvx after attempting to install uv. Expected ${joinPath(installDir, "uvx")}`;
2471
+ const result = await runUvInstaller(env, installDir, message);
2472
+ const installedUvx = which("uvx", { PATH: installDir });
2473
+ if (installedUvx) return installedUvx;
2474
+ const detail = result.stderr.trim() || result.stdout.trim();
2475
+ throw new CliExitError({
2476
+ code: result.exitCode || 1,
2477
+ message: detail ? `${message}\n${detail}` : message
2478
+ });
2479
+ };
2480
+ const resolveUvx = async (env) => {
2481
+ const uvxOnPath = which("uvx", { PATH: env.PATH ?? "" });
2482
+ if (uvxOnPath) return uvxOnPath;
2483
+ const installDir = joinPath(homedir(), ".local", "bin");
2484
+ const localUvx = which("uvx", { PATH: installDir });
2485
+ if (localUvx) return localUvx;
2486
+ return await installUvx(env, installDir);
2487
+ };
2374
2488
  const runFixCommand = async ({ clearFailures, ctx, fixSteps, human, runStepsSilent }) => {
2375
2489
  if (ctx.shouldComments) await fixComments({ files: ctx.sourceFiles });
2376
2490
  if (ctx.sourceFiles.length > 0) await cleanIgnores(ctx.sourceFiles.map((f) => joinPath(cwd, f)));
@@ -2382,7 +2496,7 @@ const runFixCommand = async ({ clearFailures, ctx, fixSteps, human, runStepsSile
2382
2496
  });
2383
2497
  await (human ? runFixHuman(ctx) : runFixAgent(ctx));
2384
2498
  };
2385
- const runLint = async ({ command, human = false }) => {
2499
+ const prepareLintRuntime = async () => {
2386
2500
  const dir = joinPath(cwd, cacheDir);
2387
2501
  await ensureDirectory({ directory: dir });
2388
2502
  const configPath = joinPath(cwd, "lintmax.config.ts");
@@ -2394,11 +2508,19 @@ const runLint = async ({ command, human = false }) => {
2394
2508
  });
2395
2509
  const runtime = readRequiredJson(await file(runtimePath).text());
2396
2510
  const failures = [];
2397
- const { clearFailures, runCompactContinue, runSteps, runStepsSilent, throwIfFailures } = createStepExecutor({
2511
+ return {
2512
+ dir,
2398
2513
  env,
2514
+ executor: createStepExecutor({
2515
+ env,
2516
+ failures,
2517
+ root: cwd
2518
+ }),
2399
2519
  failures,
2400
- root: cwd
2401
- });
2520
+ runtime
2521
+ };
2522
+ };
2523
+ const prepareLintFiles = async ({ command, dir, env, human, runCompactContinue, runtime }) => {
2402
2524
  const oxlintIgnorePatternsEarly = await readOxlintIgnorePatterns({ dir });
2403
2525
  const ignoreGlobsEarly = oxlintIgnorePatternsEarly.map((p) => new Glob(p));
2404
2526
  const isIgnored = (filePath) => ignoreGlobsEarly.some((g) => g.match(filePath));
@@ -2407,11 +2529,63 @@ const runLint = async ({ command, human = false }) => {
2407
2529
  isIgnored,
2408
2530
  mode: "fix"
2409
2531
  });
2410
- const allGitFiles = (await listCompactFiles({
2411
- env,
2412
- root: cwd
2413
- })).filter((one) => !isIgnored(one));
2414
- const targets = createLintTargets(allGitFiles);
2532
+ return {
2533
+ allGitFiles: (await listCompactFiles({
2534
+ env,
2535
+ root: cwd
2536
+ })).filter((one) => !isIgnored(one)),
2537
+ isIgnored,
2538
+ oxlintIgnorePatternsEarly
2539
+ };
2540
+ };
2541
+ const createFlowmarkStep = async (command, env, prettierMarkdownTargets) => {
2542
+ const markdownFiles = prettierMarkdownTargets.filter((p) => p.endsWith(".md"));
2543
+ if (markdownFiles.length === 0) return;
2544
+ const uvx = await resolveUvx(env);
2545
+ if (uvx.length === 0) return;
2546
+ return {
2547
+ args: [
2548
+ "--from",
2549
+ "flowmark@latest",
2550
+ "flowmark",
2551
+ "-w",
2552
+ "0",
2553
+ ...command === "fix" ? ["--auto"] : [
2554
+ "--check",
2555
+ "--semantic",
2556
+ "--cleanups",
2557
+ "--smartquotes",
2558
+ "--ellipses"
2559
+ ],
2560
+ ...markdownFiles
2561
+ ],
2562
+ command: uvx,
2563
+ label: "flowmark",
2564
+ silent: true
2565
+ };
2566
+ };
2567
+ const createLintCommands = ({ command, commandParams, env, failures, flowmarkStep }) => {
2568
+ const flowmarkCheckStep = command === "check" ? flowmarkStep : void 0;
2569
+ const checkSteps = createCheckSteps({
2570
+ ...commandParams,
2571
+ flowmarkStep: flowmarkCheckStep
2572
+ });
2573
+ const fixSteps = createFixSteps({
2574
+ ...commandParams,
2575
+ flowmarkStep: command === "fix" ? flowmarkStep : void 0
2576
+ });
2577
+ return {
2578
+ agentParams: {
2579
+ ...commandParams,
2580
+ env,
2581
+ failures,
2582
+ flowmarkStep: flowmarkCheckStep
2583
+ },
2584
+ checkSteps,
2585
+ fixSteps
2586
+ };
2587
+ };
2588
+ const prepareLintCommands = async ({ allGitFiles, command, dir, env, failures, oxlintIgnorePatternsEarly, targets }) => {
2415
2589
  const eslintArgs = [
2416
2590
  "--config",
2417
2591
  joinPath(dir, "eslint.generated.mjs"),
@@ -2423,62 +2597,72 @@ const runLint = async ({ command, human = false }) => {
2423
2597
  dprint: dprintBin,
2424
2598
  tombi: tombiBin
2425
2599
  };
2426
- const hasFlowmark = (await $`which flowmark`.env(env).quiet().nothrow()).exitCode === 0;
2427
- const oxlintIgnorePatterns = oxlintIgnorePatternsEarly;
2428
2600
  const prettierMarkdownTargets = allGitFiles.filter((p) => hasExtension(p, PRETTIER_EXTENSIONS)).map((p) => joinPath(cwd, p));
2429
- const checkSteps = createCheckSteps({
2430
- biomeBin,
2601
+ const flowmarkStep = await createFlowmarkStep(command, env, prettierMarkdownTargets);
2602
+ return {
2603
+ ...createLintCommands({
2604
+ command,
2605
+ commandParams: {
2606
+ biomeBin,
2607
+ dir,
2608
+ eslintArgs,
2609
+ eslintBin,
2610
+ oxlintBin,
2611
+ oxlintIgnorePatterns: oxlintIgnorePatternsEarly,
2612
+ prettierBin,
2613
+ prettierMarkdownTargets,
2614
+ sortPkgJson,
2615
+ targets
2616
+ },
2617
+ env,
2618
+ failures,
2619
+ flowmarkStep
2620
+ }),
2621
+ extraBins
2622
+ };
2623
+ };
2624
+ const prepareLintContext = async (command, isHuman) => {
2625
+ const { dir, env, executor, failures, runtime } = await prepareLintRuntime();
2626
+ const { clearFailures, runCompactContinue, runSteps, runStepsSilent, throwIfFailures } = executor;
2627
+ const { allGitFiles, isIgnored, oxlintIgnorePatternsEarly } = await prepareLintFiles({
2628
+ command,
2431
2629
  dir,
2432
- eslintArgs,
2433
- eslintBin,
2434
- oxlintBin,
2435
- oxlintIgnorePatterns,
2436
- prettierBin,
2437
- prettierMarkdownTargets,
2438
- sortPkgJson,
2630
+ env,
2631
+ human: isHuman,
2632
+ runCompactContinue,
2633
+ runtime
2634
+ });
2635
+ const targets = createLintTargets(allGitFiles);
2636
+ const { agentParams, checkSteps, extraBins, fixSteps } = await prepareLintCommands({
2637
+ allGitFiles,
2638
+ command,
2639
+ dir,
2640
+ env,
2641
+ failures,
2642
+ oxlintIgnorePatternsEarly,
2439
2643
  targets
2440
2644
  });
2441
- const shouldComments = runtime.comments !== false;
2442
- const sourceFiles = allGitFiles.filter((f) => !isIgnored(f));
2443
- const ctx = {
2444
- agentParams: {
2445
- biomeBin,
2446
- dir,
2645
+ return {
2646
+ clearFailures,
2647
+ ctx: {
2648
+ agentParams,
2649
+ allGitFiles,
2650
+ checkSteps,
2447
2651
  env,
2448
- eslintArgs,
2449
- eslintBin,
2652
+ extraBins,
2450
2653
  failures,
2451
- oxlintBin,
2452
- oxlintIgnorePatterns,
2453
- prettierBin,
2454
- prettierMarkdownTargets,
2455
- sortPkgJson,
2456
- targets
2654
+ runSteps,
2655
+ shouldComments: runtime.comments !== false,
2656
+ sourceFiles: allGitFiles.filter((f) => !isIgnored(f)),
2657
+ throwIfFailures
2457
2658
  },
2458
- allGitFiles,
2459
- checkSteps,
2460
- env,
2461
- extraBins,
2462
- failures,
2463
- runSteps,
2464
- shouldComments,
2465
- sourceFiles,
2466
- throwIfFailures
2659
+ fixSteps,
2660
+ runStepsSilent
2467
2661
  };
2662
+ };
2663
+ const runLint = async ({ command, human = false }) => {
2664
+ const { clearFailures, ctx, fixSteps, runStepsSilent } = await prepareLintContext(command, human);
2468
2665
  if (command === "fix") {
2469
- const fixSteps = createFixSteps({
2470
- biomeBin,
2471
- dir,
2472
- eslintArgs,
2473
- eslintBin,
2474
- hasFlowmark,
2475
- oxlintBin,
2476
- oxlintIgnorePatterns,
2477
- prettierBin,
2478
- prettierMarkdownTargets,
2479
- sortPkgJson,
2480
- targets
2481
- });
2482
2666
  await runFixCommand({
2483
2667
  clearFailures,
2484
2668
  ctx,
@@ -2490,8 +2674,7 @@ const runLint = async ({ command, human = false }) => {
2490
2674
  }
2491
2675
  await (human ? runCheckHuman(ctx) : runCheckAgent(ctx));
2492
2676
  };
2493
- //#endregion
2494
- //#region src/state.ts
2677
+ // src/state.ts
2495
2678
  const appDir = "lintmax";
2496
2679
  const fileName = "state.json";
2497
2680
  const userCacheDir = () => {
@@ -2546,7 +2729,7 @@ const loadState = async () => {
2546
2729
  const saveState = async (state) => {
2547
2730
  const path = statePath();
2548
2731
  try {
2549
- await write(path, `${JSON.stringify(state, null, 2)}\n`);
2732
+ await write(path, `${JSON.stringify(state, void 0, 2)}\n`);
2550
2733
  } catch {
2551
2734
  process.exitCode ??= 0;
2552
2735
  }
@@ -2571,37 +2754,54 @@ const hashTree = async ({ files, root, version }) => {
2571
2754
  for (const line of digests) hash.update(line);
2572
2755
  return hash.digest("hex");
2573
2756
  };
2574
- //#endregion
2575
- //#region src/staleness.ts
2757
+ // src/staleness.ts
2576
2758
  const httpTimeoutMs = 15e3;
2577
2759
  const cacheTtlMs = 864e5;
2578
2760
  const sixMonthsMs = 158112e5;
2579
2761
  const envSkip = "LINTMAX_SKIP_STALENESS";
2580
2762
  const envForce = "LINTMAX_STALENESS_FORCE";
2581
- /** 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. */
2582
2763
  const trackedPackages = async () => {
2583
2764
  const deps = (await readJson({ path: joinPath(lintmaxRoot, "package.json") })).dependencies;
2584
2765
  return isRecord(deps) ? Object.keys(deps).toSorted((a, b) => a.localeCompare(b)) : [];
2585
2766
  };
2586
- /** 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. */
2587
- const fetchLatestPublish = async (name) => {
2588
- const response = await fetch(`https://registry.npmjs.org/${name}`, { signal: AbortSignal.timeout(httpTimeoutMs) });
2589
- if (!response.ok) throw new Error(`registry answered ${String(response.status)} for ${name}`);
2590
- const body = await response.json();
2767
+ const readLatestTag = (distTags, name) => {
2768
+ const { latest } = distTags;
2769
+ if (typeof latest !== "string") throw new TypeError(`no latest tag for ${name}`);
2770
+ return latest;
2771
+ };
2772
+ const readPublishTime = (time, latest, name) => {
2773
+ const published = time[latest];
2774
+ if (typeof published !== "string") throw new TypeError(`no publish time for ${name}@${latest}`);
2775
+ return published;
2776
+ };
2777
+ const readPublishTables = (body, name) => {
2591
2778
  if (!isRecord(body)) throw new Error(`registry sent no document for ${name}`);
2592
2779
  const distTags = body["dist-tags"];
2593
2780
  const { time } = body;
2594
2781
  if (!isRecord(distTags)) throw new Error(`no dist-tags for ${name}`);
2595
2782
  if (!isRecord(time)) throw new Error(`no publish times for ${name} — the abbreviated packument omits them`);
2596
- const { latest } = distTags;
2597
- if (typeof latest !== "string") throw new Error(`no latest tag for ${name}`);
2598
- const published = time[latest];
2599
- if (typeof published !== "string") throw new Error(`no publish time for ${name}@${latest}`);
2783
+ return {
2784
+ distTags,
2785
+ time
2786
+ };
2787
+ };
2788
+ const readPublishMetadata = (body, name) => {
2789
+ const { distTags, time } = readPublishTables(body, name);
2790
+ const latest = readLatestTag(distTags, name);
2791
+ return {
2792
+ latest,
2793
+ published: readPublishTime(time, latest, name)
2794
+ };
2795
+ };
2796
+ const fetchLatestPublish = async (name) => {
2797
+ const response = await fetch(`https://registry.npmjs.org/${name}`, { signal: AbortSignal.timeout(httpTimeoutMs) });
2798
+ if (!response.ok) throw new Error(`registry answered ${String(response.status)} for ${name}`);
2799
+ const body = await response.json();
2800
+ const { latest, published } = readPublishMetadata(body, name);
2600
2801
  const parsed = Date.parse(published);
2601
- if (Number.isNaN(parsed)) throw new Error(`unparsable publish time for ${name}@${latest}: ${published}`);
2802
+ if (Number.isNaN(parsed)) throw new TypeError(`unparsable publish time for ${name}@${latest}: ${published}`);
2602
2803
  return parsed;
2603
2804
  };
2604
- /** 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. */
2605
2805
  const staleExceptions = {
2606
2806
  "@eslint/js": {
2607
2807
  reason: "it is the eslint monorepo own co-published config package, republished only when its recommended/all rule map changes; eslint core ships actively (10.8.x within days) while @eslint/js sits at 10.0.1 because that rule map is settled under eslint 10 — the age means finished, not abandoned",
@@ -2621,25 +2821,25 @@ const staleExceptions = {
2621
2821
  }
2622
2822
  };
2623
2823
  const toIssue = (name, publishedAt) => {
2624
- if (name in staleExceptions) return null;
2824
+ if (name in staleExceptions) return;
2625
2825
  const age = Date.now() - publishedAt;
2626
- if (age < sixMonthsMs) return null;
2826
+ if (age < sixMonthsMs) return;
2627
2827
  return {
2628
2828
  ageDays: Math.floor(age / 864e5),
2629
2829
  name
2630
2830
  };
2631
2831
  };
2632
- const scanStaleness = async (force = false) => {
2832
+ const scanStaleness = async (shouldForce = false) => {
2633
2833
  if (envValue(envSkip) === "1") return [];
2634
- const ci = envValue("CI") === "true" || envValue("CI") === "1";
2635
- const forced = force || ci || envValue(envForce) === "1";
2834
+ const isCi = envValue("CI") === "true" || envValue("CI") === "1";
2835
+ const isForced = shouldForce || isCi || envValue(envForce) === "1";
2636
2836
  const state = await loadState();
2637
- if (!forced && state.lastCheck > 0 && Date.now() - state.lastCheck < cacheTtlMs) return state.staleIssues.filter((issue) => !Object.hasOwn(staleExceptions, issue.name));
2837
+ if (!isForced && state.lastCheck > 0 && Date.now() - state.lastCheck < cacheTtlMs) return state.staleIssues.filter((issue) => !Object.hasOwn(staleExceptions, issue.name));
2638
2838
  const names = await trackedPackages();
2639
2839
  const issues = (await Promise.all(names.map(async (name) => {
2640
2840
  const publishedAt = await fetchLatestPublish(name);
2641
2841
  return toIssue(name, publishedAt);
2642
- }))).filter((issue) => issue !== null);
2842
+ }))).filter((issue) => issue !== void 0);
2643
2843
  await saveState({
2644
2844
  ...state,
2645
2845
  lastCheck: Date.now(),
@@ -2651,11 +2851,10 @@ const formatStaleness = (issues) => {
2651
2851
  if (issues.length === 0) return "";
2652
2852
  return `lintmax: stale linter deps — FAILS the gate:\n${issues.map((issue) => ` ${issue.name} latest release ${issue.ageDays}d old (>6mo)`).join("\n")}\nClear by bumping the dependency, or adding a staleExceptions entry with a reason and a revisitWhen trigger.`;
2653
2853
  };
2654
- //#endregion
2655
- //#region src/gate.ts
2854
+ // src/gate.ts
2656
2855
  const envNoCache = "LINTMAX_NO_CACHE";
2657
2856
  const computeGreenKey = async (version) => {
2658
- if (envValue(envNoCache) === "1") return null;
2857
+ if (envValue(envNoCache) === "1") return;
2659
2858
  const files = await listProjectFiles({ root: cwd });
2660
2859
  return hashTree({
2661
2860
  files,
@@ -2663,19 +2862,18 @@ const computeGreenKey = async (version) => {
2663
2862
  version
2664
2863
  });
2665
2864
  };
2666
- const tryCached = async (greenKey) => {
2667
- if (greenKey === null) return false;
2865
+ const didReuseGreenCache = async (greenKey) => {
2866
+ if (greenKey === void 0) return false;
2668
2867
  if ((await loadState()).lastGreenByCwd[cwd] !== greenKey) return false;
2669
2868
  process.stdout.write("ok (cached)\n");
2670
2869
  return true;
2671
2870
  };
2672
2871
  const persistGreen = async (greenKey) => {
2673
- if (greenKey === null) return;
2872
+ if (greenKey === void 0) return;
2674
2873
  const state = await loadState();
2675
2874
  state.lastGreenByCwd[cwd] = greenKey;
2676
2875
  await saveState(state);
2677
2876
  };
2678
- /** 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. */
2679
2877
  const emitStaleness = async () => {
2680
2878
  try {
2681
2879
  const issues = await scanStaleness();
@@ -2691,7 +2889,7 @@ const emitStaleness = async () => {
2691
2889
  };
2692
2890
  const runGate = async ({ command, human, version }) => {
2693
2891
  const startKey = await computeGreenKey(version);
2694
- if (await tryCached(startKey)) return;
2892
+ if (await didReuseGreenCache(startKey)) return;
2695
2893
  const stalePromise = emitStaleness();
2696
2894
  await runLint({
2697
2895
  command,
@@ -2702,34 +2900,36 @@ const runGate = async ({ command, human, version }) => {
2702
2900
  if (process.exitCode !== void 0 && process.exitCode !== 0) return;
2703
2901
  process.stdout.write("ok\n");
2704
2902
  };
2705
- //#endregion
2706
- //#region src/cli.ts
2903
+ // src/cli.ts
2707
2904
  const command = process.argv[2];
2708
- const main = async () => {
2709
- const version = await readVersion();
2710
- if (command === "--version" || command === "-v" || command === "version") {
2711
- process.stdout.write(`${version}\n`);
2712
- return;
2713
- }
2714
- if (command === "rules") {
2715
- const human = process.argv.includes("--human");
2716
- const rules = await extractAllRules();
2717
- const output = human ? formatRulesHuman(rules) : formatRulesCompact(rules);
2718
- process.stdout.write(`${output}\n`);
2719
- return;
2720
- }
2905
+ const printRules = async () => {
2906
+ const isHuman = process.argv.includes("--human");
2907
+ const rules = await extractAllRules();
2908
+ const output = isHuman ? formatRulesHuman(rules) : formatRulesCompact(rules);
2909
+ process.stdout.write(`${output}\n`);
2910
+ };
2911
+ const runLintCommand = async (version) => {
2721
2912
  if (command !== "fix" && command !== "check") {
2722
2913
  usage({ version });
2723
2914
  if (command === "--help" || command === "-h") return;
2724
2915
  throw new CliExitError({ code: 1 });
2725
2916
  }
2726
- const human = process.argv.includes("--human");
2917
+ const isHuman = process.argv.includes("--human");
2727
2918
  await runGate({
2728
2919
  command,
2729
- human,
2920
+ human: isHuman,
2730
2921
  version
2731
2922
  });
2732
2923
  };
2924
+ const main = async () => {
2925
+ const version = await readVersion();
2926
+ if (command === "--version" || command === "-v" || command === "version") {
2927
+ process.stdout.write(`${version}\n`);
2928
+ return;
2929
+ }
2930
+ if (command === "rules") return printRules();
2931
+ await runLintCommand(version);
2932
+ };
2733
2933
  try {
2734
2934
  await main();
2735
2935
  } catch (error) {
@@ -2738,5 +2938,4 @@ try {
2738
2938
  process.exitCode = error.code;
2739
2939
  } else throw error;
2740
2940
  }
2741
- //#endregion
2742
2941
  export {};