// src/lib/checkResult.ts
import chalk from "chalk";
var checkResult = (name, result, level = "error", exitOnFail = false) => {
  if (result) {
    const exiting = exitOnFail ? "[Exiting Process]" : "[Continuing]";
    const chalkFunc = level === "error" ? chalk.red : chalk.yellow;
    console[level](chalkFunc(`${name} had ${result} failures ${exiting}`));
    if (exitOnFail) {
      process.exit(result);
    }
  }
};

// src/lib/claudeMdTemplate.ts
import {
  readdirSync,
  readFileSync,
  statSync
} from "node:fs";
import { createRequire } from "node:module";
import PATH from "node:path";
var require2 = createRequire(import.meta.url);
var packageRoot = PATH.dirname(require2.resolve("@xylabs/toolchain/package.json"));
var templatesDir = PATH.resolve(packageRoot, "templates", "claude");
function applyPackageManager(content, pm) {
  const xyCommand = pm === "npm" ? "npm exec -- xy" : pm === "bun" ? "bun run xy" : `${pm} xy`;
  const addCommand = pm === "npm" ? "npm install" : pm === "bun" ? "bun add" : `${pm} add`;
  return content.replaceAll("yarn xy", xyCommand).replaceAll("pnpm xy", xyCommand).replaceAll("yarn add", addCommand).replaceAll("pnpm add", addCommand);
}
var XYLABS_RULES_PREFIX = "xylabs-";
var XYLABS_COMMANDS_PREFIX = "xy-";
var LEGACY_COMMANDS_PREFIX = "xylabs-";
var XYLABS_SKILLS_PREFIX = "xylabs-";
var claudeMdRuleTemplates = () => {
  const rulesDir = PATH.resolve(templatesDir, "rules");
  const files = readdirSync(rulesDir).filter((f) => f.startsWith(XYLABS_RULES_PREFIX) && f.endsWith(".md"));
  const result = {};
  for (const file of files) {
    result[file] = readFileSync(PATH.resolve(rulesDir, file), "utf8");
  }
  return result;
};
var claudeCommandTemplates = () => {
  const commandsDir = PATH.resolve(templatesDir, "commands");
  const files = readdirSync(commandsDir).filter((f) => f.startsWith(XYLABS_COMMANDS_PREFIX) && f.endsWith(".md"));
  const result = {};
  for (const file of files) {
    result[file] = readFileSync(PATH.resolve(commandsDir, file), "utf8");
  }
  return result;
};
var claudeSkillTemplates = () => {
  const skillsDir = PATH.resolve(templatesDir, "skills");
  const dirs = readdirSync(skillsDir).filter(
    (f) => f.startsWith(XYLABS_SKILLS_PREFIX) && statSync(PATH.resolve(skillsDir, f)).isDirectory()
  );
  const result = {};
  for (const dir of dirs) {
    const dirPath = PATH.resolve(skillsDir, dir);
    const files = readdirSync(dirPath, { recursive: true, encoding: "utf8" });
    result[dir] = {};
    for (const file of files) {
      if (statSync(PATH.resolve(dirPath, file)).isFile()) {
        result[dir][file] = readFileSync(PATH.resolve(dirPath, file), "utf8");
      }
    }
  }
  return result;
};
var claudeMdProjectTemplate = () => readFileSync(PATH.resolve(templatesDir, "CLAUDE-project.md"), "utf8");
var claudeMdLocalTemplate = () => readFileSync(PATH.resolve(templatesDir, "CLAUDE-local.md"), "utf8");

// src/lib/concurrency.ts
import { AsyncLocalStorage } from "node:async_hooks";
var outputStorage = new AsyncLocalStorage();
var captureInstalled = false;
function installOutputCapture() {
  if (captureInstalled) return;
  captureInstalled = true;
  const originalStdoutWrite2 = process.stdout.write.bind(process.stdout);
  const originalStderrWrite = process.stderr.write.bind(process.stderr);
  function intercept(original) {
    return function(chunk, ...args) {
      const buffer = outputStorage.getStore();
      if (buffer) {
        buffer.push(typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk));
        return true;
      }
      return original(chunk, ...args);
    };
  }
  process.stdout.write = intercept(originalStdoutWrite2);
  process.stderr.write = intercept(originalStderrWrite);
}
async function runWithConcurrency(items, concurrency, fn) {
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      await fn(items[i]);
    }
  }
  await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
}

// src/lib/createBuildConfig.ts
import { readFileSync as readFileSync2 } from "node:fs";

// src/lib/defaultBuildConfig.ts
var defaultBuildConfig = {
  compilerOptions: {
    rootDir: "src",
    rootDirs: ["package.json"]
  },
  exclude: [
    "**/build",
    "**/dist",
    "**/node_modules",
    "**/*.spec.*",
    "**/*.spec",
    "**/*.stories.*",
    "**/*.example.*",
    "**/spec/*",
    "**/stories/*"
  ],
  include: ["src"]
};

// src/lib/createBuildConfig.ts
var getGeneralTypescriptConfig = (location) => {
  let generalConfig;
  try {
    generalConfig = readFileSync2(`${location}/tsconfig.json`, { encoding: "utf8" });
  } catch {
    return false;
  }
  return JSON.parse(generalConfig);
};
var createBuildConfig = (location, module, target, outDirSuffix) => {
  const generalConfigObject = getGeneralTypescriptConfig(location);
  if (generalConfigObject === false) {
    return void 0;
  }
  return {
    ...generalConfigObject,
    compilerOptions: {
      ...defaultBuildConfig.compilerOptions,
      ...generalConfigObject.compilerOptions,
      module,
      outDir: `./${generalConfigObject.compilerOptions?.outDir ?? "dist"}/${outDirSuffix}`,
      target
    },
    exclude: [...generalConfigObject.exclude ?? [], ...defaultBuildConfig.exclude],
    include: [...generalConfigObject.include ?? [], ...defaultBuildConfig.include]
  };
};

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

// src/lib/deleteGlob.ts
import fs from "node:fs";
import { glob } from "glob";
var deleteGlob = (globPath) => {
  const files = glob.sync(globPath);
  for (const file of files) {
    fs.rmSync(file, { recursive: true, force: true });
  }
};

// src/lib/dependencies/detectDuplicateDependencies.ts
import { execSync } from "node:child_process";

// src/pm/resolveWorkspace.ts
import chalk2 from "chalk";
function shortName(name) {
  const slash = name.lastIndexOf("/");
  return slash === -1 ? name : name.slice(slash + 1);
}
function resolveWorkspace(workspaces, query) {
  const exact = workspaces.find((ws) => ws.name === query);
  if (exact) return exact;
  const byLocation = workspaces.find((ws) => ws.location === query);
  if (byLocation) return byLocation;
  const byShort = workspaces.filter((ws) => shortName(ws.name) === query);
  if (byShort.length === 1) return byShort[0];
  if (byShort.length > 1) {
    console.error(chalk2.red(`Ambiguous workspace "${query}"; matches: ${byShort.map((ws) => ws.name).join(", ")}`));
    return void 0;
  }
  return void 0;
}

