// src/actions/deplint/getBasePackageName.ts
function getBasePackageName(importName) {
  const importNameScrubbed = importName.replaceAll('"', "").trim();
  if (importNameScrubbed.startsWith("@")) {
    const parts = importNameScrubbed.split("/");
    return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : importNameScrubbed;
  }
  return importNameScrubbed.split("/")[0];
}

// src/actions/deplint/checkPackage/getMismatchedPeerDevVersions.ts
import chalk2 from "chalk";
import semver from "semver";

// 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;
  }
}
function getRequiredPeerDependencies(location, allDeps) {
  const required = /* @__PURE__ */ new Set();
  for (const dep of allDeps) {
    const depPkgPath = findDepPackageJson(location, dep);
    if (!depPkgPath) continue;
    try {
      const raw = fs.readFileSync(depPkgPath, "utf8");
      const pkg = JSON.parse(raw);
      const peerDeps = pkg.peerDependencies;
      if (peerDeps) {
        for (const peer of Object.keys(peerDeps)) {
          required.add(peer);
        }
      }
    } catch {
    }
  }
  return required;
}

// src/actions/deplint/packageJsonEditor.ts
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 "*";
}

// src/actions/deplint/checkPackage/getMismatchedPeerDevVersions.ts
function findMismatchedPeerDevVersions({
  peerDependencies,
  peerDependencyVersions,
  devDependencyVersions
}, exclude) {
  const mismatches = [];
  for (const dep of peerDependencies) {
    if (exclude?.has(dep)) continue;
    const peerVersion = peerDependencyVersions[dep];
    const devVersion = devDependencyVersions[dep];
    const hasWorkspaceProtocol = devVersion?.startsWith("workspace:") || peerVersion?.startsWith("workspace:");
    if (devVersion && peerVersion !== devVersion && !hasWorkspaceProtocol && !semver.subset(devVersion, peerVersion)) {
      mismatches.push({
        dep,
        devVersion,
        peerVersion
      });
    }
  }
  return mismatches;
}

// src/actions/deplint/checkPackage/getUnlistedDependencies.ts
import fs3 from "fs";
import { builtinModules } from "module";
import chalk3 from "chalk";

// src/actions/deplint/tsScriptsAliases.ts
var VARIANT_MAP = {
  "@xylabs/ts-scripts-yarn3": "@xylabs/ts-scripts-pnpm",
  "@xylabs/ts-scripts-pnpm": "@xylabs/ts-scripts-yarn3",
  "@xylabs/ts-scripts-react-yarn3": "@xylabs/ts-scripts-react-pnpm",
  "@xylabs/ts-scripts-react-pnpm": "@xylabs/ts-scripts-react-yarn3"
};
function isSatisfiedByTsScriptsVariant(imp, allDeps) {
  const variant = VARIANT_MAP[imp];
  return variant !== void 0 && allDeps.includes(variant);
}
function isUsedViaTsScriptsVariant(dep, imports) {
  const variant = VARIANT_MAP[dep];
  return variant !== void 0 && imports.includes(variant);
}

// src/actions/deplint/checkPackage/getUnlistedDependencies.ts
function isRuntimeImportListed(imp, name, dependencies, peerDependencies) {
  return dependencies.includes(imp) || imp === name || peerDependencies.includes(imp) || builtinModules.includes(imp);
}
function isDistTypeImportListed(imp, name, dependencies, devDependencies, peerDependencies) {
  return dependencies.includes(imp) || imp === name || dependencies.includes(`@types/${imp}`) || devDependencies.includes(`@types/${imp}`) || peerDependencies.includes(imp) || peerDependencies.includes(`@types/${imp}`) || builtinModules.includes(imp);
}
function shouldBePeerDependency(imp, location, currentPeers, distImports) {
  if (currentPeers.length === 0) return false;
  const depPkgPath = findDepPackageJson(location, imp);
  if (!depPkgPath) return false;
  try {
    const pkg = JSON.parse(fs3.readFileSync(depPkgPath, "utf8"));
    const importPeers = Object.keys(pkg.peerDependencies ?? {});
    const peerMeta = pkg.peerDependenciesMeta ?? {};
    const requiredPeers = importPeers.filter((peer) => !peerMeta[peer]?.optional);
    return requiredPeers.length > 0 && requiredPeers.every(
      (peer) => currentPeers.includes(peer) && distImports.includes(peer)
    );
  } catch {
    return false;
  }
}
function findUnlistedDependencies(name, dependencies, devDependencies, peerDependencies, externalDistImports, externalDistTypeImports) {
  const allDeps = [...dependencies, ...devDependencies, ...peerDependencies];
  const results = [];
  for (const imp of externalDistImports) {
    if (!isRuntimeImportListed(imp, name, dependencies, peerDependencies) && !isSatisfiedByTsScriptsVariant(imp, allDeps)) {
      results.push({ imp, section: "dependencies" });
    }
  }
  for (const imp of externalDistTypeImports) {
    if (!isDistTypeImportListed(imp, name, dependencies, devDependencies, peerDependencies) && !isSatisfiedByTsScriptsVariant(imp, allDeps)) {
      results.push({ imp, section: "dependencies" });
    }
  }
  return results;
}

