// `tsus fix`: apply the machine-applicable fixes that `tsus check --json`// reports. Safe fixes by default; --unsafe adds fixes that can change// behavior. Re-checks after each pass because one fix can expose or settle// another (an enum rewrite, then a let that is now never reassigned).import fs from "node:fs";import path from "node:path";import { checkProject } from "./build.js";const overlaps = (a, b) => (a.start < b.end && b.start < a.end) || (a.start === a.end && b.start === b.end && a.start === b.start);// Applies edits ({ start, end, newText }) to text. Edits must not overlap.export const applyEdits = (text, edits) => { const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end); let out = text; for (const e of sorted) { out = out.slice(0, e.start) + e.newText + out.slice(e.end); } return out;};const wanted = (d, opts) => d.fix && d.fix.edits?.length > 0 && (d.fix.safe || opts.unsafe) && (!opts.codes || opts.codes.has(d.code));export const fixProject = (rootDir, opts = {}) => { const applied = []; const maxPasses = 10; let diagnostics = []; for (let pass = 0; pass < maxPasses; pass += 1) { diagnostics = checkProject(rootDir).diagnostics; const byFile = new Map(); for (const d of diagnostics) { if (!wanted(d, opts)) { continue; } const file = path.resolve(rootDir, d.file); if (!byFile.has(file)) { byFile.set(file, []); } byFile.get(file).push(d); } if (byFile.size === 0) { break; } let changedAny = false; for (const [file, ds] of byFile) { const accepted = []; for (const d of ds) { // A fix is all-or-nothing: skip it if any edit collides with one // already accepted this pass; the next pass picks it up. if (d.fix.edits.some((e) => accepted.some((a) => overlaps(a, e)))) { continue; } accepted.push(...d.fix.edits); applied.push({ file: d.file, code: d.code, line: d.line, col: d.col, description: d.fix.description, safe: d.fix.safe }); } if (accepted.length === 0) { continue; } const before = fs.readFileSync(file, "utf8"); const after = applyEdits(before, accepted); if (after !== before) { changedAny = true; if (!opts.dryRun) { fs.writeFileSync(file, after); } } } if (!changedAny || opts.dryRun) { break; } } if (!opts.dryRun) { diagnostics = checkProject(rootDir).diagnostics; } return { applied, diagnostics };};