"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
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 binary_resolution_exports = {};
__export(binary_resolution_exports, {
  findBinaryPath: () => findBinaryPath,
  makePackageBinsExecutable: () => makePackageBinsExecutable,
  resolveBinaryPath: () => resolveBinaryPath
});
module.exports = __toCommonJS(binary_resolution_exports);
var import_platform = require("../constants/platform");
var import_read_json = require("../fs/read-json");
var import_libnpmexec = __toESM(require("../external/libnpmexec"));
var import_normalize = require("../paths/normalize");
var import_error = require("../primordials/error");
var import_object = require("../primordials/object");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
var import_internal = require("./_internal");
function findBinaryPath(packageDir, packageName, binaryName) {
  const path = (0, import_path.getNodePath)();
  const installedDir = (0, import_normalize.normalizePath)(
    path.join(packageDir, "node_modules", packageName)
  );
  const pkgJsonPath = path.join(installedDir, "package.json");
  const pkgJson = (0, import_read_json.readJsonSync)(pkgJsonPath);
  const bin = pkgJson["bin"];
  let binName;
  let binPath;
  if (typeof bin === "string") {
    binPath = bin;
  } else if (typeof bin === "object" && bin !== null) {
    const binObj = bin;
    const binKeys = (0, import_object.ObjectKeys)(binObj);
    if (binKeys.length === 1) {
      binName = binKeys[0];
      binPath = binObj[binName];
    } else {
      try {
        const { getBinFromManifest } = import_libnpmexec.default;
        binName = getBinFromManifest({
          name: packageName,
          bin: binObj,
          _id: `${packageName}@${pkgJson.version || "unknown"}`
        });
        binPath = binObj[binName];
      } catch {
        const lastSegment = packageName.split("/").pop() ?? packageName;
        const candidates = [
          binaryName,
          lastSegment,
          packageName.replace(/^@[^/]+\//, "")
        ].filter(Boolean);
        for (const candidate of candidates) {
          if (candidate && binObj[candidate]) {
            binName = candidate;
            binPath = binObj[candidate];
            break;
          }
        }
        if (!binPath && binKeys.length > 0) {
          binName = binKeys[0];
          binPath = binObj[binName];
        }
      }
    }
  }
  if (!binPath) {
    throw new import_error.ErrorCtor(`No binary found for package "${packageName}"`);
  }
  const rawPath = (0, import_normalize.normalizePath)(path.join(installedDir, binPath));
  return resolveBinaryPath(rawPath);
}
function makePackageBinsExecutable(packageDir, packageName) {
  if (import_platform.WIN32) {
    return;
  }
  const fs = (0, import_fs.getNodeFs)();
  const path = (0, import_path.getNodePath)();
  const installedDir = (0, import_normalize.normalizePath)(
    path.join(packageDir, "node_modules", packageName)
  );
  const pkgJsonPath = path.join(installedDir, "package.json");
  try {
    const pkgJson = (0, import_read_json.readJsonSync)(pkgJsonPath);
    const bin = pkgJson["bin"];
    if (!bin) {
      return;
    }
    const binPaths = [];
    if (typeof bin === "string") {
      binPaths.push(bin);
    } else if (typeof bin === "object" && bin !== null) {
      const binObj = bin;
      binPaths.push(...(0, import_object.ObjectValues)(binObj));
    }
    for (const binPath of binPaths) {
      const fullPath = (0, import_normalize.normalizePath)(path.join(installedDir, binPath));
      if (fs.existsSync(fullPath)) {
        try {
          fs.chmodSync(fullPath, 493);
        } catch {
        }
      }
    }
  } catch {
  }
}
function resolveBinaryPath(basePath) {
  if (!import_platform.WIN32) {
    return basePath;
  }
  const fs = (0, import_fs.getNodeFs)();
  const cached = import_internal.binaryPathCache.get(basePath);
  if (cached) {
    if (fs.existsSync(cached)) {
      (0, import_internal.binaryPathCacheSet)(basePath, cached);
      return cached;
    }
    import_internal.binaryPathCache.delete(basePath);
  }
  const extensions = [".cmd", ".bat", ".ps1", ".exe", ""];
  for (const ext of extensions) {
    const testPath = basePath + ext;
    if (fs.existsSync(testPath)) {
      (0, import_internal.binaryPathCacheSet)(basePath, testPath);
      return testPath;
    }
  }
  return basePath;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  findBinaryPath,
  makePackageBinsExecutable,
  resolveBinaryPath
});
