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

// src/lib/packageManagerRuntime.ts
import fs from "node:fs";
import chalk from "chalk";
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 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/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/fillTemplate.ts
function fillTemplate(template, data) {
  return template.replaceAll(/\{\{(.*?)\}\}/g, (_, key) => data[key.trim()] ?? "");
}

// 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/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/pnpmConfig/readMinReleaseAge.ts
import * as yaml from "yaml";
var DEFAULT_MINIMUM_RELEASE_AGE_MINUTES = 1440;

// src/lib/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var reporterState = {
  currentCommand: "unknown",
  isEnvelopeEmitted: false,
  isJsonModeEnabled: false,
  isStrictModeEnabled: false,
  originalStdoutWrite: void 0,
  startTime: 0
};
function isJsonMode() {
  return reporterState.isJsonModeEnabled;
}
function setCurrentCommand(name) {
  reporterState.currentCommand = name;
  reporterState.startTime = performance.now();
  reporterState.isEnvelopeEmitted = false;
}
function emitJson(envelope) {
  if (reporterState.isEnvelopeEmitted) return;
  reporterState.isEnvelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (reporterState.originalStdoutWrite) {
    reporterState.originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance2.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance2.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

// src/lib/repoTemplates.ts
import { readdirSync, readFileSync as readFileSync3 } from "node:fs";
import { createRequire as createRequire2 } from "node:module";
import PATH2 from "node:path";
var require3 = createRequire2(import.meta.url);
var packageRoot = PATH2.dirname(require3.resolve("@xylabs/toolchain/package.json"));
var repoTemplatesDir = PATH2.resolve(packageRoot, "templates", "repo");
function collectFiles(dir, prefix) {
  const results = [];
  const entries = readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isDirectory()) {
      results.push(...collectFiles(PATH2.resolve(dir, entry.name), rel));
    } else {
      results.push({
        content: readFileSync3(PATH2.resolve(dir, entry.name), "utf8"),
        relativePath: rel
      });
    }
  }
  return results;
}
function loadRepoTemplateFiles(template, section) {
  const dir = PATH2.resolve(repoTemplatesDir, template, section);
  return collectFiles(dir, "");
}

