// 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/concurrency.ts
import { AsyncLocalStorage } from "node:async_hooks";
var outputStorage = new AsyncLocalStorage();
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/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/packageManagerRuntime.ts
import fs from "node:fs";
import chalk2 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 = fs.readSync(process.stdin.fd, buffer, 0, buffer.length, null);
  const answer = buffer.toString("utf8", 0, bytesRead).trim().toLowerCase();
  return answer === "y" || answer === "yes";
}
function isCommandInstalled(command) {
  const result = spawnSync(command, ["--version"], {
    encoding: "utf8",
    stdio: "ignore"
  });
  return !result.error && result.status === 0;
}
function isPackageManagerInstalled(pm) {
  return isCommandInstalled(pm);
}
function getPackageManagerInstallPlan(pm, platform = currentPlatform()) {
  const displayName = DISPLAY_NAMES[pm];
  if (platform === "darwin") {
    const command = MAC_INSTALL_COMMANDS[pm];
    return {
      command,
      manualInstructions: [
        `Install ${displayName} with: ${command}`
      ],
      packageManager: pm,
      platform,
      supported: true
    };
  }
  if (platform === "linux") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Linux yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  if (platform === "win32") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Windows yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  return {
    manualInstructions: [
      `Automatic installation for ${displayName} is not implemented on ${platform} yet.`,
      `Install ${displayName} manually and re-run the command.`
    ],
    packageManager: pm,
    platform,
    supported: false
  };
}
function printManualInstructions(plan, context) {
  console.error(chalk2.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk2.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(chalk2.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk2.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk2.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk2.gray(`  ${plan.command}`));
    return false;
  }
  const confirmed = askYesNo(chalk2.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!confirmed) {
    console.error(chalk2.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!installWithHomebrew(pm, context.cwd)) {
    console.error(chalk2.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk2.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk2.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk2.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.green(`${displayName} installed successfully.`));
  return true;
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } from "glob";
function readJsonFile(path4) {
  if (!existsSync(path4)) return void 0;
  try {
    return JSON.parse(readFileSync(path4, "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/processEx.ts
import chalk3 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(chalk3.red(`'${error2.path}' not found.`));
    } else {
      console.error(chalk3.red(`Errno: ${error2.code}`));
    }
    return error2.errno ?? -1;
  }) ?? withError(error, (error2) => {
    console.error(chalk3.red(`${error2.name}: ${error2.message}`));
    return -1;
  }) ?? (() => {
    console.error(chalk3.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/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/packageName.ts
import { readFileSync as readFileSync2 } 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(readFileSync2(pkgPath, "utf8"));
    return pkg.name;
  } catch {
    return void 0;
  }
}

// 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/lib/runSteps.ts
import { existsSync as existsSync3 } from "node:fs";
import chalk4 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(chalk4.green(`${name} [${pkgName}]`));
    let totalStatus = 0;
    for (const [i, [command, args, config]] of steps.entries()) {
      if (messages?.[i]) {
        console.log(chalk4.gray(messages?.[i]));
      }
      const argList = Array.isArray(args) ? args : args.split(" ");
      if (command === "node" && !existsSync3(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(" "), {
        ...config,
        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,
          ...config?.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 existsSync4 } from "node:fs";
import chalk5 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, config] = step;
    if (message) {
      console.log(chalk5.gray(message));
    }
    const argList = Array.isArray(args) ? args : args.split(" ");
    if (command === "node" && !existsSync4(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(" "), {
      ...config,
      env: { FORCE_COLOR: "3", ...process.env },
      stdio: isJsonMode() ? ["inherit", 2, 2] : "inherit"
    }).on("close", (code) => {
      if (code) {
        console.error(
          chalk5.red(
            `Command Exited With Non-Zero Result [${chalk5.gray(code)}] | ${chalk5.yellow(command)} ${chalk5.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(chalk5.green(`${name} [${pkgName}]`));
    let result = 0;
    for (const [i, step] of steps.entries()) {
      result += await runStepAsync(name, step, exitOnFail, messages?.[i]);
    }
    return result;
  });
};

// src/actions/build.ts
import chalk6 from "chalk";
var build = async ({
  incremental,
  jobs,
  verbose,
  pkg
}) => {
  const pkgOptions = pkg === void 0 ? [] : [pkg];
  const incrementalOptions = incremental ? ["-i"] : [];
  const verboseOptions = verbose ? ["-v"] : [];
  const jobsOptions = ["-j", `${jobs}`];
  const pm = getPackageManager();
  return await safeExitAsync(async () => {
    const name = `Build${incremental ? "-Incremental" : ""} [${pkg ?? "All"}]`;
    console.log(chalk6.green(`${name} [${packageName()}]`));
    const compileResult = await runStepAsync(
      name,
      pm.runXy(["compile", ...pkgOptions, ...verboseOptions, ...jobsOptions, ...incrementalOptions]),
      false
    );
    if (compileResult !== 0) return compileResult;
    const validationResults = await Promise.all([
      runStepAsync(name, pm.runXy(["publint", ...pkgOptions, ...verboseOptions, ...jobsOptions, ...incrementalOptions]), false),
      runStepAsync(name, pm.runXy(["deplint", ...pkgOptions, ...verboseOptions, ...jobsOptions, ...incrementalOptions]), false),
      runStepAsync(name, pm.runXy(["lint", ...pkgOptions, ...verboseOptions, ...jobsOptions, ...incrementalOptions]), false)
    ]);
    return validationResults.reduce((total, result) => total + result, 0);
  });
};

// src/actions/compile.ts
import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
import path2 from "node:path";
import chalk7 from "chalk";
function isWorkspaceRange(value) {
  return typeof value === "string" && value.startsWith("workspace:");
}
function readWorkspacePackageJson(rootDir, workspace) {
  const packageJsonPath = path2.resolve(rootDir, workspace.location, "package.json");
  return JSON.parse(readFileSync3(packageJsonPath, "utf8"));
}
function readRootWorkspace(rootDir) {
  const packageJsonPath = path2.resolve(rootDir, "package.json");
  if (!existsSync5(packageJsonPath)) return void 0;
  const packageJson = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
  if (!packageJson.name) return void 0;
  return {
    listed: false,
    location: ".",
    name: packageJson.name,
    packageJson
  };
}
function allCompileWorkspaces(pm) {
  const rootDir = INIT_CWD();
  const workspaces = pm.listWorkspaces();
  return workspaces.map((workspace) => ({
    ...workspace,
    listed: true,
    packageJson: readWorkspacePackageJson(rootDir, workspace)
  }));
}
function emitWorkspaces(pm) {
  const rootDir = INIT_CWD();
  const workspaces = allCompileWorkspaces(pm);
  const nonRootWorkspaces = workspaces.filter((workspace) => workspace.location !== ".");
  if (nonRootWorkspaces.length > 0) return nonRootWorkspaces;
  if (workspaces.length > 0) return workspaces;
  const rootWorkspace = readRootWorkspace(rootDir);
  return rootWorkspace ? [rootWorkspace] : [];
}
function validationWorkspaces(pm) {
  const rootDir = INIT_CWD();
  const allWorkspaces = allCompileWorkspaces(pm);
  const rootWorkspace = allWorkspaces.find((workspace) => workspace.location === ".") ?? readRootWorkspace(rootDir);
  const workspaces = allWorkspaces.filter((workspace) => workspace.location !== ".");
  return rootWorkspace ? [rootWorkspace, ...workspaces] : workspaces;
}
function packageScriptStep(pm, workspace, script, args) {
  return workspace.location === "." && workspace.listed !== true ? [script, args] : pm.runInWorkspaceByName(workspace.name, script, args);
}
function tarjanStronglyConnectedComponents(nodes, edges) {
  const indexMap = /* @__PURE__ */ new Map();
  const lowlink = /* @__PURE__ */ new Map();
  const onStack = /* @__PURE__ */ new Set();
  const stack = [];
  const sccs = [];
  let nextIndex = 0;
  const strongConnect = (v) => {
    indexMap.set(v, nextIndex);
    lowlink.set(v, nextIndex);
    nextIndex += 1;
    stack.push(v);
    onStack.add(v);
    for (const w of edges.get(v) ?? []) {
      if (!indexMap.has(w)) {
        strongConnect(w);
        lowlink.set(v, Math.min(lowlink.get(v) ?? 0, lowlink.get(w) ?? 0));
      } else if (onStack.has(w)) {
        lowlink.set(v, Math.min(lowlink.get(v) ?? 0, indexMap.get(w) ?? 0));
      }
    }
    if (lowlink.get(v) === indexMap.get(v)) {
      const scc = [];
      let popped;
      do {
        popped = stack.pop();
        if (popped === void 0) break;
        onStack.delete(popped);
        scc.push(popped);
      } while (popped !== v);
      sccs.push(scc);
    }
  };
  for (const v of nodes) {
    if (!indexMap.has(v)) {
      strongConnect(v);
    }
  }
  return sccs;
}
function edgeKey(from, to) {
  return `${from} ${to}`;
}
function dropDevDepEdgesInScc(scc, dependencies, strictEdges) {
  const sccSet = new Set(scc);
  for (const from of scc) {
    const outgoing = dependencies.get(from);
    if (!outgoing) continue;
    const removable = [];
    for (const to of outgoing) {
      if (sccSet.has(to) && !strictEdges.has(edgeKey(from, to))) {
        removable.push(to);
      }
    }
    for (const to of removable) outgoing.delete(to);
  }
}
function breakDevDependencyCycles(nodeNames, dependencies, strictEdges) {
  const sccs = tarjanStronglyConnectedComponents(nodeNames, dependencies);
  for (const scc of sccs) {
    if (scc.length >= 2) dropDevDepEdgesInScc(scc, dependencies, strictEdges);
  }
  const residualSccs = tarjanStronglyConnectedComponents(nodeNames, dependencies);
  for (const scc of residualSccs) {
    if (scc.length > 1) {
      const cycle = scc.toSorted().join(" -> ");
      throw new Error(`workspace dependency cycle in 'dependencies': ${cycle}`);
    }
  }
}
function collectWorkspaceEdges(workspaces, workspaceNames, fields) {
  const dependencies = /* @__PURE__ */ new Map();
  const strictEdges = /* @__PURE__ */ new Set();
  for (const workspace of workspaces) {
    dependencies.set(workspace.name, /* @__PURE__ */ new Set());
  }
  for (const workspace of workspaces) {
    for (const field of fields) {
      for (const [name, range] of Object.entries(workspace.packageJson[field] ?? {})) {
        if (name === workspace.name) continue;
        if (!workspaceNames.has(name) || !isWorkspaceRange(range)) continue;
        dependencies.get(workspace.name)?.add(name);
        if (field === "dependencies") {
          strictEdges.add(edgeKey(workspace.name, name));
        }
      }
    }
  }
  return { dependencies, strictEdges };
}
function createWorkspaceDependencyGraph(workspaces, fields) {
  const workspacesByName = new Map(workspaces.map((workspace) => [workspace.name, workspace]));
  const workspaceNames = new Set(workspacesByName.keys());
  const { dependencies, strictEdges } = collectWorkspaceEdges(workspaces, workspaceNames, fields);
  const dependents = /* @__PURE__ */ new Map();
  for (const workspace of workspaces) {
    dependents.set(workspace.name, /* @__PURE__ */ new Set());
  }
  breakDevDependencyCycles([...workspaceNames], dependencies, strictEdges);
  for (const [workspaceName, dependencyNames] of dependencies) {
    for (const dependencyName of dependencyNames) {
      dependents.get(dependencyName)?.add(workspaceName);
    }
  }
  return {
    dependencies,
    dependents,
    workspacesByName
  };
}
async function runWorkspaceScripts(label, pm, workspaces, script, args, jobs) {
  const results = Array.from({ length: workspaces.length }, () => 0);
  await runWithConcurrency(
    workspaces.map((workspace, index) => ({ index, workspace })),
    Math.max(1, jobs),
    async ({ index, workspace }) => {
      results[index] = await runStepAsync(label, packageScriptStep(pm, workspace, script, args), false);
    }
  );
  return results.reduce((total, result) => total + result, 0);
}
async function runWorkspaceScriptsTopologically(label, pm, workspaces, fields, script, args, jobs) {
  const {
    dependencies,
    dependents,
    workspacesByName
  } = createWorkspaceDependencyGraph(workspaces, fields);
  const pendingDependencies = new Map(
    [...dependencies].map(([workspaceName, dependencyNames]) => [workspaceName, dependencyNames.size])
  );
  const ready = [...pendingDependencies].filter(([, count]) => count === 0).map(([workspaceName]) => workspaceName).toSorted();
  const concurrency = Math.max(1, jobs);
  let active = 0;
  let completed = 0;
  let stopped = false;
  let totalStatus = 0;
  return await new Promise((resolve) => {
    const finishIfDone = () => {
      if ((completed === workspaces.length || stopped) && active === 0) {
        if (!stopped && ready.length === 0 && completed < workspaces.length) {
          console.error(chalk7.red(`${label}: workspace dependency cycle detected`));
          resolve(totalStatus + 1);
          return true;
        }
        resolve(totalStatus);
        return true;
      }
      if (!stopped && ready.length === 0 && active === 0 && completed < workspaces.length) {
        console.error(chalk7.red(`${label}: workspace dependency cycle detected`));
        resolve(totalStatus + 1);
        return true;
      }
      return false;
    };
    const launch = () => {
      if (finishIfDone()) return;
      while (!stopped && active < concurrency && ready.length > 0) {
        const workspaceName = ready.shift();
        if (workspaceName === void 0) continue;
        const workspace = workspacesByName.get(workspaceName);
        if (!workspace) continue;
        active += 1;
        void runStepAsync(label, packageScriptStep(pm, workspace, script, args), false).then((status) => {
          active -= 1;
          completed += 1;
          totalStatus += status;
          if (status === 0) {
            for (const dependentName of dependents.get(workspace.name) ?? []) {
              const nextCount = (pendingDependencies.get(dependentName) ?? 0) - 1;
              pendingDependencies.set(dependentName, nextCount);
              if (nextCount === 0) {
                ready.push(dependentName);
              }
            }
            ready.sort();
          } else {
            stopped = true;
          }
          launch();
        }).catch((reason) => {
          active -= 1;
          completed += 1;
          stopped = true;
          totalStatus += 1;
          console.error(chalk7.red(`${label}: ${reason.message}`));
          launch();
        });
      }
    };
    launch();
  });
}
var compile = ({
  verbose,
  pkg,
  incremental,
  jobs
}) => {
  return pkg ? compilePackage({ pkg, verbose }) : compileAll({
    incremental,
    jobs,
    verbose
  });
};
var compilePackage = ({ pkg, verbose }) => {
  const pm = getPackageManager();
  const verboseOptions = verbose ? ["-v"] : [];
  return runSteps(
    `Compile [${pkg}]`,
    [pm.runInWorkspace(pkg, "package-compile", verboseOptions)]
  );
};
var compileAll = ({
  jobs,
  verbose,
  incremental
}) => {
  const pm = getPackageManager();
  const verboseOptions = verbose ? ["-v"] : [];
  if (incremental) {
    return runSteps("Compile-Incremental [All]", [
      pm.foreachWorkspace("package-compile", verboseOptions, {
        incremental,
        jobs,
        topological: true,
        verbose
      })
    ]);
  }
  return safeExitAsync(async () => {
    console.log(chalk7.green(`Compile [All] [${packageName()}]`));
    const workspaces = emitWorkspaces(pm);
    const emitResult = await runWorkspaceScriptsTopologically(
      "Compile:Emit",
      pm,
      workspaces,
      ["dependencies", "devDependencies"],
      "package-compile",
      ["--emit-only", ...verboseOptions],
      jobs
    );
    if (emitResult !== 0) return emitResult;
    return await runWorkspaceScripts(
      "Compile:Validate",
      pm,
      validationWorkspaces(pm),
      "package-compile",
      ["--validate-only", ...verboseOptions],
      jobs
    );
  });
};

// src/actions/copy-assets.ts
import path3 from "node:path/posix";
import chalk8 from "chalk";
import cpy from "cpy";
var copyPackageTargetAssets = async (target, name, location) => {
  try {
    const values = await cpy(
      ["**/*.jpg", "**/*.png", "**/*.gif", "**/*.svg", "**/*.webp", "**/*.sass", "**/*.scss", "**/*.gif", "**/*.css"],
      `../dist/${target}`,
      {
        cwd: path3.join(process.cwd(), location, "src"),
        flat: false
      }
    );
    for (const value of values) {
      console.log(`${value.split("/").pop()} => ./dist/${target}`);
    }
    return 0;
  } catch (reason) {
    console.log(`Copy Failed: ${name}: ${String(reason)}`);
    return 1;
  }
};
var copyTargetAssets = async (target, pkg) => {
  const workspaces = getPackageManager().listWorkspaces();
  console.log(chalk8.green(`Copying Assets [${target.toUpperCase()}]`));
  const workspaceList = workspaces.filter(({ name }) => {
    return pkg === void 0 || name === pkg;
  });
  if (workspaceList.length === 0) {
    console.error(`Package not found [${pkg}]`);
  } else {
    const results = await Promise.all(
      workspaceList.map(async (workspace) => {
        const { location, name } = workspace;
        return await copyPackageTargetAssets(target, name, location);
      })
    );
    return results.reduce((prev, result) => prev || result, 0);
  }
  return 0;
};
var copyAssets = async ({ target, pkg }) => {
  switch (target) {
    case "esm": {
      return await copyTargetAssets("esm", pkg);
    }
    case "cjs": {
      return await copyTargetAssets("cjs", pkg);
    }
    default: {
      return await copyTargetAssets("esm", pkg) || await copyTargetAssets("cjs", pkg);
    }
  }
};

// src/actions/rebuild.ts
var rebuild = ({ verbose }) => {
  const pm = getPackageManager();
  return runSteps("Rebuild", [
    pm.runXy(["clean"]),
    pm.runXy(verbose ? ["build", "-v"] : ["build"])
  ]);
};

// src/actions/recompile.ts
var recompile = async ({
  incremental,
  jobs,
  pkg,
  verbose
}) => {
  return pkg ? await recompilePackage({ pkg, verbose }) : await recompileAll({
    incremental,
    jobs,
    verbose
  });
};
var recompilePackage = ({ pkg, verbose }) => {
  const pm = getPackageManager();
  const verboseOptions = verbose ? ["-v"] : [];
  return runStepsAsync(
    `Recompile [${pkg}]`,
    [pm.runInWorkspace(pkg, "package-recompile", verboseOptions)]
  );
};
var recompileAll = async ({
  jobs,
  verbose,
  incremental
}) => {
  const pm = getPackageManager();
  const verboseOptions = verbose ? ["-v"] : [];
  const foreachOptions = {
    incremental,
    jobs,
    topological: true,
    verbose
  };
  return runStepsAsync(`Recompile${incremental ? "-Incremental" : ""} [All]`, [
    // Root inclusion is `clean`-specific: the recompile loop only compiles
    // sub-package sources, but a stale root `dist/` from a prior bundle
    // would survive recompile without this. See `cleanAll` for context.
    pm.foreachWorkspace("package-clean", [], { ...foreachOptions, includeWorkspaceRoot: true }),
    pm.foreachWorkspace("package-compile", verboseOptions, foreachOptions)
  ]);
};

// src/xy/build/buildCommand.ts
var buildCommand = {
  command: "build [package]",
  describe: "Build - Compile & Lint",
  builder: (yargs) => {
    return yargs.positional("package", { describe: "Specific package to build" });
  },
  handler: async (argv) => {
    if (argv.verbose) {
      console.log(`Building: ${argv.package ?? "all"}`);
    }
    await withEnvelope("build", () => build({
      incremental: !!argv.incremental,
      jobs: argv.jobs,
      pkg: argv.package,
      verbose: !!argv.verbose
    }));
  }
};

// src/xy/build/compileCommand.ts
var compileCommand = {
  command: "compile [package]",
  describe: "Compile with Typescript",
  builder: (yargs) => {
    return yargs.positional("package", { describe: "Specific package to compile" });
  },
  handler: async (argv) => {
    if (argv.verbose) {
      console.log(`Compiling: ${argv.package ?? "all"}`);
    }
    await withEnvelope("compile", () => compile({
      incremental: !!argv.incremental,
      jobs: argv.jobs,
      pkg: argv.package,
      verbose: !!argv.verbose
    }));
  }
};

// src/xy/build/copyAssetsCommand.ts
var copyAssetsCommand = {
  command: "copy-assets [package]",
  describe: "Copy Assets - Copy the assets from src to dist",
  builder: (yargs) => {
    return yargs.positional("package", { describe: "Specific package to copy assets" });
  },
  handler: async (argv) => {
    if (argv.verbose) console.log(`Copying Assets: ${argv.package ?? "all"}`);
    await withEnvelope("copy-assets", () => copyAssets({ pkg: argv.package }));
  }
};

// src/xy/build/rebuildCommand.ts
var rebuildCommand = {
  command: "rebuild [package]",
  describe: "Rebuild - Clean, Compile & Lint",
  builder: (yargs) => {
    return yargs.positional("package", { describe: "Specific package to rebuild" });
  },
  handler: async (argv) => {
    if (argv.verbose) console.log(`Rebuilding: ${argv.package ?? "all"}`);
    await withEnvelope("rebuild", () => rebuild({ verbose: !!argv.verbose }));
  }
};

// src/xy/build/recompileCommand.ts
var recompileCommand = {
  command: "recompile [package]",
  describe: "Re-compile with Typescript & Copy Images",
  builder: (yargs) => {
    return yargs.positional("package", { describe: "Specific package to re-compile" });
  },
  handler: async (argv) => {
    if (argv.verbose) {
      console.log(`Re-compiling: ${argv.package ?? "all"}`);
    }
    await withEnvelope("recompile", () => recompile({
      incremental: !!argv.incremental,
      jobs: argv.jobs,
      pkg: argv.package,
      verbose: !!argv.verbose
    }));
  }
};

// src/xy/build/index.ts
var xyBuildCommands = (args) => {
  return args.command(buildCommand).command(compileCommand).command(recompileCommand).command(rebuildCommand).command(copyAssetsCommand);
};
export {
  xyBuildCommands
};
//# sourceMappingURL=index.mjs.map
