// src/actions/packman/clean.ts
import {
  existsSync as existsSync11,
  rmSync as rmSync5,
  writeFileSync as writeFileSync11
} from "node:fs";
import PATH13 from "node:path";
import chalk15 from "chalk";

// src/actions/packman/convert.ts
import {
  existsSync as existsSync10,
  readdirSync as readdirSync2,
  statSync as statSync2
} from "node:fs";
import PATH12 from "node:path";
import chalk14 from "chalk";

// src/lib/packageManagerRuntime.ts
import fs from "node:fs";
import chalk from "chalk";

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/packageManagerRuntime.ts
var DISPLAY_NAMES = {
  bun: "Bun",
  npm: "npm",
  pnpm: "pnpm",
  yarn: "Yarn"
};
var MAC_INSTALL_COMMANDS = {
  bun: "brew install oven-sh/bun/bun",
  npm: "brew install node",
  pnpm: "brew install pnpm",
  yarn: "brew install yarn"
};
var SUPPORTED_PLATFORMS = ["darwin", "linux", "win32"];
function currentPlatform() {
  return SUPPORTED_PLATFORMS.find((platform) => platform === process.platform) ?? "unknown";
}
function shouldAskYesNo(question) {
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
    return false;
  }
  process.stdout.write(question);
  const buffer = Buffer.alloc(1024);
  const bytesRead = fs.readSync(process.stdin.fd, buffer, 0, buffer.length, null);
  const answer = buffer.toString("utf8", 0, bytesRead).trim().toLowerCase();
  return answer === "y" || answer === "yes";
}
function isCommandInstalled(command) {
  const result = spawnSync(command, ["--version"], {
    encoding: "utf8",
    stdio: "ignore"
  });
  return !result.error && result.status === 0;
}
function isPackageManagerInstalled(pm) {
  return isCommandInstalled(pm);
}
function getPackageManagerInstallPlan(pm, platform = currentPlatform()) {
  const displayName = DISPLAY_NAMES[pm];
  if (platform === "darwin") {
    const command = MAC_INSTALL_COMMANDS[pm];
    return {
      command,
      manualInstructions: [
        `Install ${displayName} with: ${command}`
      ],
      packageManager: pm,
      platform,
      supported: true
    };
  }
  if (platform === "linux") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Linux yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  if (platform === "win32") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Windows yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  return {
    manualInstructions: [
      `Automatic installation for ${displayName} is not implemented on ${platform} yet.`,
      `Install ${displayName} manually and re-run the command.`
    ],
    packageManager: pm,
    platform,
    supported: false
  };
}
function printManualInstructions(plan, context) {
  console.error(chalk.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk.gray(`  ${line}`));
  }
}
function shouldInstallWithHomebrew(pm, cwd) {
  const command = MAC_INSTALL_COMMANDS[pm];
  const result = spawnSync("brew", command.replace("brew ", "").split(" "), {
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  return result.status === 0;
}
function didEnsurePackageManagerInstalled(pm, context) {
  if (isPackageManagerInstalled(pm)) return true;
  const plan = getPackageManagerInstallPlan(pm, context.platform ?? currentPlatform());
  const displayName = DISPLAY_NAMES[pm];
  console.error(chalk.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk.gray(`  ${plan.command}`));
    return false;
  }
  const isConfirmed = shouldAskYesNo(chalk.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!isConfirmed) {
    console.error(chalk.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!shouldInstallWithHomebrew(pm, context.cwd)) {
    console.error(chalk.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk.green(`${displayName} installed successfully.`));
  return true;
}
function failureResult() {
  return {
    output: ["", ""],
    pid: 0,
    signal: null,
    status: 1,
    stderr: "",
    stdout: ""
  };
}
function spawnPackageManagerSync(pm, args, options) {
  if (!didEnsurePackageManagerInstalled(pm, options.context)) {
    return failureResult();
  }
  return spawnSync(pm, args, { encoding: "utf8", ...options });
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH.resolve(cwd, "package.json"));
}
function readWorkspacePatternsFromPackageJson(cwd = process.cwd()) {
  const pkg = readRootPackageJson(cwd);
  if (!pkg?.workspaces) return [];
  if (Array.isArray(pkg.workspaces)) return [...pkg.workspaces];
  return pkg.workspaces.packages ? [...pkg.workspaces.packages] : [];
}
function readPnpmWorkspacePatterns(cwd = process.cwd()) {
  const wsPath = PATH.resolve(cwd, "pnpm-workspace.yaml");
  if (!existsSync(wsPath)) return [];
  const content = readFileSync(wsPath, "utf8");
  const patterns = [];
  let isInPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      isInPackages = true;
      continue;
    }
    if (isInPackages) {
      const match = /^\s+-\s+['"]?([^'"]+)['"]?\s*$/.exec(line);
      if (match) {
        patterns.push(match[1]);
      } else if (line.trim() !== "" && !/^\s/.test(line)) {
        break;
      }
    }
  }
  return patterns;
}
function readWorkspacePatterns(cwd = process.cwd()) {
  const fromPackageJson = readWorkspacePatternsFromPackageJson(cwd);
  return fromPackageJson.length > 0 ? fromPackageJson : readPnpmWorkspacePatterns(cwd);
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!(packageManager != null && packageManager.length > 0)) return void 0;
  return packageManager.split("@", 1)[0];
}

// src/pm/detectPackageManager.ts
import { existsSync as existsSync2 } from "node:fs";
var knownPackageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
function detectPackageManager() {
  const packageManager = detectPackageManagerFromPackageJson();
  if (packageManager != null && packageManager.length > 0 && knownPackageManagers.has(packageManager)) {
    return packageManager;
  }
  if (existsSync2("pnpm-lock.yaml") || existsSync2("pnpm-workspace.yaml")) return "pnpm";
  if (existsSync2("bun.lock") || existsSync2("bun.lockb")) return "bun";
  if (existsSync2("yarn.lock") || existsSync2(".yarnrc.yml")) return "yarn";
  if (existsSync2("package-lock.json") || existsSync2("npm-shrinkwrap.json")) return "npm";
  return "yarn";
}

// src/pm/registry.ts
var implementations = /* @__PURE__ */ new Map();
function getPackageManager(name) {
  const pmName = name ?? detectPackageManager();
  const pm = implementations.get(pmName);
  if (!pm) {
    throw new Error(
      `No package manager implementation registered for "${pmName}". Ensure registerPackageManager() has been called before getPackageManager().`
    );
  }
  return pm;
}

// src/actions/package-lint.ts
import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "node:fs";
import PATH6 from "node:path";
import chalk7 from "chalk";

// src/lib/deepMerge.ts
var UNSAFE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
function isPlainObject(value) {
  if (typeof value !== "object" || value === null) return false;
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}
function isMergeable(value) {
  return Array.isArray(value) || isPlainObject(value);
}
function cloneValue(value) {
  if (Array.isArray(value)) {
    return value.map((item) => cloneValue(item));
  }
  if (isPlainObject(value)) {
    const result = {};
    for (const [key, item] of Object.entries(value)) {
      if (UNSAFE_KEYS.has(key)) continue;
      result[key] = cloneValue(item);
    }
    return result;
  }
  return value;
}
function mergeObject(target, source, options) {
  const destination = {};
  if (isPlainObject(target)) {
    for (const [key, item] of Object.entries(target)) {
      if (UNSAFE_KEYS.has(key)) continue;
      destination[key] = cloneValue(item);
    }
  }
  for (const [key, sourceValue] of Object.entries(source)) {
    if (UNSAFE_KEYS.has(key)) continue;
    if (Object.hasOwn(target, key) && isMergeable(sourceValue)) {
      const customMerge = options.customMerge?.(key);
      destination[key] = (customMerge ?? deepMerge)(target[key], sourceValue, options);
    } else {
      destination[key] = cloneValue(sourceValue);
    }
  }
  return destination;
}
function deepMerge(target, source, options = {}) {
  const isSourceIsArray = Array.isArray(source);
  const isTargetIsArray = Array.isArray(target);
  if (isSourceIsArray !== isTargetIsArray) {
    return cloneValue(source);
  }
  if (isSourceIsArray) {
    return [...target, ...source].map((item) => cloneValue(item));
  }
  return mergeObject(target, source, options);
}

// src/lib/toolchainVersion.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { createRequire } from "node:module";
var require2 = createRequire(import.meta.url);
function bundledToolchainVersion() {
  const pkgPath = require2.resolve("@xylabs/toolchain/package.json");
  const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
  if (!(pkg.version != null && pkg.version.length > 0)) throw new Error("Could not read @xylabs/toolchain version");
  return pkg.version;
}
function bundledToolchainRange() {
  return `^${bundledToolchainVersion()}`;
}

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/latestVersions.ts
var latestVersions = {
  node: "24.14.1",
  nodeLtsCodename: "Krypton",
  npm: "11.11.0",
  pnpm: "10.33.0",
  yarn: "4.13.0"
};

// src/lib/loadConfig.ts
import chalk2 from "chalk";
import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
var configState = {
  config: void 0,
  rootConfigPath: void 0
};
function createExplorer() {
  return cosmiconfig("xy", { cache: true, loaders: { ".ts": TypeScriptLoader() } });
}
var loadConfig = async (params) => {
  if (configState.config === void 0) {
    const cosmicConfigResult = await createExplorer().search();
    configState.config = cosmicConfigResult?.config ?? {};
    configState.rootConfigPath = cosmicConfigResult?.filepath;
    const configFilePath = cosmicConfigResult?.filepath;
    if (configFilePath !== void 0) {
      console.log(chalk2.green(`Loaded config from ${configFilePath}`));
      if (Boolean(configState.config.verbose)) {
        console.log(chalk2.gray(JSON.stringify(configState.config, null, 2)));
      }
    }
  }
  return deepMerge(configState.config, params ?? {});
};

// src/lib/match.ts
import { minimatch } from "minimatch";
function makeMatcher(pattern, options = {}) {
  const patterns = Array.isArray(pattern) ? pattern : [pattern];
  return (input) => patterns.some((p) => minimatch(input, p, options));
}

// src/lib/npmLatestVersion.ts
var REGISTRY_BASE = "https://registry.npmjs.org";
var cache = /* @__PURE__ */ new Map();
async function fetchUncached(packageName) {
  try {
    const url = `${REGISTRY_BASE}/${encodeURIComponent(packageName)}/latest`;
    const res = await fetch(url, { headers: { Accept: "application/vnd.npm.install-v1+json" } });
    if (!res.ok) return void 0;
    const data = await res.json();
    return data.version;
  } catch {
    return void 0;
  }
}
function fetchLatestPackageVersion(packageName) {
  const existing = cache.get(packageName);
  if (existing) return existing;
  const pending = fetchUncached(packageName);
  cache.set(packageName, pending);
  return pending;
}

// src/lib/pnpmConfig/readMinReleaseAge.ts
import * as yaml from "yaml";
var DEFAULT_MINIMUM_RELEASE_AGE_MINUTES = 1440;

