import { createRequire } from "node:module";
import fs from "node:fs";
import path from "node:path";
import fs$1 from "fs";
import path$1 from "path";
import { createRequire as createRequire$1 } from "module";
import { fileURLToPath } from "url";
//#region src/shared/runtimeManifest.ts
var MANIFEST_FILE = "plugin-dev-manifest.json";
/**
* Корень npm-пакета продукта по URL собранного entry (`vite/index.js`, `vite/pluginDev/index.js`, …).
* @param dirnameStepsToPackageRoot сколько раз подняться из `path.dirname(entryUrl)` до корня пакета
*   (для `…/vite/index.js` → 1, для `…/vite/pluginDev/index.js` → 2).
*/
function hostProductPackageRootFromBundledEntry(bundledEntryImportMetaUrl, dirnameStepsToPackageRoot) {
	let dir = path$1.dirname(fileURLToPath(bundledEntryImportMetaUrl));
	for (let i = 0; i < dirnameStepsToPackageRoot; i++) dir = path$1.join(dir, "..");
	return path$1.resolve(dir);
}
function readJson(filePath) {
	return JSON.parse(fs$1.readFileSync(filePath, "utf-8"));
}
function tryResolveFromPackage(_require, request) {
	try {
		return _require.resolve(request);
	} catch {
		return null;
	}
}
/**
* Проверяет совместимость `schemaVersion` манифеста с поддерживаемым диапазоном.
*
* - Отсутствие поля → legacy v0 (старые main packages до введения versioning).
*   Возвращает `0`, чтобы caller мог при желании логировать deprecation.
* - Integer > 0 в пределах [1, MAX_SUPPORTED_MANIFEST_SCHEMA_VERSION] → OK.
* - Выше или невалидный тип → throw с подсказкой обновить PluginDev.
*/
function assertManifestSchemaVersion(manifest, pluginName, runtimePackage) {
	const raw = manifest.schemaVersion;
	if (raw === void 0) return 0;
	if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0) throw new Error([`[${pluginName}] ${MANIFEST_FILE} has invalid schemaVersion (expected non-negative integer, got ${JSON.stringify(raw)}).`, `This usually means a malformed install of ${runtimePackage}. Try removing node_modules and reinstalling.`].join("\n"));
	if (raw > 1) throw new Error([
		`[${pluginName}] ${MANIFEST_FILE} schemaVersion=${raw} is newer than this PluginDev can read (max 1).`,
		`The installed ${runtimePackage} ships a newer runtime contract.`,
		`Upgrade your @scope/<main>/{vite,webpack}/pluginDev import to a matching version`,
		`or downgrade ${runtimePackage} to a version compatible with this PluginDev.`
	].join("\n"));
	return raw;
}
function readRuntimeManifest(runtimePackage, pluginName, bundledEntryImportMetaUrl, dirnameStepsToPackageRoot) {
	const _require = createRequire$1(path$1.resolve(process.cwd(), "package.json"));
	const hostRoot = hostProductPackageRootFromBundledEntry(bundledEntryImportMetaUrl, dirnameStepsToPackageRoot);
	const embeddedRuntimePkgJson = path$1.join(hostRoot, "runtime", "package.json");
	const packageJsonPath = fs$1.existsSync(embeddedRuntimePkgJson) ? embeddedRuntimePkgJson : _require.resolve(`${runtimePackage}/package.json`);
	const packageDir = path$1.dirname(packageJsonPath);
	const manifestPath = tryResolveFromPackage(_require, `${runtimePackage}/plugin-dev-manifest.json`) || path$1.join(packageDir, "plugin-dev-manifest.json");
	if (fs$1.existsSync(manifestPath)) {
		const manifest = readJson(manifestPath);
		assertManifestSchemaVersion(manifest, pluginName, runtimePackage);
		console.log(`[${pluginName}] runtime manifest at ${manifestPath}`);
		return manifest;
	}
	const runtimePkg = readJson(packageJsonPath);
	if (!runtimePkg.runtimeModules || typeof runtimePkg.runtimeModules !== "object") throw new Error(`No "${MANIFEST_FILE}" and no legacy runtime metadata in ${runtimePackage}/package.json`);
	console.warn(`[${pluginName}] ${MANIFEST_FILE} not found, falling back to legacy package.json metadata`);
	return {
		runtimeModules: runtimePkg.runtimeModules,
		runtimeExports: runtimePkg.runtimeExports || {},
		runtimeCoreModules: Array.isArray(runtimePkg.runtimeCoreModules) ? runtimePkg.runtimeCoreModules : [],
		runtimeCoreExport: runtimePkg.runtimeCoreExport || "Core"
	};
}
function createRuntimeEntryList(runtimeManifest) {
	const runtimeModules = runtimeManifest.runtimeModules || {};
	const runtimeExports = runtimeManifest.runtimeExports || {};
	const runtimeCoreModules = Array.isArray(runtimeManifest.runtimeCoreModules) ? runtimeManifest.runtimeCoreModules : [];
	return {
		runtimeModules,
		runtimeExports,
		runtimeCoreModules,
		runtimeCoreExport: runtimeManifest.runtimeCoreExport || "Core",
		runtimeEntries: Object.entries(runtimeModules).map(([runtimeSubpath, originalName]) => ({
			runtimeSubpath,
			originalName,
			exportName: runtimeExports[runtimeSubpath]
		})),
		runtimeCoreModuleSet: new Set(runtimeCoreModules)
	};
}
//#endregion
//#region src/shared/pluginDevOptions.ts
/**
* Normalizes shared `pluginDev` options for Vite and Webpack adapters.
*/
function resolvePluginDevOptions(options) {
	let o = {};
	if (options && options !== true) o = options;
	const externals = o.externals === "global" ? "globals" : o.externals;
	const defaultAlias = externals === void 0 || externals === "esm" || externals === false;
	return {
		externals: externals !== void 0 ? externals : "esm",
		alias: o.alias !== void 0 ? o.alias : defaultAlias,
		allowedDeepRuntimeImports: new Set(o.allowedDeepRuntimeImports ?? [])
	};
}
//#endregion
//#region src/shared/runtimeCorePackage.ts
function getRuntimeCorePackageName(mainPackageName) {
	const normalized = String(mainPackageName || "").replace(/\/+$/, "");
	if (!normalized) throw new Error("[runtime-core] mainPackageName is empty");
	return `${normalized}/runtime-core`;
}
//#endregion
//#region src/shared/branding.ts
/**
* Чтение `process.env.REACT_APP_*` — как в основном приложении.
* На этапе сборки `build.ts` подставляет в `define` итоговые строки (см. `bundlerDefines()`).
*/
var BUNDLER_DEFAULT_PACKAGE_NAME = "useblocks";
var BUNDLER_DEFAULT_APP_NAME = "useblocks";
var BUNDLER_RUNTIME_PACKAGE = "useblocks/runtime";
var BUNDLER_NAMESPACE = `__${BUNDLER_DEFAULT_APP_NAME}__`;
//#endregion
//#region src/shared/escapeRegex.ts
/** Escape string for use inside `RegExp` source (character class safe subset aligned with prior helpers). */
function escapeRegex(value) {
	return value.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&");
}
//#endregion
//#region src/shared/runtimePublicEntries.ts
/**
* Политика runtime alias для PluginDev:
*
* - В `resolve.alias` маппятся только **bare** specifiers с точным совпадением (`/^react$/`, `/^antd$/`, …).
* - Запрещено подменять префиксом: `antd/es/locale/...` не должен превращаться в
*   `@scope/runtime/antd/es/...` — такого пути в runtime-пакете нет.
*
* Глубокие импорты (`antd/es/...`) резолвятся обычным образом в `node_modules` / peer.
*
* Список bare-имён берётся из манифеста (`runtimeModules` values); replacement считается через
* `canonicalRuntimePackageRequest` в [runtimeResolveAliases.ts](./runtimeResolveAliases.ts).
*/
/** Точное совпадение specifier (не префикс). */
function exactBareSpecifierPattern(originalName) {
	return new RegExp(`^${escapeRegex(originalName)}$`);
}
function buildExactBarePackageAliasEntries(uniqueOriginalNames, getReplacement, options) {
	const out = [];
	for (const originalName of uniqueOriginalNames) {
		if (!options.aliasBarePackages && !options.runtimeCoreModuleSet.has(originalName)) continue;
		out.push({
			find: exactBareSpecifierPattern(originalName),
			replacement: getReplacement(originalName)
		});
	}
	return out;
}
//#endregion
//#region src/shared/uiKitPaths.ts
/** Main package import for ui-kit bytes: `@scope/app/ui-kit` (not under `/runtime/`). */
function getMainPackageUiKitSubpath(mainPackage = BUNDLER_DEFAULT_PACKAGE_NAME) {
	const normalized = String(mainPackage || "").replace(/\/+$/, "");
	if (!normalized) throw new Error("[ui-kit-paths] mainPackage is empty");
	return `${normalized}/ui-kit`;
}
function isUiKitManifestEntry(exportName) {
	return exportName === "UiKit";
}
/** True when specifier is the main package ui-kit subpath (after PluginDev alias). */
function isMainPackageUiKitImport(source, mainPackage = BUNDLER_DEFAULT_PACKAGE_NAME) {
	const mainUiKit = getMainPackageUiKitSubpath(mainPackage);
	return source === mainUiKit || source.startsWith(`${mainUiKit}/`);
}
//#endregion
//#region src/shared/runtimeResolveAliases.ts
var RUNTIME_INDEX_SUFFIX_RE$3 = /\/index(?:\.(?:js|mjs|cjs))?$/;
function normalizeRuntimeSubpath$2(subpath) {
	return subpath.replace(RUNTIME_INDEX_SUFFIX_RE$3, "");
}
/** Canonical mapping aligned with `vite/pluginDev/index.ts`. */
function canonicalRuntimePackageRequest(packageOrSubpathSpecifier, runtimePkgImportRoot, runtimeCorePackage, runtimeCoreModuleSet) {
	const canonicalSubpath = normalizeRuntimeSubpath$2(packageOrSubpathSpecifier);
	if (runtimeCoreModuleSet.has(canonicalSubpath)) return runtimeCorePackage;
	return `${runtimePkgImportRoot}/${canonicalSubpath}`;
}
/** PluginDev target id: runtime subpath or main `/ui-kit` (not `runtime/@…/ui-kit`). */
function resolvePluginDevPackageRequest(originalName, exportName, runtimePkgImportRoot, runtimeCorePackage, runtimeCoreModuleSet, mainPackageImport) {
	if (isUiKitManifestEntry(exportName)) return getMainPackageUiKitSubpath(mainPackageImport);
	return canonicalRuntimePackageRequest(originalName, runtimePkgImportRoot, runtimeCorePackage, runtimeCoreModuleSet);
}
/** `@scope/ui-kit/foo` → `@scope/main/ui-kit/foo` (ui-kit only; not a prefix rule for other packages). */
function buildUiKitDeepImportAliasEntries(runtimeEntries, mainPackageImport) {
	const mainUiKit = getMainPackageUiKitSubpath(mainPackageImport);
	const out = [];
	for (const { originalName, exportName } of runtimeEntries) {
		if (!isUiKitManifestEntry(exportName)) continue;
		out.push({
			find: new RegExp(`^${escapeRegex(originalName)}(/.*)$`),
			replacement: `${mainUiKit}$1`
		});
	}
	return out;
}
function createRuntimeIndexAliasEntries(runtimeEntries, runtimePkgImportRoot, runtimeCorePackage, runtimeCoreModuleSet) {
	const escapedRuntimeRoot = escapeRegex(runtimePkgImportRoot);
	return runtimeEntries.filter((entry) => !isUiKitManifestEntry(entry.exportName)).map(({ runtimeSubpath }) => {
		const canonicalSubpath = normalizeRuntimeSubpath$2(runtimeSubpath);
		const escapedSubpath = escapeRegex(canonicalSubpath);
		return {
			find: new RegExp(`^${escapedRuntimeRoot}/${escapedSubpath}/index(?:\\.(?:js|mjs|cjs))?$`),
			replacement: canonicalRuntimePackageRequest(canonicalSubpath, runtimePkgImportRoot, runtimeCorePackage, runtimeCoreModuleSet)
		};
	});
}
/** Vite resolve aliases: exact bare packages + нормализация `@scope/runtime/.../index`. */
function attachRuntimeAliasesToManifestList(list, aliasBarePackages) {
	const runtimeCorePackage = getRuntimeCorePackageName(BUNDLER_DEFAULT_PACKAGE_NAME);
	const { runtimeModules, runtimeEntries, runtimeCoreModuleSet } = list;
	const exportNameByOriginal = new Map(runtimeEntries.map((entry) => [entry.originalName, entry.exportName]));
	const packageAliasEntries = [...buildExactBarePackageAliasEntries(Array.from(new Set(Object.values(runtimeModules))), (originalName) => resolvePluginDevPackageRequest(originalName, exportNameByOriginal.get(originalName), BUNDLER_RUNTIME_PACKAGE, runtimeCorePackage, runtimeCoreModuleSet, BUNDLER_DEFAULT_PACKAGE_NAME), {
		aliasBarePackages,
		runtimeCoreModuleSet
	}), ...buildUiKitDeepImportAliasEntries(runtimeEntries, BUNDLER_DEFAULT_PACKAGE_NAME)];
	const runtimeIndexAliases = [...createRuntimeIndexAliasEntries(runtimeEntries, BUNDLER_RUNTIME_PACKAGE, runtimeCorePackage, runtimeCoreModuleSet), {
		find: new RegExp(`^${escapeRegex(BUNDLER_RUNTIME_PACKAGE)}/core(?:/index(?:\\.(?:js|mjs|cjs))?)?$`),
		replacement: runtimeCorePackage
	}];
	return {
		...list,
		packageAliasEntries,
		runtimeIndexAliases
	};
}
//#endregion
//#region src/shared/pluginDevOptimizeDepsExclude.ts
var RUNTIME_INDEX_SUFFIX_RE$2 = /\/index(?:\.(?:js|mjs|cjs))?$/;
function normalizeRuntimeSubpath$1(subpath) {
	return subpath.replace(RUNTIME_INDEX_SUFFIX_RE$2, "");
}
function appendIndexVariants(target, request, runtimeCorePackage) {
	if (request === runtimeCorePackage) return;
	for (const suffix of [
		"",
		"/index",
		"/index.js",
		"/index.mjs",
		"/index.cjs"
	]) target.add(`${request}${suffix}`);
}
/**
* Singleton runtime ids that must never be prebundled as bare npm copies alongside
* `<mainPackage>/runtime/*` in PluginDev dev server (Invalid hook call / #321).
*
* Host integrator plugin must NOT set these — only PluginDev (`vite/pluginDev`).
*/
function buildPluginDevOptimizeDepsExclude(input) {
	const runtimeCorePackage = getRuntimeCorePackageName(input.mainPackage);
	const runtimeCompatCoreRequest = `${input.runtimePackage}/core`;
	const exclude = new Set([
		input.mainPackage,
		runtimeCorePackage,
		runtimeCompatCoreRequest
	]);
	for (const originalName of new Set(Object.values(input.runtimeModules))) exclude.add(originalName);
	for (const [runtimeSubpath, originalName] of Object.entries(input.runtimeModules)) {
		exclude.add(runtimeSubpath);
		exclude.add(`${input.runtimePackage}/${normalizeRuntimeSubpath$1(runtimeSubpath)}`);
		const canonical = resolvePluginDevPackageRequest(originalName, input.runtimeEntries.find((item) => item.originalName === originalName)?.exportName, input.runtimePackage, runtimeCorePackage, input.runtimeCoreModuleSet, input.mainPackage);
		exclude.add(canonical);
		appendIndexVariants(exclude, canonical, runtimeCorePackage);
		appendIndexVariants(exclude, `${input.runtimePackage}/${normalizeRuntimeSubpath$1(runtimeSubpath)}`, runtimeCorePackage);
	}
	return Array.from(exclude);
}
//#endregion
//#region src/shared/pluginDevOptimizeDepsPolicy.ts
function buildPluginDevSingletonDepIds(input) {
	return new Set(buildPluginDevOptimizeDepsExclude(input));
}
/**
* Strip runtime singleton ids from `optimizeDeps.include`.
* `@vitejs/plugin-react` adds bare `react` / `react-dom` which Rolldown-prebundles runtime
* into `.vite/deps/` while other modules load native `static/runtime/*` → Invalid hook call.
*/
function sanitizePluginDevOptimizeDepsInclude(include, singletonIds) {
	if (!Array.isArray(include) || include.length === 0) return;
	const filtered = include.filter((id) => !singletonIds.has(id));
	if (filtered.length === include.length) return;
	return filtered;
}
function mergePluginDevOptimizeDepsExclude(prevOptimizeDeps, exclude) {
	const prevExclude = Array.isArray(prevOptimizeDeps?.exclude) ? prevOptimizeDeps.exclude : [];
	return {
		...prevOptimizeDeps || {},
		exclude: Array.from(new Set([...prevExclude, ...exclude]))
	};
}
/**
* Post-merge patch for PluginDev dev serve: re-apply singleton exclude after all plugins
* (incl. `@vitejs/plugin-react`), drop singleton ids from accumulated `optimizeDeps.include`,
* and disable automatic dep discovery so crawl cannot re-add excluded runtime singletons.
*/
function buildPluginDevOptimizeDepsServePostPatch(accumulatedConfig, singletonIds, exclude) {
	const prev = accumulatedConfig.optimizeDeps;
	const mergedExclude = mergePluginDevOptimizeDepsExclude(prev, exclude);
	const sanitizedInclude = sanitizePluginDevOptimizeDepsInclude(prev?.include, singletonIds);
	return {
		...prev || {},
		...mergedExclude,
		...sanitizedInclude !== void 0 ? { include: sanitizedInclude } : {},
		noDiscovery: true
	};
}
function checkPluginDevRuntimeSingletonPrebundle(input) {
	const optimized = input.metadata?.optimized;
	if (!optimized) return { status: "no-metadata" };
	const entries = [];
	for (const id of Object.keys(optimized)) {
		if (!input.singletonIds.has(id)) continue;
		const entry = optimized[id];
		entries.push({
			id,
			src: String(entry?.src || ""),
			file: String(entry?.file || "")
		});
	}
	if (entries.length === 0) return { status: "clean" };
	const lines = [
		`[${input.pluginName}] Runtime singleton(s) must not appear in Vite dep optimizer output (.vite/deps).`,
		`Prebundled runtime React/antd (even when src points at ${input.mainPackage}/runtime/*) creates a second module instance`,
		`alongside native static/runtime/* loads → Invalid hook call / React #321.`,
		"",
		"Found in .vite/deps/_metadata.json:"
	];
	for (const entry of entries) {
		lines.push(`  • ${entry.id}`);
		if (entry.src) lines.push(`      src: ${entry.src}`);
		if (entry.file) lines.push(`      file: ${entry.file}`);
	}
	lines.push("", "Likely cause: optimizeDeps.include from @vitejs/plugin-react (bare react/react-dom).", "PluginDev should strip singleton ids from include; if this warning persists, check plugin order and rebuild bundler-plugins.");
	return {
		status: "prebundled",
		entries,
		warnMessage: lines.join("\n")
	};
}
//#endregion
//#region src/shared/detectViteJsxToolchain.ts
var toolchainCache = /* @__PURE__ */ new Map();
function readPackageJson(filePath) {
	try {
		return JSON.parse(fs.readFileSync(filePath, "utf8"));
	} catch {
		return null;
	}
}
function depsRecord(pkg) {
	return {
		...pkg.dependencies,
		...pkg.optionalDependencies,
		...pkg.peerDependencies
	};
}
function packageDeclaresRolldown(pkg) {
	return Boolean(depsRecord(pkg).rolldown);
}
function vitePackageDirUsesRolldown(vitePkgPath) {
	path.dirname(vitePkgPath);
	const vitePkg = readPackageJson(vitePkgPath);
	if (vitePkg && packageDeclaresRolldown(vitePkg)) return true;
	try {
		createRequire(vitePkgPath).resolve("rolldown/package.json");
		return true;
	} catch {
		return false;
	}
}
function userConfigPrefersRolldownBuild(userConfig) {
	return userConfig?.build?.rolldownOptions != null;
}
/**
* Detect which JSX / dep-optimizer toolchain the integrator's Vite uses.
* Not version-based: `rolldown-vite` package name, Rolldown in vite's deps, or user `build.rolldownOptions`.
*/
function detectViteJsxToolchain(input = {}) {
	const projectRoot = path.resolve(input.projectRoot ?? process.cwd());
	const cacheKey = `${projectRoot}:${userConfigPrefersRolldownBuild(input.userConfig) ? "r" : "n"}`;
	const cached = toolchainCache.get(cacheKey);
	if (cached) return cached;
	let toolchain = "legacy-esbuild";
	try {
		const vitePkgPath = createRequire(path.join(projectRoot, "package.json")).resolve("vite/package.json");
		const vitePkg = readPackageJson(vitePkgPath);
		if (vitePkg) {
			if (vitePkg.name === "rolldown-vite" || vitePackageDirUsesRolldown(vitePkgPath) || userConfigPrefersRolldownBuild(input.userConfig)) toolchain = "rolldown-oxc";
		}
	} catch {}
	toolchainCache.set(cacheKey, toolchain);
	return toolchain;
}
//#endregion
//#region src/shared/runtimeJsxPolicy.ts
function createRuntimeBoundOxcJsx(runtimePackage) {
	return {
		runtime: "automatic",
		importSource: `${runtimePackage}/react`,
		development: false
	};
}
/**
* Runtime ships production React only. Code resolved through PluginDev alias must compile
* with `jsx` / `jsxs` from `jsx-runtime`, never `jsxDEV` from `jsx-dev-runtime`.
*/
function getRuntimeBoundJsxUserConfig(runtimePackage, toolchain) {
	const jsxImportSource = `${runtimePackage}/react`;
	if (toolchain === "rolldown-oxc") return { oxc: { jsx: createRuntimeBoundOxcJsx(runtimePackage) } };
	return { esbuild: {
		jsx: "automatic",
		jsxImportSource,
		jsxDev: false
	} };
}
/**
* Dep optimizer JSX. For Rolldown-based Vite, use `esbuildOptions` — Vite converts them to
* `rolldownOptions` internally (see Vite 8 migration). Direct `rolldownOptions.transform.jsx`
* uses a different schema and can break dep-scan with JSX resolve errors.
*/
function getRuntimeBoundOptimizeDepsJsxConfig(runtimePackage, _toolchain) {
	return { esbuildOptions: {
		jsx: "automatic",
		jsxImportSource: `${runtimePackage}/react`,
		jsxDev: false
	} };
}
function getRuntimeBoundJsxPolicy(runtimePackage, toolchain, options) {
	const includeUserTransform = options?.includeUserTransform !== false;
	const policy = {};
	if (includeUserTransform) Object.assign(policy, getRuntimeBoundJsxUserConfig(runtimePackage, toolchain));
	if (options?.includeOptimizeDeps !== false) policy.optimizeDeps = getRuntimeBoundOptimizeDepsJsxConfig(runtimePackage, toolchain);
	return policy;
}
//#endregion
//#region src/shared/pluginDevServePostPlugin.ts
function resolveProjectRoot(userConfig) {
	return path.resolve(userConfig.root ?? process.cwd());
}
function userConfigHasOptimizeDepsJsxTransform(userConfig) {
	const optimizeDeps = userConfig.optimizeDeps;
	if (!optimizeDeps) return false;
	if (optimizeDeps.esbuildOptions?.jsx != null) return true;
	return (optimizeDeps.rolldownOptions?.transform)?.jsx != null;
}
/**
* PluginDev serve-only post hooks: sanitize singleton `optimizeDeps.include` (after @vitejs/plugin-react)
* and apply runtime-bound JSX policy without clobbering integrator / plugin-react settings.
*/
function createPluginDevServePostPlugin(pluginName, runtimePackage, optimizeDepsInput) {
	const singletonIds = buildPluginDevSingletonDepIds(optimizeDepsInput);
	const optimizeDepsExclude = buildPluginDevOptimizeDepsExclude(optimizeDepsInput);
	return {
		name: `${pluginName}-serve-post`,
		enforce: "post",
		config(accumulatedConfig, env) {
			if (env.command !== "serve") return;
			const patch = { optimizeDeps: buildPluginDevOptimizeDepsServePostPatch(accumulatedConfig, singletonIds, optimizeDepsExclude) };
			const jsxPolicy = getRuntimeBoundJsxPolicy(runtimePackage, detectViteJsxToolchain({
				projectRoot: resolveProjectRoot(accumulatedConfig),
				userConfig: accumulatedConfig
			}), {
				includeOptimizeDeps: !userConfigHasOptimizeDepsJsxTransform(accumulatedConfig),
				includeUserTransform: true
			});
			if (jsxPolicy.esbuild || jsxPolicy.oxc) {
				if (jsxPolicy.esbuild) patch.esbuild = {
					...accumulatedConfig.esbuild || {},
					...jsxPolicy.esbuild
				};
				if (jsxPolicy.oxc) patch.oxc = {
					...accumulatedConfig.oxc || {},
					...jsxPolicy.oxc
				};
			}
			if (jsxPolicy.optimizeDeps) patch.optimizeDeps = {
				...patch.optimizeDeps || accumulatedConfig.optimizeDeps || {},
				...jsxPolicy.optimizeDeps
			};
			return Object.keys(patch).length > 0 ? patch : void 0;
		},
		/**
		* Vite mergeConfig concatenates `optimizeDeps.include` across plugins, so a post `config`
		* patch cannot remove `@vitejs/plugin-react` entries. Mutate the resolved list here.
		*/
		configResolved(resolvedConfig) {
			if (resolvedConfig.command !== "serve") return;
			const optimizeDeps = resolvedConfig.optimizeDeps;
			optimizeDeps.noDiscovery = true;
			const prevExclude = Array.isArray(optimizeDeps.exclude) ? optimizeDeps.exclude : [];
			optimizeDeps.exclude = Array.from(new Set([...prevExclude, ...optimizeDepsExclude]));
			const prevInclude = optimizeDeps.include;
			if (Array.isArray(prevInclude) && prevInclude.length > 0) {
				const filtered = prevInclude.filter((id) => !singletonIds.has(id));
				optimizeDeps.include = filtered.length > 0 ? filtered : void 0;
			}
		}
	};
}
//#endregion
//#region src/shared/externalsResolver.ts
/**
* Rollup/Vite globals map: external module id → `__ns__.modules.Export` path (without `window.`).
* Matches historical PluginDev behavior.
*/
function buildPluginDevGlobalMap(options) {
	const { namespace, mainPackage, runtimePackage, runtimeCorePackage, runtimeCompatCoreRequest, runtimeCoreExport, runtimeCoreModuleSet, runtimeEntries } = options;
	const globalMap = {};
	if (runtimeCoreModuleSet.size > 0) {
		const corePath = `${namespace}.modules.${runtimeCoreExport}`;
		globalMap[runtimeCompatCoreRequest] = corePath;
		globalMap[runtimeCorePackage] = corePath;
	}
	for (const { runtimeSubpath, originalName, exportName } of runtimeEntries) {
		if (!originalName) continue;
		if (runtimeCoreModuleSet.has(originalName)) {
			const coreGlobalPath = `${namespace}.modules.${runtimeCoreExport}`;
			globalMap[originalName] = coreGlobalPath;
			globalMap[`${runtimePackage}/${runtimeSubpath}`] = coreGlobalPath;
			continue;
		}
		if (!exportName) continue;
		const globalPath = `${namespace}.modules.${exportName}`;
		globalMap[originalName] = globalPath;
		if (isUiKitManifestEntry(exportName)) globalMap[getMainPackageUiKitSubpath(mainPackage)] = globalPath;
		else globalMap[`${runtimePackage}/${runtimeSubpath}`] = globalPath;
	}
	return globalMap;
}
//#endregion
//#region src/shared/runtimeDeepImportGuard.ts
/**
* Singleton-safe deep-import guard for runtime packages.
*
* Background: runtime packages (`react`, `antd`, `@ant-design/icons`, …) are delivered
* to plugins via published subpaths `<main>/runtime/<name>/`. If a plugin imports an
* unpublished deep path (e.g. `antd/es/locale/zh_CN`), the plugin's bundler will
* resolve it from the plugin's own `node_modules` — yielding a **second copy** of the
* package inside the plugin bundle. For singleton-sensitive libraries (React,
* `@ant-design/cssinjs`, our DI) this silently splits the graph and breaks the host
* contract at runtime.
*
* Policy:
*   1. Default — **throw** with a diagnostic listing the registered subpaths.
*   2. Escape-hatch — `allowedDeepRuntimeImports` (exact strings only). A matching
*      request is allowed but emits a one-shot warn, signalling that the plugin
*      consciously ships its own copy of that subpath.
*
* Pure: no side effects on input, returns a plain decision the caller renders into
* the bundler's native error/warn channel.
*
* @module runtimeDeepImportGuard
*/
/**
* Корень bare-package для проверки запрещённых deep-импортов runtime пакетов.
* - `react` → `react`
* - `@ant-design/icons` → `@ant-design/icons`
* - `antd/es/locale/zh_CN` → `antd`
*/
function getRuntimePackageRoot(spec) {
	if (spec.startsWith("@")) return spec.split("/").slice(0, 2).join("/");
	return spec.split("/")[0];
}
/** Strip branded runtime root prefix so `@scope/runtime/antd/es/…` is checked as bare `antd/es/…`. */
function stripRuntimePackagePrefix(request, runtimePackage) {
	const prefix = `${runtimePackage}/`;
	if (!request.startsWith(prefix)) return null;
	return request.slice(prefix.length);
}
/** Bare + runtime-prefixed forms (deduped) for guard evaluation. */
function resolveDeepImportGuardRequests(request, runtimePackage) {
	const seen = /* @__PURE__ */ new Set();
	const out = [];
	const push = (value) => {
		if (!seen.has(value)) {
			seen.add(value);
			out.push(value);
		}
	};
	push(request);
	if (runtimePackage) {
		const bare = stripRuntimePackagePrefix(request, runtimePackage);
		if (bare) push(bare);
	}
	return out;
}
function hasKey(set, key) {
	if (set instanceof Set) return set.has(key);
	return Object.prototype.hasOwnProperty.call(set, key);
}
/** Strip runtime entry index file suffix (`react/index.js` → `react`). */
var RUNTIME_INDEX_SUFFIX_RE$1 = /\/index(?:\.(?:js|mjs|cjs))?$/;
function normalizeRegisteredRuntimeSubpath(request) {
	return request.replace(RUNTIME_INDEX_SUFFIX_RE$1, "");
}
function normalizeDeepImportRequestId(request) {
	return request.replace(/\\/g, "/");
}
function evaluateSingleDeepImportRequest(request, input) {
	const normalizedRequestId = normalizeDeepImportRequestId(request);
	const { knownRuntimeModules, runtimePackageRoots, runtimeRootKnownSubpaths, allowedDeepRuntimeImports, pluginName, optInExample } = input;
	for (const root of runtimePackageRoots) {
		if (!normalizedRequestId.startsWith(`${root}/`)) continue;
		if (hasKey(knownRuntimeModules, normalizedRequestId)) return { action: "pass-through" };
		const normalizedSubpath = normalizeRegisteredRuntimeSubpath(normalizedRequestId);
		if (normalizedSubpath !== normalizedRequestId && hasKey(knownRuntimeModules, normalizedSubpath)) return { action: "pass-through" };
		if (allowedDeepRuntimeImports.has(normalizedRequestId)) return {
			action: "allow-with-warn",
			matchedRoot: root,
			warnMessage: [`[${pluginName}] allowed deep runtime import "${normalizedRequestId}" — singleton invariant is relaxed.`, `The plugin will bundle its own copy of "${root}" subpath; ensure this is intentional.`].join(" ")
		};
		const known = Array.from(runtimeRootKnownSubpaths.get(root) ?? []).sort();
		return {
			action: "block",
			matchedRoot: root,
			errorMessage: [
				`[${pluginName}] Deep import "${normalizedRequestId}" of runtime package "${root}" is not allowed.`,
				`Runtime packages must be imported as bare specifiers or via known runtime subpaths.`,
				known.length > 0 ? `Available subpaths: ${known.join(", ")}` : "",
				`If you need this deep path, either:`,
				`  • add a runtime entry to runtime-contract.ts on the host side, or`,
				`  • ${optInExample(request)} — at the cost of a second copy.`
			].filter(Boolean).join("\n")
		};
	}
	return { action: "pass-through" };
}
function evaluateDeepImportRequest(input) {
	const { request, runtimePackage, ...rest } = input;
	for (const candidate of resolveDeepImportGuardRequests(request, runtimePackage)) {
		const decision = evaluateSingleDeepImportRequest(candidate, rest);
		if (decision.action !== "pass-through") return decision;
	}
	return { action: "pass-through" };
}
//#endregion
//#region src/shared/pluginBundleSanityCheck.ts
/**
* Build-time defensive check для bundle плагина.
*
* После сборки плагина (Vite generateBundle / Webpack afterEmit) проверяет,
* что в его JS-чанках НЕТ bare-импортов рантайм-пакетов (react, react-dom,
* antd, @ant-design/icons, …). Все они должны идти через
* `<main>/runtime/<pkg>` (singleton) или `<main>/ui-kit` / `<main>/runtime-core`.
*
* Симптом-кейс: integrator грузит plugin в release-host Vite, который видит
* `import "react"` в chunk'е плагина и независимо prebundle'ит его → второй
* React → `Invalid hook call`. См. `reactDuplicateDetector.ts` (runtime-side
* проверка) и `RUNTIME_DELIVERY_CR.md` §12.
*
* Pure: возвращает решение, caller рендерит warn / throw в нужный канал.
*
* @module pluginBundleSanityCheck
*/
/**
* Bare-имена, которые НЕ должны попадать в bundle плагина как external.
* Источник истины — пакеты `runtime-bundle` в runtime-contract. Жёстко
* перечислены, чтобы host plugin/PluginDev не читали контракт runtime'ом
* (контракт замораживается в branding на этапе сборки bundler-plugins).
*/
var SINGLETON_BARE_NAMES$1 = [
	"react",
	"react-dom",
	"react-dom/client",
	"react/jsx-runtime",
	"react/jsx-dev-runtime",
	"antd",
	"@ant-design/icons"
];
/**
* Регекспы для поиска bare-импорта `from "X"` / `from 'X'` / `import "X"` / `import('X')`.
* Точно совпадает с bare-id (не подцеплять `<main>/runtime/react`).
*/
function buildBareImportPattern(bare) {
	const escaped = bare.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
	return new RegExp(String.raw`(?:from|import)\s*\(?\s*["']` + escaped + String.raw`["']\s*\)?`);
}
var BARE_PATTERNS = new Map(SINGLETON_BARE_NAMES$1.map((bare) => [bare, buildBareImportPattern(bare)]));
var LEGACY_CORE_DI_EXTERNAL_PATTERNS = [
	/\.modules\.Core\b/,
	/modules\["Core"\]/,
	/modules\.Core\b/,
	/\["promise\s+__[\w]+__\.modules",\s*"Core"\]/
];
function checkPluginBundleSanity(input) {
	const violations = [];
	const uiKitPattern = input.uiKitPackage ? buildBareImportPattern(input.uiKitPackage) : null;
	const uiKitName = input.uiKitPackage ?? "";
	for (const [chunkFileName, source] of input.chunks) {
		for (const [bare, pattern] of BARE_PATTERNS) if (pattern.test(source)) violations.push({
			chunkFileName,
			bare
		});
		if (uiKitPattern && uiKitPattern.test(source)) violations.push({
			chunkFileName,
			bare: uiKitName
		});
		for (const legacyPattern of LEGACY_CORE_DI_EXTERNAL_PATTERNS) if (legacyPattern.test(source)) {
			violations.push({
				chunkFileName,
				bare: "legacy-modules.Core-external"
			});
			break;
		}
	}
	if (violations.length === 0) return { status: "clean" };
	return {
		status: "violations",
		violations,
		warnMessage: renderViolationsWarn(input.pluginName, input.mainPackage, violations)
	};
}
function renderViolationsWarn(pluginName, mainPackage, violations) {
	const byBare = /* @__PURE__ */ new Map();
	for (const v of violations) {
		if (!byBare.has(v.bare)) byBare.set(v.bare, []);
		byBare.get(v.bare).push(v.chunkFileName);
	}
	const lines = [];
	lines.push(`[${pluginName}] Plugin bundle contains BARE runtime imports (singleton invariant broken).`, `These imports will be resolved by the integrator's Vite as a SEPARATE React/antd copy,`, `causing "Invalid hook call" when the plugin meets host singletons.`, ``, `Bare imports found:`);
	for (const [bare, chunks] of byBare) {
		lines.push(`  • "${bare}"`);
		for (const c of chunks.slice(0, 5)) lines.push(`      in ${c}`);
		if (chunks.length > 5) lines.push(`      …and ${chunks.length - 5} more chunk(s)`);
	}
	lines.push(``, `Likely root cause: PluginDev externals/alias did not catch these imports.`, `Each bare id should resolve through main subpath:`, `   "react"             → "${mainPackage}/runtime/react"`, `   "react-dom"         → "${mainPackage}/runtime/react-dom"`, `   "react/jsx-runtime" → "${mainPackage}/runtime/react/jsx-runtime"`, `   "antd"              → "${mainPackage}/runtime/antd"`, `   "@<scope>/ui-kit"   → "${mainPackage}/ui-kit"`, ``, `Check that PluginDev() is added to plugin's vite/webpack config with externals: 'esm' (or 'globals').`);
	return lines.join("\n");
}
//#endregion
//#region src/vite/pluginDev/mergeRollupOutputWithGlobals.ts
function mergeRollupOutputWithGlobals(prevOutput, resolveGlobalPath, pluginName) {
	function patchOne(out) {
		const base = out && typeof out === "object" ? { ...out } : {};
		const prevG = base.globals;
		base.globals = function globals(id) {
			const p = resolveGlobalPath(id);
			if (p) return `window.${p}`;
			if (typeof prevG === "function") return prevG(id);
			if (prevG && typeof prevG === "object" && !Array.isArray(prevG)) {
				const mapped = prevG[id];
				if (mapped !== void 0) return mapped;
			}
			console.warn(`[${pluginName}] Missing global mapping for external id: ${id}`);
			return id;
		};
		return base;
	}
	if (prevOutput == null) return patchOne({});
	if (Array.isArray(prevOutput)) return prevOutput.map(patchOne);
	return patchOne(prevOutput);
}
//#endregion
//#region src/shared/reactDuplicateDetector.ts
/**
* Детектор дублированных runtime-копий React/antd в Vite-prebundle integrator'а.
*
* Симптом: на странице одновременно живут два набора React-чанков —
* наш singleton (`<main>/runtime/react`) и собственный prebundle Vite
* (`react`, `react-dom`, `react/jsx-runtime`). Любой компонент, который
* импортирует bare `react` (например, independent `@<scope>/ui-kit` с
* `peerDependencies.react`), линкуется ко второй копии. Provider в host
* и Consumer в plugin оказываются в разных React'ах →
* `Invalid hook call` / `useContext returned null`.
*
* Эта функция читает `.vite/deps/_metadata.json` integrator'а и выдаёт
* pure-decision: какие пары `<bare> ↔ <main>/runtime/<bare>` обнаружены.
* Никаких side-effects на FS — caller (host plugin) рендерит warn в нужный
* канал и/или throw'ит под env-флагом.
*
* @module reactDuplicateDetector
*/
/**
* Bare-имена пакетов, для которых дубликат с `<main>/runtime/<name>` критичен
* (нарушает singleton invariant и приводит к Invalid hook call / Provider/Consumer
* на разных React'ах). Источник истины — пакеты из `runtime-contract` группы
* `runtime-bundle` (react / react-dom / antd / @ant-design/icons и их subpath'ы).
*
* Жёстко перечислены, потому что host plugin рантаймно НЕ читает контракт
* (контракт замораживается в branding на этапе сборки bundler-plugins).
*/
var SINGLETON_BARE_NAMES = [
	"react",
	"react-dom",
	"react-dom/client",
	"react/jsx-runtime",
	"react/jsx-dev-runtime",
	"antd",
	"@ant-design/icons"
];
function safeRead(p, existsSync, readFileSync) {
	if (!existsSync(p)) return null;
	try {
		return JSON.parse(readFileSync(p, "utf-8"));
	} catch {
		return null;
	}
}
/**
* Возвращает `<mainPackage>/runtime/<bare>` (например, `@scope/main/runtime/react`).
* Учитывает subpath'ы вида `react/jsx-runtime` → `<main>/runtime/react/jsx-runtime`.
*/
function buildRuntimeSubpath(mainPackage, bare) {
	return `${mainPackage}/runtime/${bare}`;
}
function checkReactDuplicatePrebundle(input) {
	const existsSync = input.existsSync ?? fs$1.existsSync;
	const readFileSync = input.readFileSync ?? fs$1.readFileSync;
	const metadata = safeRead(path$1.join(input.viteCacheDir, "deps", "_metadata.json"), existsSync, readFileSync);
	if (!metadata || !metadata.optimized) return { status: "no-prebundle" };
	const optimized = metadata.optimized;
	if (Object.keys(optimized).filter((k) => k.startsWith(`${input.mainPackage}/runtime/`)).length === 0) return { status: "no-runtime-resolved" };
	const duplicates = [];
	for (const bare of SINGLETON_BARE_NAMES) {
		const bareEntry = optimized[bare];
		if (!bareEntry) continue;
		const runtimeSubpath = buildRuntimeSubpath(input.mainPackage, bare);
		const runtimeEntry = optimized[runtimeSubpath];
		if (!runtimeEntry) continue;
		duplicates.push({
			bare,
			bareSrc: String(bareEntry.src || bareEntry.file || "?"),
			runtimeSubpath,
			runtimeSrc: String(runtimeEntry.src || runtimeEntry.file || "?")
		});
	}
	if (duplicates.length === 0) return { status: "clean" };
	return {
		status: "duplicate",
		duplicates,
		warnMessage: renderDuplicateWarn(input.pluginName, input.mainPackage, duplicates)
	};
}
function renderDuplicateWarn(pluginName, mainPackage, duplicates) {
	const lines = [];
	lines.push(`[${pluginName}] Detected DUPLICATE React/antd copies in Vite prebundle (singleton invariant broken).`, `This causes "Invalid hook call" / "useContext returned null" when plugin code consumes a context whose Provider was set up against ${mainPackage}/runtime/* singleton (or vice versa).`, ``, `Found in .vite/deps/_metadata.json:`);
	for (const pair of duplicates) {
		lines.push(`  • ${pair.bare}`);
		lines.push(`      bare  → ${pair.bareSrc}`);
		lines.push(`      via   → ${pair.runtimeSubpath}`);
		lines.push(`      via   → ${pair.runtimeSrc}`);
	}
	lines.push(``, `Likely root cause: some node_modules dependency (e.g. independent @scope/ui-kit) declares peerDependencies.react`, `and is reachable from the integrator's release-host. Vite sees a bare \`import 'react'\` and prebundles it`, `independently of ${mainPackage}/runtime/react.`, ``, `Fix (release-host vite config of the integrator / CLI-generated plugin):`, `  1. Either alias bare ids to main subpath:`, `     resolve: { alias: { 'react': '${mainPackage}/runtime/react', 'react-dom': '${mainPackage}/runtime/react-dom', ... } }`, `  2. Or pre-bundle only via main and disable bare-id optimizer:`, `     optimizeDeps: { exclude: ['react', 'react-dom', 'react/jsx-runtime', 'antd'] }`, ``, `For full diagnostic run:  npx tsx build-tools/scripts/diagnose/diagnose-react-duplicates.ts --plugin-dir <path>`);
	return lines.join("\n");
}
//#endregion
//#region src/vite/reactDuplicateRuntimeCheck.ts
/**
* Env-флаг `BUNDLER_RUNTIME_STRICT=1` переводит defensive детекторы в throw-режим.
* CLI устанавливает его автоматически при локальной сборке плагина из нашего репо.
*/
var STRICT_ENV_FLAG$1 = "BUNDLER_RUNTIME_STRICT";
function isStrictMode(envSource = process.env) {
	const raw = envSource[STRICT_ENV_FLAG$1];
	return raw === "1" || raw === "true";
}
function runReactDuplicateRuntimeCheck(opts, signals = {}) {
	const result = checkReactDuplicatePrebundle({
		viteCacheDir: opts.viteCacheDir,
		mainPackage: opts.mainPackage,
		pluginName: opts.pluginName,
		existsSync: opts.existsSync,
		readFileSync: opts.readFileSync
	});
	if (result.status !== "duplicate" || !result.warnMessage) return result.status;
	if (isStrictMode(signals.env)) {
		(signals.fail ?? ((message) => {
			throw new Error(message);
		}))(result.warnMessage);
		return "duplicate-throw";
	}
	(signals.warn ?? ((message) => console.warn(message)))(result.warnMessage);
	return "duplicate-warned";
}
//#endregion
//#region src/vite/pluginDev/index.ts
var PLUGIN_NAME = `${BUNDLER_DEFAULT_APP_NAME}-pluginDev-vite`;
var RUNTIME_INDEX_SUFFIX_RE = /\/index(?:\.(?:js|mjs|cjs))?$/;
var RUNTIME_CORE_PACKAGE = getRuntimeCorePackageName(BUNDLER_DEFAULT_PACKAGE_NAME);
var RUNTIME_COMPAT_CORE_REQUEST = `${BUNDLER_RUNTIME_PACKAGE}/core`;
var PLUGIN_DEV_VITE_ENTRY_URL = import.meta.url;
var STRICT_ENV_FLAG = "BUNDLER_RUNTIME_STRICT";
function isPluginDevStrictMode(envSource = process.env) {
	const raw = envSource[STRICT_ENV_FLAG];
	return raw === "1" || raw === "true";
}
function extractBarePackageFromResolvedId(id) {
	if (!id || typeof id !== "string") return null;
	const normalized = id.replace(/\\/g, "/");
	const idx = normalized.lastIndexOf("/node_modules/");
	if (idx === -1) return null;
	const parts = normalized.slice(idx + 14).split("/");
	if (parts[0].startsWith("@")) {
		if (parts.length < 2) return null;
		return `${parts[0]}/${parts[1]}`;
	}
	return parts[0] || null;
}
function createGlobalPathResolver(globalMap) {
	const keys = Object.keys(globalMap).sort((a, b) => b.length - a.length);
	return function resolveGlobalPath(id) {
		if (globalMap[id]) return globalMap[id];
		for (let i = 0; i < keys.length; i += 1) {
			const key = keys[i];
			if (id === key || id.startsWith(`${key}/`)) return globalMap[key];
		}
		const bare = extractBarePackageFromResolvedId(id);
		if (bare && globalMap[bare]) return globalMap[bare];
		return null;
	};
}
function chainRollupExternal(prevExternal, isOurExternal) {
	return function external(id, importer, isResolved) {
		if (isOurExternal(id)) return true;
		if (prevExternal == null) return false;
		if (typeof prevExternal === "function") {
			const r = prevExternal(id, importer, isResolved);
			return Boolean(r);
		}
		if (Array.isArray(prevExternal)) return prevExternal.includes(id);
		if (prevExternal instanceof RegExp) return prevExternal.test(id);
		return prevExternal === id;
	};
}
function mergeRollupOptionsForGlobals(userRollup, resolveGlobalPath, pluginName) {
	const prev = userRollup || {};
	const prevExternal = prev.external;
	const isOurExternal = (id) => Boolean(resolveGlobalPath(id));
	return {
		...prev,
		external: chainRollupExternal(prevExternal, isOurExternal),
		output: mergeRollupOutputWithGlobals(prev.output, resolveGlobalPath, pluginName)
	};
}
function mergeOptimizeDepsExclude(prevOptimizeDeps, nextExclude) {
	return mergePluginDevOptimizeDepsExclude(prevOptimizeDeps, nextExclude);
}
function normalizeRuntimeSubpath(subpath) {
	return subpath.replace(RUNTIME_INDEX_SUFFIX_RE, "");
}
function attachPluginDevDuplicateRuntimeCheck(server, singletonIds) {
	let metadataDebounceTimer = null;
	let metadataWatcher;
	const depsMetadataPath = path.join(server.config.cacheDir, "deps", "_metadata.json");
	const runCheck = () => {
		runReactDuplicateRuntimeCheck({
			viteCacheDir: server.config.cacheDir,
			mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME,
			pluginName: PLUGIN_NAME
		});
		const metadataPath = path.join(server.config.cacheDir, "deps", "_metadata.json");
		let metadata = null;
		try {
			if (fs.existsSync(metadataPath)) metadata = JSON.parse(fs.readFileSync(metadataPath, "utf8"));
		} catch {
			metadata = null;
		}
		const singletonCheck = checkPluginDevRuntimeSingletonPrebundle({
			metadata,
			singletonIds,
			pluginName: PLUGIN_NAME,
			mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME
		});
		if (singletonCheck.status === "prebundled" && singletonCheck.warnMessage) {
			if (isPluginDevStrictMode()) throw new Error(singletonCheck.warnMessage);
			console.warn(singletonCheck.warnMessage);
		}
	};
	const scheduleCheck = () => {
		if (metadataDebounceTimer) clearTimeout(metadataDebounceTimer);
		metadataDebounceTimer = setTimeout(() => {
			metadataDebounceTimer = null;
			runCheck();
		}, 150);
	};
	runCheck();
	try {
		if (fs.existsSync(depsMetadataPath)) metadataWatcher = fs.watch(depsMetadataPath, { persistent: false }, scheduleCheck);
	} catch {}
	server.httpServer?.once("close", () => {
		metadataWatcher?.close();
		if (metadataDebounceTimer) clearTimeout(metadataDebounceTimer);
	});
}
function printModeHints(opts) {
	if (opts.externals === "globals") console.warn(`[${PLUGIN_NAME}] globals mode is intended for the browser/script target. Make sure the host loads runtime globals before loading the plugin bundle.`);
	if (opts.alias && opts.externals === "globals") console.warn(`[${PLUGIN_NAME}] alias=true with globals mode is an advanced setup and is usually unnecessary.`);
}
function PluginDev(options) {
	const opts = resolvePluginDevOptions(options);
	if (opts.externals === "async-globals") throw new Error(`[${PLUGIN_NAME}] externals: 'async-globals' is Webpack-only. Use @scope/webpack/pluginDev or Vite modes 'esm' | 'globals'.`);
	let runtimeModules;
	let runtimeCoreModules;
	let runtimeCoreExport;
	let runtimeEntries;
	let runtimeCoreModuleSet;
	let manifestList;
	try {
		manifestList = createRuntimeEntryList(readRuntimeManifest(BUNDLER_RUNTIME_PACKAGE, PLUGIN_NAME, PLUGIN_DEV_VITE_ENTRY_URL, 2));
	} catch (e) {
		const msg = e instanceof Error ? e.message : String(e);
		throw new Error(`[${PLUGIN_NAME}] ${BUNDLER_RUNTIME_PACKAGE} not found.\nMake sure it is installed: npm install ${BUNDLER_RUNTIME_PACKAGE}\n` + msg);
	}
	({runtimeModules, runtimeCoreModules, runtimeCoreExport, runtimeEntries, runtimeCoreModuleSet} = manifestList);
	const exportNameByOriginal = new Map(runtimeEntries.map((entry) => [entry.originalName, entry.exportName]));
	/**
	* Корни bare-package'ов рантайма (react, react-dom, antd, @ant-design/icons, …).
	* Используются, чтобы запретить deep-импорты вида `antd/es/locale/zh_CN`,
	* которые приведут к расщеплению singleton-графа (antd в host + antd в плагине).
	* UI-kit и main package исключены — у них своя обработка выше.
	*/
	const runtimePackageRoots = /* @__PURE__ */ new Set();
	const runtimeRootKnownSubpaths = /* @__PURE__ */ new Map();
	for (const entry of runtimeEntries) {
		if (isUiKitManifestEntry(entry.exportName)) continue;
		const root = getRuntimePackageRoot(entry.originalName);
		runtimePackageRoots.add(root);
		if (!runtimeRootKnownSubpaths.has(root)) runtimeRootKnownSubpaths.set(root, /* @__PURE__ */ new Set());
		runtimeRootKnownSubpaths.get(root).add(entry.originalName);
	}
	const resolvedAliases = attachRuntimeAliasesToManifestList(manifestList, opts.alias || runtimeCoreModules.length > 0);
	const aliasEntries = resolvedAliases.packageAliasEntries;
	const runtimeIndexAliasEntries = resolvedAliases.runtimeIndexAliases;
	const isGlobalMode = opts.externals === "globals";
	const isEsmMode = opts.externals === "esm";
	const globalMap = isGlobalMode ? buildPluginDevGlobalMap({
		namespace: BUNDLER_NAMESPACE,
		mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME,
		runtimePackage: BUNDLER_RUNTIME_PACKAGE,
		runtimeCorePackage: RUNTIME_CORE_PACKAGE,
		runtimeCompatCoreRequest: RUNTIME_COMPAT_CORE_REQUEST,
		runtimeCoreExport,
		runtimeCoreModuleSet,
		runtimeEntries
	}) : {};
	const resolveGlobalPath = isGlobalMode ? createGlobalPathResolver(globalMap) : null;
	const deepImportGuardInput = {
		knownRuntimeModules: runtimeModules,
		runtimePackageRoots,
		runtimeRootKnownSubpaths,
		allowedDeepRuntimeImports: opts.allowedDeepRuntimeImports,
		pluginName: PLUGIN_NAME,
		runtimePackage: BUNDLER_RUNTIME_PACKAGE,
		optInExample: (req) => `opt in via PluginDev({ allowedDeepRuntimeImports: ['${req}'] })`
	};
	const applyDeepImportGuard = (request) => {
		const guard = evaluateDeepImportRequest({
			request,
			...deepImportGuardInput
		});
		if (guard.action === "allow-with-warn") {
			console.warn(guard.warnMessage);
			return;
		}
		if (guard.action === "block") throw new Error(guard.errorMessage);
	};
	console.log(`[${PLUGIN_NAME}] externals: ${opts.externals || "disabled"}, alias: ${opts.alias}`);
	printModeHints(opts);
	if (opts.externals) console.log(`[${PLUGIN_NAME}] ${Object.values(runtimeModules).length} runtime externals`);
	const optimizeDepsManifestInput = {
		mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME,
		runtimePackage: BUNDLER_RUNTIME_PACKAGE,
		runtimeModules,
		runtimeEntries,
		runtimeCoreModuleSet
	};
	const singletonDepIds = buildPluginDevSingletonDepIds(optimizeDepsManifestInput);
	const plugins = [{
		name: PLUGIN_NAME,
		enforce: "pre",
		config(userConfig) {
			const config = {};
			if (aliasEntries.length > 0 || runtimeIndexAliasEntries.length > 0) config.resolve = { alias: [...aliasEntries, ...runtimeIndexAliasEntries] };
			/** Bare singleton packages must not be prebundled from node_modules (see `pluginDevOptimizeDepsExclude`). */
			config.optimizeDeps = mergeOptimizeDepsExclude(userConfig.optimizeDeps, buildPluginDevOptimizeDepsExclude(optimizeDepsManifestInput));
			if (isGlobalMode && resolveGlobalPath && Object.keys(globalMap).length > 0) config.build = { rollupOptions: mergeRollupOptionsForGlobals(userConfig && userConfig.build && userConfig.build.rollupOptions, resolveGlobalPath, PLUGIN_NAME) };
			return config;
		},
		configureServer(server) {
			if (opts.alias && opts.externals === false) attachPluginDevDuplicateRuntimeCheck(server, singletonDepIds);
		},
		resolveId(source) {
			if (opts.alias) applyDeepImportGuard(source);
			if (isEsmMode) {
				if (source === RUNTIME_COMPAT_CORE_REQUEST || source === RUNTIME_CORE_PACKAGE) return {
					id: RUNTIME_CORE_PACKAGE,
					external: true
				};
				if (source.startsWith(`${RUNTIME_CORE_PACKAGE}/`)) return {
					id: RUNTIME_CORE_PACKAGE,
					external: true
				};
				if (source.startsWith(`useblocks/runtime/`)) {
					const normalizedRuntimeSubpath = normalizeRuntimeSubpath(source.slice(`${BUNDLER_RUNTIME_PACKAGE}/`.length));
					if (normalizedRuntimeSubpath === "core") return {
						id: RUNTIME_CORE_PACKAGE,
						external: true
					};
					if (runtimeCoreModuleSet.has(normalizedRuntimeSubpath)) return {
						id: RUNTIME_CORE_PACKAGE,
						external: true
					};
					return {
						id: `${BUNDLER_RUNTIME_PACKAGE}/${normalizedRuntimeSubpath}`,
						external: true
					};
				}
				if (runtimeModules[source] !== void 0) return {
					id: resolvePluginDevPackageRequest(source, exportNameByOriginal.get(source), BUNDLER_RUNTIME_PACKAGE, RUNTIME_CORE_PACKAGE, runtimeCoreModuleSet, BUNDLER_DEFAULT_PACKAGE_NAME),
					external: true
				};
				const uiKitOriginal = runtimeEntries.find((entry) => isUiKitManifestEntry(entry.exportName) && source.startsWith(`${entry.originalName}/`));
				if (uiKitOriginal) {
					const suffix = source.slice(uiKitOriginal.originalName.length);
					return {
						id: `${resolvePluginDevPackageRequest(uiKitOriginal.originalName, uiKitOriginal.exportName, BUNDLER_RUNTIME_PACKAGE, RUNTIME_CORE_PACKAGE, runtimeCoreModuleSet, BUNDLER_DEFAULT_PACKAGE_NAME)}${suffix}`,
						external: true
					};
				}
				if (isMainPackageUiKitImport(source, "useblocks")) return {
					id: source,
					external: true
				};
			}
			return null;
		},
		/**
		* Build-time defensive sanity check: после генерации output chunks
		* сканируем их на bare-импорты runtime-пакетов. Все они должны идти
		* через `<main>/runtime/<pkg>` — иначе integrator'ский Vite в release-host
		* сделает второй prebundle (см. `reactDuplicateDetector` runtime-side).
		*
		* Default — warn. Под `BUNDLER_RUNTIME_STRICT=1` (CLI local-build) — throw.
		*/
		generateBundle(_outputOptions, bundle) {
			const chunks = /* @__PURE__ */ new Map();
			for (const fileName of Object.keys(bundle)) {
				const entry = bundle[fileName];
				if (entry.type !== "chunk") continue;
				if (!/\.(?:js|mjs|cjs)$/.test(fileName)) continue;
				chunks.set(fileName, entry.code);
			}
			if (chunks.size === 0) return;
			const sanity = checkPluginBundleSanity({
				chunks,
				mainPackage: BUNDLER_DEFAULT_PACKAGE_NAME,
				pluginName: PLUGIN_NAME
			});
			if (sanity.status === "violations" && sanity.warnMessage) {
				if (isPluginDevStrictMode()) this.error(sanity.warnMessage);
				console.warn(sanity.warnMessage);
			}
		}
	}];
	if (opts.alias) plugins.push(createPluginDevServePostPlugin(PLUGIN_NAME, BUNDLER_RUNTIME_PACKAGE, optimizeDepsManifestInput));
	return plugins;
}
//#endregion
export { PluginDev as default };
