// src/actions/lintNext.ts
import { createRequire as createRequire2 } from "node:module";
import path3 from "node:path";
import { pathToFileURL as pathToFileURL2 } from "node:url";
import chalk3 from "chalk";

// 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);
}

// src/pm/resolveWorkspace.ts
import chalk 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(chalk.red(`Ambiguous workspace "${query}"; matches: ${byShort.map((ws) => ws.name).join(", ")}`));
    return void 0;
  }
  return void 0;
}

// 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 != null && packageManager.length > 0)) return void 0;
  return packageManager.split("@", 1)[0];
}

// src/pm/detectPackageManager.ts
import { existsSync as existsSync2 } from "node:fs";
var knownPackageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
function detectPackageManager() {
  const packageManager = detectPackageManagerFromPackageJson();
  if (packageManager != null && packageManager.length > 0 && knownPackageManagers.has(packageManager)) {
    return packageManager;
  }
  if (existsSync2("pnpm-lock.yaml") || existsSync2("pnpm-workspace.yaml")) return "pnpm";
  if (existsSync2("bun.lock") || existsSync2("bun.lockb")) return "bun";
  if (existsSync2("yarn.lock") || existsSync2(".yarnrc.yml")) return "yarn";
  if (existsSync2("package-lock.json") || existsSync2("npm-shrinkwrap.json")) return "npm";
  return "yarn";
}

// src/pm/registry.ts
var implementations = /* @__PURE__ */ new Map();
function getPackageManager(name) {
  const pmName = name ?? detectPackageManager();
  const pm = implementations.get(pmName);
  if (!pm) {
    throw new Error(
      `No package manager implementation registered for "${pmName}". Ensure registerPackageManager() has been called before getPackageManager().`
    );
  }
  return pm;
}

// src/lib/eslintCache.ts
import { mkdirSync } from "node:fs";
import path from "node:path";
function workspaceEslintCachePath(rootDir, workspaceLocation) {
  const segment = workspaceLocation === "." ? "root" : workspaceLocation;
  return path.resolve(rootDir, ".xy/cache/eslint", segment, ".eslintcache");
}
function ensureEslintCacheDir(cachePath) {
  mkdirSync(path.dirname(cachePath), { recursive: true });
}

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

// src/lib/reporting/xyReporter.ts
var reporterState = {
  currentCommand: "unknown",
  isEnvelopeEmitted: false,
  isJsonModeEnabled: false,
  isStrictModeEnabled: false,
  originalStdoutWrite: void 0,
  startTime: 0
};
function isStrictMode() {
  return reporterState.isStrictModeEnabled || process.env.XY_STRICT === "1";
}

