"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_integrity = require('../integrity.js');
const require_constants_platform = require('../constants/platform.js');
const require_paths_normalize = require('../paths/normalize.js');
const require_primordials_array = require('../primordials/array.js');
const require_node_fs = require('../node/fs.js');
const require_node_path = require('../node/path.js');
const require_fs_read_json = require('../fs/read-json.js');
const require_process_spawn_child = require('../process/spawn/child.js');
const require_fs_safe = require('../fs/safe.js');
const require_constants_time = require('../constants/time.js');
const require_dlx_binary_cache = require('./binary-cache.js');
const require_dlx_cache = require('./cache.js');
const require_dlx_binary_download = require('./binary-download.js');
let node_process = require("node:process");
node_process = require_runtime.__toESM(node_process);

//#region src/dlx/binary.ts
/**
* @file DLX binary execution utilities for Socket ecosystem. High-level entry
*   points for downloading standalone URL-hosted binaries (not npm packages —
*   see `./package` for those) and executing them with cross-platform shell
*   handling.
*
*   - `dlxBinary` — download (if needed) + execute
*   - `executeBinary` — execute an already-cached binary Supporting surface lives
*     in sibling leaves and is re-exported here so existing `dlx/binary`
*     importers keep working unchanged:
*   - lazy `node:fs` / `node:path` / `node:crypto` + LRU cache — `./_internal`
*   - types — `./binary-types`
*   - on-disk cache metadata — `./binary-cache`
*   - download + integrity verification — `./binary-download`
*/
/**
* Download and execute a binary from a URL with caching.
*
* @example
*   ;```typescript
*   const result = await dlxBinary(['--version'], {
*     url: 'https://example.com/tool-linux-x64',
*     name: 'tool',
*   })
*   await result.spawnPromise
*   ```
*/
async function dlxBinary(args, options, spawnExtra) {
	const { cacheTtl = require_constants_time.DLX_BINARY_CACHE_TTL, force: userForce = false, hash, integrity: rawIntegrity, name, sha256: rawSha256, spawnOptions, url, yes } = {
		__proto__: null,
		...options
	};
	let integrity = rawIntegrity;
	let sha256 = rawSha256;
	if (hash !== void 0) {
		const normalized = require_integrity.normalizeHash(hash);
		if (normalized.type === "integrity") integrity = normalized.value;
		else sha256 = normalized.value;
	}
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const force = yes === true ? true : userForce;
	const cacheDir = require_dlx_binary_cache.getDlxCachePath();
	const binaryName = name || `binary-${node_process.default.platform}-${require_constants_platform.getArch()}`;
	const cacheKey = require_dlx_cache.generateCacheKey(`${url}:${binaryName}`);
	const cacheEntryDir = path.join(cacheDir, cacheKey);
	const binaryPath = /* @__PURE__ */ require_paths_normalize.normalizePath(path.join(cacheEntryDir, binaryName));
	let downloaded = false;
	let computedIntegrity = integrity;
	if (!force && fs.existsSync(cacheEntryDir) && await require_dlx_binary_cache.isBinaryCacheValid(cacheEntryDir, cacheTtl)) try {
		const metadata = await /* @__PURE__ */ require_fs_read_json.readJson(require_dlx_binary_cache.getBinaryCacheMetadataPath(cacheEntryDir), { throws: false });
		if (metadata && typeof metadata === "object" && !require_primordials_array.ArrayIsArray(metadata) && typeof metadata["integrity"] === "string") {
			computedIntegrity = metadata["integrity"];
			if (!fs.existsSync(binaryPath)) downloaded = true;
		} else downloaded = true;
	} catch {
		downloaded = true;
	}
	else downloaded = true;
	if (downloaded) {
		try {
			await require_fs_safe.safeMkdir(cacheEntryDir);
		} catch (e) {
			const code = e.code;
			if (code === "EACCES" || code === "EPERM") throw new require_primordials_error.ErrorCtor(`Permission denied creating binary cache directory: ${cacheEntryDir}\nPlease check directory permissions or run with appropriate access.`, { cause: e });
			if (code === "EROFS") throw new require_primordials_error.ErrorCtor(`Cannot create binary cache directory on read-only filesystem: ${cacheEntryDir}\nEnsure the filesystem is writable or set SOCKET_DLX_DIR to a writable location.`, { cause: e });
			throw new require_primordials_error.ErrorCtor(`Failed to create binary cache directory: ${cacheEntryDir}`, { cause: e });
		}
		computedIntegrity = await require_dlx_binary_download.downloadBinaryFile(url, binaryPath, integrity, sha256);
		const stats = await fs.promises.stat(binaryPath);
		await require_dlx_binary_cache.writeBinaryCacheMetadata(cacheEntryDir, cacheKey, url, computedIntegrity || "", stats.size);
	}
	const spawnPromise = require_process_spawn_child.spawn(binaryPath, args, require_constants_platform.WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath) ? {
		...spawnOptions,
		env: {
			...spawnOptions?.env,
			PATH: `${cacheEntryDir}${path.delimiter}${node_process.default.env["PATH"] || ""}`
		},
		shell: true
	} : spawnOptions, spawnExtra);
	return {
		binaryPath,
		downloaded,
		spawnPromise
	};
}
/**
* Execute a cached binary without re-downloading. Similar to executePackage
* from dlx/package. Binary must have been previously downloaded via
* downloadBinary or dlxBinary.
*
* @example
*   ;```typescript
*   const { binaryPath } = await downloadBinary({
*     url: 'https://example.com/tool-linux-x64',
*     name: 'tool',
*   })
*   const result = executeBinary(binaryPath, ['--help'])
*   ```
*
* @param binaryPath Path to the cached binary (from downloadBinary result)
* @param args Arguments to pass to the binary.
* @param spawnOptions Spawn options for execution.
* @param spawnExtra Extra spawn configuration.
*
* @returns The spawn promise for the running process
*/
function executeBinary(binaryPath, args, spawnOptions, spawnExtra) {
	const needsShell = require_constants_platform.WIN32 && /\.(?:bat|cmd|ps1)$/i.test(binaryPath);
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const cacheEntryDir = path.dirname(binaryPath);
	return require_process_spawn_child.spawn(binaryPath, args, needsShell ? {
		...spawnOptions,
		env: {
			...spawnOptions?.env,
			PATH: `${cacheEntryDir}${path.delimiter}${node_process.default.env["PATH"] || ""}`
		},
		shell: true
	} : spawnOptions, spawnExtra);
}

//#endregion
exports.cleanDlxCache = require_dlx_binary_cache.cleanDlxCache;
exports.dlxBinary = dlxBinary;
exports.downloadBinary = require_dlx_binary_download.downloadBinary;
exports.downloadBinaryFile = require_dlx_binary_download.downloadBinaryFile;
exports.executeBinary = executeBinary;
exports.getBinaryCacheMetadataPath = require_dlx_binary_cache.getBinaryCacheMetadataPath;
exports.getDlxCachePath = require_dlx_binary_cache.getDlxCachePath;
exports.isBinaryCacheValid = require_dlx_binary_cache.isBinaryCacheValid;
exports.listDlxCache = require_dlx_binary_cache.listDlxCache;
exports.writeBinaryCacheMetadata = require_dlx_binary_cache.writeBinaryCacheMetadata;