// src/lib/packageManagerRuntime.ts
import fs2 from "node:fs";
import chalk3 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"
};
function currentPlatform() {
  if (process.platform === "darwin" || process.platform === "linux" || process.platform === "win32") {
    return process.platform;
  }
  return "unknown";
}
function askYesNo(question) {
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
    return false;
  }
  process.stdout.write(question);
  const buffer = Buffer.alloc(1024);
  const bytesRead = fs2.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(chalk3.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk3.gray(`  ${line}`));
  }
}
function installWithHomebrew(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 ensurePackageManagerInstalled(pm, context) {
  if (isPackageManagerInstalled(pm)) return true;
  const plan = getPackageManagerInstallPlan(pm, context.platform ?? currentPlatform());
  const displayName = DISPLAY_NAMES[pm];
  console.error(chalk3.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk3.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk3.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk3.gray(`  ${plan.command}`));
    return false;
  }
  const confirmed = askYesNo(chalk3.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!confirmed) {
    console.error(chalk3.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk3.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!installWithHomebrew(pm, context.cwd)) {
    console.error(chalk3.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk3.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk3.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk3.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk3.green(`${displayName} installed successfully.`));
  return true;
}
function failureResult() {
  return {
    output: ["", ""],
    pid: 0,
    signal: null,
    status: 1,
    stderr: "",
    stdout: ""
  };
}
function spawnPackageManagerSync(pm, args, options) {
  if (!ensurePackageManagerInstalled(pm, options.context)) {
    return failureResult();
  }
  return spawnSync(pm, args, { encoding: "utf8", ...options });
}

// src/pm/workspaces.ts
import { existsSync, readFileSync as readFileSync3 } from "node:fs";
import PATH2 from "node:path";
import { globSync } from "glob";
function readJsonFile(path3) {
  if (!existsSync(path3)) return void 0;
  try {
    return JSON.parse(readFileSync3(path3, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH2.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 = PATH2.resolve(cwd, "pnpm-workspace.yaml");
  if (!existsSync(wsPath)) return [];
  const content = readFileSync3(wsPath, "utf8");
  const patterns = [];
  let inPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      inPackages = true;
      continue;
    }
    if (inPackages) {
      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 listDeclaredWorkspaces(cwd = process.cwd()) {
  const patterns = readWorkspacePatterns(cwd);
  const seen = /* @__PURE__ */ new Set();
  const workspaces = [];
  for (const pattern of patterns) {
    const matches = globSync(PATH2.posix.join(pattern.replaceAll(PATH2.sep, "/"), "package.json"), {
      absolute: true,
      cwd,
      ignore: ["**/node_modules/**", "**/dist/**", "**/build/**"]
    });
    for (const match of matches) {
      const pkg = readJsonFile(match);
      if (!pkg?.name) continue;
      const location = PATH2.relative(cwd, PATH2.dirname(match)) || ".";
      if (seen.has(location)) continue;
      seen.add(location);
      workspaces.push({ location, name: pkg.name });
    }
  }
  return workspaces.toSorted((a, b) => a.location.localeCompare(b.location));
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!packageManager) return void 0;
  return packageManager.split("@")[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 && 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/yarn/isYarnVersionOrGreater.ts
var isYarnVersionOrGreater = (major, minor, patch) => {
  const result = spawnPackageManagerSync("yarn", ["-v"], {
    context: { operation: "Check installed Yarn version" },
    encoding: "utf8"
  });
  const version = result.stdout.toString().replaceAll("\n", "");
  const versionNumbers = version.split(".").map((ver) => Number.parseInt(ver));
  const majorDelta = versionNumbers[0] - major;
  const minorDelta = versionNumbers[1] - (minor ?? versionNumbers[1]);
  const patchDelta = versionNumbers[2] - (patch ?? versionNumbers[2]);
  const majorOk = majorDelta >= 0;
  const minorOk = majorDelta > 0 || minorDelta >= 0;
  const patchOk = majorDelta > 0 || minorDelta > 0 || patchDelta >= 0;
  return [majorOk && minorOk && patchOk, version];
};

// src/lib/yarn/workspace/yarnWorkspaces.ts
var yarnWorkspaces = () => {
  const result = spawnPackageManagerSync("yarn", ["workspaces", "list", "--json", "--recursive"], {
    context: { operation: "List Yarn workspaces" },
    encoding: "utf8"
  });
  if (result.error) {
    throw result.error;
  }
  return result.stdout.toString().split("\n").slice(0, -1).map((item) => {
    return JSON.parse(item);
  });
};

// src/lib/yarn/workspace/yarnWorkspace.ts
var yarnWorkspace = (pkg) => {
  const workspace = yarnWorkspaces().find(({ name }) => name === pkg);
  if (!workspace) throw new Error(`Workspace ${pkg} not found`);
  return workspace;
};

// src/lib/processEx.ts
import chalk4 from "chalk";

// src/lib/withError.ts
var withError = (ex, closure, predicate = (ex2) => !!ex2.name && !!ex2.message) => {
  return predicate(ex) ? closure(ex) : void 0;
};

// src/lib/withErrnoException.ts
var withErrnoException = (ex, closure) => {
  return withError(ex, closure, (ex2) => ex2.errno !== void 0);
};

// src/lib/processEx.ts
var processEx = (ex) => {
  const error = typeof ex === "string" ? new Error(ex) : ex;
  const exitCode = withErrnoException(error, (error2) => {
    if (error2.code === "ENOENT") {
      console.error(chalk4.red(`'${error2.path}' not found.`));
    } else {
      console.error(chalk4.red(`Errno: ${error2.code}`));
    }
    return error2.errno ?? -1;
  }) ?? withError(error, (error2) => {
    console.error(chalk4.red(`${error2.name}: ${error2.message}`));
    return -1;
  }) ?? (() => {
    console.error(chalk4.red(`Unexpected Error: ${JSON.stringify(ex, null, 2)}`));
    return -1;
  })();
  process.exit(process.exitCode ?? exitCode);
};

// src/lib/safeExit.ts
var safeExit = (func, exitOnFail = true) => {
  try {
    const result = func();
    if (result && exitOnFail) {
      process.exit(result);
    }
    return result;
  } catch (ex) {
    return processEx(ex);
  }
};
var safeExitAsync = async (func, exitOnFail = true) => {
  try {
    const result = await func();
    if (result && exitOnFail) {
      process.exit(result);
    }
    return result;
  } catch (ex) {
    return processEx(ex);
  }
};

// src/lib/dependencies/DuplicateDetector.ts
import { EOL } from "node:os";
import chalk5 from "chalk";

// src/lib/jsonFormatters.ts
var multiLineToJSONArray = (output) => {
  const withCommas = output.replaceAll("\r\n", "").replaceAll("\n", ",");
  const cleanCollection = withCommas.slice(0, Math.max(0, withCommas.length - 1));
  const collection = `[${cleanCollection}]`;
  return JSON.parse(collection);
};

// src/lib/dependencies/DuplicateDetector.ts
var trimVirtualMeta = (value) => {
  const virtualParts = value.split("virtual:");
  if (virtualParts.length > 1) {
    const hashParts = virtualParts[1].split("#");
    return virtualParts[0] + hashParts[1];
  } else {
    return value;
  }
};
var trimObjectDependencyVirtualMeta = (obj) => {
  const resultObj = {};
  for (const [key, value] of Object.entries(obj)) {
    resultObj[trimVirtualMeta(key)] = {
      descriptor: trimVirtualMeta(value.descriptor),
      locator: trimVirtualMeta(value.locator)
    };
  }
  return resultObj;
};
var trimDependencyVirtualMeta = (dependencies) => {
  return dependencies.map((dependency) => {
    return { children: trimObjectDependencyVirtualMeta(dependency.children), value: trimVirtualMeta(dependency.value) };
  });
};
function extractPnpmVersions(data, depName) {
  const versions = /* @__PURE__ */ new Set();
  function walk(obj) {
    if (Array.isArray(obj)) {
      for (const item of obj) walk(item);
    } else if (obj && typeof obj === "object") {
      const record = obj;
      if (typeof record.version === "string" && typeof record.from === "string" && record.from === depName) {
        versions.add(record.version);
      }
      for (const val of Object.values(record)) walk(val);
    }
  }
  walk(data);
  return [...versions];
}
var DuplicateDetector = class {
  dependency;
  duplicateVersions;
  constructor(output, dependency) {
    this.dependency = dependency;
    this.duplicateVersions = this.parseVersions(output, dependency);
  }
  detect() {
    if (this.duplicateVersions.length > 1) {
      console.log(chalk5.yellow(`${EOL}Duplicates found for: ${this.dependency}`));
      const duplicateVersions = this.duplicateVersions.join(`${EOL}  `);
      console.log(chalk5.grey(`  ${duplicateVersions}`, EOL));
      return 1;
    } else {
      console.log(`${this.dependency} - OK`);
      return 0;
    }
  }
  parseVersions(output, dependency) {
    try {
      const parsed = JSON.parse(output);
      if (Array.isArray(parsed)) {
        return extractPnpmVersions(parsed, dependency);
      }
    } catch {
    }
    try {
      const entries = trimDependencyVirtualMeta(multiLineToJSONArray(output));
      const versions = /* @__PURE__ */ new Set();
      for (const entry of entries) {
        for (const key of Object.keys(entry.children)) {
          const version = key.includes("@virtual:") ? void 0 : key;
          if (version) versions.add(version);
        }
      }
      return [...versions];
    } catch {
      console.warn(chalk5.yellow(`Could not parse dependency output for ${dependency}`));
      return [];
    }
  }
};

// src/lib/dependencies/detectDuplicateDependencies.ts
var detectDuplicateDependencies = (depsFromPackageJSON, DefaultDependencies, exitOnFail = true) => {
  let exitCode = 0;
  const dependencies = depsFromPackageJSON?.length ? depsFromPackageJSON : DefaultDependencies;
  return safeExit(() => {
    if (dependencies) {
      for (const dependency of dependencies) {
        let output;
        try {
          const pm = getPackageManager();
          const cmd = `${pm.command} why ${dependency} --json`;
          output = execSync(cmd, { maxBuffer: 64 * 1024 * 1024 }).toString();
        } catch (e) {
          console.error(`Error running dependency check: ${String(e)}`);
          exitCode = 1;
          continue;
        }
        if (output) {
          exitCode = new DuplicateDetector(output, dependency).detect();
        } else {
          console.log(`${dependency} - N/A`);
          if (depsFromPackageJSON) {
            exitCode = 1;
            console.log(`\u{1F6A8} Library ${dependency} was requested in package.json but not found`);
          }
        }
      }
      return exitCode;
    } else {
      console.log("\u{1F6A8} No dependencies where passed");
      return exitCode;
    }
  }, exitOnFail);
};

// src/lib/dependencies/workspaceCycles.ts
import { readFileSync as readFileSync4 } from "node:fs";
import PATH3 from "node:path";
import chalk6 from "chalk";
function detectWorkspaceCycles(workspaces) {
  const workspaceNames = new Set(workspaces.map((ws) => ws.name));
  const graph = /* @__PURE__ */ new Map();
  for (const ws of workspaces) {
    const pkgPath = PATH3.join(ws.location, "package.json");
    const pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
    const deps = pkg.dependencies ?? {};
    const devDeps = pkg.devDependencies ?? {};
    const edges = [];
    for (const dep of Object.keys(deps)) {
      if (workspaceNames.has(dep)) edges.push({ name: dep, type: "dep" });
    }
    for (const dep of Object.keys(devDeps)) {
      if (workspaceNames.has(dep)) edges.push({ name: dep, type: "devDep" });
    }
    graph.set(ws.name, edges);
  }
  const WHITE = 0;
  const GRAY = 1;
  const BLACK = 2;
  const color = /* @__PURE__ */ new Map();
  const cycles = [];
  const path3 = [];
  const onPath = /* @__PURE__ */ new Set();
  for (const name of workspaceNames) color.set(name, WHITE);
  function dfs(u, incomingEdgeType) {
    color.set(u, GRAY);
    onPath.add(u);
    path3.push({ name: u, edgeType: incomingEdgeType });
    for (const edge of graph.get(u) ?? []) {
      const v = edge.name;
      if (onPath.has(v)) {
        const cycleEdges = [];
        const startIdx = path3.findIndex((p) => p.name === v);
        for (let i = startIdx; i < path3.length - 1; i++) {
          const nextEdgeType = path3[i + 1].edgeType ?? "dep";
          cycleEdges.push({
            from: path3[i].name,
            to: path3[i + 1].name,
            type: nextEdgeType
          });
        }
        cycleEdges.push({
          from: u,
          to: v,
          type: edge.type
        });
        cycles.push(cycleEdges);
      } else if (color.get(v) === WHITE) {
        dfs(v, edge.type);
      }
    }
    path3.pop();
    onPath.delete(u);
    color.set(u, BLACK);
  }
  for (const name of workspaceNames) {
    if (color.get(name) === WHITE) dfs(name);
  }
  return cycles;
}
function printWorkspaceCycles(cycles) {
  for (const cycle of cycles) {
    console.error(chalk6.red("  Workspace dependency cycle:"));
    for (const edge of cycle) {
      const edgeLabel = edge.type === "devDep" ? chalk6.yellow("devDep") : chalk6.cyan("dep");
      console.error(`    ${chalk6.white(edge.from)} --(${edgeLabel})--> ${chalk6.white(edge.to)}`);
    }
  }
}

// src/lib/deprecationMigrate.ts
import {
  existsSync as existsSync3,
  readFileSync as readFileSync6,
  writeFileSync
} from "node:fs";
import PATH4 from "node:path";
import { createInterface } from "node:readline";
import chalk7 from "chalk";
import semver from "semver";

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

// src/lib/deprecationMigrate.ts
var DEPRECATED_PACKAGES = [
  "@xylabs/ts-scripts-common",
  "@xylabs/toolchain",
  "@xylabs/toolchain",
  "@xylabs/ts-scripts-react-yarn3"
];
function findProjectRoot() {
  return process.env.INIT_CWD ?? process.cwd();
}
function askYesNo2(question) {
  const rl = createInterface({ input: process.stdin, output: process.stderr });
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer.trim().toLowerCase().startsWith("y"));
    });
  });
}
function replaceAllOldPackagesInFile(filePath) {
  if (!existsSync3(filePath)) return false;
  let content = readFileSync6(filePath, "utf8");
  let changed = false;
  for (const oldPkg of DEPRECATED_PACKAGES) {
    if (content.includes(oldPkg)) {
      content = content.replaceAll(oldPkg, "@xylabs/toolchain");
      changed = true;
    }
  }
  if (changed) {
    writeFileSync(filePath, content, "utf8");
  }
  return changed;
}
function applyVersionStyle(previousVersion, latestVersion) {
  if (!previousVersion) return `^${latestVersion}`;
  if (previousVersion.startsWith("~")) return `~${latestVersion}`;
  if (previousVersion.startsWith("^")) return `^${latestVersion}`;
  if (semver.valid(previousVersion)) return latestVersion;
  return `^${latestVersion}`;
}
function findPreferredVersion(pkg, field) {
  return pkg[field]?.["@xylabs/toolchain"] ?? DEPRECATED_PACKAGES.map((name) => pkg[field]?.[name]).find(Boolean);
}
function migratePackageJson(pkgPath, label, latestToolchainVersion) {
  if (!existsSync3(pkgPath)) return false;
  const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
  let changed = false;
  for (const field of ["dependencies", "devDependencies", "peerDependencies"]) {
    const previousVersion = findPreferredVersion(pkg, field);
    let foundDeprecatedPackage = false;
    for (const oldPkg of DEPRECATED_PACKAGES) {
      if (pkg[field]?.[oldPkg]) {
        delete pkg[field][oldPkg];
        changed = true;
        foundDeprecatedPackage = true;
      }
    }
    if (foundDeprecatedPackage || pkg[field]?.["@xylabs/toolchain"]) {
      pkg[field] ??= {};
      pkg[field]["@xylabs/toolchain"] = applyVersionStyle(previousVersion, latestToolchainVersion);
      changed = true;
    }
  }
  if (changed) {
    writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
    console.warn(chalk7.green(`  \u2713 Updated ${label}`));
  }
  return changed;
}
async function migrateWorkspaces(root, latestToolchainVersion) {
  const { globSync: globSync2 } = await import("glob");
  const packageJsonFiles = globSync2("**/package.json", {
    cwd: root,
    ignore: ["node_modules/**", "**/node_modules/**", "dist/**", "**/dist/**"]
  });
  for (const relPath of packageJsonFiles) {
    if (relPath === "package.json") continue;
    const dir = PATH4.dirname(relPath);
    migratePackageJson(PATH4.join(root, relPath), relPath, latestToolchainVersion);
    const xyConfigPath = PATH4.join(root, dir, "xy.config.ts");
    if (replaceAllOldPackagesInFile(xyConfigPath)) {
      console.warn(chalk7.green(`  \u2713 Updated ${dir}/xy.config.ts`));
    }
  }
}
function printManualInstructions2() {
  console.warn(chalk7.gray("  Skipped. To migrate manually:\n"));
  console.warn(chalk7.gray("    1. Replace all @xylabs/ts-scripts-* deps with @xylabs/toolchain in package.json"));
  console.warn(chalk7.gray("    2. Update imports in xy.config.ts files"));
  console.warn(chalk7.gray("    3. Run your package manager install\n"));
}
function resolveTargetToolchainVersion() {
  return bundledToolchainVersion();
}
async function deprecationMigrate(oldPackage) {
  const root = findProjectRoot();
  const pkgPath = PATH4.join(root, "package.json");
  if (!existsSync3(pkgPath)) return;
  const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
  const hasOldDep = DEPRECATED_PACKAGES.some((dep) => pkg.dependencies?.[dep] || pkg.devDependencies?.[dep]);
  if (!hasOldDep) return;
  console.warn(chalk7.yellow(`
\u26A0  ${oldPackage} is deprecated. Use @xylabs/toolchain instead.
`));
  const shouldMigrate = await askYesNo2(chalk7.cyan("  Auto-migrate to @xylabs/toolchain? [y/N] "));
  if (!shouldMigrate) {
    printManualInstructions2();
    return;
  }
  const targetToolchainVersion = resolveTargetToolchainVersion();
  migratePackageJson(pkgPath, "package.json", targetToolchainVersion);
  if (replaceAllOldPackagesInFile(PATH4.join(root, "xy.config.ts"))) {
    console.warn(chalk7.green("  \u2713 Updated xy.config.ts"));
  }
  await migrateWorkspaces(root, targetToolchainVersion);
  const pm = detectPackageManager();
  console.warn(chalk7.cyan(`
  Running ${pm} install...
`));
  const result = spawnPackageManagerSync(pm, ["install"], {
    context: { cwd: root, operation: `Run ${pm} install after toolchain migration` },
    cwd: root,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (result.status === 0) {
    console.warn(chalk7.green("  \u2713 Migration complete. Re-run your command.\n"));
  } else {
    console.warn(chalk7.red(`  Install failed (exit ${result.status}). Run "${pm} install" manually.
`));
  }
  process.exit(result.status ?? 1);
}

// src/lib/file/constants.ts
var WINDOWS_NEWLINE_REGEX = /\r\n/g;
var CROSS_PLATFORM_NEWLINE = "\n";

// src/lib/file/fileLines.ts
import {
  existsSync as existsSync4,
  readFileSync as readFileSync7,
  writeFileSync as writeFileSync2
} from "node:fs";

// src/lib/string/empty.ts
var empty = (value) => value?.trim().length === 0;
var notEmpty = (value) => !empty(value);

// src/lib/string/union.ts
var union = (a, b) => /* @__PURE__ */ new Set([...new Set(a), ...new Set(b)]);

// src/lib/file/ReadFileSyncOptions.ts
var defaultReadFileSyncOptions = { encoding: "utf8" };

// src/lib/file/fileLines.ts
var readLines = (uri, options = defaultReadFileSyncOptions) => existsSync4(uri) ? readFileSync7(uri, options).replace(WINDOWS_NEWLINE_REGEX, CROSS_PLATFORM_NEWLINE).split(CROSS_PLATFORM_NEWLINE) : [];
var readNonEmptyLines = (uri, options = defaultReadFileSyncOptions) => readLines(uri, options).filter(notEmpty);
var writeLines = (uri, lines, options = defaultReadFileSyncOptions) => {
  const existing = existsSync4(uri) ? readFileSync7(uri, options) : void 0;
  const desired = lines.join(CROSS_PLATFORM_NEWLINE);
  if (existing !== desired) writeFileSync2(uri, desired, options);
};

// src/lib/file/tryReadFileSync.ts
import { existsSync as existsSync5, readFileSync as readFileSync8 } from "node:fs";
var tryReadFileSync = (uri, options = defaultReadFileSyncOptions) => {
  return existsSync5(uri) ? readFileSync8(uri, options) : void 0;
};

// src/lib/fillTemplate.ts
function fillTemplate(template, data) {
  return template.replaceAll(/\{\{(.*?)\}\}/g, (_, key) => data[key.trim()] ?? "");
}

// src/lib/generateIgnoreFiles.ts
import chalk8 from "chalk";

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

// src/lib/generateIgnoreFiles.ts
var localeCompare = (a, b) => a.localeCompare(b);
var mergeEntries = (a, b) => [...union(a, b)].toSorted(localeCompare);
var generateIgnoreFiles = (filename, pkg) => {
  console.log(chalk8.green(`Generate ${filename} Files`));
  const cwd = INIT_CWD();
  const pm = getPackageManager();
  const singleWorkspace = pkg ? pm.findWorkspace(pkg) : void 0;
  const workspaces = singleWorkspace ? [singleWorkspace] : pm.listWorkspaces();
  const readEntries = (location) => readNonEmptyLines(`${location}/${filename}`);
  const writeEntries = (location, entries) => writeLines(`${location}/${filename}`, entries);
  const results = workspaces.map(({ location, name }) => {
    try {
      writeEntries(location, mergeEntries(readEntries(cwd), readEntries(location)));
      return 0;
    } catch (ex) {
      const error = ex;
      console.error(`Generate ${filename} Files [${name}] [${error.message}]`);
      return 1;
    }
  });
  const succeeded = results.every((result) => result === 0);
  return succeeded ? 0 : 1;
};

// src/lib/gitConfig.ts
import { execFileSync } from "node:child_process";
function getGitConfig(key) {
  try {
    const value = execFileSync("git", ["config", "--get", key], {
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"]
    }).trim();
    return value.length > 0 ? value : void 0;
  } catch {
    return void 0;
  }
}
function getGitConfigBool(key) {
  try {
    const value = execFileSync("git", ["config", "--bool", "--get", key], {
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"]
    }).trim();
    if (value === "true") return true;
    if (value === "false") return false;
    return void 0;
  } catch {
    return void 0;
  }
}
function setGitConfig(key, value) {
  execFileSync("git", ["config", key, value], { stdio: "inherit" });
}

// src/lib/gitignoreTemplate.ts
import { readFileSync as readFileSync9 } from "node:fs";
import { createRequire as createRequire3 } from "node:module";
import PATH5 from "node:path";
var require4 = createRequire3(import.meta.url);
var packageRoot2 = PATH5.dirname(require4.resolve("@xylabs/toolchain/package.json"));
var templatesDir2 = PATH5.resolve(packageRoot2, "templates", "gitignore");
var gitignoreTemplate = () => readFileSync9(PATH5.resolve(templatesDir2, "template.gitignore"), "utf8");

// 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 chalk9 from "chalk";
import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
import deepmerge from "deepmerge";
var config;
var rootConfigPath;
var workspaceConfigCache = /* @__PURE__ */ new Map();
var deprecationWarned = /* @__PURE__ */ new Set();
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function createExplorer() {
  return cosmiconfig("xy", { cache: true, loaders: { ".ts": TypeScriptLoader() } });
}
var loadConfig = async (params) => {
  if (config === void 0) {
    const cosmicConfigResult = await createExplorer().search();
    config = cosmicConfigResult?.config ?? {};
    rootConfigPath = cosmicConfigResult?.filepath;
    const configFilePath = cosmicConfigResult?.filepath;
    if (configFilePath !== void 0) {
      console.log(chalk9.green(`Loaded config from ${configFilePath}`));
      if (config.verbose) {
        console.log(chalk9.gray(`${JSON.stringify(config, null, 2)}`));
      }
    }
  }
  return deepmerge(config, params ?? {});
};
async function loadWorkspaceConfig(workspaceDir) {
  const cached = workspaceConfigCache.get(workspaceDir);
  if (cached !== void 0) return cached;
  const result = await createExplorer().search(workspaceDir);
  if (!result || result.filepath === rootConfigPath) {
    workspaceConfigCache.set(workspaceDir, {});
    return {};
  }
  const wsConfig = result.config ?? {};
  workspaceConfigCache.set(workspaceDir, wsConfig);
  return wsConfig;
}
var DEPRECATED_COMMAND_FIELDS = /* @__PURE__ */ new Set(["deplint", "publint"]);
function resolveCommandField(cfg, commandName, configPath) {
  const commands = cfg.commands;
  const fromCommands = commands?.[commandName];
  const fromTopLevel = cfg[commandName];
  if (fromCommands !== void 0 && typeof fromCommands === "object") {
    return fromCommands;
  }
  if (fromTopLevel !== void 0 && typeof fromTopLevel === "object" && DEPRECATED_COMMAND_FIELDS.has(commandName)) {
    const key = `${configPath ?? "unknown"}:${commandName}`;
    if (!deprecationWarned.has(key)) {
      deprecationWarned.add(key);
      console.warn(chalk9.yellow(
        `[xy] Deprecated: top-level "${commandName}" in ${configPath ?? "xy.config"} \u2014 move to "commands.${commandName}"`
      ));
    }
    return fromTopLevel;
  }
  return {};
}
function mergeRuleConfigs(target, source) {
  if (isRecord(target) && isRecord(source)) {
    return { ...target, ...source };
  }
  return source;
}
function mergeCommandConfig(rootCmd, workspaceCmd, commandName) {
  return deepmerge(rootCmd, workspaceCmd, { customMerge: (key) => commandName === "deplint" && key === "rules" ? mergeRuleConfigs : void 0 });
}
async function loadWorkspaceCommandConfig(workspaceDir, commandName) {
  const root = await loadConfig();
  const rootCmd = resolveCommandField(root, commandName, rootConfigPath);
  const wsConfig = await loadWorkspaceConfig(workspaceDir);
  const wsConfigPath = workspaceConfigCache.has(workspaceDir) ? workspaceDir : void 0;
  const wsCmd = resolveCommandField(wsConfig, commandName, wsConfigPath);
  return mergeCommandConfig(rootCmd, wsCmd, commandName);
}

// src/lib/npmLatestVersion.ts
var REGISTRY_BASE = "https://registry.npmjs.org";
var cache = /* @__PURE__ */ new Map();
async function fetchUncached(packageName2) {
  try {
    const url = `${REGISTRY_BASE}/${encodeURIComponent(packageName2)}/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(packageName2) {
  const existing = cache.get(packageName2);
  if (existing) return existing;
  const pending = fetchUncached(packageName2);
  cache.set(packageName2, pending);
  return pending;
}
function clearLatestPackageVersionCache() {
  cache.clear();
}

// src/lib/packageName.ts
import { readFileSync as readFileSync10 } from "node:fs";
import path from "node:path";
function packageName() {
  if (process.env.npm_package_name) {
    return process.env.npm_package_name;
  }
  try {
    const pkgPath = path.join(INIT_CWD(), "package.json");
    const pkg = JSON.parse(readFileSync10(pkgPath, "utf8"));
    return pkg.name;
  } catch {
    return void 0;
  }
}

// src/lib/parsedPackageJSON.ts
import { readFileSync as readFileSync11 } from "node:fs";
var parsedPackageJSON = (path3) => {
  const pathToPackageJSON = path3 ?? process.env.npm_package_json ?? "";
  const packageJSON = readFileSync11(pathToPackageJSON).toString();
  return JSON.parse(packageJSON);
};

// src/lib/pnpmConfig/readMinReleaseAge.ts
import { existsSync as existsSync6, readFileSync as readFileSync12 } from "node:fs";
import os from "node:os";
import PATH6 from "node:path";
import * as yaml from "yaml";
function emptySource() {
  return {
    excludeSet: void 0,
    ignoreMissingTime: void 0,
    minutes: void 0,
    strict: void 0
  };
}
function coerceNumber(value) {
  if (typeof value === "number" && Number.isFinite(value)) return value;
  if (typeof value === "string" && value.trim() !== "") {
    const n = Number(value);
    return Number.isFinite(n) ? n : void 0;
  }
  return void 0;
}
function coerceBoolean(value) {
  if (typeof value === "boolean") return value;
  if (typeof value === "string") {
    const lower = value.trim().toLowerCase();
    if (lower === "true") return true;
    if (lower === "false") return false;
  }
  return void 0;
}
function coerceStringArray(value) {
  if (Array.isArray(value)) {
    return value.filter((v) => typeof v === "string" && v.length > 0);
  }
  if (typeof value === "string") {
    return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
  }
  return void 0;
}
function readWorkspaceYaml(filePath) {
  const out = emptySource();
  if (!existsSync6(filePath)) return out;
  let parsed;
  try {
    parsed = yaml.parse(readFileSync12(filePath, "utf8"));
  } catch {
    return out;
  }
  if (parsed === null || typeof parsed !== "object") return out;
  const obj = parsed;
  out.minutes = coerceNumber(obj.minimumReleaseAge);
  out.excludeSet = coerceStringArray(obj.minimumReleaseAgeExclude);
  out.ignoreMissingTime = coerceBoolean(obj.minimumReleaseAgeIgnoreMissingTime);
  out.strict = coerceBoolean(obj.minimumReleaseAgeStrict);
  return out;
}
function applyNpmrcKey(out, key, value) {
  switch (key) {
    case "minimum-release-age":
    case "minimumreleaseage": {
      const n = coerceNumber(value);
      if (n !== void 0) out.minutes = n;
      return;
    }
    case "minimum-release-age-exclude":
    case "minimumreleaseageexclude": {
      const arr = coerceStringArray(value);
      if (arr !== void 0) out.excludeSet = arr;
      return;
    }
    case "minimum-release-age-ignore-missing-time":
    case "minimumreleaseageignoremissingtime": {
      const b = coerceBoolean(value);
      if (b !== void 0) out.ignoreMissingTime = b;
      return;
    }
    case "minimum-release-age-strict":
    case "minimumreleaseagestrict": {
      const b = coerceBoolean(value);
      if (b !== void 0) out.strict = b;
    }
  }
}
function readNpmrc(filePath) {
  const out = emptySource();
  if (!existsSync6(filePath)) return out;
  let text;
  try {
    text = readFileSync12(filePath, "utf8");
  } catch {
    return out;
  }
  for (const rawLine of text.split("\n")) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#") || line.startsWith(";")) continue;
    const eq = line.indexOf("=");
    if (eq === -1) continue;
    const key = line.slice(0, eq).trim().toLowerCase();
    const value = line.slice(eq + 1).trim().replaceAll(/^["']|["']$/g, "");
    applyNpmrcKey(out, key, value);
  }
  return out;
}
function merge(primary, fallback) {
  return {
    minutes: primary.minutes ?? fallback.minutes,
    excludeSet: primary.excludeSet ?? fallback.excludeSet,
    ignoreMissingTime: primary.ignoreMissingTime ?? fallback.ignoreMissingTime,
    strict: primary.strict ?? fallback.strict
  };
}
function readMinReleaseAgeConfig(cwd) {
  const workspace = readWorkspaceYaml(PATH6.resolve(cwd, "pnpm-workspace.yaml"));
  const projectNpmrc = readNpmrc(PATH6.resolve(cwd, ".npmrc"));
  const userNpmrc = readNpmrc(PATH6.resolve(os.homedir(), ".npmrc"));
  const merged = merge(merge(workspace, projectNpmrc), userNpmrc);
  return {
    minutes: merged.minutes,
    exclude: merged.excludeSet ?? [],
    ignoreMissingTime: merged.ignoreMissingTime ?? true,
    strict: merged.strict ?? true
  };
}

// 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 jsonMode = false;
var strictMode = false;
var originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
function setJsonMode(enabled) {
  if (jsonMode === enabled) return;
  jsonMode = enabled;
  if (enabled && !originalStdoutWrite) {
    originalStdoutWrite = process.stdout.write.bind(process.stdout);
    const stderrWrite = process.stderr.write.bind(process.stderr);
    process.stdout.write = stderrWrite;
    process.on("exit", emitFallbackEnvelope);
  }
}
function isStrictMode() {
  return strictMode || process.env.XY_STRICT === "1";
}
function setStrictMode(enabled) {
  strictMode = enabled;
  if (enabled) {
    process.env.XY_STRICT = "1";
  }
}
function setCurrentCommand(name) {
  currentCommand = name;
  startTime = performance.now();
  envelopeEmitted = false;
}
function emitJson(envelope) {
  if (envelopeEmitted) return;
  envelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (originalStdoutWrite) {
    originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}
function emitFallbackEnvelope() {
  if (envelopeEmitted) return;
  const raw = process.exitCode ?? 0;
  const code = typeof raw === "number" ? raw : Number(raw) || 0;
  emitJson({
    command: currentCommand,
    durationMs: Math.round(performance.now() - startTime),
    errorCount: code === 0 ? 0 : 1,
    exitCode: code,
    schemaVersion: 1,
    success: code === 0,
    warningCount: 0
  });
}
function xyLog(...args) {
  if (jsonMode) {
    process.stderr.write(args.map((arg) => typeof arg === "string" ? arg : String(arg)).join(" ") + "\n");
  } else {
    console.log(...args);
  }
}
function resetReporterForTesting() {
  if (originalStdoutWrite) {
    process.stdout.write = originalStdoutWrite;
    originalStdoutWrite = void 0;
  }
  jsonMode = false;
  envelopeEmitted = false;
  currentCommand = "unknown";
  startTime = 0;
}

// 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 as readdirSync2, readFileSync as readFileSync13 } from "node:fs";
import { createRequire as createRequire4 } from "node:module";
import PATH7 from "node:path";
var require5 = createRequire4(import.meta.url);
var packageRoot3 = PATH7.dirname(require5.resolve("@xylabs/toolchain/package.json"));
var repoTemplatesDir = PATH7.resolve(packageRoot3, "templates", "repo");
function collectFiles(dir, prefix) {
  const results = [];
  for (const entry of readdirSync2(dir, { withFileTypes: true })) {
    const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isDirectory()) {
      results.push(...collectFiles(PATH7.resolve(dir, entry.name), rel));
    } else {
      results.push({
        content: readFileSync13(PATH7.resolve(dir, entry.name), "utf8"),
        relativePath: rel
      });
    }
  }
  return results;
}
function loadRepoTemplateFiles(template, section) {
  const dir = PATH7.resolve(repoTemplatesDir, template, section);
  return collectFiles(dir, "");
}
function listRepoTemplates() {
  return readdirSync2(repoTemplatesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
}

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

// src/lib/runSteps.ts
import { existsSync as existsSync7 } from "node:fs";
import chalk11 from "chalk";
var packageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
var runSteps = (name, steps, exitOnFail = true, messages) => {
  return safeExit(() => {
    const pkgName = packageName();
    console.log(chalk11.green(`${name} [${pkgName}]`));
    let totalStatus = 0;
    for (const [i, [command, args, config2]] of steps.entries()) {
      if (messages?.[i]) {
        console.log(chalk11.gray(messages?.[i]));
      }
      const argList = Array.isArray(args) ? args : args.split(" ");
      if (command === "node" && !existsSync7(argList[0])) {
        throw new Error(`File not found [${argList[0]}]`);
      }
      if (packageManagers.has(command) && !ensurePackageManagerInstalled(command, { operation: `${name}: ${command} ${Array.isArray(args) ? args.join(" ") : args}`.trim() })) {
        checkResult(name, 1, "error", exitOnFail);
        totalStatus += 1;
        continue;
      }
      const status = spawnSync(command, Array.isArray(args) ? args : args.split(" "), {
        ...config2,
        encoding: "utf8",
        // Merge per-step env on top so callers can supply overrides
        // (e.g. NODE_OPTIONS=--max-old-space-size=...); process.env still
        // seeds the common case so FORCE_COLOR etc. survive.
        env: {
          FORCE_COLOR: "3",
          ...process.env,
          ...config2?.env
        },
        stdio: isJsonMode() ? ["inherit", 2, 2] : "inherit"
      }).status ?? 0;
      checkResult(name, status, "error", exitOnFail);
      totalStatus += status ?? 0;
    }
    return totalStatus;
  }, !!exitOnFail);
};

// src/lib/runStepsAsync.ts
import { existsSync as existsSync8 } from "node:fs";
import chalk12 from "chalk";
var packageManagers2 = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
var runStepAsync = (name, step, exitOnFail = true, message) => {
  return new Promise((resolve) => {
    const [command, args, config2] = step;
    if (message) {
      console.log(chalk12.gray(message));
    }
    const argList = Array.isArray(args) ? args : args.split(" ");
    if (command === "node" && !existsSync8(argList[0])) {
      throw new Error(`File not found [${argList[0]}]`);
    }
    if (packageManagers2.has(command) && !ensurePackageManagerInstalled(command, { operation: `${name}: ${command} ${Array.isArray(args) ? args.join(" ") : args}`.trim() })) {
      checkResult(name, 1, "error", exitOnFail);
      resolve(1);
      return;
    }
    spawn(command, Array.isArray(args) ? args : args.split(" "), {
      ...config2,
      env: { FORCE_COLOR: "3", ...process.env },
      stdio: isJsonMode() ? ["inherit", 2, 2] : "inherit"
    }).on("close", (code) => {
      if (code) {
        console.error(
          chalk12.red(
            `Command Exited With Non-Zero Result [${chalk12.gray(code)}] | ${chalk12.yellow(command)} ${chalk12.white(
              Array.isArray(args) ? args.join(" ") : args
            )}`
          )
        );
        checkResult(name, code, "error", exitOnFail);
        resolve(code);
      } else {
        resolve(0);
      }
    });
  });
};
var runStepsAsync = async (name, steps, exitOnFail = true, messages) => {
  return await safeExitAsync(async () => {
    const pkgName = packageName();
    console.log(chalk12.green(`${name} [${pkgName}]`));
    let result = 0;
    for (const [i, step] of steps.entries()) {
      result += await runStepAsync(name, step, exitOnFail, messages?.[i]);
    }
    return result;
  });
};

// src/lib/runXy.ts
var runXy = (command) => {
  const pm = getPackageManager();
  return runSteps(
    `XY [${command}]`,
    [pm.runXy([command, ...process.argv.filter((value, index) => index > 1 ? value : void 0)])]
  );
};

// src/lib/runXyWithWarning.ts
import chalk13 from "chalk";
var runXyWithWarning = (command) => {
  const pm = getPackageManager();
  const commandString = `${pm.command} ${command}`;
  const commandXyString = `${pm.command} xy ${command}`;
  console.warn(chalk13.yellow(`WARNING: [${chalk13.white(commandString)}] is deprecated for XY Labs Scripts.`));
  console.warn(chalk13.gray(`Did you mean [${chalk13.magenta(commandXyString)}]?`));
  return 1;
};

// src/lib/secure/classify.ts
var DAY_MS = 24 * 60 * 60 * 1e3;
function classifySecureAge(publishedAt, now = /* @__PURE__ */ new Date()) {
  if (!publishedAt || Number.isNaN(publishedAt.getTime())) {
    return { level: "gray" };
  }
  const ageDays = Math.max(0, (now.getTime() - publishedAt.getTime()) / DAY_MS);
  if (ageDays < 3) return { ageDays, level: "red" };
  if (ageDays < 10) return { ageDays, level: "yellow" };
  if (ageDays < 365) return { ageDays, level: "green" };
  return { ageDays, level: "purple" };
}
function classifySecureDownloads(downloads) {
  if (downloads === void 0 || !Number.isFinite(downloads)) return "gray";
  if (downloads < 1e3) return "red";
  if (downloads < 1e4) return "yellow";
  return "green";
}

// src/lib/secure/collectDeclaredDependencies.ts
import { existsSync as existsSync9, readFileSync as readFileSync14 } from "node:fs";
import PATH8 from "node:path";
var DEP_FIELDS = ["dependencies", "devDependencies"];
var LOCAL_PROTOCOLS = ["workspace:", "file:", "link:", "portal:"];
function readPackageJson(filePath) {
  if (!existsSync9(filePath)) return void 0;
  try {
    return JSON.parse(readFileSync14(filePath, "utf8"));
  } catch {
    return void 0;
  }
}
function collectSecurePackageTargets(cwd, workspaces) {
  const targets = [];
  const seenLocations = /* @__PURE__ */ new Set();
  const root = readPackageJson(PATH8.resolve(cwd, "package.json"));
  if (root?.name) {
    targets.push({ location: ".", name: root.name });
    seenLocations.add(".");
  }
  for (const workspace of workspaces) {
    const normalizedLocation = workspace.location || ".";
    if (seenLocations.has(normalizedLocation)) continue;
    targets.push({ location: normalizedLocation, name: workspace.name });
    seenLocations.add(normalizedLocation);
  }
  return targets.toSorted((a, b) => a.location.localeCompare(b.location));
}
function isLocalSecureDependency(name, range, localPackageNames) {
  return localPackageNames.has(name) || LOCAL_PROTOCOLS.some((protocol) => range.startsWith(protocol));
}
function collectSecureDeclaredDependencies(cwd, targets, localPackageNames) {
  const declared = [];
  for (const target of targets) {
    const pkgPath = PATH8.resolve(cwd, target.location, "package.json");
    const pkg = readPackageJson(pkgPath);
    if (!pkg) continue;
    for (const depType of DEP_FIELDS) {
      const deps = pkg[depType];
      if (!deps) continue;
      for (const [name, range] of Object.entries(deps)) {
        if (typeof range !== "string") continue;
        if (isLocalSecureDependency(name, range, localPackageNames)) continue;
        declared.push({
          depType,
          name,
          packageLocation: target.location,
          packageName: target.name,
          range
        });
      }
    }
  }
  return declared.toSorted((a, b) => {
    return a.name.localeCompare(b.name) || a.packageLocation.localeCompare(b.packageLocation) || a.depType.localeCompare(b.depType);
  });
}

// src/lib/secure/fetchPackageSecurityMetadata.ts
var REGISTRY_BASE2 = "https://registry.npmjs.org";
var DOWNLOADS_BASE = "https://api.npmjs.org/downloads/point/last-week";
var BULK_DOWNLOADS_CHUNK_SIZE = 100;
var SCOPED_DOWNLOADS_CONCURRENCY = 4;
var manifestCache = /* @__PURE__ */ new Map();
var downloadsCache = /* @__PURE__ */ new Map();
function packageUrlSegment(packageName2) {
  return encodeURIComponent(packageName2);
}
function isScopedPackageName(packageName2) {
  return packageName2.startsWith("@");
}
function chunks(items, size) {
  const result = [];
  for (let index = 0; index < items.length; index += size) {
    result.push(items.slice(index, index + size));
  }
  return result;
}
async function fetchManifestUncached(packageName2) {
  try {
    const res = await fetch(`${REGISTRY_BASE2}/${packageUrlSegment(packageName2)}`, { headers: { Accept: "application/json" } });
    if (!res.ok) return void 0;
    const data = await res.json();
    return {
      distTags: data["dist-tags"] ?? {},
      time: data.time ?? {},
      versions: Object.keys(data.versions ?? {})
    };
  } catch {
    return void 0;
  }
}
function fetchSecureRegistryManifest(packageName2) {
  const cached = manifestCache.get(packageName2);
  if (cached) return cached;
  const pending = fetchManifestUncached(packageName2);
  manifestCache.set(packageName2, pending);
  return pending;
}
async function fetchDownloadsUncached(packageName2) {
  try {
    const res = await fetch(`${DOWNLOADS_BASE}/${packageUrlSegment(packageName2)}`);
    if (!res.ok) return void 0;
    const data = await res.json();
    return typeof data.downloads === "number" ? data.downloads : void 0;
  } catch {
    return void 0;
  }
}
function fetchSecureWeeklyDownloads(packageName2) {
  const cached = downloadsCache.get(packageName2);
  if (cached) return cached;
  const pending = fetchDownloadsUncached(packageName2);
  downloadsCache.set(packageName2, pending);
  return pending;
}
async function fetchBulkWeeklyDownloads(packageNames) {
  const results = /* @__PURE__ */ new Map();
  if (packageNames.length === 0) return results;
  try {
    const packageSegment = packageNames.map(packageUrlSegment).join(",");
    const res = await fetch(`${DOWNLOADS_BASE}/${packageSegment}`);
    if (!res.ok) {
      await runWithConcurrency(packageNames, SCOPED_DOWNLOADS_CONCURRENCY, async (name) => {
        results.set(name, await fetchSecureWeeklyDownloads(name));
      });
      return results;
    }
    const data = await res.json();
    for (const name of packageNames) {
      const downloads = data[name]?.downloads;
      results.set(name, typeof downloads === "number" ? downloads : void 0);
    }
  } catch {
    await runWithConcurrency(packageNames, SCOPED_DOWNLOADS_CONCURRENCY, async (name) => {
      results.set(name, await fetchSecureWeeklyDownloads(name));
    });
  }
  return results;
}
async function fetchAllSecureWeeklyDownloads(packageNames, concurrency = SCOPED_DOWNLOADS_CONCURRENCY) {
  const uniqueNames = [...new Set(packageNames)].toSorted();
  const unscopedNames = uniqueNames.filter((name) => !isScopedPackageName(name));
  const scopedNames = uniqueNames.filter(isScopedPackageName);
  const results = /* @__PURE__ */ new Map();
  await runWithConcurrency(chunks(unscopedNames, BULK_DOWNLOADS_CHUNK_SIZE), 1, async (chunk) => {
    const chunkResults = await fetchBulkWeeklyDownloads(chunk);
    for (const [name, downloads] of chunkResults) {
      results.set(name, downloads);
    }
  });
  const scopedConcurrency = Math.max(1, Math.min(concurrency, SCOPED_DOWNLOADS_CONCURRENCY));
  await runWithConcurrency(scopedNames, scopedConcurrency, async (name) => {
    results.set(name, await fetchSecureWeeklyDownloads(name));
  });
  return results;
}
async function fetchSecurePackageMetadata(packageName2) {
  const [manifest, downloads] = await Promise.all([
    fetchSecureRegistryManifest(packageName2),
    fetchSecureWeeklyDownloads(packageName2)
  ]);
  return { downloads, manifest };
}
async function fetchAllSecurePackageMetadata(packageNames, concurrency = 16) {
  const uniqueNames = [...new Set(packageNames)].toSorted();
  const manifests = /* @__PURE__ */ new Map();
  const results = /* @__PURE__ */ new Map();
  await runWithConcurrency(uniqueNames, concurrency, async (name) => {
    manifests.set(name, await fetchSecureRegistryManifest(name));
  });
  const downloads = await fetchAllSecureWeeklyDownloads(uniqueNames, concurrency);
  for (const name of uniqueNames) {
    results.set(name, {
      downloads: downloads.get(name),
      manifest: manifests.get(name)
    });
  }
  return results;
}
function clearSecurePackageMetadataCache() {
  manifestCache.clear();
  downloadsCache.clear();
}

// src/lib/secure/renderSecurityAudit.ts
import chalk14 from "chalk";
var PURPLE = chalk14.hex("#b26cff");
var COLOR = {
  gray: chalk14.gray,
  green: chalk14.green,
  purple: PURPLE,
  red: chalk14.red,
  yellow: chalk14.yellow
};
function depTypeLabel(depTypes) {
  return depTypes.map((depType) => depType === "dependencies" ? "dep" : "dev").join(",");
}
function formatAge(ageDays) {
  if (ageDays === void 0) return "-";
  if (ageDays < 1) return "<1d";
  if (ageDays < 365) return `${Math.floor(ageDays)}d`;
  return `${(ageDays / 365).toFixed(1)}y`;
}
function formatSecureDownloads(downloads) {
  if (downloads === void 0) return "-";
  if (downloads < 1e3) return `${downloads}`;
  const formatter = new Intl.NumberFormat("en-US", {
    maximumFractionDigits: 1,
    notation: "compact"
  });
  return formatter.format(downloads).toLowerCase();
}
function pad(raw, colored, width) {
  return colored + " ".repeat(Math.max(0, width - raw.length));
}
var columns = [
  {
    color: (_row, raw) => chalk14.white(raw),
    header: "Package",
    value: (row) => row.name
  },
  {
    color: (_row, raw) => chalk14.gray(raw),
    header: "Version",
    value: (row) => row.version ?? "-"
  },
  {
    color: (_row, raw) => chalk14.gray(raw),
    header: "Type",
    value: (row) => depTypeLabel(row.depTypes)
  },
  {
    color: (_row, raw) => chalk14.gray(raw),
    header: "Decls",
    value: (row) => `${row.declarationCount}`
  },
  {
    color: (row, raw) => COLOR[row.ageLevel](raw),
    header: "Age",
    value: (row) => formatAge(row.ageDays)
  },
  {
    color: (row, raw) => COLOR[row.downloadsLevel](raw),
    header: "Downloads/wk",
    value: (row) => formatSecureDownloads(row.downloads)
  }
];
function renderSecurityAuditRows(rows) {
  if (rows.length === 0) {
    console.log(chalk14.green("Secure: no external direct dependencies found."));
    return;
  }
  const widths = columns.map((column) => {
    let width = column.header.length;
    for (const row of rows) {
      width = Math.max(width, column.value(row).length);
    }
    return width;
  });
  console.log(chalk14.green("Secure: direct dependency audit"));
  const header = columns.map((column, index) => chalk14.bold(column.header.padEnd(widths[index]))).join("  ");
  console.log(header);
  console.log(chalk14.gray("\u2500".repeat(widths.reduce((total, width) => total + width + 2, -2))));
  for (const row of rows) {
    const line = columns.map((column, index) => {
      const raw = column.value(row);
      return pad(raw, column.color(row, raw), widths[index]);
    }).join("  ");
    console.log(line);
  }
  const redCount = rows.filter((row) => row.red).length;
  if (redCount > 0) {
    console.warn(chalk14.red(`Secure: ${redCount} red finding${redCount === 1 ? "" : "s"} found.`));
  } else {
    console.log(chalk14.green("Secure: no red findings."));
  }
}

// src/lib/secure/runSecurityAudit.ts
import chalk15 from "chalk";
import semver2 from "semver";
function parseDate(value) {
  if (!value) return void 0;
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? void 0 : date;
}
function canUseInstalledVersion(version, range) {
  if (!semver2.valid(version)) return false;
  const validRange = semver2.validRange(range);
  if (!validRange) return true;
  return semver2.satisfies(version, validRange, { includePrerelease: range.includes("-") });
}
function resolveSecureDependencyVersion(dep, installedVersion, manifest) {
  if (installedVersion && canUseInstalledVersion(installedVersion, dep.range)) {
    return installedVersion;
  }
  if (!manifest) return void 0;
  const distTagVersion = manifest.distTags[dep.range];
  if (distTagVersion) return distTagVersion;
  const validRange = semver2.validRange(dep.range);
  if (!validRange) return void 0;
  return semver2.maxSatisfying(
    manifest.versions.filter((version) => semver2.valid(version) !== null),
    validRange,
    { includePrerelease: dep.range.includes("-") }
  ) ?? void 0;
}
function buildSecurityAuditRows(declaredDeps, installedVersions, metadata, now = /* @__PURE__ */ new Date()) {
  const groups = /* @__PURE__ */ new Map();
  for (const dep of declaredDeps) {
    const packageMetadata = metadata.get(dep.name);
    const version = resolveSecureDependencyVersion(dep, installedVersions.get(dep.name), packageMetadata?.manifest);
    const key = `${dep.name}\0${version ?? ""}`;
    let group = groups.get(key);
    if (!group) {
      group = {
        declarations: [],
        depTypes: /* @__PURE__ */ new Set(),
        name: dep.name,
        packageLocations: /* @__PURE__ */ new Set(),
        packageNames: /* @__PURE__ */ new Set(),
        version
      };
      groups.set(key, group);
    }
    group.declarations.push(dep);
    group.depTypes.add(dep.depType);
    group.packageLocations.add(dep.packageLocation);
    group.packageNames.add(dep.packageName);
  }
  return [...groups.values()].map((group) => {
    const packageMetadata = metadata.get(group.name);
    const publishedAt = parseDate(group.version ? packageMetadata?.manifest?.time[group.version] : void 0);
    const age = classifySecureAge(publishedAt, now);
    const downloadsLevel = classifySecureDownloads(packageMetadata?.downloads);
    return {
      ageDays: age.ageDays,
      ageLevel: age.level,
      declarationCount: group.declarations.length,
      depTypes: [...group.depTypes].toSorted(),
      downloads: packageMetadata?.downloads,
      downloadsLevel,
      name: group.name,
      packageLocations: [...group.packageLocations].toSorted(),
      packageNames: [...group.packageNames].toSorted(),
      red: age.level === "red" || downloadsLevel === "red",
      version: group.version
    };
  }).toSorted((a, b) => {
    return a.name.localeCompare(b.name) || (a.version ?? "").localeCompare(b.version ?? "");
  });
}
function resolveTargetPackages(targets, pkg) {
  if (pkg === void 0) return targets;
  const target = resolveWorkspace(targets, pkg);
  return target ? [target] : [];
}
async function runSecurityAudit(pm, options = {}) {
  const cwd = options.cwd ?? INIT_CWD();
  const allTargets = collectSecurePackageTargets(cwd, pm.listWorkspaces());
  const targetPackages = resolveTargetPackages(allTargets, options.pkg);
  if (targetPackages.length === 0) {
    console.error(chalk15.red(`Package not found: ${options.pkg}`));
    return 1;
  }
  const localPackageNames = new Set(allTargets.map((target) => target.name));
  const declaredDeps = collectSecureDeclaredDependencies(cwd, targetPackages, localPackageNames);
  if (options.verbose) {
    console.log(chalk15.gray(`Secure: found ${declaredDeps.length} external direct dependency declarations`));
  }
  const packageNames = [...new Set(declaredDeps.map((dep) => dep.name))].toSorted();
  const fetchMetadata = options.fetchMetadata ?? fetchAllSecurePackageMetadata;
  const metadata = await fetchMetadata(packageNames, options.concurrency ?? 16);
  const rows = buildSecurityAuditRows(
    declaredDeps,
    pm.listInstalledVersions(),
    metadata,
    options.now
  );
  const render = options.render ?? renderSecurityAuditRows;
  render(rows);
  return rows.some((row) => row.red) ? 1 : 0;
}

// src/lib/tryRunLocalScript.ts
import { readFileSync as readFileSync15 } from "node:fs";
import PATH9 from "node:path";
import chalk16 from "chalk";
function tryRunLocalScript(commandName) {
  if (process.env.XY_LOCAL_SCRIPT === "1") return void 0;
  const rootPkgPath = PATH9.resolve(process.cwd(), "package.json");
  let rootPkg;
  try {
    rootPkg = JSON.parse(readFileSync15(rootPkgPath, "utf8"));
  } catch {
    return void 0;
  }
  if (!rootPkg.scripts?.[commandName]) return void 0;
  const extraArgs = process.argv.slice(process.argv.indexOf(commandName) + 1);
  console.log(chalk16.blue(`Delegating "${commandName}" to local script`));
  const pm = getPackageManager();
  const result = spawnPackageManagerSync(pm.name, ["run", commandName, ...extraArgs], {
    cwd: process.cwd(),
    context: { operation: `Run local "${commandName}" script with ${pm.command}` },
    encoding: "utf8",
    env: {
      FORCE_COLOR: "3",
      ...process.env,
      XY_LOCAL_SCRIPT: "1"
    },
    stdio: "inherit"
  });
  return result.status ?? 1;
}

// src/lib/updo/applyUpdates.ts
import { readFileSync as readFileSync16, writeFileSync as writeFileSync3 } from "node:fs";
import PATH10 from "node:path";
import chalk17 from "chalk";
import semver3 from "semver";
function isSimpleRange(range) {
  const trimmed = range.trim();
  if (trimmed.startsWith("^") || trimmed.startsWith("~")) return true;
  return semver3.valid(trimmed) !== null;
}
function applyToBag(bag, updateMap) {
  if (!bag) return false;
  let changed = false;
  for (const name of Object.keys(bag)) {
    const update = updateMap.get(name);
    if (!update) continue;
    if (bag[name] !== update.targetRange) {
      bag[name] = update.targetRange;
      changed = true;
    }
  }
  return changed;
}
function applyToPeerBag(pkg, updateMap) {
  const peer = pkg.peerDependencies;
  if (!peer) return false;
  let changed = false;
  for (const name of Object.keys(peer)) {
    const update = updateMap.get(name);
    if (!update) continue;
    if (pkg.dependencies?.[name] !== void 0) continue;
    if (pkg.devDependencies?.[name] !== void 0) continue;
    if (!isSimpleRange(peer[name])) continue;
    if (peer[name] !== update.targetRange) {
      peer[name] = update.targetRange;
      changed = true;
    }
  }
  return changed;
}
function applyToWorkspace(pkgPath, updateMap) {
  let content;
  try {
    content = readFileSync16(pkgPath, "utf8");
  } catch {
    return false;
  }
  const pkg = JSON.parse(content);
  const depsChanged = applyToBag(pkg.dependencies, updateMap);
  const devDepsChanged = applyToBag(pkg.devDependencies, updateMap);
  const peerChanged = applyToPeerBag(pkg, updateMap);
  const changed = depsChanged || devDepsChanged || peerChanged;
  if (changed) {
    writeFileSync3(pkgPath, `${JSON.stringify(pkg, null, 2)}
`);
  }
  return changed;
}
function applyUpdates(cwd, workspaces, updates) {
  const updateMap = new Map(updates.map((u) => [u.name, u]));
  let modified = 0;
  for (const ws of workspaces) {
    const pkgPath = PATH10.resolve(cwd, ws.location, "package.json");
    if (applyToWorkspace(pkgPath, updateMap)) {
      modified++;
      console.log(chalk17.gray(`  Updated ${ws.name}`));
    }
  }
  return modified;
}

// src/lib/updo/collectWorkspaceDeps.ts
import { readFileSync as readFileSync17 } from "node:fs";
import PATH11 from "node:path";
var DEP_FIELDS2 = ["dependencies", "devDependencies", "peerDependencies"];
function collectWorkspaceDeps(cwd, workspaces, workspaceNames) {
  const declaredDeps = [];
  for (const ws of workspaces) {
    const pkgPath = PATH11.resolve(cwd, ws.location, "package.json");
    let pkg;
    try {
      pkg = JSON.parse(readFileSync17(pkgPath, "utf8"));
    } catch {
      continue;
    }
    for (const depField of DEP_FIELDS2) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [name, range] of Object.entries(deps)) {
        if (workspaceNames.has(name)) continue;
        if (range.startsWith("workspace:")) continue;
        declaredDeps.push({
          depType: depField,
          name,
          range,
          workspaceLocation: ws.location,
          workspaceName: ws.name
        });
      }
    }
  }
  return declaredDeps;
}

// src/lib/updo/fetchRegistryInfo.ts
import fs3 from "node:fs";
import os2 from "node:os";
import path2 from "node:path";
var REGISTRY_BASE3 = "https://registry.npmjs.org";
function parseNpmrc(filePath, into) {
  let text;
  try {
    text = fs3.readFileSync(filePath, "utf8");
  } catch {
    return;
  }
  for (const rawLine of text.split("\n")) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#") || line.startsWith(";")) continue;
    const tokenMatch = /^\/\/([^:]+?):_authToken=(.+)$/.exec(line);
    if (tokenMatch) {
      const hostPath = tokenMatch[1];
      const token = tokenMatch[2].trim().replaceAll(/^["']|["']$/g, "");
      const host = hostPath.split("/")[0];
      into.tokens.set(`https://${host}`, token);
      continue;
    }
    const scopeMatch = /^(@[^:]+):registry=(.+)$/.exec(line);
    if (scopeMatch) {
      into.scopeRegistries.set(scopeMatch[1], scopeMatch[2].trim().replace(/\/$/, ""));
    }
  }
}
var cachedConfig;
function loadNpmrcConfig() {
  if (cachedConfig) return cachedConfig;
  const config2 = { scopeRegistries: /* @__PURE__ */ new Map(), tokens: /* @__PURE__ */ new Map() };
  parseNpmrc(path2.join(INIT_CWD(), ".npmrc"), config2);
  parseNpmrc(path2.join(os2.homedir(), ".npmrc"), config2);
  cachedConfig = config2;
  return config2;
}
function resolveRegistry(packageName2, config2) {
  if (packageName2.startsWith("@")) {
    const scope = packageName2.split("/")[0];
    const scoped = config2.scopeRegistries.get(scope);
    if (scoped) return scoped;
  }
  return REGISTRY_BASE3;
}
async function fetchRegistryInfo(packageName2, options = {}) {
  try {
    const config2 = loadNpmrcConfig();
    const registry = resolveRegistry(packageName2, config2);
    const url = `${registry}/${packageName2}`;
    const headers = {};
    if (!options.wantTimes) {
      headers.Accept = "application/vnd.npm.install-v1+json";
    }
    const token = config2.tokens.get(registry);
    if (token) headers.Authorization = `Bearer ${token}`;
    const res = await fetch(url, { headers });
    if (!res.ok) {
      return { distTags: {}, versions: [] };
    }
    const data = await res.json();
    const versionKeys = Object.keys(data.versions ?? {});
    const result = {
      distTags: data["dist-tags"] ?? {},
      versions: versionKeys
    };
    if (options.wantTimes && data.time) {
      const publishTimes = {};
      for (const v of versionKeys) {
        const t = data.time[v];
        if (typeof t === "string") publishTimes[v] = t;
      }
      result.publishTimes = publishTimes;
    }
    return result;
  } catch {
    return { distTags: {}, versions: [] };
  }
}
async function fetchAllRegistryInfo(packageNames, options = {}) {
  const results = /* @__PURE__ */ new Map();
  const concurrency = options.concurrency ?? 16;
  let completed = 0;
  const total = packageNames.length;
  await runWithConcurrency(packageNames, concurrency, async (name) => {
    results.set(name, await fetchRegistryInfo(name, { wantTimes: options.wantTimes }));
    completed++;
    if (completed % 25 === 0 || completed === total) {
      process.stderr.write(`\r  Fetched ${completed}/${total} packages...`);
    }
  });
  if (total > 0) {
    process.stderr.write("\n");
  }
  return results;
}

// src/lib/updo/interactiveSelect.ts
import {
  createPrompt,
  ExitPromptError,
  isDownKey,
  isEnterKey,
  isSpaceKey,
  isUpKey,
  useKeypress,
  useRef,
  useState
} from "@inquirer/core";
import chalk18 from "chalk";
var ORANGE = chalk18.hex("#ff8800");
var COLOR2 = {
  gray: chalk18.gray,
  green: chalk18.green,
  orange: ORANGE,
  red: chalk18.red,
  yellow: chalk18.yellow
};
function classifyCell(prefix, column, hasValue) {
  if (!hasValue) return "gray";
  if (column === "next") return "orange";
  if (column === "downgrade") return "red";
  if (prefix === "^") {
    if (column === "patch" || column === "minor") return "green";
    return "yellow";
  }
  if (prefix === "~") {
    if (column === "patch") return "green";
    if (column === "minor") return "yellow";
    return "red";
  }
  if (column === "patch") return "yellow";
  return "red";
}
function pad2(raw, colored, width) {
  return colored + " ".repeat(Math.max(0, width - raw.length));
}
function dot(selected) {
  return selected ? chalk18.green("\u25CF") : chalk18.dim("\u25CB");
}
function valueOf(dep, column) {
  if (column === "patch") return dep.patch;
  if (column === "minor") return dep.minor;
  if (column === "major") return dep.major;
  if (column === "downgrade") return dep.downgrade;
  return dep.next;
}
function selectionFor(column) {
  if (column === "patch") return 0;
  if (column === "minor") return 1;
  if (column === "major") return 2;
  if (column === "next") return 3;
  return 4;
}
function renderCell(dep, column, selection, width) {
  const value = valueOf(dep, column);
  const raw = value ?? "-";
  const cls = classifyCell(dep.preferredRangePrefix, column, Boolean(value));
  const colored = COLOR2[cls](raw);
  const sel = value ? dot(selection === selectionFor(column)) : " ";
  return `${sel} ${pad2(raw, colored, width)}`;
}
function renderHeader(w, includeNext, includeDowngrade) {
  const parts = [
    "  ",
    chalk18.bold("Package".padEnd(w.name)),
    chalk18.bold("Current".padEnd(w.current)),
    chalk18.bold("  Patch".padEnd(w.patch + 2)),
    chalk18.bold("  Minor".padEnd(w.minor + 2)),
    chalk18.bold("  Major".padEnd(w.major + 2))
  ];
  if (includeNext) parts.push(chalk18.bold("  Next".padEnd(w.next + 2)));
  if (includeDowngrade) parts.push(chalk18.bold("  Down".padEnd(w.downgrade + 2)));
  const header = parts.join("  ");
  const totalWidth = w.name + w.current + w.patch + w.minor + w.major + (includeNext ? w.next + 2 : 0) + (includeDowngrade ? w.downgrade + 2 : 0) + 24;
  return `${header}
${chalk18.gray("\u2500".repeat(totalWidth))}`;
}
function renderRow(dep, selection, active, w, includeNext, includeDowngrade) {
  const pointer = active ? chalk18.cyan("\u276F") : " ";
  const rawName = dep.name;
  const name = active ? chalk18.white(rawName) : chalk18.gray(rawName);
  const rawCurrent = dep.current;
  const current = chalk18.gray(rawCurrent);
  const patch = renderCell(dep, "patch", selection, w.patch);
  const minor = renderCell(dep, "minor", selection, w.minor);
  const major = renderCell(dep, "major", selection, w.major);
  const next = includeNext ? `  ${renderCell(dep, "next", selection, w.next)}` : "";
  const downgrade = includeDowngrade ? `  ${renderCell(dep, "downgrade", selection, w.downgrade)}` : "";
  return `${pointer} ${pad2(rawName, name, w.name)}  ${pad2(rawCurrent, current, w.current)}  ${patch}  ${minor}  ${major}${next}${downgrade}`;
}
function getAvailableSelections(dep) {
  const available = [-1];
  if (dep.patch) available.push(0);
  if (dep.minor) available.push(1);
  if (dep.major) available.push(2);
  if (dep.next) available.push(3);
  if (dep.downgrade) available.push(4);
  return available;
}
var RISK_RANK = {
  green: 0,
  yellow: 1,
  red: 2
};
var CLASS_RANK = {
  green: 0,
  yellow: 1,
  red: 2
};
function defaultSelection(dep, options = {}) {
  const candidates = [
    {
      column: "patch",
      selection: 0,
      value: dep.patch
    },
    {
      column: "minor",
      selection: 1,
      value: dep.minor
    },
    {
      column: "major",
      selection: 2,
      value: dep.major
    }
  ];
  const maxRisk = RISK_RANK[options.risk ?? "green"];
  const eligible = candidates.filter((c) => c.value !== void 0).map((c) => {
    const cls = classifyCell(dep.preferredRangePrefix, c.column, true);
    return { ...c, cls: cls === "orange" || cls === "gray" ? "green" : cls };
  }).filter((c) => CLASS_RANK[c.cls] <= maxRisk);
  if (eligible.length === 0) {
    if (dep.downgrade && maxRisk >= CLASS_RANK.red) return 4;
    return -1;
  }
  if (options.latest) {
    return eligible.toSorted((a, b) => b.selection - a.selection)[0].selection;
  }
  const sorted = eligible.toSorted((a, b) => {
    if (a.cls !== b.cls) return CLASS_RANK[a.cls] - CLASS_RANK[b.cls];
    return a.selection - b.selection;
  });
  return sorted[0].selection;
}
function getTargetVersion(dep, selection) {
  if (selection === 0) return dep.patch;
  if (selection === 1) return dep.minor;
  if (selection === 2) return dep.major;
  if (selection === 3) return dep.next;
  if (selection === 4) return dep.downgrade;
  return void 0;
}
function computeWidths(rows) {
  let name = 7;
  let current = 7;
  let patch = 5;
  let minor = 5;
  let major = 5;
  let next = 4;
  let downgrade = 4;
  for (const dep of rows) {
    name = Math.max(name, dep.name.length);
    current = Math.max(current, dep.current.length);
    patch = Math.max(patch, (dep.patch ?? "-").length);
    minor = Math.max(minor, (dep.minor ?? "-").length);
    major = Math.max(major, (dep.major ?? "-").length);
    next = Math.max(next, (dep.next ?? "-").length);
    downgrade = Math.max(downgrade, (dep.downgrade ?? "-").length);
  }
  return {
    current,
    downgrade,
    major,
    minor,
    name,
    next,
    patch
  };
}
function renderPage(rows, cursor, selections, w, pageSize, includeNext, includeDowngrade) {
  const total = rows.length;
  let start = 0;
  if (total > pageSize) {
    start = Math.max(0, Math.min(cursor - Math.floor(pageSize / 2), total - pageSize));
  }
  const end = Math.min(start + pageSize, total);
  const lines = [];
  for (let i = start; i < end; i++) {
    lines.push(renderRow(rows[i], selections[i], i === cursor, w, includeNext, includeDowngrade));
  }
  if (total > pageSize) {
    if (start > 0) lines.unshift(chalk18.dim("  \u2191 more"));
    if (end < total) lines.push(chalk18.dim("  \u2193 more"));
  }
  return lines.join("\n");
}
var updoPrompt = createPrompt((config2, done) => {
  const {
    rows,
    includeNext,
    latest,
    risk
  } = config2;
  const [cursor, setCursor] = useState(0);
  const [tick, setTick] = useState(0);
  const availableSelectionsRef = useRef(rows.map((r) => getAvailableSelections(r)));
  const selectionsRef = useRef(rows.map((r) => defaultSelection(r, { latest, risk })));
  const widthsRef = useRef(computeWidths(rows));
  useKeypress((key) => {
    if (key.name === "escape" || key.ctrl && key.name === "c") {
      done([]);
      return;
    }
    if (isEnterKey(key)) {
      const results = [];
      for (const [i, dep] of rows.entries()) {
        const version = getTargetVersion(dep, selectionsRef.current[i]);
        if (version) {
          results.push({
            name: dep.name,
            targetRange: version,
            workspaces: dep.workspaces
          });
        }
      }
      done(results);
      return;
    }
    if (isUpKey(key)) {
      setCursor(Math.max(0, cursor - 1));
    } else if (isDownKey(key)) {
      setCursor(Math.min(rows.length - 1, cursor + 1));
    } else if (isSpaceKey(key)) {
      const available = availableSelectionsRef.current[cursor];
      const currentSel = selectionsRef.current[cursor];
      const currentIdx = available.indexOf(currentSel);
      const nextIdx = (currentIdx + 1) % available.length;
      selectionsRef.current[cursor] = available[nextIdx];
      setTick(tick + 1);
    }
  });
  const w = widthsRef.current;
  const includeDowngrade = rows.some((r) => r.downgrade !== void 0);
  const header = renderHeader(w, includeNext, includeDowngrade);
  const page = renderPage(rows, cursor, selectionsRef.current, w, 20, includeNext, includeDowngrade);
  const selectedCount = selectionsRef.current.filter((s) => s >= 0).length;
  const status = chalk18.gray(`  ${selectedCount} selected  \u2191/\u2193 navigate  space cycle version  enter confirm`);
  return `${header}
${page}
${status}`;
});
async function interactiveSelect(deps, options = {}) {
  const updatable = deps.filter((d) => d.updateAvailable);
  if (updatable.length === 0) {
    console.log(chalk18.green("\nAll packages are up to date!"));
    return [];
  }
  if (!process.stdout.isTTY) {
    console.log(chalk18.yellow("Non-interactive environment detected, skipping selection."));
    return [];
  }
  try {
    return await updoPrompt({
      includeNext: options.includeNext ?? false,
      latest: options.latest ?? false,
      risk: options.risk ?? "green",
      rows: updatable
    });
  } catch (error) {
    if (error instanceof ExitPromptError) {
      return [];
    }
    throw error;
  }
}

// src/lib/updo/renderTable.ts
import chalk19 from "chalk";
var ORANGE2 = chalk19.hex("#ff8800");
function classify(prefix, column, hasValue) {
  if (!hasValue) return chalk19.gray;
  if (column === "next") return ORANGE2;
  if (prefix === "^") return column === "major" ? chalk19.yellow : chalk19.green;
  if (prefix === "~") {
    if (column === "patch") return chalk19.green;
    if (column === "minor") return chalk19.yellow;
    return chalk19.red;
  }
  return column === "patch" ? chalk19.yellow : chalk19.red;
}
function bucketValue(column, dep) {
  if (column === "patch") return dep.patch;
  if (column === "minor") return dep.minor;
  if (column === "major") return dep.major;
  return dep.next;
}
function bucketCell(column, dep) {
  const value = bucketValue(column, dep);
  const raw = value ?? "-";
  return classify(dep.preferredRangePrefix, column, Boolean(value))(raw);
}
var columns2 = [
  {
    color: (dep) => dep.updateAvailable ? chalk19.white(dep.name) : chalk19.gray(dep.name),
    header: "Package",
    value: (dep) => dep.name
  },
  {
    color: (dep) => chalk19.gray(dep.current),
    header: "Current",
    value: (dep) => dep.current
  },
  {
    color: (dep) => bucketCell("patch", dep),
    header: "Patch",
    value: (dep) => dep.patch ?? "-"
  },
  {
    color: (dep) => bucketCell("minor", dep),
    header: "Minor",
    value: (dep) => dep.minor ?? "-"
  },
  {
    color: (dep) => bucketCell("major", dep),
    header: "Major",
    value: (dep) => dep.major ?? "-"
  },
  {
    color: (dep) => bucketCell("next", dep),
    header: "Next",
    value: (dep) => dep.next ?? "-"
  },
  {
    color: (dep) => chalk19.gray(`${dep.workspaces.length}`),
    header: "Packages",
    value: (dep) => `${dep.workspaces.length}`
  }
];
function renderTable(deps) {
  const updatable = deps.filter((d) => d.updateAvailable);
  if (updatable.length === 0) {
    console.log(chalk19.green("\nAll packages are up to date!"));
    return;
  }
  const widths = columns2.map((col) => {
    let maxData = 0;
    for (const dep of updatable) {
      maxData = Math.max(maxData, col.value(dep).length);
    }
    return Math.max(col.header.length, maxData);
  });
  const header = columns2.map((col, i) => chalk19.bold(col.header.padEnd(widths[i]))).join("  ");
  console.log(`
${header}`);
  let totalWidth = -2;
  for (const w of widths) {
    totalWidth += w + 2;
  }
  console.log(chalk19.gray("\u2500".repeat(totalWidth)));
  for (const dep of updatable) {
    const row = columns2.map((col, i) => {
      const raw = col.value(dep);
      const colored = col.color(dep);
      const padding = widths[i] - raw.length;
      return colored + " ".repeat(Math.max(0, padding));
    }).join("  ");
    console.log(row);
  }
  console.log();
}

// src/lib/updo/resolveVersions.ts
import picomatch from "picomatch";
import semver4 from "semver";
function parseExclude(pattern) {
  const sep = pattern.indexOf("@", 1);
  if (sep > 0 && sep < pattern.length - 1) {
    const name = pattern.slice(0, sep);
    const version = pattern.slice(sep + 1);
    return { matcher: picomatch(name), version };
  }
  return { matcher: picomatch(pattern), version: void 0 };
}
function isExcluded(name, version, rules) {
  for (const rule of rules) {
    if (!rule.matcher(name)) continue;
    if (rule.version === void 0) return true;
    if (rule.version === version) return true;
    try {
      if (semver4.satisfies(version, rule.version)) return true;
    } catch {
    }
  }
  return false;
}
function buildExcludeRules(patterns) {
  return patterns.map(parseExclude);
}
function isVersionAllowed(name, version, info, filter, rules) {
  if (isExcluded(name, version, rules)) return true;
  const published = info.publishTimes?.[version];
  if (!published) return filter.ignoreMissingTime;
  const publishedMs = Date.parse(published);
  if (Number.isNaN(publishedMs)) return filter.ignoreMissingTime;
  return filter.now - publishedMs >= filter.minutes * 6e4;
}
function filterRegistryInfo(name, info, filter, rules) {
  const allowedVersions = info.versions.filter((v) => isVersionAllowed(name, v, info, filter, rules));
  const allowedSet = new Set(allowedVersions);
  const allowedDistTags = {};
  for (const [tag, version] of Object.entries(info.distTags)) {
    if (allowedSet.has(version)) allowedDistTags[tag] = version;
  }
  return {
    distTags: allowedDistTags,
    publishTimes: info.publishTimes,
    versions: allowedVersions
  };
}
function declaredRangeSatisfiable(declaredRanges, allowedStable) {
  for (const v of allowedStable) {
    for (const range of declaredRanges) {
      try {
        if (semver4.satisfies(v, range)) return true;
      } catch {
      }
    }
  }
  return false;
}
function pickDowngrade(allowedStable, anchor) {
  const below = allowedStable.filter((v) => semver4.lt(v, anchor));
  return highest(below);
}
function pickPrefix(declaredRanges) {
  if (declaredRanges.some((r) => r.startsWith("^"))) return "^";
  if (declaredRanges.some((r) => r.startsWith("~"))) return "~";
  return "";
}
function lowestAnchor(declaredRanges) {
  let lowest;
  for (const range of declaredRanges) {
    try {
      const min = semver4.minVersion(range);
      if (!min) continue;
      if (!lowest || semver4.lt(min, lowest)) lowest = min;
    } catch {
    }
  }
  return lowest;
}
function highest(versions) {
  if (versions.length === 0) return void 0;
  return versions.toSorted(semver4.rcompare)[0];
}
function isStable(version) {
  return semver4.prerelease(version) === null;
}
function format(prefix, version) {
  if (!version) return void 0;
  return `${prefix}${version}`;
}
function pickBuckets(stableVersions, anchor) {
  const above = stableVersions.filter((v) => semver4.gt(v, anchor));
  const sameMajor = above.filter((v) => semver4.major(v) === anchor.major);
  const samePatch = sameMajor.filter((v) => semver4.minor(v) === anchor.minor);
  const minorAbove = sameMajor.filter((v) => semver4.minor(v) > anchor.minor);
  const majorAbove = above.filter((v) => semver4.major(v) > anchor.major);
  return {
    major: highest(majorAbove),
    minor: highest(minorAbove),
    patch: highest(samePatch)
  };
}
function pickPrerelease(distTags, anchor) {
  let best;
  for (const tag of ["next", "rc", "beta", "alpha"]) {
    const v = distTags[tag];
    if (!v) continue;
    if (semver4.prerelease(v) === null) continue;
    if (!semver4.gt(v, anchor)) continue;
    if (!best || semver4.gt(v, best)) best = v;
  }
  return best;
}
function differentFromCurrent(value, current) {
  if (!value) return void 0;
  return value === current ? void 0 : value;
}
function resolveOne(name, group, info, options, excludeRules) {
  const nonPeer = group.filter((d) => d.depType !== "peerDependencies");
  const sourceForRange = nonPeer.length > 0 ? nonPeer : group;
  const declaredRanges = [...new Set(sourceForRange.map((d) => d.range))];
  const workspaces = [...new Set(group.map((d) => d.workspaceName))];
  const current = declaredRanges.length === 1 ? declaredRanges[0] : "mixed";
  const preferredRangePrefix = pickPrefix(declaredRanges);
  const anchor = lowestAnchor(declaredRanges);
  if (!info || !anchor) {
    return {
      current,
      declaredRanges,
      downgrade: void 0,
      major: void 0,
      minor: void 0,
      name,
      next: void 0,
      patch: void 0,
      preferredRangePrefix,
      updateAvailable: false,
      workspaces
    };
  }
  const effectiveInfo = options.minReleaseAge ? filterRegistryInfo(name, info, options.minReleaseAge, excludeRules) : info;
  const stable = effectiveInfo.versions.filter((v) => semver4.valid(v) !== null && isStable(v));
  const downgrade = options.minReleaseAge && !declaredRangeSatisfiable(declaredRanges, stable) ? format(preferredRangePrefix, pickDowngrade(stable, anchor)) : void 0;
  const buckets = pickBuckets(stable, anchor);
  const patchRaw = format(preferredRangePrefix, buckets.patch);
  const minorRaw = format(preferredRangePrefix, buckets.minor);
  const majorRaw = format(preferredRangePrefix, buckets.major);
  const nextRaw = options.includeNext ? format(preferredRangePrefix, pickPrerelease(effectiveInfo.distTags, anchor)) : void 0;
  let patch = differentFromCurrent(patchRaw, current);
  const minor = differentFromCurrent(minorRaw, current);
  const major = differentFromCurrent(majorRaw, current);
  const next = differentFromCurrent(nextRaw, current);
  if (!patch && declaredRanges.length > 1) {
    const allSameAnchor = declaredRanges.every((range) => {
      const v = semver4.minVersion(range);
      return v !== null && v.version === anchor.version;
    });
    if (allSameAnchor) {
      const normalized = `${preferredRangePrefix}${anchor.version}`;
      if (declaredRanges.some((r) => r !== normalized)) {
        patch = normalized;
      }
    }
  }
  const updateAvailable = Boolean(patch ?? minor ?? major ?? next ?? downgrade);
  return {
    current,
    declaredRanges,
    downgrade,
    major,
    minor,
    name,
    next,
    patch,
    preferredRangePrefix,
    updateAvailable,
    workspaces
  };
}
function resolveVersions(deps, registry, options = {}) {
  const grouped = /* @__PURE__ */ new Map();
  for (const dep of deps) {
    const existing = grouped.get(dep.name);
    if (existing) existing.push(dep);
    else grouped.set(dep.name, [dep]);
  }
  const excludeRules = options.minReleaseAge ? buildExcludeRules(options.minReleaseAge.exclude) : [];
  const resolved = [];
  for (const [name, group] of grouped) {
    resolved.push(resolveOne(name, group, registry.get(name), options, excludeRules));
  }
  return resolved.toSorted((a, b) => {
    if (a.updateAvailable !== b.updateAvailable) return a.updateAvailable ? -1 : 1;
    return a.name.localeCompare(b.name);
  });
}

// src/lib/updo/runUpdo.ts
import { existsSync as existsSync10, readFileSync as readFileSync18 } from "node:fs";
import PATH12 from "node:path";
import chalk20 from "chalk";
function listWorkspacesFromFs(cwd) {
  const workspaces = listDeclaredWorkspaces(cwd);
  const rootPath = PATH12.resolve(cwd, "package.json");
  if (existsSync10(rootPath)) {
    try {
      const root = JSON.parse(readFileSync18(rootPath, "utf8"));
      if (root.name && !workspaces.some((ws) => ws.location === ".")) {
        workspaces.unshift({ location: ".", name: root.name });
      }
    } catch {
    }
  }
  return workspaces;
}
function resolveMinReleaseAgeFilter(pm, cwd) {
  if (pm.name !== "pnpm") return void 0;
  const cfg = readMinReleaseAgeConfig(cwd);
  if (cfg.minutes === void 0 || cfg.minutes <= 0) return void 0;
  console.log(chalk20.gray(`  Filtering versions by minimumReleaseAge=${cfg.minutes}m (pnpm); ${cfg.exclude.length} exclude(s)`));
  return {
    exclude: cfg.exclude,
    ignoreMissingTime: cfg.ignoreMissingTime,
    minutes: cfg.minutes,
    now: Date.now()
  };
}
async function runUpdo(pm, options = {}) {
  const cwd = INIT_CWD();
  const workspaces = listWorkspacesFromFs(cwd);
  const workspaceNames = new Set(workspaces.map((ws) => ws.name));
  const uniqueDependencyNames = /* @__PURE__ */ new Set();
  console.log(chalk20.gray("Scanning workspace dependencies..."));
  const declaredDeps = collectWorkspaceDeps(cwd, workspaces, workspaceNames);
  for (const dep of declaredDeps) {
    uniqueDependencyNames.add(dep.name);
  }
  console.log(chalk20.gray(`  Found ${uniqueDependencyNames.size} unique dependencies across ${workspaces.length} workspaces`));
  const minReleaseAge = resolveMinReleaseAgeFilter(pm, cwd);
  console.log(chalk20.gray("Fetching registry info..."));
  const registryInfo = await fetchAllRegistryInfo([...uniqueDependencyNames], { wantTimes: minReleaseAge !== void 0 });
  const includeNext = options.next ?? false;
  const latest = options.latest ?? false;
  const risk = options.risk ?? "green";
  const resolved = resolveVersions(declaredDeps, registryInfo, { includeNext, minReleaseAge });
  const downgradeCount = resolved.filter((r) => r.downgrade !== void 0).length;
  if (downgradeCount > 0) {
    console.log(chalk20.yellow(`  ${downgradeCount} package(s) have a current range that pnpm will reject \u2014 see the red "Down" column for downgrade suggestions.`));
  }
  const updates = await interactiveSelect(resolved, {
    includeNext,
    latest,
    risk
  });
  if (updates.length === 0) {
    console.log(chalk20.gray("No updates selected."));
    return 0;
  }
  console.log(chalk20.gray(`
Applying ${updates.length} updates...`));
  const modified = applyUpdates(cwd, workspaces, updates);
  console.log(chalk20.gray(`  Modified ${modified} package.json files`));
  console.log(chalk20.gray("Installing updated dependencies..."));
  return runSteps("Updo", [
    pm.install(),
    pm.dedupe()
  ], true);
}
export {
  CROSS_PLATFORM_NEWLINE,
  DuplicateDetector,
  INIT_CWD,
  LEGACY_COMMANDS_PREFIX,
  WINDOWS_NEWLINE_REGEX,
  XYLABS_COMMANDS_PREFIX,
  XYLABS_RULES_PREFIX,
  XYLABS_SKILLS_PREFIX,
  applyPackageManager,
  applyUpdates,
  buildSecurityAuditRows,
  bundledToolchainRange,
  bundledToolchainVersion,
  checkResult,
  classifyCell,
  classifySecureAge,
  classifySecureDownloads,
  claudeCommandTemplates,
  claudeMdLocalTemplate,
  claudeMdProjectTemplate,
  claudeMdRuleTemplates,
  claudeSkillTemplates,
  clearLatestPackageVersionCache,
  clearSecurePackageMetadataCache,
  collectSecureDeclaredDependencies,
  collectSecurePackageTargets,
  collectWorkspaceDeps,
  createBuildConfig,
  defaultBuildConfig,
  defaultReadFileSyncOptions,
  defaultSelection,
  deleteGlob,
  deprecationMigrate,
  detectDuplicateDependencies,
  detectWorkspaceCycles,
  emitJson,
  empty,
  ensurePackageManagerInstalled,
  fetchAllRegistryInfo,
  fetchAllSecurePackageMetadata,
  fetchAllSecureWeeklyDownloads,
  fetchLatestPackageVersion,
  fetchRegistryInfo,
  fetchSecurePackageMetadata,
  fetchSecureRegistryManifest,
  fetchSecureWeeklyDownloads,
  fillTemplate,
  formatSecureDownloads,
  generateIgnoreFiles,
  getGitConfig,
  getGitConfigBool,
  getPackageManagerInstallPlan,
  gitignoreTemplate,
  installOutputCapture,
  interactiveSelect,
  isJsonMode,
  isLocalSecureDependency,
  isPackageManagerInstalled,
  isStrictMode,
  isYarnVersionOrGreater,
  latestVersions,
  listRepoTemplates,
  listWorkspacesFromFs,
  loadConfig,
  loadRepoTemplateFiles,
  loadWorkspaceCommandConfig,
  mergeCommandConfig,
  multiLineToJSONArray,
  notEmpty,
  outputStorage,
  packageName,
  parsedPackageJSON,
  printWorkspaceCycles,
  processEx,
  readLines,
  readMinReleaseAgeConfig,
  readNonEmptyLines,
  renderSecurityAuditRows,
  renderTable,
  resetReporterForTesting,
  resolveSecureDependencyVersion,
  resolveVersions,
  runInstall,
  runSecurityAudit,
  runStepAsync,
  runSteps,
  runStepsAsync,
  runUpdo,
  runWithConcurrency,
  runWithEnvelope,
  runXy,
  runXyWithWarning,
  safeExit,
  safeExitAsync,
  setCurrentCommand,
  setGitConfig,
  setJsonMode,
  setStrictMode,
  spawn,
  spawnPackageManagerSync,
  spawnSync,
  tryReadFileSync,
  tryRunLocalScript,
  union,
  withEnvelope,
  withErrnoException,
  withError,
  writeLines,
  xyLog,
  yarnWorkspace,
  yarnWorkspaces
};
//# sourceMappingURL=index.mjs.map
