"use strict";
/* Socket Lib - Built with esbuild */
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bin_exports = {};
__export(bin_exports, {
  execBin: () => execBin,
  findRealBin: () => findRealBin,
  findRealNpm: () => findRealNpm,
  findRealPnpm: () => findRealPnpm,
  findRealYarn: () => findRealYarn,
  isShadowBinPath: () => isShadowBinPath,
  resolveRealBinSync: () => resolveRealBinSync,
  which: () => which,
  whichReal: () => whichReal,
  whichRealSync: () => whichRealSync,
  whichSync: () => whichSync
});
module.exports = __toCommonJS(bin_exports);
var import_node_fs = __toESM(require("node:fs"));
var import_node_path = __toESM(require("node:path"));
var import_home = require("./env/home");
var import_windows = require("./env/windows");
var import_xdg = require("./env/xdg");
var import_platform = require("./constants/platform");
var import_which = __toESM(require("./external/which"));
var import_fs = require("./fs");
var import_normalize = require("./paths/normalize");
var import_spawn = require("./spawn");
// @__NO_SIDE_EFFECTS__
async function execBin(binPath, args, options) {
  const resolvedPath = (0, import_normalize.isPath)(binPath) ? /* @__PURE__ */ resolveRealBinSync(binPath) : await whichReal(binPath);
  if (!resolvedPath) {
    const error = new Error(
      `Binary not found: ${binPath}
Possible causes:
  - Binary "${binPath}" is not installed or not in PATH
  - Binary name is incorrect or misspelled
  - Installation directory is not in system PATH
To resolve:
  1. Verify "${binPath}" is installed: which ${binPath} (Unix) or where ${binPath} (Windows)
  2. Install the binary if missing, ex: npm install -g ${binPath}
  3. Check PATH environment variable includes the binary location`
    );
    error.code = "ENOENT";
    throw error;
  }
  const binCommand = Array.isArray(resolvedPath) ? resolvedPath[0] : resolvedPath;
  return await (0, import_spawn.spawn)(binCommand, args ?? [], {
    shell: import_platform.WIN32,
    ...options
  });
}
function findRealBin(binName, commonPaths = []) {
  for (const binPath2 of commonPaths) {
    if (import_node_fs.default.existsSync(binPath2)) {
      return binPath2;
    }
  }
  const binPath = import_which.default.sync(binName, { nothrow: true });
  if (binPath) {
    const binDir = import_node_path.default.dirname(binPath);
    if (isShadowBinPath(binDir)) {
      const allPaths = import_which.default.sync(binName, { all: true, nothrow: true }) || [];
      const pathsArray = Array.isArray(allPaths) ? allPaths : typeof allPaths === "string" ? [allPaths] : [];
      for (const altPath of pathsArray) {
        const altDir = import_node_path.default.dirname(altPath);
        if (!isShadowBinPath(altDir)) {
          return altPath;
        }
      }
    }
    return binPath;
  }
  return void 0;
}
function findRealNpm() {
  const nodeDir = import_node_path.default.dirname(process.execPath);
  const npmInNodeDir = import_node_path.default.join(nodeDir, "npm");
  if (import_node_fs.default.existsSync(npmInNodeDir)) {
    return npmInNodeDir;
  }
  const commonPaths = ["/usr/local/bin/npm", "/usr/bin/npm"];
  const result = findRealBin("npm", commonPaths);
  if (result && import_node_fs.default.existsSync(result)) {
    return result;
  }
  const npmPath = whichRealSync("npm", { nothrow: true });
  if (npmPath && typeof npmPath === "string" && import_node_fs.default.existsSync(npmPath)) {
    return npmPath;
  }
  return "npm";
}
function findRealPnpm() {
  const commonPaths = import_platform.WIN32 ? [
    // Windows common paths.
    import_node_path.default.join((0, import_windows.getAppdata)(), "npm", "pnpm.cmd"),
    import_node_path.default.join((0, import_windows.getAppdata)(), "npm", "pnpm"),
    import_node_path.default.join((0, import_windows.getLocalappdata)(), "pnpm", "pnpm.cmd"),
    import_node_path.default.join((0, import_windows.getLocalappdata)(), "pnpm", "pnpm"),
    "C:\\Program Files\\nodejs\\pnpm.cmd",
    "C:\\Program Files\\nodejs\\pnpm"
  ].filter(Boolean) : [
    // Unix common paths.
    "/usr/local/bin/pnpm",
    "/usr/bin/pnpm",
    import_node_path.default.join(
      (0, import_xdg.getXdgDataHome)() || `${(0, import_home.getHome)()}/.local/share`,
      "pnpm/pnpm"
    ),
    import_node_path.default.join((0, import_home.getHome)(), ".pnpm/pnpm")
  ].filter(Boolean);
  return findRealBin("pnpm", commonPaths) ?? "";
}
function findRealYarn() {
  const commonPaths = [
    "/usr/local/bin/yarn",
    "/usr/bin/yarn",
    import_node_path.default.join((0, import_home.getHome)(), ".yarn/bin/yarn"),
    import_node_path.default.join(
      (0, import_home.getHome)(),
      ".config/yarn/global/node_modules/.bin/yarn"
    )
  ].filter(Boolean);
  return findRealBin("yarn", commonPaths) ?? "";
}
function isShadowBinPath(dirPath) {
  if (!dirPath) {
    return false;
  }
  const normalized = dirPath.replace(/\\/g, "/");
  return normalized.includes("node_modules/.bin");
}
// @__NO_SIDE_EFFECTS__
function resolveRealBinSync(binPath) {
  if (!import_node_path.default.isAbsolute(binPath)) {
    try {
      const resolved = whichRealSync(binPath);
      if (resolved) {
        binPath = resolved;
      }
    } catch {
    }
  }
  binPath = (0, import_normalize.normalizePath)(binPath);
  if (binPath === ".") {
    return binPath;
  }
  const ext = import_node_path.default.extname(binPath);
  const extLowered = ext.toLowerCase();
  const basename = import_node_path.default.basename(binPath, ext);
  const voltaIndex = basename === "node" ? -1 : /(?<=\/)\.volta\//i.exec(binPath)?.index ?? -1;
  if (voltaIndex !== -1) {
    const voltaPath = binPath.slice(0, voltaIndex);
    const voltaToolsPath = import_node_path.default.join(voltaPath, "tools");
    const voltaImagePath = import_node_path.default.join(voltaToolsPath, "image");
    const voltaUserPath = import_node_path.default.join(voltaToolsPath, "user");
    const voltaPlatform = (0, import_fs.readJsonSync)(
      import_node_path.default.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 = import_node_path.default.join(
          voltaImagePath,
          `npm/${voltaNpmVersion}/${relCliPath}`
        );
        if (voltaNodeVersion && !import_node_fs.default.existsSync(voltaBinPath)) {
          voltaBinPath = import_node_path.default.join(
            voltaImagePath,
            `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`
          );
          if (!import_node_fs.default.existsSync(voltaBinPath)) {
            voltaBinPath = "";
          }
        }
      }
    } else {
      const voltaUserBinPath = import_node_path.default.join(voltaUserPath, "bin");
      const binInfo = (0, import_fs.readJsonSync)(
        import_node_path.default.join(voltaUserBinPath, `${basename}.json`),
        { throws: false }
      );
      const binPackage = binInfo?.package;
      if (binPackage) {
        voltaBinPath = import_node_path.default.join(
          voltaImagePath,
          `packages/${binPackage}/bin/${basename}`
        );
        if (!import_node_fs.default.existsSync(voltaBinPath)) {
          voltaBinPath = `${voltaBinPath}.cmd`;
          if (!import_node_fs.default.existsSync(voltaBinPath)) {
            voltaBinPath = "";
          }
        }
      }
    }
    if (voltaBinPath) {
      try {
        return (0, import_normalize.normalizePath)(import_node_fs.default.realpathSync.native(voltaBinPath));
      } catch {
      }
      return voltaBinPath;
    }
  }
  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 = import_node_path.default.join(
        import_node_path.default.dirname(binPath),
        `node_modules/npm/bin/${basename}-cli.js`
      );
      if (import_node_fs.default.existsSync(quickPath)) {
        try {
          return import_node_fs.default.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.
    import_node_fs.default.existsSync(binPath)) {
      const source = import_node_fs.default.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)(import_node_path.default.resolve(import_node_path.default.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 = import_node_fs.default.statSync(baseBinPath);
          if (stats.isFile()) {
            binPath = (0, import_normalize.normalizePath)(baseBinPath);
            hasNoExt = !import_node_path.default.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.
    import_node_fs.default.existsSync(binPath)) {
      const source = import_node_fs.default.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" && relPath.startsWith("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)(import_node_path.default.resolve(import_node_path.default.dirname(binPath), relPath));
      }
    }
  }
  try {
    const realPath = import_node_fs.default.realpathSync.native(binPath);
    return (0, import_normalize.normalizePath)(realPath);
  } catch {
  }
  return (0, import_normalize.normalizePath)(binPath);
}
async function which(binName, options) {
  if ((0, import_normalize.isPath)(binName)) {
    return binName;
  }
  try {
    const result = await (0, import_which.default)(binName, options);
    return result;
  } catch {
    return null;
  }
}
async function whichReal(binName, options) {
  const opts = { nothrow: true, ...options };
  const result = await (0, import_which.default)(binName, opts);
  if (opts?.all) {
    const paths = Array.isArray(result) ? result : typeof result === "string" ? [result] : void 0;
    return paths?.length ? paths.map((p) => /* @__PURE__ */ resolveRealBinSync(p)) : paths;
  }
  if (!result) {
    return void 0;
  }
  return /* @__PURE__ */ resolveRealBinSync(result);
}
function whichRealSync(binName, options) {
  const opts = { nothrow: true, ...options };
  const result = whichSync(binName, opts);
  if (opts.all) {
    const paths = Array.isArray(result) ? result : typeof result === "string" ? [result] : void 0;
    return paths?.length ? paths.map((p) => /* @__PURE__ */ resolveRealBinSync(p)) : paths;
  }
  if (!result) {
    return void 0;
  }
  return /* @__PURE__ */ resolveRealBinSync(result);
}
function whichSync(binName, options) {
  if ((0, import_normalize.isPath)(binName)) {
    return binName;
  }
  try {
    const result = import_which.default.sync(binName, options);
    return result;
  } catch {
    return null;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  execBin,
  findRealBin,
  findRealNpm,
  findRealPnpm,
  findRealYarn,
  isShadowBinPath,
  resolveRealBinSync,
  which,
  whichReal,
  whichRealSync,
  whichSync
});
