// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } from "glob";
function readJsonFile(path2) {
  if (!existsSync(path2)) return void 0;
  try {
    return JSON.parse(readFileSync(path2, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH.resolve(cwd, "package.json"));
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!packageManager) 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/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// 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 originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
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);
  }
}

// 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/actions/orphan.ts
import fs from "node:fs";
import path from "node:path";
import chalk from "chalk";
import { glob } from "glob";
function isAncestorOfWorkspace(dir, workspaceLocations) {
  const dirWithSep = dir.endsWith(path.sep) ? dir : dir + path.sep;
  for (const ws of workspaceLocations) {
    if (ws.startsWith(dirWithSep)) return true;
  }
  return false;
}
function findOrphans(cwd, verbose) {
  const pm = getPackageManager();
  const workspaces = pm.listWorkspaces();
  const workspaceLocations = new Set(
    workspaces.map((ws) => path.resolve(cwd, ws.location))
  );
  const distDirs = glob.sync("**/dist", {
    cwd,
    ignore: ["**/node_modules/**"]
  });
  const orphans = /* @__PURE__ */ new Set();
  for (const distDir of distDirs) {
    const parentRel = path.dirname(distDir);
    const parentAbs = path.resolve(cwd, parentRel);
    if (parentRel === ".") continue;
    if (workspaceLocations.has(parentAbs)) continue;
    if (fs.existsSync(path.join(parentAbs, "package.json"))) continue;
    if (verbose) {
      console.log(chalk.gray(`  Found orphan: ${parentRel}`));
    }
    let topOrphan = parentRel;
    let current = path.dirname(parentRel);
    while (current !== ".") {
      const currentAbs = path.resolve(cwd, current);
      if (workspaceLocations.has(currentAbs)) break;
      if (fs.existsSync(path.join(currentAbs, "package.json"))) break;
      if (isAncestorOfWorkspace(currentAbs, workspaceLocations)) break;
      topOrphan = current;
      current = path.dirname(current);
    }
    orphans.add(topOrphan);
  }
  return [...orphans].toSorted();
}
function orphanList({ verbose } = {}) {
  const cwd = INIT_CWD();
  console.log(chalk.green("Orphan List"));
  const orphans = findOrphans(cwd, verbose);
  if (orphans.length === 0) {
    console.log(chalk.green("  No orphaned directories found"));
    return 0;
  }
  for (const orphan of orphans) {
    console.log(chalk.yellow(`  ${orphan}`));
  }
  console.log(chalk.yellow(`
  Found ${orphans.length} orphaned director${orphans.length === 1 ? "y" : "ies"}`));
  return 1;
}

// src/xy/common/orphan/listCommand.ts
var listCommand = {
  command: "list",
  describe: "List orphaned directories containing only build artifacts",
  handler: async (argv) => {
    if (argv.verbose) console.log("Orphan List");
    await withEnvelope("orphan list", () => orphanList({ verbose: argv.verbose }));
  }
};
export {
  listCommand
};
//# sourceMappingURL=listCommand.mjs.map