// src/actions/deplint/checkPackage/getUnlistedDevDependencies.ts
import { builtinModules as builtinModules2 } from "module";
import chalk4 from "chalk";
function findUnlistedDevDeps(name, dependencies, devDependencies, peerDependencies, externalAllImports, distImports, externalDistTypeImports) {
  const results = [];
  for (const imp of externalAllImports) {
    if (!distImports.includes(imp) && !externalDistTypeImports.includes(imp) && imp !== name && !dependencies.includes(imp) && !dependencies.includes(`@types/${imp}`) && !peerDependencies.includes(imp) && !peerDependencies.includes(`@types/${imp}`) && !devDependencies.includes(imp) && !devDependencies.includes(`@types/${imp}`) && !builtinModules2.includes(imp) && !isSatisfiedByTsScriptsVariant(imp, [...dependencies, ...devDependencies, ...peerDependencies])) {
      results.push(imp);
    }
  }
  return results;
}

// src/actions/deplint/checkPackage/getUnnecessaryPeerDependencies.ts
import fs5 from "fs";
import chalk6 from "chalk";

// src/actions/deplint/checkPackage/getUnsatisfiedPeerDependencies.ts
import fs4 from "fs";
import chalk5 from "chalk";
import semver2 from "semver";
import sortPackageJson2 from "sort-package-json";
function readDepPackageJson(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return void 0;
  try {
    return JSON.parse(fs4.readFileSync(depPkgPath, "utf8"));
  } catch {
    return void 0;
  }
}
function readPeerDeps(location, dep) {
  const pkg = readDepPackageJson(location, dep);
  if (!pkg) return [];
  const peers = pkg.peerDependencies;
  return Object.keys(peers ?? {});
}
function readPeerVersionRange(location, dep, peer) {
  const pkg = readDepPackageJson(location, dep);
  if (!pkg) return void 0;
  const peers = pkg.peerDependencies;
  return peers?.[peer];
}
function readInstalledVersion(location, dep) {
  const pkg = readDepPackageJson(location, dep);
  if (!pkg) return void 0;
  return pkg.version;
}
function isPeerOptionalInAll(location, peer, sources) {
  for (const source of sources) {
    const pkg = readDepPackageJson(location, source.requiredBy);
    if (!pkg) continue;
    const meta = pkg.peerDependenciesMeta?.[peer];
    if (!meta?.optional) return false;
  }
  return true;
}
var MAX_TRANSITIVE_DEPTH = 2;
function collectPeerSources(location, dependencies, devDependencies) {
  const peerSources = /* @__PURE__ */ new Map();
  const visited = /* @__PURE__ */ new Set();
  function addPeerSource(peer, source) {
    const sources = peerSources.get(peer) ?? [];
    sources.push(source);
    peerSources.set(peer, sources);
  }
  function collectFromDeps(deps, isRuntime, chain) {
    for (const dep of deps) {
      const visitKey = `${dep}:${chain.join(">")}`;
      if (visited.has(visitKey)) continue;
      visited.add(visitKey);
      for (const peer of readPeerDeps(location, dep)) {
        addPeerSource(peer, {
          chain: chain.length > 0 ? [...chain, dep] : void 0,
          isRuntimeDep: isRuntime,
          requiredBy: dep
        });
      }
      if (chain.length < MAX_TRANSITIVE_DEPTH) {
        const depPkg = readDepPackageJson(location, dep);
        if (depPkg) {
          const transitiveDeps = Object.keys(depPkg.dependencies ?? {});
          collectFromDeps(transitiveDeps, isRuntime, [...chain, dep]);
        }
      }
    }
  }
  collectFromDeps(dependencies, true, []);
  const devOnly = devDependencies.filter((d) => !dependencies.includes(d));
  collectFromDeps(devOnly, false, []);
  return peerSources;
}
function getRequiredTransitivePeers(location, { dependencies, devDependencies }) {
  const peerSources = collectPeerSources(location, dependencies, devDependencies);
  return new Set(peerSources.keys());
}
function resolveVersionRange(location, sources, peer) {
  for (const source of sources) {
    const range = readPeerVersionRange(location, source.requiredBy, peer);
    if (range) return range;
  }
  return "*";
}
function checkVersionSatisfaction(location, peer, requestedRange) {
  const installedVersion = readInstalledVersion(location, peer);
  if (!installedVersion) return { satisfied: true };
  if (requestedRange === "*") return { installedVersion, satisfied: true };
  if (requestedRange.startsWith("workspace:")) return { installedVersion, satisfied: true };
  try {
    const satisfied = semver2.satisfies(installedVersion, requestedRange, { includePrerelease: true });
    return { installedVersion, satisfied };
  } catch {
    return { installedVersion, satisfied: true };
  }
}
function findDeclaredPeerVersionMismatches(name, location, peerDependencies, peerDependencyVersions, exclude) {
  const results = [];
  for (const peer of peerDependencies) {
    if (exclude?.has(peer) || peer === name) continue;
    const declaredRange = peerDependencyVersions[peer];
    if (!declaredRange || declaredRange === "*") continue;
    const { installedVersion, satisfied } = checkVersionSatisfaction(location, peer, declaredRange);
    if (!satisfied) {
      results.push({
        hasRuntimeSource: true,
        installedVersion,
        peer,
        reason: "version-mismatch",
        sources: [{ isRuntimeDep: true, requiredBy: name }],
        versionRange: declaredRange
      });
    }
  }
  return results;
}
function findUnsatisfiedPeers({ name, location }, {
  dependencies,
  devDependencies,
  peerDependencies,
  peerDependencyVersions
}, exclude, isTerminal) {
  const peerSources = collectPeerSources(location, dependencies, devDependencies);
  const depsSet = new Set(dependencies);
  const devDepsSet = new Set(devDependencies);
  const peerDepsSet = new Set(peerDependencies);
  const isTerminalResolved = isTerminal ?? isTerminalPackage(`${location}/package.json`);
  const unsatisfied = [];
  for (const [peer, sources] of peerSources) {
    if (exclude?.has(peer) || peer === name) continue;
    if (isPeerOptionalInAll(location, peer, sources)) continue;
    const hasRuntimeSource = sources.some((s) => s.isRuntimeDep);
    const isPresent = depsSet.has(peer) || devDepsSet.has(peer);
    if (!isPresent) {
      const versionRange2 = resolveVersionRange(location, sources, peer);
      unsatisfied.push({
        hasRuntimeSource,
        peer,
        reason: "missing",
        sources,
        versionRange: versionRange2
      });
      continue;
    }
    const hasDirectRuntimeSource = sources.some((s) => s.isRuntimeDep && !s.chain);
    if (hasDirectRuntimeSource && !isTerminalResolved && !depsSet.has(peer) && !peerDepsSet.has(peer)) {
      const versionRange2 = resolveVersionRange(location, sources, peer);
      unsatisfied.push({
        hasRuntimeSource,
        peer,
        reason: "under-exposed",
        sources,
        versionRange: versionRange2
      });
      continue;
    }
    const versionRange = resolveVersionRange(location, sources, peer);
    const { installedVersion, satisfied } = checkVersionSatisfaction(location, peer, versionRange);
    if (!satisfied) {
      unsatisfied.push({
        hasRuntimeSource,
        installedVersion,
        peer,
        reason: "version-mismatch",
        sources,
        versionRange
      });
    }
  }
  return [
    ...unsatisfied,
    ...findDeclaredPeerVersionMismatches(name, location, peerDependencies, peerDependencyVersions, exclude)
  ];
}
function isTerminalPackage(packageJsonPath) {
  try {
    const pkg = JSON.parse(fs4.readFileSync(packageJsonPath, "utf8"));
    return pkg.private === true;
  } catch {
    return false;
  }
}
function resolvePeerTargetSections(hasRuntimeSource, isTerminal) {
  if (!hasRuntimeSource) return ["devDependencies"];
  if (isTerminal) return ["dependencies"];
  return ["peerDependencies", "devDependencies"];
}

