"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
const require_primordials_error = require('../primordials/error.js');
const require_constants_platform = require('../constants/platform.js');
const require_paths_normalize = require('../paths/normalize.js');
const require_node_fs = require('../node/fs.js');
const require_node_path = require('../node/path.js');
const require_primordials_object = require('../primordials/object.js');
const require_fs_read_json = require('../fs/read-json.js');
const require_dlx__internal = require('./_internal.js');
let src_external_libnpmexec = require("../external/libnpmexec");
src_external_libnpmexec = require_runtime.__toESM(src_external_libnpmexec);

//#region src/dlx/binary-resolution.ts
/**
* @file Binary resolution for installed dlx packages.
*
*   - `findBinaryPath` — pick the right binary entry from package.json `bin`
*   - `makePackageBinsExecutable` — chmod all bin entries to 0o755 on Unix
*   - `resolveBinaryPath` — Windows wrapper (.cmd/.bat/.ps1/.exe) lookup Split
*     out of `dlx/package.ts` for size hygiene. The cache used by
*     `resolveBinaryPath` lives in `_internal.ts` so both this leaf and any
*     direct consumers (`binaryPathCacheSet`) share one source.
*/
/**
* Find the binary path for an installed package. Uses npm's bin resolution
* strategy with user-friendly fallbacks. Resolves platform-specific wrappers
* (.cmd, .ps1, etc.) on Windows.
*
* Resolution strategy (cherry-picked from libnpmexec): 1. Use npm's
* getBinFromManifest (handles aliases and standard cases) 2. Fall back to
* user-provided binaryName if npm's strategy fails 3. Try last segment of
* package name as final fallback 4. Use first binary as last resort.
*
* @example
*   ```typescript
*   const binPath = findBinaryPath('/tmp/.socket/_dlx/a1b2c3d4', 'prettier')
*   console.log(`Binary: ${binPath}`)
*   ```
*/
function findBinaryPath(packageDir, packageName, binaryName) {
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const installedDir = /* @__PURE__ */ require_paths_normalize.normalizePath(path.join(packageDir, "node_modules", packageName));
	const pkgJson = /* @__PURE__ */ require_fs_read_json.readJsonSync(path.join(installedDir, "package.json"));
	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 = require_primordials_object.ObjectKeys(binObj);
		if (binKeys.length === 1) {
			binName = binKeys[0];
			binPath = binObj[binName];
		} else try {
			/* c8 ignore start */
			const { getBinFromManifest } = src_external_libnpmexec.default;
			binName = getBinFromManifest({
				name: packageName,
				bin: binObj,
				_id: `${packageName}@${pkgJson.version || "unknown"}`
			});
			/* c8 ignore stop */
			binPath = binObj[binName];
		} catch {
			const candidates = [
				binaryName,
				packageName.split("/").pop() ?? packageName,
				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 require_primordials_error.ErrorCtor(`No binary found for package "${packageName}"`);
	return resolveBinaryPath(/* @__PURE__ */ require_paths_normalize.normalizePath(path.join(installedDir, binPath)));
}
/**
* Make all binaries in an installed package executable. Reads the package.json
* bin field and makes all binaries executable (chmod 0o755). Handles both
* single binary (string) and multiple binaries (object) formats.
*
* Aligns with npm's approach: - Uses 0o755 permission (matches npm's cmd-shim)
* - Reads bin field from package.json (matches npm's bin-links and libnpmexec)
* - Handles both string and object bin formats.
*
* References: - npm cmd-shim:
* https://github.com/npm/cmd-shim/blob/main/lib/index.js - npm
* getBinFromManifest:
* https://github.com/npm/libnpmexec/blob/main/lib/get-bin-from-manifest.js.
*
* @example
*   ;```typescript
*   makePackageBinsExecutable('/tmp/.socket/_dlx/a1b2c3d4', 'prettier')
*   ```
*/
function makePackageBinsExecutable(packageDir, packageName) {
	if (require_constants_platform.WIN32) return;
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const installedDir = /* @__PURE__ */ require_paths_normalize.normalizePath(path.join(packageDir, "node_modules", packageName));
	const pkgJsonPath = path.join(installedDir, "package.json");
	try {
		const bin = (/* @__PURE__ */ require_fs_read_json.readJsonSync(pkgJsonPath))["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(...require_primordials_object.ObjectValues(binObj));
		}
		for (const binPath of binPaths) {
			const fullPath = /* @__PURE__ */ require_paths_normalize.normalizePath(path.join(installedDir, binPath));
			if (fs.existsSync(fullPath)) try {
				fs.chmodSync(fullPath, 493);
			} catch {}
		}
	} catch {}
}
/**
* Resolve binary path with cross-platform wrapper support. On Windows, checks
* for .cmd, .bat, .ps1, .exe wrappers in order. On Unix, uses path directly.
*
* Aligns with npm/npx binary resolution strategy.
*
* @example
*   ;```typescript
*   const resolved = resolveBinaryPath('/tmp/.socket/_dlx/a1b2c3d4/prettier')
*   // On Windows: may resolve to '.cmd' or '.ps1' wrapper
*   // On Unix: returns the path unchanged
*   ```
*/
function resolveBinaryPath(basePath) {
	if (!require_constants_platform.WIN32) return basePath;
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	const cached = require_dlx__internal.binaryPathCache.get(basePath);
	if (cached) {
		if (fs.existsSync(cached)) {
			require_dlx__internal.binaryPathCacheSet(basePath, cached);
			return cached;
		}
		require_dlx__internal.binaryPathCache.delete(basePath);
	}
	for (const ext of [
		".cmd",
		".bat",
		".ps1",
		".exe",
		""
	]) {
		const testPath = basePath + ext;
		if (fs.existsSync(testPath)) {
			require_dlx__internal.binaryPathCacheSet(basePath, testPath);
			return testPath;
		}
	}
	return basePath;
}

//#endregion
exports.findBinaryPath = findBinaryPath;
exports.makePackageBinsExecutable = makePackageBinsExecutable;
exports.resolveBinaryPath = resolveBinaryPath;