// src/actions/lintNext.ts
import path from "path";
import chalk from "chalk";
import { ESLint } from "eslint";

// src/lib/concurrency.ts
import { AsyncLocalStorage } from "async_hooks";
var outputStorage = new AsyncLocalStorage();
var captureInstalled = false;
function installOutputCapture() {
  if (captureInstalled) return;
  captureInstalled = true;
  const originalStdoutWrite = 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(originalStdoutWrite);
  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/pm/workspaces.ts
import { existsSync, readFileSync } from "fs";
import PATH from "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 "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/actions/lintNext.ts
var dumpMessages = (lintResults) => {
  const colors = ["white", "yellow", "red"];
  const severity = ["none", "warning", "error"];
  for (const lintResult of lintResults) {
    if (lintResult.messages.length > 0) {
      console.log(chalk.gray(`
${lintResult.filePath}`));
      for (const message of lintResult.messages) {
        console.log(
          chalk.gray(`	${message.line}:${message.column}`),
          chalk[colors[message.severity]](`	${severity[message.severity]}`),
          chalk.white(`	${message.message}`),
          chalk.gray(`	${message.ruleId}`)
        );
      }
    }
  }
};
async function lintOnePackage({
  cache,
  cwd,
  fix,
  verbose
}) {
  const engine = new ESLint({
    cache,
    cacheLocation: path.join(cwd, ".eslintcache"),
    cacheStrategy: "content",
    cwd,
    fix,
    warnIgnored: false
  });
  const lintResults = await engine.lintFiles(".");
  dumpMessages(lintResults);
  if (fix) {
    await ESLint.outputFixes(lintResults);
  }
  const errors = lintResults.reduce((sum, r) => sum + r.errorCount, 0);
  const warnings = lintResults.reduce((sum, r) => sum + r.warningCount, 0);
  const files = lintResults.length;
  if (verbose) {
    const filesColor = files < 100 ? "green" : files < 1e3 ? "yellow" : "red";
    console.log(chalk.white(`  ${chalk[filesColor](files)} files linted`));
  }
  return {
    errors,
    files,
    warnings
  };
}
async function lintNext({
  cache = false,
  fix = false,
  jobs,
  pkg,
  verbose = false
}) {
  const rootDir = INIT_CWD();
  const pm = getPackageManager();
  const allWorkspaces = pm.listWorkspaces();
  const workspaces = pkg ? allWorkspaces.filter((ws) => ws.name === pkg) : allWorkspaces;
  if (workspaces.length === 0) {
    console.log(chalk.red(pkg ? `Package "${pkg}" not found` : "No workspaces found"));
    return 1;
  }
  const concurrency = jobs;
  const label = fix ? "Fix" : "Lint";
  installOutputCapture();
  const results = Array.from(
    { length: workspaces.length },
    () => ({
      errors: 0,
      files: 0,
      output: [],
      pkg: "",
      timeMs: 0,
      warnings: 0
    })
  );
  await runWithConcurrency(
    workspaces.map((ws, i) => ({ i, ws })),
    concurrency,
    async ({ i, ws }) => {
      const output = [];
      await outputStorage.run(output, async () => {
        const pkgStart = Date.now();
        const absCwd = path.resolve(rootDir, ws.location);
        console.log(chalk.green(`${label} [${ws.name}]`));
        try {
          const {
            errors,
            files,
            warnings
          } = await lintOnePackage({
            cache,
            cwd: absCwd,
            fix,
            verbose
          });
          const timeMs = Date.now() - pkgStart;
          results[i] = {
            errors,
            files,
            output,
            pkg: ws.name,
            timeMs,
            warnings
          };
        } catch (ex) {
          output.push(chalk.red(`${label} failed for ${ws.name}: ${ex.message}
`));
          results[i] = {
            errors: 1,
            files: 0,
            output,
            pkg: ws.name,
            timeMs: Date.now() - pkgStart,
            warnings: 0
          };
        }
      });
    }
  );
  let totalErrors = 0;
  let totalWarnings = 0;
  let totalFiles = 0;
  for (const result of results) {
    for (const line of result.output) {
      process.stdout.write(line);
    }
    totalErrors += result.errors;
    totalWarnings += result.warnings;
    totalFiles += result.files;
  }
  const errColor = totalErrors > 0 ? "red" : "green";
  const warnColor = totalWarnings > 0 ? "yellow" : "green";
  console.log(
    chalk[errColor](`${totalErrors} errors`) + chalk.gray(", ") + chalk[warnColor](`${totalWarnings} warnings`) + chalk.gray(` across ${totalFiles} files in ${workspaces.length} packages`)
  );
  return totalErrors;
}
export {
  lintNext
};
//# sourceMappingURL=lintNext.mjs.map