import { __require } from "../_virtual/rolldown_runtime.mjs";
import { join } from "node:path";
import { readFile } from "node:fs/promises";
import { builtinModules, createRequire } from "node:module";
import { bundleFile, configESMxCJSRequire, getProjectRequire, isESModule } from "@intlayer/config";

//#region ../@intlayer/cli/dist/esm/chokidar/dist/esm/loadDictionaries/getIntlayerBundle.mjs
/**
* Rewrites selected bare specifiers (and any of their subpaths) to absolute file paths,
* using the provided localeRequire (either createRequire(import.meta.url) or require).
*
* Example:
*   rewritePathsPlugin(["@intlayer/config", "@intlayer/core"], localeRequire)
* …will also rewrite "@intlayer/core/file" etc.
*/
const rewritePathsPlugin = (replaceModules, excludeModules) => {
	return {
		name: "rewrite-paths",
		setup(build) {
			build.onResolve({ filter: /.*/ }, (args) => {
				const exact = replaceModules[args.path];
				if (excludeModules?.includes(args.path)) return null;
				if (exact) return {
					path: exact,
					namespace: "intlayer-replace-modules",
					external: true
				};
				for (const key of Object.keys(replaceModules)) if (args.path === key || args.path.startsWith(`${key}/`)) {
					const sub = args.path.slice(key.length);
					return {
						path: replaceModules[key] + sub,
						namespace: "intlayer-replace-modules",
						external: true
					};
				}
			});
		}
	};
};
/**
* Get the intlayer bundle to embed @intlayer/core and be able to mock @intlayer/config/built to mock the configuration file.
*/
const getIntlayerBundle = async (configuration) => {
	const rootRequire = getProjectRequire(configuration.content.baseDir);
	const configPackageRequire = configESMxCJSRequire;
	const localRequire = isESModule ? createRequire(import.meta.url) : __require;
	const configurationPath = join(configuration.content.configDir, `configuration.json`);
	const replaceModules = {
		deepmerge: localRequire.resolve("deepmerge"),
		esbuild: configPackageRequire.resolve("esbuild"),
		"@intlayer/config/built": configurationPath,
		"@intlayer/config": localRequire.resolve("@intlayer/config"),
		"@intlayer/config/client": localRequire.resolve("@intlayer/config/client"),
		"@intlayer/core/file": localRequire.resolve("@intlayer/core/file")
	};
	const filePath = rootRequire.resolve("intlayer");
	return await bundleFile(await readFile(filePath, "utf-8"), filePath, {
		external: [...builtinModules, ...builtinModules.map((mod) => `node:${mod}`)],
		minify: true,
		plugins: [rewritePathsPlugin(replaceModules)]
	}) ?? "";
};

//#endregion
export { getIntlayerBundle };
//# sourceMappingURL=getIntlayerBundle.mjs.map