// src/actions/lintTierAnalysis.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { createRequire } from "node:module";
import path2 from "node:path";
import { pathToFileURL } from "node:url";
import chalk2 from "chalk";
import { findUpSync } from "find-up";
var tierExportPattern = /config(?:React)?Tier\d+[A-Za-z]*/g;
var composedConfigModules = [
  "bestPracticesCoreConfig",
  "consistencyRulesConfig",
  "correctnessCoreConfig",
  "importConfig",
  "rulesConfig",
  "typescriptConfig",
  "typescriptConsistencyConfig",
  "typescriptCorrectnessConfig",
  "typescriptTypeCheckedConfig",
  "typescriptTypeCheckedConsistencyConfig",
  "typescriptTypeCheckedCorrectnessConfig",
  "unicornConfig",
  "workspacesConfig"
];
function escapeRegExp(value) {
  return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
}
function hasComposedConfigModules(source) {
  return composedConfigModules.some((module) => source.includes(module));
}
function normalizeRuleLevel(setting) {
  let current = setting;
  while (Array.isArray(current) && current.length > 0) {
    current = current[0];
  }
  if (current === void 0) return "off";
  if (current === "off" || current === 0) return "off";
  if (current === "warn" || current === 1) return "warn";
  if (current === "error" || current === 2) return "error";
  return "off";
}
function countActualLintMessages(messages) {
  let errors = 0;
  let warnings = 0;
  for (const message of messages) {
    if (message.severity === 2) errors++;
    else warnings++;
  }
  return { errors, warnings };
}
function countMessagesForTier(messages, rules) {
  let errors = 0;
  let warnings = 0;
  for (const message of messages) {
    if (message.ruleId === null) {
      errors++;
      continue;
    }
    const level = normalizeRuleLevel(rules[message.ruleId]);
    if (level === "off") continue;
    if (level === "error") errors++;
    else warnings++;
  }
  return { errors, warnings };
}
function resolveLintTierConfigKind(source, currentTierExport) {
  if (currentTierExport === void 0) return "custom";
  const presetExportPattern = RegExp(String.raw`export\s+default\s+${escapeRegExp(currentTierExport)}\b`);
  if (presetExportPattern.test(source)) return "preset";
  if (hasComposedConfigModules(source)) return "custom";
  if (source.includes(`...${currentTierExport}`)) return "preset";
  return "custom";
}
function getLintTierDefinitions(isReact, isTypeChecked) {
  if (isReact) {
    return [
      {
        id: 0,
        label: "Correctness",
        exportName: isTypeChecked ? "configReactTier0CorrectnessTypeChecked" : "configReactTier0Correctness"
      },
      {
        id: 1,
        label: "Consistency",
        exportName: isTypeChecked ? "configReactTier1ConsistencyTypeChecked" : "configReactTier1Consistency"
      },
      {
        id: 2,
        label: "Best Practices",
        exportName: isTypeChecked ? "configReactTier2BestPracticesTypeChecked" : "configReactTier2BestPractices"
      },
      {
        id: 3,
        label: "Opinionated",
        exportName: "configReactTier3OpinionatedTypeChecked"
      },
      {
        id: 4,
        label: "Experimental",
        exportName: isTypeChecked ? "configReactTier4ExperimentalTypeChecked" : "configReactTier4Experimental"
      }
    ];
  }
  return [
    {
      id: 0,
      label: "Correctness",
      exportName: isTypeChecked ? "configTier0CorrectnessTypeChecked" : "configTier0Correctness"
    },
    {
      id: 1,
      label: "Consistency",
      exportName: isTypeChecked ? "configTier1ConsistencyTypeChecked" : "configTier1Consistency"
    },
    {
      id: 2,
      label: "Best Practices",
      exportName: isTypeChecked ? "configTier2BestPracticesTypeChecked" : "configTier2BestPractices"
    },
    {
      id: 3,
      label: "Opinionated",
      exportName: isTypeChecked ? "configTier3OpinionatedTypeChecked" : "configTier3Opinionated"
    },
    {
      id: 4,
      label: "Experimental",
      exportName: isTypeChecked ? "configTier4ExperimentalTypeChecked" : "configTier4Experimental"
    }
  ];
}
function detectLintTierContext(cwd) {
  const configPath = findUpSync("eslint.config.ts", { cwd });
  if (configPath === void 0) {
    return {
      configKind: "custom",
      hasXylabsConfig: false,
      isReact: false,
      isTypeChecked: true
    };
  }
  const source = readFileSync2(configPath, "utf8");
  const hasXylabsConfig = source.includes("@xylabs/eslint-config-flat") || source.includes("@xylabs/eslint-config-react-flat");
  const isReact = source.includes("@xylabs/eslint-config-react-flat");
  const isTypeChecked = /(?:config(?:React)?Tier\d+\w*TypeChecked|typescriptTypeCheckedConfig)/.test(source);
  const tierMatches = source.match(tierExportPattern) ?? [];
  const currentTierExport = tierMatches.at(-1);
  const configKind = resolveLintTierConfigKind(source, currentTierExport);
  return {
    configKind,
    currentTierExport,
    hasXylabsConfig,
    isReact,
    isTypeChecked
  };
}
function findClosestTierPreset(actual, counts) {
  if (counts.length === 0) return void 0;
  let closest = counts[0];
  let closestDistance = Infinity;
  for (const entry of counts) {
    const distance = Math.abs(entry.errors - actual.errors) + Math.abs(entry.warnings - actual.warnings);
    if (distance < closestDistance) {
      closest = entry;
      closestDistance = distance;
    }
  }
  return closest?.tier;
}
async function loadXylabsEslintConfigPackage(cwd, isReact) {
  const packageName = isReact ? "@xylabs/eslint-config-react-flat" : "@xylabs/eslint-config-flat";
  const requireFromCwd = createRequire(path2.join(cwd, "package.json"));
  const resolved = requireFromCwd.resolve(packageName);
  return import(pathToFileURL(resolved).href);
}
function resolveTierConfigExport(configPackage, exportName) {
  const configs = configPackage[exportName];
  if (!Array.isArray(configs)) {
    throw new TypeError(`Missing ESLint tier export "${exportName}" from @xylabs/eslint-config`);
  }
  return configs;
}
function mergeTierRules(mergeConfigRules, configs) {
  return mergeConfigRules(configs);
}
async function loadMergeConfigRules(cwd) {
  const flatPackage = await loadXylabsEslintConfigPackage(cwd, false);
  const mergeConfigRules = flatPackage.mergeConfigRules;
  if (typeof mergeConfigRules !== "function") {
    throw new TypeError("mergeConfigRules is missing from @xylabs/eslint-config-flat");
  }
  return mergeConfigRules;
}
async function buildLintTierRuleMaps(cwd, context) {
  const configPackage = await loadXylabsEslintConfigPackage(cwd, context.isReact);
  const mergeConfigRules = await loadMergeConfigRules(cwd);
  const definitions = getLintTierDefinitions(context.isReact, context.isTypeChecked);
  const maps = /* @__PURE__ */ new Map();
  for (const definition of definitions) {
    const configs = resolveTierConfigExport(configPackage, definition.exportName);
    maps.set(definition.id, mergeTierRules(mergeConfigRules, configs));
  }
  return maps;
}
function projectLintTierCounts(messages, tierRuleMaps, definitions) {
  return definitions.map((definition) => {
    const rules = tierRuleMaps.get(definition.id) ?? {};
    const { errors, warnings } = countMessagesForTier(messages, rules);
    return {
      errors,
      label: definition.label,
      tier: definition.id,
      warnings
    };
  });
}
function formatLintTierAnalysisReport({
  actual,
  context,
  counts,
  currentTierExport,
  files,
  timeMs
}) {
  const definitions = getLintTierDefinitions(context.isReact, context.isTypeChecked);
  const currentTierId = definitions.find((tier) => tier.exportName === currentTierExport)?.id;
  const closestTierId = context.configKind === "custom" ? findClosestTierPreset(actual, counts) : currentTierId;
  const profile = [
    context.isReact ? "react" : "flat",
    context.isTypeChecked ? "type-checked" : "untyped"
  ].join(", ");
  const labelWidth = Math.max(...counts.map((entry) => entry.label.length), "Experimental".length);
  const lines = [
    chalk2.cyan("Lint tier analysis"),
    chalk2.gray(`XY preset projection (${profile}); based on your eslint.config.ts with no extra ESLint passes`),
    chalk2.white(`Your lint run: ${actual.errors} errors, ${actual.warnings} warnings`),
    "",
    chalk2.gray("If you switched to each XY tier preset:"),
    ` ${"Tier".padEnd(4)} ${"Preset".padEnd(labelWidth)}  ${"Errors".padStart(6)}  ${"Warnings".padStart(8)}`,
    ` ${"-".repeat(4)} ${"-".repeat(labelWidth)}  ${"-".repeat(6)}  ${"-".repeat(8)}`
  ];
  for (const entry of counts) {
    const isCurrentPreset = context.configKind === "preset" && entry.tier === currentTierId;
    const isClosestPreset = context.configKind === "custom" && entry.tier === closestTierId;
    const marker = isCurrentPreset ? chalk2.gray("  <- current preset") : isClosestPreset ? chalk2.gray("  <- closest preset") : "";
    lines.push(
      ` ${String(entry.tier).padEnd(4)} ${entry.label.padEnd(labelWidth)}  ${String(entry.errors).padStart(6)}  ${String(entry.warnings).padStart(8)}${marker}`
    );
  }
  if (context.configKind === "custom") {
    lines.push(
      "",
      chalk2.yellow("Note: eslint.config.ts composes XY modules directly instead of exporting a single tier preset. Higher-tier error counts promote current warnings to errors.")
    );
  } else if (currentTierId !== void 0 && currentTierId < 4) {
    lines.push(
      "",
      chalk2.yellow("Note: eslint.config.ts is below tier 4. Counts for higher tiers only include violations ESLint reported with your current config and may be understated.")
    );
  }
  lines.push(
    "",
    chalk2.gray(`Analyzed ${files} files in ${timeMs < 1e3 ? `${timeMs}ms` : `${(timeMs / 1e3).toFixed(2)}s`}`)
  );
  return lines.join("\n");
}

