// src/actions/deplint/packageJsonEditor.ts
import fs2 from "fs";
import chalk from "chalk";
import sortPackageJson from "sort-package-json";

// src/actions/deplint/getRequiredPeerDependencies.ts
import fs from "fs";
import path from "path";
function findDepPackageJson(location, dep) {
  let dir = location;
  while (true) {
    const candidate = path.join(dir, "node_modules", dep, "package.json");
    if (fs.existsSync(candidate)) return candidate;
    const parent = path.dirname(dir);
    if (parent === dir) return void 0;
    dir = parent;
  }
}

// src/actions/deplint/packageJsonEditor.ts
function readPackageJson(location) {
  return JSON.parse(fs2.readFileSync(`${location}/package.json`, "utf8"));
}
function writePackageJson(location, pkg) {
  const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
  fs2.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;
}
function resolveDepVersion(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (depPkgPath) {
    try {
      const depPkg = JSON.parse(fs2.readFileSync(depPkgPath, "utf8"));
      const version = depPkg.version;
      if (version) return `~${version}`;
    } catch {
    }
  }
  return "*";
}
function resolveExpectedPeerVersion(location, dep, currentRange) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (depPkgPath) {
    try {
      const depPkg = JSON.parse(fs2.readFileSync(depPkgPath, "utf8"));
      const version = depPkg.version;
      if (version) {
        const match = /^(\d+)\.(\d+)/.exec(version);
        if (match) {
          if (currentRange?.startsWith("^")) {
            return `^${match[1]}`;
          }
          return `~${match[1]}.${match[2]}`;
        }
        return `~${version}`;
      }
    } catch {
    }
  }
  return "*";
}
function logFix(workspace, action, dep, detail) {
  const detailStr = detail ? ` (${detail})` : "";
  console.log(`[${chalk.blue(workspace.name)}] Fixed: ${action} ${chalk.green(dep)}${detailStr}`);
}
export {
  addDep,
  logFix,
  moveDep,
  readPackageJson,
  removeDep,
  resolveDepVersion,
  resolveExpectedPeerVersion,
  writePackageJson
};
//# sourceMappingURL=packageJsonEditor.mjs.map