// src/lib/shouldRunInstall.ts
import chalk3 from "chalk";
function shouldRunInstall(cwd) {
  const pm = detectPackageManager();
  console.log(chalk3.gray(`Running ${pm} install...`));
  const result = spawnPackageManagerSync(pm, ["install"], {
    context: { cwd, operation: `Run ${pm} install` },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (result.status !== 0) {
    console.warn(chalk3.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk3.green("Dependencies installed"));
  return true;
}

// src/actions/package-lint-deps.ts
import { readFileSync as readFileSync3, writeFileSync } from "node:fs";
import PATH2 from "node:path";
import chalk4 from "chalk";
import semver from "semver";
function readWorkspacePackageJson(cwd, location) {
  const pkgPath = PATH2.resolve(cwd, location, "package.json");
  try {
    return JSON.parse(readFileSync3(pkgPath, "utf8"));
  } catch {
    return void 0;
  }
}
function writeWorkspacePackageJson(cwd, location, pkg) {
  const pkgPath = PATH2.resolve(cwd, location, "package.json");
  writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
}
function buildWorkspaceVersionMap(cwd, workspaces) {
  const map = /* @__PURE__ */ new Map();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    if (version != null && version.length > 0) map.set(name, version);
  }
  return map;
}
function internalWorkspaceEntries(deps, workspaceVersions) {
  return Object.entries(deps).flatMap(([dep, version]) => {
    const targetVersion = workspaceVersions.get(dep);
    return targetVersion != null && targetVersion.length > 0 ? [[dep, version, targetVersion]] : [];
  });
}
function workspaceProtocolEntries(deps, workspaceNames) {
  return Object.entries(deps).filter(([dep]) => workspaceNames.has(dep));
}
function internalPeerEntries(peerDeps, workspaceVersions, shouldRewriteWorkspaceProtocol) {
  return Object.entries(peerDeps).flatMap(([dep, version]) => {
    const targetVersion = workspaceVersions.get(dep);
    if (!(targetVersion != null && targetVersion.length > 0)) return [];
    if (shouldRewriteWorkspaceProtocol && version.startsWith("workspace:")) return [];
    return [[dep, version, targetVersion]];
  });
}
function forEachReadableWorkspace(cwd, workspaces, callback) {
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    callback(pkg, location, name);
  }
}
function forEachDependencyField(pkg, callback) {
  for (const depField of ["dependencies", "devDependencies"]) {
    const deps = pkg[depField];
    if (!deps) continue;
    callback(depField, deps);
  }
}
function internalPeerVersionIssue(name, location, dep, version, targetVersion, devDepVersion, shouldRewriteWorkspaceProtocol) {
  if (version.startsWith("workspace:")) {
    if (shouldRewriteWorkspaceProtocol) return void 0;
    const expected2 = expectedPeerRange(devDepVersion, targetVersion);
    return `${name} (${location}) peerDependencies.${dep} uses workspace: protocol \u2014 should be "${expected2}"`;
  }
  const expected = expectedPeerRange(devDepVersion, targetVersion);
  if (version !== expected && !semver.satisfies(targetVersion, version)) {
    return `${name} (${location}) peerDependencies.${dep} is "${version}" \u2014 current version ${targetVersion} is not satisfied; expected "${expected}"`;
  }
  return void 0;
}
function expectedPeerRange(devDepVersion, targetVersion) {
  const parsed = semver.parse(targetVersion);
  if (!parsed) return `~${targetVersion}`;
  if (devDepVersion === "workspace:^") {
    return `^${parsed.major}`;
  }
  return `~${parsed.major}.${parsed.minor}`;
}
function checkVersionConsistency(cwd, rootPkg, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  if (rootPkg.version !== void 0) {
    result.fixable.push('Root package.json should not have a "version" field in a monorepo');
  }
  const versions = /* @__PURE__ */ new Map();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    if (version != null && version.length > 0) {
      versions.set(name, version);
    } else {
      result.errors.push(`${name} (${location}) is missing a "version" field`);
    }
  }
  const uniqueVersions = new Set(versions.values());
  if (uniqueVersions.size > 1) {
    const versionList = [...uniqueVersions].toSorted(semver.rcompare);
    for (const [name, version] of versions) {
      if (version !== versionList[0]) {
        result.fixable.push(`${name} has version ${version} (expected ${versionList[0]})`);
      }
    }
  }
  return result;
}
function fixVersionConsistency(cwd, rootPkg, writeRootPackageJson2, workspaces) {
  if (rootPkg.version !== void 0) {
    delete rootPkg.version;
    writeRootPackageJson2(cwd, rootPkg);
    console.log(chalk4.green('  \u2714 Fixed: removed "version" from root package.json'));
  }
  const versions = [];
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    const validVersion = version === void 0 ? null : semver.valid(version);
    if (version !== void 0 && version.length > 0 && validVersion !== null && validVersion.length > 0) {
      versions.push(version);
    }
  }
  if (versions.length === 0) return;
  const highest = versions.toSorted(semver.rcompare)[0];
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    if (pkg.version !== highest) {
      pkg.version = highest;
      writeWorkspacePackageJson(cwd, location, pkg);
      console.log(chalk4.green(`  \u2714 Fixed: set version to ${highest} in ${name} (${location})`));
    }
  }
}
function expectedDepVersion(targetVersion) {
  const parsed = semver.parse(targetVersion);
  if (!parsed) return `~${targetVersion}`;
  return `~${targetVersion}`;
}
function checkInternalDepVersions(cwd, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  forEachReadableWorkspace(cwd, workspaces, (pkg, location, name) => {
    forEachDependencyField(pkg, (depField, deps) => {
      for (const [dep, version, targetVersion] of internalWorkspaceEntries(deps, workspaceVersions)) {
        const expected = expectedDepVersion(targetVersion);
        if (version.startsWith("workspace:")) {
          result.fixable.push(
            `${name} (${location}) ${depField}.${dep} is "${version}" \u2014 should be "${expected}" (not workspace: protocol)`
          );
        } else if (version !== expected) {
          result.fixable.push(
            `${name} (${location}) ${depField}.${dep} is "${version}" \u2014 should be "${expected}"`
          );
        }
      }
    });
  });
  return result;
}
function fixInternalDepVersions(cwd, workspaces) {
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  forEachReadableWorkspace(cwd, workspaces, (pkg, location, name) => {
    let isModified = false;
    forEachDependencyField(pkg, (depField, deps) => {
      for (const [dep, version, targetVersion] of internalWorkspaceEntries(deps, workspaceVersions)) {
        const expected = expectedDepVersion(targetVersion);
        if (version !== expected) {
          deps[dep] = expected;
          console.log(chalk4.green(`  \u2714 Fixed: set ${depField}.${dep} to "${expected}" in ${name} (${location})`));
          isModified = true;
        }
      }
    });
    if (isModified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  });
}
function checkWorkspaceProtocol(cwd, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  const workspaceNames = new Set(workspaces.map((w) => w.name));
  forEachReadableWorkspace(cwd, workspaces, (pkg, location, name) => {
    forEachDependencyField(pkg, (depField, deps) => {
      for (const [dep, version] of workspaceProtocolEntries(deps, workspaceNames)) {
        if (!version.startsWith("workspace:")) {
          result.fixable.push(
            `${name} (${location}) ${depField}.${dep} is "${version}" \u2014 should use workspace: protocol`
          );
        }
      }
    });
  });
  return result;
}
function fixWorkspaceProtocol(cwd, workspaces) {
  const workspaceNames = new Set(workspaces.map((w) => w.name));
  forEachReadableWorkspace(cwd, workspaces, (pkg, location, name) => {
    let isModified = false;
    forEachDependencyField(pkg, (depField, deps) => {
      for (const [dep, version] of workspaceProtocolEntries(deps, workspaceNames)) {
        if (!version.startsWith("workspace:")) {
          deps[dep] = "workspace:~";
          console.log(chalk4.green(`  \u2714 Fixed: set ${depField}.${dep} to "workspace:~" in ${name} (${location})`));
          isModified = true;
        }
      }
    });
    if (isModified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  });
}
function checkInternalPeerVersions(cwd, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  const pmName = getPackageManager().name;
  const isRewritesWorkspaceProtocol = pmName === "pnpm" || pmName === "bun";
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const peerDeps = pkg.peerDependencies;
    if (!peerDeps) continue;
    const devDeps = pkg.devDependencies;
    for (const [dep, version, targetVersion] of internalPeerEntries(peerDeps, workspaceVersions, isRewritesWorkspaceProtocol)) {
      const issue = internalPeerVersionIssue(name, location, dep, version, targetVersion, devDeps?.[dep], isRewritesWorkspaceProtocol);
      if (issue != null && issue.length > 0) result.fixable.push(issue);
    }
  }
  return result;
}
function fixInternalPeerVersions(cwd, workspaces) {
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  const pmName = getPackageManager().name;
  const isRewritesWorkspaceProtocol = pmName === "pnpm" || pmName === "bun";
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const peerDeps = pkg.peerDependencies;
    if (!peerDeps) continue;
    const devDeps = pkg.devDependencies;
    let isModified = false;
    for (const [dep, version, targetVersion] of internalPeerEntries(peerDeps, workspaceVersions, isRewritesWorkspaceProtocol)) {
      const expected = expectedPeerRange(devDeps?.[dep], targetVersion);
      if (version !== expected) {
        peerDeps[dep] = expected;
        console.log(chalk4.green(`  \u2714 Fixed: set peerDependencies.${dep} to "${expected}" in ${name} (${location})`));
        isModified = true;
      }
    }
    if (isModified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}

// src/actions/package-lint-engines.ts
import { readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
import PATH3 from "node:path";
import chalk5 from "chalk";
import semver2 from "semver";
function emptyResult() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function isTerminalPackage(pkg) {
  return pkg.private === true;
}
function checkVoltaOnlyInRoot(cwd, workspaces) {
  const result = emptyResult();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH3.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
      if (Boolean(pkg.volta)) {
        result.fixable.push(`${name} (${location}) has a volta field \u2014 only the root should define this`);
      }
    } catch {
    }
  }
  return result;
}
function fixVoltaOnlyInRoot(cwd, _pkg, workspaces) {
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH3.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync4(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (Boolean(pkg.volta)) {
        delete pkg.volta;
        writeFileSync2(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: removed volta from ${location}/package.json`));
      }
    } catch {
    }
  }
}
function checkEnginesOnlyInNonTerminal(cwd, workspaces) {
  const result = emptyResult();
  const rootPkg = JSON.parse(readFileSync4(PATH3.resolve(cwd, "package.json"), "utf8"));
  if (Boolean(rootPkg.engines)) {
    result.fixable.push("Root package.json has engines \u2014 terminal packages should not declare engines (use volta instead)");
  }
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH3.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
      if (isTerminalPackage(pkg) && Boolean(pkg.engines)) {
        result.fixable.push(`${name} (${location}) is terminal (private) but has engines \u2014 terminal packages should not declare engines`);
      }
      if (!isTerminalPackage(pkg) && !Boolean(pkg.engines)) {
        result.fixable.push(`${name} (${location}) is a library but has no engines field`);
      }
    } catch {
    }
  }
  return result;
}
function resolveEnginesTemplate(cwd, workspaces) {
  for (const { location } of workspaces) {
    if (location === ".") continue;
    try {
      const pkg = JSON.parse(readFileSync4(PATH3.resolve(cwd, location, "package.json"), "utf8"));
      if (!isTerminalPackage(pkg) && Boolean(pkg.engines)) {
        return pkg.engines;
      }
    } catch {
    }
  }
  return void 0;
}
function fixEnginesOnlyInNonTerminal(cwd, _pkg, workspaces) {
  const rootPath = PATH3.resolve(cwd, "package.json");
  const rootRaw = readFileSync4(rootPath, "utf8");
  const rootPkg = JSON.parse(rootRaw);
  if (Boolean(rootPkg.engines)) {
    delete rootPkg.engines;
    writeFileSync2(rootPath, `${JSON.stringify(rootPkg, null, 2)}
`, "utf8");
    console.log(chalk5.green("  \u2714 Fixed: removed engines from root package.json"));
  }
  const enginesTemplate = resolveEnginesTemplate(cwd, workspaces);
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH3.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync4(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (isTerminalPackage(pkg) && Boolean(pkg.engines)) {
        delete pkg.engines;
        writeFileSync2(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: removed engines from ${location}/package.json`));
      }
      if (!isTerminalPackage(pkg) && !Boolean(pkg.engines) && enginesTemplate) {
        pkg.engines = enginesTemplate;
        writeFileSync2(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: added engines to ${location}/package.json`));
      }
    } catch {
    }
  }
}
function checkVersionsIncludeLts(cwd, workspaces) {
  const result = emptyResult();
  const toolVersions = {
    node: latestVersions.node,
    npm: latestVersions.npm,
    pnpm: latestVersions.pnpm,
    yarn: latestVersions.yarn
  };
  for (const { location, name } of workspaces) {
    const pkgPath = location === "." ? PATH3.resolve(cwd, "package.json") : PATH3.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
      const label = location === "." ? "root" : `${name} (${location})`;
      const engines = pkg.engines;
      if (engines) {
        for (const [tool, range] of Object.entries(engines)) {
          const latest = toolVersions[tool];
          if (latest && !semver2.satisfies(latest, range)) {
            result.errors.push(
              `${label} engines.${tool} "${range}" does not include latest ${tool === "node" ? "LTS " : ""}version ${latest}`
            );
          }
        }
      }
      const volta = pkg.volta;
      if (volta) {
        for (const [tool, pinnedVersion] of Object.entries(volta)) {
          const latest = toolVersions[tool];
          if (latest && semver2.lt(pinnedVersion, latest)) {
            result.warnings.push(
              `${label} volta.${tool} "${pinnedVersion}" is older than latest ${tool === "node" ? "LTS " : ""}version ${latest}`
            );
          }
        }
      }
    } catch {
    }
  }
  return result;
}

// src/actions/package-lint-pnpm.ts
import {
  existsSync as existsSync3,
  readFileSync as readFileSync5,
  writeFileSync as writeFileSync3
} from "node:fs";
import PATH4 from "node:path";
import chalk6 from "chalk";
import * as yaml2 from "yaml";
function emptyResult2() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function pnpmWorkspacePath(cwd) {
  return PATH4.resolve(cwd, "pnpm-workspace.yaml");
}
function readPnpmWorkspaceDocument(cwd) {
  const wsPath = pnpmWorkspacePath(cwd);
  if (!existsSync3(wsPath)) return void 0;
  try {
    return yaml2.parseDocument(readFileSync5(wsPath, "utf8"));
  } catch {
    return void 0;
  }
}
function readPnpmWorkspaceGlobs(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return void 0;
  const packages = doc.get("packages");
  if (!yaml2.isSeq(packages)) return void 0;
  const globs = [];
  for (const item of packages.items) {
    const value = yaml2.isScalar(item) ? item.value : item;
    if (typeof value === "string") globs.push(value);
  }
  return globs.length > 0 ? globs : void 0;
}
var PNPM_RELEASE_AGE_REQUIRED_EXCLUDES = ["@xylabs/*", "@xyo-network/*"];
function readSequenceStrings(node) {
  if (!yaml2.isSeq(node)) return [];
  const out = [];
  for (const item of node.items) {
    const value = yaml2.isScalar(item) ? item.value : item;
    if (typeof value === "string") out.push(value);
  }
  return out;
}
function checkPnpmReleaseAgeExcludes(cwd, pm) {
  const result = emptyResult2();
  if (pm !== "pnpm") return result;
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return result;
  const existing = readSequenceStrings(doc.get("minimumReleaseAgeExclude"));
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (!existing.includes(required)) {
      result.fixable.push(`pnpm-workspace.yaml minimumReleaseAgeExclude is missing '${required}'`);
    }
  }
  return result;
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isConfiguredValue(value) {
  if (value === void 0 || value === null) return false;
  if (isRecord(value)) return Object.keys(value).length > 0;
  if (Array.isArray(value)) return value.length > 0;
  return value !== "";
}
function configuredYamlKeys(node) {
  if (!yaml2.isMap(node)) return [];
  const keys = [];
  for (const item of node.items) {
    const key = yaml2.isScalar(item.key) ? item.key.value : item.key;
    if (typeof key === "string" || typeof key === "number") keys.push(String(key));
  }
  return keys;
}
function isConfiguredYamlNode(node) {
  if (node === void 0 || node === null) return false;
  if (yaml2.isMap(node) || yaml2.isSeq(node)) return node.items.length > 0;
  if (yaml2.isScalar(node)) return node.value !== void 0 && node.value !== null && node.value !== "";
  return true;
}
function formatOverrideWarning(location, keys) {
  if (keys.length === 0) return `${location} defines dependency overrides`;
  const shown = keys.slice(0, 5).join(", ");
  const suffix = keys.length > 5 ? `, and ${keys.length - 5} more` : "";
  return `${location} defines ${keys.length} dependency override${keys.length === 1 ? "" : "s"}: ${shown}${suffix}`;
}
function checkPnpmDependencyOverrides(cwd, pm, rootPkg) {
  const result = emptyResult2();
  if (pm !== "pnpm") return result;
  const pnpmConfig = isRecord(rootPkg.pnpm) ? rootPkg.pnpm : void 0;
  const packageJsonOverrides = pnpmConfig?.overrides;
  if (isConfiguredValue(packageJsonOverrides)) {
    result.warnings.push(formatOverrideWarning(
      "Root package.json pnpm.overrides field",
      isRecord(packageJsonOverrides) ? Object.keys(packageJsonOverrides) : []
    ));
  }
  const doc = readPnpmWorkspaceDocument(cwd);
  const workspaceOverrides = doc?.get("overrides");
  if (isConfiguredYamlNode(workspaceOverrides)) {
    result.warnings.push(formatOverrideWarning(
      "pnpm-workspace.yaml overrides field",
      configuredYamlKeys(workspaceOverrides)
    ));
  }
  return result;
}
function isMinimumReleaseAgeSatisfied(value) {
  return value !== void 0 && value !== null;
}
function checkPnpmMinimumReleaseAge(cwd, pm) {
  const result = emptyResult2();
  if (pm !== "pnpm") return result;
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return result;
  if (!isMinimumReleaseAgeSatisfied(doc.get("minimumReleaseAge"))) {
    result.fixable.push(`pnpm-workspace.yaml is missing minimumReleaseAge (recommended: ${DEFAULT_MINIMUM_RELEASE_AGE_MINUTES})`);
  }
  return result;
}
function setWorkspaceScalar(cwd, key, value, isSatisfied, successMessage) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return;
  if (!yaml2.isMap(doc.contents)) {
    console.log(chalk6.yellow("  \u26A0 pnpm-workspace.yaml has no top-level map; skipping fix"));
    return;
  }
  if (isSatisfied(doc.get(key))) return;
  doc.set(key, value);
  writeFileSync3(pnpmWorkspacePath(cwd), String(doc), "utf8");
  console.log(chalk6.green(successMessage));
}
function fixPnpmMinimumReleaseAge(cwd) {
  setWorkspaceScalar(
    cwd,
    "minimumReleaseAge",
    DEFAULT_MINIMUM_RELEASE_AGE_MINUTES,
    isMinimumReleaseAgeSatisfied,
    `  \u2714 Fixed: set minimumReleaseAge: ${DEFAULT_MINIMUM_RELEASE_AGE_MINUTES} in pnpm-workspace.yaml`
  );
}
function fixPnpmReleaseAgeExcludes(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return;
  if (!yaml2.isMap(doc.contents)) {
    console.log(chalk6.yellow("  \u26A0 pnpm-workspace.yaml has no top-level map; skipping fix"));
    return;
  }
  let seq = doc.get("minimumReleaseAgeExclude");
  if (!yaml2.isSeq(seq)) {
    seq = new yaml2.YAMLSeq();
    doc.set("minimumReleaseAgeExclude", seq);
  }
  const seqNode = seq;
  const existing = new Set(readSequenceStrings(seqNode));
  let isAdded = false;
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (existing.has(required)) continue;
    seqNode.add(required);
    existing.add(required);
    isAdded = true;
  }
  if (!isAdded) return;
  writeFileSync3(pnpmWorkspacePath(cwd), String(doc), "utf8");
  console.log(chalk6.green("  \u2714 Fixed: added @xylabs/* and @xyo-network/* to minimumReleaseAgeExclude in pnpm-workspace.yaml"));
}

// src/actions/package-lint-specs.ts
import { readdirSync, statSync } from "node:fs";
import PATH5 from "node:path";
function emptyResult3() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function collectSpecFiles(dir, out) {
  for (const entry of readdirSync(dir)) {
    const fullPath = PATH5.join(dir, entry);
    const stats = statSync(fullPath);
    if (stats.isDirectory()) {
      if (entry === "node_modules" || entry === "dist") {
        continue;
      }
      collectSpecFiles(fullPath, out);
      continue;
    }
    if (entry.endsWith(".spec.ts")) {
      out.push(fullPath);
    }
  }
}
function checkSpecFileLayout(cwd, workspaces) {
  const result = emptyResult3();
  for (const { location, name } of workspaces) {
    if (location === ".") {
      continue;
    }
    const srcDir = PATH5.resolve(cwd, location, "src");
    const specFiles = [];
    try {
      collectSpecFiles(srcDir, specFiles);
    } catch {
      continue;
    }
    for (const specPath of specFiles) {
      const relativeToSrc = PATH5.relative(srcDir, specPath).replaceAll("\\", "/");
      if (!relativeToSrc.startsWith("spec/")) {
        const relativeToRepo = PATH5.relative(cwd, specPath).replaceAll("\\", "/");
        result.errors.push(`${name}: spec file must live under src/spec/ \u2014 ${relativeToRepo}`);
      }
    }
  }
  return result;
}

// src/actions/package-lint.ts
function emptyResult4() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function readRootPackageJson2(cwd) {
  const raw = readFileSync6(PATH6.resolve(cwd, "package.json"), "utf8");
  return JSON.parse(raw);
}
function writeRootPackageJson(cwd, pkg) {
  const path = PATH6.resolve(cwd, "package.json");
  writeFileSync4(path, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
}
function isMonorepo(pkg, cwd) {
  const workspaces = pkg.workspaces;
  if (Array.isArray(workspaces) && workspaces.length > 0) return true;
  return readPnpmWorkspaceGlobs(cwd) !== void 0;
}
function checkPackagesFolder(workspaces) {
  const result = emptyResult4();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    if (!location.startsWith("packages/") && !location.startsWith("packages\\")) {
      result.errors.push(`${name} (${location}) is not inside a packages/ folder`);
    }
  }
  return result;
}
function checkRootPrivate(pkg) {
  const result = emptyResult4();
  if (!Boolean(pkg.private)) {
    result.fixable.push("Root package.json must be private to prevent accidental publishing");
  }
  return result;
}
function fixRootPrivate(cwd, pkg) {
  pkg.private = true;
  writeRootPackageJson(cwd, pkg);
  console.log(chalk7.green('  \u2714 Fixed: set "private": true in root package.json'));
}
function checkNoPublishConfigOnPrivate(pkg) {
  const result = emptyResult4();
  if (Boolean(pkg.private) && Boolean(pkg.publishConfig)) {
    result.fixable.push("Root package.json has publishConfig but is private \u2014 publishConfig is unnecessary");
  }
  return result;
}
function fixNoPublishConfigOnPrivate(cwd, pkg) {
  delete pkg.publishConfig;
  writeRootPackageJson(cwd, pkg);
  console.log(chalk7.green("  \u2714 Fixed: removed publishConfig from private root package.json"));
}
function checkNoPackageManagerInWorkspaces(cwd, workspaces) {
  const result = emptyResult4();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH6.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync6(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (Boolean(pkg.packageManager)) {
        result.fixable.push(`${name} (${location}) has a packageManager field \u2014 only the root should define this`);
      }
    } catch {
    }
  }
  return result;
}
function fixNoPackageManagerInWorkspaces(cwd, _pkg, workspaces) {
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH6.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync6(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (Boolean(pkg.packageManager)) {
        delete pkg.packageManager;
        writeFileSync4(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk7.green(`  \u2714 Fixed: removed packageManager from ${location}/package.json`));
      }
    } catch {
    }
  }
}
function checkWorkspacesFieldPlacement(cwd, pm, workspaces) {
  const result = emptyResult4();
  for (const { location, name } of workspaces) {
    if (pm === "pnpm" ? true : location !== ".") {
      const pkgPath = PATH6.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
        if (Boolean(pkg.workspaces)) {
          const label = location === "." ? "Root" : `${name} (${location})`;
          const reason = pm === "pnpm" ? "pnpm uses pnpm-workspace.yaml instead" : "only the root should define workspaces";
          result.fixable.push(`${label} has a workspaces field \u2014 ${reason}`);
        }
      } catch {
      }
    }
  }
  return result;
}
function fixWorkspacesFieldPlacement(cwd, pm, workspaces) {
  for (const { location } of workspaces) {
    if (pm === "pnpm" ? true : location !== ".") {
      const pkgPath = PATH6.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
        if (Boolean(pkg.workspaces)) {
          delete pkg.workspaces;
          writeFileSync4(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
          const label = location === "." ? "root" : location;
          console.log(chalk7.green(`  \u2714 Fixed: removed workspaces from ${label}/package.json`));
        }
      } catch {
      }
    }
  }
}
function checkWorkspaceGlobCoverage(pkg, cwd, pm, workspaces) {
  const result = emptyResult4();
  const globs = pm === "pnpm" ? readPnpmWorkspaceGlobs(cwd) ?? [] : Array.isArray(pkg.workspaces) ? pkg.workspaces : [];
  if (globs.length === 0) {
    const source = pm === "pnpm" ? "pnpm-workspace.yaml" : "root package.json workspaces";
    result.errors.push(`No workspace globs found in ${source}`);
    return result;
  }
  const matchesGlob = makeMatcher(globs);
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    if (!matchesGlob(location)) {
      const source = pm === "pnpm" ? "pnpm-workspace.yaml" : "root package.json workspaces";
      result.errors.push(`${name} (${location}) is not matched by any glob in ${source}`);
    }
  }
  return result;
}
function logResults(label, result, shouldFix) {
  let errors = 0;
  let fixed = 0;
  for (const error of result.errors) {
    console.log(chalk7.red(`  \u2717 ${error}`));
    errors++;
  }
  for (const fixable of result.fixable) {
    if (shouldFix) {
      fixed++;
    } else {
      console.log(chalk7.red(`  \u2717 ${fixable} (fixable)`));
      errors++;
    }
  }
  for (const warning of result.warnings) {
    console.log(chalk7.yellow(`  \u26A0 ${warning}`));
  }
  if (errors === 0 && fixed === 0 && result.warnings.length === 0) {
    console.log(chalk7.green(`  \u2713 ${label}`));
  }
  return { errors, fixed };
}
function runChecks(entries, cwd, pkg, shouldFix) {
  let totalErrors = 0;
  let totalFixed = 0;
  for (const entry of entries) {
    const result = entry.check();
    const log = logResults(entry.label, result, shouldFix);
    if (shouldFix && entry.shouldFix && result.fixable.length > 0) {
      entry.shouldFix(cwd, pkg);
    }
    totalErrors += log.errors;
    totalFixed += log.fixed;
  }
  return { errors: totalErrors, fixed: totalFixed };
}
function logSummary(errors, fixed) {
  if (fixed > 0) {
    console.log(chalk7.green(`
  Fixed ${fixed} issue(s)`));
  }
  if (errors > 0) {
    console.log(chalk7.red(`
  ${errors} error(s) found`));
  } else if (fixed === 0) {
    console.log(chalk7.green("\n  All checks passed"));
  }
}
function packageLintMonorepo(shouldFix = false) {
  const cwd = INIT_CWD();
  let pkg;
  try {
    pkg = readRootPackageJson2(cwd);
  } catch {
    console.error(chalk7.red("Could not read package.json"));
    return 1;
  }
  if (!isMonorepo(pkg, cwd)) {
    console.log(chalk7.gray("Not a monorepo \u2014 skipping repo lint checks"));
    return 0;
  }
  console.log(chalk7.green("Repo Lint"));
  const pm = detectPackageManager();
  const workspaces = getPackageManager().listWorkspaces();
  const internalDepCheck = pm === "pnpm" ? {
    check: () => checkWorkspaceProtocol(cwd, workspaces),
    shouldFix: () => fixWorkspaceProtocol(cwd, workspaces),
    label: "Internal deps/devDeps use workspace: protocol"
  } : {
    check: () => checkInternalDepVersions(cwd, workspaces),
    shouldFix: () => fixInternalDepVersions(cwd, workspaces),
    label: "Internal deps/devDeps use correct version ranges"
  };
  const checks = [
    {
      check: () => checkRootPrivate(pkg),
      shouldFix: fixRootPrivate,
      label: "Root package is private"
    },
    {
      check: () => checkNoPublishConfigOnPrivate(pkg),
      shouldFix: fixNoPublishConfigOnPrivate,
      label: "No publishConfig on private root"
    },
    { check: () => checkPackagesFolder(workspaces), label: "All packages are in packages/ folder" },
    { check: () => checkSpecFileLayout(cwd, workspaces), label: "Spec files live under src/spec/" },
    {
      check: () => checkWorkspacesFieldPlacement(cwd, pm, workspaces),
      shouldFix: () => fixWorkspacesFieldPlacement(cwd, pm, workspaces),
      label: pm === "pnpm" ? "No workspaces field in package.json (use pnpm-workspace.yaml)" : "Workspaces field only in root package.json"
    },
    {
      check: () => checkWorkspaceGlobCoverage(pkg, cwd, pm, workspaces),
      label: "Workspace globs cover all packages"
    },
    {
      check: () => checkNoPackageManagerInWorkspaces(cwd, workspaces),
      shouldFix: () => fixNoPackageManagerInWorkspaces(cwd, pkg, workspaces),
      label: "No packageManager in workspace packages"
    },
    {
      check: () => checkVoltaOnlyInRoot(cwd, workspaces),
      shouldFix: () => fixVoltaOnlyInRoot(cwd, pkg, workspaces),
      label: "Volta only in root package.json"
    },
    {
      check: () => checkEnginesOnlyInNonTerminal(cwd, workspaces),
      shouldFix: () => fixEnginesOnlyInNonTerminal(cwd, pkg, workspaces),
      label: "Engines only in non-terminal (library) packages"
    },
    {
      check: () => checkVersionsIncludeLts(cwd, workspaces),
      label: "Engine/volta versions include latest LTS"
    },
    {
      check: () => checkVersionConsistency(cwd, pkg, workspaces),
      shouldFix: () => fixVersionConsistency(cwd, pkg, writeRootPackageJson, workspaces),
      label: "Consistent versions across packages"
    },
    internalDepCheck,
    {
      check: () => checkInternalPeerVersions(cwd, workspaces),
      shouldFix: () => fixInternalPeerVersions(cwd, workspaces),
      label: "Internal peerDeps use publishable ranges"
    },
    {
      check: () => checkPnpmReleaseAgeExcludes(cwd, pm),
      shouldFix: () => fixPnpmReleaseAgeExcludes(cwd),
      label: "pnpm-workspace.yaml excludes @xylabs/* and @xyo-network/* from minimumReleaseAge"
    },
    {
      check: () => checkPnpmMinimumReleaseAge(cwd, pm),
      shouldFix: () => fixPnpmMinimumReleaseAge(cwd),
      label: "pnpm-workspace.yaml sets minimumReleaseAge"
    },
    ...pm === "pnpm" ? [{
      check: () => checkPnpmDependencyOverrides(cwd, pm, pkg),
      label: "No pnpm dependency overrides configured"
    }] : []
  ];
  const { errors, fixed } = runChecks(checks, cwd, pkg, shouldFix);
  logSummary(errors, fixed);
  if (shouldFix && fixed > 0) shouldRunInstall();
  return errors > 0 ? 1 : 0;
}

// src/actions/packman/convertToBun.ts
import {
  existsSync as existsSync6,
  readFileSync as readFileSync9,
  rmSync,
  writeFileSync as writeFileSync7
} from "node:fs";
import PATH8 from "node:path";
import chalk10 from "chalk";

// src/actions/packman/rewriteScripts.ts
function xyCommand(pm) {
  switch (pm) {
    case "bun": {
      return "bun run xy";
    }
    case "npm": {
      return "npm exec -- xy";
    }
    case "pnpm": {
      return "pnpm xy";
    }
    default: {
      return "yarn xy";
    }
  }
}
function rootRunCommand(pm, script, rest = "") {
  const suffix = rest.trim() ? ` ${rest.trim()}` : "";
  return `${pm} run ${script}${suffix}`;
}
function addCommand(pm) {
  switch (pm) {
    case "bun": {
      return "bun add";
    }
    case "npm": {
      return "npm install";
    }
    case "pnpm": {
      return "pnpm add";
    }
    default: {
      return "yarn add";
    }
  }
}
function removeCommand(pm) {
  switch (pm) {
    case "bun": {
      return "bun remove";
    }
    case "npm": {
      return "npm uninstall";
    }
    case "pnpm": {
      return "pnpm remove";
    }
    default: {
      return "yarn remove";
    }
  }
}
function installCommand(pm) {
  return `${pm} install`;
}
function outdatedCommand(pm) {
  return `${pm} outdated`;
}
function dedupeCommand(pm) {
  return pm === "npm" ? "npm dedupe" : `${pm} dedupe`;
}
function trimRest(rest) {
  if (!(rest != null && rest.length > 0)) return "";
  const normalized = rest.trim();
  return normalized ? ` ${normalized}` : "";
}
function workspaceRunCommand(pm, pkg, script, rest = "") {
  const suffix = trimRest(rest);
  switch (pm) {
    case "bun": {
      return `bun run --filter ${pkg} ${script}${suffix}`;
    }
    case "npm": {
      return `npm run ${script} --workspace=${pkg}${suffix}`;
    }
    case "pnpm": {
      return `pnpm --filter ${pkg} run ${script}${suffix}`;
    }
    default: {
      return `yarn workspace ${pkg} run ${script}${suffix}`;
    }
  }
}
function workspaceRunAllCommand(pm, script, rest = "") {
  const suffix = trimRest(rest);
  switch (pm) {
    case "bun": {
      return `bun run --workspaces --if-present ${script}${suffix}`;
    }
    case "npm": {
      return `npm run ${script} --workspaces --if-present${suffix}`;
    }
    case "pnpm": {
      return `pnpm -r run ${script}${suffix}`;
    }
    default: {
      return `yarn workspaces foreach -Apt run ${script}${suffix}`;
    }
  }
}
function normalizeWorkspaceCommands(script, target) {
  let result = script;
  result = result.replaceAll(/\byarn workspace (\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\byarn workspace (\S+) (package-\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bpnpm --filter (\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bpnpm --filter (\S+) (package-\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bnpm run (\S+) --workspace(?:=|\s+)(\S+)(?:\s+(.*))?$/g, (_, command, pkg, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bnpm --workspace(?:=|\s+)(\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bnpm run (\S+) -w (\S+)(?:\s+(.*))?$/g, (_, command, pkg, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bbun run --filter (\S+) (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bbun --filter (\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\byarn workspaces foreach\s+(?:[^\s]+\s+)*run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  result = result.replaceAll(/\bpnpm -r(?:\s+[^\s]+)* run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  result = result.replaceAll(/\bnpm run (\S+) --workspaces(?: --if-present)?(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  result = result.replaceAll(/\bbun run(?:\s+--[^\s]+)* --workspaces(?: --if-present)? (\S+)(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  return result;
}
function normalizeRootRunCommands(script, target) {
  let result = script;
  result = result.replaceAll(/\byarn run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  result = result.replaceAll(/\bpnpm run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  result = result.replaceAll(/\bnpm run (\S+)(?!\s+(?:--workspace(?:=|\s)|-w\s|--workspaces)\b)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  result = result.replaceAll(/\bbun run (\S+)(?!\s+(?:--filter|--workspaces)\b)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  return result;
}
function normalizeXyCommands(script, target) {
  return script.replaceAll(/\byarn xy\b/g, () => xyCommand(target)).replaceAll(/\bpnpm xy\b/g, () => xyCommand(target)).replaceAll(/\bnpm exec(?: --)? xy\b/g, () => xyCommand(target)).replaceAll(/\bnpx(?: --no-install)? xy\b/g, () => xyCommand(target)).replaceAll(/\bbun run xy\b/g, () => xyCommand(target)).replaceAll(/\bbun x xy\b/g, () => xyCommand(target));
}
function rewriteScript(script, target) {
  let result = normalizeWorkspaceCommands(script, target);
  result = normalizeRootRunCommands(result, target);
  result = normalizeXyCommands(result, target);
  result = result.replaceAll(/\byarn add\b/g, () => addCommand(target));
  result = result.replaceAll(/\bpnpm add\b/g, () => addCommand(target));
  result = result.replaceAll(/\bbun add\b/g, () => addCommand(target));
  result = result.replaceAll(/\byarn remove\b/g, () => removeCommand(target));
  result = result.replaceAll(/\bpnpm remove\b/g, () => removeCommand(target));
  result = result.replaceAll(/\bbun remove\b/g, () => removeCommand(target));
  result = result.replaceAll(/\bnpm uninstall\b/g, () => removeCommand(target));
  result = result.replaceAll(/\byarn install\b/g, () => installCommand(target));
  result = result.replaceAll(/\bpnpm install\b/g, () => installCommand(target));
  result = result.replaceAll(/\bbun install\b/g, () => installCommand(target));
  result = result.replaceAll(/\bnpm install\b/g, () => installCommand(target));
  result = result.replaceAll(/\byarn dedupe\b/g, () => dedupeCommand(target));
  result = result.replaceAll(/\bpnpm dedupe\b/g, () => dedupeCommand(target));
  result = result.replaceAll(/\bnpm dedupe\b/g, () => dedupeCommand(target));
  result = result.replaceAll(/\byarn outdated\b/g, () => outdatedCommand(target));
  result = result.replaceAll(/\bpnpm outdated\b/g, () => outdatedCommand(target));
  result = result.replaceAll(/\bbun outdated\b/g, () => outdatedCommand(target));
  result = result.replaceAll(/\bnpm outdated\b/g, () => outdatedCommand(target));
  return result;
}
function rewriteScriptsInPackageJson(pkg, target) {
  const scripts = pkg.scripts;
  if (!scripts) return pkg;
  const rewritten = {};
  for (const [name, script] of Object.entries(scripts)) {
    rewritten[name] = rewriteScript(script, target);
  }
  return { ...pkg, scripts: rewritten };
}

// src/actions/packman/rewriteSourceImports.ts
import {
  existsSync as existsSync4,
  readFileSync as readFileSync7,
  writeFileSync as writeFileSync5
} from "node:fs";
import chalk8 from "chalk";
import { globSync as globSync2 } from "glob";
var SWAPS = [
  ["@xylabs/toolchain", "@xylabs/toolchain"],
  ["@xylabs/toolchain", "@xylabs/toolchain"]
];
var SOURCE_GLOBS = [
  "**/*.ts",
  "**/*.tsx",
  "**/*.mts",
  "**/*.cts",
  "**/*.js",
  "**/*.mjs"
];
var IGNORE_PATTERNS = [
  "**/node_modules/**",
  "**/dist/**",
  "**/build/**",
  "**/.yarn/**"
];
function rewriteSourceImports(cwd) {
  const files = globSync2(SOURCE_GLOBS, {
    cwd,
    absolute: true,
    ignore: IGNORE_PATTERNS
  });
  let count = 0;
  for (const file of files) {
    if (!existsSync4(file)) continue;
    const original = readFileSync7(file, "utf8");
    let content = original;
    for (const [from, to] of SWAPS) {
      content = content.replaceAll(from, () => to);
    }
    if (content !== original) {
      writeFileSync5(file, content, "utf8");
      count++;
    }
  }
  if (count > 0) {
    console.log(chalk8.green(`  Rewrote toolchain imports in ${count} source file(s)`));
  }
}

// src/actions/packman/swapTsScriptsDependency.ts
import {
  existsSync as existsSync5,
  readFileSync as readFileSync8,
  writeFileSync as writeFileSync6
} from "node:fs";
import PATH7 from "node:path";
import chalk9 from "chalk";
var TARGET_PACKAGE = "@xylabs/toolchain";
var managedPackages = [
  "@xylabs/toolchain",
  "@xylabs/ts-scripts-pnpm",
  "@xylabs/ts-scripts-yarn3"
];
function shouldSetToolchainInPackageJson(pkgPath, range) {
  if (!existsSync5(pkgPath)) return false;
  const raw = readFileSync8(pkgPath, "utf8");
  const pkg = JSON.parse(raw);
  let isChanged = false;
  let foundInDepsField;
  for (const depField of ["dependencies", "devDependencies"]) {
    const deps = pkg[depField];
    if (!deps) continue;
    let isRemoved = false;
    for (const name of managedPackages) {
      if (Object.hasOwn(deps, name)) {
        delete deps[name];
        isRemoved = true;
        isChanged = true;
      }
    }
    if (isRemoved) {
      foundInDepsField = depField;
      deps[TARGET_PACKAGE] = range;
    }
  }
  if (foundInDepsField) {
    const targetDeps = pkg[foundInDepsField];
    if (targetDeps[TARGET_PACKAGE] !== range) {
      targetDeps[TARGET_PACKAGE] = range;
      isChanged = true;
    }
  } else {
    const devDeps = pkg.devDependencies ?? {};
    if (devDeps[TARGET_PACKAGE] !== range) {
      devDeps[TARGET_PACKAGE] = range;
      pkg.devDependencies = devDeps;
      isChanged = true;
    }
  }
  if (isChanged) {
    writeFileSync6(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
  }
  return isChanged;
}
function swapTsScriptsDependency(cwd, workspacePackageJsonPaths) {
  const range = bundledToolchainRange();
  let count = 0;
  if (shouldSetToolchainInPackageJson(PATH7.join(cwd, "package.json"), range)) {
    count++;
  }
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH7.resolve(cwd, pkgPath, "package.json");
    if (shouldSetToolchainInPackageJson(fullPath, range)) {
      count++;
    }
  }
  if (count > 0) {
    console.log(chalk9.green(`  Set toolchain dependency to ${TARGET_PACKAGE}@${range} in ${count} package(s)`));
  }
}

// src/actions/packman/convertToBun.ts
var BUN_VERSION = "1.3.3";
function updateRootPackageJson(cwd) {
  const pkgPath = PATH8.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync9(pkgPath, "utf8"));
  pkg.packageManager = `bun@${BUN_VERSION}`;
  const updated = rewriteScriptsInPackageJson(pkg, "bun");
  writeFileSync7(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk10.green("  Updated root package.json"));
}
function deleteArtifacts(cwd) {
  for (const relativePath of ["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".yarnrc.yml"]) {
    const fullPath = PATH8.join(cwd, relativePath);
    if (existsSync6(fullPath)) {
      rmSync(fullPath, { force: true, recursive: true });
      console.log(chalk10.gray(`  Deleted ${relativePath}`));
    }
  }
  const yarnDir = PATH8.join(cwd, ".yarn");
  if (existsSync6(yarnDir)) {
    rmSync(yarnDir, { force: true, recursive: true });
    console.log(chalk10.gray("  Deleted .yarn/"));
  }
}
function convertToBun(cwd, workspacePackageJsonPaths) {
  console.log(chalk10.blue("\nConverting to bun...\n"));
  updateRootPackageJson(cwd);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH8.resolve(cwd, pkgPath, "package.json");
    if (!existsSync6(fullPath)) continue;
    const pkg = JSON.parse(readFileSync9(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "bun");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync7(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk10.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deleteArtifacts(cwd);
  console.log(chalk10.blue("\nRunning bun install..."));
  const install = spawnPackageManagerSync("bun", ["install"], {
    context: { cwd, operation: "Convert repo to bun and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk10.red("bun install failed"));
    return 1;
  }
  console.log(chalk10.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convertToNpm.ts
import {
  existsSync as existsSync7,
  readFileSync as readFileSync10,
  rmSync as rmSync2,
  writeFileSync as writeFileSync8
} from "node:fs";
import PATH9 from "node:path";
import chalk11 from "chalk";
var NPM_VERSION = "10.9.4";
function readWorkspacePatterns2(cwd) {
  const pkgPath = PATH9.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync10(pkgPath, "utf8"));
  return pkg.workspaces ?? [];
}
function updateRootPackageJson2(cwd) {
  const pkgPath = PATH9.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync10(pkgPath, "utf8"));
  pkg.packageManager = `npm@${NPM_VERSION}`;
  const updated = rewriteScriptsInPackageJson(pkg, "npm");
  writeFileSync8(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk11.green("  Updated root package.json"));
}
function deleteArtifacts2(cwd) {
  for (const relativePath of ["bun.lock", "bun.lockb", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".yarnrc.yml"]) {
    const fullPath = PATH9.join(cwd, relativePath);
    if (existsSync7(fullPath)) {
      rmSync2(fullPath, { force: true, recursive: true });
      console.log(chalk11.gray(`  Deleted ${relativePath}`));
    }
  }
  const yarnDir = PATH9.join(cwd, ".yarn");
  if (existsSync7(yarnDir)) {
    rmSync2(yarnDir, { force: true, recursive: true });
    console.log(chalk11.gray("  Deleted .yarn/"));
  }
}
function convertToNpm(cwd, workspacePackageJsonPaths) {
  console.log(chalk11.blue("\nConverting to npm...\n"));
  const workspacePatterns = readWorkspacePatterns2(cwd);
  if (workspacePatterns.length === 0) {
    console.warn(chalk11.yellow("  No root package.json workspaces found; npm monorepo support relies on the workspaces field"));
  }
  updateRootPackageJson2(cwd);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH9.resolve(cwd, pkgPath, "package.json");
    if (!existsSync7(fullPath)) continue;
    const pkg = JSON.parse(readFileSync10(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "npm");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync8(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk11.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deleteArtifacts2(cwd);
  console.log(chalk11.blue("\nRunning npm install..."));
  const install = spawnPackageManagerSync("npm", ["install"], {
    context: { cwd, operation: "Convert repo to npm and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk11.red("npm install failed"));
    return 1;
  }
  console.log(chalk11.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convertToPnpm.ts
import {
  existsSync as existsSync8,
  mkdirSync,
  readFileSync as readFileSync11,
  rmSync as rmSync3,
  writeFileSync as writeFileSync9
} from "node:fs";
import PATH10 from "node:path";
import chalk12 from "chalk";
function createPnpmWorkspaceYaml(cwd, workspacePatterns) {
  const lines = ["packages:"];
  for (const pattern of workspacePatterns) {
    lines.push(`  - '${pattern}'`);
  }
  writeFileSync9(PATH10.join(cwd, "pnpm-workspace.yaml"), lines.join("\n") + "\n", "utf8");
  console.log(chalk12.green("  Created pnpm-workspace.yaml"));
}
function readPnpmWorkspacePatterns2(cwd) {
  const wsPath = PATH10.join(cwd, "pnpm-workspace.yaml");
  if (!existsSync8(wsPath)) return [];
  const content = readFileSync11(wsPath, "utf8");
  const patterns = [];
  const lines = content.split("\n");
  let isInPackages = false;
  for (const line of lines) {
    if (line.trim() === "packages:") {
      isInPackages = true;
      continue;
    }
    if (isInPackages && /^\s+-\s+/.test(line)) {
      const pattern = line.replace(/^\s+-\s+/, "").replaceAll(/['"]/g, "").trim();
      if (pattern) patterns.push(pattern);
    } else if (isInPackages && !/^\s/.test(line) && line.trim()) {
      isInPackages = false;
    }
  }
  return patterns;
}
function updateRootPackageJson3(cwd, pnpmVersion) {
  const pkgPath = PATH10.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync11(pkgPath, "utf8"));
  const workspacePatterns = pkg.workspaces ?? readPnpmWorkspacePatterns2(cwd);
  delete pkg.workspaces;
  pkg.packageManager = `pnpm@${pnpmVersion}`;
  const updated = rewriteScriptsInPackageJson(pkg, "pnpm");
  writeFileSync9(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk12.green("  Updated root package.json"));
  return workspacePatterns;
}
function updateGitignore(cwd) {
  const gitignorePath = PATH10.join(cwd, ".gitignore");
  if (!existsSync8(gitignorePath)) return;
  let content = readFileSync11(gitignorePath, "utf8");
  const yarnLines = [
    ".pnp.*",
    ".pnp",
    ".yarn/*",
    "!.yarn/patches",
    "!.yarn/plugins",
    "!.yarn/releases",
    "!.yarn/sdks",
    "!.yarn/versions"
  ];
  for (const line of yarnLines) {
    content = content.replaceAll(new RegExp(String.raw`^${line.replaceAll(".", String.raw`\.`).replaceAll("*", String.raw`\*`).replaceAll("!", String.raw`\!`)}\s*$`, "gm"), "");
  }
  content = content.replaceAll(/\n{3,}/g, "\n\n");
  writeFileSync9(gitignorePath, content, "utf8");
  console.log(chalk12.green("  Updated .gitignore"));
}
function deleteYarnArtifacts(cwd) {
  const yarnLock = PATH10.join(cwd, "yarn.lock");
  const yarnrc = PATH10.join(cwd, ".yarnrc.yml");
  const yarnDir = PATH10.join(cwd, ".yarn");
  if (existsSync8(yarnLock)) {
    rmSync3(yarnLock);
    console.log(chalk12.gray("  Deleted yarn.lock"));
  }
  if (existsSync8(yarnrc)) {
    rmSync3(yarnrc);
    console.log(chalk12.gray("  Deleted .yarnrc.yml"));
  }
  if (existsSync8(yarnDir)) {
    rmSync3(yarnDir, { force: true, recursive: true });
    console.log(chalk12.gray("  Deleted .yarn/"));
  }
}
function createNpmrc(cwd) {
  const npmrcPath = PATH10.join(cwd, ".npmrc");
  if (existsSync8(npmrcPath)) return;
  mkdirSync(PATH10.dirname(npmrcPath), { recursive: true });
  writeFileSync9(npmrcPath, "", "utf8");
  console.log(chalk12.green("  Created .npmrc"));
}
async function resolvePnpmVersion() {
  const latest = await fetchLatestPackageVersion("pnpm");
  if (latest != null && latest.length > 0) return latest;
  console.warn(chalk12.yellow(`  Unable to reach npm for pnpm latest; falling back to bundled pnpm version ${latestVersions.pnpm}`));
  return latestVersions.pnpm;
}
async function convertToPnpm(cwd, workspacePackageJsonPaths) {
  console.log(chalk12.blue("\nConverting to pnpm...\n"));
  const pnpmVersion = await resolvePnpmVersion();
  const workspacePatterns = updateRootPackageJson3(cwd, pnpmVersion);
  createPnpmWorkspaceYaml(cwd, workspacePatterns);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH10.resolve(cwd, pkgPath, "package.json");
    if (!existsSync8(fullPath)) continue;
    const pkg = JSON.parse(readFileSync11(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "pnpm");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync9(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk12.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  updateGitignore(cwd);
  createNpmrc(cwd);
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deleteYarnArtifacts(cwd);
  console.log(chalk12.blue("\nRunning pnpm install..."));
  const install = spawnPackageManagerSync("pnpm", ["install"], {
    context: { cwd, operation: "Convert repo to pnpm and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk12.red("pnpm install failed"));
    return 1;
  }
  console.log(chalk12.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convertToYarn.ts
import {
  existsSync as existsSync9,
  readFileSync as readFileSync12,
  rmSync as rmSync4,
  writeFileSync as writeFileSync10
} from "node:fs";
import PATH11 from "node:path";
import chalk13 from "chalk";
var YARN_VERSION = "4.13.0";
var YARNRC_TEMPLATE = `compressionLevel: mixed

enableGlobalCache: true

enableInlineBuilds: true

nmHoistingLimits: none

nodeLinker: node-modules
`;
var YARN_GITIGNORE_ENTRIES = `
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
`;
function readPnpmWorkspacePatterns3(cwd) {
  const wsPath = PATH11.join(cwd, "pnpm-workspace.yaml");
  if (!existsSync9(wsPath)) return [];
  const content = readFileSync12(wsPath, "utf8");
  const patterns = [];
  const lines = content.split("\n");
  let isInPackages = false;
  for (const line of lines) {
    if (line.trim() === "packages:") {
      isInPackages = true;
      continue;
    }
    if (isInPackages && /^\s+-\s+/.test(line)) {
      const pattern = line.replace(/^\s+-\s+/, "").replaceAll(/['"]/g, "").trim();
      if (pattern) patterns.push(pattern);
    } else if (isInPackages && !/^\s/.test(line) && line.trim()) {
      isInPackages = false;
    }
  }
  return patterns;
}
function updateRootPackageJson4(cwd, workspacePatterns) {
  const pkgPath = PATH11.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync12(pkgPath, "utf8"));
  pkg.workspaces = workspacePatterns;
  pkg.packageManager = `yarn@${YARN_VERSION}`;
  const updated = rewriteScriptsInPackageJson(pkg, "yarn");
  writeFileSync10(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk13.green("  Updated root package.json"));
}
function updateGitignore2(cwd) {
  const gitignorePath = PATH11.join(cwd, ".gitignore");
  let content = existsSync9(gitignorePath) ? readFileSync12(gitignorePath, "utf8") : "";
  if (!content.includes(".yarn/*")) {
    content = content.trimEnd() + "\n" + YARN_GITIGNORE_ENTRIES;
  }
  writeFileSync10(gitignorePath, content, "utf8");
  console.log(chalk13.green("  Updated .gitignore"));
}
function deletePnpmArtifacts(cwd) {
  const lockfile = PATH11.join(cwd, "pnpm-lock.yaml");
  const workspaceYaml = PATH11.join(cwd, "pnpm-workspace.yaml");
  const npmrc = PATH11.join(cwd, ".npmrc");
  if (existsSync9(lockfile)) {
    rmSync4(lockfile);
    console.log(chalk13.gray("  Deleted pnpm-lock.yaml"));
  }
  if (existsSync9(workspaceYaml)) {
    rmSync4(workspaceYaml);
    console.log(chalk13.gray("  Deleted pnpm-workspace.yaml"));
  }
  if (existsSync9(npmrc)) {
    const content = readFileSync12(npmrc, "utf8");
    if (content.trim() === "" || content.includes("shamefully-hoist") || content.includes("node-linker")) {
      rmSync4(npmrc);
      console.log(chalk13.gray("  Deleted .npmrc"));
    }
  }
}
function createYarnrc(cwd) {
  const yarnrcPath = PATH11.join(cwd, ".yarnrc.yml");
  if (existsSync9(yarnrcPath)) return;
  writeFileSync10(yarnrcPath, YARNRC_TEMPLATE, "utf8");
  console.log(chalk13.green("  Created .yarnrc.yml"));
}
function readWorkspacePatternsFromPackageJson2(cwd) {
  const pkgPath = PATH11.join(cwd, "package.json");
  if (!existsSync9(pkgPath)) return [];
  const pkg = JSON.parse(readFileSync12(pkgPath, "utf8"));
  return pkg.workspaces ?? [];
}
function convertToYarn(cwd, workspacePackageJsonPaths) {
  console.log(chalk13.blue("\nConverting to yarn...\n"));
  const workspacePatterns = readPnpmWorkspacePatterns3(cwd);
  if (workspacePatterns.length === 0) {
    const fromPkg = readWorkspacePatternsFromPackageJson2(cwd);
    if (fromPkg.length > 0) {
      workspacePatterns.push(...fromPkg);
    } else {
      console.warn(chalk13.yellow("  No workspace patterns found"));
    }
  }
  updateRootPackageJson4(cwd, workspacePatterns);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH11.resolve(cwd, pkgPath, "package.json");
    if (!existsSync9(fullPath)) continue;
    const pkg = JSON.parse(readFileSync12(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "yarn");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync10(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk13.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  updateGitignore2(cwd);
  createYarnrc(cwd);
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deletePnpmArtifacts(cwd);
  console.log(chalk13.blue("\nRunning yarn install..."));
  const install = spawnPackageManagerSync("yarn", ["install"], {
    context: { cwd, operation: "Convert repo to yarn and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk13.red("yarn install failed"));
    return 1;
  }
  console.log(chalk13.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convert.ts
var TARGET_PMS = ["bun", "npm", "pnpm", "yarn"];
function detectCurrentPM(cwd) {
  const packageManager = detectPackageManagerFromPackageJson(cwd);
  const target = TARGET_PMS.find((pm) => pm === packageManager);
  if (target) {
    return target;
  }
  if (existsSync10(PATH12.join(cwd, "pnpm-lock.yaml")) || existsSync10(PATH12.join(cwd, "pnpm-workspace.yaml"))) {
    return "pnpm";
  }
  if (existsSync10(PATH12.join(cwd, "bun.lock")) || existsSync10(PATH12.join(cwd, "bun.lockb"))) {
    return "bun";
  }
  if (existsSync10(PATH12.join(cwd, "yarn.lock")) || existsSync10(PATH12.join(cwd, ".yarnrc.yml"))) {
    return "yarn";
  }
  if (existsSync10(PATH12.join(cwd, "package-lock.json")) || existsSync10(PATH12.join(cwd, "npm-shrinkwrap.json"))) {
    return "npm";
  }
  return "unknown";
}
function findWorkspacePackagePaths(cwd) {
  const patterns = readWorkspacePatterns(cwd);
  const dirs = [];
  for (const pattern of patterns) {
    const resolved = resolveWorkspaceGlob(cwd, pattern);
    dirs.push(...resolved);
  }
  return dirs;
}
function resolveWorkspaceGlob(cwd, pattern) {
  const parts = pattern.split("/");
  return walkGlob(cwd, parts, "");
}
function walkGlob(basePath, parts, currentPath) {
  let remaining = parts;
  let path = currentPath;
  while (remaining.length > 0) {
    const [segment, ...rest2] = remaining;
    if (segment === "*" || segment === "**") {
      break;
    }
    path = path ? `${path}/${segment}` : segment;
    remaining = rest2;
  }
  if (remaining.length === 0) {
    const fullPath = PATH12.join(basePath, path);
    if (existsSync10(PATH12.join(fullPath, "package.json"))) {
      return [path];
    }
    return [];
  }
  const [part, ...rest] = remaining;
  const dirPath = PATH12.join(basePath, path);
  if (!existsSync10(dirPath) || !statSync2(dirPath).isDirectory()) {
    return [];
  }
  if (part === "*" || part === "**") {
    const entries = readdirSync2(dirPath, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules" && e.name !== "dist");
    const results = [];
    if (part === "**") {
      results.push(...walkGlob(basePath, rest, path));
    }
    for (const entry of entries) {
      const subPath = path ? `${path}/${entry.name}` : entry.name;
      if (part === "**") {
        results.push(
          ...walkGlob(basePath, rest, subPath),
          ...walkGlob(basePath, remaining, subPath)
        );
      } else {
        results.push(...walkGlob(basePath, rest, subPath));
      }
    }
    return results;
  }
  return [];
}
async function runTargetConversion(target, cwd, workspacePaths) {
  switch (target) {
    case "pnpm": {
      return await convertToPnpm(cwd, workspacePaths);
    }
    case "yarn": {
      return convertToYarn(cwd, workspacePaths);
    }
    case "npm": {
      return convertToNpm(cwd, workspacePaths);
    }
    case "bun": {
      return convertToBun(cwd, workspacePaths);
    }
  }
}
async function convert({ target, verbose }) {
  const validTargets = ["bun", "npm", "pnpm", "yarn"];
  if (!validTargets.includes(target)) {
    console.error(chalk14.red(`Invalid target "${target}". Must be one of: ${validTargets.join(", ")}`));
    return 1;
  }
  const cwd = process.cwd();
  const currentPM = detectCurrentPM(cwd);
  if (verbose ?? false) {
    console.log(chalk14.gray(`Current package manager: ${currentPM}`));
    console.log(chalk14.gray(`Target package manager: ${target}`));
  }
  if (currentPM === target) {
    console.log(chalk14.yellow(`Already using ${target}. Re-applying conversion to fix any incomplete steps...`));
  }
  if (currentPM === "unknown") {
    console.error(chalk14.red("Could not detect current package manager. No packageManager field or known lockfile found."));
    return 1;
  }
  const workspacePaths = findWorkspacePackagePaths(cwd);
  if (verbose ?? false) {
    console.log(chalk14.gray(`Found ${workspacePaths.length} workspace packages`));
  }
  const result = await runTargetConversion(target, cwd, workspacePaths);
  if (result !== 0) return result;
  console.log(chalk14.green("\nRunning repo lint --fix..."));
  packageLintMonorepo(true);
  return result;
}

// src/actions/packman/clean.ts
function shouldRemoveNodeModules(dir, isVerbose) {
  const nmPath = PATH13.join(dir, "node_modules");
  if (existsSync11(nmPath)) {
    if (isVerbose ?? false) console.log(chalk15.gray(`Removing ${nmPath}`));
    rmSync5(nmPath, { force: true, recursive: true });
    return true;
  }
  return false;
}
function cleanLockFiles(cwd, pm) {
  switch (pm) {
    case "yarn": {
      const lockPath = PATH13.join(cwd, "yarn.lock");
      if (existsSync11(lockPath)) {
        writeFileSync11(lockPath, "");
        console.log(chalk15.green("Truncated yarn.lock"));
      }
      break;
    }
    case "npm": {
      const lockPath = PATH13.join(cwd, "package-lock.json");
      if (existsSync11(lockPath)) {
        rmSync5(lockPath);
        console.log(chalk15.green("Deleted package-lock.json"));
      }
      break;
    }
    case "bun": {
      for (const lockfile of ["bun.lock", "bun.lockb"]) {
        const lockPath = PATH13.join(cwd, lockfile);
        if (existsSync11(lockPath)) {
          rmSync5(lockPath);
          console.log(chalk15.green(`Deleted ${lockfile}`));
        }
      }
      break;
    }
    case "pnpm": {
      const lockPath = PATH13.join(cwd, "pnpm-lock.yaml");
      if (existsSync11(lockPath)) {
        rmSync5(lockPath);
        console.log(chalk15.green("Deleted pnpm-lock.yaml"));
      }
      break;
    }
  }
}
function packmanClean({ isVerbose }) {
  const cwd = process.cwd();
  const pm = detectCurrentPM(cwd);
  if (pm === "unknown") {
    console.error(chalk15.red("Could not detect current package manager. No packageManager field or known lockfile found."));
    return 1;
  }
  console.log(chalk15.blue(`Detected package manager: ${pm}`));
  let removedCount = 0;
  if (shouldRemoveNodeModules(cwd, isVerbose)) removedCount++;
  const workspacePaths = findWorkspacePackagePaths(cwd);
  for (const wsPath of workspacePaths) {
    if (shouldRemoveNodeModules(PATH13.join(cwd, wsPath), isVerbose)) removedCount++;
  }
  console.log(chalk15.green(`Removed ${removedCount} node_modules folder${removedCount === 1 ? "" : "s"}`));
  cleanLockFiles(cwd, pm);
  console.log(chalk15.green("Ready for a clean install"));
  return 0;
}

// src/actions/packman/lint.ts
import {
  existsSync as existsSync12,
  readFileSync as readFileSync13,
  writeFileSync as writeFileSync12
} from "node:fs";
import PATH14 from "node:path";
import chalk16 from "chalk";
var DEFAULT_RELEASE_AGE_EXCLUDES = ["'@xylabs/*'", "'@xyo-network/*'"];
var DEFAULT_VERIFY_DEPS_BEFORE_RUN = "warn";
function resolvePackmanConfig(cfg) {
  return {
    minimumReleaseAge: cfg?.minimumReleaseAge ?? DEFAULT_MINIMUM_RELEASE_AGE_MINUTES,
    minimumReleaseAgeExclude: cfg?.minimumReleaseAgeExclude ?? DEFAULT_RELEASE_AGE_EXCLUDES
  };
}
function readPnpmWorkspaceYaml(cwd) {
  const wsPath = PATH14.join(cwd, "pnpm-workspace.yaml");
  if (!existsSync12(wsPath)) return void 0;
  return readFileSync13(wsPath, "utf8");
}
function writePnpmWorkspaceYaml(cwd, content) {
  writeFileSync12(PATH14.join(cwd, "pnpm-workspace.yaml"), content, "utf8");
}
function parseYamlListSection(content, sectionName) {
  const items = [];
  let isInSection = false;
  for (const line of content.split("\n")) {
    const sectionPattern = new RegExp(String.raw`^${sectionName}\s*:`);
    if (sectionPattern.test(line)) {
      isInSection = true;
      continue;
    }
    if (isInSection) {
      const match = /^\s+-\s+(.+)$/.exec(line);
      if (match) {
        items.push(match[1].trim());
      } else if (line.trim() && !/^\s/.test(line)) {
        break;
      }
    }
  }
  return items;
}
function shouldCheckEnableScripts(cwd, isVerbose, isSilent) {
  const yarnrcPath = PATH14.join(cwd, ".yarnrc.yml");
  if (!existsSync12(yarnrcPath)) {
    if (isVerbose ?? false) console.log(chalk16.gray("  No .yarnrc.yml found, skipping enableScripts check"));
    return true;
  }
  const content = readFileSync13(yarnrcPath, "utf8");
  for (const line of content.split("\n")) {
    const trimmed = line.trim();
    if (/^enableScripts\s*:/.test(trimmed)) {
      const value = trimmed.replace(/^enableScripts\s*:\s*/, "").trim();
      if (value === "false") {
        if (isVerbose ?? false) console.log(chalk16.green("  enableScripts is correctly set to false"));
        return true;
      }
      if (!(isSilent ?? false)) console.log(chalk16.red("  enableScripts is set to", value, "(expected false)"));
      return false;
    }
  }
  if (!(isSilent ?? false)) console.log(chalk16.red("  enableScripts is not set in .yarnrc.yml (expected false)"));
  return false;
}
function shouldFixEnableScripts(cwd) {
  const yarnrcPath = PATH14.join(cwd, ".yarnrc.yml");
  if (!existsSync12(yarnrcPath)) return true;
  const content = readFileSync13(yarnrcPath, "utf8");
  const lines = content.split("\n");
  let isFound = false;
  const newLines = lines.map((line) => {
    if (/^\s*enableScripts\s*:/.test(line)) {
      isFound = true;
      return "enableScripts: false";
    }
    return line;
  });
  if (!isFound) {
    let isInserted = false;
    for (let i = 0; i < newLines.length; i++) {
      const trimmed = newLines[i].trim();
      if (trimmed && !trimmed.startsWith("#") && trimmed > "enableScripts:") {
        newLines.splice(i, 0, "enableScripts: false", "");
        isInserted = true;
        break;
      }
    }
    if (!isInserted) {
      const lastLine = newLines.at(-1);
      if (lastLine === "") {
        newLines.splice(-1, 0, "enableScripts: false", "");
      } else {
        newLines.push("", "enableScripts: false");
      }
    }
  }
  writeFileSync12(yarnrcPath, newLines.join("\n"), "utf8");
  console.log(chalk16.green("  Fixed: enableScripts set to false"));
  return true;
}
function shouldCheckMinimumReleaseAge(cwd, config, isVerbose, isSilent) {
  const content = readPnpmWorkspaceYaml(cwd);
  if (!(content != null && content.length > 0)) {
    if (!(isSilent ?? false)) console.log(chalk16.red("  No pnpm-workspace.yaml found"));
    return false;
  }
  const { minimumReleaseAge } = config;
  for (const line of content.split("\n")) {
    const match = /^minimumReleaseAge\s*:\s*(\d+)/.exec(line.trim());
    if (match) {
      const value = Number(match[1]);
      if (value >= minimumReleaseAge) {
        if (isVerbose ?? false) console.log(chalk16.green(`  minimumReleaseAge is ${value} (>= ${minimumReleaseAge})`));
        return true;
      }
      if (!(isSilent ?? false)) console.log(chalk16.red(`  minimumReleaseAge is ${value} (expected >= ${minimumReleaseAge})`));
      return false;
    }
  }
  if (!(isSilent ?? false)) console.log(chalk16.red(`  minimumReleaseAge is not set in pnpm-workspace.yaml (expected >= ${minimumReleaseAge})`));
  return false;
}
function shouldFixMinimumReleaseAge(cwd, config) {
  const content = readPnpmWorkspaceYaml(cwd);
  if (!(content != null && content.length > 0)) return false;
  const { minimumReleaseAge } = config;
  const lines = content.split("\n");
  let isFound = false;
  const newLines = lines.map((line) => {
    if (/^minimumReleaseAge\s*:/.test(line)) {
      isFound = true;
      return `minimumReleaseAge: ${minimumReleaseAge}`;
    }
    return line;
  });
  if (!isFound) {
    const lastLine = newLines.at(-1);
    if (lastLine === "") {
      newLines.pop();
      newLines.push(`minimumReleaseAge: ${minimumReleaseAge}`, "");
    } else {
      newLines.push(`minimumReleaseAge: ${minimumReleaseAge}`);
    }
  }
  writePnpmWorkspaceYaml(cwd, newLines.join("\n"));
  console.log(chalk16.green(`  Fixed: minimumReleaseAge set to ${minimumReleaseAge}`));
  return true;
}
function shouldCheckMinimumReleaseAgeExclude(cwd, config, isVerbose, isSilent) {
  const content = readPnpmWorkspaceYaml(cwd);
  if (!(content != null && content.length > 0)) {
    if (!(isSilent ?? false)) console.log(chalk16.red("  No pnpm-workspace.yaml found"));
    return false;
  }
  const excludes = parseYamlListSection(content, "minimumReleaseAgeExclude");
  const missing = config.minimumReleaseAgeExclude.filter((scope) => !excludes.includes(scope));
  if (missing.length === 0) {
    if (isVerbose ?? false) console.log(chalk16.green("  minimumReleaseAgeExclude includes all required scopes"));
    return true;
  }
  if (!(isSilent ?? false)) console.log(chalk16.red(`  minimumReleaseAgeExclude is missing: ${missing.join(", ")}`));
  return false;
}
function shouldFixMinimumReleaseAgeExclude(cwd, config) {
  const content = readPnpmWorkspaceYaml(cwd);
  if (!(content != null && content.length > 0)) return false;
  const existingExcludes = parseYamlListSection(content, "minimumReleaseAgeExclude");
  const toAdd = config.minimumReleaseAgeExclude.filter((scope) => !existingExcludes.includes(scope));
  if (toAdd.length === 0) return true;
  const lines = content.split("\n");
  const sectionIndex = lines.findIndex((line) => /^minimumReleaseAgeExclude\s*:/.test(line));
  if (sectionIndex === -1) {
    const newSection = ["minimumReleaseAgeExclude:", ...config.minimumReleaseAgeExclude.map((s) => `  - ${s}`)];
    const lastLine = lines.at(-1);
    if (lastLine === "") {
      lines.splice(-1, 0, ...newSection);
    } else {
      lines.push(...newSection);
    }
  } else {
    let insertAt = sectionIndex + 1;
    while (insertAt < lines.length && /^\s+-/.test(lines[insertAt])) {
      insertAt++;
    }
    for (const scope of toAdd) {
      lines.splice(insertAt, 0, `  - ${scope}`);
      insertAt++;
    }
  }
  writePnpmWorkspaceYaml(cwd, lines.join("\n"));
  console.log(chalk16.green(`  Fixed: added ${toAdd.join(", ")} to minimumReleaseAgeExclude`));
  return true;
}
function hasPnpmWorkspaceSetting(content, key) {
  if (!(content != null && content.length > 0)) return false;
  const keyPattern = new RegExp(String.raw`^${key}\s*:`, "m");
  return keyPattern.test(content);
}
function shouldCheckVerifyDepsBeforeRun(cwd, isVerbose, isSilent) {
  const content = readPnpmWorkspaceYaml(cwd);
  if (!(content != null && content.length > 0)) {
    if (!(isSilent ?? false)) console.log(chalk16.red("  No pnpm-workspace.yaml found"));
    return false;
  }
  if (hasPnpmWorkspaceSetting(content, "verifyDepsBeforeRun")) {
    if (isVerbose ?? false) console.log(chalk16.green("  verifyDepsBeforeRun is set"));
    return true;
  }
  if (!(isSilent ?? false)) {
    console.log(chalk16.red(`  verifyDepsBeforeRun is not set in pnpm-workspace.yaml (expected ${DEFAULT_VERIFY_DEPS_BEFORE_RUN})`));
  }
  return false;
}
function shouldFixVerifyDepsBeforeRun(cwd) {
  const content = readPnpmWorkspaceYaml(cwd);
  if (!(content != null && content.length > 0)) return false;
  const lines = content.split("\n");
  const newLines = [...lines];
  const lastLine = newLines.at(-1);
  const setting = `verifyDepsBeforeRun: ${DEFAULT_VERIFY_DEPS_BEFORE_RUN}`;
  if (lastLine === "") {
    newLines.splice(-1, 0, setting, "");
  } else {
    newLines.push(setting);
  }
  writePnpmWorkspaceYaml(cwd, newLines.join("\n"));
  console.log(chalk16.green(`  Fixed: verifyDepsBeforeRun set to ${DEFAULT_VERIFY_DEPS_BEFORE_RUN}`));
  return true;
}
function recordCheckFailure(hasPassed, fix, shouldApplyFix) {
  if (hasPassed) return 0;
  if (fix ?? false) return shouldApplyFix() ? 0 : 1;
  return 1;
}
function runYarnLintChecks(cwd, fix, isVerbose) {
  return recordCheckFailure(
    shouldCheckEnableScripts(cwd, isVerbose, fix),
    fix,
    () => shouldFixEnableScripts(cwd)
  );
}
function runPnpmLintChecks(cwd, config, fix, isVerbose) {
  let failures = 0;
  failures += recordCheckFailure(
    shouldCheckMinimumReleaseAge(cwd, config, isVerbose, fix),
    fix,
    () => shouldFixMinimumReleaseAge(cwd, config)
  );
  failures += recordCheckFailure(
    shouldCheckMinimumReleaseAgeExclude(cwd, config, isVerbose, fix),
    fix,
    () => shouldFixMinimumReleaseAgeExclude(cwd, config)
  );
  failures += recordCheckFailure(
    shouldCheckVerifyDepsBeforeRun(cwd, isVerbose, fix),
    fix,
    () => shouldFixVerifyDepsBeforeRun(cwd)
  );
  return failures;
}
function resolvePackmanConfigFromRoot(rootConfig) {
  const commands = rootConfig.commands;
  return resolvePackmanConfig(commands?.packman);
}
async function packmanLint({ fix, isVerbose } = {}) {
  const cwd = process.cwd();
  const pm = detectPackageManager();
  if (pm === "npm" || pm === "bun") {
    console.log(chalk16.green(`packman lint: no manager-specific checks are currently required for ${pm}`));
    return 0;
  }
  let failures = 0;
  if (pm === "yarn") {
    failures += runYarnLintChecks(cwd, fix, isVerbose);
  } else if (pm === "pnpm") {
    const rootConfig = await loadConfig();
    failures += runPnpmLintChecks(
      cwd,
      resolvePackmanConfigFromRoot(rootConfig),
      fix,
      isVerbose
    );
  }
  if (failures > 0) {
    console.log(chalk16.red(`
packman lint: ${failures} check(s) failed`));
    if (!(fix ?? false)) {
      console.log(chalk16.yellow("Run with --fix to auto-fix issues"));
    }
  } else {
    console.log(chalk16.green("\npackman lint: all checks hasPassed"));
  }
  return failures > 0 ? 1 : 0;
}
export {
  convert,
  detectCurrentPM,
  findWorkspacePackagePaths,
  packmanClean,
  packmanLint,
  rewriteScript,
  rewriteScriptsInPackageJson
};
//# sourceMappingURL=index.mjs.map