// src/actions/deplint/checkPackage/getUnnecessaryPeerDependencies.ts
function isPeerImportedInDist(dep, externalDistImports, externalDistTypeImports) {
  const baseName = dep.replace(/^@types\//, "");
  return externalDistImports.includes(dep) || externalDistImports.includes(baseName) || externalDistTypeImports.includes(dep) || externalDistTypeImports.includes(baseName);
}
function findUnrequestedPeerDeps(location, packageParams, { externalDistImports, externalDistTypeImports }, exclude) {
  const requiredPeers = getRequiredTransitivePeers(location, packageParams);
  const unrequested = [];
  for (const dep of packageParams.peerDependencies) {
    if (exclude?.has(dep)) continue;
    if (packageParams.dependencies.includes(dep)) continue;
    if (!isPeerImportedInDist(dep, externalDistImports, externalDistTypeImports)) continue;
    if (!requiredPeers.has(dep)) {
      unrequested.push(dep);
    }
  }
  return unrequested;
}
function findRedundantPeerDeps({ peerDependencies, dependencies }, exclude) {
  const depsSet = new Set(dependencies);
  const redundant = [];
  for (const dep of peerDependencies) {
    if (exclude?.has(dep)) continue;
    if (depsSet.has(dep)) {
      redundant.push(dep);
    }
  }
  return redundant;
}

// src/actions/deplint/checkPackage/getUnusedDependencies.ts
import chalk7 from "chalk";
function isDepImported(dep, distImports, distTypeImports) {
  const baseName = dep.replace(/^@types\//, "");
  return distImports.includes(dep) || distImports.includes(baseName) || distTypeImports.includes(dep) || distTypeImports.includes(baseName);
}
function findUnusedDependencies(location, dependencies, devDependencies, externalDistImports, externalDistTypeImports, externalAllImports, exclude) {
  const runtimeRequiredPeers = getRequiredPeerDependencies(location, dependencies);
  const devRequiredPeers = getRequiredPeerDependencies(location, devDependencies);
  const results = [];
  for (const dep of dependencies) {
    if (exclude?.has(dep)) continue;
    if (runtimeRequiredPeers.has(dep)) continue;
    const isImported = isDepImported(dep, externalDistImports, externalDistTypeImports);
    if (isImported || isUsedViaTsScriptsVariant(dep, [...externalDistImports, ...externalDistTypeImports])) continue;
    if (devRequiredPeers.has(dep)) {
      results.push({
        dep,
        kind: "move-to-dev",
        reason: "only needed as peer of devDependencies"
      });
    } else if (externalAllImports.includes(dep)) {
      results.push({ dep, kind: "move-to-dev" });
    } else {
      results.push({ dep, kind: "remove" });
    }
  }
  return results;
}

// src/actions/deplint/checkPackage/getUnusedDevDependencies.ts
import chalk8 from "chalk";

// src/actions/deplint/getCliReferencedPackagesFromFiles.ts
import fs7 from "fs";
import path3 from "path";
import ts from "typescript";

// src/actions/deplint/getScriptReferencedPackages.ts
import fs6 from "fs";
import path2 from "path";
function getBinNames(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return [];
  try {
    const raw = fs6.readFileSync(depPkgPath, "utf8");
    const pkg = JSON.parse(raw);
    if (!pkg.bin) return [];
    if (typeof pkg.bin === "string") return [pkg.name?.split("/").pop() ?? dep];
    return Object.keys(pkg.bin);
  } catch {
    return [];
  }
}
function tokenizeScript(script) {
  return script.split(/[&|;$()"`\s]+/).map((t) => t.trim()).filter(Boolean);
}
function getScriptReferencedPackages(location, allDeps) {
  const pkgPath = path2.join(location, "package.json");
  let scripts;
  try {
    const raw = fs6.readFileSync(pkgPath, "utf8");
    const pkg = JSON.parse(raw);
    scripts = pkg.scripts ?? {};
  } catch {
    return /* @__PURE__ */ new Set();
  }
  const scriptText = Object.values(scripts).join(" ");
  const tokens = new Set(tokenizeScript(scriptText));
  const binToPackage = /* @__PURE__ */ new Map();
  for (const dep of allDeps) {
    const bins = getBinNames(location, dep);
    for (const bin of bins) {
      binToPackage.set(bin, dep);
    }
  }
  const referenced = /* @__PURE__ */ new Set();
  for (const token of tokens) {
    const baseName = getBasePackageName(token);
    if (allDeps.includes(baseName)) {
      referenced.add(baseName);
    }
    const pkg = binToPackage.get(token);
    if (pkg) {
      referenced.add(pkg);
    }
  }
  return referenced;
}

// src/actions/deplint/getCliReferencedPackagesFromFiles.ts
var shellCommandFunctions = /* @__PURE__ */ new Set(["execSync", "exec"]);
var directExecFunctions = /* @__PURE__ */ new Set(["spawn", "spawnSync", "execFile", "execFileSync"]);
var allExecFunctions = /* @__PURE__ */ new Set([...shellCommandFunctions, ...directExecFunctions]);
function getCommandTokensFromFile(filePath) {
  const tokens = /* @__PURE__ */ new Set();
  let sourceCode;
  try {
    sourceCode = fs7.readFileSync(filePath, "utf8");
  } catch {
    return tokens;
  }
  const isMjsFile = filePath.endsWith(".mjs");
  const sourceFile = ts.createSourceFile(
    path3.basename(filePath),
    sourceCode,
    ts.ScriptTarget.Latest,
    true,
    isMjsFile ? ts.ScriptKind.JS : void 0
  );
  function visit(node) {
    if (ts.isCallExpression(node) && node.arguments.length > 0) {
      const fnName = getFunctionName(node.expression);
      if (fnName && allExecFunctions.has(fnName)) {
        const firstArg = node.arguments[0];
        if (ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg)) {
          const value = firstArg.text;
          if (shellCommandFunctions.has(fnName)) {
            for (const token of tokenizeScript(value)) {
              tokens.add(token);
            }
          } else {
            tokens.add(value);
          }
        } else if (ts.isTemplateExpression(firstArg)) {
          const head = firstArg.head.text;
          if (head) {
            for (const token of tokenizeScript(head)) {
              tokens.add(token);
            }
          }
        }
      }
    }
    ts.forEachChild(node, visit);
  }
  visit(sourceFile);
  return tokens;
}
function getFunctionName(expr) {
  if (ts.isIdentifier(expr)) {
    return expr.text;
  }
  if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.name)) {
    return expr.name.text;
  }
  return void 0;
}
function getCliReferencedPackagesFromFiles(allFiles, location, allDeps) {
  const allTokens = /* @__PURE__ */ new Set();
  for (const file of allFiles) {
    for (const token of getCommandTokensFromFile(file)) {
      allTokens.add(token);
    }
  }
  if (allTokens.size === 0) return /* @__PURE__ */ new Set();
  const binToPackage = /* @__PURE__ */ new Map();
  for (const dep of allDeps) {
    for (const bin of getBinNames(location, dep)) {
      binToPackage.set(bin, dep);
    }
  }
  const referenced = /* @__PURE__ */ new Set();
  for (const token of allTokens) {
    const baseName = getBasePackageName(token);
    if (allDeps.includes(baseName)) {
      referenced.add(baseName);
    }
    const pkg = binToPackage.get(token);
    if (pkg) {
      referenced.add(pkg);
    }
  }
  return referenced;
}

// src/actions/deplint/implicitDevDependencies.ts
import fs8 from "fs";
var hasFileWithExtension = (files, extensions) => files.some((f) => extensions.some((ext) => f.endsWith(ext)));
var tsExtensions = [".ts", ".tsx", ".mts", ".cts"];
var hasTypescriptFiles = ({ allFiles }) => hasFileWithExtension(allFiles, tsExtensions);
var decoratorPattern = /^\s*@[a-zA-Z]\w*/m;
var hasDecorators = ({ allFiles }) => allFiles.filter((f) => tsExtensions.some((ext) => f.endsWith(ext))).some((file) => {
  try {
    const content = fs8.readFileSync(file, "utf8");
    return decoratorPattern.test(content);
  } catch {
    return false;
  }
});
var hasDependencyRequiringTslib = ({ location, allDependencies }) => allDependencies.some((dep) => {
  const pkgPath = findDepPackageJson(location, dep);
  if (!pkgPath) return false;
  try {
    const pkg = JSON.parse(fs8.readFileSync(pkgPath, "utf8"));
    const peers = pkg.peerDependencies;
    return peers !== void 0 && "tslib" in peers;
  } catch {
    return false;
  }
});
var importPlugins = /* @__PURE__ */ new Set(["eslint-plugin-import-x", "eslint-plugin-import"]);
function hasImportPlugin({ location, allDependencies }) {
  if (allDependencies.some((d) => importPlugins.has(d))) return true;
  for (const dep of allDependencies) {
    const pkgPath = findDepPackageJson(location, dep);
    if (!pkgPath) continue;
    try {
      const pkg = JSON.parse(fs8.readFileSync(pkgPath, "utf8"));
      const transitiveDeps = [
        ...Object.keys(pkg.dependencies ?? {}),
        ...Object.keys(pkg.peerDependencies ?? {})
      ];
      if (transitiveDeps.some((d) => importPlugins.has(d))) return true;
    } catch {
    }
  }
  return false;
}
var hasVitest = ({ allDependencies }) => allDependencies.includes("vitest");
var rules = [
  {
    package: "typescript",
    isNeeded: hasTypescriptFiles
  },
  {
    package: "eslint-import-resolver-typescript",
    isNeeded: (context) => hasTypescriptFiles(context) && context.allDependencies.includes("eslint") && hasImportPlugin(context)
  },
  {
    package: "tslib",
    isNeeded: (context) => hasDecorators(context) || hasDependencyRequiringTslib(context)
  },
  {
    package: "@vitest/coverage-v8",
    isNeeded: hasVitest
  },
  {
    package: "@xylabs/toolchain",
    isNeeded: hasTypescriptFiles
  }
];
function getImplicitDevDependencies(context) {
  const implicit = /* @__PURE__ */ new Set();
  for (const rule of rules) {
    if (rule.isNeeded(context)) {
      implicit.add(rule.package);
    }
  }
  return implicit;
}

// src/actions/deplint/checkPackage/getUnusedDevDependencies.ts
var allExternalImports = ({
  externalAllImports,
  externalDistImports,
  externalDistTypeImports
}) => {
  return /* @__PURE__ */ new Set([
    ...externalAllImports,
    ...externalDistImports,
    ...externalDistTypeImports
  ]);
};
function isDevDepUsed(dep, allImports, implicitDeps, requiredPeers, scriptRefs, cliRefs) {
  if (implicitDeps.has(dep)) return true;
  if (requiredPeers.has(dep)) return true;
  if (scriptRefs.has(dep)) return true;
  if (cliRefs.has(dep)) return true;
  if (dep.startsWith("@types/")) {
    const baseName = dep.replace(/^@types\//, "");
    return allImports.has(baseName) || allImports.has(dep) || implicitDeps.has(baseName);
  }
  if (allImports.has(dep)) return true;
  return isUsedViaTsScriptsVariant(dep, [...allImports]);
}
function findUnusedDevDeps(location, dependencies, devDependencies, peerDependencies, sourceParams, fileContext, exclude) {
  const allImports = allExternalImports(sourceParams);
  const allDeps = [...dependencies, ...devDependencies, ...peerDependencies];
  const implicitDeps = getImplicitDevDependencies({
    ...fileContext,
    allDependencies: allDeps,
    location
  });
  const requiredPeers = getRequiredPeerDependencies(location, allDeps);
  const scriptRefs = getScriptReferencedPackages(location, allDeps);
  const cliRefs = getCliReferencedPackagesFromFiles(fileContext.allFiles, location, allDeps);
  const unused = [];
  for (const dep of devDependencies) {
    if (exclude?.has(dep)) continue;
    if (dependencies.includes(dep) || peerDependencies.includes(dep)) continue;
    if (!isDevDepUsed(dep, allImports, implicitDeps, requiredPeers, scriptRefs, cliRefs)) {
      unused.push(dep);
    }
  }
  return unused;
}

// src/actions/deplint/checkPackage/getUnusedPeerDependencies.ts
import chalk9 from "chalk";
function isPeerUsed(dep, externalDistImports, externalDistTypeImports) {
  const baseName = dep.replace(/^@types\//, "");
  return externalDistImports.includes(dep) || externalDistImports.includes(baseName) || externalDistTypeImports.includes(dep) || externalDistTypeImports.includes(baseName);
}
function findUnusedPeerDeps(peerDependencies, externalDistImports, externalDistTypeImports, exclude) {
  const unused = [];
  for (const dep of peerDependencies) {
    if (exclude?.has(dep)) continue;
    if (!isPeerUsed(dep, externalDistImports, externalDistTypeImports)) {
      unused.push(dep);
    }
  }
  return unused;
}

// src/actions/deplint/checkPackage/getWorkspaceVersionProblems.ts
import chalk10 from "chalk";
import semver3 from "semver";
function checkSection(deps, versions, section, workspaceNames, problems) {
  for (const dep of deps) {
    if (!workspaceNames.has(dep)) continue;
    const version = versions[dep];
    if (version && !version.startsWith("workspace:")) {
      problems.push({
        dep,
        section,
        version
      });
    }
  }
}
function findWorkspaceVersionProblems(packageParams, workspaceNames) {
  const problems = [];
  checkSection(packageParams.dependencies, packageParams.dependencyVersions, "dependencies", workspaceNames, problems);
  checkSection(packageParams.devDependencies, packageParams.devDependencyVersions, "devDependencies", workspaceNames, problems);
  return problems;
}
function findWorkspacePeerVersionProblems(packageParams, workspaceNames, location) {
  const problems = [];
  for (const dep of packageParams.peerDependencies) {
    if (!workspaceNames.has(dep)) continue;
    const declaredRange = packageParams.peerDependencyVersions[dep];
    if (!declaredRange || declaredRange.startsWith("workspace:")) continue;
    const resolved = resolveDepVersion(location, dep);
    const actualVersion = resolved.startsWith("~") ? resolved.slice(1) : resolved;
    if (actualVersion === "*") continue;
    if (!semver3.satisfies(actualVersion, declaredRange)) {
      problems.push({
        actualVersion,
        declaredRange,
        dep
      });
    }
  }
  return problems;
}

// src/actions/deplint/rules.ts
function diagnostic(context, id, message, dependency, evidence, fixes) {
  return {
    dependency,
    evidence,
    file: context.packageJsonPath,
    fixes,
    id,
    message,
    severity: "error",
    workspace: context.workspace
  };
}
function resolvedAddFix(context, dependency, section, detail) {
  return {
    action: "add",
    dependency,
    detail,
    section,
    version: resolveDepVersion(context.workspace.location, dependency)
  };
}
var unlistedDependenciesRule = {
  category: "dependencies",
  id: "deplint.dependencies.unlisted",
  evaluate(context) {
    const findings = findUnlistedDependencies(
      context.workspace.name,
      context.packageParams.dependencies,
      context.packageParams.devDependencies,
      context.packageParams.peerDependencies,
      context.sourceParams.externalDistImports,
      context.sourceParams.externalDistTypeImports
    );
    return findings.map(({ imp, section }) => {
      const isPeer = !context.isTerminalPackage && section === "dependencies" && !context.forceDeps.has(imp) && shouldBePeerDependency(imp, context.workspace.location, context.packageParams.peerDependencies, context.sourceParams.externalDistImports);
      const fixes = isPeer ? ["peerDependencies", "devDependencies"].map(
        (s) => resolvedAddFix(context, imp, s, `added to ${s}`)
      ) : [resolvedAddFix(context, imp, section, `added to ${section}`)];
      return diagnostic(
        context,
        "deplint.dependencies.unlisted",
        `Missing dependency in package.json: ${imp}`,
        imp,
        context.sourceParams.distImportPaths[imp],
        fixes
      );
    });
  }
};
var unusedDependenciesRule = {
  category: "dependencies",
  id: "deplint.dependencies.unused",
  evaluate(context) {
    const findings = findUnusedDependencies(
      context.workspace.location,
      context.packageParams.dependencies,
      context.packageParams.devDependencies,
      context.sourceParams.externalDistImports,
      context.sourceParams.externalDistTypeImports,
      context.sourceParams.externalAllImports,
      context.unusedDependencyExclude
    );
    return findings.map(({
      dep,
      kind,
      reason
    }) => diagnostic(
      context,
      "deplint.dependencies.unused",
      kind === "move-to-dev" ? `dependency should be devDependency in package.json: ${dep}${reason ? ` (${reason})` : ""}` : `Unused dependency in package.json: ${dep}`,
      dep,
      void 0,
      [kind === "move-to-dev" ? {
        action: "move",
        dependency: dep,
        detail: "moved to devDependencies",
        fromSection: "dependencies",
        toSection: "devDependencies"
      } : {
        action: "remove",
        dependency: dep,
        detail: "removed from dependencies",
        section: "dependencies"
      }]
    ));
  }
};
var unlistedDevDependenciesRule = {
  category: "devDependencies",
  id: "deplint.devDependencies.unlisted",
  evaluate(context) {
    const findings = findUnlistedDevDeps(
      context.workspace.name,
      context.packageParams.dependencies,
      context.packageParams.devDependencies,
      context.packageParams.peerDependencies,
      context.sourceParams.externalAllImports,
      context.sourceParams.distImports,
      context.sourceParams.externalDistTypeImports
    );
    return findings.map((imp) => diagnostic(
      context,
      "deplint.devDependencies.unlisted",
      `Missing devDependency in package.json: ${imp}`,
      imp,
      context.sourceParams.allImportPaths[imp],
      [resolvedAddFix(context, imp, "devDependencies", "added to devDependencies")]
    ));
  }
};
var unusedDevDependenciesRule = {
  category: "devDependencies",
  id: "deplint.devDependencies.unused",
  evaluate(context) {
    const findings = findUnusedDevDeps(
      context.workspace.location,
      context.packageParams.dependencies,
      context.packageParams.devDependencies,
      context.packageParams.peerDependencies,
      context.sourceParams,
      context.fileContext,
      context.unusedDependencyExclude
    );
    return findings.map((dep) => diagnostic(
      context,
      "deplint.devDependencies.unused",
      `Unused devDependency in package.json: ${dep}`,
      dep,
      void 0,
      [{
        action: "remove",
        dependency: dep,
        detail: "removed from devDependencies",
        section: "devDependencies"
      }]
    ));
  }
};
var redundantDevDependenciesRule = {
  category: "devDependencies",
  id: "deplint.devDependencies.redundant",
  evaluate(context) {
    const diagnostics = [];
    for (const dep of context.packageParams.devDependencies) {
      if (!context.packageParams.dependencies.includes(dep)) continue;
      if (!context.isTerminalPackage && !context.forceDeps.has(dep) && shouldBePeerDependency(dep, context.workspace.location, context.packageParams.peerDependencies, context.sourceParams.externalDistImports)) {
        continue;
      }
      diagnostics.push(diagnostic(
        context,
        "deplint.devDependencies.redundant",
        `Redundant devDependency ${dep} \u2014 already listed in dependencies`,
        dep,
        void 0,
        [{
          action: "remove",
          dependency: dep,
          detail: "removed redundant devDependency (kept in dependencies)",
          section: "devDependencies"
        }]
      ));
    }
    return diagnostics;
  }
};
function generateVersionMismatchFixes(context, finding) {
  const expectedVersion = resolveExpectedPeerVersion(
    context.workspace.location,
    finding.peer,
    finding.versionRange
  );
  if (expectedVersion === "*") return [];
  const fixes = [];
  if (context.packageParams.peerDependencies.includes(finding.peer)) {
    fixes.push({
      action: "set-version",
      dependency: finding.peer,
      detail: `updated peerDependency version to match installed (${finding.installedVersion})`,
      section: "peerDependencies",
      version: expectedVersion
    });
  }
  if (context.packageParams.devDependencies.includes(finding.peer)) {
    const devVersion = context.packageParams.devDependencyVersions[finding.peer];
    if (devVersion && !devVersion.startsWith("workspace:")) {
      fixes.push({
        action: "set-version",
        dependency: finding.peer,
        detail: `updated devDependency version to match installed (${finding.installedVersion})`,
        section: "devDependencies",
        version: expectedVersion
      });
    }
  }
  return fixes;
}
var unsatisfiedPeersRule = {
  category: "peerDependencies",
  id: "deplint.peerDependencies.unsatisfied",
  evaluate(context) {
    const findings = findUnsatisfiedPeers(
      context.workspace,
      context.packageParams,
      context.exclude,
      context.isTerminalPackage
    );
    return findings.map((finding) => {
      const requiredBy = finding.sources.map((source) => source.requiredBy).join(", ");
      const chain = finding.sources.find((source) => source.chain && source.chain.length > 0)?.chain?.join(" -> ");
      const evidence = chain ? [`via ${chain}`] : void 0;
      const message = finding.reason === "version-mismatch" ? `Peer dependency version mismatch ${finding.peer} \u2014 installed ${finding.installedVersion ?? "unknown"} does not satisfy ${finding.versionRange} (required by ${requiredBy})` : finding.reason === "under-exposed" ? `Under-exposed peer dependency ${finding.peer} (required by ${requiredBy}) \u2014 in devDependencies only; must also be in dependencies or peerDependencies` : finding.hasRuntimeSource ? `Unsatisfied peer dependency ${finding.peer} (required by ${requiredBy}) \u2014 must be in dependencies or peerDependencies` : `Unsatisfied peer dependency ${finding.peer} (required by devDependency ${requiredBy}) \u2014 must be in dependencies, devDependencies, or peerDependencies`;
      const fixes = finding.reason === "missing" ? resolvePeerTargetSections(finding.hasRuntimeSource, context.isTerminalPackage).map((section) => ({
        action: "add",
        dependency: finding.peer,
        detail: `added to ${section}`,
        section,
        version: finding.versionRange
      })) : finding.reason === "under-exposed" ? [{
        action: "add",
        dependency: finding.peer,
        detail: "added to peerDependencies",
        section: "peerDependencies",
        version: finding.versionRange
      }] : finding.reason === "version-mismatch" ? generateVersionMismatchFixes(context, finding) : void 0;
      return diagnostic(
        context,
        "deplint.peerDependencies.unsatisfied",
        message,
        finding.peer,
        evidence,
        fixes
      );
    });
  }
};
var unusedPeerDependenciesRule = {
  category: "peerDependencies",
  id: "deplint.peerDependencies.unused",
  evaluate(context) {
    const findings = findUnusedPeerDeps(
      context.packageParams.peerDependencies,
      context.sourceParams.externalDistImports,
      context.sourceParams.externalDistTypeImports,
      context.unusedDependencyExclude
    );
    return findings.map((dep) => diagnostic(
      context,
      "deplint.peerDependencies.unused",
      context.packageParams.dependencies.includes(dep) ? `Unused peerDependency [already a dependency] in package.json: ${dep}` : `Unused peerDependency in package.json: ${dep}`,
      dep,
      void 0,
      [{
        action: "remove",
        dependency: dep,
        detail: "removed from peerDependencies",
        section: "peerDependencies"
      }]
    ));
  }
};
var unrequestedPeerDependenciesRule = {
  category: "peerDependencies",
  id: "deplint.peerDependencies.unrequested",
  evaluate(context) {
    if (!context.isTerminalPackage) return [];
    const findings = findUnrequestedPeerDeps(
      context.workspace.location,
      context.packageParams,
      context.sourceParams,
      context.exclude
    );
    return findings.map((dep) => diagnostic(
      context,
      "deplint.peerDependencies.unrequested",
      `Unnecessary peerDependency ${dep} \u2014 imported in dist but no dependency requires it as a peer; should be a dependency`,
      dep,
      void 0,
      [{
        action: "move",
        dependency: dep,
        detail: "moved from peerDependencies to dependencies",
        fromSection: "peerDependencies",
        toSection: "dependencies",
        version: context.packageParams.peerDependencyVersions[dep] ?? "*"
      }]
    ));
  }
};
var misplacedDependenciesRule = {
  category: "dependencies",
  id: "deplint.dependencies.misplaced",
  evaluate(context) {
    if (context.isTerminalPackage) return [];
    const diagnostics = [];
    for (const dep of context.packageParams.dependencies) {
      if (context.forceDeps.has(dep)) continue;
      if (context.forcePeers.has(dep) || shouldBePeerDependency(dep, context.workspace.location, context.packageParams.peerDependencies, context.sourceParams.externalDistImports)) {
        const fixes = [{
          action: "move",
          dependency: dep,
          detail: "moved from dependencies to peerDependencies",
          fromSection: "dependencies",
          toSection: "peerDependencies"
        }];
        if (!context.packageParams.devDependencies.includes(dep)) {
          fixes.push(resolvedAddFix(context, dep, "devDependencies", "added to devDependencies"));
        }
        const reason = context.forcePeers.has(dep) ? 'configured as refType "peer"' : "it shares peers with existing peerDependencies";
        diagnostics.push(diagnostic(
          context,
          "deplint.dependencies.misplaced",
          `dependency ${dep} should be a peerDependency \u2014 ${reason}`,
          dep,
          void 0,
          fixes
        ));
      }
    }
    return diagnostics;
  }
};
var misplacedPeerDependenciesRule = {
  category: "peerDependencies",
  id: "deplint.peerDependencies.misplaced",
  evaluate(context) {
    const diagnostics = [];
    for (const dep of context.packageParams.peerDependencies) {
      if (context.forceDeps.has(dep)) {
        const fixes = [{
          action: "move",
          dependency: dep,
          detail: "moved from peerDependencies to dependencies",
          fromSection: "peerDependencies",
          toSection: "dependencies",
          version: context.packageParams.peerDependencyVersions[dep] ?? "*"
        }];
        diagnostics.push(diagnostic(
          context,
          "deplint.peerDependencies.misplaced",
          `peerDependency ${dep} should be a dependency \u2014 configured as refType "dep"`,
          dep,
          void 0,
          fixes
        ));
      }
    }
    return diagnostics;
  }
};
var redundantPeerDependenciesRule = {
  category: "peerDependencies",
  id: "deplint.peerDependencies.redundant",
  evaluate(context) {
    const findings = findRedundantPeerDeps(context.packageParams, context.exclude);
    return findings.map((dep) => diagnostic(
      context,
      "deplint.peerDependencies.redundant",
      `Redundant peerDependency ${dep} \u2014 already listed in dependencies`,
      dep,
      void 0,
      [{
        action: "remove",
        dependency: dep,
        detail: "removed redundant peerDependency (kept in dependencies)",
        section: "peerDependencies"
      }]
    ));
  }
};
var mismatchedPeerDevVersionsRule = {
  category: "peerDependencies",
  id: "deplint.peerDependencies.version-mismatch",
  evaluate(context) {
    const findings = findMismatchedPeerDevVersions(context.packageParams, context.exclude);
    return findings.map(({
      dep,
      devVersion,
      peerVersion
    }) => diagnostic(
      context,
      "deplint.peerDependencies.version-mismatch",
      `Peer/dev version mismatch ${dep} \u2014 peer: ${peerVersion}, dev: ${devVersion}`,
      dep,
      void 0,
      [{
        action: "set-version",
        dependency: dep,
        detail: "synced peerDependency to devDependency version",
        section: "peerDependencies",
        version: devVersion
      }]
    ));
  }
};
var workspaceVersionProblemsRule = {
  category: "peerDependencies",
  id: "deplint.workspace.protocol",
  evaluate(context) {
    if (!context.workspaceNames) return [];
    const protocolFindings = findWorkspaceVersionProblems(context.packageParams, context.workspaceNames);
    const protocolDiagnostics = protocolFindings.map(({
      dep,
      section,
      version
    }) => diagnostic(
      context,
      "deplint.workspace.protocol",
      `Workspace dependency ${dep} in ${section} should use workspace: protocol \u2014 found ${version}`,
      dep,
      void 0,
      [{
        action: "set-version",
        dependency: dep,
        detail: `set workspace:~ for ${section}`,
        section,
        version: "workspace:~"
      }]
    ));
    const peerFindings = findWorkspacePeerVersionProblems(
      context.packageParams,
      context.workspaceNames,
      context.workspace.location
    );
    const peerDiagnostics = peerFindings.map(({
      dep,
      actualVersion,
      declaredRange
    }) => {
      const expectedRange = resolveExpectedPeerVersion(
        context.workspace.location,
        dep,
        declaredRange
      );
      return diagnostic(
        context,
        "deplint.workspace.protocol",
        `Workspace peerDependency ${dep} range ${declaredRange} does not satisfy workspace version ${actualVersion}`,
        dep,
        void 0,
        expectedRange === "*" ? void 0 : [{
          action: "set-version",
          dependency: dep,
          detail: "updated peerDependency to match workspace version",
          section: "peerDependencies",
          version: expectedRange
        }]
      );
    });
    return [...protocolDiagnostics, ...peerDiagnostics];
  }
};
var deplintRules = [
  unlistedDependenciesRule,
  unusedDependenciesRule,
  misplacedDependenciesRule,
  unlistedDevDependenciesRule,
  unusedDevDependenciesRule,
  redundantDevDependenciesRule,
  unsatisfiedPeersRule,
  unusedPeerDependenciesRule,
  unrequestedPeerDependenciesRule,
  misplacedPeerDependenciesRule,
  redundantPeerDependenciesRule,
  mismatchedPeerDevVersionsRule,
  workspaceVersionProblemsRule
];
export {
  deplintRules
};
//# sourceMappingURL=rules.mjs.map