// src/actions/result.ts
function actionResult({
  errorCount,
  exitCode = errorCount,
  warningCount
}) {
  if (errorCount === 0 && warningCount === 0 && exitCode === 0) return 0;
  return {
    envelope: {
      errorCount,
      warningCount
    },
    exitCode
  };
}
function resultFromExitCode(exitCode) {
  return actionResult({
    errorCount: exitCode === 0 ? 0 : Math.max(1, exitCode),
    exitCode,
    warningCount: 0
  });
}

// src/actions/lintNext.ts
var lintNextIgnorePatterns = ["packages/**"];
var lintNextResultMarker = "__XY_LINT_NEXT_RESULT__";
var require2 = createRequire2(import.meta.url);
var chalkImportUrl = pathToFileURL2(require2.resolve("chalk")).href;
var cycleRuleFilePatterns = [
  "**/*.ts",
  "**/*.tsx",
  "**/*.mts",
  "**/*.cts",
  "**/*.js",
  "**/*.jsx",
  "**/*.cjs",
  "**/*.mjs",
  "**/*.d.ts",
  "**/*.d.tsx",
  "**/*.d.jsx",
  "**/*.d.mts",
  "**/*.d.cts"
];
var lintNextWorkerSource = String.raw`
import path from 'node:path'
import { ESLint } from 'eslint'

const marker = ${JSON.stringify(lintNextResultMarker)}
const options = JSON.parse(process.env.XY_LINT_NEXT_OPTIONS ?? '{}')
const cycleRuleFilePatterns = ${JSON.stringify(cycleRuleFilePatterns)}
const { default: chalk } = await import(process.env.XY_LINT_NEXT_CHALK_URL)
const colors = ['white', 'yellow', 'red']
const severity = ['none', 'warning', 'error']

function dumpMessages(lintResults) {
  for (const lintResult of lintResults) {
    if (lintResult.messages.length === 0) continue
    console.log(chalk.gray('\n' + lintResult.filePath))
    for (const message of lintResult.messages) {
      console.log(
        chalk.gray('\t' + message.line + ':' + message.column),
        chalk[colors[message.severity]]('\t' + severity[message.severity]),
        chalk.white('\t' + message.message),
        chalk.gray('\t' + message.ruleId),
      )
    }
  }
}

async function createLintEngine(cwd) {
  const cycleOverrideConfig = options.cycleDepth === undefined
    ? undefined
    : {
        files: cycleRuleFilePatterns,
        rules: { 'import-x/no-cycle': ['warn', { maxDepth: options.cycleDepth }] },
      }
  return new ESLint({
    cache: options.cache,
    cacheLocation: options.cacheLocation ?? path.join(cwd, '.eslintcache'),
    cacheStrategy: 'content',
    cwd,
    fix: options.fix,
    ignorePatterns: options.ignorePatterns,
    overrideConfig: cycleOverrideConfig,
    warnIgnored: false,
  })
}

try {
  const cwd = process.cwd()
  const engine = await createLintEngine(cwd)
  const lintResults = await engine.lintFiles('.')
  if (!options.analyze || options.verbose) {
    dumpMessages(lintResults)
  }

  if (options.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
  const messages = options.analyze
    ? lintResults.flatMap((result) => result.messages.map((message) => ({
        ruleId: message.ruleId ?? null,
        severity: message.severity,
      })))
    : undefined

  if (options.verbose) {
    const filesColor = files < 100 ? 'green' : files < 1000 ? 'yellow' : 'red'
    console.log(chalk.white('  ' + chalk[filesColor](files) + ' files linted'))
  }

  console.log(marker + JSON.stringify({ errors, files, messages, warnings }))
} catch (ex) {
  console.error(ex instanceof Error ? (ex.stack ?? ex.message) : String(ex))
  console.log(marker + JSON.stringify({ errors: 1, files: 0, messages: [], warnings: 0 }))
  process.exitCode = 1
}
`;
function formatDuration(ms) {
  if (ms < 1e3) return `${ms}ms`;
  return `${(ms / 1e3).toFixed(2)}s`;
}
function resultColor(result) {
  if (result.errors > 0) return "red";
  if (result.warnings > 0) return "yellow";
  return "green";
}
function parseLintNextOutput(output, status) {
  const markerIndex = output.lastIndexOf(lintNextResultMarker);
  if (markerIndex === -1) {
    return {
      errors: status === 0 ? 0 : 1,
      files: 0,
      messages: [],
      output,
      warnings: 0
    };
  }
  const beforeMarker = output.slice(0, markerIndex);
  const afterMarker = output.slice(markerIndex + lintNextResultMarker.length);
  const [jsonLine = "", ...remainingLines] = afterMarker.split(/\r?\n/);
  try {
    const parsed = JSON.parse(jsonLine);
    return {
      errors: parsed.errors,
      files: parsed.files,
      messages: parsed.messages ?? [],
      output: beforeMarker + remainingLines.join("\n"),
      warnings: parsed.warnings
    };
  } catch {
    return {
      errors: status === 0 ? 0 : 1,
      files: 0,
      messages: [],
      output,
      warnings: 0
    };
  }
}
async function lintOnePackageProcess({
  analyze,
  cache,
  cacheLocation,
  cwd,
  cycleDepth,
  fix,
  verbose
}) {
  return await new Promise((resolve) => {
    const output = [];
    const env = {
      ...process.env,
      FORCE_COLOR: "3",
      XY_LINT_NEXT_OPTIONS: JSON.stringify({
        analyze,
        cache,
        cacheLocation,
        cycleDepth,
        fix,
        ignorePatterns: lintNextIgnorePatterns,
        verbose
      }),
      XY_LINT_NEXT_CHALK_URL: chalkImportUrl
    };
    delete env.NO_COLOR;
    delete env.NODE_DISABLE_COLORS;
    const child = spawn(process.execPath, ["--input-type=module", "--eval", lintNextWorkerSource], {
      cwd,
      env,
      stdio: ["ignore", "pipe", "pipe"]
    });
    child.stdout?.on("data", (chunk) => {
      output.push(String(chunk));
    });
    child.stderr?.on("data", (chunk) => {
      output.push(String(chunk));
    });
    child.on("error", (ex) => {
      resolve({
        errors: 1,
        files: 0,
        messages: [],
        output: `${ex.message}
`,
        warnings: 0
      });
    });
    child.on("close", (status) => {
      resolve(parseLintNextOutput(output.join(""), status));
    });
  });
}
function printPackageResult(label, result) {
  const color = resultColor(result);
  console.log(
    chalk3[color](`${label} [${result.pkg}]`) + chalk3.gray(` (${result.files} files, ${formatDuration(result.timeMs)})`)
  );
  if (result.output.length > 0) {
    process.stdout.write(result.output.endsWith("\n") ? result.output : `${result.output}
`);
  }
}
function selectLintWorkspaces(allWorkspaces, pkg, targetWorkspaces) {
  if (pkg === void 0) return targetWorkspaces ?? allWorkspaces;
  const targetWorkspace = resolveWorkspace(allWorkspaces, pkg);
  return targetWorkspace === void 0 ? [] : [targetWorkspace];
}
function getLintLabel(isAnalyze, isFix, cycleDepth) {
  if (isAnalyze) return "Analyze";
  if (isFix) return "Fix";
  if (cycleDepth === void 0) return "Lint";
  return "Cycle";
}
function resolveAnalyzeContext(isAnalyze, rootDir) {
  if (!isAnalyze) return { kind: "disabled" };
  const tierContext = detectLintTierContext(rootDir);
  if (!tierContext.hasXylabsConfig) {
    console.error(chalk3.red("Lint tier analysis requires @xylabs/eslint-config-flat or @xylabs/eslint-config-react-flat in eslint.config.ts"));
    return { kind: "invalid" };
  }
  return { kind: "ready", tierContext };
}
async function printLintAnalyzeReport(rootDir, tierContext, totals, timeMs) {
  const tierRuleMaps = await buildLintTierRuleMaps(rootDir, tierContext);
  const definitions = getLintTierDefinitions(tierContext.isReact, tierContext.isTypeChecked);
  const tierCounts = projectLintTierCounts(totals.messages, tierRuleMaps, definitions);
  console.log(formatLintTierAnalysisReport({
    actual: countActualLintMessages(totals.messages),
    context: tierContext,
    counts: tierCounts,
    currentTierExport: tierContext.currentTierExport,
    files: totals.files,
    timeMs
  }));
}
function printLintSummary(totalErrors, totalWarnings, totalFiles, packageCount) {
  const errColor = totalErrors > 0 ? "red" : "green";
  const warnColor = totalWarnings > 0 ? "yellow" : "green";
  console.log(
    chalk3[errColor](`${totalErrors} errors`) + chalk3.gray(", ") + chalk3[warnColor](`${totalWarnings} warnings`) + chalk3.gray(` across ${totalFiles} files in ${packageCount} packages`)
  );
  return actionResult({
    errorCount: totalErrors,
    exitCode: totalErrors + (isStrictMode() ? totalWarnings : 0),
    warningCount: totalWarnings
  });
}
function totalLintResults(results) {
  const total = {
    errors: 0,
    files: 0,
    messages: [],
    warnings: 0
  };
  for (const result of results) {
    total.errors += result.errors;
    total.files += result.files;
    total.warnings += result.warnings;
    total.messages.push(...result.messages);
  }
  return total;
}
async function lintNext({
  analyze = false,
  cache = false,
  cycleDepth,
  fix = false,
  jobs,
  pkg,
  verbose = false,
  workspaces: targetWorkspaces
}) {
  const rootDir = INIT_CWD();
  const analyzeContext = resolveAnalyzeContext(analyze, rootDir);
  if (analyzeContext.kind === "invalid") {
    return resultFromExitCode(1);
  }
  const tierContext = analyzeContext.kind === "ready" ? analyzeContext.tierContext : void 0;
  const pm = getPackageManager();
  const allWorkspaces = pm.listWorkspaces();
  const workspaces = selectLintWorkspaces(allWorkspaces, pkg, targetWorkspaces);
  if (pkg === void 0 && targetWorkspaces !== void 0 && workspaces.length === 0) {
    console.log(chalk3.gray("No workspaces to lint"));
    return 0;
  }
  if (workspaces.length === 0) {
    console.log(chalk3.red(pkg != null && pkg.length > 0 ? `Package "${pkg}" not found` : "No workspaces found"));
    return resultFromExitCode(1);
  }
  const concurrency = jobs;
  const label = getLintLabel(analyze, fix, cycleDepth);
  const analyzeStarted = Date.now();
  const results = Array.from(
    { length: workspaces.length },
    () => ({
      errors: 0,
      files: 0,
      messages: [],
      output: "",
      pkg: "",
      timeMs: 0,
      warnings: 0
    })
  );
  await runWithConcurrency(
    workspaces.map((ws, i) => ({ i, ws })),
    concurrency,
    async ({ i, ws }) => {
      const pkgStart = Date.now();
      const absCwd = path3.resolve(rootDir, ws.location);
      const cacheLocation = cache ? workspaceEslintCachePath(rootDir, ws.location) : void 0;
      if (cacheLocation !== void 0) ensureEslintCacheDir(cacheLocation);
      const {
        errors,
        files,
        messages,
        output,
        warnings
      } = await lintOnePackageProcess({
        analyze,
        cache,
        cacheLocation,
        cwd: absCwd,
        cycleDepth,
        fix,
        verbose
      });
      const result = {
        errors,
        files,
        messages,
        output,
        pkg: ws.name,
        timeMs: Date.now() - pkgStart,
        warnings
      };
      results[i] = result;
      printPackageResult(label, result);
    }
  );
  const {
    errors: totalErrors,
    files: totalFiles,
    messages: totalMessages,
    warnings: totalWarnings
  } = totalLintResults(results);
  if (analyze && tierContext !== void 0) {
    await printLintAnalyzeReport(rootDir, tierContext, {
      errors: totalErrors,
      files: totalFiles,
      messages: totalMessages,
      warnings: totalWarnings
    }, Date.now() - analyzeStarted);
    return 0;
  }
  return printLintSummary(totalErrors, totalWarnings, totalFiles, workspaces.length);
}
export {
  lintNext
};
//# sourceMappingURL=lintNext.mjs.map
