/* 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 dlx_package_exports = {};
__export(dlx_package_exports, {
  dlxPackage: () => dlxPackage
});
module.exports = __toCommonJS(dlx_package_exports);
var import_node_crypto = require("node:crypto");
var import_node_fs = require("node:fs");
var import_node_path = __toESM(require("node:path"));
var import_platform = require("./constants/platform");
var import_fs = require("./fs");
var import_path = require("./path");
var import_paths = require("./paths");
var import_spawn = require("./spawn");
const rangeOperatorsRegExp = /[~^><=xX* ]|\|\|/;
function generatePackageCacheKey(packageSpec) {
  return (0, import_node_crypto.createHash)("sha256").update(packageSpec).digest("hex").slice(0, 16);
}
function parsePackageSpec(spec) {
  if (spec.startsWith("@")) {
    const parts = spec.split("@");
    if (parts.length === 3) {
      return { name: parts[1], version: parts[2] };
    }
    if (parts.length === 2) {
      return { name: `@${parts[1]}`, version: void 0 };
    }
    const scopeAndName = `@${parts[1]}`;
    return { name: scopeAndName, version: parts[2] };
  }
  const atIndex = spec.lastIndexOf("@");
  if (atIndex === -1) {
    return { name: spec, version: void 0 };
  }
  return {
    name: spec.slice(0, atIndex),
    version: spec.slice(atIndex + 1)
  };
}
async function ensurePackageInstalled(packageSpec, packageName, force) {
  const cacheKey = generatePackageCacheKey(packageSpec);
  const packageDir = (0, import_path.normalizePath)(import_node_path.default.join((0, import_paths.getSocketDlxDir)(), cacheKey));
  const installedDir = (0, import_path.normalizePath)(
    import_node_path.default.join(packageDir, "node_modules", packageName)
  );
  if (!force && (0, import_node_fs.existsSync)(installedDir)) {
    const pkgJsonPath = import_node_path.default.join(installedDir, "package.json");
    if ((0, import_node_fs.existsSync)(pkgJsonPath)) {
      return { installed: false, packageDir };
    }
  }
  await (0, import_spawn.spawn)(
    "npm",
    [
      "install",
      "--prefix",
      packageDir,
      "--no-save",
      "--no-package-lock",
      "--no-audit",
      "--no-fund",
      packageSpec
    ],
    {
      stdio: "pipe"
    }
  );
  return { installed: true, packageDir };
}
function findBinaryPath(packageDir, packageName, binaryName) {
  const installedDir = (0, import_path.normalizePath)(
    import_node_path.default.join(packageDir, "node_modules", packageName)
  );
  const pkgJsonPath = import_node_path.default.join(installedDir, "package.json");
  const pkgJson = (0, import_fs.readJsonSync)(pkgJsonPath);
  const bin = pkgJson["bin"];
  let binPath;
  if (typeof bin === "string") {
    binPath = bin;
  } else if (typeof bin === "object" && bin !== null) {
    const binName = binaryName || packageName.split("/").pop();
    binPath = bin[binName];
  }
  if (!binPath) {
    throw new Error(`No binary found for package "${packageName}"`);
  }
  return (0, import_path.normalizePath)(import_node_path.default.join(installedDir, binPath));
}
async function dlxPackage(args, options, spawnExtra) {
  const {
    force: userForce,
    package: packageSpec,
    spawnOptions
  } = { __proto__: null, ...options };
  const { name: packageName, version: packageVersion } = parsePackageSpec(packageSpec);
  const isVersionRange = packageVersion !== void 0 && rangeOperatorsRegExp.test(packageVersion);
  const force = userForce !== void 0 ? userForce : isVersionRange;
  const fullPackageSpec = packageVersion ? `${packageName}@${packageVersion}` : packageName;
  const { installed, packageDir } = await ensurePackageInstalled(
    fullPackageSpec,
    packageName,
    force
  );
  const binaryPath = findBinaryPath(packageDir, packageName);
  if (!import_platform.WIN32 && (0, import_node_fs.existsSync)(binaryPath)) {
    const { chmodSync } = require("node:fs");
    try {
      chmodSync(binaryPath, 493);
    } catch {
    }
  }
  const spawnPromise = (0, import_spawn.spawn)(binaryPath, args, spawnOptions, spawnExtra);
  return {
    binaryPath,
    installed,
    packageDir,
    spawnPromise
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  dlxPackage
});
//# sourceMappingURL=dlx-package.js.map
