"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const events = require("./fetch-virtual-server-J6SUa9HS.cjs");
const jsonc = require("./jsonc-QW8UOlGt.cjs");
const FORMATTER_CONFIG_NAMES = [
  "oxfmtrc.json",
  "oxfmtrc.jsonc",
  ".oxfmtrc",
  ".oxfmtrc.json",
  ".oxfmtrc.jsonc"
];
const LINTER_CONFIG_NAMES = [
  "oxlintrc.json",
  "oxlintrc.jsonc",
  ".oxlintrc",
  ".oxlintrc.json",
  ".oxlintrc.jsonc"
];
const SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
  ".js",
  ".jsx",
  ".ts",
  ".tsx",
  ".mjs",
  ".cjs",
  ".mts",
  ".cts"
]);
let oxcBindingPromise = null;
function isNodeLikeEnvironment() {
  var _a;
  return typeof process !== "undefined" && !!((_a = process.versions) == null ? void 0 : _a.node) && typeof window === "undefined";
}
async function loadOxcBinding() {
  if (isNodeLikeEnvironment()) {
    const { getOxcNodeBinding } = await Promise.resolve().then(() => require("./node-binding-DmyaZPEl.cjs"));
    const mod = await getOxcNodeBinding();
    return {
      Oxc: mod.exports.Oxc
    };
  }
  const { getOxcBrowserBinding } = await Promise.resolve().then(() => require("./browser-binding-By3gn-kN.cjs"));
  const binding = await getOxcBrowserBinding();
  return {
    Oxc: binding.exports.Oxc
  };
}
async function getOxcBinding() {
  oxcBindingPromise ?? (oxcBindingPromise = loadOxcBinding());
  return oxcBindingPromise;
}
function normalizeAbsolutePath(filePath) {
  if (!filePath) {
    return "/";
  }
  if (events.isAbsolute(filePath)) {
    return events.normalize(filePath);
  }
  return events.normalize(`/${filePath}`);
}
function findNearestConfigPath(accessor, startingDirectory, candidateNames) {
  let currentDirectory = normalizeAbsolutePath(startingDirectory);
  while (true) {
    for (const candidateName of candidateNames) {
      const candidatePath = events.join(currentDirectory, candidateName);
      if (accessor.exists(candidatePath)) {
        return candidatePath;
      }
    }
    const parentDirectory = events.dirname(currentDirectory);
    if (parentDirectory === currentDirectory) {
      return null;
    }
    currentDirectory = parentDirectory;
  }
}
function resolveSeverity(input) {
  switch ((input || "").toLowerCase()) {
    case "error":
      return "error";
    case "warning":
      return "warning";
    default:
      return "info";
  }
}
function isRawOxcDiagnostic(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  return typeof value.message === "string";
}
function isSupportedOxcPath(filePath) {
  return SUPPORTED_EXTENSIONS.has(events.extname(filePath).toLowerCase());
}
function resolveOxcParserExtension(filePath) {
  const extension = events.extname(filePath).toLowerCase();
  switch (extension) {
    case ".jsx":
      return "jsx";
    case ".tsx":
      return "tsx";
    case ".ts":
    case ".mts":
    case ".cts":
      return "ts";
    default:
      return "js";
  }
}
function resolveOxcConfigForFile(accessor, filePath) {
  const absoluteFilePath = normalizeAbsolutePath(filePath);
  const startingDirectory = events.dirname(absoluteFilePath);
  const formatterConfigPath = findNearestConfigPath(accessor, startingDirectory, FORMATTER_CONFIG_NAMES);
  const linterConfigPath = findNearestConfigPath(accessor, startingDirectory, LINTER_CONFIG_NAMES);
  return {
    formatterConfigPath,
    formatterConfigText: formatterConfigPath ? accessor.readText(formatterConfigPath) : null,
    linterConfigPath,
    linterConfigText: linterConfigPath ? accessor.readText(linterConfigPath) : null
  };
}
function formatOxcDiagnosticsForTerminal(filePath, sourceText, diagnostics) {
  if (diagnostics.length === 0) {
    return "";
  }
  const lineStarts = [0];
  for (let index = 0; index < sourceText.length; index += 1) {
    if (sourceText[index] === "\n") {
      lineStarts.push(index + 1);
    }
  }
  const offsetToPosition = (offset) => {
    const safeOffset = Math.max(0, Math.min(offset, sourceText.length));
    let line = 0;
    while (line + 1 < lineStarts.length && lineStarts[line + 1] <= safeOffset) {
      line += 1;
    }
    return {
      line: line + 1,
      column: safeOffset - lineStarts[line] + 1
    };
  };
  return diagnostics.map((diagnostic) => {
    const position = offsetToPosition(diagnostic.start);
    const suffix = diagnostic.helpMessage ? ` (${diagnostic.helpMessage})` : "";
    return `${filePath}:${position.line}:${position.column}: ${diagnostic.severity}: ${diagnostic.message}${suffix}`;
  }).join("\n");
}
async function runOxcOnSource(options) {
  const binding = await getOxcBinding();
  const oxc = new binding.Oxc();
  const formatterOptions = jsonc.parseJsoncObject(options.formatterConfigText);
  oxc.run(options.sourceText, {
    run: {
      lint: options.lint !== false,
      formatter: options.format !== false,
      transform: false,
      isolatedDeclarations: false,
      whitespace: false,
      compress: false,
      mangle: false,
      scope: false,
      symbol: false,
      cfg: false
    },
    parser: {
      extension: resolveOxcParserExtension(options.filePath),
      allowReturnOutsideFunction: false,
      preserveParens: false,
      allowV8Intrinsics: false,
      semanticErrors: true
    },
    linter: options.linterConfigText ? { config: options.linterConfigText } : {},
    formatter: formatterOptions ?? void 0
  });
  const diagnostics = (oxc.getDiagnostics() || []).filter(isRawOxcDiagnostic).map((diagnostic) => {
    var _a;
    const firstLabel = (_a = diagnostic.labels) == null ? void 0 : _a[0];
    return {
      severity: resolveSeverity(diagnostic.severity),
      message: diagnostic.message,
      start: (firstLabel == null ? void 0 : firstLabel.start) ?? 0,
      end: (firstLabel == null ? void 0 : firstLabel.end) ?? (firstLabel == null ? void 0 : firstLabel.start) ?? 0,
      helpMessage: diagnostic.helpMessage ?? null
    };
  });
  const rawFormattedText = oxc.formatterFormattedText || oxc.formattedText || "";
  return {
    formattedText: options.format === false ? null : rawFormattedText,
    diagnostics: options.lint === false ? [] : diagnostics
  };
}
exports.formatOxcDiagnosticsForTerminal = formatOxcDiagnosticsForTerminal;
exports.isSupportedOxcPath = isSupportedOxcPath;
exports.resolveOxcConfigForFile = resolveOxcConfigForFile;
exports.resolveOxcParserExtension = resolveOxcParserExtension;
exports.runOxcOnSource = runOxcOnSource;
//# sourceMappingURL=runtime-BFolbRtR.cjs.map
