"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 package_exports = {};
__export(package_exports, {
  binaryPathCacheSet: () => import_internal.binaryPathCacheSet,
  checkFirewallPurls: () => import_firewall2.checkFirewallPurls,
  dlxPackage: () => dlxPackage,
  downloadPackage: () => downloadPackage,
  ensurePackageInstalled: () => ensurePackageInstalled,
  executePackage: () => executePackage,
  findBinaryPath: () => import_binary_resolution2.findBinaryPath,
  makePackageBinsExecutable: () => import_binary_resolution2.makePackageBinsExecutable,
  npmPurl: () => import_firewall2.npmPurl,
  parsePackageSpec: () => import_spec2.parsePackageSpec,
  resolveBinaryPath: () => import_binary_resolution2.resolveBinaryPath
});
module.exports = __toCommonJS(package_exports);
var import_platform = require("../constants/platform");
var import_predicates = require("../errors/predicates");
var import_arborist = __toESM(require("../external/@npmcli/arborist"));
var import_safe = require("../fs/safe");
var import_normalize = require("../paths/normalize");
var import_socket = require("../paths/socket");
var import_lock_instance = require("../process/lock-instance");
var import_spawn = require("../spawn/spawn");
var import_cache = require("./cache");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
var import_binary_resolution = require("./binary-resolution");
var import_firewall = require("./firewall");
var import_spec = require("./spec");
var import_error = require("../primordials/error");
var import_regexp = require("../primordials/regexp");
var import_internal = require("./_internal");
var import_binary_resolution2 = require("./binary-resolution");
var import_firewall2 = require("./firewall");
var import_spec2 = require("./spec");
const rangeOperatorsRegExp = /[~^><=xX* ]|\|\|/;
async function dlxPackage(args, options, spawnExtra) {
  const downloadResult = await downloadPackage(options);
  const spawnPromise = executePackage(
    downloadResult.binaryPath,
    args,
    options.spawnOptions,
    spawnExtra
  );
  return {
    ...downloadResult,
    spawnPromise
  };
}
async function downloadPackage(options) {
  const {
    binaryName,
    force: userForce,
    hash,
    installRoot,
    lockfile,
    package: packageSpec,
    yes
  } = {
    __proto__: null,
    ...options
  };
  const { name: packageName, version: packageVersion } = (0, import_spec.parsePackageSpec)(packageSpec);
  const isVersionRange = packageVersion !== void 0 && (0, import_regexp.RegExpPrototypeTest)(rangeOperatorsRegExp, packageVersion);
  const force = userForce !== void 0 ? userForce : yes === true ? true : isVersionRange;
  const fullPackageSpec = packageVersion ? `${packageName}@${packageVersion}` : packageName;
  const { installed, packageDir } = await ensurePackageInstalled(
    packageName,
    fullPackageSpec,
    force,
    { hash, installRoot, lockfile }
  );
  const binaryPath = (0, import_binary_resolution.findBinaryPath)(packageDir, packageName, binaryName);
  (0, import_binary_resolution.makePackageBinsExecutable)(packageDir, packageName);
  return {
    binaryPath,
    installed,
    packageDir
  };
}
async function ensurePackageInstalled(packageName, packageSpec, force, install) {
  const fs = (0, import_fs.getNodeFs)();
  const path = (0, import_path.getNodePath)();
  const packageDir = (0, import_normalize.normalizePath)(
    install?.installRoot ?? path.join((0, import_socket.getSocketDlxDir)(), (0, import_cache.generateCacheKey)(packageSpec))
  );
  const installedDir = (0, import_normalize.normalizePath)(
    path.join(packageDir, "node_modules", packageName)
  );
  try {
    await (0, import_safe.safeMkdir)(packageDir);
  } catch (e) {
    const code = e.code;
    if (code === "EACCES" || code === "EPERM") {
      throw new import_error.ErrorCtor(
        `Permission denied creating package directory: ${packageDir}
Please check directory permissions or run with appropriate access.`,
        { cause: e }
      );
    }
    if (code === "EROFS") {
      throw new import_error.ErrorCtor(
        `Cannot create package directory on read-only filesystem: ${packageDir}
Ensure the filesystem is writable or set SOCKET_DLX_DIR to a writable location.`,
        { cause: e }
      );
    }
    throw new import_error.ErrorCtor(`Failed to create package directory: ${packageDir}`, {
      cause: e
    });
  }
  const lockPath = path.join(packageDir, "concurrency.lock");
  return await import_lock_instance.processLock.withLock(
    lockPath,
    async () => {
      if (!force && fs.existsSync(installedDir)) {
        const pkgJsonPath = path.join(installedDir, "package.json");
        if (fs.existsSync(pkgJsonPath)) {
          return { installed: false, packageDir };
        }
      }
      if (install?.lockfile !== void 0) {
        const spec = install.lockfile;
        const lockDest = path.join(packageDir, "package-lock.json");
        let isContent;
        let value;
        if (typeof spec === "string") {
          isContent = spec.trimStart().startsWith("{");
          value = spec;
        } else {
          isContent = spec.type === "content";
          value = spec.value;
        }
        if (isContent) {
          fs.writeFileSync(lockDest, value, "utf8");
        } else {
          fs.copyFileSync(value, lockDest);
        }
        fs.writeFileSync(
          path.join(packageDir, ".npmrc"),
          "ignore-scripts=true\naudit=false\nfund=false\nsave=false\n",
          "utf8"
        );
      }
      try {
        const arb = new import_arborist.default({
          path: packageDir,
          // Use Socket's shared cacache directory (~/.socket/_cacache).
          /* c8 ignore stop */
          cache: (0, import_socket.getSocketCacacheDir)(),
          // Skip devDependencies (production-only like npx).
          omit: ["dev"],
          // Security: Skip install/preinstall/postinstall scripts to prevent arbitrary code execution.
          ignoreScripts: true,
          // Security: Enable binary links (needed for dlx to execute the package binary).
          binLinks: true,
          // Suppress funding messages (unneeded for ephemeral dlx installs).
          fund: false,
          // Skip audit (unneeded for ephemeral dlx installs).
          audit: false,
          // Suppress output (unneeded for ephemeral dlx installs).
          silent: true
        });
        await arb.buildIdealTree({ add: [packageSpec] });
        await (0, import_firewall.checkFirewallPurls)(arb, packageName);
        await arb.reify({ save: true });
      } catch (e) {
        if ((0, import_predicates.isError)(e) && e.message.startsWith("Socket Firewall blocked")) {
          throw e;
        }
        const code = e?.code;
        if (code === "E404" || code === "ETARGET") {
          throw new import_error.ErrorCtor(
            `Package not found: ${packageSpec}
Verify the package exists on npm registry and check the version.
Visit https://www.npmjs.com/package/${packageName} to see available versions.`,
            { cause: e }
          );
        }
        if (code === "ENOTFOUND" || code === "ETIMEDOUT" || code === "EAI_AGAIN") {
          throw new import_error.ErrorCtor(
            `Network error installing ${packageSpec}
Check your internet connection and try again.`,
            { cause: e }
          );
        }
        throw new import_error.ErrorCtor(
          `Failed to install package: ${packageSpec}
Destination: ${installedDir}
Check npm registry connectivity or package name.`,
          { cause: e }
        );
      }
      return { installed: true, packageDir };
    },
    {
      // Align with npm npx locking strategy.
      staleMs: 5e3,
      touchIntervalMs: 2e3
    }
  );
}
function executePackage(binaryPath, args, spawnOptions, spawnExtra) {
  const needsShell = import_platform.WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath);
  const finalOptions = needsShell ? {
    ...spawnOptions,
    shell: true
  } : spawnOptions;
  return (0, import_spawn.spawn)(binaryPath, args, finalOptions, spawnExtra);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  binaryPathCacheSet,
  checkFirewallPurls,
  dlxPackage,
  downloadPackage,
  ensurePackageInstalled,
  executePackage,
  findBinaryPath,
  makePackageBinsExecutable,
  npmPurl,
  parsePackageSpec,
  resolveBinaryPath
});