// src/lib/shouldRunInstall.ts
import chalk2 from "chalk";
function shouldRunInstall(cwd) {
  const pm = detectPackageManager();
  console.log(chalk2.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(chalk2.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk2.green("Dependencies installed"));
  return true;
}

// src/actions/package-lint-deps.ts
import { readFileSync as readFileSync4, writeFileSync } from "node:fs";
import PATH3 from "node:path";
import chalk3 from "chalk";
import semver from "semver";
function readWorkspacePackageJson(cwd, location) {
  const pkgPath = PATH3.resolve(cwd, location, "package.json");
  try {
    return JSON.parse(readFileSync4(pkgPath, "utf8"));
  } catch {
    return void 0;
  }
}
function writeWorkspacePackageJson(cwd, location, pkg) {
  const pkgPath = PATH3.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(chalk3.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(chalk3.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(chalk3.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(chalk3.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(chalk3.green(`  \u2714 Fixed: set peerDependencies.${dep} to "${expected}" in ${name} (${location})`));
        isModified = true;
      }
    }
    if (isModified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}

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

// src/actions/package-lint-engines.ts
import { readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
import PATH4 from "node:path";
import chalk4 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 = PATH4.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync5(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 = PATH4.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync5(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (Boolean(pkg.volta)) {
        delete pkg.volta;
        writeFileSync2(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk4.green(`  \u2714 Fixed: removed volta from ${location}/package.json`));
      }
    } catch {
    }
  }
}
function checkEnginesOnlyInNonTerminal(cwd, workspaces) {
  const result = emptyResult();
  const rootPkg = JSON.parse(readFileSync5(PATH4.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 = PATH4.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync5(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(readFileSync5(PATH4.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 = PATH4.resolve(cwd, "package.json");
  const rootRaw = readFileSync5(rootPath, "utf8");
  const rootPkg = JSON.parse(rootRaw);
  if (Boolean(rootPkg.engines)) {
    delete rootPkg.engines;
    writeFileSync2(rootPath, `${JSON.stringify(rootPkg, null, 2)}
`, "utf8");
    console.log(chalk4.green("  \u2714 Fixed: removed engines from root package.json"));
  }
  const enginesTemplate = resolveEnginesTemplate(cwd, workspaces);
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync5(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(chalk4.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(chalk4.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 === "." ? PATH4.resolve(cwd, "package.json") : PATH4.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync5(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 readFileSync6,
  writeFileSync as writeFileSync3
} from "node:fs";
import PATH5 from "node:path";
import chalk5 from "chalk";
import * as yaml2 from "yaml";
function emptyResult2() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function pnpmWorkspacePath(cwd) {
  return PATH5.resolve(cwd, "pnpm-workspace.yaml");
}
function readPnpmWorkspaceDocument(cwd) {
  const wsPath = pnpmWorkspacePath(cwd);
  if (!existsSync3(wsPath)) return void 0;
  try {
    return yaml2.parseDocument(readFileSync6(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(chalk5.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(chalk5.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(chalk5.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(chalk5.green("  \u2714 Fixed: added @xylabs/* and @xyo-network/* to minimumReleaseAgeExclude in pnpm-workspace.yaml"));
}

// src/actions/package-lint-specs.ts
import { readdirSync as readdirSync2, statSync } from "node:fs";
import PATH6 from "node:path";
function emptyResult3() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function collectSpecFiles(dir, out) {
  for (const entry of readdirSync2(dir)) {
    const fullPath = PATH6.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 = PATH6.resolve(cwd, location, "src");
    const specFiles = [];
    try {
      collectSpecFiles(srcDir, specFiles);
    } catch {
      continue;
    }
    for (const specPath of specFiles) {
      const relativeToSrc = PATH6.relative(srcDir, specPath).replaceAll("\\", "/");
      if (!relativeToSrc.startsWith("spec/")) {
        const relativeToRepo = PATH6.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 = readFileSync7(PATH7.resolve(cwd, "package.json"), "utf8");
  return JSON.parse(raw);
}
function writeRootPackageJson(cwd, pkg) {
  const path = PATH7.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(chalk6.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(chalk6.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 = PATH7.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync7(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 = PATH7.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync7(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (Boolean(pkg.packageManager)) {
        delete pkg.packageManager;
        writeFileSync4(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk6.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 = PATH7.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync7(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 = PATH7.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync7(pkgPath, "utf8"));
        if (Boolean(pkg.workspaces)) {
          delete pkg.workspaces;
          writeFileSync4(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
          const label = location === "." ? "root" : location;
          console.log(chalk6.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(chalk6.red(`  \u2717 ${error}`));
    errors++;
  }
  for (const fixable of result.fixable) {
    if (shouldFix) {
      fixed++;
    } else {
      console.log(chalk6.red(`  \u2717 ${fixable} (fixable)`));
      errors++;
    }
  }
  for (const warning of result.warnings) {
    console.log(chalk6.yellow(`  \u26A0 ${warning}`));
  }
  if (errors === 0 && fixed === 0 && result.warnings.length === 0) {
    console.log(chalk6.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(chalk6.green(`
  Fixed ${fixed} issue(s)`));
  }
  if (errors > 0) {
    console.log(chalk6.red(`
  ${errors} error(s) found`));
  } else if (fixed === 0) {
    console.log(chalk6.green("\n  All checks passed"));
  }
}
function packageLintMonorepo(shouldFix = false) {
  const cwd = INIT_CWD();
  let pkg;
  try {
    pkg = readRootPackageJson2(cwd);
  } catch {
    console.error(chalk6.red("Could not read package.json"));
    return 1;
  }
  if (!isMonorepo(pkg, cwd)) {
    console.log(chalk6.gray("Not a monorepo \u2014 skipping repo lint checks"));
    return 0;
  }
  console.log(chalk6.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/repo-init.ts
import {
  existsSync as existsSync4,
  mkdirSync,
  readdirSync as readdirSync3,
  readFileSync as readFileSync8,
  writeFileSync as writeFileSync5
} from "node:fs";
import PATH8 from "node:path";
import { createInterface } from "node:readline";
import chalk7 from "chalk";
function askQuestion(question) {
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer.trim());
    });
  });
}
function mapOutputPath(relativePath, variables) {
  let result = relativePath;
  if (result.endsWith(".tmpl")) {
    result = result.slice(0, -5);
  }
  if (result === "gitignore") {
    result = ".gitignore";
  }
  if (result.startsWith("github/")) {
    result = `.${result}`;
  }
  result = result.replaceAll("__packageName__", () => variables.packageName);
  return result;
}
function isPmSpecificFile(relativePath, pm) {
  if (relativePath === "pnpm-workspace.yaml" && pm !== "pnpm") return true;
  if (relativePath.includes("build-pnpm") && pm !== "pnpm") return true;
  if (relativePath.includes("build-npm") && pm !== "npm") return true;
  if (relativePath.includes("build-bun") && pm !== "bun") return true;
  if (relativePath.includes("build-yarn") && pm !== "yarn") return true;
  return false;
}
function mapBuildWorkflowName(outputPath) {
  return outputPath.replace(/build-(bun|npm|pnpm|yarn)\.yml/, "build.yml");
}
function buildVariables(params) {
  const {
    description,
    githubOrg,
    packageName,
    pm,
    projectName,
    scope
  } = params;
  const identifierName = packageName.replaceAll(/-([a-z])/g, (_, c) => c.toUpperCase());
  const packageManager = pm === "pnpm" ? "pnpm@10.33.0+sha512.10568bb4a6afb58c9eb3630da90cc9516417abebd3fabbe6739f0ae795728da1491e9db5a544c76ad8eb7570f5c4bb3d6c637b2cb41bfdcdb47fa823c8649319" : pm === "yarn" ? "yarn@4.13.0" : pm === "npm" ? "npm@10.9.4" : "bun@1.3.3";
  const xyCommand = pm === "npm" ? "npm exec -- xy" : pm === "bun" ? "bun run xy" : `${pm} xy`;
  return {
    description,
    githubOrg,
    identifierName,
    npmScope: scope,
    packageName,
    packageManager,
    pmName: pm,
    projectName,
    toolchainRange: bundledToolchainRange(),
    toolchainVersion: bundledToolchainVersion(),
    xyCommand
  };
}
function didEnsureEmptyDir(projectDir, name) {
  if (existsSync4(projectDir)) {
    const entries = readdirSync3(projectDir);
    if (entries.length > 0) {
      console.error(chalk7.red(`Directory '${name}' already exists and is not empty`));
      return false;
    }
  }
  mkdirSync(projectDir, { recursive: true });
  return true;
}
function scaffoldFiles(templateName, layer, outputDir, pm, variables, isVerbose) {
  const files = loadRepoTemplateFiles(templateName, layer);
  let count = 0;
  for (const file of files) {
    if (isPmSpecificFile(file.relativePath, pm)) continue;
    const content = fillTemplate(file.content, variables);
    let outputPath = mapOutputPath(file.relativePath, variables);
    if (!(outputPath != null && outputPath.length > 0)) continue;
    if (layer === "root") outputPath = mapBuildWorkflowName(outputPath);
    const fullPath = PATH8.resolve(outputDir, outputPath);
    mkdirSync(PATH8.dirname(fullPath), { recursive: true });
    writeFileSync5(fullPath, content);
    count++;
    if (isVerbose ?? false) console.log(chalk7.gray(`  ${layer === "root" ? outputPath : `packages/${variables.packageName}/${outputPath}`}`));
  }
  return count;
}
function initGitRepo(projectDir, isVerbose) {
  if (isVerbose ?? false) console.log(chalk7.gray("Initializing git repository..."));
  const result = spawnSync("git", ["init", "-b", "main"], {
    cwd: projectDir,
    stdio: isVerbose ?? false ? "inherit" : "pipe"
  });
  if (result.status === 0) {
    console.log(chalk7.green("Initialized git repository"));
  } else {
    console.warn(chalk7.yellow("git init failed, skipping"));
  }
}
function didInstallDependencies(projectDir, pm) {
  console.log(chalk7.gray(`Running ${pm} install...`));
  const result = spawnPackageManagerSync(pm, ["install"], {
    context: { cwd: projectDir, operation: `Install ${pm} dependencies for repo init` },
    cwd: projectDir,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (result.status !== 0) {
    console.warn(chalk7.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk7.green("Dependencies installed"));
  return true;
}
function normalizeRootPackageJson(projectDir, pm) {
  const pkgPath = PATH8.resolve(projectDir, "package.json");
  const pkg = JSON.parse(readFileSync8(pkgPath, "utf8"));
  if (pm === "pnpm") {
    delete pkg.workspaces;
  } else {
    pkg.workspaces ??= ["packages/*"];
  }
  writeFileSync5(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
}
function renderXyCommand(pm, args) {
  const suffix = args.join(" ");
  switch (pm) {
    case "bun": {
      return `bun run xy ${suffix}`.trim();
    }
    case "npm": {
      return `npm exec -- xy ${suffix}`.trim();
    }
    default: {
      return `${pm} xy ${suffix}`.trim();
    }
  }
}
async function repoInit(params) {
  const {
    description,
    pm,
    scope,
    skipGit,
    skipInstall,
    template,
    isVerbose
  } = params;
  let name = params.name;
  if (!(name != null && name.length > 0)) {
    name = await askQuestion(chalk7.cyan("Project name: "));
    if (!name) {
      console.error(chalk7.red("Project name is required"));
      return 1;
    }
  }
  const projectName = PATH8.basename(name);
  const packageName = params.packageName ?? projectName;
  const githubOrg = params.githubOrg ?? scope.replace(/^@/, "");
  const variables = buildVariables({
    description,
    githubOrg,
    packageName,
    pm,
    projectName,
    scope
  });
  if (isVerbose ?? false) {
    console.log(chalk7.gray("Template variables:"));
    for (const [key, value] of Object.entries(variables)) {
      console.log(chalk7.gray(`  ${key}: ${value}`));
    }
  }
  const projectDir = PATH8.resolve(process.cwd(), name);
  if (!didEnsureEmptyDir(projectDir, name)) return 1;
  const rootCount = scaffoldFiles(template, "root", projectDir, pm, variables, isVerbose);
  const pkgDir = PATH8.resolve(projectDir, "packages", packageName);
  const pkgCount = scaffoldFiles(template, "package", pkgDir, pm, variables, isVerbose);
  normalizeRootPackageJson(projectDir, pm);
  console.log(chalk7.green(`Scaffolded ${rootCount + pkgCount} files into ${name}/`));
  if (!(skipGit ?? false)) initGitRepo(projectDir, isVerbose);
  if (!(skipInstall ?? false) && !didInstallDependencies(projectDir, pm)) return 1;
  console.log("");
  console.log(chalk7.cyan(`Project ${name} created successfully!`));
  console.log("");
  console.log(chalk7.gray("Next steps:"));
  console.log(chalk7.gray(`  cd ${name}`));
  if (skipInstall ?? false) console.log(chalk7.gray(`  ${pm} install`));
  console.log(chalk7.gray(`  ${renderXyCommand(pm, ["build"])}`));
  return 0;
}

// src/xy/common/repo/initCommand.ts
var initCommand = {
  command: "init <template> [name]",
  describe: "Scaffold a new monorepo from a template",
  builder: (yargs) => {
    return yargs.positional("template", {
      choices: ["cli"],
      describe: "Template to use",
      type: "string"
    }).positional("name", {
      describe: "Project name (also used as directory name)",
      type: "string"
    }).option("scope", {
      default: "@xylabs",
      describe: "npm scope for packages",
      type: "string"
    }).option("package", {
      describe: "Package name within the monorepo (defaults to project name)",
      type: "string"
    }).option("description", {
      default: "",
      describe: "Project description",
      type: "string"
    }).option("github-org", {
      describe: "GitHub organization (derived from scope if not set)",
      type: "string"
    }).option("pm", {
      choices: ["bun", "npm", "pnpm", "yarn"],
      default: "pnpm",
      describe: "Package manager to configure",
      type: "string"
    }).option("skip-install", {
      default: false,
      describe: "Skip dependency installation after scaffolding",
      type: "boolean"
    }).option("skip-git", {
      default: false,
      describe: "Skip git init after scaffolding",
      type: "boolean"
    });
  },
  handler: async (argv) => {
    if (Boolean(argv.verbose)) console.log("Repo Init");
    await withEnvelope("repo init", () => repoInit({
      description: argv.description,
      githubOrg: argv["github-org"],
      name: argv.name,
      packageName: argv.package,
      pm: argv.pm,
      scope: argv.scope,
      skipGit: !!Boolean(argv.skipGit),
      skipInstall: !!Boolean(argv.skipInstall),
      template: argv.template,
      isVerbose: !!Boolean(argv.verbose)
    }));
  }
};

// src/xy/common/repo/lintCommand.ts
var lintCommand = {
  command: "lint",
  describe: "Check monorepo package structure",
  builder: (yargs) => {
    return yargs.option("fix", {
      default: false,
      description: "Auto-fix fixable issues",
      type: "boolean"
    });
  },
  handler: async (argv) => {
    if (Boolean(argv.verbose)) console.log("Repo Lint");
    await withEnvelope("repo lint", () => packageLintMonorepo(!!Boolean(argv.fix)));
  }
};

// src/xy/common/repo/index.ts
var repoCommand = {
  builder: (yargs) => {
    return yargs.command(initCommand).command(lintCommand).demandCommand(1, "Please specify a repo subcommand").strictCommands();
  },
  command: "repo",
  describe: "Repo - Repository structure utilities",
  handler: () => {
  }
};
export {
  repoCommand
};
//# sourceMappingURL=index.mjs.map
