// src/actions/deplint/packageJsonEditor.ts
import fs from "fs";
import chalk from "chalk";
import semver from "semver";
import sortPackageJson from "sort-package-json";
function readPackageJson(location) {
  return JSON.parse(fs.readFileSync(`${location}/package.json`, "utf8"));
}
function writePackageJson(location, pkg) {
  const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
  fs.writeFileSync(`${location}/package.json`, `${sorted}
`);
}
function moveDep(pkg, dep, from, to) {
  const fromSection = pkg[from];
  if (!fromSection?.[dep]) return;
  const version = fromSection[dep];
  delete fromSection[dep];
  if (Object.keys(fromSection).length === 0) {
    delete pkg[from];
  }
  const toSection = pkg[to] ?? {};
  toSection[dep] = version;
  pkg[to] = toSection;
}
function removeDep(pkg, dep, section) {
  const sectionObj = pkg[section];
  if (!sectionObj?.[dep]) return;
  delete sectionObj[dep];
  if (Object.keys(sectionObj).length === 0) {
    delete pkg[section];
  }
}
function addDep(pkg, dep, version, section) {
  const sectionObj = pkg[section] ?? {};
  sectionObj[dep] = version;
  pkg[section] = sectionObj;
}

// src/actions/deplint/packageEditor.ts
var DeplintPackageEditor = class {
  constructor(workspace) {
    this.workspace = workspace;
    this.pkg = readPackageJson(workspace.location);
  }
  workspace;
  pkg;
  applyFix(fix) {
    switch (fix.action) {
      case "add": {
        addDep(this.pkg, fix.dependency, fix.version, fix.section);
        break;
      }
      case "move": {
        moveDep(this.pkg, fix.dependency, fix.fromSection, fix.toSection);
        if (fix.version !== void 0 && this.pkg[fix.toSection]?.[fix.dependency] !== void 0) {
          this.pkg[fix.toSection][fix.dependency] = fix.version;
        }
        break;
      }
      case "remove": {
        removeDep(this.pkg, fix.dependency, fix.section);
        break;
      }
      case "set-version": {
        addDep(this.pkg, fix.dependency, fix.version, fix.section);
        break;
      }
      case "resolve-peer-bump": {
        break;
      }
    }
    return {
      dependency: fix.dependency,
      detail: fix.detail,
      workspace: this.workspace
    };
  }
  save() {
    writePackageJson(this.workspace.location, this.pkg);
  }
};
export {
  DeplintPackageEditor
};
//# sourceMappingURL=packageEditor.mjs.map