"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var resolve_exports = {};
__export(resolve_exports, {
  resolveRealBinSync: () => resolveRealBinSync
});
module.exports = __toCommonJS(resolve_exports);
var import_platform = require("../constants/platform");
var import_read_json = require("../fs/read-json");
var import_normalize = require("../paths/normalize");
var import_string = require("../primordials/string");
var import_internal = require("./_internal");
var import_which = require("./which");
// @__NO_SIDE_EFFECTS__
function resolveRealBinSync(binPath) {
  const fs = (0, import_internal.getFs)();
  const path = (0, import_internal.getPath)();
  if (!path.isAbsolute(binPath)) {
    try {
      const resolved = (0, import_which.whichRealSync)(binPath);
      if (resolved) {
        binPath = resolved;
      }
    } catch {
    }
  }
  binPath = (0, import_normalize.normalizePath)(binPath);
  if (binPath === ".") {
    return binPath;
  }
  const ext = path.extname(binPath);
  const extLowered = ext.toLowerCase();
  const basename = path.basename(binPath, ext);
  const voltaIndex = basename === "node" ? -1 : /(?<=\/)\.volta\//i.exec(binPath)?.index ?? -1;
  if (voltaIndex !== -1) {
    const voltaPath = binPath.slice(0, voltaIndex);
    const voltaCacheKey = `${voltaPath}:${basename}`;
    const cachedVolta = import_internal.voltaBinCache.get(voltaCacheKey);
    if (cachedVolta) {
      if (fs.existsSync(cachedVolta)) {
        return cachedVolta;
      }
      import_internal.voltaBinCache.delete(voltaCacheKey);
    }
    const voltaToolsPath = path.join(voltaPath, "tools");
    const voltaImagePath = path.join(voltaToolsPath, "image");
    const voltaUserPath = path.join(voltaToolsPath, "user");
    const voltaPlatform = (0, import_read_json.readJsonSync)(
      path.join(voltaUserPath, "platform.json"),
      { throws: false }
    );
    const voltaNodeVersion = voltaPlatform?.node?.runtime;
    const voltaNpmVersion = voltaPlatform?.node?.npm;
    let voltaBinPath = "";
    if (basename === "npm" || basename === "npx") {
      if (voltaNpmVersion) {
        const relCliPath = `bin/${basename}-cli.js`;
        voltaBinPath = path.join(
          voltaImagePath,
          `npm/${voltaNpmVersion}/${relCliPath}`
        );
        if (voltaNodeVersion && !fs.existsSync(voltaBinPath)) {
          voltaBinPath = path.join(
            voltaImagePath,
            `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`
          );
          if (!fs.existsSync(voltaBinPath)) {
            voltaBinPath = "";
          }
        }
      }
    } else {
      const voltaUserBinPath = path.join(voltaUserPath, "bin");
      const binInfo = (0, import_read_json.readJsonSync)(
        path.join(voltaUserBinPath, `${basename}.json`),
        { throws: false }
      );
      const binPackage = binInfo?.package;
      if (binPackage) {
        voltaBinPath = path.join(
          voltaImagePath,
          `packages/${binPackage}/bin/${basename}`
        );
        if (!fs.existsSync(voltaBinPath)) {
          voltaBinPath = `${voltaBinPath}.cmd`;
          if (!fs.existsSync(voltaBinPath)) {
            voltaBinPath = "";
          }
        }
      }
    }
    if (voltaBinPath) {
      let resolvedVoltaPath = voltaBinPath;
      try {
        resolvedVoltaPath = (0, import_normalize.normalizePath)(fs.realpathSync.native(voltaBinPath));
      } catch {
      }
      import_internal.voltaBinCache.set(voltaCacheKey, resolvedVoltaPath);
      return resolvedVoltaPath;
    }
  }
  if (import_platform.WIN32) {
    const hasKnownExt = extLowered === "" || extLowered === ".cmd" || extLowered === ".exe" || extLowered === ".ps1";
    const isNpmOrNpx = basename === "npm" || basename === "npx";
    const isPnpmOrYarn = basename === "pnpm" || basename === "yarn";
    if (hasKnownExt && isNpmOrNpx) {
      const quickPath = path.join(
        path.dirname(binPath),
        `node_modules/npm/bin/${basename}-cli.js`
      );
      if (fs.existsSync(quickPath)) {
        try {
          return fs.realpathSync.native(quickPath);
        } catch {
        }
        return quickPath;
      }
    }
    let relPath = "";
    if (hasKnownExt && // Only parse shell scripts and batch files, not actual executables.
    // .exe files are already executables and don't need path resolution from wrapper scripts.
    extLowered !== ".exe" && // Check if file exists before attempting to read it to avoid ENOENT errors.
    fs.existsSync(binPath)) {
      const source = fs.readFileSync(binPath, "utf8");
      if (isNpmOrNpx) {
        if (extLowered === ".cmd") {
          relPath = basename === "npm" ? /(?<="NPM_CLI_JS=%~dp0\\).*(?=")/.exec(source)?.[0] || "" : /(?<="NPX_CLI_JS=%~dp0\\).*(?=")/.exec(source)?.[0] || "";
        } else if (extLowered === "") {
          relPath = basename === "npm" ? /(?<=NPM_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "" : /(?<=NPX_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "";
        } else if (extLowered === ".ps1") {
          relPath = basename === "npm" ? /(?<=\$NPM_CLI_JS="\$PSScriptRoot\/).*(?=")/.exec(
            source
          )?.[0] || "" : /(?<=\$NPX_CLI_JS="\$PSScriptRoot\/).*(?=")/.exec(
            source
          )?.[0] || "";
        }
      } else if (isPnpmOrYarn) {
        if (extLowered === ".cmd") {
          relPath = /(?<=node\s+")%~dp0\\([^"]+)(?="\s+%\*)/.exec(source)?.[1] || "";
          if (!relPath) {
            relPath = /(?<="%~dp0\\[^"]*node[^"]*"\s+")%~dp0\\([^"]+)(?="\s+%\*)/.exec(
              source
            )?.[1] || "";
          }
          if (!relPath) {
            relPath = /(?<="%dp0%\\).*(?=" %\*\r\n)/.exec(source)?.[0] || "";
          }
        } else if (extLowered === "") {
          relPath = /(?<="\$basedir\/)\.tools\/pnpm\/[^"]+(?="\s+"\$@")/.exec(
            source
          )?.[0] || "";
          if (!relPath) {
            relPath = /(?<=exec\s+node\s+"\$basedir\/)\.tools\/pnpm\/[^"]+(?="\s+"\$@")/.exec(
              source
            )?.[0] || "";
          }
          if (!relPath) {
            relPath = /(?<="\$basedir\/).*(?=" "\$@"\n)/.exec(source)?.[0] || "";
          }
        } else if (extLowered === ".ps1") {
          relPath = /(?<="\$basedir\/).*(?=" $args\n)/.exec(source)?.[0] || "";
        }
      } else if (extLowered === ".cmd") {
        relPath = /(?<="%dp0%\\).*(?=" %\*\r\n)/.exec(source)?.[0] || "";
      } else if (extLowered === "") {
        relPath = /(?<="$basedir\/).*(?=" "\$@"\n)/.exec(source)?.[0] || "";
      } else if (extLowered === ".ps1") {
        relPath = /(?<="\$basedir\/).*(?=" $args\n)/.exec(source)?.[0] || "";
      }
      if (relPath) {
        binPath = (0, import_normalize.normalizePath)(path.resolve(path.dirname(binPath), relPath));
      }
    }
  } else {
    let hasNoExt = extLowered === "";
    const isPnpmOrYarn = basename === "pnpm" || basename === "yarn";
    const isNpmOrNpx = basename === "npm" || basename === "npx";
    if (isPnpmOrYarn && binPath.includes("/.bin/pnpm/bin/")) {
      const binIndex = binPath.indexOf("/.bin/pnpm");
      if (binIndex !== -1) {
        const baseBinPath = binPath.slice(0, binIndex + "/.bin/pnpm".length);
        try {
          const stats = fs.statSync(baseBinPath);
          if (stats.isFile()) {
            binPath = (0, import_normalize.normalizePath)(baseBinPath);
            hasNoExt = !path.extname(binPath);
          }
        } catch {
        }
      }
    }
    if (hasNoExt && (isPnpmOrYarn || isNpmOrNpx) && // For extensionless files (Unix shell scripts), verify existence before reading.
    // This prevents ENOENT errors when the bin path doesn't exist.
    fs.existsSync(binPath)) {
      const source = fs.readFileSync(binPath, "utf8");
      let relPath = "";
      if (isPnpmOrYarn) {
        relPath = /(?<="\$basedir\/)\.tools\/[^"]+(?="\s+"\$@")/.exec(source)?.[0] || "";
        if (!relPath) {
          relPath = /(?<="\$basedir\/)[^"]+(?="\s+"\$@")/.exec(source)?.[0] || "";
        }
        if (!relPath) {
          const match = /exec\s+node\s+"?\$basedir\/([^"]+)"?\s+"\$@"/.exec(
            source
          );
          if (match) {
            relPath = match[1] || "";
          }
        }
        if (relPath && basename === "pnpm" && (0, import_string.StringPrototypeStartsWith)(relPath, "pnpm/")) {
          relPath = `../${relPath}`;
        }
      } else if (isNpmOrNpx) {
        relPath = basename === "npm" ? /(?<=NPM_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "" : /(?<=NPX_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "";
      }
      if (relPath) {
        binPath = (0, import_normalize.normalizePath)(path.resolve(path.dirname(binPath), relPath));
      }
    }
  }
  try {
    const realPath = fs.realpathSync.native(binPath);
    return (0, import_normalize.normalizePath)(realPath);
  } catch {
  }
  return (0, import_normalize.normalizePath)(binPath);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  resolveRealBinSync
});
