// src/actions/deplint/packageJsonEditor.ts
import fs2 from "fs";
import chalk from "chalk";
import semver from "semver";
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 formatPeerRange(version, boundType = "major") {
  const parsed = semver.parse(version);
  if (!parsed) return `~${version}`;
  if (boundType === "minor") return `>=${parsed.version} <${parsed.major}.${parsed.minor + 1}`;
  return `>=${parsed.version} <${parsed.major + 1}`;
}
function inferPeerBoundType(devRange) {
  return devRange?.startsWith("~") ? "minor" : "major";
}
function readInstalledVersion(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return void 0;
  try {
    const depPkg = JSON.parse(fs2.readFileSync(depPkgPath, "utf8"));
    return depPkg.version;
  } catch {
    return void 0;
  }
}
function resolvePeerLowerBound(location, dep, devRange) {
  if (devRange && devRange !== "*" && !devRange.startsWith("workspace:") && !devRange.startsWith("catalog:") && !devRange.startsWith("npm:")) {
    try {
      const min = semver.minVersion(devRange);
      if (min) return min.version;
    } catch {
    }
  }
  return readInstalledVersion(location, dep);
}
function resolveDepVersion(location, dep) {
  const version = readInstalledVersion(location, dep);
  return version ? `~${version}` : "*";
}
function resolvePeerDepVersion(location, dep, devRange) {
  const lower = resolvePeerLowerBound(location, dep, devRange);
  return lower ? formatPeerRange(lower, inferPeerBoundType(devRange)) : "*";
}

// src/actions/deplint/rulesDiagnostic.ts
function isRuleFixable(rule) {
  return (rule.meta.fixable?.length ?? 0) > 0;
}
function resolvedAddFix(context, dependency, section, detail, optional) {
  const devRange = context.packageParams.devDependencyVersions[dependency];
  const version = section === "peerDependencies" ? resolvePeerDepVersion(context.workspace.location, dependency, devRange) : resolveDepVersion(context.workspace.location, dependency);
  return {
    action: "add",
    dependency,
    detail,
    ...section === "peerDependencies" && optional !== void 0 ? { optional } : {},
    section,
    version
  };
}
export {
  isRuleFixable,
  resolvedAddFix
};
//# sourceMappingURL=rulesDiagnostic.mjs.map