import { builtinModules } from "node:module";
import ts from "typescript";

//#region src/utils/detectDependencies.ts
const collapseSubpath = (spec) => {
	if (spec.startsWith("@")) {
		const [scope, name] = spec.split("/");
		return `${scope}/${name ?? ""}`;
	}
	return spec.split("/")[0];
};
const NODE_BUILTINS = new Set(builtinModules.concat(builtinModules.map((m) => `node:${m}`)));
/**
* Extract external NPM dependencies from JavaScript/TypeScript code
* Returns a Set of package names (without versions)
*/
function collectDepsFromCode(code) {
	const isExternal = (spec) => !spec.startsWith(".") && !spec.startsWith("/") && !NODE_BUILTINS.has(spec);
	const dependencies = /* @__PURE__ */ new Set();
	const addDependency = (spec) => {
		if (isExternal(spec)) dependencies.add(collapseSubpath(spec));
	};
	if (ts) try {
		const info = ts.preProcessFile(code, true, true);
		for (const importedFile of info.importedFiles) {
			const spec = importedFile.fileName;
			if (spec) addDependency(spec);
		}
	} catch {}
	const requirePattern = /(?:require|import)\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
	let match;
	while (match = requirePattern.exec(code)) addDependency(match[2]);
	return dependencies;
}
/**
* Convert detected dependencies to a Record with "latest" versions
*/
function createLatestDependencies(dependencies) {
	const result = {};
	for (const dep of dependencies) result[dep] = "latest";
	return result;
}
/**
* Auto-detect dependencies from code and return them with "latest" versions
*/
function autoDetectDependencies(executeCode) {
	return createLatestDependencies(collectDepsFromCode(executeCode));
}

//#endregion
export { autoDetectDependencies, collectDepsFromCode, createLatestDependencies };