UNPKG

weapp-vite

Version:

weapp-vite 一个现代化的小程序打包工具

36,242 lines 1.53 MB
import { n as applyWeappViteHostMeta } from "./pluginHost--CaeyWpA.mjs";
import { C as inlineAutoRoutesImports, T as MINI_PROGRAM_PLATFORM_ADAPTERS, _ as templateExtensions, a as findJsonEntry, b as isNativeTemplateSource, c as isJsOrTs, d as touch, g as supportedCssLangs, h as scriptExtensions, i as findJsEntry, l as isTemplate, m as jsExtensions, n as changeFileExtension, o as findTemplateEntry, p as configExtensions, r as findCssEntry, s as findVueEntry, t as extractConfigFromVue, v as vueExtensions, x as isSourceStyleExtension, y as ALL_NATIVE_STYLE_RESOLVER_EXTENSIONS } from "./file-B34zY0ET.mjs";
import { n as configureLogger, r as logger_default } from "./logger-mt4mSTqV.mjs";
import { createRequire, isBuiltin } from "node:module";
import { createDebug } from "obug";
import fs, { existsSync, readFileSync, realpathSync } from "node:fs";
import { APP_PRELUDE_CHUNK_MARKER, APP_PRELUDE_GUARD_KEY, APP_PRELUDE_REQUIRE_MARKER, REQUEST_GLOBAL_ACTUALS_KEY, REQUEST_GLOBAL_BUNDLE_HOST_REF, REQUEST_GLOBAL_BUNDLE_MARKER, REQUEST_GLOBAL_BUNDLE_MARKER as REQUEST_GLOBAL_BUNDLE_MARKER$1, REQUEST_GLOBAL_CHUNK_HOST_REF, REQUEST_GLOBAL_CHUNK_MODULE_REF, REQUEST_GLOBAL_EXPOSE_HELPER, REQUEST_GLOBAL_INSTALLER_HOST_REF, REQUEST_GLOBAL_LAZY_CONSTRUCTOR_HELPER, REQUEST_GLOBAL_LAZY_FUNCTION_HELPER, REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER, REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER as REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER$1, REQUEST_GLOBAL_MARK_PLACEHOLDER_HELPER, REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER, REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER as REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER$1, REQUEST_GLOBAL_PLACEHOLDER_KEY, REQUEST_GLOBAL_PRELUDE_GUARD_KEY, REQUEST_GLOBAL_PRELUDE_MARKER, REQUEST_GLOBAL_SYNTHETIC_EXPORT_NAME, REQUEST_GLOBAL_USABLE_CONSTRUCTOR_HELPER, WEAPP_I18N_JS_FILE, WEAPP_I18N_LOCALE_DATA_KEY, WEAPP_I18N_PUBLIC_MODULE_ID, WEAPP_I18N_RUNTIME_MARKER, WEAPP_I18N_VIRTUAL_MODULE_ID, WEAPP_I18N_WXS_FILE, WEAPP_REACT_EVENT_METHOD_NAME, WEAPP_VITE_EXTERNAL_OUTPUT_DIRECTORY, WEAPP_VITE_IMPORT_META_ENV_KEY, WEAPP_VITE_INJECTED_API_IDENTIFIER, WEAPP_VITE_LOGICAL_ENTRY_RESOLVED_PREFIX, WEAPP_VITE_LOGICAL_ENTRY_VIRTUAL_PREFIX, WEAPP_VITE_RUNTIME_CONTRACT_VERSION, WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID, WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID, WEAPP_VITE_RUNTIME_VIRTUAL_ID, WEAPP_VITE_RUNTIME_VIRTUAL_IDS, WEAPP_VITE_SIDECAR_OWNER_QUERY_MARKER, WEAPP_VITE_SIDECAR_QUERY_MARKER, WEAPP_VITE_SIDECAR_RESOLVED_PREFIX, WEAPP_VITE_SIDECAR_VIRTUAL_PREFIX, WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY, WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY, WEAPP_VITE_STATEFUL_HMR_PRELOAD_FILE, WEAPP_VITE_STATEFUL_HMR_UPDATE_FILE, WEVU_APP_SHELL_COMPONENT_BASE, WEVU_APP_SHELL_TAG_NAME, WEVU_EXPRESSION_ERROR_IDENTIFIER, WEVU_INTERNAL_KEY_IDENTIFIER, WEVU_LAYOUT_BIND_PREFIX, WEVU_PAGE_LAYOUT_CURRENT_NAME_IDENTIFIER, WEVU_PAGE_LAYOUT_CURRENT_PROPS_IDENTIFIER, WEVU_PAGE_LAYOUT_NAME_KEY, WEVU_PAGE_LAYOUT_NEXT_NAME_IDENTIFIER, WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER, WEVU_PAGE_LAYOUT_NONE, WEVU_PAGE_LAYOUT_PROPS_KEY, WEVU_PAGE_LAYOUT_SETTER_KEY, WEVU_SCOPED_SLOT_CREATOR_KEY, WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE, WEVU_SLOT_FALLBACK_VIRTUAL_HOST_GLOBAL_PATH, WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME, WEVU_SLOT_NAMES_PROP, WEVU_SLOT_OWNER_ID_ATTR, WEVU_SLOT_OWNER_ID_KEY, WEVU_SLOT_OWNER_ID_PROP, WEVU_SLOT_PROPS_ATTR, WEVU_SLOT_SCOPE_ATTR, WEVU_SLOT_SCOPE_KEY } from "@weapp-core/constants";
import path, { posix } from "pathe";
import { fileURLToPath } from "node:url";
import path$1, { normalize, relative, win32 } from "node:path";
import { MINI_PROGRAM_PLATFORM_ALIASES, MINI_PROGRAM_PLATFORM_DESCRIPTORS, addExtension, defu, escapeStringRegexp, escapeWxmlAttribute, escapeWxmlText, get, getDefaultMiniProgramPlatform, getMiniProgramAppTypesPackage, getMiniProgramDefaultBuildTarget, getMiniProgramDirectivePrefix, getMiniProgramRouteRuntimeGlobalKeys, getMiniProgramRuntimeGlobalKey, getMiniProgramRuntimeGlobalKeys, getMiniProgramRuntimeGlobalKeysByResolvePriority, getSupportedMiniProgramDirectivePrefixes, getSupportedMiniProgramPlatforms, isEmptyObject, isObject, normalizeMiniProgramPlatform, removeExtension, removeExtensionDeep, resolveMiniProgramPlatform, set, supportsMiniProgramAutoTouchAppStyle } from "@weapp-core/shared";
import { parse, stringify } from "comment-json";
import { fs as fs$1 } from "@weapp-core/shared/fs";
import process from "node:process";
import { compileScript, parse as parse$1 } from "vue/compiler-sfc";
import { BABEL_TS_MODULE_PARSER_OPTIONS, analyzeScript as analyzeScript$1, analyzeScripts, collectComponentPropsFromCode, collectRequireTokens, collectScriptSetupImportsFromCode, generate, mayContainPlatformApiIdentifierByText, mayContainStaticRequireLiteral, parse as parse$2, parseJsLikeWithEngine, platformApiIdentifiers } from "@weapp-vite/ast";
import { collectOnPageScrollPerformanceWarnings } from "@weapp-vite/ast/operations/onPageScroll";
import { collectSetDataPickKeysFromTemplateCode } from "@weapp-vite/ast/operations/setDataPick";
import { BABEL_TS_MODULE_PARSER_OPTIONS as BABEL_TS_MODULE_PARSER_OPTIONS$1, generate as generate$1, getVisitorKeys, parse as parse$3, parseJsLike, traverse } from "@weapp-vite/ast/babel";
import picomatch from "picomatch";
import { VUE_COMPONENT_TAG_RE, WE_VU_COMPILER_REACTIVITY_MODULE_ID, WE_VU_COMPILER_RUNTIME_MODULE_ID, WE_VU_COMPILER_TEMPLATE_MODULE_ID, WE_VU_RUNTIME_APIS, buildClassStyleComputedCode, classifyVueSfcBlockChanges, collectVueTemplateTags, compileJsxFile, compileVueFile, compileVueStyleToWxss, createJsonMerger, createPageEntryMatcher, createPageEntryMatcher as createPageEntryMatcher$1, generateScopedId, getClassStyleWxsSource, getMiniProgramTemplatePlatform, getSfcCheckMtime, injectWevuPageFeaturesInJsWithResolver, invalidateFileCache, isAutoImportCandidateTag, isBuiltinComponent, isUniAppCompatibilityFile, pathExists, readAndParseSfc, readFile as readFile$1, refreshVueFileJsonConfig, resolveClassStyleWxsLocation, resolveVueSfcHmrSignatures, resolveVueSfcStyleIndependentSignature, transformNestedWxssVars, transformUniAppSource, transformVueDeepSelectors } from "wevu/compiler";
import fs$2, { appendFile, copyFile, mkdir, readFile, readdir, rm } from "node:fs/promises";
import { build, createLogger, createServer, loadConfigFromFile, preprocessCSS, transformWithOxc } from "vite";
import { createHash, randomBytes } from "node:crypto";
import semverGte from "semver/functions/gte.js";
import semverSatisfies from "semver/functions/satisfies.js";
import semverValid from "semver/functions/valid.js";
import { LRUCache } from "lru-cache";
import { fdir } from "fdir";
import chokidar from "chokidar";
import { getPackageInfo, getPackageInfoSync, resolveModule } from "local-pkg";
import { build as build$1 } from "rolldown";
import { dts } from "rolldown-plugin-dts";
import os from "node:os";
import { spawn } from "node:child_process";
import PQueue from "p-queue";
import { Buffer } from "node:buffer";
import MagicString from "magic-string";
import remapping from "@jridgewell/remapping";
import * as t from "@weapp-vite/ast/babelTypes";
import { dev } from "rolldown/experimental";
import babelPresetEnv from "@babel/preset-env";
import babelPresetTypescript from "@babel/preset-typescript";
import * as babel from "@weapp-vite/ast/babelCore";
import { Parser } from "htmlparser2";
import { detect } from "package-manager-detector/detect";
import tsconfigPaths from "vite-tsconfig-paths";
import { objectHash } from "@weapp-core/shared/node";
import { wrapPlugin } from "vite-plugin-performance";
import { performance as performance$1 } from "node:perf_hooks";
import postcss from "postcss";
import { compileI18nCatalog, generateI18nCatalogModuleSource, generateI18nRuntimeSource, generateI18nWxsSource } from "@weapp-vite/i18n/compiler";
import { weappWebPlugin } from "@weapp-vite/web";
import { bundleRequire } from "rolldown-require";
//#region src/debugger.ts
/**
* 创建一个调试器实例,用于输出带有命名空间的调试信息。
* @param namespace - 调试信息的命名空间,格式为 'weapp-vite:' + 自定义字符串。
* @returns 如果调试器启用,则返回调试器实例;否则返回 undefined。
*/
function createDebugger(namespace) {
	const debug = createDebug(namespace);
	if (debug.enabled) return debug;
}
//#endregion
//#region src/moduleGraph/protocol.ts
const VIRTUAL_MODULE_SUFFIX = ":module.js";
const SIDECAR_SOURCE_JS_SUFFIX = "&lang.js";
const SIDECAR_SOURCE_STYLE_SUFFIX = "&lang.css";
function normalizeProtocolPath(id) {
	const normalized = path.normalize(id.replaceAll("\\", "/"));
	if (!path.isAbsolute(normalized)) return normalized;
	try {
		return path.normalize(realpathSync.native(normalized));
	} catch {
		return normalized;
	}
}
function encodePath(id) {
	return encodeURIComponent(normalizeProtocolPath(id));
}
function decodePath(id) {
	return normalizeProtocolPath(decodeURIComponent(id));
}
function resolveProtocolPrefix(id, virtualPrefix, resolvedPrefix) {
	if (id.startsWith(resolvedPrefix)) return id.slice(resolvedPrefix.length);
	if (id.startsWith(virtualPrefix)) return id.slice(virtualPrefix.length);
}
function createLogicalEntryId(sourceId, type) {
	return `${WEAPP_VITE_LOGICAL_ENTRY_RESOLVED_PREFIX}${type}:${encodePath(sourceId)}${VIRTUAL_MODULE_SUFFIX}`;
}
function parseLogicalEntryId(id) {
	const request = resolveProtocolPrefix(id, WEAPP_VITE_LOGICAL_ENTRY_VIRTUAL_PREFIX, WEAPP_VITE_LOGICAL_ENTRY_RESOLVED_PREFIX);
	if (!request) return;
	if (!request.endsWith(VIRTUAL_MODULE_SUFFIX)) return;
	const normalizedRequest = request.slice(0, -10);
	const separator = normalizedRequest.indexOf(":");
	if (separator < 0) return;
	const type = normalizedRequest.slice(0, separator);
	if (![
		"app",
		"page",
		"component",
		"layout"
	].includes(type)) return;
	return {
		sourceId: decodePath(normalizedRequest.slice(separator + 1)),
		type
	};
}
function createSidecarModuleId(ownerId, sourceId, kind) {
	return `${WEAPP_VITE_SIDECAR_RESOLVED_PREFIX}${kind}:${encodePath(ownerId)}:${encodePath(sourceId)}${VIRTUAL_MODULE_SUFFIX}`;
}
function parseSidecarModuleId(id) {
	const request = resolveProtocolPrefix(id, WEAPP_VITE_SIDECAR_VIRTUAL_PREFIX, WEAPP_VITE_SIDECAR_RESOLVED_PREFIX);
	if (!request) return;
	if (!request.endsWith(VIRTUAL_MODULE_SUFFIX)) return;
	const [kind, ownerId, sourceId, ...rest] = request.slice(0, -10).split(":");
	if (rest.length || !kind || !ownerId || !sourceId || ![
		"json",
		"jsx",
		"layout",
		"script",
		"style",
		"template",
		"using-component",
		"wxs"
	].includes(kind)) return;
	return {
		kind,
		ownerId: decodePath(ownerId),
		sourceId: decodePath(sourceId)
	};
}
function createSidecarSourceSpecifier(ownerId, sourceId, kind) {
	const queryPrefix = kind === "style" ? "?" : "?raw&";
	const suffix = kind === "style" ? SIDECAR_SOURCE_STYLE_SUFFIX : SIDECAR_SOURCE_JS_SUFFIX;
	return `${normalizeProtocolPath(sourceId)}${queryPrefix}${WEAPP_VITE_SIDECAR_OWNER_QUERY_MARKER}=${encodePath(ownerId)}&${WEAPP_VITE_SIDECAR_QUERY_MARKER}=${kind}${suffix}`;
}
function parseSidecarSourceRequest(id) {
	const queryIndex = id.indexOf("?");
	if (queryIndex < 0) return;
	const query = new URLSearchParams(id.slice(queryIndex + 1));
	const kind = query.get(WEAPP_VITE_SIDECAR_QUERY_MARKER);
	const ownerId = query.get(WEAPP_VITE_SIDECAR_OWNER_QUERY_MARKER);
	if (!kind || ![
		"json",
		"jsx",
		"layout",
		"script",
		"style",
		"template",
		"using-component",
		"wxs"
	].includes(kind)) return;
	if (!ownerId) return;
	const isStyle = kind === "style";
	const hasExpectedLang = query.has(isStyle ? "lang.css" : "lang.js");
	const hasUnexpectedLang = query.has(isStyle ? "lang.js" : "lang.css");
	const hasExpectedRawMode = query.has("raw") !== isStyle;
	if (!hasExpectedLang || hasUnexpectedLang || !hasExpectedRawMode) return;
	return {
		kind,
		ownerId: normalizeProtocolPath(ownerId),
		sourceId: normalizeProtocolPath(id.slice(0, queryIndex))
	};
}
function resolveVirtualModuleId(id) {
	const logicalEntry = parseLogicalEntryId(id);
	if (logicalEntry) return createLogicalEntryId(logicalEntry.sourceId, logicalEntry.type);
	const sidecar = parseSidecarModuleId(id);
	if (sidecar) return createSidecarModuleId(sidecar.ownerId, sidecar.sourceId, sidecar.kind);
}
//#endregion
//#region src/utils/viteId.ts
const VUE_VIRTUAL_MODULE_PREFIX$1 = "\0vue:";
const BACKSLASH_RE$1 = /\\/g;
const WINDOWS_VITE_AT_FS_DRIVE_RE = /^\/[A-Z]:\//i;
function stripViteAtFsPrefix(id) {
	if (!id.startsWith("/@fs/")) return id;
	let clean = id.slice(4);
	if (WINDOWS_VITE_AT_FS_DRIVE_RE.test(clean)) clean = clean.slice(1);
	return clean;
}
function normalizeViteId(id, options) {
	const stripQuery = options?.stripQuery !== false;
	const fileProtocolToPathEnabled = options?.fileProtocolToPath !== false;
	const stripAtFsPrefix = options?.stripAtFsPrefix !== false;
	const stripVueVirtualPrefix = options?.stripVueVirtualPrefix === true;
	const stripLeadingNullByte = options?.stripLeadingNullByte === true;
	let clean = id;
	if (stripVueVirtualPrefix && clean.startsWith(VUE_VIRTUAL_MODULE_PREFIX$1)) clean = clean.slice(5);
	if (stripQuery) clean = clean.split("?", 1)[0];
	if (fileProtocolToPathEnabled && clean.startsWith("file://")) try {
		clean = fileURLToPath(clean);
	} catch {
		try {
			clean = decodeURIComponent(new URL(clean).pathname);
		} catch {}
	}
	if (stripAtFsPrefix) clean = stripViteAtFsPrefix(clean);
	if (stripLeadingNullByte && clean.startsWith("\0")) clean = clean.slice(1);
	if (clean.includes("\\")) clean = clean.replace(BACKSLASH_RE$1, "/");
	return clean;
}
//#endregion
//#region src/utils/resolvedId.ts
function isSkippableResolvedId(id) {
	if (!id) return true;
	return id.startsWith("\0") || id.startsWith("node:");
}
function resolveFsResolvedIdNormalizeOptions(options) {
	const normalizeOptions = { stripVueVirtualPrefix: true };
	if (options?.normalize) Object.assign(normalizeOptions, options.normalize);
	if (options?.stripLeadingNullByte) normalizeOptions.stripLeadingNullByte = true;
	return normalizeOptions;
}
/**
* 将 Vite/Rolldown resolve 出来的 id 归一化为可用于 fs 读取/判断的路径形式。
*
* 默认会:
* - 去掉 query(?xxx)
* - 处理 `file://` URL
* - 处理 `/@fs/` 前缀
* - 可选剥离 `\0vue:` 前缀(默认开启)
*
* 注意:默认不剥离 `\0`,因为 `\0` 常用作虚拟模块标记,通常应当直接跳过。
*/
function normalizeFsResolvedId(id, options) {
	return normalizeViteId(id, resolveFsResolvedIdNormalizeOptions(options));
}
//#endregion
//#region src/moduleGraph/traversal.ts
function normalizeSourceId(id) {
	const normalized = normalizeFsResolvedId(id).split("?")[0];
	try {
		return normalizeFsResolvedId(realpathSync.native(normalized));
	} catch {
		return normalized;
	}
}
function moduleIdMatchesFile(id, file) {
	const sidecarSource = parseSidecarSourceRequest(id);
	if (sidecarSource) return normalizeSourceId(sidecarSource.sourceId) === file;
	const sidecar = parseSidecarModuleId(id);
	if (sidecar) return normalizeSourceId(sidecar.sourceId) === file;
	const logicalEntry = parseLogicalEntryId(id);
	if (logicalEntry) return normalizeSourceId(logicalEntry.sourceId) === file;
	return normalizeSourceId(id) === file;
}
function collectBuildStartIds(context, file) {
	const ids = /* @__PURE__ */ new Set();
	if (typeof context.getModuleIds !== "function") return ids;
	for (const id of context.getModuleIds()) if (moduleIdMatchesFile(id, file)) ids.add(id);
	return ids;
}
function collectDevStartNodes(server, file) {
	const nodes = new Set(server.moduleGraph.getModulesByFile(file) ?? []);
	for (const [id, node] of server.moduleGraph.idToModuleMap ?? []) if (moduleIdMatchesFile(id, file)) nodes.add(node);
	return nodes;
}
//#endregion
//#region src/moduleGraph/service.ts
const debug$3 = createDebugger("weapp-vite:module-graph");
function createModuleGraphService() {
	const buildContexts = /* @__PURE__ */ new Map();
	let pluginContext;
	let devServer;
	let topologyRescan;
	const entryDependencies = /* @__PURE__ */ new Map();
	const pendingChanges = /* @__PURE__ */ new Map();
	const hasRegisteredEntryDependency = (file) => {
		if (entryDependencies.has(file)) return true;
		for (const dependenciesByKind of entryDependencies.values()) for (const sourceIds of dependenciesByKind.values()) if (sourceIds.has(file)) return true;
		return false;
	};
	const collectFromBuildGraph = (file, affected) => {
		for (const buildContext of buildContexts.values()) {
			if (typeof buildContext.getModuleInfo !== "function") continue;
			const queue = [...collectBuildStartIds(buildContext, file)];
			const visited = /* @__PURE__ */ new Set();
			for (let index = 0; index < queue.length; index += 1) {
				const id = queue[index];
				if (visited.has(id)) continue;
				visited.add(id);
				const logicalEntry = parseLogicalEntryId(id);
				if (logicalEntry) {
					affected.add(normalizeSourceId(logicalEntry.sourceId));
					if (logicalEntry.type !== "layout") continue;
				}
				const sidecar = parseSidecarModuleId(id);
				if (sidecar) affected.add(normalizeSourceId(sidecar.ownerId));
				const sidecarSource = parseSidecarSourceRequest(id);
				if (sidecarSource) affected.add(normalizeSourceId(sidecarSource.ownerId));
				const info = buildContext.getModuleInfo(id);
				for (const importer of [...info?.importers ?? [], ...info?.dynamicImporters ?? []]) if (!visited.has(importer)) queue.push(importer);
			}
		}
	};
	const collectFromDevGraph = (file, affected) => {
		if (!devServer) return;
		const queue = [...collectDevStartNodes(devServer, file)];
		const visited = /* @__PURE__ */ new Set();
		for (let index = 0; index < queue.length; index += 1) {
			const module = queue[index];
			if (visited.has(module)) continue;
			visited.add(module);
			const logicalEntry = module.id ? parseLogicalEntryId(module.id) : void 0;
			if (logicalEntry) {
				affected.add(normalizeSourceId(logicalEntry.sourceId));
				if (logicalEntry.type !== "layout") continue;
			}
			const sidecar = module.id ? parseSidecarModuleId(module.id) : void 0;
			if (sidecar) {
				affected.add(normalizeSourceId(sidecar.ownerId));
				continue;
			}
			const sidecarSource = module.id ? parseSidecarSourceRequest(module.id) : void 0;
			if (sidecarSource) {
				affected.add(normalizeSourceId(sidecarSource.ownerId));
				continue;
			}
			for (const importer of module.importers ?? []) if (!visited.has(importer)) queue.push(importer);
		}
	};
	const collectAffectedEntries = (rawFile) => {
		const file = normalizeSourceId(rawFile);
		const affected = /* @__PURE__ */ new Set();
		for (const [ownerId, dependenciesByKind] of entryDependencies) for (const sourceIds of dependenciesByKind.values()) if (sourceIds.has(file)) {
			affected.add(ownerId);
			break;
		}
		if (devServer) collectFromDevGraph(file, affected);
		else collectFromBuildGraph(file, affected);
		return affected;
	};
	const warmDevModule = async (id) => {
		if (!devServer?.transformRequest) return;
		const queue = [id];
		const visited = /* @__PURE__ */ new Set();
		for (let index = 0; index < queue.length; index += 1) {
			const request = queue[index];
			if (visited.has(request)) continue;
			visited.add(request);
			try {
				await devServer.transformRequest(request);
			} catch (error) {
				debug$3?.(`dev graph 预热跳过无法展开的 external 终点 ${request}: ${String(error)}`);
				continue;
			}
			const module = devServer.moduleGraph.getModuleById(request);
			for (const dependency of module?.importedModules ?? []) {
				const dependencyRequest = dependency.url ?? dependency.id;
				if (dependencyRequest && !visited.has(dependencyRequest)) queue.push(dependencyRequest);
			}
		}
	};
	return {
		bindBuildContext(scope, context) {
			buildContexts.set(scope, context);
		},
		bindDevServer(server) {
			devServer = server;
		},
		bindPluginContext(context) {
			pluginContext = context;
		},
		collectAffectedEntries,
		getPendingChanges() {
			return Array.from(pendingChanges, ([file, event]) => ({
				event,
				file
			}));
		},
		consumeTopologyRescan() {
			const request = topologyRescan;
			topologyRescan = void 0;
			return request;
		},
		hasModule(rawFile) {
			const file = normalizeSourceId(rawFile);
			if (hasRegisteredEntryDependency(file)) return true;
			if (devServer) return collectDevStartNodes(devServer, file).size > 0;
			return Array.from(buildContexts.values()).some((context) => collectBuildStartIds(context, file).size > 0);
		},
		invalidate(rawFile) {
			const file = normalizeSourceId(rawFile);
			const affected = collectAffectedEntries(file);
			if (devServer) for (const module of collectDevStartNodes(devServer, file)) devServer.moduleGraph.invalidateModule(module);
			return affected;
		},
		isLogicalLayoutEntry(rawFile) {
			const file = normalizeSourceId(rawFile);
			for (const byKind of entryDependencies.values()) if (byKind.get("layout")?.has(file) && /\.(?:[cm]?[jt]sx?|vue)$/.test(file)) return true;
			return false;
		},
		async load(options) {
			if (typeof pluginContext?.load !== "function") throw new TypeError("ModuleGraphService 尚未绑定支持 load 的 PluginContext。");
			return await pluginContext.load(options);
		},
		replaceEntryDependencies(rawOwnerId, kind, sourceIds) {
			const ownerId = normalizeSourceId(rawOwnerId);
			let byKind = entryDependencies.get(ownerId);
			if (!byKind) {
				byKind = /* @__PURE__ */ new Map();
				entryDependencies.set(ownerId, byKind);
			}
			const normalized = new Set(Array.from(sourceIds, normalizeSourceId));
			if (normalized.size) byKind.set(kind, normalized);
			else byKind.delete(kind);
			if (!byKind.size) entryDependencies.delete(ownerId);
		},
		recordChangedFile(rawFile, event) {
			const file = normalizeSourceId(rawFile);
			pendingChanges.set(file, event);
		},
		clearPendingChanges() {
			pendingChanges.clear();
		},
		requestTopologyRescan(reason, rawFile) {
			topologyRescan ??= {
				files: /* @__PURE__ */ new Set(),
				reasons: /* @__PURE__ */ new Set()
			};
			topologyRescan.files.add(normalizeSourceId(rawFile));
			topologyRescan.reasons.add(reason);
		},
		async resolve(source, importer, options) {
			if (typeof pluginContext?.resolve !== "function") throw new TypeError("ModuleGraphService 尚未绑定支持 resolve 的 PluginContext。");
			return await pluginContext.resolve(source, importer, options);
		},
		async syncDevGraph(context) {
			if (!devServer || typeof context.getModuleIds !== "function") return;
			const logicalEntryIds = Array.from(context.getModuleIds()).filter((id) => parseLogicalEntryId(id));
			await Promise.all(logicalEntryIds.map(warmDevModule));
		},
		getEntryDependencies(rawOwnerId) {
			const ownerId = normalizeSourceId(rawOwnerId);
			const byKind = entryDependencies.get(ownerId);
			if (!byKind) return [];
			const dependencies = [];
			for (const [kind, sourceIds] of byKind) for (const sourceId of sourceIds) dependencies.push({
				kind,
				sourceId
			});
			return dependencies;
		}
	};
}
//#endregion
//#region src/runtime/autoImport/config/base.ts
const DEFAULT_AUTO_IMPORT_MANIFEST_FILENAME = "auto-import-components.json";
const WEAPP_VITE_INTERNAL_DIRNAME = ".weapp-vite";
function resolveBaseDir(configService) {
	const configFilePath = configService.configFilePath;
	if (configFilePath) return path.dirname(configFilePath);
	return configService.cwd;
}
function isProductionBuildWithInternalSupportFiles(configService) {
	return configService.emitDefaultAutoImportOutputs === false;
}
function resolveTypedComponentsDefaultPath(configService) {
	return path.resolve(resolveBaseDir(configService), WEAPP_VITE_INTERNAL_DIRNAME, "typed-components.d.ts");
}
function resolveHtmlCustomDataDefaultPath(configService) {
	return path.resolve(resolveBaseDir(configService), WEAPP_VITE_INTERNAL_DIRNAME, "mini-program.html-data.json");
}
function resolveVueComponentsDefaultPath(configService) {
	return path.resolve(resolveBaseDir(configService), WEAPP_VITE_INTERNAL_DIRNAME, "components.d.ts");
}
function resolveLayoutTypesDefaultPath(configService) {
	return path.resolve(resolveBaseDir(configService), WEAPP_VITE_INTERNAL_DIRNAME, "wevu-layouts.d.ts");
}
//#endregion
//#region src/utils/path.ts
const BACKSLASH_RE = /\\/g;
const LEADING_SLASH_RE$3 = /^[\\/]+/;
const DUPLICATE_SLASH_RE = /\/{2,}/g;
const TRIM_SLASH_RE = /^\/+|\/+$/g;
const WINDOWS_DEVICE_RE = /^\\\\\?\\/;
const WINDOWS_UNC_PREFIX = /^\\\\\?\\UNC\\/;
function stripWindowsDevicePath(value) {
	if (WINDOWS_UNC_PREFIX.test(value)) return `\\\\${value.slice(8)}`;
	if (WINDOWS_DEVICE_RE.test(value)) return value.slice(4);
	return value;
}
function toPosixPath(value) {
	return value.replace(BACKSLASH_RE, "/");
}
function normalizePath$1(value) {
	if (!value) return value;
	const cleaned = stripWindowsDevicePath(value);
	return toPosixPath(path.normalize(cleaned));
}
function normalizeRelativePath$1(value) {
	if (value === "") return value;
	return normalizePath$1(value);
}
function normalizeWatchPath(value) {
	if (!value) return value;
	const posix = toPosixPath(stripWindowsDevicePath(value));
	return toPosixPath(normalize(posix));
}
function stripLeadingSlashes(value) {
	return value.replace(LEADING_SLASH_RE$3, "");
}
function normalizeRoot(root) {
	return toPosixPath(root).replace(DUPLICATE_SLASH_RE, "/").replace(TRIM_SLASH_RE, "");
}
function isPathInside(parent, target) {
	if (!parent) return false;
	const relative = path.relative(parent, target);
	return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
}
//#endregion
//#region src/runtime/autoImport/config/merge.ts
function cloneAutoImportComponents(config) {
	if (config === false || !config) return;
	if (config === true) return {};
	const cloned = {};
	if (Array.isArray(config.globs)) cloned.globs = [...config.globs];
	if (Array.isArray(config.resolvers)) cloned.resolvers = [...config.resolvers];
	if (config.output !== void 0) cloned.output = config.output;
	if (config.typedComponents !== void 0) cloned.typedComponents = config.typedComponents;
	if (config.htmlCustomData !== void 0) cloned.htmlCustomData = config.htmlCustomData;
	if (config.vueComponents !== void 0) cloned.vueComponents = config.vueComponents;
	if (config.vueComponentsModule !== void 0) cloned.vueComponentsModule = config.vueComponentsModule;
	return cloned;
}
function mergeGlobs(base, extra) {
	const values = [...base ?? [], ...extra ?? []].map((entry) => entry?.trim()).filter((entry) => Boolean(entry));
	if (!values.length) return;
	const deduped = [];
	const seen = /* @__PURE__ */ new Set();
	for (const entry of values) {
		if (seen.has(entry)) continue;
		seen.add(entry);
		deduped.push(entry);
	}
	return deduped;
}
function normalizeGlobs(globs) {
	if (!Array.isArray(globs)) return;
	return mergeGlobs(void 0, globs) ?? [];
}
function mergeResolvers(base, extra) {
	const merged = [...base ?? [], ...extra ?? []].filter(Boolean);
	return merged.length ? merged : void 0;
}
function mergeAutoImportComponents(lower, upper, preferUpperScalars = false) {
	if (!lower && !upper) return;
	if (!lower) return cloneAutoImportComponents(upper);
	if (!upper) return cloneAutoImportComponents(lower);
	const merged = {};
	const globs = preferUpperScalars && Array.isArray(upper.globs) ? normalizeGlobs(upper.globs) : mergeGlobs(lower.globs, upper.globs);
	if (globs !== void 0) merged.globs = globs;
	const resolvers = mergeResolvers(lower.resolvers, upper.resolvers);
	if (resolvers) merged.resolvers = resolvers;
	const pickScalar = (baseline, candidate) => {
		return preferUpperScalars ? candidate ?? baseline : baseline ?? candidate;
	};
	const output = pickScalar(lower.output, upper.output);
	if (output !== void 0) merged.output = output;
	const typedComponents = pickScalar(lower.typedComponents, upper.typedComponents);
	if (typedComponents !== void 0) merged.typedComponents = typedComponents;
	const htmlCustomData = pickScalar(lower.htmlCustomData, upper.htmlCustomData);
	if (htmlCustomData !== void 0) merged.htmlCustomData = htmlCustomData;
	const vueComponents = pickScalar(lower.vueComponents, upper.vueComponents);
	if (vueComponents !== void 0) merged.vueComponents = vueComponents;
	const vueComponentsModule = pickScalar(lower.vueComponentsModule, upper.vueComponentsModule);
	if (vueComponentsModule !== void 0) merged.vueComponentsModule = vueComponentsModule;
	return merged;
}
//#endregion
//#region src/runtime/autoImport/config/defaults.ts
function addDefaultComponentGlobs(globs, configService, extension) {
	globs.add(`components/**/*.${extension}`);
	const subPackages = configService.weappViteConfig?.subPackages;
	if (!subPackages) return;
	for (const [root, subConfig] of Object.entries(subPackages)) {
		if (!root) continue;
		if (subConfig?.autoImportComponents === false) continue;
		const normalized = normalizeRoot(root);
		if (!normalized) continue;
		globs.add(`${normalized}/components/**/*.${extension}`);
	}
}
function createDefaultAutoImportComponents(configService) {
	const globs = /* @__PURE__ */ new Set();
	addDefaultComponentGlobs(globs, configService, "wxml");
	return globs.size ? { globs: [...globs] } : void 0;
}
function hasWevuDependency$2(configService) {
	const packageJson = configService.packageJson ?? {};
	return Boolean(packageJson.dependencies?.wevu || packageJson.devDependencies?.wevu || packageJson.peerDependencies?.wevu);
}
function createEnabledAutoImportComponents(configService) {
	const defaults = createDefaultAutoImportComponents(configService);
	if (!defaults) return;
	const globs = new Set(defaults.globs ?? []);
	if (hasWevuDependency$2(configService)) addDefaultComponentGlobs(globs, configService, "vue");
	return {
		...defaults,
		globs: [...globs],
		output: true,
		typedComponents: true,
		htmlCustomData: true,
		vueComponents: true,
		vueComponentsModule: hasWevuDependency$2(configService) ? "wevu" : void 0
	};
}
function getAutoImportConfig(configService) {
	if (!configService) return;
	const weappConfig = configService.weappViteConfig;
	if (!weappConfig) return;
	const userConfigured = weappConfig.autoImportComponents ?? weappConfig.enhance?.autoImportComponents;
	const enabledDefaults = createEnabledAutoImportComponents(configService);
	const hasMergeableSubPackageAutoImportConfig = Boolean(Object.values(weappConfig.subPackages ?? {}).some((subConfig) => {
		const scoped = subConfig?.autoImportComponents;
		return scoped !== void 0 && scoped !== false;
	}));
	if (userConfigured === false) return;
	const normalizedConfig = userConfigured === true ? enabledDefaults : userConfigured ? mergeAutoImportComponents(enabledDefaults, cloneAutoImportComponents(userConfigured), true) : void 0;
	const baseConfig = cloneAutoImportComponents(normalizedConfig ?? (normalizedConfig === void 0 && !hasMergeableSubPackageAutoImportConfig ? enabledDefaults : void 0));
	const subPackageConfigs = weappConfig.subPackages;
	const currentRoot = configService.currentSubPackageRoot;
	if (currentRoot) {
		const scopedRaw = subPackageConfigs?.[currentRoot]?.autoImportComponents;
		if (scopedRaw === false) return;
		const scoped = cloneAutoImportComponents(scopedRaw);
		return mergeAutoImportComponents(baseConfig, scoped, true) ?? baseConfig ?? scoped;
	}
	let merged = baseConfig;
	if (subPackageConfigs) for (const root of Object.keys(subPackageConfigs)) {
		const scopedRaw = subPackageConfigs[root]?.autoImportComponents;
		if (scopedRaw === false || !scopedRaw) continue;
		const scoped = cloneAutoImportComponents(scopedRaw);
		if (scoped) merged = mergeAutoImportComponents(merged, scoped, false);
	}
	return merged;
}
//#endregion
//#region src/runtime/autoImport/config/resolve.ts
function resolveManifestOutputPath(configService, manifestFileName = DEFAULT_AUTO_IMPORT_MANIFEST_FILENAME) {
	if (!configService) return;
	const autoImportConfig = getAutoImportConfig(configService);
	if (!autoImportConfig) return;
	const baseDir = resolveBaseDir(configService);
	const outputOption = autoImportConfig.output;
	if (outputOption === false) return;
	if (typeof outputOption === "string" && outputOption.length > 0) return path.isAbsolute(outputOption) ? outputOption : path.resolve(baseDir, outputOption);
	if (isProductionBuildWithInternalSupportFiles(configService)) return;
	return path.resolve(baseDir, WEAPP_VITE_INTERNAL_DIRNAME, manifestFileName);
}
//#endregion
//#region src/runtime/autoImport/config/settings.ts
function getTypedComponentsSettings(ctx) {
	const configService = ctx.configService;
	if (!configService) return { enabled: false };
	const option = getAutoImportConfig(configService)?.typedComponents;
	if (option === true) {
		if (isProductionBuildWithInternalSupportFiles(configService)) return { enabled: false };
		return {
			enabled: true,
			outputPath: resolveTypedComponentsDefaultPath(configService)
		};
	}
	if (typeof option === "string") {
		const trimmed = option.trim();
		if (!trimmed) return { enabled: false };
		const baseDir = resolveBaseDir(configService);
		return {
			enabled: true,
			outputPath: path.isAbsolute(trimmed) ? trimmed : path.resolve(baseDir, trimmed)
		};
	}
	return { enabled: false };
}
function getHtmlCustomDataSettings(ctx) {
	const configService = ctx.configService;
	if (!configService) return { enabled: false };
	const option = getAutoImportConfig(configService)?.htmlCustomData;
	if (option === true) {
		if (isProductionBuildWithInternalSupportFiles(configService)) return { enabled: false };
		return {
			enabled: true,
			outputPath: resolveHtmlCustomDataDefaultPath(configService)
		};
	}
	if (typeof option === "string") {
		const trimmed = option.trim();
		if (!trimmed) return { enabled: false };
		const baseDir = resolveBaseDir(configService);
		return {
			enabled: true,
			outputPath: path.isAbsolute(trimmed) ? trimmed : path.resolve(baseDir, trimmed)
		};
	}
	return { enabled: false };
}
function getVueComponentsSettings(ctx) {
	const configService = ctx.configService;
	if (!configService) return { enabled: false };
	const autoImportConfig = getAutoImportConfig(configService);
	const option = autoImportConfig?.vueComponents;
	const moduleName = autoImportConfig?.vueComponentsModule?.trim() || void 0;
	if (option === true) {
		if (isProductionBuildWithInternalSupportFiles(configService)) return { enabled: false };
		return {
			enabled: true,
			outputPath: resolveVueComponentsDefaultPath(configService),
			moduleName
		};
	}
	if (typeof option === "string") {
		const trimmed = option.trim();
		if (!trimmed) return { enabled: false };
		const baseDir = resolveBaseDir(configService);
		return {
			enabled: true,
			outputPath: path.isAbsolute(trimmed) ? trimmed : path.resolve(baseDir, trimmed),
			moduleName
		};
	}
	return { enabled: false };
}
//#endregion
//#region src/platform.ts
const DEFAULT_MP_PLATFORM = getDefaultMiniProgramPlatform();
const NPM_PROTOCOL_RE$1 = /^npm:/;
const EXPLICIT_NPM_DIR_RE$1 = /^\/(?:miniprogram_npm|node_modules)\//;
const LEADING_SLASH_RE$2 = /^\/+/;
function createMiniProgramPlatformRegistry(adapters) {
	const adapterById = /* @__PURE__ */ new Map();
	const aliasToId = /* @__PURE__ */ new Map();
	for (const adapter of adapters) {
		adapterById.set(adapter.id, adapter);
		aliasToId.set(adapter.id, adapter.id);
		for (const alias of adapter.aliases) {
			const normalized = alias.trim().toLowerCase();
			if (!normalized) continue;
			aliasToId.set(normalized, adapter.id);
		}
	}
	return {
		adapterById,
		aliasToId
	};
}
const { adapterById: PLATFORM_ADAPTER_BY_ID, aliasToId: PLATFORM_ALIAS_TO_ID } = createMiniProgramPlatformRegistry(MINI_PROGRAM_PLATFORM_ADAPTERS);
const SUPPORTED_MINI_PROGRAM_PLATFORMS = getSupportedMiniProgramPlatforms();
Object.freeze({
	...MINI_PROGRAM_PLATFORM_ALIASES,
	...Object.fromEntries(PLATFORM_ALIAS_TO_ID.entries())
});
function getSupportedMiniProgramPlatforms$1() {
	return SUPPORTED_MINI_PROGRAM_PLATFORMS;
}
function normalizeMiniPlatform(input) {
	return normalizeMiniProgramPlatform(input);
}
function resolveMiniPlatform(input) {
	const resolved = resolveMiniProgramPlatform(input);
	if (resolved) return resolved;
	const normalized = normalizeMiniPlatform(input);
	if (!normalized) return;
	return PLATFORM_ALIAS_TO_ID.get(normalized);
}
function resolveMiniPlatformWithDefault(platform) {
	return platform ?? DEFAULT_MP_PLATFORM;
}
function getMiniProgramPlatformAdapter(platform) {
	const adapter = PLATFORM_ADAPTER_BY_ID.get(platform);
	if (!adapter) throw new Error(`不支持的小程序平台 "${platform}"。`);
	return adapter;
}
function getIdePlatformOptions(platform) {
	return {
		requiresOpenPlatformArg: platform ? getMiniProgramPlatformAdapter(platform).ide?.requiresOpenPlatformArg === true : false,
		defaultProjectRoot: platform ? getMiniProgramPlatformAdapter(platform).ide?.defaultProjectRoot : void 0
	};
}
function shouldPassPlatformArgToIdeOpen(platform) {
	return getIdePlatformOptions(platform).requiresOpenPlatformArg;
}
function getDefaultIdeProjectRoot(platform) {
	return getIdePlatformOptions(platform).defaultProjectRoot;
}
function getPlatformOutputExtensions(platform) {
	return { ...getMiniProgramPlatformAdapter(platform).outputExtensions };
}
function getJsonPlatformOptions(platform) {
	const json = platform ? getMiniProgramPlatformAdapter(platform).json : void 0;
	return {
		normalizeUsingComponents: json?.normalizeUsingComponents === true,
		fillComponentGenericsDefault: json?.fillComponentGenericsDefault === true,
		rewriteBundleNpmImports: json?.rewriteBundleNpmImports === true
	};
}
function shouldNormalizeUsingComponents(platform) {
	return getJsonPlatformOptions(platform).normalizeUsingComponents;
}
function shouldFillComponentGenericsDefault(platform) {
	return getJsonPlatformOptions(platform).fillComponentGenericsDefault;
}
function shouldRewriteBundleNpmImports(platform) {
	return getJsonPlatformOptions(platform).rewriteBundleNpmImports;
}
function getNpmPlatformOptions(platform, options) {
	const npm = platform ? getMiniProgramPlatformAdapter(platform).npm : void 0;
	const adapter = platform ? getMiniProgramPlatformAdapter(platform) : void 0;
	const distDirName = npm?.distDirName?.(options) ?? "miniprogram_npm";
	return {
		distDirName,
		preservedDirNames: adapter?.resolvePreservedNpmDirNames(options) ?? ["miniprogram_npm"],
		importPrefix: `/${distDirName}/`,
		normalizeImportPath: npm?.normalizeImportPath === true,
		normalizeMiniprogramPackage: npm?.normalizeMiniprogramPackage === true,
		copyEsModuleDirectory: npm?.copyEsModuleDirectory === true,
		hoistNestedDependencies: npm?.hoistNestedDependencies === true,
		shouldRebuildCachedPackage: npm?.shouldRebuildCachedPackage === true
	};
}
function getPreservedNpmDirNames(platform, options) {
	return getNpmPlatformOptions(platform, options).preservedDirNames;
}
function getPlatformNpmDistDirName(platform, options) {
	return getNpmPlatformOptions(platform, options).distDirName;
}
function shouldNormalizePlatformNpmImportPath(platform) {
	return getNpmPlatformOptions(platform).normalizeImportPath;
}
function getPlatformNpmImportPrefix(platform, options) {
	return getNpmPlatformOptions(platform, options).importPrefix;
}
function stripExplicitNpmImportPrefix(importee) {
	return importee.replace(NPM_PROTOCOL_RE$1, "").replace(EXPLICIT_NPM_DIR_RE$1, "");
}
function normalizePlatformNpmImportPath(platform, importee, options) {
	if (!shouldNormalizePlatformNpmImportPath(platform)) return importee;
	const normalized = stripExplicitNpmImportPrefix(importee);
	return `${getPlatformNpmImportPrefix(platform, options)}${normalized.replace(LEADING_SLASH_RE$2, "")}`;
}
function shouldRebuildCachedMiniprogramPackage(platform) {
	return getNpmPlatformOptions(platform).shouldRebuildCachedPackage;
}
function shouldNormalizeMiniprogramPackage(platform) {
	return getNpmPlatformOptions(platform).normalizeMiniprogramPackage;
}
function shouldCopyEsModuleDirectory(platform) {
	return getNpmPlatformOptions(platform).copyEsModuleDirectory;
}
function shouldHoistNestedMiniprogramDependencies(platform) {
	return getNpmPlatformOptions(platform).hoistNestedDependencies;
}
function getProjectPlatformOptions(platform) {
	const adapter = getMiniProgramPlatformAdapter(platform);
	return {
		projectConfigFileName: adapter.projectConfigFileName,
		projectConfigRootKeys: adapter.projectConfigRootKeys,
		usesProjectRootNpmDir: adapter.usesProjectRootNpmDir === true
	};
}
function getScriptModulePlatformOptions(platform) {
	return { tagByExtension: platform ? getMiniProgramPlatformAdapter(platform).scriptModuleTagByExtension ?? {} : {} };
}
function getWxmlPlatformTransformOptions(platform) {
	const wxml = platform ? getMiniProgramPlatformAdapter(platform).wxml : void 0;
	return {
		eventBindingStyle: wxml?.eventBindingStyle ?? "default",
		directivePrefix: wxml?.directivePrefix ?? getMiniProgramDirectivePrefix(platform),
		normalizeComponentTagName: wxml?.normalizeComponentTagName === true,
		normalizeVueTemplate: wxml?.normalizeVueTemplate === true,
		emitGenericPlaceholder: wxml?.emitGenericPlaceholder === true
	};
}
function getWxmlDirectivePrefix(platform) {
	return getWxmlPlatformTransformOptions(platform).directivePrefix;
}
function shouldNormalizeVueTemplateForPlatform(platform) {
	return getWxmlPlatformTransformOptions(platform).normalizeVueTemplate;
}
function shouldEmitGenericPlaceholderAsset(platform) {
	return getWxmlPlatformTransformOptions(platform).emitGenericPlaceholder;
}
function getPlatformScriptModuleTag(platform, scriptModuleExtension) {
	if (!scriptModuleExtension) return;
	return getScriptModulePlatformOptions(platform).tagByExtension[scriptModuleExtension];
}
function shouldUseProjectRootNpmDir(platform) {
	return getProjectPlatformOptions(platform).usesProjectRootNpmDir;
}
function getTypeScriptPlatformOptions(platform) {
	return { appTypesPackage: platform ? getMiniProgramPlatformAdapter(platform).typescript?.appTypesPackage ?? getMiniProgramAppTypesPackage(platform) : getMiniProgramAppTypesPackage() };
}
function getPlatformAppTypesPackage(platform) {
	return getTypeScriptPlatformOptions(platform).appTypesPackage;
}
//#endregion
//#region src/utils/npmImport.ts
const WINDOWS_PATH_SEPARATORS_RE = /\\/g;
const WINDOWS_ABSOLUTE_PATH_RE$2 = /^[a-z]:[\\/]/i;
const NPM_PROTOCOL_RE = /^npm:/;
const PLUGIN_PROTOCOL_RE$1 = /^plugin:\/\//;
const EXPLICIT_NPM_DIR_RE = /^\/(?:miniprogram_npm|node_modules)\//;
const LEADING_SLASHES_RE$4 = /^\/+/;
const NODE_MODULES_SEGMENT = "/node_modules/";
const STRIP_SCRIPT_EXTENSION_RE = /\.[cm]?[jt]sx?$/;
const INFERRED_MINIPROGRAM_ROOTS = ["miniprogram_dist", "miniprogram"];
const miniprogramRootCache = /* @__PURE__ */ new Map();
const packageRootCache$1 = /* @__PURE__ */ new Map();
const resolveFromCurrentModule = createRequire(import.meta.url);
function stripScriptExtension(value) {
	return value.replace(STRIP_SCRIPT_EXTENSION_RE, "");
}
function stripInferredMiniprogramRoot(subPath) {
	for (const miniprogramRoot of INFERRED_MINIPROGRAM_ROOTS) if (subPath === miniprogramRoot || subPath.startsWith(`${miniprogramRoot}/`)) return subPath.slice(miniprogramRoot.length).replace(LEADING_SLASHES_RE$4, "");
	return subPath;
}
function readMiniprogramRoot(packageRoot) {
	const cached = miniprogramRootCache.get(packageRoot);
	if (cached !== void 0 || miniprogramRootCache.has(packageRoot)) return cached;
	const packageJsonPath = path$1.join(packageRoot, "package.json");
	if (!existsSync(packageJsonPath)) {
		miniprogramRootCache.set(packageRoot, void 0);
		return;
	}
	try {
		const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
		const miniprogramRoot = typeof packageJson.miniprogram === "string" ? packageJson.miniprogram.replace(WINDOWS_PATH_SEPARATORS_RE, "/").replace(LEADING_SLASHES_RE$4, "") : void 0;
		miniprogramRootCache.set(packageRoot, miniprogramRoot);
		return miniprogramRoot;
	} catch {
		miniprogramRootCache.set(packageRoot, void 0);
		return;
	}
}
function resolveInstalledPackageRoot(packageName, basedir) {
	const cacheKey = `${basedir}::${packageName}`;
	const cached = packageRootCache$1.get(cacheKey);
	if (cached !== void 0 || packageRootCache$1.has(cacheKey)) return cached;
	try {
		const packageJsonPath = resolveFromCurrentModule.resolve(`${packageName}/package.json`, { paths: [basedir] });
		const resolvedPackageRoot = path$1.dirname(packageJsonPath);
		packageRootCache$1.set(cacheKey, resolvedPackageRoot);
		return resolvedPackageRoot;
	} catch {
		packageRootCache$1.set(cacheKey, void 0);
		return;
	}
}
function normalizeAbsoluteNodeModulesImport(importee) {
	const nodeModulesIndex = importee.lastIndexOf(NODE_MODULES_SEGMENT);
	if (nodeModulesIndex === -1) return;
	const packageStart = nodeModulesIndex + 14;
	const packageTokens = importee.slice(packageStart).replace(LEADING_SLASHES_RE$4, "").split("/").filter(Boolean);
	if (packageTokens.length === 0) return;
	const packageTokenCount = packageTokens[0].startsWith("@") ? 2 : 1;
	if (packageTokens.length < packageTokenCount) return;
	const packageName = packageTokens.slice(0, packageTokenCount).join("/");
	const inferredPackageRoot = `${importee.slice(0, packageStart)}${packageName}`;
	const packageRoot = existsSync(path$1.join(inferredPackageRoot, "package.json")) ? inferredPackageRoot : resolveInstalledPackageRoot(packageName, path$1.dirname(importee)) ?? inferredPackageRoot;
	let subPath = packageTokens.slice(packageTokenCount).join("/");
	const miniprogramRoot = readMiniprogramRoot(packageRoot);
	if (miniprogramRoot && (subPath === miniprogramRoot || subPath.startsWith(`${miniprogramRoot}/`))) subPath = subPath.slice(miniprogramRoot.length).replace(LEADING_SLASHES_RE$4, "");
	else subPath = stripInferredMiniprogramRoot(subPath);
	const normalizedSubPath = stripScriptExtension(subPath);
	return normalizedSubPath ? `${packageName}/${normalizedSubPath}` : packageName;
}
function normalizeNpmImportLookupPath(importee) {
	const normalized = importee.replace(WINDOWS_PATH_SEPARATORS_RE, "/").replace(NPM_PROTOCOL_RE, "");
	const nodeModulesResolved = normalizeAbsoluteNodeModulesImport(normalized);
	if (nodeModulesResolved) return nodeModulesResolved;
	return normalized.replace(EXPLICIT_NPM_DIR_RE, "").replace(LEADING_SLASHES_RE$4, "");
}
function resolveNpmDependencyId(importee) {
	const normalizedImportee = normalizeNpmImportLookupPath(importee);
	const importeeTokens = normalizedImportee.split("/").filter(Boolean);
	if (importeeTokens.length === 0) return "";
	if (normalizedImportee.startsWith("@") && importeeTokens.length > 1) return `${importeeTokens[0]}/${importeeTokens[1]}`;
	return importeeTokens[0];
}
function normalizeNpmPackageSpecifier(specifier) {
	const normalized = specifier.trim();
	if (!normalized || normalized.startsWith(".") || normalized.startsWith("/") || normalized.startsWith("\\")) return;
	if (WINDOWS_ABSOLUTE_PATH_RE$2.test(normalized)) return;
	return normalized;
}
function parseNpmPackageSpecifier(specifier) {
	const normalized = normalizeNpmPackageSpecifier(specifier);
	if (!normalized) return;
	const normalizedImportee = normalizeNpmImportLookupPath(normalized);
	if (normalizedImportee.startsWith("@") && !normalizedImportee.includes("/")) return;
	const packageName = resolveNpmDependencyId(normalizedImportee);
	if (!packageName) return;
	return {
		packageName,
		subPath: normalizedImportee.slice(packageName.length).replace(LEADING_SLASHES_RE$4, "")
	};
}
function hasNpmDependencyPrefix(dependencies, importee) {
	if (!dependencies) return false;
	const importeeTokens = normalizeNpmImportLookupPath(importee).split("/").filter(Boolean);
	if (importeeTokens.length === 0) return false;
	return Object.keys(dependencies).some((dep) => {
		const depTokens = dep.replace(WINDOWS_PATH_SEPARATORS_RE, "/").split("/").filter(Boolean);
		if (depTokens.length === 0 || depTokens.length > importeeTokens.length) return false;
		for (let i = 0; i < depTokens.length; i++) if (depTokens[i] !== importeeTokens[i]) return false;
		return true;
	});
}
function shouldNormalizeNpmImportByPlatform(importee, options) {
	const trimmed = importee.trim();
	if (!trimmed || PLUGIN_PROTOCOL_RE$1.test(trimmed)) return false;
	if (!options.platform || !shouldNormalizePlatformNpmImportPath(options.platform)) return false;
	const normalized = trimmed.replace(NPM_PROTOCOL_RE, "");
	if (EXPLICIT_NPM_DIR_RE.test(normalized)) return true;
	return hasNpmDependencyPrefix(options.dependencies, normalized);
}
function normalizeNpmImportPathByPlatform(importee, options) {
	const trimmed = importee.trim();
	if (!shouldNormalizeNpmImportByPlatform(trimmed, options)) return importee;
	if (!options.platform) return importee;
	const normalized = trimmed.replace(NPM_PROTOCOL_RE, "");
	return normalizePlatformNpmImportPath(options.platform, normalized, { alipayNpmMode: options.alipayNpmMode });
}
//#endregion
//#region src/utils/json.ts
const ALIPAY_GENERIC_COMPONENT_PLACEHOLDER = "./__weapp_vite_generic_component";
const WEAPP_SCOPED_SLOT_GENERIC_COMPONENT_PLACEHOLDER = "./__weapp_vite_scoped_slot_generic_component";
const JSON_FILE_JS_EXTENSION_RE = /\.[jt]s$/;
const COMPONENT_NAME_LOWER_TO_UPPER_RE = /([a-z0-9])([A-Z])/g;
const COMPONENT_NAME_MULTI_UPPER_RE = /([A-Z]+)([A-Z][a-z])/g;
const COMPONENT_NAME_HAS_UPPER_RE = /[A-Z]/;
const SCOPED_SLOT_GENERIC_KEY_RE$1 = /^scoped-slots-/;
function parseCommentJson(json) {
	return parse(json, void 0, true);
}
function jsonFileRemoveJsExtension(fileName) {
	return fileName.replace(JSON_FILE_JS_EXTENSION_RE, "");
}
function stringifyJson$1(value, replacer) {
	return stringify(value, replacer, 2);
}
function normalizeAppJson(json) {
	if (!json || typeof json !== "object" || Array.isArray(json)) return json;
	const subPackages = Array.isArray(json.subPackages) ? json.subPackages : Array.isArray(json.subpackages) ? json.subpackages : [];
	const { subpackages: _subpackages, ...rest } = json;
	return {
		...rest,
		subPackages: subPackages.map((subPackage) => ({
			...subPackage,
			pages: Array.isArray(subPackage?.pages) ? subPackage.pages : []
		}))
	};
}
function matches(pattern, importee) {
	if (pattern instanceof RegExp) return pattern.test(importee);
	if (importee.length < pattern.length) return false;
	if (importee === pattern) return true;
	return importee.startsWith(pattern + "/");
}
function getAliasEntries(options = {}) {
	if (options === false) return [];
	const { entries } = options;
	if (!entries) return [];
	if (Array.isArray(entries)) return entries.map((entry) => {
		return {
			find: entry.find,
			replacement: entry.replacement
		};
	});
	return Object.entries(entries).map(([key, value]) => {
		return {
			find: key,
			replacement: value
		};
	});
}
function resolveImportee$1(importee, jsonPath, aliasEntries) {
	if (Array.isArray(aliasEntries)) {
		if (!jsonPath) return importee;
		const matchedEntry = aliasEntries.find((x) => matches(x.find, importee));
		if (!matchedEntry) return importee;
		const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
		return toPosixPath(path.relative(path.dirname(jsonPath), updatedId));
	}
	return importee;
}
function toKebabCaseComponentName(name) {
	return name.replace(COMPONENT_NAME_LOWER_TO_UPPER_RE, "$1-$2").replace(COMPONENT_NAME_MULTI_UPPER_RE, "$1-$2").toLowerCase();
}
function normalizeUsingComponentPathByPlatform(importee, platform, dependencies, mode) {
	if (!hasNpmDependencyPrefix(dependencies, importee) && !importee.trim().startsWith("/")) return importee;
	return normalizeNpmImportPathByPlatform(importee, {
		platform,
		dependencies,
		alipayNpmMode: mode
	});
}
function normalizeUsingComponentsByPlatform(usingComponents, platform, options) {
	if (!shouldNormalizeUsingComponents(platform)) return usingComponents;
	const normalized = {};
	for (const [key, value] of Object.entries(usingComponents)) {
		const nextKey = COMPONENT_NAME_HAS_UPPER_RE.test(key) ? toKebabCaseComponentName(key) : key;
		const nextValue = normalizeUsingComponentPathByPlatform(value, platform, options?.dependencies, options?.alipayNpmMode);
		if (!Reflect.has(normalized, nextKey)) normalized[nextKey] = nextValue;
	}
	return normalized;
}
function normalizeComponentGenericsByPlatform(componentGenerics, platform) {
	if (!shouldFillComponentGenericsDefault(platform) && platform !== "weapp") return componentGenerics;
	const normalized = {};
	for (const [key, value] of Object.entries(componentGenerics)) {
		const placeholder = platform === "weapp" ? SCOPED_SLOT_GENERIC_KEY_RE$1.test(key) ? WEAPP_SCOPED_SLOT_GENERIC_COMPONENT_PLACEHOLDER : void 0 : ALIPAY_GENERIC_COMPONENT_PLACEHOLDER;
		if (!placeholder) {
			normalized[key] = value;
			continue;
		}
		if (value === true) {
			normalized[key] = { default: placeholder };
			continue;
		}
		if (isObject(value)) {
			const nextValue = { ...value };
			if (typeof nextValue.default !== "string" || !nextValue.default.trim()) nextValue.default = placeholder;
			normalized[key] = nextValue;
			continue;
		}
		normalized[key] = value;
	}
	return normalized;
}
function resolveJson(entry, aliasEntries, platform, options) {
	if (entry.json) {
		const json = entry.type === "app" ? normalizeAppJson(structuredClone(entry.json)) : structuredClone(entry.json);
		if (entry.jsonPath && Array.isArray(aliasEntries)) {
			const usingComponents = get(json, "usingComponents");
			if (isObject(usingComponents)) {
				for (const [key, importee] of Object.entries(usingComponents)) {
					const resolvedId = resolveImportee$1(importee, entry.jsonPath, aliasEntries);
					set(json, `usingComponents.${key}`, resolvedId);
				}
				set(json, "usingComponents", normalizeUsingComponentsByPlatform(usingComponents, platform, options));
			}
			if (entry.type === "app") for (const field of ["subPackages", "subpackages"]) {
				const subPackages = get(json, field);
				if (Array.isArray(subPackages)) {
					for (const subPackage of subPackages) if (subPackage.entry) subPackage.entry = changeFileExtension(subPackage.entry, "js");
				}
			}
		} else {
			const usingComponents = get(json, "usingComponents");
			if (isObject(usingComponents)) set(json, "usingComponents", normalizeUsingComponentsByPlatform(usingComponents, platform, options));
		}
		const componentGenerics = get(json, "componentGenerics");
		if (isObject(componentGenerics)) set(json, "componentGenerics", normalizeComponentGenericsByPlatform(componentGenerics, platform));
		if (Reflect.has(json, "$schema")) delete json.$schema;
		return stringifyJson$1(json);
	}
}
//#endregion
//#region src/runtime/autoImport/service/actions.ts
function createAutoImportActions(options) {
	function bumpVersion() {
		options.autoImportState.version += 1;
	}
	async function awaitOutputWrites() {
		while (true) {
			const pending = [
				...options.pendingRegistrations,
				options.outputsState.pendingWrite,
				options.outputsState.pendingTypedWrite,
				options.outputsState.pendingHtmlCustomDataWrite,
				options.outputsState.pendingVueComponentsWrite
			].filter((task) => Boolean(task));
			if (!pending.length) return;
			await Promise.all(pending);
		}
	}
	function setSupportFileResolverComponents(components) {
		if (!options.resolverHelpers.setSupportFileResolverComponents(components)) return;
		bumpVersion();
		options.deferOrSchedule("manifest", true);
		const { typed, html, vue } = options.getOutputSettingsSnapshot();
		if (typed.enabled || html.enabled) options.resolverHelpers.syncResolverComponentProps();
		if (typed.enabled) options.deferOrSchedule("typed", true);
		if (html.enabled) options.deferOrSchedule("html", true);
		if (vue.enabled) {
			options.resolverHelpers.syncResolverComponentProps();
			options.deferOrSchedule("vue", true);
		}
	}
	function clearSupportFileResolverComponents() {
		if (!options.resolverHelpers.clearSupportFileResolverComponents()) return;
		bumpVersion();
		options.resolverHelpers.syncResolverComponentProps();
	}
	return {
		reset() {
			bumpVersion();
			options.registry.clear();
			options.normalizedLocalComponents.clear();
			options.autoImportState.matcher = void 0;
			options.autoImportState.matcherKey = "";
			options.autoImportState.preparedGlobsKey = void 0;
			options.resolvedResolverComponents.clear();
			options.resolverHelpers.clearResolveCache();
			options.deferOrSchedule("manifest", true);
			options.componentMetadataMap.clear();
			options.resolverComponentNames.clear();
			const { typed, html, vue } = options.getOutputSettingsSnapshot();
			if (typed.enabled || html.enabled) options.resolverHelpers.syncResolverComponentProps();
			options.deferOrSchedule("typed", true);
			options.deferOrSchedule("html", true);
			if (vue.enabled) options.resolverHelpers.syncResolverComponentProps();
			options.deferOrSchedule("vue", true);
		},
		async registerPotentialComponent(filePath) {
			const task = Promise.resolve().then(async () => {
				await options.registryHelpers.registerLocalComponent(filePath);
			}).finally(() => {
				options.pendingRegistrations.delete(task);
			});
			options.pendingRegistrations.add(task);
			await task;
		},
		removePotentialComponent(filePath) {
			bumpVersion();
			const { removed, removedNames } = options.registryHelpers.removeRegisteredComponent({
				baseName: removeExtensionDeep(filePath),
				templatePath: filePath
			});
			options.deferOrSchedule("manifest", removed);
			for (const name of removedNames) if (options.resolverComponentNames.has(name)) options.componentMetadataMap.set(name, {
				types: /* @__PURE__ */ new Map(),
				docs: /* @__PURE__ */ new Map()
			});
			else options.componentMetadataMap.delete(name);
			const shouldWriteArtifacts = removed || removedNames.length > 0;
			options.deferOrSchedule("typed", shouldWriteArtifacts);
			options.deferOrSchedule("html", shouldWriteArtifacts);
			options.deferOrSchedule("vue", shouldWriteArtifacts);
		},
		setSupportFileResolverComponents,
		clearSupportFileResolverComponents,
		async syncSupportFileResolverComponents() {
			try {
				setSupportFileResolverComponents(options.resolverHelpers.collectStaticResolverComponentsForSupportFiles());
				await awaitOutputWrites();
			} finally {
				clearSupportFileResolverComponents();
			}
		},
		collectStaticResolverComponentsForSupportFiles() {
			return options.resolverHelpers.collectStaticResolverComponentsForSupportFiles();
		},
		resolve(componentName, importerBaseName) {
			const local = options.registry.get(componentName) ?? options.normalizedLocalComponents.get(toKebabCaseComponentName(componentName));
			if (local) return local;
			const resolvedValue = options.resolverHelpers.resolveWithResolvers(componentName, importerBaseName);
			if (!resolvedValue) return;
			const resolverChanged = options.resolvedResolverComponents.get(resolvedValue.name) !== resolvedValue.from;
			options.resolvedResolverComponents.set(resolvedValue.name, resolvedValue.from);
			if (resolverChanged) bumpVersion();
			const resolved = {
				kind: "resolver",
				value: resolvedValue
			};
			const { typed, html, vue } = options.getOutputSettingsSnapshot();
			if (typed.enabled || html.enabled) {
				const metadataMissing = !options.componentMetadataMap.has(resolved.value.name);
				if (metadataMissing) options.componentMetadataMap.set(resolved.value.name, {
					types: /* @__PURE__ */ new Map(),
					docs: /* @__PURE__ */ new Map()
				});
				if (typed.enabled && (resolverChanged || metadataMissing)) options.deferOrSchedule("typed", true);
				if (html.enabled && (resolverChanged || metadataMissing)) options.deferOrSchedule("html", true);
			} else options.componentMetadataMap.delete(resolved.value.name);
			if (vue.enabled && resolverChanged) options.deferOrSchedule("vue", true);
			if (resolverChanged) options.deferOrSchedule("manifest", true);
			return resolved;
		},
		filter(id) {
			const globMatcher = options.registryHelpers.ensureMatcher();
			if (!globMatcher) return false;
			return globMatcher(id);
		},
		getRegisteredLocalComponents() {
			return Array.from(options.registry.values());
		},
		hasPendingRegistrations() {
			return options.pendingRegistrations.size > 0;
		},
		awaitPendingRegistrations() {
			return Promise.all([...options.pendingRegistrations]).then(() => {});
		},
		awaitManifestWrites() {
			return awaitOutputWrites();
		}
	};
}
//#endregion
//#region src/ast/index.ts
/**
* 解析 AST 引擎配置。
*/
function resolveAstEngine(config) {
	return config?.ast?.engine ?? "babel";
}
//#endregion
//#region src/context/shared.ts
const debug$2 = createDebugger("weapp-vite:context");
function hasOwn$6(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
function resolvedComponentName(entry) {
	const base = path.basename(entry);
	if (base === "index") {
		const dirName = path.dirname(entry);
		if (dirName === ".") return { base };
		return {
			componentName: path.basename(dirName),
			base
		};
	}
	return {
		componentName: base,
		base
	};
}
function isEmptyObject$1(obj) {
	for (const key in obj) if (hasOwn$6(obj, key)) return false;
	return true;
}
//#endregion
//#region src/runtime/componentProps.ts
/**
* 提取组件 `properties/props` 的静态类型信息。
*/
function extractComponentProps(code, options) {
	return collectComponentPropsFromCode(code, options);
}
//#endregion
//#region src/runtime/utils/object.ts
function hasOwn$5(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
//#endregion
//#region src/runtime/utils/constructorType.ts
const CONSTRUCTOR_TYPE_MAP = {
	String: "string",
	StringConstructor: "string",
	Number: "number",
	NumberConstructor: "number",
	Boolean: "boolean",
	BooleanConstructor: "boolean",
	Object: "Record<string, any>",
	ObjectConstructor: "Record<string, any>",
	Array: "any[]",
	ArrayConstructor: "any[]",
	null: "any",
	Null: "any",
	NullConstructor: "any"
};
function mapConstructorName(name) {
	if (hasOwn$5(CONSTRUCTOR_TYPE_MAP, name)) return CONSTRUCTOR_TYPE_MAP[name];
	const normalized = name.endsWith("Constructor") ? name.slice(0, -11) : name;
	return CONSTRUCTOR_TYPE_MAP[normalized] ?? "any";
}
//#endregion
//#region src/runtime/autoImport/dtsProps.ts
function getNodeText(node) {
	return generate$1(node, {
		comments: false,
		concise: true
	}).code.trim();
}
function getPropertyName$1(name) {
	if (name.type === "Identifier") return name.name;
	if (name.type === "StringLiteral") return name.value;
	if (name.type === "NumericLiteral") return String(name.value);
	return getNodeText(name);
}
function unwrapTypeAnnotation(annotation) {
	if (!annotation) return;
	if ("typeAnnotation" in annotation) return annotation.typeAnnotation;
}
function containsImportType(node) {
	let has = false;
	const VISITOR_KEYS = getVisitorKeys();
	const visit = (current) => {
		if (has) return;
		if (!current) return;
		if (Array.isArray(current)) {
			for (const item of current) {
				visit(item);
				if (has) return;
			}
			return;
		}
		if (typeof current.type !== "string") return;
		if (current.type === "TSImportType") {
			has = true;
			return;
		}
		const keys = VISITOR_KEYS[current.type];
		if (!keys) return;
		for (const key of keys) {
			visit(current[key]);
			if (has) return;
		}
	};
	visit(node);
	return has;
}
function mapConstructorType(node) {
	if (!node) return;
	if (node.type === "TSTypeReference") {
		if (node.typeName.type === "Identifier") return mapConstructorName(node.typeName.name);
		return mapConstructorName(getNodeText(node.typeName));
	}
	if (node.type === "TSUnionType") {
		const items = node.types.map((item) => mapConstructorType(item)).filter((value) => Boolean(value));
		return items.length ? [...new Set(items)].join(" | ") : void 0;
	}
	if (node.type === "TSNullKeyword") return "any";
	return mapConstructorName(getNodeText(node));
}
function resolveTypeFromConfigLiteral(configType) {
	if (!configType || configType.type !== "TSTypeLiteral") return;
	let valueType;
	let constructorType;
	for (const member of configType.members) {
		if (member.type !== "TSPropertySignature") continue;
		const key = getPropertyName$1(member.key);
		const type = unwrapTypeAnnotation(member.typeAnnotation);
		if (key === "value" && type && !containsImportType(type)) valueType = getNodeText(type);
		else if (key === "type") constructorType = mapConstructorType(type);
	}
	return valueType ?? constructorType;
}
function isPropsConfigLiteral(configType) {
	for (const member of configType.members) {
		if (member.type !== "TSPropertySignature") continue;
		const key = getPropertyName$1(member.key);
		if (key === "type" || key === "value") return true;
	}
	return false;
}
function extractFromPropertiesTypeLiteral(node) {
	const map = /* @__PURE__ */ new Map();
	for (const member of node.members) {
		if (member.type !== "TSPropertySignature") continue;
		const propName = getPropertyName$1(member.key);
		if (!propName) continue;
		const type = resolveTypeFromConfigLiteral(unwrapTypeAnnotation(member.typeAnnotation)) ?? "any";
		map.set(propName, type);
	}
	return map;
}
function extractFromPropsInterfaceMembers(node) {
	const map = /* @__PURE__ */ new Map();
	for (const member of node.body.body) {
		if (member.type !== "TSPropertySignature") continue;
		const propName = getPropertyName$1(member.key);
		if (!propName) continue;
		const typeNode = unwrapTypeAnnotation(member.typeAnnotation);
		if (!typeNode || typeNode.type !== "TSTypeLiteral") continue;
		if (!isPropsConfigLiteral(typeNode)) continue;
		const type = resolveTypeFromConfigLiteral(typeNode) ?? "any";
		map.set(propName, type);
	}
	return map;
}
function extractComponentPropsFromDts(code) {
	let props = /* @__PURE__ */ new Map();
	const ast = parse$3(code, {
		...BABEL_TS_MODULE_PARSER_OPTIONS$1,
		errorRecovery: true
	});
	traverse(ast, {
		TSInterfaceDeclaration(path) {
			if (props.size > 0) {
				path.stop();
				return;
			}
			for (const member of path.node.body.body) {
				if (member.type !== "TSPropertySignature") continue;
				if (getPropertyName$1(member.key) !== "properties") continue;
				const typeNode = unwrapTypeAnnotation(member.typeAnnotation);
				if (typeNode?.type === "TSTypeLiteral") {
					props = extractFromPropertiesTypeLiteral(typeNode);
					path.stop();
					return;
				}
			}
			const extracted = extractFromPropsInterfaceMembers(path.node);
			if (extracted.size > 0) {
				props = extracted;
				path.stop();
			}
		},
		ClassDeclaration(path) {
			if (props.size > 0) {
				path.stop();
				return;
			}
			for (const member of path.node.body.body) {
				if (member.type !== "ClassProperty" && member.type !== "ClassAccessorProperty") continue;
				if (getPropertyName$1(member.key) !== "properties") continue;
				const typeNode = unwrapTypeAnnotation(member.typeAnnotation);
				if (typeNode?.type === "TSTypeLiteral") {
					props = extractFromPropertiesTypeLiteral(typeNode);
					path.stop();
					return;
				}
			}
		}
	});
	return props;
}
function extractInlinePropsTypeFromCode(code) {
	const props = /* @__PURE__ */ new Map();
	const ast = parse$3(code, {
		...BABEL_TS_MODULE_PARSER_OPTIONS$1,
		errorRecovery: true
	});
	const typeAliases = /* @__PURE__ */ new Map();
	const interfaces = /* @__PURE__ */ new Map();
	traverse(ast, {
		TSTypeAliasDeclaration(path) {
			typeAliases.set(path.node.id.name, path.node.typeAnnotation);
		},
		TSInterfaceDeclaration(path) {
			interfaces.set(path.node.id.name, path.node);
		}
	});
	const pushTypeLiteralMembers = (node) => {
		for (const member of node.members) {
			if (member.type !== "TSPropertySignature") continue;
			const propName = getPropertyName$1(member.key);
			if (!propName) continue;
			const typeNode = unwrapTypeAnnotation(member.typeAnnotation);
			props.set(propName, typeNode ? getNodeText(typeNode) : "any");
		}
	};
	const pushInterfaceMembers = (node) => {
		for (const member of node.body.body) {
			if (member.type !== "TSPropertySignature") continue;
			const propName = getPropertyName$1(member.key);
			if (!propName) continue;
			const typeNode = unwrapTypeAnnotation(member.typeAnnotation);
			props.set(propName, typeNode ? getNodeText(typeNode) : "any");
		}
	};
	traverse(ast, { CallExpression(path) {
		if (!path.node.callee || path.node.callee.type !== "Identifier" || path.node.callee.name !== "defineProps") return;
		const typeParameter = (path.node.typeParameters ?? path.node.typeArguments)?.params?.[0];
		if (!typeParameter) return;
		if (typeParameter.type === "TSTypeLiteral") {
			pushTypeLiteralMembers(typeParameter);
			path.stop();
			return;
		}
		if (typeParameter.type === "TSTypeReference" && typeParameter.typeName.type === "Identifier") {
			const alias = typeAliases.get(typeParameter.typeName.name);
			if (alias?.type === "TSTypeLiteral") {
				pushTypeLiteralMembers(alias);
				path.stop();
				return;
			}
			const iface = interfaces.get(typeParameter.typeName.name);
			if (iface) {
				pushInterfaceMembers(iface);
				path.stop();
			}
		}
	} });
	return props;
}
//#endregion
//#region src/runtime/autoImport/externalMetadata.ts
const metadataCache = /* @__PURE__ */ new WeakMap();
const fallbackMetadataCache = /* @__PURE__ */ new Map();
const requireCache = /* @__PURE__ */ new Map();
const packageRootCache = /* @__PURE__ */ new Map();
const metadataRootExistsCache = /* @__PURE__ */ new Map();
function getMetadataCache(resolvers) {
	if (!resolvers) return fallbackMetadataCache;
	let cache = metadataCache.get(resolvers);
	if (!cache) {
		cache = /* @__PURE__ */ new Map();
		metadataCache.set(resolvers, cache);
	}
	return cache;
}
function safeCreateRequire(cwd) {
	const cacheKey = path.resolve(cwd);
	const cached = requireCache.get(cacheKey);
	if (cached) return cached;
	try {
		const require = createRequire(path.join(cacheKey, "package.json"));
		requireCache.set(cacheKey, require);
		return require;
	} catch {
		const require = createRequire(import.meta.url);
		requireCache.set(cacheKey, require);
		return require;
	}
}
function tryResolvePackageRoot(packageName, cwd) {
	const cacheKey = `${path.resolve(cwd)}\n${packageName}`;
	const cached = packageRootCache.get(cacheKey);
	if (cached) return cached;
	const require = safeCreateRequire(cwd);
	try {
		const pkgJson = require.resolve(`${packageName}/package.json`);
		const packageRoot = path.dirname(pkgJson);
		packageRootCache.set(cacheKey, packageRoot);
		return packageRoot;
	} catch {
		return;
	}
}
function readTextIfExists(filePath) {
	try {
		return fs$1.readFileSync(filePath, "utf8");
	} catch {
		return;
	}
}
function resolveExternalMetadataCandidates(from, resolvers) {
	if (!Array.isArray(resolvers) || resolvers.length === 0) return;
	for (const resolver of resolvers) {
		const fn = resolver?.resolveExternalMetadataCandidates;
		if (typeof fn !== "function") continue;
		const candidates = fn(from);
		if (candidates) return candidates;
	}
}
function resolveHeuristicExternalMetadataCandidates(from) {
	const parsed = parseNpmPackageSpecifier(from);
	if (!parsed?.packageName) return;
	const { packageName, subPath } = parsed;
	if (!subPath) return;
	return {
		packageName,
		dts: [
			`lib/${subPath}/index.d.ts`,
			`dist/${subPath}/index.d.ts`,
			`esm/${subPath}/index.d.ts`,
			`miniprogram_dist/${subPath}.d.ts`,
			`${subPath}.d.ts`,
			`${subPath}/index.d.ts`
		],
		js: [
			`lib/${subPath}/index.js`,
			`dist/${subPath}/index.js`,
			`esm/${subPath}/index.js`,
			`miniprogram_dist/${subPath}.js`,
			`${subPath}.js`,
			`${subPath}.cjs`,
			`${subPath}.mjs`,
			`${subPath}/index.js`,
			`${subPath}/index.cjs`,
			`${subPath}/index.mjs`
		]
	};
}
function getMetadataRootSegment(relativeFile) {
	const [segment] = relativeFile.split("/").filter(Boolean);
	if (!segment || path.extname(segment)) return;
	return segment;
}
function pathExistsCached(filePath) {
	const cached = metadataRootExistsCache.get(filePath);
	if (cached !== void 0) return cached;
	const exists = fs$1.pathExistsSync(filePath);
	metadataRootExistsCache.set(filePath, exists);
	return exists;
}
function filterMetadataCandidatesByExistingRoots(pkgRoot, from, files) {
	const subPathRoot = parseNpmPackageSpecifier(from)?.subPath?.split("/").filter(Boolean)[0];
	return files.filter((file) => {
		const segment = getMetadataRootSegment(file);
		if (!segment || segment === subPathRoot) return true;
		return pathExistsCached(path.join(pkgRoot, segment));
	});
}
function resolveResolverMetadataFiles(from, cwd, resolvers) {
	const candidates = resolveExternalMetadataCandidates(from, resolvers) ?? resolveHeuristicExternalMetadataCandidates(from);
	if (!candidates) return;
	const pkgRoot = tryResolvePackageRoot(candidates.packageName, cwd);
	if (!pkgRoot) return;
	return {
		dts: filterMetadataCandidatesByExistingRoots(pkgRoot, from, candidates.dts).map((file) => path.join(pkgRoot, file)),
		js: filterMetadataCandidatesByExistingRoots(pkgRoot, from, candidates.js).map((file) => path.join(pkgRoot, file))
	};
}
function resolveGenericMetadataFiles(from, cwd) {
	if (!from || from.startsWith("/")) return;
	const require = safeCreateRequire(cwd);
	try {
		const resolved = require.resolve(from);
		const ext = path.extname(resolved);
		const base = ext ? resolved.slice(0, -ext.length) : resolved;
		return {
			dts: [`${base}.d.ts`],
			js: [
				`${base}.js`,
				`${base}.cjs`,
				`${base}.mjs`
			]
		};
	} catch {
		return;
	}
}
function resolveExternalMetadataFiles(from, cwd, resolvers) {
	return resolveResolverMetadataFiles(from, cwd, resolvers) ?? resolveGenericMetadataFiles(from, cwd);
}
function loadExternalComponentMetadata(from, cwd, resolvers, options) {
	const cache = getMetadataCache(resolvers);
	const cacheKey = `${options?.astEngine ?? "babel"}\n${cwd}\n${from}`;
	const cached = cache.get(cacheKey);
	if (cached !== void 0) return cached ?? void 0;
	const files = resolveExternalMetadataFiles(from, cwd, resolvers);
	if (!files) {
		cache.set(cacheKey, null);
		return;
	}
	for (const candidate of files.dts) {
		const code = readTextIfExists(candidate);
		if (!code) continue;
		try {
			const types = extractComponentPropsFromDts(code);
			if (types.size > 0) {
				const result = { types };
				cache.set(cacheKey, result);
				return result;
			}
		} catch {}
	}
	for (const candidate of files.js) {
		const code = readTextIfExists(candidate);
		if (!code) continue;
		try {
			const types = extractComponentProps(code, { astEngine: options?.astEngine });
			if (types.size > 0) {
				const result = { types };
				cache.set(cacheKey, result);
				return result;
			}
		} catch {}
	}
	cache.set(cacheKey, null);
}
//#endregion
//#region src/runtime/autoImport/metadata.ts
const JSON_TYPE_ALIASES = {
	String: "string",
	Number: "number",
	Boolean: "boolean",
	Object: "Record<string, any>",
	Array: "any[]",
	Null: "null",
	Any: "any"
};
function mergeTypeCandidates(candidates) {
	const merged = candidates.filter((item) => Boolean(item)).flatMap((item) => item.split("|").map((part) => part.trim()).filter(Boolean));
	if (merged.length === 0) return;
	return Array.from(new Set(merged)).join(" | ");
}
function normalizeJsonPropertyType(raw) {
	if (typeof raw === "string") {
		const key = raw.trim();
		return JSON_TYPE_ALIASES[key] ?? key;
	}
	if (Array.isArray(raw)) {
		const normalized = raw.map((item) => normalizeJsonPropertyType(item)).filter((item) => Boolean(item));
		return normalized.length > 0 ? normalized.join(" | ") : void 0;
	}
	if (raw && typeof raw === "object") return mergeTypeCandidates([raw.type !== void 0 ? normalizeJsonPropertyType(raw.type) : void 0, Array.isArray(raw.optionalTypes) ? normalizeJsonPropertyType(raw.optionalTypes) : void 0]);
}
function extractJsonPropMetadata(json) {
	const props = /* @__PURE__ */ new Map();
	const docs = /* @__PURE__ */ new Map();
	if (!json || typeof json !== "object") return {
		props,
		docs
	};
	const properties = json.properties;
	if (!properties || typeof properties !== "object") return {
		props,
		docs
	};
	for (const [propName, rawConfig] of Object.entries(properties)) {
		const config = rawConfig ?? {};
		const type = normalizeJsonPropertyType(rawConfig) ?? "any";
		props.set(propName, type);
		const description = config.description;
		if (typeof description === "string" && description.trim().length > 0) docs.set(propName, description.trim());
	}
	return {
		props,
		docs
	};
}
function mergePropMaps(base, override) {
	const next = new Map(base);
	for (const [key, value] of override.entries()) next.set(key, value);
	return next;
}
//#endregion
//#region src/runtime/autoImport/service/metadata.ts
const LEADING_SLASH_RE$1 = /^\//;
function createMetadataHelpers(state) {
	function getComponentMetadata(name) {
		if (state.resolverComponentNames.has(name)) {
			const configService = state.ctx.configService;
			const existing = state.componentMetadataMap.get(name);
			if (existing && existing.types.size > 0) return {
				types: new Map(existing.types),
				docs: new Map(existing.docs)
			};
			const from = state.resolverComponentsMapRef.value[name];
			const cwd = configService?.cwd;
			if (from && cwd) try {
				const resolvers = getAutoImportConfig(configService)?.resolvers;
				const loaded = loadExternalComponentMetadata(from, cwd, resolvers, { astEngine: resolveAstEngine(configService.weappViteConfig) });
				if (loaded?.types?.size) {
					state.componentMetadataMap.set(name, {
						types: new Map(loaded.types),
						docs: /* @__PURE__ */ new Map()
					});
					return {
						types: new Map(loaded.types),
						docs: /* @__PURE__ */ new Map()
					};
				}
			} catch {}
		}
		const existing = state.componentMetadataMap.get(name);
		if (existing) return {
			types: new Map(existing.types),
			docs: new Map(existing.docs)
		};
		const record = state.registry.get(name);
		if (record && record.kind === "local") {
			let metadata = extractJsonPropMetadata(record.entry.json);
			const candidatePaths = /* @__PURE__ */ new Set();
			if (record.entry.jsonPath) candidatePaths.add(record.entry.jsonPath);
			const configService = state.ctx.configService;
			if (configService) {
				const from = record.value.from?.replace(LEADING_SLASH_RE$1, "");
				if (from) candidatePaths.add(path.resolve(configService.absoluteSrcRoot, `${from}.json`));
				const manifestFrom = state.manifestCache.get(name)?.replace(LEADING_SLASH_RE$1, "");
				if (manifestFrom) candidatePaths.add(path.resolve(configService.absoluteSrcRoot, `${manifestFrom}.json`));
			}
			if (metadata.props.size === 0 && metadata.docs.size === 0 && candidatePaths.size > 0) for (const candidate of candidatePaths) try {
				metadata = extractJsonPropMetadata(fs$1.readJsonSync(candidate));
				if (metadata.props.size > 0 || metadata.docs.size > 0) {
					logger_default.debug?.(`[auto-import] loaded metadata for ${name} from ${candidate}`);
					break;
				}
			} catch {}
			logger_default.debug?.(`[auto-import] metadata for ${name}: props=${metadata.props.size} docs=${metadata.docs.size}`);
			return {
				types: new Map(metadata.props),
				docs: new Map(metadata.docs)
			};
		}
		return {
			types: /* @__PURE__ */ new Map(),
			docs: /* @__PURE__ */ new Map()
		};
	}
	function preloadResolverComponentMetadata() {
		const configService = state.ctx.configService;
		const cwd = configService?.cwd;
		if (!configService || !cwd) return;
		const resolvers = getAutoImportConfig(configService)?.resolvers;
		const resolverEntries = state.collectResolverComponents();
		if (!resolverEntries || Object.keys(resolverEntries).length === 0) return;
		for (const [name, from] of Object.entries(resolverEntries)) {
			if (!from) continue;
			const existing = state.componentMetadataMap.get(name);
			if (existing && existing.types.size > 0) continue;
			try {
				const loaded = loadExternalComponentMetadata(from, cwd, resolvers, { astEngine: resolveAstEngine(configService.weappViteConfig) });
				if (loaded?.types?.size) state.componentMetadataMap.set(name, {
					types: new Map(loaded.types),
					docs: /* @__PURE__ */ new Map()
				});
			} catch {}
		}
	}
	return {
		getComponentMetadata,
		preloadResolverComponentMetadata
	};
}
//#endregion
//#region src/runtime/autoImport/service/outputs/manifest.ts
function collectAllComponentNames(options) {
	const { collectResolverComponents, registry, componentMetadataMap, manifestCache } = options;
	const resolverEntries = collectResolverComponents();
	const names = /* @__PURE__ */ new Set([...Object.keys(resolverEntries)]);
	for (const key of registry.keys()) names.add(key);
	for (const key of componentMetadataMap.keys()) names.add(key);
	for (const key of manifestCache.keys()) names.add(key);
	return Array.from(names).sort((a, b) => a.localeCompare(b));
}
async function writeManifestFile(options) {
	const { outputPath, collectManifestResolverComponents, registry, manifestCache, scheduleHtmlCustomDataWrite } = options;
	const resolverEntries = Object.entries(collectManifestResolverComponents());
	const localEntries = Array.from(registry.entries()).filter((entry) => entry[1].kind === "local");
	const manifestMap = /* @__PURE__ */ new Map();
	for (const [componentName, from] of resolverEntries) manifestMap.set(componentName, from);
	for (const [componentName, match] of localEntries) manifestMap.set(componentName, match.value.from);
	const manifest = Object.fromEntries(Array.from(manifestMap.entries()).sort(([a], [b]) => a.localeCompare(b)));
	if (manifestCache.size === manifestMap.size && Array.from(manifestMap.entries()).every(([componentName, fromPath]) => manifestCache.get(componentName) === fromPath)) return;
	manifestCache.clear();
	for (const [componentName, fromPath] of manifestMap.entries()) manifestCache.set(componentName, fromPath);
	await fs$1.outputJson(outputPath, manifest, { spaces: 2 });
	scheduleHtmlCustomDataWrite(true);
}
//#endregion
//#region src/runtime/autoImport/service/outputs/schedule.ts
function createScheduleHelpers(options) {
	const { ctx, outputsState, manifestFileName, writeManifest, syncTyped, syncHtmlCustomData: syncHtml, syncVueComponents: syncVue } = options;
	function scheduleHtmlCustomDataWrite(shouldWrite) {
		const settings = getHtmlCustomDataSettings(ctx);
		const configChanged = settings.enabled !== outputsState.lastHtmlCustomDataEnabled || settings.outputPath !== outputsState.lastHtmlCustomDataOutput;
		if (!shouldWrite && !configChanged && !outputsState.lastHtmlCustomDataOutputPath) return;
		outputsState.htmlCustomDataWriteRequested = true;
		if (outputsState.pendingHtmlCustomDataWrite) return;
		outputsState.pendingHtmlCustomDataWrite = Promise.resolve().then(async () => {
			while (outputsState.htmlCustomDataWriteRequested) {
				outputsState.htmlCustomDataWriteRequested = false;
				const currentSettings = getHtmlCustomDataSettings(ctx);
				await syncHtml(currentSettings);
				outputsState.lastHtmlCustomDataEnabled = currentSettings.enabled;
				outputsState.lastHtmlCustomDataOutput = currentSettings.outputPath;
			}
		}).finally(() => {
			outputsState.pendingHtmlCustomDataWrite = void 0;
		});
	}
	async function scheduleManifestWrite(shouldWrite) {
		if (!shouldWrite) return;
		const configService = ctx.configService;
		if (!getAutoImportConfig(configService)) return;
		outputsState.writeRequested = true;
		if (outputsState.pendingWrite) return;
		outputsState.pendingWrite = Promise.resolve().then(async () => {
			while (outputsState.writeRequested) {
				outputsState.writeRequested = false;
				const outputPath = resolveManifestOutputPath(ctx.configService, manifestFileName);
				if (!outputPath) return;
				try {
					await writeManifest(outputPath);
				} catch (error) {
					const message = error instanceof Error ? error.message : String(error);
					logger_default.error(`自动导出组件清单失败: ${message}`);
				}
			}
		}).finally(() => {
			outputsState.pendingWrite = void 0;
		});
	}
	function scheduleTypedComponentsWrite(shouldWrite) {
		const settings = getTypedComponentsSettings(ctx);
		const configChanged = settings.enabled !== outputsState.lastTypedComponentsEnabled || settings.outputPath !== outputsState.lastTypedComponentsOutput;
		if (!shouldWrite && !configChanged && !outputsState.lastTypedDefinitionOutputPath) return;
		outputsState.typedWriteRequested = true;
		if (outputsState.pendingTypedWrite) return;
		outputsState.pendingTypedWrite = Promise.resolve().then(async () => {
			while (outputsState.typedWriteRequested) {
				outputsState.typedWriteRequested = false;
				const currentSettings = getTypedComponentsSettings(ctx);
				await syncTyped(currentSettings);
				outputsState.lastTypedComponentsEnabled = currentSettings.enabled;
				outputsState.lastTypedComponentsOutput = currentSettings.outputPath;
			}
		}).finally(() => {
			outputsState.pendingTypedWrite = void 0;
		});
	}
	function scheduleVueComponentsWrite(shouldWrite) {
		const settings = getVueComponentsSettings(ctx);
		const configChanged = settings.enabled !== outputsState.lastVueComponentsEnabled || settings.outputPath !== outputsState.lastVueComponentsOutput;
		if (!shouldWrite && !configChanged && !outputsState.lastVueComponentsOutputPath) return;
		outputsState.vueComponentsWriteRequested = true;
		if (outputsState.pendingVueComponentsWrite) return;
		outputsState.pendingVueComponentsWrite = Promise.resolve().then(async () => {
			while (outputsState.vueComponentsWriteRequested) {
				outputsState.vueComponentsWriteRequested = false;
				const currentSettings = getVueComponentsSettings(ctx);
				await syncVue(currentSettings);
				outputsState.lastVueComponentsEnabled = currentSettings.enabled;
				outputsState.lastVueComponentsOutput = currentSettings.outputPath;
			}
		}).finally(() => {
			outputsState.pendingVueComponentsWrite = void 0;
		});
	}
	return {
		scheduleManifestWrite,
		scheduleTypedComponentsWrite,
		scheduleHtmlCustomDataWrite,
		scheduleVueComponentsWrite
	};
}
//#endregion
//#region src/runtime/utils/requireConfigService.ts
function requireConfigService(ctx, message) {
	const configService = ctx.configService;
	if (!configService) throw new Error(message);
	return configService;
}
//#endregion
//#region src/runtime/autoImport/htmlCustomData.ts
function createHtmlCustomDataDefinition(componentNames, getMetadata, baseTags = []) {
	const payload = {
		version: 1.1,
		tags: mergeHtmlCustomDataTags(baseTags, componentNames.map((name) => {
			const metadata = getMetadata(name);
			const combinedTypes = metadata.types;
			const docs = metadata.docs;
			const attributeNames = /* @__PURE__ */ new Set([...combinedTypes.keys(), ...docs.keys()]);
			const attributes = Array.from(attributeNames).sort((a, b) => a.localeCompare(b)).map((propName) => {
				const type = combinedTypes.get(propName);
				const doc = docs.get(propName);
				const pieces = [];
				if (type) pieces.push(`类型: ${type}`);
				if (doc) pieces.push(doc);
				const entry = { name: propName };
				if (pieces.length > 0) entry.description = pieces.join("\n");
				return entry;
			});
			const tag = {
				name,
				description: "自动导入的小程序组件"
			};
			if (attributes.length) tag.attributes = attributes;
			tag.references = [{
				name: "weapp-vite 自动导入组件",
				url: "https://vite.weapp.dev/guide/auto-import-components.html"
			}];
			return tag;
		}))
	};
	return `${JSON.stringify(payload, null, 2)}\n`;
}
function mergeHtmlCustomDataTags(baseTags, extraTags) {
	if (!baseTags.length) return extraTags;
	if (!extraTags.length) return baseTags;
	const tagMap = /* @__PURE__ */ new Map();
	for (const tag of baseTags) if (tag?.name) tagMap.set(tag.name, { ...tag });
	for (const tag of extraTags) {
		if (!tag?.name) continue;
		const existing = tagMap.get(tag.name);
		if (!existing) {
			tagMap.set(tag.name, { ...tag });
			continue;
		}
		const mergedAttributes = mergeHtmlAttributes(existing.attributes, tag.attributes);
		const mergedReferences = mergeReferences(existing.references, tag.references);
		tagMap.set(tag.name, {
			...existing,
			...tag,
			description: tag.description ?? existing.description,
			attributes: mergedAttributes,
			references: mergedReferences
		});
	}
	return Array.from(tagMap.values()).sort((a, b) => a.name.localeCompare(b.name));
}
function mergeHtmlAttributes(baseAttributes, extraAttributes) {
	if (!baseAttributes?.length) return extraAttributes?.length ? [...extraAttributes] : void 0;
	if (!extraAttributes?.length) return [...baseAttributes];
	const attrMap = /* @__PURE__ */ new Map();
	for (const attr of baseAttributes) if (attr?.name) attrMap.set(attr.name, { ...attr });
	for (const attr of extraAttributes) {
		if (!attr?.name) continue;
		const existing = attrMap.get(attr.name);
		if (!existing) {
			attrMap.set(attr.name, { ...attr });
			continue;
		}
		attrMap.set(attr.name, {
			...existing,
			...attr,
			description: attr.description ?? existing.description,
			values: mergeAttributeValues(existing.values, attr.values)
		});
	}
	return Array.from(attrMap.values()).sort((a, b) => a.name.localeCompare(b.name));
}
function mergeAttributeValues(baseValues, extraValues) {
	if (!baseValues?.length) return extraValues?.length ? [...extraValues] : void 0;
	if (!extraValues?.length) return [...baseValues];
	const valueMap = /* @__PURE__ */ new Map();
	for (const entry of baseValues) if (entry?.name) valueMap.set(entry.name, { ...entry });
	for (const entry of extraValues) {
		if (!entry?.name) continue;
		const existing = valueMap.get(entry.name);
		if (!existing) {
			valueMap.set(entry.name, { ...entry });
			continue;
		}
		valueMap.set(entry.name, {
			...existing,
			...entry,
			description: entry.description ?? existing.description
		});
	}
	return Array.from(valueMap.values());
}
function mergeReferences(base, extra) {
	if (!base?.length) return extra?.length ? [...extra] : void 0;
	if (!extra?.length) return [...base];
	const referenceMap = /* @__PURE__ */ new Map();
	for (const entry of base) if (entry?.url) referenceMap.set(entry.url, { ...entry });
	for (const entry of extra) {
		if (!entry?.url) continue;
		const existing = referenceMap.get(entry.url);
		if (!existing) {
			referenceMap.set(entry.url, { ...entry });
			continue;
		}
		referenceMap.set(entry.url, {
			...existing,
			...entry,
			name: entry.name ?? existing.name
		});
	}
	return Array.from(referenceMap.values());
}
//#endregion
//#region src/runtime/autoImport/definitionFormat.ts
const VALID_IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
function isValidIdentifierName(name) {
	return VALID_IDENTIFIER_RE.test(name);
}
function formatPropertyKey(name) {
	if (isValidIdentifierName(name)) return name;
	return `'${name.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
}
//#endregion
//#region src/runtime/autoImport/typedDefinition.ts
function formatComponentEntry(name, props) {
	const indent = "    ";
	const key = formatPropertyKey(name);
	if (!props || props.size === 0) return `${indent}${key}: Record<string, any>;`;
	const lines = [`${indent}${key}: {`];
	const innerIndent = `${indent}  `;
	const entries = Array.from(props.entries()).sort((a, b) => a[0].localeCompare(b[0]));
	for (const [propName, type] of entries) {
		const formattedProp = formatPropertyKey(propName);
		lines.push(`${innerIndent}readonly ${formattedProp}?: ${type};`);
	}
	lines.push(`${indent}};`);
	return lines.join("\n");
}
function createTypedComponentsDefinition(componentNames, getMetadata) {
	const lines = [
		"/* eslint-disable */",
		"// @ts-nocheck",
		"// biome-ignore lint: disable",
		"// oxlint-disable",
		"// ------",
		"// 由 weapp-vite 自动生成,请勿编辑。",
		"declare module 'weapp-vite/typed-components' {",
		"  export interface ComponentProps {"
	];
	if (componentNames.length === 0) lines.push("    [component: string]: Record<string, any>;");
	else for (const name of componentNames) {
		const metadata = getMetadata(name);
		lines.push(formatComponentEntry(name, metadata.types));
	}
	lines.push("  }");
	lines.push("  export type ComponentPropName = keyof ComponentProps;");
	lines.push("  export type ComponentProp<Name extends string> = Name extends ComponentPropName ? ComponentProps[Name] : Record<string, any>;");
	lines.push("  export const componentProps: ComponentProps;");
	lines.push("}");
	lines.push("");
	return lines.join("\n");
}
//#endregion
//#region src/runtime/autoImport/vueDefinition.ts
const VUE_SFC_IMPORT_RE = /\.vue(?:$|[?#])/i;
function formatPropsType(props) {
	if (!props || props.size === 0) return "Record<string, any>";
	const entries = Array.from(props.entries()).sort((a, b) => a[0].localeCompare(b[0]));
	const lines = ["{"];
	for (const [propName, type] of entries) {
		const key = formatPropertyKey(propName);
		lines.push(`  readonly ${key}?: ${type};`);
	}
	lines.push("}");
	return lines.join("\n");
}
function createLayoutTypesDefinition(layoutNames, layoutPropsMap) {
	const normalized = Array.from(new Set(layoutNames)).sort((a, b) => a.localeCompare(b));
	if (normalized.length === 0) return "";
	const lines = [
		"/* eslint-disable */",
		"// biome-ignore lint: disable",
		"// oxlint-disable",
		"// ------",
		"// 由 weapp-vite 自动生成,请勿编辑。",
		"export {}",
		"",
		"declare module 'wevu' {",
		"  interface WevuPageLayoutMap {"
	];
	for (const name of normalized) lines.push(`    ${formatPropertyKey(name)}: ${formatPropsType(layoutPropsMap?.get(name))};`);
	lines.push("  }");
	lines.push("}");
	lines.push("");
	return lines.join("\n");
}
function toPascalCase(name) {
	if (!name.includes("-")) return;
	const segments = name.split("-").map((s) => s.trim()).filter(Boolean);
	if (segments.length === 0) return;
	return segments.map((segment) => {
		const first = segment[0];
		if (!first) return "";
		return first.toUpperCase() + segment.slice(1);
	}).join("") || void 0;
}
function formatSourceImportType(importPath, fallbackType) {
	const spec = JSON.stringify(importPath);
	if (!fallbackType) return `__WeappComponentImport<typeof import(${spec})>`;
	return `__WeappComponentImport<typeof import(${spec}), ${fallbackType}>`;
}
function isVueSfcImport(importPath) {
	return VUE_SFC_IMPORT_RE.test(importPath);
}
function formatSourceDefaultImportType(importPath) {
	return `typeof import(${JSON.stringify(importPath)})['default']`;
}
function formatComponentTypeWithSourceImport(importPath, fallbackType) {
	if (isVueSfcImport(importPath)) return formatSourceDefaultImportType(importPath);
	return formatSourceImportType(importPath, fallbackType);
}
function formatWeappComponentTypeFromPropsType(propsType) {
	if (propsType.includes("\n")) return `WeappComponent<${propsType.split("\n").map((line, index) => {
		if (index === 0) return line;
		return `      ${line}`;
	}).join("\n")}>`;
	return `WeappComponent<${propsType}>`;
}
function formatGlobalComponentEntry(name, metadata, sourceImport) {
	const key = formatPropertyKey(name);
	const baseType = formatWeappComponentTypeFromPropsType(formatPropsType(metadata.types));
	return `    ${key}: ${sourceImport ? formatComponentTypeWithSourceImport(sourceImport, baseType) : baseType};`;
}
function formatGlobalConstEntry(name, metadata, sourceImport) {
	if (!isValidIdentifierName(name)) return;
	const propsType = formatPropsType(metadata.types);
	const baseType = propsType.includes("\n") ? (() => {
		return `WeappComponent<${propsType.split("\n").map((line, index) => {
			if (index === 0) return line;
			return `    ${line}`;
		}).join("\n")}>`;
	})() : `WeappComponent<${propsType}>`;
	return `  const ${name}: ${sourceImport ? formatComponentTypeWithSourceImport(sourceImport, baseType) : baseType}`;
}
function createVueComponentsDefinition(componentNames, getMetadata, options = {}) {
	const moduleName = options.moduleName?.trim() || "vue";
	const emittedComponentKeys = /* @__PURE__ */ new Set();
	const emittedGlobalConstKeys = /* @__PURE__ */ new Set();
	const globalConstLines = [];
	const lines = [
		"/* eslint-disable */",
		"// biome-ignore lint: disable",
		"// oxlint-disable",
		"// ------",
		"// 由 weapp-vite autoImportComponents 生成",
		"import type { ComponentOptionsMixin, DefineComponent, PublicProps, WeappIntrinsicElementBaseAttributes } from 'wevu'",
		...options.useTypedComponents ? ["import type { ComponentProp } from 'weapp-vite/typed-components'"] : [],
		"",
		"export {}",
		"",
		"type WeappComponent<Props = Record<string, any>> = new (...args: any[]) => InstanceType<DefineComponent<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, {}, string, PublicProps, Props & WeappIntrinsicElementBaseAttributes, {}>>",
		"type __WeappComponentProps<TComponent> = TComponent extends new (...args: any[]) => { $props: infer Props } ? Props : Record<string, any>",
		"type __WeappComponentImport<TModule, Fallback = {}> = 0 extends 1 & TModule ? Fallback : TModule extends { default: infer Component } ? Component extends new (...args: infer Args) => infer Instance ? new (...args: Args) => Omit<Instance, '$props'> & { $props: __WeappComponentProps<Component> & __WeappComponentProps<Fallback> } : Fallback : Fallback",
		"",
		`declare module '${moduleName}' {`,
		"  export interface GlobalComponents {"
	];
	if (componentNames.length === 0) lines.push("    [component: string]: WeappComponent;");
	else {
		const emitGlobalConst = (keyName, sourceName) => {
			if (!isValidIdentifierName(keyName)) return;
			if (emittedGlobalConstKeys.has(keyName)) return;
			emittedGlobalConstKeys.add(keyName);
			if (options.useTypedComponents) {
				const sourceImport = options.resolveComponentImport?.(sourceName);
				const baseType = `WeappComponent<ComponentProp<${JSON.stringify(sourceName)}>>`;
				const typeWithSource = sourceImport ? formatComponentTypeWithSourceImport(sourceImport, baseType) : baseType;
				globalConstLines.push(`  const ${keyName}: ${typeWithSource}`);
				return;
			}
			const sourceImport = options.resolveComponentImport?.(sourceName);
			const metadata = getMetadata(sourceName);
			globalConstLines.push(formatGlobalConstEntry(keyName, metadata, sourceImport));
		};
		const emitGlobalComponent = (keyName, sourceName) => {
			if (emittedComponentKeys.has(keyName)) return;
			emittedComponentKeys.add(keyName);
			const sourceImport = options.resolveComponentImport?.(sourceName);
			if (options.useTypedComponents) {
				const baseType = `WeappComponent<ComponentProp<${JSON.stringify(sourceName)}>>`;
				const typeWithSource = sourceImport ? formatComponentTypeWithSourceImport(sourceImport, baseType) : baseType;
				lines.push(`    ${formatPropertyKey(keyName)}: ${typeWithSource};`);
				emitGlobalConst(keyName, sourceName);
				return;
			}
			const metadata = getMetadata(sourceName);
			lines.push(formatGlobalComponentEntry(keyName, metadata, sourceImport));
			emitGlobalConst(keyName, sourceName);
		};
		for (const name of componentNames) {
			const pascal = toPascalCase(name);
			if (pascal && isValidIdentifierName(pascal)) {
				emitGlobalComponent(pascal, name);
				emitGlobalComponent(name, name);
				continue;
			}
			emitGlobalComponent(name, name);
		}
	}
	lines.push("  }");
	lines.push("}");
	lines.push("");
	const layoutDefinition = createLayoutTypesDefinition(options.layoutNames ?? [], options.layoutPropsMap);
	if (layoutDefinition) {
		lines.push(...layoutDefinition.trimEnd().split("\n"));
		lines.push("");
	}
	lines.push("// 用于 TSX 支持");
	lines.push("declare global {");
	if (globalConstLines.length === 0) lines.push("}");
	else {
		lines.push(...globalConstLines);
		lines.push("}");
	}
	lines.push("");
	return lines.join("\n");
}
//#endregion
//#region src/runtime/autoImport/vueProps.ts
/** 提取 Vue SFC 组件 props,避免为了类型支持文件走完整 SFC 编译。 */
function extractVueComponentProps(source, filename, options = {}) {
	const { descriptor, errors } = parse$1(source, { filename });
	if (errors.length || !descriptor.script && !descriptor.scriptSetup) return /* @__PURE__ */ new Map();
	const inlineProps = extractInlinePropsTypeFromCode(descriptor.scriptSetup?.content ?? descriptor.script?.content ?? "");
	if (inlineProps.size > 0) return inlineProps;
	const compiled = compileScript(descriptor, {
		id: filename,
		isProd: false
	});
	if (!compiled.content) return /* @__PURE__ */ new Map();
	return extractComponentProps(compiled.content, { astEngine: options.astEngine });
}
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/adsAndMeta.ts
const WEAPP_BUILTIN_HTML_TAGS_ADS_AND_META = [
	{
		"name": "ad",
		"description": "广告。**目前暂时以邀请制开放申请,请留意后续模板消息的通知**",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: function => any\n当广告发生错误时,触发的事件,可以通过该事件获取错误码及原因,事件对象event.detail = {errCode: 1002}\nSince: 2.2.1"
			},
			{
				"name": "bindload",
				"description": "Type: function => any\n广告加载成功的回调\nSince: 2.2.1"
			},
			{
				"name": "unit-id",
				"description": "Type: string\n广告单元id,可在[小程序管理后台](https://mp.weixin.qq.com)的流量主模块新建"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/ad.html"
		}]
	},
	{
		"name": "ad-custom",
		"description": "原生模板 广告。",
		"attributes": [
			{
				"name": "ad-intervals",
				"description": "Type: number\n广告自动刷新的间隔时间,单位为秒,参数值必须大于等于30(该参数不传入时 模板 广告不会自动刷新)"
			},
			{
				"name": "binderror",
				"description": "Type: eventhandle\n广告加载失败的回调,`event.detail = {errCode: 1002}`"
			},
			{
				"name": "bindload",
				"description": "Type: eventhandle\n广告加载成功的回调"
			},
			{
				"name": "unit-id",
				"description": "Type: string\n广告单元id,可在[小程序管理后台](https://mp.weixin.qq.com)的流量主模块新建"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/ad-custom.html"
		}]
	},
	{
		"name": "block",
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/conditional.html#block-wx-if"
		}]
	},
	{
		"name": "match-media",
		"description": "media query 匹配检测节点。可以指定一组media query规则,满足时,这个节点才会被展示。\n通过这个节点可以实现“页面宽高在某个范围时才展示某个区域”这样的效果。",
		"attributes": [
			{
				"name": "height",
				"description": "Type: number\n页面高度(`px`为单位)"
			},
			{
				"name": "max-height",
				"description": "Type: number\n页面最大高度(`px`为单位)"
			},
			{
				"name": "max-width",
				"description": "Type: number\n页面最大宽度(`px`为单位)"
			},
			{
				"name": "min-height",
				"description": "Type: number\n页面最小高度(`px`为单位)"
			},
			{
				"name": "min-width",
				"description": "Type: number\n页面最小宽度(`px`为单位)"
			},
			{
				"name": "orientation",
				"description": "Type: string\n屏幕方向(`landscape`或`portrait`)"
			},
			{
				"name": "width",
				"description": "Type: number\n页面宽度(`px`为单位))"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/match-media.html"
		}]
	},
	{
		"name": "navigation-bar",
		"description": "页面导航条配置节点,用于指定导航栏的一些属性。只能是[page-meta](https://developers.weixin.qq.com/miniprogram/dev/component/page-meta.html)组件内的第一个节点,需要配合它一同使用。\n通过这个节点可以获得类似于调用[wx.setNavigationBarTitle](https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.setNavigationBarTitle.html) [wx.setNavigationBarColor](https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.setNavigationBarColor.html) 等接口调用的效果。",
		"attributes": [
			{
				"name": "background-color",
				"description": "Type: string\n导航条背景颜色值,有效值为十六进制颜色"
			},
			{
				"name": "color-animation-duration",
				"description": "Type: number\n改变导航栏颜色时的动画时长,默认为`0`(即没有动画效果)\nDefault: 0"
			},
			{
				"name": "color-animation-timing-func",
				"description": "Type: string\n改变导航栏颜色时的动画方式,支持`linear`、`easeIn`、`easeOut`和`easeInOut`\nDefault: linear",
				"values": [
					{ "name": "linear" },
					{ "name": "easeIn" },
					{ "name": "easeOut" },
					{ "name": "easeInOut" }
				]
			},
			{
				"name": "front-color",
				"description": "Type: string\n导航条前景颜色值,包括按钮、标题、状态栏的颜色,仅支持`#ffffff`和`#000000`",
				"values": [{
					"name": "#ffffff",
					"description": "白色"
				}, {
					"name": "#ffffff",
					"description": "黑色"
				}]
			},
			{
				"name": "loading",
				"description": "Type: boolean\n是否在导航条显示loading加载提示\nDefault: false"
			},
			{
				"name": "title",
				"description": "Type: string\n导航条标题"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/navigation-bar.html"
		}]
	},
	{
		"name": "official-account",
		"description": "用户扫码打开小程序时,开发者可在小程序内配置公众号关注组件,方便用户快捷关注公众号,可嵌套在原生组件内。",
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/official-account.html"
		}]
	},
	{
		"name": "open-data",
		"description": "用于展示微信开放的数据。",
		"attributes": [
			{
				"name": "lang",
				"description": "Type: string\n当 type=\"user*\" 时生效,以哪种语言展示 userInfo,有效值有:en, zh_CN, zh_TW\nDefault: en"
			},
			{
				"name": "open-gid",
				"description": "Type: string\n当 type=\"groupName\" 时生效, 群id"
			},
			{
				"name": "type",
				"description": "Type: string\n开放数据类型",
				"values": [
					{
						"name": "groupName",
						"description": "拉取群名称"
					},
					{
						"name": "userNickName",
						"description": "用户昵称"
					},
					{
						"name": "userAvatarUrl",
						"description": "用户头像"
					},
					{
						"name": "userGender",
						"description": "用户性别"
					},
					{
						"name": "userCity",
						"description": "用户所在城市"
					},
					{
						"name": "userProvince",
						"description": "用户所在省份"
					},
					{
						"name": "userCountry",
						"description": "用户所在国家"
					},
					{
						"name": "userLanguage",
						"description": "用户的语言"
					}
				]
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html"
		}]
	},
	{
		"name": "page-container",
		"description": "页面容器。\n小程序如果在页面内进行复杂的界面设计(如在页面内弹出半屏的弹窗、在页面内加载一个全屏的子页面等),用户进行返回操作会直接离开当前页面,不符合用户预期,预期应为关闭当前弹出的组件。 为此提供“假页”容器组件,效果类似于`popup`弹出层,页面内存在该容器时,当用户进行返回操作,关闭该容器不关闭页面。返回操作包括三种情形,右滑手势、安卓物理返回键和调用`navigateBack`接口。",
		"attributes": [
			{
				"name": "bind:afterenter",
				"description": "Type: eventhandle\n进入后触发"
			},
			{
				"name": "bind:afterleave",
				"description": "Type: eventhandle\n离开后触发"
			},
			{
				"name": "bind:beforeenter",
				"description": "Type: eventhandle\n进入前触发"
			},
			{
				"name": "bind:beforeleave",
				"description": "Type: eventhandle\n离开前触发"
			},
			{
				"name": "bind:clickoverlay",
				"description": "Type: eventhandle\n点击遮罩层时触发"
			},
			{
				"name": "bind:enter",
				"description": "Type: eventhandle\n进入中触发"
			},
			{
				"name": "bind:leave",
				"description": "Type: eventhandle\n离开中触发"
			},
			{
				"name": "close-on-slideDown",
				"description": "Type: boolean\n是否在下滑一段距离后关闭\nDefault: false"
			},
			{
				"name": "custom-style",
				"description": "Type: string\n自定义弹出层样式"
			},
			{
				"name": "duration",
				"description": "Type: number\n动画时长,单位毫秒\nDefault: 300"
			},
			{
				"name": "overlay",
				"description": "Type: boolean\n是否显示遮罩层\nDefault: true"
			},
			{
				"name": "overlay-style",
				"description": "Type: string\n自定义遮罩层样式"
			},
			{
				"name": "position",
				"description": "Type: string\n弹出位置,可选值为`top` `bottom` `right` `center`\nDefault: bottom",
				"values": [
					{ "name": "top" },
					{ "name": "bottom" },
					{ "name": "right" },
					{ "name": "center" }
				]
			},
			{
				"name": "round",
				"description": "Type: boolean\n是否显示圆角\nDefault: false"
			},
			{
				"name": "show",
				"description": "Type: boolean\n是否显示容器组件\nDefault: false"
			},
			{
				"name": "z-index",
				"description": "Type: number\nz-index 层级\nDefault: 100"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/page-container.html"
		}]
	},
	{
		"name": "page-meta",
		"description": "页面属性配置节点,用于指定页面的一些属性、监听页面事件。只能是页面内的第一个节点。可以配合[navigation-bar](https://developers.weixin.qq.com/miniprogram/dev/component/navigation-bar.html)组件一同使用。\n过这个节点可以获得类似于调用 [wx.setBackgroundTextStyle](https://developers.weixin.qq.com/miniprogram/dev/api/ui/background/wx.setBackgroundTextStyle.html) [wx.setBackgroundColor](https://developers.weixin.qq.com/miniprogram/dev/api/ui/background/wx.setBackgroundColor.html) 等接口调用的效果。",
		"attributes": [
			{
				"name": "background-color",
				"description": "Type: string\n窗口的背景色,必须为十六进制颜色值"
			},
			{
				"name": "background-color-bottom",
				"description": "Type: string\n底部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持"
			},
			{
				"name": "background-color-top",
				"description": "Type: string\n顶部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持"
			},
			{
				"name": "background-text-style",
				"description": "Type: string\n下拉背景字体、loading 图的样式,仅支持`dark`和`light`",
				"values": [{ "name": "dark" }, { "name": "light" }]
			},
			{
				"name": "bindresize",
				"description": "Type: eventhandle\n页面尺寸变化时会触发`resize`事件, `event.detail = { size: { windowWidth, windowHeight } }`"
			},
			{
				"name": "bindscroll",
				"description": "Type: eventhandle\n页面滚动时会触发`scroll`事件, `event.detail = { scrollTop }`"
			},
			{
				"name": "bindscrolldone",
				"description": "Type: eventhandle\n如果通过改变`scroll-top`属性来使页面滚动,页面滚动结束后会触发`scrolldone`事件"
			},
			{
				"name": "page-font-size",
				"description": "Type: string\n页面 page 的字体大小,可以设置为`system`,表示使用当前用户设置的微信字体大小"
			},
			{
				"name": "page-orientation",
				"description": "Type: string\n页面的方向,可为`auto` `portrait`或`landscape`",
				"values": [
					{ "name": "auto" },
					{ "name": "portrait" },
					{ "name": "landscape" }
				]
			},
			{
				"name": "page-style",
				"description": "Type: string\n页面根节点样式,页面根节点是所有页面节点的祖先节点,相当于 HTML 中的 body 节点"
			},
			{
				"name": "root-background-color",
				"description": "Type: string\n页面内容的背景色,用于页面中的空白部分和页面大小变化resize动画期间的临时空闲区域"
			},
			{
				"name": "root-font-size",
				"description": "Type: string\n页面的根字体大小,页面中的所有`rem`单位,将使用这个字体大小作为参考值,即`1rem`等于这个字体大小;自小程序版本 2.11.0 起,也可以设置为`system`"
			},
			{
				"name": "scroll-duration",
				"description": "Type: number\n滚动动画时长\nDefault: 300"
			},
			{
				"name": "scroll-top",
				"description": "Type: string\n滚动位置,可以使用 px 或者 rpx 为单位,在被设置时,页面会滚动到对应位置"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/page-meta.html"
		}]
	},
	{
		"name": "share-element",
		"description": "共享元素。\n共享元素是一种动画形式,类似于[flutter Hero](https://flutterchina.club/animations/hero-animations)动画,表现为元素像是在页面间穿越一样。该组件需与[page-container](https://developers.weixin.qq.com/miniprogram/dev/component/page-container.html)组件结合使用。\n使用时需在当前页放置`share-element`组件,同时在`page-container`容器中放置对应的`share-element`组件,对应关系通过属性值`key`映射。当设置`page-container`显示时,`transform`属性为`true`的共享元素会产生动画。当前页面容器退出时,会产生返回动画。",
		"attributes": [
			{
				"name": "duration",
				"description": "Type: number\n动画时长,单位毫秒\nDefault: 300"
			},
			{
				"name": "easing-function",
				"description": "Type: string\n`css`缓动函数\nDefault: ease-out"
			},
			{
				"name": "key",
				"description": "Type: string\n映射标记"
			},
			{
				"name": "transform",
				"description": "Type: boolean\n是否进行动画\nDefault: false"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/share-element.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/formControlsPrimary.ts
const WEAPP_BUILTIN_HTML_TAGS_FORM_CONTROLS_PRIMARY = [
	{
		"name": "button",
		"description": "按钮。",
		"attributes": [
			{
				"name": "app-parameter",
				"description": "Type: string\n打开 APP 时,向 APP 传递的参数\nSince: 1.9.5"
			},
			{
				"name": "bindcontact",
				"description": "Type: function => any\n客服消息回调\nSince: 1.5.0"
			},
			{
				"name": "binderror",
				"description": "Type: function => any\n当使用开放能力时,发生错误的回调\nSince: 1.9.5"
			},
			{
				"name": "bindgetphonenumber",
				"description": "Type: function => any\n获取用户手机号回调\nSince: 1.2.0"
			},
			{
				"name": "bindgetuserinfo",
				"description": "Type: function => any\n用户点击该按钮时,会返回获取到的用户信息,回调的detail数据与[wx.getUserInfo](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html)返回的一致\nSince: 1.3.0"
			},
			{
				"name": "bindopensetting",
				"description": "Type: function => any\n在打开授权设置页后回调\nSince: 2.0.7"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "form-type",
				"description": "Type: string\n用于 `<form/>` 组件,点击分别会触发 `<form/>` 组件的 submit/reset 事件",
				"values": [{
					"name": "submit",
					"description": "提交表单"
				}, {
					"name": "reset",
					"description": "重置表单"
				}]
			},
			{
				"name": "hover-class",
				"description": "Type: string\n指定按钮按下去的样式类。当 `hover-class=\"none\"` 时,没有点击态效果\nDefault: button-hover"
			},
			{
				"name": "hover-start-time",
				"description": "Type: number\n按住后多久出现点击态,单位毫秒\nDefault: 20"
			},
			{
				"name": "hover-stay-time",
				"description": "Type: number\n手指松开后点击态保留时间,单位毫秒\nDefault: 70"
			},
			{
				"name": "hover-stop-propagation",
				"description": "Type: boolean\n指定是否阻止本节点的祖先节点出现点击态\nDefault: false\nSince: 1.5.0"
			},
			{
				"name": "lang",
				"description": "Type: string\n指定返回用户信息的语言,zh_CN 简体中文,zh_TW 繁体中文,en 英文。\nDefault: en\nSince: 1.3.0"
			},
			{
				"name": "loading",
				"description": "Type: boolean\n名称前是否带 loading 图标\nDefault: false"
			},
			{
				"name": "open-type",
				"description": "Type: string\n微信开放能力\nSince: 1.1.0",
				"values": [
					{
						"name": "contact",
						"description": "打开客服会话"
					},
					{
						"name": "share",
						"description": "触发用户转发,使用前建议先阅读[使用指引](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share.html#使用指引)"
					},
					{
						"name": "getUserInfo",
						"description": "获取用户信息,可以从bindgetuserinfo回调中获取到用户信息"
					},
					{
						"name": "getPhoneNumber",
						"description": "获取用户手机号,可以从bindgetphonenumber回调中获取到用户信息,[具体说明](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html)"
					},
					{
						"name": "launchApp",
						"description": "打开APP,可以通过app-parameter属性设定向APP传的参数[具体说明](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/launchApp.html)"
					},
					{
						"name": "openSetting",
						"description": "打开授权设置页"
					},
					{
						"name": "feedback",
						"description": "打开“意见反馈”页面,用户可提交反馈内容并上传[日志](https://developers.weixin.qq.com/miniprogram/dev/api/debug/wx.getLogManager.html),开发者可以登录[小程序管理后台](https://mp.weixin.qq.com/)后进入左侧菜单“客服反馈”页面获取到反馈内容"
					}
				]
			},
			{
				"name": "plain",
				"description": "Type: boolean\n按钮是否镂空,背景色透明\nDefault: false"
			},
			{
				"name": "send-message-img",
				"description": "Type: string\n会话内消息卡片图片\nDefault: 截图\nSince: 1.5.0"
			},
			{
				"name": "send-message-path",
				"description": "Type: string\n会话内消息卡片点击跳转小程序路径\nDefault: 当前分享路径\nSince: 1.5.0"
			},
			{
				"name": "send-message-title",
				"description": "Type: string\n会话内消息卡片标题\nDefault: 当前标题\nSince: 1.5.0"
			},
			{
				"name": "session-from",
				"description": "Type: string\n会话来源\nSince: 1.4.0"
			},
			{
				"name": "show-message-card",
				"description": "Type: boolean\n显示会话内消息卡片\nDefault: false\nSince: 1.5.0"
			},
			{
				"name": "size",
				"description": "Type: string\n按钮的大小\nDefault: default",
				"values": [{
					"name": "default",
					"description": "默认大小"
				}, {
					"name": "mini",
					"description": "小尺寸"
				}]
			},
			{
				"name": "type",
				"description": "Type: string\n按钮的样式类型\nDefault: default",
				"values": [
					{
						"name": "primary",
						"description": "绿色"
					},
					{
						"name": "default",
						"description": "白色"
					},
					{
						"name": "warn",
						"description": "红色"
					}
				]
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/button.html"
		}]
	},
	{
		"name": "checkbox",
		"description": "多选项目。",
		"attributes": [
			{
				"name": "checked",
				"description": "Type: boolean\n当前是否选中,可用来设置默认选中\nDefault: false"
			},
			{
				"name": "color",
				"description": "Type: string\ncheckbox的颜色,同css的color"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "value",
				"description": "Type: string\n`<checkbox/>`标识,选中时触发`<checkbox-group/>`的 change 事件,并携带 `<checkbox/>` 的 value"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/checkbox.html"
		}]
	},
	{
		"name": "checkbox-group",
		"description": "多项选择器,内部由多个`checkbox`组成。",
		"attributes": [{
			"name": "bindchange",
			"description": "Type: function => any\n`<checkbox-group/>`中选中项发生改变是触发 change 事件,detail = {value:\\[选中的checkbox的value的数组\\]}"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/checkbox.html"
		}]
	},
	{
		"name": "editor",
		"description": "富文本编辑器,可以对图片、文字进行编辑。\n编辑器导出内容支持带标签的`html`和纯文本的`text`,编辑器内部采用`delta`格式进行存储。\n通过`setContents`接口设置内容时,解析插入的`html`可能会由于一些非法标签导致解析错误,建议开发者在小程序内使用时通过`delta`进行插入。\n富文本组件内部引入了一些基本的样式使得内容可以正确的展示,开发时可以进行覆盖。需要注意的是,在其它组件或环境中使用富文本组件导出的`html`时,需要额外引入[这段样式](https://developers.weixin.qq.com/miniprogram/dev/component/editor.html),并维护`<ql-container><ql-editor></ql-editor></ql-container>`的结构。\n图片控件仅初始化时设置有效。\n编辑器内支持部分`HTML`标签和内联样式,不支持`class`和`id`\n不满足的标签会被忽略,`<div>`会被转行为`<p>`储存。\n内联样式仅能设置在行内元素或块级元素上,不能同时设置。例如`font-size`归类为行内元素属性,在`p`标签上设置是无效的。",
		"attributes": [
			{
				"name": "bindblur",
				"description": "Type: eventhandle\n编辑器失去焦点时触发,`detail = {html, text, delta}`"
			},
			{
				"name": "bindfocus",
				"description": "Type: eventhandle\n编辑器聚焦时触发,`event.detail = {html, text, delta}`"
			},
			{
				"name": "bindinput",
				"description": "Type: eventhandle\n编辑器内容改变时触发,`detail = {html, text, delta}`"
			},
			{
				"name": "bindready",
				"description": "Type: eventhandle\n编辑器初始化完成时触发"
			},
			{
				"name": "bindstatuschange",
				"description": "Type: eventhandle\n通过`Context`方法改变编辑器内样式时触发,返回选区已设置的样式"
			},
			{
				"name": "placeholder",
				"description": "Type: string\n提示信息"
			},
			{
				"name": "read-only",
				"description": "Type: boolean\n设置编辑器为只读\nDefault: false"
			},
			{
				"name": "show-img-resize",
				"description": "Type: boolean\n点击图片时显示修改尺寸控件\nDefault: false"
			},
			{
				"name": "show-img-size",
				"description": "Type: boolean\n点击图片时显示图片大小控件\nDefault: false"
			},
			{
				"name": "show-img-toolbar",
				"description": "Type: boolean\n点击图片时显示工具栏控件\nDefault: false"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/editor.html"
		}]
	},
	{
		"name": "form",
		"description": "表单,将组件内的用户输入的`<switch/>` `<input/>` `<checkbox/>` `<slider/>` `<radio/>` `<picker/>` 提交。\n\n当点击 `<form/>` 表单中 formType 为 submit 的 `<button/>` 组件时,会将表单组件中的 value 值进行提交,需要在表单组件中加上 name 来作为 key。",
		"attributes": [
			{
				"name": "bindreset",
				"description": "Type: function => any\n表单重置时会触发 reset 事件"
			},
			{
				"name": "bindsubmit",
				"description": "Type: function => any\n携带 form 中的数据触发 submit 事件,event.detail = {value : {'name': 'value'} , formId: ''}"
			},
			{
				"name": "report-submit",
				"description": "Type: boolean\n是否返回 formId 用于发送[模板消息](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/template-message.html)"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/form.html"
		}]
	},
	{
		"name": "input",
		"description": "输入框。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。",
		"attributes": [
			{
				"name": "adjust-position",
				"description": "Type: boolean\n键盘弹起时,是否自动上推页面\nDefault: true\nSince: 1.9.90"
			},
			{
				"name": "always-embed",
				"description": "Type: boolean\n强制 input 处于同层状态,默认 focus 时 input 会切到非同层状态 (仅在 iOS 下生效)\nDefault: false\nSince: 2.10.4"
			},
			{
				"name": "auto-focus",
				"description": "Type: boolean\n(即将废弃,请直接使用 focus )自动聚焦,拉起键盘\nDefault: false"
			},
			{
				"name": "bindblur",
				"description": "Type: function => any\n输入框失去焦点时触发,event.detail = {value: value}"
			},
			{
				"name": "bindconfirm",
				"description": "Type: function => any\n点击完成按钮时触发,event.detail = {value: value}"
			},
			{
				"name": "bindfocus",
				"description": "Type: function => any\n输入框聚焦时触发,event.detail = { value, height },height 为键盘高度,在基础库 1.9.90 起支持"
			},
			{
				"name": "bindinput",
				"description": "Type: function => any\n键盘输入时触发,event.detail = {value, cursor, keyCode},keyCode 为键值,2.1.0 起支持,处理函数可以直接 return 一个字符串,将替换输入框的内容。"
			},
			{
				"name": "bindkeyboardheightchange",
				"description": "Type: function => any\n键盘高度发生变化的时候触发此事件,event.detail = {height: height, duration: duration}\nSince: 2.7.0"
			},
			{
				"name": "confirm-hold",
				"description": "Type: boolean\n点击键盘右下角按钮时是否保持键盘不收起\nDefault: false\nSince: 1.1.0"
			},
			{
				"name": "confirm-type",
				"description": "Type: string\n设置键盘右下角按钮的文字,仅在type='text'时生效\nDefault: done\nSince: 1.1.0",
				"values": [
					{
						"name": "send",
						"description": "右下角按钮为“发送”"
					},
					{
						"name": "search",
						"description": "右下角按钮为“搜索”"
					},
					{
						"name": "next",
						"description": "右下角按钮为“下一个”"
					},
					{
						"name": "go",
						"description": "右下角按钮为“前往”"
					},
					{
						"name": "done",
						"description": "右下角按钮为“完成”"
					}
				]
			},
			{
				"name": "cursor",
				"description": "Type: number\n指定focus时的光标位置\nSince: 1.5.0"
			},
			{
				"name": "cursor-spacing",
				"description": "Type: number\n指定光标与键盘的距离,单位 px 。取 input 距离底部的距离和 cursor-spacing 指定的距离的最小值作为光标与键盘的距离\nDefault: 0"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "focus",
				"description": "Type: boolean\n获取焦点\nDefault: false"
			},
			{
				"name": "hold-keyboard",
				"description": "Type: boolean\nfocus时,点击页面的时候不收起键盘\nDefault: false\nSince: 2.8.2"
			},
			{
				"name": "maxlength",
				"description": "Type: number\n最大输入长度,设置为 -1 的时候不限制最大长度\nDefault: 140"
			},
			{
				"name": "password",
				"description": "Type: boolean\n是否是密码类型\nDefault: false"
			},
			{
				"name": "placeholder",
				"description": "Type: string\n输入框为空时占位符"
			},
			{
				"name": "placeholder-class",
				"description": "Type: string\n指定 placeholder 的样式类\nDefault: input-placeholder"
			},
			{
				"name": "placeholder-style",
				"description": "Type: string\n指定 placeholder 的样式"
			},
			{
				"name": "safe-password-cert-path",
				"description": "Type: string\n安全键盘加密公钥的路径,只支持包内路径\nSince: 2.18.0"
			},
			{
				"name": "safe-password-custom-hash",
				"description": "Type: string\n安全键盘计算hash的算法表达式,如`md5(sha1('foo' + sha256(sm3(password + 'bar'))))`\nSince: 2.18.0"
			},
			{
				"name": "safe-password-length",
				"description": "Type: number\n安全键盘输入密码长度\nSince: 2.18.0"
			},
			{
				"name": "safe-password-nonce",
				"description": "Type: string\n安全键盘加密盐值\nSince: 2.18.0"
			},
			{
				"name": "safe-password-salt",
				"description": "Type: string\n安全键盘计算hash盐值,若指定`custom-hash`则无效\nSince: 2.18.0"
			},
			{
				"name": "safe-password-time-stamp",
				"description": "Type: number\n安全键盘加密时间戳\nSince: 2.18.0"
			},
			{
				"name": "selection-end",
				"description": "Type: number\n光标结束位置,自动聚集时有效,需与selection-start搭配使用\nDefault: -1\nSince: 1.9.0"
			},
			{
				"name": "selection-start",
				"description": "Type: number\n光标起始位置,自动聚集时有效,需与selection-end搭配使用\nDefault: -1\nSince: 1.9.0"
			},
			{
				"name": "type",
				"description": "Type: string\ninput 的类型\nDefault: text",
				"values": [
					{
						"name": "text",
						"description": "文本输入键盘"
					},
					{
						"name": "number",
						"description": "数字输入键盘"
					},
					{
						"name": "idcard",
						"description": "身份证输入键盘"
					},
					{
						"name": "digit",
						"description": "带小数点的数字键盘"
					}
				]
			},
			{
				"name": "value",
				"description": "Type: string\n输入框的初始内容"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/input.html"
		}]
	},
	{
		"name": "keyboard-accessory",
		"description": "设置 `input` / `textarea` 聚焦时键盘上方 `cover-view` / `cover-image` 工具栏视图",
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/keyboard-accessory.html"
		}]
	},
	{
		"name": "label",
		"description": "用来改进表单组件的可用性,使用`for`属性找到对应的`id`,或者将控件放在该标签下,当点击时,就会触发对应的控件。\n\n`for`优先级高于内部控件,内部有多个控件的时候默认触发第一个控件。\n\n目前可以绑定的控件有:`<button/>`, `<checkbox/>`, `<radio/>`, `<switch/>`。",
		"attributes": [{
			"name": "for",
			"description": "Type: string\n绑定控件的 id"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/label.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/formControlsSelection.ts
const WEAPP_BUILTIN_HTML_TAGS_FORM_CONTROLS_SELECTION = [
	{
		"name": "picker",
		"description": "从底部弹起的滚动选择器,现支持五种选择器,通过mode来区分,分别是普通选择器,多列选择器,时间选择器,日期选择器,省市区选择器,默认是普通选择器。",
		"attributes": [{
			"name": "mode",
			"description": "Type: string\n选择器的类型\nDefault: selector"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/picker.html"
		}]
	},
	{
		"name": "picker-view",
		"description": "嵌入页面的滚动选择器",
		"attributes": [
			{
				"name": "bindchange",
				"description": "Type: function => any\n当滚动选择,value 改变时触发 change 事件,event.detail = {value: value};value为数组,表示 picker-view 内的 picker-view-column 当前选择的是第几项(下标从 0 开始)"
			},
			{
				"name": "indicator-class",
				"description": "Type: string\n设置选择器中间选中框的类名\nSince: 1.1.0"
			},
			{
				"name": "indicator-style",
				"description": "Type: string\n设置选择器中间选中框的样式"
			},
			{
				"name": "mask-class",
				"description": "Type: string\n设置蒙层的类名\nSince: 1.5.0"
			},
			{
				"name": "mask-style",
				"description": "Type: string\n设置蒙层的样式\nSince: 1.5.0"
			},
			{
				"name": "value",
				"description": "Type: number[]\n数组中的数字依次表示 picker-view 内的 picker-view-column 选择的第几项(下标从 0 开始),数字大于 picker-view-column 可选项长度时,选择最后一项。"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/picker-view.html"
		}]
	},
	{
		"name": "picker-view-column",
		"description": "仅可放置于`<picker-view />`中,其孩子节点的高度会自动设置成与picker-view的选中框的高度一致",
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/picker-view.html"
		}]
	},
	{
		"name": "progress",
		"description": "进度条。",
		"attributes": [
			{
				"name": "active",
				"description": "Type: boolean\n进度条从左往右的动画\nDefault: false"
			},
			{
				"name": "active-color",
				"description": "Type: string\n已选择的进度条的颜色"
			},
			{
				"name": "active-mode",
				"description": "Type: string\nbackwards: 动画从头播;forwards:动画从上次结束点接着播\nDefault: backwards\nSince: 1.7.0"
			},
			{
				"name": "background-color",
				"description": "Type: string\n未选择的进度条的颜色"
			},
			{
				"name": "color",
				"description": "Type: string\n进度条颜色 (请使用 active-color)\nDefault: #09BB07"
			},
			{
				"name": "percent",
				"description": "Type: number\n百分比0~100\nDefault: 无"
			},
			{
				"name": "show-info",
				"description": "Type: boolean\n在进度条右侧显示百分比\nDefault: false"
			},
			{
				"name": "stroke-width",
				"description": "Type: number\n进度条线的宽度,单位px\nDefault: 6"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/progress.html"
		}]
	},
	{
		"name": "radio",
		"description": "单选项目",
		"attributes": [
			{
				"name": "checked",
				"description": "Type: boolean\n当前是否选中\nDefault: false"
			},
			{
				"name": "color",
				"description": "Type: string\nradio的颜色,同css的color"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "value",
				"description": "Type: string\n`<radio/>` 标识。当该`<radio/>` 选中时,`<radio-group/>` 的 change 事件会携带`<radio/>`的value"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/radio.html"
		}]
	},
	{
		"name": "radio-group",
		"description": "单项选择器,内部由多个`<radio/>`组成。",
		"attributes": [{
			"name": "bindchange",
			"description": "Type: function => any\n`<radio-group/>` 中的选中项发生变化时触发 change 事件,event.detail = {value: 选中项radio的value}"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/radio.html"
		}]
	},
	{
		"name": "slider",
		"description": "滑动选择器。",
		"attributes": [
			{
				"name": "active-color",
				"description": "Type: string\n已选择的颜色\nDefault: #1aad19"
			},
			{
				"name": "background-color",
				"description": "Type: string\n背景条的颜色\nDefault: #e9e9e9"
			},
			{
				"name": "bindchange",
				"description": "Type: function => any\n完成一次拖动后触发的事件,event.detail = {value: value}"
			},
			{
				"name": "bindchanging",
				"description": "Type: function => any\n拖动过程中触发的事件,event.detail = {value: value}\nSince: 1.7.0"
			},
			{
				"name": "block-color",
				"description": "Type: string\n滑块的颜色\nDefault: #ffffff\nSince: 1.9.0"
			},
			{
				"name": "block-size",
				"description": "Type: number\n滑块的大小,取值范围为 12 - 28\nDefault: 28\nSince: 1.9.0"
			},
			{
				"name": "color",
				"description": "Type: string\n背景条的颜色(请使用 background-color)\nDefault: #e9e9e9"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "max",
				"description": "Type: number\n最大值\nDefault: 100"
			},
			{
				"name": "min",
				"description": "Type: number\n最小值\nDefault: 0"
			},
			{
				"name": "selected-color",
				"description": "Type: string\n已选择的颜色(请使用 active-color)\nDefault: #1aad19"
			},
			{
				"name": "show-value",
				"description": "Type: boolean\n是否显示当前 value\nDefault: false"
			},
			{
				"name": "step",
				"description": "Type: number\n步长,取值必须大于 0,并且可被(max - min)整除\nDefault: 1"
			},
			{
				"name": "value",
				"description": "Type: number\n当前取值\nDefault: 0"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/slider.html"
		}]
	},
	{
		"name": "switch",
		"description": "开关选择器。",
		"attributes": [
			{
				"name": "bindchange",
				"description": "Type: function => any\nchecked 改变时触发 change 事件,event.detail={ value:checked}"
			},
			{
				"name": "checked",
				"description": "Type: boolean\n是否选中\nDefault: false"
			},
			{
				"name": "color",
				"description": "Type: string\nswitch 的颜色,同 css 的 color"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "type",
				"description": "Type: string\n样式,有效值:switch, checkbox\nDefault: switch"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/switch.html"
		}]
	},
	{
		"name": "textarea",
		"description": "多行输入框。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。",
		"attributes": [
			{
				"name": "adjust-position",
				"description": "Type: boolean\n键盘弹起时,是否自动上推页面\nDefault: true\nSince: 1.9.90"
			},
			{
				"name": "auto-focus",
				"description": "Type: boolean\n自动聚焦,拉起键盘。\nDefault: false"
			},
			{
				"name": "auto-height",
				"description": "Type: boolean\n是否自动增高,设置auto-height时,style.height不生效\nDefault: false"
			},
			{
				"name": "bindblur",
				"description": "Type: function => any\n输入框失去焦点时触发,event.detail = {value, cursor}"
			},
			{
				"name": "bindconfirm",
				"description": "Type: function => any\n点击完成时, 触发 confirm 事件,event.detail = {value: value}"
			},
			{
				"name": "bindfocus",
				"description": "Type: function => any\n输入框聚焦时触发,event.detail = { value, height },height 为键盘高度,在基础库 1.9.90 起支持"
			},
			{
				"name": "bindinput",
				"description": "Type: function => any\n当键盘输入时,触发 input 事件,event.detail = {value, cursor},**bindinput 处理函数的返回值并不会反映到 textarea 上**"
			},
			{
				"name": "bindkeyboardheightchange",
				"description": "Type: function => any\n键盘高度发生变化的时候触发此事件,event.detail = {height: height, duration: duration}\nSince: 2.7.0"
			},
			{
				"name": "bindlinechange",
				"description": "Type: function => any\n输入框行数变化时调用,event.detail = {height: 0, heightRpx: 0, lineCount: 0}"
			},
			{
				"name": "confirm-hold",
				"description": "Type: boolean\n点击键盘右下角按钮时是否保持键盘不收起\nDefault: false\nSince: 2.16.0"
			},
			{
				"name": "confirm-type",
				"description": "Type: string\n设置键盘右下角按钮的文字\nDefault: return\nSince: 2.13.0"
			},
			{
				"name": "cursor",
				"description": "Type: number\n指定focus时的光标位置\nSince: 1.5.0"
			},
			{
				"name": "cursor-spacing",
				"description": "Type: number\n指定光标与键盘的距离,单位 px 。取 textarea 距离底部的距离和 cursor-spacing 指定的距离的最小值作为光标与键盘的距离\nDefault: 0"
			},
			{
				"name": "disable-default-padding",
				"description": "Type: boolean\n是否去掉 iOS 下的默认内边距\nDefault: false\nSince: 2.10.0"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false"
			},
			{
				"name": "fixed",
				"description": "Type: boolean\n如果 textarea 是在一个 `position:fixed` 的区域,需要显示指定属性 fixed 为 true\nDefault: false"
			},
			{
				"name": "focus",
				"description": "Type: boolean\n获取焦点\nDefault: false"
			},
			{
				"name": "hold-keyboard",
				"description": "Type: boolean\nfocus时,点击页面的时候不收起键盘\nDefault: false\nSince: 2.8.2"
			},
			{
				"name": "maxlength",
				"description": "Type: number\n最大输入长度,设置为 -1 的时候不限制最大长度\nDefault: 140"
			},
			{
				"name": "placeholder",
				"description": "Type: string\n输入框为空时占位符"
			},
			{
				"name": "placeholder-class",
				"description": "Type: string\n指定 placeholder 的样式类\nDefault: textarea-placeholder"
			},
			{
				"name": "placeholder-style",
				"description": "Type: string\n指定 placeholder 的样式"
			},
			{
				"name": "selection-end",
				"description": "Type: number\n光标结束位置,自动聚集时有效,需与selection-start搭配使用\nDefault: -1\nSince: 1.9.0"
			},
			{
				"name": "selection-start",
				"description": "Type: number\n光标起始位置,自动聚集时有效,需与selection-end搭配使用\nDefault: -1\nSince: 1.9.0"
			},
			{
				"name": "show-confirm-bar",
				"description": "Type: boolean\n是否显示键盘上方带有”完成“按钮那一栏\nDefault: true\nSince: 1.6.0"
			},
			{
				"name": "value",
				"description": "Type: string\n输入框的内容"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/textarea.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/mapAndMovable.ts
const WEAPP_BUILTIN_HTML_TAGS_MAP_AND_MOVABLE = [
	{
		"name": "map",
		"description": "地图。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。 个性化地图能力可在小程序后台“设置-开发者工具-腾讯位置服务”申请开通。 设置subkey后,小程序内的地图组件均会使用该底图效果,底图场景的切换会在后续版本提供。 详见[《小程序个性地图使用指南》](https://lbs.qq.com/product/miniapp/guide/)",
		"attributes": [
			{
				"name": "bindcallouttap",
				"description": "Type: function => any\n点击标记点对应的气泡时触发,会返回marker的id\nSince: 1.2.0"
			},
			{
				"name": "bindcontroltap",
				"description": "Type: function => any\n点击控件时触发,会返回control的id"
			},
			{
				"name": "bindmarkertap",
				"description": "Type: function => any\n点击标记点时触发,会返回marker的id"
			},
			{
				"name": "bindpoitap",
				"description": "Type: function => any\n点击地图poi点时触发\nSince: 2.3.0"
			},
			{
				"name": "bindregionchange",
				"description": "Type: function => any\n视野发生变化时触发\nSince: [2.3.0](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html \"基础库 2.3.0 开始支持,低版本需做兼容处理。\")起增加`causedBy` 参数区分拖动、缩放和调用接口等来源"
			},
			{
				"name": "bindtap",
				"description": "Type: function => any\n点击地图时触发"
			},
			{
				"name": "bindupdated",
				"description": "Type: function => any\n在地图渲染更新完成时触发\nSince: 1.6.0"
			},
			{
				"name": "circles",
				"description": "Type: Object\n圆"
			},
			{
				"name": "controls",
				"description": "Type: Object\n控件(即将废弃,建议使用 [cover-view](https://developers.weixin.qq.com/miniprogram/dev/component/cover-view.html) 代替)"
			},
			{
				"name": "covers",
				"description": "Type: any[]\n**即将移除,请使用 markers**"
			},
			{
				"name": "enable-3D",
				"description": "Type: boolean\n展示3D楼块(工具暂不支持)\nDefault: false\nSince: 2.3.0"
			},
			{
				"name": "enable-overlooking",
				"description": "Type: boolean\n开启俯视\nDefault: false\nSince: 2.3.0"
			},
			{
				"name": "enable-rotate",
				"description": "Type: boolean\n是否支持旋转\nDefault: false\nSince: 2.3.0"
			},
			{
				"name": "enable-scroll",
				"description": "Type: boolean\n是否支持拖动\nDefault: true\nSince: 2.3.0"
			},
			{
				"name": "enable-zoom",
				"description": "Type: boolean\n是否支持缩放\nDefault: true\nSince: 2.3.0"
			},
			{
				"name": "include-points",
				"description": "Type: any[]\n缩放视野以包含所有给定的坐标点"
			},
			{
				"name": "latitude",
				"description": "Type: number\n中心纬度"
			},
			{
				"name": "longitude",
				"description": "Type: number\n中心经度"
			},
			{
				"name": "markers",
				"description": "Type: Object\n标记点"
			},
			{
				"name": "polygons",
				"description": "Type: Object\n多边形\nSince: 2.3.0"
			},
			{
				"name": "polyline",
				"description": "Type: Object\n路线"
			},
			{
				"name": "scale",
				"description": "Type: number\n缩放级别,取值范围为5-18\nDefault: 16"
			},
			{
				"name": "show-compass",
				"description": "Type: boolean\n显示指南针\nDefault: false\nSince: 2.3.0"
			},
			{
				"name": "show-location",
				"description": "Type: boolean\n显示带有方向的当前定位点"
			},
			{
				"name": "subkey",
				"description": "Type: string\n个性化地图使用的key,仅初始化地图时有效\nDefault: ''\nSince: 2.3.0"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/map.html"
		}]
	},
	{
		"name": "movable-area",
		"description": "`movable-view` 的可移动区域",
		"attributes": [{
			"name": "scale-area",
			"description": "Type: boolean\n当里面的movable-view设置为支持双指缩放时,设置此值可将缩放手势生效区域修改为整个movable-area\nDefault: false\nSince: 1.9.90"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/movable-view.html"
		}]
	},
	{
		"name": "movable-view",
		"description": "可移动的视图容器,在页面中可以拖拽滑动",
		"attributes": [
			{
				"name": "animation",
				"description": "Type: boolean\n是否使用动画\nDefault: true\nSince: 2.1.0"
			},
			{
				"name": "bindchange",
				"description": "Type: function => any\n拖动过程中触发的事件,event.detail = {x: x, y: y, source: source},其中source表示产生移动的原因,值可为touch(拖动)、touch-out-of-bounds(超出移动范围)、out-of-bounds(超出移动范围后的回弹)、friction(惯性)和空字符串(setData)\nSince: 1.9.90"
			},
			{
				"name": "bindscale",
				"description": "Type: function => any\n缩放过程中触发的事件,event.detail = {x: x, y: y, scale: scale},其中x和y字段在[2.1.0](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html \"基础库 2.1.0 开始支持,低版本需做兼容处理。\")之后开始支持返回\nSince: 1.9.90"
			},
			{
				"name": "damping",
				"description": "Type: number\n阻尼系数,用于控制x或y改变时的动画和过界回弹的动画,值越大移动越快\nDefault: 20"
			},
			{
				"name": "direction",
				"description": "Type: string\nmovable-view的移动方向,属性值有all、vertical、horizontal、none\nDefault: none"
			},
			{
				"name": "disabled",
				"description": "Type: boolean\n是否禁用\nDefault: false\nSince: 1.9.90"
			},
			{
				"name": "friction",
				"description": "Type: number\n摩擦系数,用于控制惯性滑动的动画,值越大摩擦力越大,滑动越快停止;必须大于0,否则会被设置成默认值\nDefault: 2"
			},
			{
				"name": "htouchmove",
				"description": "Type: function => any\n初次手指触摸后移动为横向的移动,如果catch此事件,则意味着touchmove事件也被catch\nSince: 1.9.90"
			},
			{
				"name": "inertia",
				"description": "Type: boolean\nmovable-view是否带有惯性\nDefault: false"
			},
			{
				"name": "out-of-bounds",
				"description": "Type: boolean\n超过可移动区域后,movable-view是否还可以移动\nDefault: false"
			},
			{
				"name": "scale",
				"description": "Type: boolean\n是否支持双指缩放,默认缩放手势生效区域是在movable-view内\nDefault: false\nSince: 1.9.90"
			},
			{
				"name": "scale-max",
				"description": "Type: number\n定义缩放倍数最大值\nDefault: 10\nSince: 1.9.90"
			},
			{
				"name": "scale-min",
				"description": "Type: number\n定义缩放倍数最小值\nDefault: 0.5\nSince: 1.9.90"
			},
			{
				"name": "scale-value",
				"description": "Type: number\n定义缩放倍数,取值范围为 0.5 - 10\nDefault: 1\nSince: 1.9.90"
			},
			{
				"name": "vtouchmove",
				"description": "Type: function => any\n初次手指触摸后移动为纵向的移动,如果catch此事件,则意味着touchmove事件也被catch\nSince: 1.9.90"
			},
			{
				"name": "x",
				"description": "Type: number | string\n定义x轴方向的偏移,如果x的值不在可移动范围内,会自动移动到可移动范围;改变x的值会触发动画"
			},
			{
				"name": "y",
				"description": "Type: number | string\n定义y轴方向的偏移,如果y的值不在可移动范围内,会自动移动到可移动范围;改变y的值会触发动画"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/movable-view.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/mediaCaptureLive.ts
const WEAPP_BUILTIN_HTML_TAGS_MEDIA_CAPTURE_LIVE = [
	{
		"name": "camera",
		"description": "系统相机。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: function => any\n用户不允许使用摄像头时触发"
			},
			{
				"name": "bindscancode",
				"description": "Type: function => any\n在成功识别到一维码时触发,仅在 mode=\"scanCode\" 时生效\nSince: 2.1.0"
			},
			{
				"name": "bindstop",
				"description": "Type: function => any\n摄像头在非正常终止时触发,如退出后台等情况"
			},
			{
				"name": "device-position",
				"description": "Type: string\n前置或后置,值为front, back\nDefault: back"
			},
			{
				"name": "flash",
				"description": "Type: string\n闪光灯,值为auto, on, off\nDefault: auto"
			},
			{
				"name": "mode",
				"description": "Type: string\n有效值为 normal, scanCode\nDefault: normal\nSince: 2.1.0"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/camera.html"
		}]
	},
	{
		"name": "canvas",
		"description": "画布。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: function => any\n当发生错误时触发 error 事件,detail = {errMsg: 'something wrong'}"
			},
			{
				"name": "bindlongtap",
				"description": "Type: function => any\n手指长按 500ms 之后触发,触发了长按事件后进行移动不会触发屏幕的滚动"
			},
			{
				"name": "bindtouchcancel",
				"description": "Type: function => any\n手指触摸动作被打断,如来电提醒,弹窗"
			},
			{
				"name": "bindtouchend",
				"description": "Type: function => any\n手指触摸动作结束"
			},
			{
				"name": "bindtouchmove",
				"description": "Type: function => any\n手指触摸后移动"
			},
			{
				"name": "bindtouchstart",
				"description": "Type: function => any\n手指触摸动作开始"
			},
			{
				"name": "canvas-id",
				"description": "Type: string\ncanvas 组件的唯一标识符"
			},
			{
				"name": "disable-scroll",
				"description": "Type: boolean\n当在 canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新\nDefault: false"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html"
		}]
	},
	{
		"name": "live-player",
		"description": "实时音视频播放。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。\n\n暂只针对国内主体如下类目的小程序开放,需要先通过类目审核,再在小程序管理后台,“设置”-“接口设置”中自助开通该组件权限。\n\n{社交 => \"直播\"; 教育 => \"在线教育\"; 医疗 => \"互联网医院,公立医院\"; 政务民生 => \"所有二级类目\"; 金融 =\\> \"基金、信托、保险、银行、证券/期货、非金融机构自营小额贷款、征信业务、消费金融\"}",
		"attributes": [
			{
				"name": "autoplay",
				"description": "Type: boolean\n自动播放\nDefault: false"
			},
			{
				"name": "background-mute",
				"description": "Type: boolean\n进入后台时是否静音(已废弃,默认退台静音)\nDefault: false"
			},
			{
				"name": "bindfullscreenchange",
				"description": "Type: function => any\n全屏变化事件,detail = {direction, fullScreen}"
			},
			{
				"name": "bindnetstatus",
				"description": "Type: function => any\n网络状态通知,detail = {info}\ninfo: {videoBitrate => \"当前视频编/码器输出的比特率,单位 kbps\"; audioBitrate => \"当前音频编/码器输出的比特率,单位 kbps\"; videoFPS => \"当前视频帧率\"; videoGOP => \"当前视频 GOP,也就是每两个关键帧(I帧)间隔时长,单位 s\"; netSpeed => \"当前的发送/接收速度\"; netJitter => \"网络抖动情况,抖动越大,网络越不稳定\"; videoWidth => \"视频画面的宽度\"; videoHeight => \"视频画面的高度\"}\nSince: 1.9.0"
			},
			{
				"name": "bindstatechange",
				"description": "Type: function => any\n播放状态变化事件,detail = {code}\ncode: {2001 => \"已经连接服务器\"; 2002 => \"已经连接服务器,开始拉流\"; 2003 => \"网络接收到首个视频数据包(IDR)\"; 2004 => \"视频播放开始\"; 2005 => \"视频播放进度\"; 2006 => \"视频播放结束\"; 2007 => \"视频播放Loading\"; 2008 => \"解码器启动\"; 2009 => \"视频分辨率改变\"; -2301 => \"网络断连,且经多次重连抢救无效,更多重试请自行重启播放\"; -2302 => \"获取加速拉流地址失败\"; 2101 => \"当前视频帧解码失败\"; 2102 => \"当前音频帧解码失败\"; 2103 => \"网络断连, 已启动自动重连\"; 2104 => \"网络来包不稳:可能是下行带宽不足,或由于主播端出流不均匀\"; 2105 => \"当前视频播放出现卡顿\"; 2106 => \"硬解启动失败,采用软解\"; 2107 => \"当前视频帧不连续,可能丢帧\"; 2108 => \"当前流硬解第一个I帧失败,SDK自动切软解\"; 3001 => \"RTMP -DNS解析失败\"; 3002 => \"RTMP服务器连接失败\"; 3003 => \"RTMP服务器握手失败\"; 3005 => \"RTMP 读/写失败\"}"
			},
			{
				"name": "max-cache",
				"description": "Type: number\n最大缓冲区,单位s\nDefault: 3"
			},
			{
				"name": "min-cache",
				"description": "Type: number\n最小缓冲区,单位s\nDefault: 1"
			},
			{
				"name": "mode",
				"description": "Type: string\nlive(直播),RTC(实时通话)\nDefault: live"
			},
			{
				"name": "muted",
				"description": "Type: boolean\n是否静音\nDefault: false"
			},
			{
				"name": "object-fit",
				"description": "Type: string\n填充模式,可选值有 contain,fillCrop\nDefault: contain"
			},
			{
				"name": "orientation",
				"description": "Type: string\n画面方向,可选值有 vertical,horizontal\nDefault: vertical"
			},
			{
				"name": "src",
				"description": "Type: string\n音视频地址。目前仅支持 flv, rtmp 格式"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/live-player.html"
		}]
	},
	{
		"name": "live-pusher",
		"description": "实时音视频录制。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。\n\n暂只针对国内主体如下类目的小程序开放,需要先通过类目审核,再在小程序管理后台,“设置”-“接口设置”中自助开通该组件权限。\n\n{社交 => \"直播\"; 教育 => \"在线教育\"; 医疗 => \"互联网医院,公立医院\"; 政务民生 => \"所有二级类目\"; 金融 =\\> \"基金、信托、保险、银行、证券/期货、非金融机构自营小额贷款、征信业务、消费金融\"}",
		"attributes": [
			{
				"name": "aspect",
				"description": "Type: string\n宽高比,可选值有 3:4, 9:16\nDefault: 9:16"
			},
			{
				"name": "auto-focus",
				"description": "Type: boolean\n自动聚集\nDefault: true"
			},
			{
				"name": "autopush",
				"description": "Type: boolean\n自动推流\nDefault: false"
			},
			{
				"name": "background-mute",
				"description": "Type: boolean\n进入后台时是否静音\nDefault: false"
			},
			{
				"name": "beauty",
				"description": "Type: number\n美颜\nDefault: 0"
			},
			{
				"name": "binderror",
				"description": "Type: function => any\n渲染错误事件,detail = {errMsg, errCode}\nerrCode: {10001 => \"用户禁止使用摄像头\"; 10002 => \"用户禁止使用录音\"}\nSince: 1.7.4"
			},
			{
				"name": "bindnetstatus",
				"description": "Type: function => any\n网络状态通知,detail = {info}\ninfo: {videoBitrate => \"当前视频编/码器输出的比特率,单位 kbps\"; audioBitrate => \"当前音频编/码器输出的比特率,单位 kbps\"; videoFPS => \"当前视频帧率\"; videoGOP => \"当前视频 GOP,也就是每两个关键帧(I帧)间隔时长,单位 s\"; netSpeed => \"当前的发送/接收速度\"; netJitter => \"网络抖动情况,抖动越大,网络越不稳定\"; videoWidth => \"视频画面的宽度\"; videoHeight => \"视频画面的高度\"}\nSince: 1.9.0"
			},
			{
				"name": "bindstatechange",
				"description": "Type: function => any\n状态变化事件,detail = {code}\ncode: {1001 => \"已经连接推流服务器\"; 1002 => \"已经与服务器握手完毕,开始推流\"; 1003 => \"打开摄像头成功\"; 1004 => \"录屏启动成功\"; 1005 => \"推流动态调整分辨率\"; 1006 => \"推流动态调整码率\"; 1007 => \"首帧画面采集完成\"; 1008 => \"编码器启动\"; -1301 => \"打开摄像头失败\"; -1302 => \"打开麦克风失败\"; -1303 => \"视频编码失败\"; -1304 => \"音频编码失败\"; -1305 => \"不支持的视频分辨率\"; -1306 => \"不支持的音频采样率\"; -1307 => \"网络断连,且经多次重连抢救无效,更多重试请自行重启推流\"; -1308 => \"开始录屏失败,可能是被用户拒绝\"; -1309 => \"录屏失败,不支持的Android系统版本,需要5.0以上的系统\"; -1310 => \"录屏被其他应用打断了\"; -1311 => \"Android Mic打开成功,但是录不到音频数据\"; -1312 => \"录屏动态切横竖屏失败\"; 1101 => \"网络状况不佳:上行带宽太小,上传数据受阻\"; 1102 => \"网络断连, 已启动自动重连\"; 1103 => \"硬编码启动失败,采用软编码\"; 1104 => \"视频编码失败\"; 1105 => \"新美颜软编码启动失败,采用老的软编码\"; 1106 => \"新美颜软编码启动失败,采用老的软编码\"; 3001 => \"RTMP -DNS解析失败\"; 3002 => \"RTMP服务器连接失败\"; 3003 => \"RTMP服务器握手失败\"; 3004 => \"RTMP服务器主动断开,请检查推流地址的合法性或防盗链有效期\"; 3005 => \"RTMP 读/写失败\"}"
			},
			{
				"name": "device-position",
				"description": "Type: string\n前置或后置,值为front, back\nDefault: front\nSince: 2.3.0"
			},
			{
				"name": "enable-camera",
				"description": "Type: boolean\n开启摄像头\nDefault: true"
			},
			{
				"name": "max-bitrate",
				"description": "Type: number\n最大码率\nDefault: 1000"
			},
			{
				"name": "min-bitrate",
				"description": "Type: number\n最小码率\nDefault: 200"
			},
			{
				"name": "mode",
				"description": "Type: string\nSD(标清), HD(高清), FHD(超清), RTC(实时通话)\nDefault: RTC"
			},
			{
				"name": "muted",
				"description": "Type: boolean\n是否静音\nDefault: false"
			},
			{
				"name": "orientation",
				"description": "Type: string\nvertical,horizontal\nDefault: vertical"
			},
			{
				"name": "url",
				"description": "Type: string\n推流地址。目前仅支持 flv, rtmp 格式"
			},
			{
				"name": "waiting-image",
				"description": "Type: string\n进入后台时推流的等待画面"
			},
			{
				"name": "waiting-image-hash",
				"description": "Type: string\n等待画面资源的MD5值"
			},
			{
				"name": "whiteness",
				"description": "Type: number\n美白\nDefault: 0"
			},
			{
				"name": "zoom",
				"description": "Type: boolean\n调整焦距\nDefault: false\nSince: 2.1.0"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/live-pusher.html"
		}]
	},
	{
		"name": "voip-room",
		"description": "多人音视频对话。\n暂只针对国内主体[如下类目](https://developers.weixin.qq.com/miniprogram/dev/component/voip-room.html)的小程序开放,需要先通过类目审核,再在小程序管理后台,「开发」-「接口设置」中自助开通该组件权限。",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: eventhandle\n创建对话窗口失败时触发"
			},
			{
				"name": "device-position",
				"description": "Type: string\n仅在 mode 为 camera 时有效,前置或后置,值为`front`,`back`\nDefault: front",
				"values": [{
					"name": "front",
					"description": "前置"
				}, {
					"name": "back",
					"description": "后置"
				}]
			},
			{
				"name": "mode",
				"description": "Type: string\n对话窗口类型,自身传入 camera,其它用户传入 video\nDefault: camera"
			},
			{
				"name": "openid",
				"description": "Type: string\n进入房间用户的 openid"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/voip-room.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/mediaPlayback.ts
const WEAPP_BUILTIN_HTML_TAGS_MEDIA_PLAYBACK = [
	{
		"name": "audio",
		"description": "音频。",
		"attributes": [
			{
				"name": "author",
				"description": "Type: string\n默认控件上的作者名字,如果 controls 属性值为 false 则设置 author 无效\nDefault: 未知作者"
			},
			{
				"name": "bindended",
				"description": "Type: function => any\n当播放到末尾时触发 ended 事件"
			},
			{
				"name": "binderror",
				"description": "Type: function => any\n当发生错误时触发 error 事件,detail = {errMsg: MediaError.code}\nMediaError.code: {1 => \"获取资源被用户禁止\"; 2 => \"网络错误\"; 3 => \"解码错误\"; 4 => \"不合适资源\"}"
			},
			{
				"name": "bindpause",
				"description": "Type: function => any\n当暂停播放时触发 pause 事件"
			},
			{
				"name": "bindplay",
				"description": "Type: function => any\n当开始/继续播放时触发play事件"
			},
			{
				"name": "bindtimeupdate",
				"description": "Type: function => any\n当播放进度改变时触发 timeupdate 事件,detail = {currentTime, duration}"
			},
			{
				"name": "controls",
				"description": "Type: boolean\n是否显示默认控件\nDefault: false"
			},
			{
				"name": "id",
				"description": "Type: string\naudio 组件的唯一标识符"
			},
			{
				"name": "loop",
				"description": "Type: boolean\n是否循环播放\nDefault: false"
			},
			{
				"name": "name",
				"description": "Type: string\n默认控件上的音频名字,如果 controls 属性值为 false 则设置 name 无效\nDefault: 未知音频"
			},
			{
				"name": "poster",
				"description": "Type: string\n默认控件上的音频封面的图片资源地址,如果 controls 属性值为 false 则设置 poster 无效"
			},
			{
				"name": "src",
				"description": "Type: string\n要播放音频的资源地址"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/audio.html"
		}]
	},
	{
		"name": "image",
		"description": "图片。",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: function => any\n当错误发生时,发布到 AppService 的事件名,事件对象event.detail = {errMsg: 'something wrong'}"
			},
			{
				"name": "bindload",
				"description": "Type: function => any\n当图片载入完毕时,发布到 AppService 的事件名,事件对象event.detail = {height:'图片高度px', width:'图片宽度px'}"
			},
			{
				"name": "lazy-load",
				"description": "Type: boolean\n图片懒加载。只针对page与scroll-view下的image有效\nDefault: false\nSince: 1.5.0"
			},
			{
				"name": "mode",
				"description": "Type: string\n图片裁剪、缩放的模式\nDefault: 'scaleToFill'",
				"values": [
					{
						"name": "scaleToFill",
						"description": "缩放: 不保持纵横比缩放图片,使图片的宽高完全拉伸至填满 image 元素"
					},
					{
						"name": "aspectFit",
						"description": "缩放: 保持纵横比缩放图片,使图片的长边能完全显示出来。也就是说,可以完整地将图片显示出来。"
					},
					{
						"name": "aspectFill",
						"description": "缩放: 保持纵横比缩放图片,只保证图片的短边能完全显示出来。也就是说,图片通常只在水平或垂直方向是完整的,另一个方向将会发生截取。"
					},
					{
						"name": "widthFix",
						"description": "缩放: 宽度不变,高度自动变化,保持原图宽高比不变"
					},
					{
						"name": "heightFix",
						"description": "缩放模式,高度不变,宽度自动变化,保持原图宽高比不变"
					},
					{
						"name": "top",
						"description": "裁剪: 不缩放图片,只显示图片的顶部区域"
					},
					{
						"name": "bottom",
						"description": "裁剪: 不缩放图片,只显示图片的底部区域"
					},
					{
						"name": "center",
						"description": "裁剪: 不缩放图片,只显示图片的中间区域"
					},
					{
						"name": "left",
						"description": "裁剪: 不缩放图片,只显示图片的左边区域"
					},
					{
						"name": "right",
						"description": "裁剪: 不缩放图片,只显示图片的右边区域"
					},
					{
						"name": "top left",
						"description": "裁剪: 不缩放图片,只显示图片的左上边区域"
					},
					{
						"name": "top right",
						"description": "裁剪: 不缩放图片,只显示图片的右上边区域"
					},
					{
						"name": "bottom left",
						"description": "裁剪: 不缩放图片,只显示图片的左下边区域"
					},
					{
						"name": "bottom right",
						"description": "裁剪: 不缩放图片,只显示图片的右下边区域"
					}
				]
			},
			{
				"name": "src",
				"description": "Type: string\n图片资源地址,支持云文件ID(2.2.3起)"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/image.html"
		}]
	},
	{
		"name": "video",
		"description": "视频。该组件是[原生组件](https://developers.weixin.qq.com/miniprogram/dev/component/native-component.html),使用时请注意相关限制。\n\n`<video />` 默认宽度300px、高度225px,可通过wxss设置宽高。",
		"attributes": [
			{
				"name": "ad-unit-id",
				"description": "Type: string\n视频前贴广告单元ID,更多详情可参考开放能力视频前贴广告\nSince: 2.8.1"
			},
			{
				"name": "auto-pause-if-navigate",
				"description": "Type: boolean\n当跳转到本小程序的其他页面时,是否自动暂停本页面的视频播放\nDefault: true\nSince: 2.5.0"
			},
			{
				"name": "auto-pause-if-open-native",
				"description": "Type: boolean\n当跳转到其它微信原生页面时,是否自动暂停本页面的视频\nDefault: true\nSince: 2.5.0"
			},
			{
				"name": "autoplay",
				"description": "Type: boolean\n是否自动播放\nDefault: false"
			},
			{
				"name": "background-poster",
				"description": "Type: string\n进入后台音频播放后的通知栏图标(Android 独有)\nSince: 2.14.3"
			},
			{
				"name": "bindcontrolstoggle",
				"description": "Type: function => any\n切换 controls 显示隐藏时触发。event.detail = {show}\nSince: 2.9.5"
			},
			{
				"name": "bindended",
				"description": "Type: function => any\n当播放到末尾时触发 ended 事件"
			},
			{
				"name": "bindenterpictureinpicture",
				"description": "Type: function => any\n播放器进入小窗\nSince: 2.11.0"
			},
			{
				"name": "binderror",
				"description": "Type: function => any\n视频播放出错时触发\nSince: 1.7.0"
			},
			{
				"name": "bindfullscreenchange",
				"description": "Type: function => any\n视频进入和退出全屏时触发,event.detail = {fullScreen, direction},direction取为 vertical 或 horizontal\nSince: 1.4.0"
			},
			{
				"name": "bindleavepictureinpicture",
				"description": "Type: function => any\n播放器退出小窗\nSince: 2.11.0"
			},
			{
				"name": "bindloadedmetadata",
				"description": "Type: function => any\n视频元数据加载完成时触发。event.detail = {width, height, duration}\nSince: 2.7.0"
			},
			{
				"name": "bindpause",
				"description": "Type: function => any\n当暂停播放时触发 pause 事件"
			},
			{
				"name": "bindplay",
				"description": "Type: function => any\n当开始/继续播放时触发play事件"
			},
			{
				"name": "bindprogress",
				"description": "Type: function => any\n加载进度变化时触发,只支持一段加载。event.detail = {buffered},百分比\nSince: 2.4.0"
			},
			{
				"name": "bindseekcomplete",
				"description": "Type: function => any\nseek 完成时触发 (position iOS 单位 s, Android 单位 ms)\nSince: 2.12.0"
			},
			{
				"name": "bindtimeupdate",
				"description": "Type: function => any\n播放进度变化时触发,event.detail = {currentTime, duration} 。触发频率 250ms 一次"
			},
			{
				"name": "bindwaiting",
				"description": "Type: function => any\n视频出现缓冲时触发\nSince: 1.7.0"
			},
			{
				"name": "certificate-url",
				"description": "Type: string\nDRM 设备身份认证 url,仅 is-drm 为 true 时生效 (iOS)\nSince: 2.19.3"
			},
			{
				"name": "controls",
				"description": "Type: boolean\n是否显示默认播放控件(播放/暂停按钮、播放进度、时间)\nDefault: true"
			},
			{
				"name": "danmu-btn",
				"description": "Type: boolean\n是否显示弹幕按钮,只在初始化时有效,不能动态变更\nDefault: false"
			},
			{
				"name": "danmu-list",
				"description": "Type: ArrayObject\n弹幕列表"
			},
			{
				"name": "direction",
				"description": "Type: number\n设置全屏时视频的方向,不指定则根据宽高比自动判断。有效值为 0(正常竖向), 90(屏幕逆时针90度), -90(屏幕顺时针90度)\nSince: 1.7.0"
			},
			{
				"name": "duration",
				"description": "Type: number\n指定视频时长\nSince: 1.1.0"
			},
			{
				"name": "enable-auto-rotation",
				"description": "Type: boolean\n是否开启手机横屏时自动全屏,当系统设置开启自动旋转时生效\nDefault: false\nSince: 2.11.0"
			},
			{
				"name": "enable-danmu",
				"description": "Type: boolean\n是否展示弹幕,只在初始化时有效,不能动态变更\nDefault: false"
			},
			{
				"name": "enable-play-gesture",
				"description": "Type: boolean\n是否开启播放手势,即双击切换播放/暂停\nDefault: false\nSince: 2.4.0"
			},
			{
				"name": "enable-progress-gesture",
				"description": "Type: boolean\n是否开启控制进度的手势\nDefault: true\nSince: 1.9.0"
			},
			{
				"name": "initial-time",
				"description": "Type: number\n指定视频初始播放位置\nSince: 1.6.0"
			},
			{
				"name": "is-drm",
				"description": "Type: boolean\n是否是 DRM 视频源\nSince: 2.19.3"
			},
			{
				"name": "license-url",
				"description": "Type: string\nDRM 获取加密信息 url,仅 is-drm 为 true 时生效\nSince: 2.19.3"
			},
			{
				"name": "loop",
				"description": "Type: boolean\n是否循环播放\nDefault: false\nSince: 1.4.0"
			},
			{
				"name": "muted",
				"description": "Type: boolean\n是否静音播放\nDefault: false\nSince: 1.4.0"
			},
			{
				"name": "object-fit",
				"description": "Type: string\n当视频大小与 video 容器大小不一致时,视频的表现形式。contain:包含,fill:填充,cover:覆盖\nDefault: contain"
			},
			{
				"name": "page-gesture",
				"description": "Type: boolean\n在非全屏模式下,是否开启亮度与音量调节手势\nDefault: false\nSince: 1.6.0"
			},
			{
				"name": "picture-in-picture-mode",
				"description": "Type: string/Array\n设置小窗模式: push, pop,空字符串或通过数组形式设置多种模式(如: [\"push\", \"pop\"])\nSince: 2.11.0"
			},
			{
				"name": "picture-in-picture-show-progress",
				"description": "Type: boolean\n是否在小窗模式下显示播放进度\nDefault: false\nSince: 2.11.0"
			},
			{
				"name": "play-btn-position",
				"description": "Type: string\n播放按钮的位置\nDefault: bottom\nSince: 2.4.0"
			},
			{
				"name": "poster",
				"description": "Type: string\n视频封面的图片网络资源地址或云文件ID(2.2.3起支持)如果 controls 属性值为 false 则设置 poster 无效"
			},
			{
				"name": "poster-for-crawler",
				"description": "Type: string\n用于给搜索等场景作为视频封面展示,建议使用无播放 icon 的视频封面图,只支持网络地址"
			},
			{
				"name": "provision-url",
				"description": "Type: string\nDRM 设备身份认证 url,仅 is-drm 为 true 时生效 (Android)\nSince: 2.19.3"
			},
			{
				"name": "referrer-policy",
				"description": "Type: string\n格式固定为 https://servicewechat.com/{appid}/{version}/page-frame.html,其中 {appid} 为小程序的 appid,{version} 为小程序的版本号,版本号为 0 表示为开发版、体验版以及审核版本,版本号为 devtools 表示为开发者工具,其余为正式版本;\nDefault: no-referrer\nSince: 2.13.0"
			},
			{
				"name": "show-background-playback-button",
				"description": "Type: boolean\n是否展示后台音频播放按钮\nDefault: false\nSince: 2.14.3"
			},
			{
				"name": "show-casting-button",
				"description": "Type: boolean\n显示投屏按钮。安卓在同层渲染下生效,支持 DLNA 协议;iOS 支持 AirPlay 和 DLNA 协议\nDefault: false\nSince: 2.10.2"
			},
			{
				"name": "show-center-play-btn",
				"description": "Type: boolean\n是否显示视频中间的播放按钮\nDefault: true\nSince: 1.9.0"
			},
			{
				"name": "show-fullscreen-btn",
				"description": "Type: boolean\n是否显示全屏按钮\nDefault: true\nSince: 1.9.0"
			},
			{
				"name": "show-mute-btn",
				"description": "Type: boolean\n是否显示静音按钮\nDefault: false\nSince: 2.4.0"
			},
			{
				"name": "show-play-btn",
				"description": "Type: boolean\n是否显示视频底部控制栏的播放按钮\nDefault: true\nSince: 1.9.0"
			},
			{
				"name": "show-progress",
				"description": "Type: boolean\n若不设置,宽度大于240时才会显示\nDefault: true\nSince: 1.9.0"
			},
			{
				"name": "show-screen-lock-button",
				"description": "Type: boolean\n是否显示锁屏按钮,仅在全屏时显示,锁屏后控制栏的操作\nDefault: false\nSince: 2.11.0"
			},
			{
				"name": "show-snapshot-button",
				"description": "Type: boolean\n是否显示截屏按钮,仅在全屏时显示\nDefault: false\nSince: 2.13.0"
			},
			{
				"name": "src",
				"description": "Type: string\n要播放视频的资源地址,支持云文件ID(2.2.3起)"
			},
			{
				"name": "title",
				"description": "Type: string\n视频的标题,全屏时在顶部展示\nSince: 2.4.0"
			},
			{
				"name": "vslide-gesture",
				"description": "Type: boolean\n在非全屏模式下,是否开启亮度与音量调节手势(同 page-gesture)\nDefault: false\nSince: 2.6.2"
			},
			{
				"name": "vslide-gesture-in-fullscreen",
				"description": "Type: boolean\n在全屏模式下,是否开启亮度与音量调节手势\nDefault: true\nSince: 2.6.2"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/video.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/templatesAndNavigation.ts
const WEAPP_BUILTIN_HTML_TAGS_TEMPLATES_AND_NAVIGATION = [
	{
		"name": "functional-page-navigator",
		"description": "这个组件从小程序基础库版本 [2.1.0](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html \"基础库 2.1.0 开始支持,低版本需做兼容处理。\") 开始支持。\n\n仅在插件的自定义组件中有效,用于跳转到插件功能页。",
		"attributes": [
			{
				"name": "args",
				"description": "Type: Object\n功能页参数,参数格式与具体功能页相关\nDefault: null\nSince: 2.1.0"
			},
			{
				"name": "bindfail",
				"description": "Type: function => any\n功能页返回,且操作失败时触发, detail 格式与具体功能页相关\nSince: 2.1.0"
			},
			{
				"name": "bindsuccess",
				"description": "Type: function => any\n功能页返回,且操作成功时触发, detail 格式与具体功能页相关\nSince: 2.1.0"
			},
			{
				"name": "name",
				"description": "Type: string\n要跳转到的功能页\n目前支持的功能页和name可选值: {loginAndGetUserInfo => \"[用户信息功能页](https://developers.weixin.qq.com/miniprogram/dev/framework/plugin/functional-pages/user-info.html)\"; requestPayment => \"[支付功能页](https://developers.weixin.qq.com/miniprogram/dev/framework/plugin/functional-pages/request-payment.html)\"}\nSince: 2.1.0"
			},
			{
				"name": "version",
				"description": "Type: string\n跳转到的小程序版本,有效值 `develop`(开发版),`trial`(体验版),`release`(正式版);**线上版本必须设置为 `release`**\nDefault: release\nSince: 2.1.0"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/functional-page-navigator.html"
		}]
	},
	{
		"name": "import",
		"description": "`import`有作用域的概念,即只会`import`目标文件中定义的`template`,而不会`import`目标文件`import`的`template`",
		"attributes": [{
			"name": "src",
			"description": "Type: string"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/import.html"
		}]
	},
	{
		"name": "include",
		"description": "`include`可以将目标文件除了 `<template />` `<wxs />` 外的整个代码引入,相当于是拷贝到`include`位置",
		"attributes": [{
			"name": "src",
			"description": "Type: string"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/import.html#include"
		}]
	},
	{
		"name": "navigator",
		"description": "页面链接。",
		"attributes": [
			{
				"name": "app-id",
				"description": "Type: string\n当target=\"miniProgram\"时有效,要打开的小程序 appId\nSince: 2.0.7"
			},
			{
				"name": "bindcomplete",
				"description": "Type: string\n当target=\"miniProgram\"时有效,跳转小程序完成\nSince: 2.0.7"
			},
			{
				"name": "bindfail",
				"description": "Type: string\n当target=\"miniProgram\"时有效,跳转小程序失败\nSince: 2.0.7"
			},
			{
				"name": "bindsuccess",
				"description": "Type: string\n当target=\"miniProgram\"时有效,跳转小程序成功\nSince: 2.0.7"
			},
			{
				"name": "delta",
				"description": "Type: number\n当 open-type 为 'navigateBack' 时有效,表示回退的层数"
			},
			{
				"name": "extra-data",
				"description": "Type: Object\n当target=\"miniProgram\"时有效,需要传递给目标小程序的数据,目标小程序可在 `App.onLaunch()`,`App.onShow()` 中获取到这份数据。[详情](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/app.html)\nSince: 2.0.7"
			},
			{
				"name": "hover-class",
				"description": "Type: string\n指定点击时的样式类,当`hover-class=\"none\"`时,没有点击态效果\nDefault: navigator-hover"
			},
			{
				"name": "hover-start-time",
				"description": "Type: number\n按住后多久出现点击态,单位毫秒\nDefault: 50"
			},
			{
				"name": "hover-stay-time",
				"description": "Type: number\n手指松开后点击态保留时间,单位毫秒\nDefault: 600"
			},
			{
				"name": "hover-stop-propagation",
				"description": "Type: boolean\n指定是否阻止本节点的祖先节点出现点击态\nDefault: false\nSince: 1.5.0"
			},
			{
				"name": "open-type",
				"description": "Type: string\n跳转方式\nDefault: navigate",
				"values": [
					{
						"name": "navigate",
						"description": "对应 `wx.navigateTo` 或 `wx.navigateToMiniProgram` 的功能"
					},
					{
						"name": "redirect",
						"description": "对应 `wx.redirectTo` 的功能"
					},
					{
						"name": "switchTab",
						"description": "对应 `wx.switchTab` 的功能"
					},
					{
						"name": "reLaunch",
						"description": "对应 `wx.reLaunch` 的功能"
					},
					{
						"name": "navigateBack",
						"description": "对应 `wx.navigateBack` 的功能"
					},
					{
						"name": "exit",
						"description": "退出小程序,target=\"miniProgram\"时生效"
					}
				]
			},
			{
				"name": "path",
				"description": "Type: string\n当target=\"miniProgram\"时有效,打开的页面路径,如果为空则打开首页\nSince: 2.0.7"
			},
			{
				"name": "short-link",
				"description": "Type: string\n当target=\"miniProgram\"时有效,当传递该参数后,可以不传 app-id 和 path。链接可以通过【小程序菜单】->【复制链接】获取。\nSince: 2.18.1"
			},
			{
				"name": "target",
				"description": "Type: string\n在哪个目标上发生跳转,默认当前小程序,可选值self/miniProgram\nDefault: self\nSince: 2.0.7"
			},
			{
				"name": "url",
				"description": "Type: string\n当前小程序内的跳转链接"
			},
			{
				"name": "version",
				"description": "Type: string\n当target=\"miniProgram\"时有效,要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版),仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是正式版,则打开的小程序必定是正式版。\nDefault: release\nSince: 2.0.7"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/navigator.html"
		}]
	},
	{
		"name": "slot",
		"description": "用于承载组件使用者提供的wxml结构",
		"attributes": [{
			"name": "name",
			"description": "Type: string"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#%E7%BB%84%E4%BB%B6-wxml-%E7%9A%84-slot"
		}]
	},
	{
		"name": "template",
		"attributes": [
			{
				"name": "data",
				"description": "Type: any"
			},
			{
				"name": "is",
				"description": "Type: string"
			},
			{
				"name": "name",
				"description": "Type: string"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/template.html"
		}]
	},
	{
		"name": "web-view",
		"description": "web-view 组件是一个可以用来承载网页的容器,会自动铺满整个小程序页面。**个人类型与海外类型的小程序暂不支持使用。**",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: function => any\n网页加载失败的时候触发此事件。e.detail = { src }"
			},
			{
				"name": "bindload",
				"description": "Type: function => any\n网页加载成功时候触发此事件。e.detail = { src }"
			},
			{
				"name": "bindmessage",
				"description": "Type: function => any\n网页向小程序 postMessage 时,会在特定时机(小程序后退、组件销毁、分享)触发并收到消息。e.detail = { data }"
			},
			{
				"name": "src",
				"description": "Type: string\nwebview 指向网页的链接。可打开关联的公众号的文章,其它网页需登录[小程序管理后台](https://mp.weixin.qq.com/)配置业务域名。"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/visualView.ts
const WEAPP_BUILTIN_HTML_TAGS_VISUAL_VIEW = [
	{
		"name": "cover-image",
		"description": "覆盖在原生组件之上的图片视图,可覆盖的原生组件同`cover-view`,支持嵌套在cover-view里。",
		"attributes": [
			{
				"name": "binderror",
				"description": "Type: function => any\n图片加载失败时触发\nSince: 2.1.0"
			},
			{
				"name": "bindload",
				"description": "Type: function => any\n图片加载成功时触发\nSince: 2.1.0"
			},
			{
				"name": "src",
				"description": "Type: string\n图标路径,支持临时路径、网络地址(1.6.0起支持)、云文件ID(2.2.3起支持)。暂不支持base64格式。"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/cover-view.html"
		}]
	},
	{
		"name": "cover-view",
		"description": "覆盖在原生组件之上的文本视图,可覆盖的原生组件包括`map`、`video`、`canvas`、`camera`、`live-player`、`live-pusher`,只支持嵌套`cover-view`、`cover-image`,可在`cover-view`中使用`button`。",
		"attributes": [{
			"name": "scroll-top",
			"description": "Type: number\n设置顶部滚动偏移量,仅在设置了 overflow-y: scroll 成为滚动元素后生效\nSince: 2.1.0"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/cover-view.html"
		}]
	},
	{
		"name": "icon",
		"description": "图标。",
		"attributes": [
			{
				"name": "color",
				"description": "Type: string\nicon的颜色,同css的color"
			},
			{
				"name": "size",
				"description": "Type: number\nicon的大小,单位px\nDefault: 23"
			},
			{
				"name": "type",
				"description": "Type: string\nicon的类型,有效值:success, success_no_circle, info, warn, waiting, cancel, download, search, clear"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/icon.html"
		}]
	},
	{
		"name": "rich-text",
		"description": "富文本。\n\n支持默认事件,包括:`tap`、`touchstart`、`touchmove`、`touchcancel`、`touchend`和`longtap`",
		"attributes": [{
			"name": "nodes",
			"description": "Type: any[] | string\n节点列表 / HTML String\nSince: 1.4.0"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/rich-text.html"
		}]
	},
	{
		"name": "scroll-view",
		"description": "可滚动视图区域。\n\n使用竖向滚动时,需要给`<scroll-view/>`一个固定高度,通过 WXSS 设置 height。",
		"attributes": [
			{
				"name": "bindscroll",
				"description": "Type: function => any\n滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}"
			},
			{
				"name": "bindscrolltolower",
				"description": "Type: function => any\n滚动到底部/右边,会触发 scrolltolower 事件"
			},
			{
				"name": "bindscrolltoupper",
				"description": "Type: function => any\n滚动到顶部/左边,会触发 scrolltoupper 事件"
			},
			{
				"name": "enable-back-to-top",
				"description": "Type: boolean\niOS点击顶部状态栏、安卓双击标题栏时,滚动条返回顶部,只支持竖向\nDefault: false"
			},
			{
				"name": "lower-threshold",
				"description": "Type: number\n距底部/右边多远时(单位px),触发 scrolltolower 事件\nDefault: 50"
			},
			{
				"name": "scroll-into-view",
				"description": "Type: string\n值应为某子元素id(id不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素"
			},
			{
				"name": "scroll-left",
				"description": "Type: number\n设置横向滚动条位置"
			},
			{
				"name": "scroll-top",
				"description": "Type: number\n设置竖向滚动条位置"
			},
			{
				"name": "scroll-with-animation",
				"description": "Type: boolean\n在设置滚动条位置时使用动画过渡\nDefault: false"
			},
			{
				"name": "scroll-x",
				"description": "Type: boolean\n允许横向滚动\nDefault: false"
			},
			{
				"name": "scroll-y",
				"description": "Type: boolean\n允许纵向滚动\nDefault: false"
			},
			{
				"name": "upper-threshold",
				"description": "Type: number\n距顶部/左边多远时(单位px),触发 scrolltoupper 事件\nDefault: 50"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html"
		}]
	},
	{
		"name": "swiper",
		"description": "滑块视图容器。\n\n从 [1.4.0](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html \"基础库 1.4.0 开始支持,低版本需做兼容处理。\") 开始,`change`事件返回`detail`中包含一个`source`字段,表示导致变更的原因,可能值如下:\n\n*   `autoplay` 自动播放导致swiper变化;\n*   `touch` 用户划动引起swiper变化;\n*   其他原因将用空字符串表示。",
		"attributes": [
			{
				"name": "autoplay",
				"description": "Type: boolean\n是否自动切换\nDefault: false"
			},
			{
				"name": "bindanimationfinish",
				"description": "Type: function => any\n动画结束时会触发 animationfinish 事件,event.detail 同上\nSince: 1.9.0"
			},
			{
				"name": "bindchange",
				"description": "Type: function => any\ncurrent 改变时会触发 change 事件,event.detail = {current: current, source: source}"
			},
			{
				"name": "circular",
				"description": "Type: boolean\n是否采用衔接滑动\nDefault: false"
			},
			{
				"name": "current",
				"description": "Type: number\n当前所在滑块的 index\nDefault: 0"
			},
			{
				"name": "current-item-id",
				"description": "Type: string\n当前所在滑块的 item-id ,不能与 current 被同时指定\nSince: 1.9.0"
			},
			{
				"name": "display-multiple-items",
				"description": "Type: number\n同时显示的滑块数量\nDefault: 1\nSince: 1.9.0"
			},
			{
				"name": "duration",
				"description": "Type: number\n滑动动画时长\nDefault: 500"
			},
			{
				"name": "indicator-active-color",
				"description": "Type: string\n当前选中的指示点颜色\nDefault: #000000\nSince: 1.1.0"
			},
			{
				"name": "indicator-color",
				"description": "Type: string\n指示点颜色\nDefault: rgba(0, 0, 0, .3)\nSince: 1.1.0"
			},
			{
				"name": "indicator-dots",
				"description": "Type: boolean\n是否显示面板指示点\nDefault: false"
			},
			{
				"name": "interval",
				"description": "Type: number\n自动切换时间间隔\nDefault: 5000"
			},
			{
				"name": "next-margin",
				"description": "Type: string\n后边距,可用于露出后一项的一小部分,接受 px 和 rpx 值\nDefault: 0px\nSince: 1.9.0"
			},
			{
				"name": "previous-margin",
				"description": "Type: string\n前边距,可用于露出前一项的一小部分,接受 px 和 rpx 值\nDefault: 0px\nSince: 1.9.0"
			},
			{
				"name": "skip-hidden-item-layout",
				"description": "Type: boolean\n是否跳过未显示的滑块布局,设为 true 可优化复杂情况下的滑动性能,但会丢失隐藏状态滑块的布局信息\nDefault: false\nSince: 1.9.0"
			},
			{
				"name": "vertical",
				"description": "Type: boolean\n滑动方向是否为纵向\nDefault: false"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html"
		}]
	},
	{
		"name": "swiper-item",
		"description": "仅可放置在`<swiper/>`组件中,宽高自动设置为100%。",
		"attributes": [{
			"name": "item-id",
			"description": "Type: string\n该 swiper-item 的标识符\nSince: 1.9.0"
		}],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html"
		}]
	},
	{
		"name": "text",
		"description": "文本。",
		"attributes": [
			{
				"name": "decode",
				"description": "Type: boolean\n是否解码\nDefault: false\nSince: 1.4.0"
			},
			{
				"name": "selectable",
				"description": "Type: boolean\n文本是否可选\nDefault: false\nSince: 1.1.0"
			},
			{
				"name": "space",
				"description": "Type: string\n显示连续空格\nDefault: false\nSince: 1.4.0",
				"values": [
					{
						"name": "ensp",
						"description": "中文字符空格一半大小"
					},
					{
						"name": "emsp",
						"description": "中文字符空格大小"
					},
					{
						"name": "nbsp",
						"description": "根据字体设置的空格大小"
					}
				]
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/text.html"
		}]
	},
	{
		"name": "view",
		"description": "视图容器。",
		"attributes": [
			{
				"name": "hover-class",
				"description": "Type: string\n指定按下去的样式类。当 `hover-class=\"none\"` 时,没有点击态效果\nDefault: none"
			},
			{
				"name": "hover-start-time",
				"description": "Type: number\n按住后多久出现点击态,单位毫秒\nDefault: 50"
			},
			{
				"name": "hover-stay-time",
				"description": "Type: number\n手指松开后点击态保留时间,单位毫秒\nDefault: 400"
			},
			{
				"name": "hover-stop-propagation",
				"description": "Type: boolean\n指定是否阻止本节点的祖先节点出现点击态\nDefault: false\nSince: 1.5.0"
			}
		],
		"references": [{
			"name": "WeChat Mini Program docs",
			"url": "https://developers.weixin.qq.com/miniprogram/dev/component/view.html"
		}]
	}
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTagsData/index.ts
const WEAPP_BUILTIN_HTML_TAGS = [
	...WEAPP_BUILTIN_HTML_TAGS_ADS_AND_META,
	...WEAPP_BUILTIN_HTML_TAGS_TEMPLATES_AND_NAVIGATION,
	...WEAPP_BUILTIN_HTML_TAGS_FORM_CONTROLS_PRIMARY,
	...WEAPP_BUILTIN_HTML_TAGS_FORM_CONTROLS_SELECTION,
	...WEAPP_BUILTIN_HTML_TAGS_MEDIA_PLAYBACK,
	...WEAPP_BUILTIN_HTML_TAGS_MEDIA_CAPTURE_LIVE,
	...WEAPP_BUILTIN_HTML_TAGS_MAP_AND_MOVABLE,
	...WEAPP_BUILTIN_HTML_TAGS_VISUAL_VIEW
];
//#endregion
//#region src/runtime/autoImport/weappBuiltinHtmlTags.ts
function loadWeappBuiltinHtmlTags() {
	return WEAPP_BUILTIN_HTML_TAGS;
}
//#endregion
//#region src/runtime/autoImport/service/outputs/sync.ts
const TS_LIKE_EXT_RE = /\.[mc]?[jt]sx?$/;
const VUE_LIKE_EXTENSIONS$2 = [
	".vue",
	".tsx",
	".jsx"
];
const CAMEL_TO_KEBAB_RE$2 = /([a-z0-9])([A-Z])/g;
const TRAILING_INDEX_SEGMENT_RE = /\/index$/;
async function getPreparedSyncState(options) {
	const { outputsState } = options;
	const currentVersion = options.getPreparedStateVersion();
	if (!outputsState.preparedSyncStatePromise || outputsState.preparedSyncStateVersion !== currentVersion) {
		outputsState.preparedSyncStateVersion = currentVersion;
		outputsState.preparedSyncStatePromise = Promise.resolve().then(() => {
			options.syncResolverComponentProps();
			options.preloadResolverComponentMetadata();
			const componentNames = collectAllComponentNames(options);
			return {
				componentNames,
				componentMetadataMap: new Map(componentNames.map((name) => [name, options.getComponentMetadata(name)]))
			};
		});
	}
	return await outputsState.preparedSyncStatePromise;
}
function toRelativeImportSpecifier(outputPath, sourcePath) {
	const relative = path.relative(path.dirname(outputPath), sourcePath).replaceAll("\\", "/");
	if (!relative || relative === ".") return "./";
	return relative.startsWith(".") ? relative : `./${relative}`;
}
function normalizeLocalNavigationSource(sourcePath) {
	if (sourcePath.endsWith(".vue")) return sourcePath;
	return sourcePath.replace(TS_LIKE_EXT_RE, "");
}
function normalizeLayoutName$1(layoutsRoot, full, ext) {
	const base = ext === ".wxml" ? full.slice(0, -ext.length) : full;
	const relativePath = path.relative(layoutsRoot, base);
	const normalized = (ext === ".wxml" ? relativePath : relativePath.slice(0, -path.extname(relativePath).length)).replaceAll("\\", "/").replace(TRAILING_INDEX_SEGMENT_RE, "");
	if (!normalized) return;
	return normalized.split("/").filter(Boolean).map((segment) => segment.replace(CAMEL_TO_KEBAB_RE$2, "$1-$2").replaceAll("_", "-").toLowerCase()).join("-") || void 0;
}
async function collectLayoutSyncState(ctx) {
	const configService = requireConfigService(ctx, "收集 layout props 前必须初始化 configService。");
	const srcRoot = configService.absoluteSrcRoot;
	const layoutsRoot = path.join(srcRoot, "layouts");
	const layoutNames = /* @__PURE__ */ new Set();
	const layoutPropsMap = /* @__PURE__ */ new Map();
	async function walk(dir) {
		let entries;
		try {
			entries = await fs$1.readdir(dir);
		} catch {
			return;
		}
		for (const entry of entries) {
			const full = path.join(dir, entry);
			if ((await fs$1.stat(full)).isDirectory()) {
				await walk(full);
				continue;
			}
			const ext = path.extname(full);
			if (!VUE_LIKE_EXTENSIONS$2.includes(ext) && ext !== ".wxml") continue;
			const base = ext === ".wxml" ? full.slice(0, -ext.length) : full;
			const layoutName = normalizeLayoutName$1(layoutsRoot, full, ext);
			if (!layoutName) continue;
			layoutNames.add(layoutName);
			let propMap = /* @__PURE__ */ new Map();
			if (ext === ".wxml") try {
				const json = await fs$1.readJson(`${base}.json`);
				const scriptSource = await fs$1.readFile(`${base}.js`, "utf8").catch(() => "");
				const jsonProps = extractJsonPropMetadata(json).props;
				propMap = mergePropMaps(jsonProps, scriptSource ? extractComponentProps(scriptSource, { astEngine: resolveAstEngine(configService.weappViteConfig) }) : /* @__PURE__ */ new Map());
			} catch {
				propMap = /* @__PURE__ */ new Map();
			}
			else try {
				const source = await fs$1.readFile(full, "utf8");
				if (ext === ".vue") propMap = extractVueComponentProps(source, full, { astEngine: resolveAstEngine(configService.weappViteConfig) });
				else propMap = extractInlinePropsTypeFromCode(source);
			} catch {
				propMap = /* @__PURE__ */ new Map();
			}
			layoutPropsMap.set(layoutName, propMap);
		}
	}
	await walk(layoutsRoot);
	return {
		layoutNames: [...layoutNames].sort((a, b) => a.localeCompare(b)),
		layoutPropsMap
	};
}
async function syncTypedComponentsDefinition(settings, options) {
	const { outputsState } = options;
	if (!settings.enabled || !settings.outputPath) {
		if (outputsState.lastTypedDefinitionOutputPath) try {
			await fs$1.remove(outputsState.lastTypedDefinitionOutputPath);
		} catch {}
		outputsState.lastTypedDefinitionOutputPath = void 0;
		outputsState.lastWrittenTypedDefinition = void 0;
		return;
	}
	const prepared = await getPreparedSyncState(options);
	const nextDefinition = createTypedComponentsDefinition(prepared.componentNames, (name) => prepared.componentMetadataMap.get(name) ?? {
		types: /* @__PURE__ */ new Map(),
		docs: /* @__PURE__ */ new Map()
	});
	if (nextDefinition === outputsState.lastWrittenTypedDefinition && settings.outputPath === outputsState.lastTypedDefinitionOutputPath) return;
	try {
		if (outputsState.lastTypedDefinitionOutputPath && outputsState.lastTypedDefinitionOutputPath !== settings.outputPath) try {
			await fs$1.remove(outputsState.lastTypedDefinitionOutputPath);
		} catch {}
		await fs$1.outputFile(settings.outputPath, nextDefinition, "utf8");
		outputsState.lastWrittenTypedDefinition = nextDefinition;
		outputsState.lastTypedDefinitionOutputPath = settings.outputPath;
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.error(`写入 typed-components.d.ts 失败: ${message}`);
	}
}
async function syncVueComponentsDefinition(settings, options) {
	const { outputsState, ctx, resolverComponentsMapRef, resolveComponentTypeImport } = options;
	const configService = requireConfigService(ctx, "写入 components.d.ts 前必须初始化 configService。");
	if (!settings.enabled || !settings.outputPath) {
		if (outputsState.lastVueComponentsOutputPath) try {
			await fs$1.remove(outputsState.lastVueComponentsOutputPath);
		} catch {}
		if (outputsState.lastLayoutTypesOutputPath) try {
			await fs$1.remove(outputsState.lastLayoutTypesOutputPath);
		} catch {}
		outputsState.lastVueComponentsOutputPath = void 0;
		outputsState.lastWrittenVueComponentsDefinition = void 0;
		outputsState.lastLayoutTypesOutputPath = void 0;
		outputsState.lastWrittenLayoutTypesDefinition = void 0;
		return;
	}
	const prepared = await getPreparedSyncState(options);
	const outputPath = settings.outputPath;
	const { layoutNames, layoutPropsMap } = await collectLayoutSyncState(ctx);
	const layoutTypesOutputPath = resolveLayoutTypesDefaultPath(configService);
	const layoutTypesDefinition = createLayoutTypesDefinition(layoutNames, layoutPropsMap);
	const nextDefinition = createVueComponentsDefinition(prepared.componentNames, (name) => prepared.componentMetadataMap.get(name) ?? {
		types: /* @__PURE__ */ new Map(),
		docs: /* @__PURE__ */ new Map()
	}, {
		useTypedComponents: getTypedComponentsSettings({ configService }).enabled,
		moduleName: settings.moduleName,
		layoutNames,
		layoutPropsMap,
		resolveComponentImport: (name) => {
			const local = options.registry.get(name);
			if (local?.kind === "local") {
				const sourcePath = local.entry?.path || local.entry?.jsonPath || local.entry?.templatePath;
				if (sourcePath) return toRelativeImportSpecifier(outputPath, normalizeLocalNavigationSource(sourcePath));
			}
			const from = resolverComponentsMapRef.value[name];
			if (!from) return;
			return resolveComponentTypeImport(name, from);
		}
	});
	const vueUnchanged = nextDefinition === outputsState.lastWrittenVueComponentsDefinition && outputPath === outputsState.lastVueComponentsOutputPath;
	const layoutTypesUnchanged = layoutTypesDefinition === outputsState.lastWrittenLayoutTypesDefinition && layoutTypesOutputPath === outputsState.lastLayoutTypesOutputPath;
	if (vueUnchanged && layoutTypesUnchanged) return;
	try {
		if (outputsState.lastVueComponentsOutputPath && outputsState.lastVueComponentsOutputPath !== outputPath) try {
			await fs$1.remove(outputsState.lastVueComponentsOutputPath);
		} catch {}
		if (!vueUnchanged) await fs$1.outputFile(outputPath, nextDefinition, "utf8");
		if (!layoutTypesUnchanged && layoutTypesDefinition) await fs$1.outputFile(layoutTypesOutputPath, layoutTypesDefinition, "utf8");
		outputsState.lastWrittenVueComponentsDefinition = nextDefinition;
		outputsState.lastVueComponentsOutputPath = outputPath;
		outputsState.lastWrittenLayoutTypesDefinition = layoutTypesDefinition;
		outputsState.lastLayoutTypesOutputPath = layoutTypesOutputPath;
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.error(`写入 components.d.ts 失败: ${message}`);
	}
}
async function syncHtmlCustomData(settings, options) {
	const { outputsState } = options;
	if (!settings.enabled || !settings.outputPath) {
		if (outputsState.lastHtmlCustomDataOutputPath) try {
			await fs$1.remove(outputsState.lastHtmlCustomDataOutputPath);
		} catch {}
		outputsState.lastHtmlCustomDataOutputPath = void 0;
		outputsState.lastWrittenHtmlCustomData = void 0;
		return;
	}
	const prepared = await getPreparedSyncState(options);
	const builtinTags = loadWeappBuiltinHtmlTags();
	const nextDefinition = createHtmlCustomDataDefinition(prepared.componentNames, (name) => prepared.componentMetadataMap.get(name) ?? {
		types: /* @__PURE__ */ new Map(),
		docs: /* @__PURE__ */ new Map()
	}, builtinTags);
	if (nextDefinition === outputsState.lastWrittenHtmlCustomData && settings.outputPath === outputsState.lastHtmlCustomDataOutputPath) return;
	try {
		if (outputsState.lastHtmlCustomDataOutputPath && outputsState.lastHtmlCustomDataOutputPath !== settings.outputPath) try {
			await fs$1.remove(outputsState.lastHtmlCustomDataOutputPath);
		} catch {}
		await fs$1.outputFile(settings.outputPath, nextDefinition, "utf8");
		outputsState.lastWrittenHtmlCustomData = nextDefinition;
		outputsState.lastHtmlCustomDataOutputPath = settings.outputPath;
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.error(`写入 mini-program.html-data.json 失败: ${message}`);
	}
}
//#endregion
//#region src/runtime/autoImport/service/outputs/index.ts
function createOutputsHelpers(options) {
	const { ctx, registry, manifestFileName, manifestCache, componentMetadataMap, outputsState, getPreparedStateVersion, resolverComponentsMapRef, collectResolverComponents, collectManifestResolverComponents, syncResolverComponentProps, preloadResolverComponentMetadata, getComponentMetadata, resolveComponentTypeImport } = options;
	const commonSyncOptions = {
		ctx,
		outputsState,
		getPreparedStateVersion,
		collectResolverComponents,
		registry,
		componentMetadataMap,
		manifestCache,
		syncResolverComponentProps,
		preloadResolverComponentMetadata,
		getComponentMetadata
	};
	const scheduleHelpers = createScheduleHelpers({
		ctx,
		outputsState,
		manifestFileName,
		writeManifest: async (outputPath) => {
			await writeManifestFile({
				outputPath,
				collectManifestResolverComponents,
				registry,
				manifestCache,
				scheduleHtmlCustomDataWrite: scheduleHelpers.scheduleHtmlCustomDataWrite
			});
		},
		syncTyped: async (settings) => syncTypedComponentsDefinition(settings, commonSyncOptions),
		syncHtmlCustomData: async (settings) => syncHtmlCustomData(settings, commonSyncOptions),
		syncVueComponents: async (settings) => syncVueComponentsDefinition(settings, {
			...commonSyncOptions,
			resolverComponentsMapRef,
			resolveComponentTypeImport
		})
	});
	return {
		scheduleManifestWrite: scheduleHelpers.scheduleManifestWrite,
		scheduleTypedComponentsWrite: scheduleHelpers.scheduleTypedComponentsWrite,
		scheduleHtmlCustomDataWrite: scheduleHelpers.scheduleHtmlCustomDataWrite,
		scheduleVueComponentsWrite: scheduleHelpers.scheduleVueComponentsWrite
	};
}
const PROD_PATH_EXISTS_TTL_MS = 6e4;
function getPathExistsTtlMs(config) {
	return config?.isDev ? 250 : PROD_PATH_EXISTS_TTL_MS;
}
function getReadFileCheckMtime(config) {
	return Boolean(config?.isDev);
}
//#endregion
//#region src/utils/configErrors.ts
const CJS_ERROR_PATTERNS = [
	"__dirname is not defined",
	"__filename is not defined",
	"require is not defined",
	"module is not defined",
	"exports is not defined",
	"es module scope"
];
function collectErrorText(error, texts) {
	if (!error) return;
	if (typeof error === "string") {
		texts.push(error);
		return;
	}
	if (typeof error === "object") {
		const err = error;
		if (err.message) texts.push(String(err.message));
		if (err.stack) texts.push(String(err.stack));
		if ("cause" in err) collectErrorText(err.cause, texts);
	}
}
function formatConfigPath(configPath, cwd) {
	if (!configPath) return "vite.config.ts";
	const relative = path.relative(cwd, configPath);
	if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return relative;
	return configPath;
}
function createCjsConfigLoadError(options) {
	const texts = [];
	collectErrorText(options.error, texts);
	const haystack = texts.join("\n").toLowerCase();
	if (!CJS_ERROR_PATTERNS.some((pattern) => haystack.includes(pattern))) return;
	const message = `${formatConfigPath(options.configPath, options.cwd)} 为 CJS 格式,需要改为 ESM 写法(可参考 import.meta.dirname 等用法)。`;
	const error = new Error(message);
	if (options.error instanceof Error) error.cause = options.error;
	return error;
}
//#endregion
//#region src/utils/entryResolve.ts
function buildCandidates(base, extensions) {
	return extensions.map((ext) => changeFileExtension(base, ext));
}
function resolveEntryExtensions(kind, isDir) {
	return kind === "named" || isDir ? [...scriptExtensions, ...vueExtensions] : [...vueExtensions, ...scriptExtensions];
}
function createCachedEntryResolveOptions(configService, options) {
	return {
		kind: options?.kind,
		indexBaseName: options?.indexBaseName,
		exists: (filePath) => pathExists(filePath, { ttlMs: getPathExistsTtlMs(configService) }),
		stat: (filePath) => fs$1.stat(filePath)
	};
}
/**
* 用于处理 resolver 返回“目录路径”或“无扩展名路径”的场景。
*
* - 如果 `input` 是目录:尝试 `${dir}/${indexBaseName}.{js/ts..}`(必要时再尝试 .vue)
* - 如果 `input` 没扩展名:尝试补全 `{.vue, .ts, .js...}`(default 优先 .vue,named 优先 js/ts)
*
* 如果 `input` 已带扩展名,则返回 `undefined`(表示无需补全)。
*/
async function resolveEntryPath(input, options) {
	if (!input || typeof input !== "string") return;
	if (path.extname(input)) return;
	const kind = options?.kind ?? "default";
	const exists = options?.exists ?? (async (p) => fs$1.pathExists(p));
	const stat = options?.stat ?? (async (p) => fs$1.stat(p));
	const indexBaseName = options?.indexBaseName ?? "index";
	let base = input;
	let isDir = false;
	try {
		isDir = Boolean((await stat(input))?.isDirectory?.());
	} catch {
		isDir = false;
	}
	if (isDir) base = path.join(input, indexBaseName);
	const extensions = resolveEntryExtensions(kind, isDir);
	for (const candidate of buildCandidates(base, extensions)) if (await exists(candidate)) return candidate;
}
//#endregion
//#region src/utils/loadViteConfigFile.ts
const DEFAULT_VITE_CONFIG_FILES = [
	"vite.config.ts",
	"vite.config.mts",
	"vite.config.cts",
	"vite.config.js",
	"vite.config.mjs",
	"vite.config.cjs"
];
const DEFAULT_VITE_CONFIG_FILE_SET = new Set(DEFAULT_VITE_CONFIG_FILES);
const TYPELESS_PACKAGE_JSON_WARNING_CODE = "MODULE_TYPELESS_PACKAGE_JSON";
function resolveWarningCode(warning, typeOrOptions, code) {
	if (warning instanceof Error && typeof warning.code === "string") return warning.code;
	if (typeOrOptions && typeof typeOrOptions === "object" && typeof typeOrOptions.code === "string") return typeOrOptions.code;
	return code;
}
async function withSuppressedWarningCodes(suppressedCodes, fn) {
	if (!suppressedCodes || suppressedCodes.length === 0) return fn();
	const suppressedCodeSet = new Set(suppressedCodes);
	const originalEmitWarning = process.emitWarning.bind(process);
	process.emitWarning = ((warning, typeOrOptions, code) => {
		const warningCode = resolveWarningCode(warning, typeOrOptions, code);
		if (warningCode && suppressedCodeSet.has(warningCode)) return;
		return originalEmitWarning(warning, typeOrOptions, code);
	});
	try {
		return await fn();
	} finally {
		process.emitWarning = originalEmitWarning;
	}
}
function isDefaultViteConfigBasename(filePath) {
	return DEFAULT_VITE_CONFIG_FILE_SET.has(path.basename(filePath));
}
async function resolveImplicitConfigFile(configRoot) {
	for (const fileName of DEFAULT_VITE_CONFIG_FILES) {
		const filePath = path.resolve(configRoot, fileName);
		try {
			await fs$2.access(filePath);
			return filePath;
		} catch {
			continue;
		}
	}
}
async function loadViteConfigFile(configEnv, configFile, configRoot, configFileDependencies, configFileExport, configLoader, suppressedWarningCodes, logLevel) {
	const resolvedConfigFile = configFile ?? await resolveImplicitConfigFile(configRoot);
	const resolvedConfigLoader = configLoader ?? "bundle";
	return withSuppressedWarningCodes(suppressedWarningCodes, () => loadConfigFromFile(configEnv, resolvedConfigFile, configRoot, logLevel, void 0, resolvedConfigLoader));
}
//#endregion
//#region src/utils/preloadScan.ts
const HOST_ROUTER_METHODS = /* @__PURE__ */ new Set([
	"navigateTo",
	"redirectTo",
	"reLaunch",
	"switchTab"
]);
const ROUTER_METHODS = /* @__PURE__ */ new Set(["push", "replace"]);
const ROUTER_MODULES = /* @__PURE__ */ new Set([
	"vue-router",
	"wevu",
	"wevu/router"
]);
const ROUTER_FACTORY_METHODS = /* @__PURE__ */ new Map([
	["createRouter", ROUTER_METHODS],
	["useNativeRouter", HOST_ROUTER_METHODS],
	["useRouter", ROUTER_METHODS]
]);
const TEMPLATE_NAVIGATOR_RE = /<navigator(?=\s|>)[^>]*?\surl\s*=\s*(["'])([^"'{}\s]+)\1/gi;
function normalizePagePath$1(value) {
	return path.posix.normalize(value).replace(/^\/+/, "").replace(/^\.\//, "");
}
function normalizeStaticTarget(target, sourcePage) {
	const route = toPosixPath(target).split(/[?#]/, 1)[0];
	return normalizePagePath$1(route.startsWith("/") ? route : route.startsWith("./") || route.startsWith("../") ? path.posix.join(path.posix.dirname(sourcePage), route) : route);
}
function getStaticString(node) {
	if (node?.type === "StringLiteral" || node?.type === "Literal" && typeof node.value === "string") return node.value;
	if (node?.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw;
}
function getPropertyName(node) {
	if (!node) return;
	if (node.type === "Identifier" && !node.computed) return node.name;
	return getStaticString(node);
}
function getRouteFromObject(argument) {
	if (argument?.type !== "ObjectExpression") return;
	for (const property of argument.properties ?? []) {
		if (property.type !== "ObjectProperty" && property.type !== "Property") continue;
		const name = getPropertyName(property.key);
		if (name !== "url" && name !== "path") continue;
		const value = getStaticString(property.value);
		if (value) return value;
	}
}
function getIdentifierName(node) {
	return node?.type === "Identifier" ? node.name : void 0;
}
function collectRouterBindings(ast) {
	const importedFactories = /* @__PURE__ */ new Map();
	const routerObjects = /* @__PURE__ */ new Map();
	const routerFunctions = /* @__PURE__ */ new Map();
	traverse(ast, { ImportDeclaration(importPath) {
		if (!ROUTER_MODULES.has(importPath.node.source?.value)) return;
		for (const specifier of importPath.node.specifiers ?? []) {
			if (specifier.type !== "ImportSpecifier") continue;
			const imported = getIdentifierName(specifier.imported) ?? getStaticString(specifier.imported);
			const local = getIdentifierName(specifier.local);
			const methods = imported ? ROUTER_FACTORY_METHODS.get(imported) : void 0;
			const binding = local ? importPath.scope.getBinding(local) : void 0;
			if (methods && binding) importedFactories.set(binding, methods);
		}
	} });
	traverse(ast, { VariableDeclarator(declaratorPath) {
		const init = declaratorPath.node.init;
		const factory = init?.type === "CallExpression" ? getIdentifierName(init.callee) : void 0;
		if (!factory) return;
		const factoryBinding = declaratorPath.scope.getBinding(factory);
		const methods = factoryBinding ? importedFactories.get(factoryBinding) : ROUTER_FACTORY_METHODS.get(factory);
		if (!methods) return;
		const id = declaratorPath.node.id;
		const objectName = getIdentifierName(id);
		if (objectName) {
			const binding = declaratorPath.scope.getBinding(objectName);
			if (binding?.constant) routerObjects.set(binding, methods);
			return;
		}
		if (id?.type !== "ObjectPattern") return;
		for (const property of id.properties ?? []) {
			if (property.type !== "ObjectProperty" && property.type !== "Property") continue;
			const importedMethod = getPropertyName(property.key);
			const local = getIdentifierName(property.value);
			const binding = local ? declaratorPath.scope.getBinding(local) : void 0;
			if (importedMethod && methods.has(importedMethod) && binding?.constant) routerFunctions.set(binding, importedMethod);
		}
	} });
	return {
		routerFunctions,
		routerObjects
	};
}
function getNavigationMethod(callPath, bindings) {
	const callee = callPath.node.callee;
	const directName = getIdentifierName(callee);
	const directMethod = directName ? bindings.routerFunctions.get(callPath.scope.getBinding(directName)) : void 0;
	if (directMethod) return directMethod;
	if (callee?.type !== "MemberExpression" && callee?.type !== "OptionalMemberExpression") return;
	const objectName = getIdentifierName(callee.object);
	const method = getPropertyName(callee.property);
	if (objectName === "wx" && !callPath.scope.getBinding("wx") && method && HOST_ROUTER_METHODS.has(method)) return method;
	if (objectName && method) {
		if (bindings.routerObjects.get(callPath.scope.getBinding(objectName))?.has(method)) return method;
	}
}
function collectScriptTargets(source, sourcePage) {
	const targets = [];
	try {
		const ast = parseJsLike(source);
		const bindings = collectRouterBindings(ast);
		traverse(ast, { CallExpression(callPath) {
			if (!getNavigationMethod(callPath, bindings)) return;
			const argument = callPath.node.arguments?.[0];
			const target = getStaticString(argument) ?? getRouteFromObject(argument);
			if (target) targets.push(normalizeStaticTarget(target, sourcePage));
		} });
	} catch {}
	return [...new Set(targets)];
}
function collectTemplateTargets(source, sourcePage) {
	const targets = [];
	const withoutComments = source.replace(/<!--[\s\S]*?-->/g, "");
	TEMPLATE_NAVIGATOR_RE.lastIndex = 0;
	for (const match of withoutComments.matchAll(TEMPLATE_NAVIGATOR_RE)) {
		const target = match[2];
		if (target) targets.push(normalizeStaticTarget(target, sourcePage));
	}
	return [...new Set(targets)];
}
function collectStaticRouteTargets(source, kind, sourcePage) {
	return kind === "template" ? collectTemplateTargets(source, sourcePage) : collectScriptTargets(source, sourcePage);
}
//#endregion
//#region src/utils/preloadRule.ts
const PRELOAD_RULE_GLOB_RE = /[*?[\]{}()!+@]/g;
function normalizePagePath(value) {
	return normalizeRoot(value).replace(/^\/+/, "");
}
function normalizePackageRoot(value) {
	return normalizeRoot(value).replace(/^\/+|\/+$/g, "");
}
function normalizeRule(value, pattern) {
	if (!isObject(value)) throw new TypeError(`routeRules.${pattern}.preload 必须是对象。`);
	const packages = value.packages;
	if (!Array.isArray(packages) || packages.length === 0 || packages.some((item) => typeof item !== "string" || !item.trim())) throw new TypeError(`routeRules.${pattern}.preload.packages 必须是非空字符串数组。`);
	const network = value.network;
	if (network !== void 0 && network !== "all" && network !== "wifi") throw new TypeError(`routeRules.${pattern}.preload.network 只能是 "all" 或 "wifi"。`);
	const normalizedPackages = [...new Set(packages.map((item) => normalizePackageRoot(item)).filter(Boolean))];
	if (normalizedPackages.length === 0) throw new TypeError(`routeRules.${pattern}.preload.packages 必须包含有效的分包 root。`);
	return {
		packages: normalizedPackages,
		...network === void 0 ? {} : { network }
	};
}
function getRuleScore(pattern) {
	const segments = pattern.split("/").filter(Boolean);
	const wildcards = pattern.match(PRELOAD_RULE_GLOB_RE) ?? [];
	PRELOAD_RULE_GLOB_RE.lastIndex = 0;
	return [
		segments.filter((segment) => {
			PRELOAD_RULE_GLOB_RE.lastIndex = 0;
			return !PRELOAD_RULE_GLOB_RE.test(segment);
		}).length,
		pattern.replace(PRELOAD_RULE_GLOB_RE, "").length,
		-wildcards.length,
		segments.length,
		pattern.length
	];
}
function compareScores(left, right) {
	for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
		const leftValue = left[index] ?? 0;
		const rightValue = right[index] ?? 0;
		if (leftValue !== rightValue) return leftValue > rightValue ? 1 : -1;
	}
	return 0;
}
function pageCandidates(page) {
	const normalized = normalizePagePath(page);
	const withoutPagesPrefix = normalized.startsWith("pages/") ? normalized.slice(6) : normalized;
	const candidates = /* @__PURE__ */ new Set();
	for (const route of [normalized, withoutPagesPrefix]) {
		const withoutIndex = route.replace(/\/index$/, "") || route;
		for (const value of [route, withoutIndex]) {
			candidates.add(value);
			candidates.add(`/${value}`);
		}
	}
	return [...candidates];
}
function findRouteRuleMatch(page, routeRules) {
	if (!routeRules) return;
	const candidates = pageCandidates(page);
	let matched;
	for (const [pattern, value] of Object.entries(routeRules)) {
		if (!value || value.preload === void 0) continue;
		if (!candidates.some((candidate) => picomatch(pattern)(candidate))) continue;
		const rule = normalizeRule(value.preload, pattern);
		const score = getRuleScore(pattern);
		if (!matched || compareScores(score, matched.score) > 0) matched = {
			page,
			rule,
			pattern,
			score
		};
	}
	if (!matched) return;
	const { score: _score, ...result } = matched;
	return result;
}
function collectSubPackages(appJson) {
	return (Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : []).flatMap((item) => {
		if (!isObject(item) || typeof item.root !== "string") return [];
		const root = normalizePackageRoot(item.root);
		return (Array.isArray(item.pages) ? item.pages.filter((page) => typeof page === "string" && page.trim().length > 0) : []).map((page) => ({
			route: normalizePagePath(path.posix.join(root, page)),
			packageRoot: root,
			...item.independent === true ? { independent: true } : {}
		}));
	});
}
function collectPreloadPages(appJson) {
	return [...Array.isArray(appJson.pages) ? appJson.pages.filter((page) => typeof page === "string" && page.trim().length > 0).map((page) => ({ route: normalizePagePath(page) })) : [], ...collectSubPackages(appJson)];
}
function findPreloadRuleKey(page, preloadRule) {
	const candidates = pageCandidates(page);
	return Object.keys(preloadRule).find((candidate) => candidates.includes(normalizePagePath(candidate)));
}
function resolvePreloadPackageIdentifier(value, appJson) {
	const normalized = value === "__APP__" ? value : normalizePackageRoot(value);
	if (!normalized || normalized === "__APP__") return normalized || void 0;
	const source = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
	for (const item of source) {
		if (!isObject(item) || typeof item.root !== "string") continue;
		const root = normalizePackageRoot(item.root);
		if (root === normalized || typeof item.name === "string" && item.name === value) return root;
	}
	return normalized;
}
function cloneRule(rule) {
	if (!isObject(rule)) return rule;
	const packages = Array.isArray(rule.packages) ? rule.packages.filter((item) => typeof item === "string") : [];
	return {
		...rule,
		packages: [...packages]
	};
}
/**
* @description 将 routeRules 中的 preload 声明合成为 app.json.preloadRule。
* 手写的 preloadRule 保持优先,其他平台不生成微信专属字段。
*/
function applyPreloadRulesToAppJson(appJson, routeRules, platform) {
	if (platform !== "weapp" || !routeRules) return appJson;
	const existing = isObject(appJson.preloadRule) ? appJson.preloadRule : {};
	const next = { ...existing };
	for (const page of collectPreloadPages(appJson)) {
		const match = findRouteRuleMatch(page.route, routeRules);
		if (!match || findPreloadRuleKey(page.route, existing) !== void 0) continue;
		next[page.route] = cloneRule(match.rule);
	}
	if (Object.keys(next).length > 0) appJson.preloadRule = next;
	return appJson;
}
function suggestPreloadRules(appJson, pageSources) {
	const pages = collectPreloadPages(appJson);
	const pageByRoute = new Map(pages.map((page) => [page.route, page]));
	const suggestions = [];
	const uncovered = /* @__PURE__ */ new Set();
	for (const page of pages) {
		const source = pageSources.get(page.route);
		for (const kind of ["template", "script"]) for (const target of collectStaticRouteTargets(source?.[kind] ?? "", kind, page.route)) {
			const targetPage = pageByRoute.get(target);
			if (!targetPage) continue;
			const packageRoot = targetPage.packageRoot ?? (page.independent ? "__APP__" : void 0);
			if (!packageRoot || packageRoot === page.packageRoot) continue;
			const suggestion = {
				page: page.route,
				packageRoot,
				target,
				source: kind
			};
			suggestions.push(suggestion);
		}
		if (source && !source.template && !source.script) uncovered.add(page.route);
	}
	return {
		pages,
		suggestions,
		uncovered: [...uncovered]
	};
}
//#endregion
//#region src/utils/projectConfig.ts
async function readProjectConfigFile(filePath, required) {
	if (!await fs$1.pathExists(filePath)) {
		if (required) throw new Error(`找不到项目配置文件:${filePath}`);
		return {};
	}
	try {
		return await fs$1.readJson(filePath) || {};
	} catch {
		throw new Error(`解析 json 格式失败, ${filePath} 为非法的 json 格式`);
	}
}
const DEFAULT_PROJECT_PRIVATE_CONFIG_FILE_NAME = "project.private.config.json";
function getProjectConfigFileName(platform) {
	return getProjectPlatformOptions(platform).projectConfigFileName;
}
function getProjectPrivateConfigFileName(_) {
	return DEFAULT_PROJECT_PRIVATE_CONFIG_FILE_NAME;
}
function getProjectConfigRootKeys(platform) {
	return getProjectPlatformOptions(platform).projectConfigRootKeys;
}
function resolveProjectConfigRoot(projectConfig, platform) {
	const keys = getProjectConfigRootKeys(platform);
	for (const key of keys) {
		const value = projectConfig[key];
		if (typeof value === "string" && value.trim()) return value;
	}
}
async function getProjectConfig(root, options) {
	const baseJsonPath = path.resolve(root, options?.basePath ?? "project.config.json");
	const privateJsonPath = path.resolve(root, options?.privatePath ?? "project.private.config.json");
	const baseJson = await readProjectConfigFile(baseJsonPath, true);
	const privateJson = options?.ignorePrivate ? {} : await readProjectConfigFile(privateJsonPath, false);
	return Object.assign({}, privateJson, baseJson);
}
async function getProjectPrivateConfig(root, options) {
	return await readProjectConfigFile(path.resolve(root, options?.privatePath ?? "project.private.config.json"), false);
}
async function disableProjectPrivateConfigHotReload(filePath) {
	const config = await readProjectConfigFile(filePath, true);
	const setting = config.setting && typeof config.setting === "object" && !Array.isArray(config.setting) ? config.setting : {};
	if (setting.compileHotReLoad === false) return false;
	config.setting = {
		...setting,
		compileHotReLoad: false
	};
	await fs$1.writeFile(filePath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
	return true;
}
function resolveProjectConfigSyncDirs(options) {
	const outputRoot = path.dirname(options.outDir);
	const sourceBasePath = path.resolve(options.projectConfigPath);
	const sourceDir = path.dirname(sourceBasePath);
	const resolvedOutputRoot = path.resolve(outputRoot);
	const resolvedSourceDir = path.resolve(sourceDir);
	return {
		outputRoot,
		sourceBasePath,
		sourceDir,
		resolvedOutputRoot,
		resolvedSourceDir,
		shouldSync: resolvedSourceDir !== resolvedOutputRoot
	};
}
async function syncProjectConfigToOutput(options) {
	if (!options.enabled || !options.projectConfigPath) return;
	const syncDirs = resolveProjectConfigSyncDirs({
		outDir: options.outDir,
		projectConfigPath: options.projectConfigPath
	});
	if (!syncDirs.shouldSync) return;
	await fs$1.ensureDir(syncDirs.outputRoot);
	await fs$1.copy(syncDirs.sourceDir, syncDirs.outputRoot);
}
//#endregion
//#region src/utils/reExport.ts
function getExportedName(spec) {
	const exported = spec?.exported;
	if (!exported) return;
	if (exported.type === "Identifier") return exported.name;
	if (exported.type === "StringLiteral") return exported.value;
}
function getSourceValue(node) {
	const source = node?.source;
	if (!source || source.type !== "StringLiteral" && source.type !== "Literal") return;
	return source.value;
}
function getReExportCacheKey(file, astEngine) {
	return `${astEngine ?? "babel"}::${file}`;
}
function parseModuleForReExport(code, astEngine) {
	if (astEngine === "oxc") return parseJsLikeWithEngine(code, {
		engine: "oxc",
		filename: "inline.ts"
	});
	return parse$3(code, BABEL_TS_MODULE_PARSER_OPTIONS$1).program;
}
async function resolveReExportedInternal(exporterFile, exportName, depth, visited, options) {
	if (depth <= 0) return;
	if (visited.has(exporterFile)) return;
	visited.add(exporterFile);
	const cacheKey = getReExportCacheKey(exporterFile, options.astEngine);
	let entry = options.cache.get(cacheKey);
	if (!entry) {
		entry = /* @__PURE__ */ new Map();
		options.cache.set(cacheKey, entry);
	}
	if (entry.has(exportName)) return entry.get(exportName);
	let code;
	try {
		code = await options.readFile(exporterFile);
	} catch {
		entry.set(exportName, void 0);
		return;
	}
	let ast;
	try {
		ast = parseModuleForReExport(code, options.astEngine);
	} catch {
		entry.set(exportName, void 0);
		return;
	}
	const exportAllSources = [];
	for (const node of ast.body ?? []) {
		if (node?.type === "ExportNamedDeclaration") {
			const source = getSourceValue(node);
			if (!source) continue;
			for (const spec of node.specifiers ?? []) {
				if (spec?.type !== "ExportSpecifier") continue;
				const exportedName = getExportedName(spec);
				if (!exportedName || exportedName !== exportName) continue;
				const resolved = await options.resolveId(source, exporterFile);
				if (resolved) {
					entry.set(exportName, resolved);
					return resolved;
				}
			}
		}
		if (node?.type === "ExportAllDeclaration") {
			const source = getSourceValue(node);
			if (source) exportAllSources.push(source);
		}
	}
	for (const source of exportAllSources) {
		const hopId = await options.resolveId(source, exporterFile);
		if (!hopId) continue;
		const nested = await resolveReExportedInternal(hopId, exportName, depth - 1, visited, options);
		if (nested) {
			entry.set(exportName, nested);
			return nested;
		}
	}
	entry.set(exportName, void 0);
}
async function resolveReExportedName(exporterFile, exportName, options) {
	return resolveReExportedInternal(exporterFile, exportName, options.maxDepth ?? 4, /* @__PURE__ */ new Set(), options);
}
//#endregion
//#region src/utils/regexp.ts
const CSS_LANGS_RE = /\.(wxss|css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
function isCSSRequest(request) {
	return CSS_LANGS_RE.test(request);
}
function isRegexp(value) {
	return Object.prototype.toString.call(value) === "[object RegExp]";
}
//#endregion
//#region src/utils/toAbsoluteId.ts
function resolveAbsoluteIdBaseDir(configService, importer, options) {
	const cleanImporter = importer ? normalizeFsResolvedId(importer) : void 0;
	if (cleanImporter && !isSkippableResolvedId(cleanImporter) && path.isAbsolute(cleanImporter)) return path.dirname(cleanImporter);
	return options?.base === "cwd" ? configService.cwd : configService.absoluteSrcRoot;
}
/**
* 将可能为相对路径的 id 解析为绝对路径。
*
* - 会先对 id/importer 做 `normalizeFsResolvedId`(去 query、处理 file://、/@fs/、\0vue: 等)
* - 若 id 已是绝对路径则直接返回
* - 若 importer 是绝对路径,则以 importer 所在目录为基准解析
* - 否则使用 `configService.absoluteSrcRoot`(默认)或 `configService.cwd`(可选)作为基准解析
*
* 注意:对于 `\0xxx` / `node:` 这类虚拟 id,会原样返回(不做路径解析)。
*/
function toAbsoluteId(id, configService, importer, options) {
	const cleanId = normalizeFsResolvedId(id);
	if (!cleanId || isSkippableResolvedId(cleanId)) return cleanId;
	if (path.isAbsolute(cleanId)) return cleanId;
	const baseDir = resolveAbsoluteIdBaseDir(configService, importer, options);
	return path.resolve(baseDir, cleanId);
}
//#endregion
//#region src/utils/usingComponentFrom.ts
function shouldResolveUsingComponentFrom(normalizedResolvedFile) {
	return Boolean(normalizedResolvedFile && !isSkippableResolvedId(normalizedResolvedFile) && path.isAbsolute(normalizedResolvedFile));
}
function usingComponentFromResolvedFile(resolvedFile, configService) {
	if (!resolvedFile) return;
	const normalized = normalizeFsResolvedId(resolvedFile);
	if (!shouldResolveUsingComponentFrom(normalized)) return;
	const base = removeExtensionDeep(normalized);
	const relative = configService.relativeOutputPath(base);
	if (!relative || relative.startsWith("..")) return;
	return `/${toPosixPath(relative)}`;
}
//#endregion
//#region src/utils/version.ts
const LEADING_V = /^v/;
function getRuntime() {
	if (typeof globalThis.Deno !== "undefined" && "version" in Deno) return {
		runtime: "deno",
		version: Deno.version.deno
	};
	if (typeof globalThis.Bun !== "undefined") return {
		runtime: "bun",
		version: globalThis.Bun.version
	};
	if (typeof process !== "undefined" && process.versions?.node) return {
		runtime: "node",
		version: process.version.replace(LEADING_V, "")
	};
	throw new Error("无法识别运行时:无法确定 Node.js / Deno / Bun。");
}
function formatRequiredRuntimeVersion(required) {
	return semverValid(required) ? `>= ${required}` : required;
}
function checkRuntime(minVersions, options = {}) {
	const { runtime, version } = options.runtimeInfo ?? getRuntime();
	const runtimeLogger = options.logger ?? logger_default;
	const required = minVersions[runtime];
	if (!required) {
		runtimeLogger.warn(`未为 ${runtime} 指定最低版本,已跳过检查。`);
		return;
	}
	if (!(Boolean(semverValid(required)) ? semverGte(version, required) : semverSatisfies(version, required))) {
		const expected = formatRequiredRuntimeVersion(required);
		runtimeLogger.warn(`当前 ${runtime} 版本为 ${version} 无法满足 \`weapp-vite\` 最低要求的版本(${expected})`);
	}
}
//#endregion
//#region src/utils/weappConfig.ts
const WEAPP_VITE_CONFIG_CANDIDATES = [
	"weapp-vite.config.ts",
	"weapp-vite.config.mts",
	"weapp-vite.config.cts",
	"weapp-vite.config.js",
	"weapp-vite.config.mjs",
	"weapp-vite.config.cjs",
	"weapp-vite.config.json"
];
const WEAPP_VITE_CONFIG_SET = new Set(WEAPP_VITE_CONFIG_CANDIDATES);
function resolveSpecifiedWeappConfigPath(root, specified) {
	return path.isAbsolute(specified) ? specified : path.resolve(root, specified);
}
function isWeappConfigBasename(filePath) {
	return WEAPP_VITE_CONFIG_SET.has(path.basename(filePath));
}
function isExplicitCustomConfigFile(filePath) {
	return path.basename(filePath).includes(".config.") && !isDefaultViteConfigBasename(filePath) && !isWeappConfigBasename(filePath);
}
async function findWeappConfigInDirectory(directory) {
	for (const filename of WEAPP_VITE_CONFIG_CANDIDATES) {
		const candidatePath = path.resolve(directory, filename);
		if (await fs$1.pathExists(candidatePath)) return candidatePath;
	}
}
async function resolveWeappConfigFile(options) {
	const { root, specified } = options;
	if (specified) {
		const resolvedSpecified = resolveSpecifiedWeappConfigPath(root, specified);
		if (isWeappConfigBasename(resolvedSpecified)) {
			if (await fs$1.pathExists(resolvedSpecified)) return resolvedSpecified;
			return;
		}
		if (isExplicitCustomConfigFile(resolvedSpecified)) return;
		const fromSpecifiedDirectory = await findWeappConfigInDirectory(path.dirname(resolvedSpecified));
		if (fromSpecifiedDirectory) return fromSpecifiedDirectory;
	}
	return findWeappConfigInDirectory(root);
}
//#endregion
//#region src/runtime/autoImport/service/registry.ts
const JSON_LIKE_FILE_RE = /\.(?:json|jsonc|json5)$/i;
function rebuildNormalizedLocalComponents(registry, normalizedLocalComponents) {
	normalizedLocalComponents.clear();
	const ambiguousNames = /* @__PURE__ */ new Set();
	for (const [componentName, match] of registry) {
		const normalizedName = toKebabCaseComponentName(componentName);
		if (ambiguousNames.has(normalizedName)) continue;
		if (normalizedLocalComponents.has(normalizedName)) {
			normalizedLocalComponents.delete(normalizedName);
			ambiguousNames.add(normalizedName);
			continue;
		}
		normalizedLocalComponents.set(normalizedName, match);
	}
}
function refreshNormalizedLocalComponent(registry, normalizedLocalComponents, normalizedName) {
	let normalizedMatch;
	for (const [componentName, match] of registry) {
		if (toKebabCaseComponentName(componentName) !== normalizedName) continue;
		if (normalizedMatch) {
			normalizedLocalComponents.delete(normalizedName);
			return;
		}
		normalizedMatch = match;
	}
	if (normalizedMatch) normalizedLocalComponents.set(normalizedName, normalizedMatch);
	else normalizedLocalComponents.delete(normalizedName);
}
function createRegistryHelpers(state) {
	function scheduleOutputs(shouldWrite, vueEnabled) {
		state.scheduleManifestWrite(shouldWrite);
		state.scheduleTypedComponentsWrite(shouldWrite);
		state.scheduleHtmlCustomDataWrite(shouldWrite);
		state.scheduleVueComponentsWrite(vueEnabled || shouldWrite);
	}
	async function extractComponentPropsFromVue(vuePath) {
		return extractVueComponentProps(await fs$1.readFile(vuePath, "utf8"), vuePath, { astEngine: resolveAstEngine(state.ctx.configService?.weappViteConfig) });
	}
	function removeRegisteredComponent(paths) {
		const { baseName, templatePath, jsEntry, jsonPath } = paths;
		let removed = false;
		const removedNames = [];
		const removedNormalizedNames = /* @__PURE__ */ new Set();
		for (const [key, value] of state.registry) {
			if (value.kind !== "local") continue;
			const entry = value.entry;
			if (Boolean(templatePath && entry.templatePath === templatePath || jsonPath && entry.jsonPath === jsonPath || jsEntry && entry.path === jsEntry || baseName && removeExtensionDeep(entry.templatePath) === baseName || baseName && removeExtensionDeep(entry.path) === baseName || baseName && removeExtensionDeep(entry.jsonPath ?? "") === baseName)) {
				if (state.registry.delete(key)) {
					removed = true;
					removedNames.push(key);
					removedNormalizedNames.add(toKebabCaseComponentName(key));
				}
			}
		}
		for (const normalizedName of removedNormalizedNames) refreshNormalizedLocalComponent(state.registry, state.normalizedLocalComponents, normalizedName);
		return {
			removed,
			removedNames
		};
	}
	async function registerLocalComponent(filePath) {
		if (!state.ctx.configService || !state.ctx.jsonService) throw new Error("扫描组件前必须初始化 configService/jsonService。");
		const baseName = removeExtensionDeep(filePath);
		const [{ path: jsEntry }, { path: jsonPath }, { path: templatePath }] = await Promise.all([
			findJsEntry(baseName),
			findJsonEntry(baseName),
			findTemplateEntry(baseName, state.ctx.configService.platform)
		]);
		let vueEntry = filePath.endsWith(".vue") ? filePath : void 0;
		if ((!jsEntry || !jsonPath || !templatePath) && !vueEntry) vueEntry = await findVueEntry(baseName);
		const { removed, removedNames } = removeRegisteredComponent({
			baseName,
			templatePath,
			jsEntry,
			jsonPath
		});
		for (const name of removedNames) if (state.resolverComponentNames.has(name)) state.componentMetadataMap.set(name, {
			types: /* @__PURE__ */ new Map(),
			docs: /* @__PURE__ */ new Map()
		});
		else state.componentMetadataMap.delete(name);
		let resolvedJsEntry = jsEntry;
		let resolvedJsonPath = jsonPath;
		let resolvedTemplatePath = templatePath;
		let json = jsonPath ? await state.ctx.jsonService.read(jsonPath) : void 0;
		const vueSettings = getVueComponentsSettings(state.ctx);
		if ((!resolvedJsEntry || !resolvedJsonPath || !resolvedTemplatePath) && vueEntry) {
			const vueConfig = await extractConfigFromVue(vueEntry);
			const vueJson = vueConfig && typeof vueConfig === "object" && !Array.isArray(vueConfig) ? { ...vueConfig } : {};
			if (vueJson.component !== false) {
				vueJson.component = true;
				resolvedJsEntry = resolvedJsEntry ?? vueEntry;
				resolvedJsonPath = resolvedJsonPath ?? vueEntry;
				resolvedTemplatePath = resolvedTemplatePath ?? vueEntry;
				json = vueJson;
			}
		}
		if (!resolvedJsEntry || !resolvedJsonPath || !resolvedTemplatePath) {
			if (removed || removedNames.length > 0) state.bumpVersion();
			scheduleOutputs(removed || removedNames.length > 0, vueSettings.enabled);
			return;
		}
		if (!json?.component) {
			if (removed || removedNames.length > 0) state.bumpVersion();
			scheduleOutputs(removed || removedNames.length > 0, vueSettings.enabled);
			return;
		}
		const { componentName, base } = resolvedComponentName(baseName);
		if (!componentName) {
			if (removed || removedNames.length > 0) state.bumpVersion();
			scheduleOutputs(removed || removedNames.length > 0, vueSettings.enabled);
			return;
		}
		if (isBuiltinComponent(componentName)) {
			const message = `检测到本地组件 \`${state.ctx.configService.relativeCwd(baseName)}\` 与微信内置组件 \`${componentName}\` 重名。自动导入将优先使用本地组件,但这会遮蔽同名内置组件;建议参考 https://developers.weixin.qq.com/miniprogram/dev/component/ 后重新命名。`;
			state.logWarnOnce(message);
		}
		if (state.registry.has(componentName) && base !== "index") {
			const message = `发现 \`${componentName}\` 组件重名! 跳过组件 \`${state.ctx.configService.relativeCwd(baseName)}\` 的自动引入`;
			state.logWarnOnce(message);
			if (removed || removedNames.length > 0) state.bumpVersion();
			scheduleOutputs(removed || removedNames.length > 0, vueSettings.enabled);
			return;
		}
		const sourceWithoutExt = removeExtensionDeep(resolvedJsonPath);
		const from = `/${state.ctx.configService.relativeSrcRoot(state.ctx.configService.relativeCwd(sourceWithoutExt))}`;
		const match = {
			kind: "local",
			entry: {
				path: resolvedJsEntry,
				json,
				jsonPath: resolvedJsonPath,
				type: "component",
				templatePath: resolvedTemplatePath
			},
			value: {
				name: componentName,
				from,
				resolvedId: resolvedJsEntry
			}
		};
		state.registry.set(componentName, match);
		refreshNormalizedLocalComponent(state.registry, state.normalizedLocalComponents, toKebabCaseComponentName(componentName));
		state.scheduleManifestWrite(true);
		const typedSettings = getTypedComponentsSettings(state.ctx);
		const htmlSettings = getHtmlCustomDataSettings(state.ctx);
		if (typedSettings.enabled || htmlSettings.enabled) {
			const astEngine = resolveAstEngine(state.ctx.configService.weappViteConfig);
			let metadataSource = json ?? void 0;
			try {
				if (!metadataSource && JSON_LIKE_FILE_RE.test(resolvedJsonPath)) metadataSource = await fs$1.readJson(resolvedJsonPath);
			} catch {}
			const metadata = extractJsonPropMetadata(metadataSource);
			const baseProps = metadata.props;
			let propMap = new Map(baseProps);
			if (typedSettings.enabled) try {
				propMap = mergePropMaps(baseProps, resolvedJsEntry.endsWith(".vue") ? await extractComponentPropsFromVue(resolvedJsEntry) : extractComponentProps(await fs$1.readFile(resolvedJsEntry, "utf8"), { astEngine }));
			} catch (error) {
				const message = error instanceof Error ? error.message : String(error);
				logger_default.error(`解析组件 \`${state.ctx.configService.relativeCwd(resolvedJsEntry)}\` 属性失败: ${message}`);
				propMap = new Map(baseProps);
			}
			state.componentMetadataMap.set(componentName, {
				types: new Map(propMap),
				docs: new Map(metadata.docs)
			});
		} else state.componentMetadataMap.delete(componentName);
		state.bumpVersion();
		state.scheduleTypedComponentsWrite(typedSettings.enabled || removed || removedNames.length > 0);
		state.scheduleHtmlCustomDataWrite(htmlSettings.enabled || removed || removedNames.length > 0);
		state.scheduleVueComponentsWrite(vueSettings.enabled || removed || removedNames.length > 0);
	}
	function ensureMatcher() {
		const globs = getAutoImportConfig(requireConfigService(state.ctx, "过滤组件前必须初始化 configService。"))?.globs;
		if (!globs || globs.length === 0) {
			state.autoImportState.matcher = void 0;
			state.autoImportState.matcherKey = "";
			return;
		}
		const nextKey = globs.join("\0");
		if (!state.autoImportState.matcher || state.autoImportState.matcherKey !== nextKey) {
			state.autoImportState.matcher = picomatch(globs, { windows: true });
			state.autoImportState.matcherKey = nextKey;
		}
		return state.autoImportState.matcher;
	}
	return {
		registerLocalComponent,
		removeRegisteredComponent,
		ensureMatcher
	};
}
//#endregion
//#region src/runtime/autoImport/service/resolver.ts
const require$2 = createRequire(import.meta.url);
const COMPONENT_HAS_UPPER_RE = /[A-Z]/;
const CAMEL_TO_KEBAB_RE$1 = /([a-z0-9])([A-Z])/g;
const MULTI_UPPER_TO_KEBAB_RE = /([A-Z]+)([A-Z][a-z])/g;
const TRAILING_RELATIVE_PREFIX_RE = /^[./]+/;
const TRAILING_SLASH_RE$1 = /\/+$/;
const SCRIPT_OR_DTS_EXTENSION_RE = /\.(?:[cm]?js|tsx?|jsx|d\.ts)$/;
function createResolverHelpers(state) {
	const miniprogramDirCache = /* @__PURE__ */ new Map();
	const packageRootCache = /* @__PURE__ */ new Map();
	const navigationImportCache = /* @__PURE__ */ new Map();
	const resolveCache = /* @__PURE__ */ new Map();
	const supportFileResolverComponents = /* @__PURE__ */ new Map();
	let compiledResolversCache;
	function getResolveCacheKey(componentName, importerBaseName) {
		return `${importerBaseName ?? ""}\0${componentName}`;
	}
	function getSupportFilesStrategy(resolver) {
		return resolver && typeof resolver.supportFilesStrategy === "string" ? resolver.supportFilesStrategy : "used";
	}
	function toComponentCandidates(componentName) {
		const candidates = [componentName];
		if (!componentName.includes("-") && COMPONENT_HAS_UPPER_RE.test(componentName)) {
			const kebab = componentName.replace(CAMEL_TO_KEBAB_RE$1, "$1-$2").replace(MULTI_UPPER_TO_KEBAB_RE, "$1-$2").toLowerCase();
			if (kebab && kebab !== componentName) candidates.push(kebab);
		}
		return candidates;
	}
	function canUseStaticComponentLookup(resolver) {
		return resolver?.componentLookupStrategy === "static" && Boolean(resolver?.components);
	}
	function getCompiledResolvers(resolvers) {
		if (compiledResolversCache?.source === resolvers) return compiledResolversCache.steps;
		const steps = resolvers.map((resolver) => {
			if (canUseStaticComponentLookup(resolver)) return {
				kind: "static",
				components: resolver.components
			};
			return {
				kind: "dynamic",
				resolver
			};
		});
		compiledResolversCache = {
			source: resolvers,
			steps
		};
		return steps;
	}
	function resolveWithResolver(resolver, componentName, baseName) {
		if (!resolver) return;
		const candidates = toComponentCandidates(componentName);
		const resolverAny = resolver;
		for (const candidate of candidates) {
			if (typeof resolverAny.resolve === "function") {
				const resolved = resolverAny.resolve(candidate, baseName);
				if (resolved) return candidate === componentName ? resolved : {
					...resolved,
					name: componentName
				};
			}
			const from = resolverAny.components?.[candidate];
			if (from) return {
				name: componentName,
				from
			};
			if (typeof resolver === "function") {
				const resolved = resolver(candidate, baseName);
				if (resolved) return candidate === componentName ? resolved : {
					...resolved,
					name: componentName
				};
			}
		}
	}
	function getMiniprogramDir(pkgName, cwd) {
		if (miniprogramDirCache.has(pkgName)) return miniprogramDirCache.get(pkgName);
		try {
			const packageJsonPath = require$2.resolve(`${pkgName}/package.json`, { paths: [cwd] });
			const raw = fs$1.readJsonSync(packageJsonPath, { throws: false });
			const normalized = (typeof raw?.miniprogram === "string" ? raw.miniprogram.trim() : void 0)?.replace(TRAILING_RELATIVE_PREFIX_RE, "").replace(TRAILING_SLASH_RE$1, "");
			miniprogramDirCache.set(pkgName, normalized || void 0);
			return normalized || void 0;
		} catch {
			miniprogramDirCache.set(pkgName, void 0);
			return;
		}
	}
	function getPackageRoot(pkgName, cwd) {
		const cacheKey = `${cwd}\0${pkgName}`;
		const cached = packageRootCache.get(cacheKey);
		if (cached) return cached;
		try {
			const packageJsonPath = require$2.resolve(`${pkgName}/package.json`, { paths: [cwd] });
			const packageRoot = path.dirname(packageJsonPath);
			packageRootCache.set(cacheKey, packageRoot);
			return packageRoot;
		} catch {
			return;
		}
	}
	function resolveNavigationImport(from) {
		const cwd = state.ctx.configService?.cwd;
		if (!cwd) return;
		const cached = navigationImportCache.get(from);
		if (cached) return cached;
		const parsed = parseNpmPackageSpecifier(from);
		if (!parsed?.packageName || !parsed.subPath) return;
		const miniprogramDir = getMiniprogramDir(parsed.packageName, cwd);
		const withMiniprogramSubpath = miniprogramDir && !parsed.subPath.startsWith(`${miniprogramDir}/`) && parsed.subPath !== miniprogramDir ? `${miniprogramDir}/${parsed.subPath}` : parsed.subPath;
		const withMiniprogramDir = `${parsed.packageName}/${withMiniprogramSubpath}`;
		const pkgRoot = getPackageRoot(parsed.packageName, cwd);
		if (pkgRoot) {
			if ([path.join(pkgRoot, `${withMiniprogramSubpath}.d.ts`), path.join(pkgRoot, withMiniprogramSubpath, "index.d.ts")].some((candidate) => fs$1.pathExistsSync(candidate))) {
				navigationImportCache.set(from, withMiniprogramDir);
				return withMiniprogramDir;
			}
		}
		const candidates = [];
		if (!SCRIPT_OR_DTS_EXTENSION_RE.test(withMiniprogramDir)) {
			candidates.push(withMiniprogramDir);
			candidates.push(`${withMiniprogramDir}.js`);
			candidates.push(`${withMiniprogramDir}/index.js`);
		} else candidates.push(withMiniprogramDir);
		for (const candidate of candidates) try {
			require$2.resolve(candidate, { paths: [cwd] });
			navigationImportCache.set(from, candidate);
			return candidate;
		} catch {}
	}
	function collectResolverComponents() {
		return Object.fromEntries([...state.resolvedResolverComponents, ...supportFileResolverComponents]);
	}
	function collectRuntimeResolverComponents() {
		return Object.fromEntries(state.resolvedResolverComponents);
	}
	function collectManifestResolverComponents() {
		return supportFileResolverComponents.size > 0 ? collectResolverComponents() : collectRuntimeResolverComponents();
	}
	function clearResolveCache() {
		resolveCache.clear();
		compiledResolversCache = void 0;
	}
	function hasSameEntries(target, source) {
		const entries = Object.entries(source);
		if (target.size !== entries.length) return false;
		return entries.every(([name, from]) => target.get(name) === from);
	}
	function setSupportFileResolverComponents(components) {
		if (hasSameEntries(supportFileResolverComponents, components)) return false;
		supportFileResolverComponents.clear();
		for (const [name, from] of Object.entries(components)) supportFileResolverComponents.set(name, from);
		return true;
	}
	function clearSupportFileResolverComponents() {
		if (supportFileResolverComponents.size === 0) return false;
		supportFileResolverComponents.clear();
		return true;
	}
	function collectStaticResolverComponentsForSupportFiles() {
		const resolvers = getAutoImportConfig(state.ctx.configService)?.resolvers;
		if (!Array.isArray(resolvers)) return {};
		const allComponents = /* @__PURE__ */ new Map();
		for (const resolver of resolvers) {
			if (getSupportFilesStrategy(resolver) !== "full") continue;
			for (const [name, from] of Object.entries(resolver?.components ?? {})) if (typeof from === "string") allComponents.set(name, from);
		}
		return Object.fromEntries(allComponents);
	}
	function syncResolverComponentProps() {
		const resolverEntries = collectResolverComponents();
		state.resolverComponentsMapRef.value = resolverEntries;
		state.resolverComponentNames.clear();
		for (const name of Object.keys(resolverEntries)) {
			state.resolverComponentNames.add(name);
			if (!state.componentMetadataMap.has(name)) state.componentMetadataMap.set(name, {
				types: /* @__PURE__ */ new Map(),
				docs: /* @__PURE__ */ new Map()
			});
		}
		for (const key of Array.from(state.componentMetadataMap.keys())) {
			if (state.resolverComponentNames.has(key)) continue;
			if (state.registry.has(key)) continue;
			state.componentMetadataMap.delete(key);
		}
	}
	function resolveWithResolvers(componentName, importerBaseName) {
		const cacheKey = getResolveCacheKey(componentName, importerBaseName);
		if (resolveCache.has(cacheKey)) return resolveCache.get(cacheKey) ?? void 0;
		const resolvers = getAutoImportConfig(state.ctx.configService)?.resolvers;
		if (!Array.isArray(resolvers)) {
			resolveCache.set(cacheKey, null);
			return;
		}
		for (const step of getCompiledResolvers(resolvers)) {
			if (step.kind === "static") {
				const components = step.components ?? {};
				for (const candidate of toComponentCandidates(componentName)) {
					const from = components[candidate];
					if (from) {
						const value = {
							name: componentName,
							from
						};
						resolveCache.set(cacheKey, value);
						return value;
					}
				}
				continue;
			}
			if (!step.resolver) continue;
			const value = resolveWithResolver(step.resolver, componentName, importerBaseName ?? "");
			if (value) {
				resolveCache.set(cacheKey, value);
				return value;
			}
		}
		resolveCache.set(cacheKey, null);
	}
	function resolveComponentTypeImport(componentName, from) {
		const resolved = resolveWithResolvers(componentName);
		if (resolved?.from === from && resolved.typeImport === false) return;
		return resolveNavigationImport(from);
	}
	return {
		collectResolverComponents,
		collectRuntimeResolverComponents,
		collectManifestResolverComponents,
		clearResolveCache,
		syncResolverComponentProps,
		setSupportFileResolverComponents,
		clearSupportFileResolverComponents,
		collectStaticResolverComponentsForSupportFiles,
		resolveWithResolvers,
		resolveNavigationImport,
		resolveComponentTypeImport
	};
}
//#endregion
//#region src/runtime/autoImport/service/scheduling.ts
function createAutoImportScheduling(options) {
	const batchedWrites = {
		depth: 0,
		manifest: void 0,
		typed: void 0,
		html: void 0,
		vue: void 0
	};
	let outputWritesSuppressed = 0;
	let outputSettingsSnapshot;
	function getOutputSettingsSnapshot() {
		if (!outputSettingsSnapshot) outputSettingsSnapshot = {
			typed: getTypedComponentsSettings(options.ctx),
			html: getHtmlCustomDataSettings(options.ctx),
			vue: getVueComponentsSettings(options.ctx)
		};
		return outputSettingsSnapshot;
	}
	function deferOrSchedule(kind, shouldWrite) {
		if (outputWritesSuppressed > 0) return;
		if (batchedWrites.depth > 0) {
			const previous = batchedWrites[kind];
			batchedWrites[kind] = previous === void 0 ? shouldWrite : previous || shouldWrite;
			return;
		}
		if (kind === "manifest") {
			options.outputsHelpers.scheduleManifestWrite(shouldWrite);
			return;
		}
		if (kind === "typed") {
			options.outputsHelpers.scheduleTypedComponentsWrite(shouldWrite);
			return;
		}
		if (kind === "html") {
			options.outputsHelpers.scheduleHtmlCustomDataWrite(shouldWrite);
			return;
		}
		options.outputsHelpers.scheduleVueComponentsWrite(shouldWrite);
	}
	function flushBatchedWrites() {
		const manifest = batchedWrites.manifest;
		const typed = batchedWrites.typed;
		const html = batchedWrites.html;
		const vue = batchedWrites.vue;
		batchedWrites.manifest = void 0;
		batchedWrites.typed = void 0;
		batchedWrites.html = void 0;
		batchedWrites.vue = void 0;
		if (manifest !== void 0) options.outputsHelpers.scheduleManifestWrite(manifest);
		if (typed !== void 0) options.outputsHelpers.scheduleTypedComponentsWrite(typed);
		if (html !== void 0) options.outputsHelpers.scheduleHtmlCustomDataWrite(html);
		if (vue !== void 0) options.outputsHelpers.scheduleVueComponentsWrite(vue);
	}
	async function runInBatch(task) {
		batchedWrites.depth += 1;
		try {
			return await task();
		} finally {
			batchedWrites.depth -= 1;
			if (batchedWrites.depth === 0) flushBatchedWrites();
		}
	}
	async function runWithoutOutputWrites(task) {
		outputWritesSuppressed += 1;
		try {
			return await task();
		} finally {
			outputWritesSuppressed -= 1;
		}
	}
	return {
		getOutputSettingsSnapshot,
		deferOrSchedule,
		runInBatch,
		runWithoutOutputWrites
	};
}
//#endregion
//#region src/runtime/autoImport/service/shared.ts
const logWarnCache = new LRUCache({
	max: 512,
	ttl: 36e5
});
function logWarnOnce(message) {
	if (logWarnCache.get(message)) return;
	logger_default.warn(message);
	logWarnCache.set(message, true);
}
//#endregion
//#region src/runtime/autoImport/service/index.ts
function createAutoImportService(ctx) {
	const autoImportState = ctx.runtimeState.autoImport;
	const registry = autoImportState.registry;
	const normalizedLocalComponents = autoImportState.normalizedLocalComponents;
	rebuildNormalizedLocalComponents(registry, normalizedLocalComponents);
	const resolvedResolverComponents = autoImportState.resolvedResolverComponents;
	const manifestFileName = DEFAULT_AUTO_IMPORT_MANIFEST_FILENAME;
	const manifestCache = /* @__PURE__ */ new Map();
	const componentMetadataMap = /* @__PURE__ */ new Map();
	const resolverComponentNames = /* @__PURE__ */ new Set();
	const resolverComponentsMapRef = { value: {} };
	const pendingRegistrations = /* @__PURE__ */ new Set();
	const outputsState = {
		pendingWrite: void 0,
		writeRequested: false,
		pendingTypedWrite: void 0,
		typedWriteRequested: false,
		lastWrittenTypedDefinition: void 0,
		lastTypedDefinitionOutputPath: void 0,
		pendingHtmlCustomDataWrite: void 0,
		htmlCustomDataWriteRequested: false,
		lastWrittenHtmlCustomData: void 0,
		lastHtmlCustomDataOutputPath: void 0,
		pendingVueComponentsWrite: void 0,
		vueComponentsWriteRequested: false,
		lastWrittenVueComponentsDefinition: void 0,
		lastVueComponentsOutputPath: void 0,
		lastWrittenLayoutTypesDefinition: void 0,
		lastLayoutTypesOutputPath: void 0,
		lastHtmlCustomDataEnabled: false,
		lastHtmlCustomDataOutput: void 0,
		lastTypedComponentsEnabled: false,
		lastTypedComponentsOutput: void 0,
		lastVueComponentsEnabled: false,
		lastVueComponentsOutput: void 0,
		preparedSyncStateVersion: void 0,
		preparedSyncStatePromise: void 0
	};
	const resolverHelpers = createResolverHelpers({
		ctx,
		registry,
		resolvedResolverComponents,
		componentMetadataMap,
		resolverComponentNames,
		resolverComponentsMapRef
	});
	const metadataHelpers = createMetadataHelpers({
		ctx,
		registry,
		componentMetadataMap,
		resolverComponentNames,
		resolverComponentsMapRef,
		manifestCache,
		collectResolverComponents: resolverHelpers.collectResolverComponents
	});
	const scheduling = createAutoImportScheduling({
		ctx,
		outputsHelpers: createOutputsHelpers({
			ctx,
			registry,
			manifestFileName,
			manifestCache,
			componentMetadataMap,
			outputsState,
			getPreparedStateVersion: () => autoImportState.version,
			resolverComponentsMapRef,
			collectResolverComponents: resolverHelpers.collectResolverComponents,
			collectManifestResolverComponents: resolverHelpers.collectManifestResolverComponents,
			syncResolverComponentProps: resolverHelpers.syncResolverComponentProps,
			preloadResolverComponentMetadata: metadataHelpers.preloadResolverComponentMetadata,
			getComponentMetadata: metadataHelpers.getComponentMetadata,
			resolveComponentTypeImport: resolverHelpers.resolveComponentTypeImport
		})
	});
	return {
		...createAutoImportActions({
			registry,
			normalizedLocalComponents,
			autoImportState,
			resolvedResolverComponents,
			componentMetadataMap,
			resolverComponentNames,
			resolverHelpers,
			registryHelpers: createRegistryHelpers({
				ctx,
				registry,
				normalizedLocalComponents,
				autoImportState,
				resolverComponentNames,
				componentMetadataMap,
				logWarnOnce,
				bumpVersion: () => {
					autoImportState.version += 1;
				},
				scheduleManifestWrite: (shouldWrite) => scheduling.deferOrSchedule("manifest", shouldWrite),
				scheduleTypedComponentsWrite: (shouldWrite) => scheduling.deferOrSchedule("typed", shouldWrite),
				scheduleHtmlCustomDataWrite: (shouldWrite) => scheduling.deferOrSchedule("html", shouldWrite),
				scheduleVueComponentsWrite: (shouldWrite) => scheduling.deferOrSchedule("vue", shouldWrite)
			}),
			pendingRegistrations,
			getOutputSettingsSnapshot: scheduling.getOutputSettingsSnapshot,
			deferOrSchedule: scheduling.deferOrSchedule,
			outputsState
		}),
		getVersion() {
			return autoImportState.version;
		},
		async runInBatch(task) {
			return await scheduling.runInBatch(task);
		},
		async runWithoutOutputWrites(task) {
			return await scheduling.runWithoutOutputWrites(task);
		}
	};
}
//#endregion
//#region src/runtime/autoImportPlugin.ts
function createAutoImportServicePlugin(ctx) {
	ctx.autoImportService = createAutoImportService(ctx);
	return { name: "weapp-runtime:auto-import-service" };
}
//#endregion
//#region src/runtime/autoRoutesPlugin/matcher.ts
const DEFAULT_AUTO_ROUTE_INCLUDE = ["pages/**"];
const GLOB_MAGIC_PATTERN = /[*?[\]{}()!]/;
const RELATIVE_PREFIX_PATTERN = /^\.?\//;
const LEADING_SLASH_PATTERN = /^\/+/;
function toArray$1(include) {
	if (include == null) return [...DEFAULT_AUTO_ROUTE_INCLUDE];
	return Array.isArray(include) ? [...include] : [include];
}
function normalizeRuleCandidate(candidate) {
	return toPosixPath(candidate.replace(RELATIVE_PREFIX_PATTERN, "").replace(LEADING_SLASH_PATTERN, ""));
}
function createRule(pattern) {
	if (pattern instanceof RegExp) return {
		pattern,
		match(candidate) {
			pattern.lastIndex = 0;
			return pattern.test(candidate);
		}
	};
	return {
		pattern,
		match: picomatch(pattern, { dot: true })
	};
}
function isDefaultAutoRouteInclude(include) {
	return include.length === DEFAULT_AUTO_ROUTE_INCLUDE.length && include.every((pattern, index) => pattern === DEFAULT_AUTO_ROUTE_INCLUDE[index]);
}
function extractStaticPrefix(pattern) {
	const normalized = normalizeRuleCandidate(pattern);
	if (!normalized) return;
	const segments = normalized.split("/");
	const staticSegments = [];
	for (const segment of segments) {
		if (!segment || GLOB_MAGIC_PATTERN.test(segment)) break;
		staticSegments.push(segment);
	}
	if (staticSegments.length === 0) return;
	return staticSegments.join("/");
}
function createAutoRoutesMatcher(include, subPackageRoots = []) {
	const normalizedInclude = toArray$1(include);
	const rules = normalizedInclude.map(createRule);
	const isDefault = isDefaultAutoRouteInclude(normalizedInclude);
	const normalizedSubPackageRoots = [...subPackageRoots].filter(Boolean).map((root) => normalizeRuleCandidate(root)).filter(Boolean);
	function matches(candidate) {
		const normalizedCandidate = normalizeRuleCandidate(candidate);
		if (!normalizedCandidate) return false;
		if (isDefault) {
			if (normalizedCandidate.startsWith("pages/")) return true;
			return normalizedSubPackageRoots.some((root) => {
				return normalizedCandidate.startsWith(`${root}/`);
			});
		}
		return rules.some((rule) => rule.match(normalizedCandidate));
	}
	function getRoots(absoluteSrcRoot) {
		if (isDefault) {
			const roots = /* @__PURE__ */ new Set([path.join(absoluteSrcRoot, "pages")]);
			for (const root of normalizedSubPackageRoots) roots.add(path.join(absoluteSrcRoot, root));
			return Array.from(roots, (root) => normalizePath$1(root));
		}
		const roots = /* @__PURE__ */ new Set();
		for (const rule of rules) {
			if (rule.pattern instanceof RegExp) {
				roots.add(absoluteSrcRoot);
				continue;
			}
			const prefix = extractStaticPrefix(rule.pattern);
			if (!prefix) {
				roots.add(absoluteSrcRoot);
				continue;
			}
			roots.add(path.resolve(absoluteSrcRoot, prefix));
		}
		if (roots.size === 0) roots.add(absoluteSrcRoot);
		return Array.from(roots, (root) => normalizePath$1(root));
	}
	return {
		include: normalizedInclude,
		isDefault,
		matches,
		matchesRelativePath(relativePath) {
			return matches(relativePath);
		},
		getSearchRoots(absoluteSrcRoot) {
			return getRoots(absoluteSrcRoot);
		},
		getWatchRoots(absoluteSrcRoot) {
			return getRoots(absoluteSrcRoot);
		}
	};
}
//#endregion
//#region src/autoRoutesConfig.ts
function resolveWeappAutoRoutesConfig(config) {
	if (config == null || config === false) return {
		enabled: false,
		typedRouter: false,
		include: [...DEFAULT_AUTO_ROUTE_INCLUDE],
		persistentCache: false,
		watch: false
	};
	const record = typeof config === "object" && config ? config : {};
	return {
		enabled: config === true || record.enabled !== false,
		typedRouter: record.typedRouter !== false,
		include: record.include == null ? [...DEFAULT_AUTO_ROUTE_INCLUDE] : Array.isArray(record.include) ? [...record.include] : [record.include],
		persistentCache: typeof record.persistentCache === "string" || record.persistentCache === true,
		persistentCachePath: typeof record.persistentCache === "string" ? record.persistentCache : void 0,
		watch: record.watch !== false
	};
}
//#endregion
//#region src/runtime/autoRoutesPlugin/generatedPaths.ts
const AUTO_ROUTES_CACHE_FILE$1 = ".weapp-vite/auto-routes.cache.json";
const TYPED_ROUTER_OUTPUT_FILE$1 = ".weapp-vite/typed-router.d.ts";
const GENERATED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
	".cache",
	".rolldown-require",
	".rolldown-require-cache",
	".tmp",
	".weapp-vite",
	".wevu-config",
	"__temp__",
	"coverage",
	"dist",
	"miniprogram_npm",
	"node_modules"
]);
const GENERATED_FILE_NAMES = /* @__PURE__ */ new Set([path.basename(AUTO_ROUTES_CACHE_FILE$1), path.basename(TYPED_ROUTER_OUTPUT_FILE$1)]);
function stripQuery(candidate) {
	return candidate.split("?")[0];
}
function resolveGeneratedCandidatePath(candidate, cwd) {
	const pathWithoutQuery = stripQuery(candidate);
	if (!pathWithoutQuery) return;
	return normalizePath$1(path.isAbsolute(pathWithoutQuery) ? pathWithoutQuery : path.resolve(cwd, pathWithoutQuery));
}
function isAutoRoutesGeneratedDirectoryName(name) {
	return GENERATED_DIRECTORY_NAMES.has(name);
}
function isAutoRoutesGeneratedFileName(fileName) {
	return GENERATED_FILE_NAMES.has(fileName) || fileName.includes(".auto-routes.") || fileName.includes(".auto-routes-");
}
function isAutoRoutesGeneratedRelativePath(relativePath) {
	const segments = toPosixPath(relativePath).split("/").filter(Boolean);
	if (segments.some(isAutoRoutesGeneratedDirectoryName)) return true;
	const fileName = segments[segments.length - 1];
	return Boolean(fileName && isAutoRoutesGeneratedFileName(fileName));
}
function resolveAutoRoutesManagedOutputPaths(ctx) {
	const configService = ctx.configService;
	const outputPaths = /* @__PURE__ */ new Set();
	if (!configService) return outputPaths;
	const baseDir = typeof configService.configFilePath === "string" ? path.dirname(configService.configFilePath) : configService.cwd;
	if (!baseDir) return outputPaths;
	outputPaths.add(normalizePath$1(path.resolve(baseDir, TYPED_ROUTER_OUTPUT_FILE$1)));
	outputPaths.add(normalizePath$1(path.resolve(baseDir, AUTO_ROUTES_CACHE_FILE$1)));
	const autoRoutesConfig = resolveWeappAutoRoutesConfig(configService.weappViteConfig?.autoRoutes);
	if (autoRoutesConfig.persistentCache) outputPaths.add(normalizePath$1(path.resolve(baseDir, autoRoutesConfig.persistentCachePath ?? AUTO_ROUTES_CACHE_FILE$1)));
	return outputPaths;
}
function isAutoRoutesGeneratedPath(candidate, options) {
	const absolutePath = resolveGeneratedCandidatePath(candidate, options.cwd);
	if (!absolutePath) return false;
	for (const outputPath of options.managedOutputPaths ?? []) if (absolutePath === normalizePath$1(outputPath)) return true;
	const normalizedSrcRoot = normalizePath$1(options.absoluteSrcRoot);
	const relativePath = toPosixPath(path.relative(normalizedSrcRoot, absolutePath));
	if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) return false;
	return isAutoRoutesGeneratedRelativePath(relativePath);
}
//#endregion
//#region src/runtime/autoRoutesPlugin/pageRoots.ts
const SKIPPED_DIRECTORIES$1 = /* @__PURE__ */ new Set([
	".git",
	".husky",
	".idea",
	".turbo"
]);
function hasNestedPagesRoot(root, discoveredPagesRoots) {
	const normalizedRoot = toPosixPath(root);
	return [...discoveredPagesRoots].some((pagesRoot) => {
		const normalizedPagesRoot = toPosixPath(pagesRoot);
		return normalizedPagesRoot === `${normalizedRoot}/pages` || normalizedPagesRoot.startsWith(`${normalizedRoot}/pages/`);
	});
}
function classifyPagesRootEntry(current, entry) {
	if (!entry.isDirectory()) return;
	if (SKIPPED_DIRECTORIES$1.has(entry.name) || isAutoRoutesGeneratedDirectoryName(entry.name)) return;
	const nextPath = path.join(current, entry.name);
	return entry.name === "pages" ? { pageRoot: nextPath } : { nextPath };
}
async function discoverPagesRootsWithReaddir(root, readdir) {
	let queue = [root];
	const pagesRoots = /* @__PURE__ */ new Set();
	while (queue.length > 0) {
		const currentBatch = queue;
		queue = [];
		const entriesBatch = await Promise.all(currentBatch.map(async (current) => {
			try {
				return {
					current,
					entries: await readdir(current)
				};
			} catch {
				return {
					current,
					entries: []
				};
			}
		}));
		for (const { current, entries } of entriesBatch) for (const entry of entries) {
			const classified = classifyPagesRootEntry(current, entry);
			if (!classified) continue;
			if ("pageRoot" in classified) {
				if (classified.pageRoot) pagesRoots.add(classified.pageRoot);
				continue;
			}
			queue.push(classified.nextPath);
		}
	}
	return pagesRoots;
}
async function discoverPagesRoots(root) {
	return await discoverPagesRootsWithReaddir(root, async (dir) => await fs$1.readdir(dir, { withFileTypes: true }));
}
function buildDefaultSearchRoots(absoluteSrcRoot, discoveredPagesRoots, subPackageRoots) {
	const roots = [];
	const discoveredRoots = [...discoveredPagesRoots];
	if (discoveredRoots.length > 0) roots.push(...discoveredRoots);
	else roots.push(absoluteSrcRoot);
	for (const root of subPackageRoots ?? []) {
		if (!root) continue;
		const absoluteRoot = path.resolve(absoluteSrcRoot, root);
		if (!hasNestedPagesRoot(absoluteRoot, discoveredRoots)) roots.push(absoluteRoot);
	}
	return roots;
}
async function resolveDefaultSearchRoots(absoluteSrcRoot, subPackageRoots) {
	return buildDefaultSearchRoots(absoluteSrcRoot, await discoverPagesRoots(absoluteSrcRoot), subPackageRoots);
}
//#endregion
//#region src/runtime/autoRoutesPlugin/candidates.ts
const SCRIPT_EXTENSIONS = new Set(scriptExtensions.map((ext) => `.${ext}`));
const TEMPLATE_EXTENSIONS = new Set(templateExtensions.map((ext) => `.${ext}`));
const VUE_EXTENSIONS = new Set(vueExtensions.map((ext) => `.${ext}`));
const STYLE_EXTENSIONS = new Set(supportedCssLangs.map((ext) => `.${ext}`));
const CONFIG_SUFFIXES = configExtensions.map((ext) => `.${ext}`);
const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
	".git",
	".husky",
	".idea",
	".turbo"
]);
const SCRIPT_SIDECAR_PATTERN = /\.(?:wxs|sjs)\.[jt]s$/i;
const TEMPLATE_SIDECAR_PATTERN = new RegExp(`\\.(?:${templateExtensions.join("|")})\\.[jt]s$`, "i");
function isConfigFile(filePath) {
	return CONFIG_SUFFIXES.some((ext) => filePath.endsWith(ext));
}
function isScriptFile(filePath) {
	if (filePath.endsWith(".d.ts")) return false;
	if (SCRIPT_SIDECAR_PATTERN.test(filePath) || TEMPLATE_SIDECAR_PATTERN.test(filePath)) return false;
	const ext = path.extname(filePath);
	return SCRIPT_EXTENSIONS.has(ext);
}
function isVueFile(filePath) {
	const ext = path.extname(filePath);
	return VUE_EXTENSIONS.has(ext);
}
function isTemplateFile(filePath) {
	const ext = path.extname(filePath);
	return TEMPLATE_EXTENSIONS.has(ext);
}
function isStyleFile(filePath) {
	const ext = path.extname(filePath);
	return STYLE_EXTENSIONS.has(ext);
}
function ensureCandidate(map, base) {
	let candidate = map.get(base);
	if (!candidate) {
		candidate = {
			base,
			files: /* @__PURE__ */ new Set(),
			hasScript: false,
			hasTemplate: false
		};
		map.set(base, candidate);
	}
	return candidate;
}
function resolveCandidateSearchRoots(absoluteSrcRoot, matcher, searchRoots) {
	if (searchRoots) return [...new Set(searchRoots)];
	return matcher.isDefault ? void 0 : matcher.getSearchRoots(absoluteSrcRoot);
}
function resolveCollectTargetRoot(absoluteSrcRoot, root) {
	const targetRoot = path.isAbsolute(root) ? root : path.resolve(absoluteSrcRoot, root);
	return toPosixPath(targetRoot).startsWith(toPosixPath(absoluteSrcRoot)) ? targetRoot : void 0;
}
async function shouldCollectTargetRoot(targetRoot) {
	return fs$1.pathExists(targetRoot);
}
async function safeCrawlCandidateFiles(crawler, targetRoot) {
	try {
		return await crawler.crawl(targetRoot).withPromise();
	} catch {
		return [];
	}
}
function resolveCandidateEntryPath(absoluteSrcRoot, entryPath) {
	const normalizedRelative = toPosixPath(path.relative(absoluteSrcRoot, entryPath));
	if (!normalizedRelative || normalizedRelative.startsWith("..")) return;
	if (isAutoRoutesGeneratedRelativePath(normalizedRelative)) return;
	return {
		normalizedRelative,
		relativeBase: removeExtensionDeep(normalizedRelative),
		candidateBase: removeExtensionDeep(entryPath)
	};
}
function shouldCollectCandidateEntry(matcher, resolvedEntryPath) {
	return Boolean(resolvedEntryPath && matcher.matches(resolvedEntryPath.relativeBase));
}
function applyCandidateEntryFile(candidate, entryPath) {
	candidate.files.add(entryPath);
	if (isConfigFile(entryPath)) {
		candidate.jsonPath = entryPath;
		return;
	}
	if (isVueFile(entryPath) || isScriptFile(entryPath)) candidate.hasScript = true;
	if (isTemplateFile(entryPath)) candidate.hasTemplate = true;
}
function applyCandidateEntryToMap(candidates, entryPath, resolvedEntryPath) {
	applyCandidateEntryFile(ensureCandidate(candidates, resolvedEntryPath.candidateBase), entryPath);
}
async function collectCandidateFilesFromRoots(absoluteSrcRoot, matcher, roots, options) {
	const rootFiles = await Promise.all(roots.map(async (root) => {
		const targetRoot = resolveCollectTargetRoot(absoluteSrcRoot, root);
		if (!targetRoot) return [];
		if (!await options.shouldCollectTargetRoot(targetRoot)) return [];
		const crawler = options.createCrawler();
		return await options.safeCrawlCandidateFiles(crawler, targetRoot);
	}));
	const candidates = /* @__PURE__ */ new Map();
	for (const files of rootFiles) for (const entryPath of files) {
		const resolvedEntryPath = resolveCandidateEntryPath(absoluteSrcRoot, entryPath);
		if (!shouldCollectCandidateEntry(matcher, resolvedEntryPath)) continue;
		if (resolvedEntryPath) applyCandidateEntryToMap(candidates, entryPath, resolvedEntryPath);
	}
	return candidates;
}
async function collectCandidates(absoluteSrcRoot, include, subPackageRoots, searchRoots) {
	const matcher = createAutoRoutesMatcher(include, subPackageRoots);
	const roots = resolveCandidateSearchRoots(absoluteSrcRoot, matcher, searchRoots) ?? [];
	if (!searchRoots) {
		if (matcher.isDefault) roots.push(...await resolveDefaultSearchRoots(absoluteSrcRoot, subPackageRoots));
		else roots.push(...matcher.getSearchRoots(absoluteSrcRoot));
	}
	const createCrawler = () => new fdir({
		includeDirs: false,
		pathSeparator: "/",
		excludeSymlinks: true,
		suppressErrors: true,
		exclude(dirName) {
			return SKIPPED_DIRECTORIES.has(dirName) || isAutoRoutesGeneratedDirectoryName(dirName);
		}
	}).withFullPaths();
	return await collectCandidateFilesFromRoots(absoluteSrcRoot, matcher, roots, {
		shouldCollectTargetRoot,
		safeCrawlCandidateFiles,
		createCrawler
	});
}
function cloneCandidate(candidate) {
	return {
		base: candidate.base,
		files: new Set(candidate.files),
		hasScript: candidate.hasScript,
		hasTemplate: candidate.hasTemplate,
		jsonPath: candidate.jsonPath
	};
}
function areSetsEqual(a, b) {
	if (a.size !== b.size) return false;
	for (const value of a) if (!b.has(value)) return false;
	return true;
}
//#endregion
//#region src/runtime/autoRoutesPlugin/routes/format.ts
const INDENT = "    ";
const TS_STRING_PLACEHOLDER = "${string}";
const TS_PATH_PLACEHOLDER = "${Path}";
function formatTuple(values, baseIndent = "") {
	if (values.length === 0) return "[]";
	const indent = `${baseIndent}${INDENT}`;
	return `[\n${values.map((value) => `${indent}${JSON.stringify(value)}`).join(",\n")}\n${baseIndent}]`;
}
function formatSubPackagesTuple(subPackages, baseIndent = "") {
	if (subPackages.length === 0) return "[]";
	const lines = ["["];
	const objectIndent = `${baseIndent}${INDENT}`;
	const fieldIndent = `${objectIndent}${INDENT}`;
	subPackages.forEach((pkg, index) => {
		lines.push(`${objectIndent}{`);
		lines.push(`${fieldIndent}root: ${JSON.stringify(pkg.root)};`);
		const pages = formatTuple(pkg.pages, fieldIndent);
		lines.push(`${fieldIndent}pages: ${pages};`);
		lines.push(`${fieldIndent}[k: string]: unknown;`);
		lines.push(`${objectIndent}}${index < subPackages.length - 1 ? "," : ""}`);
	});
	lines.push(`${baseIndent}]`);
	return lines.join("\n");
}
function createTypedRouterDefinition(routes) {
	const pagesType = formatTuple(routes.pages, INDENT);
	const entriesType = formatTuple(routes.entries, INDENT);
	const subPackagesType = formatSubPackagesTuple(routes.subPackages, INDENT);
	return [
		"/* eslint-disable */",
		"// biome-ignore lint: disable",
		"// oxlint-disable",
		"// ------",
		"// 由 weapp-vite 自动生成,请勿编辑。",
		"import 'wevu/router';",
		"",
		"declare module 'weapp-vite/auto-routes' {",
		`    export type AutoRoutesPages = ${pagesType};`,
		`    export type AutoRoutesEntries = ${entriesType};`,
		`    export type AutoRoutesSubPackages = ${subPackagesType};`,
		"    export type AutoRoutesSubPackage = AutoRoutesSubPackages[number];",
		"    export interface AutoRoutes {",
		"        readonly pages: AutoRoutesPages;",
		"        readonly entries: AutoRoutesEntries;",
		"        readonly subPackages: AutoRoutesSubPackages;",
		"    }",
		"    export type AutoRouteEntry = AutoRoutesEntries[number];",
		`    export type AutoRoutesRelativeUrl = \`./${TS_STRING_PLACEHOLDER}\` | \`../${TS_STRING_PLACEHOLDER}\`;`,
		`    export type AutoRoutesAbsoluteUrl<Path extends string> = Path | \`/${TS_PATH_PLACEHOLDER}\` | \`${TS_PATH_PLACEHOLDER}?${TS_STRING_PLACEHOLDER}\` | \`/${TS_PATH_PLACEHOLDER}?${TS_STRING_PLACEHOLDER}\`;`,
		"    export type AutoRoutesUrl = AutoRoutesAbsoluteUrl<AutoRouteEntry> | AutoRoutesRelativeUrl;",
		"    export type AutoRouteNavigateOption = {",
		"        readonly url: AutoRoutesUrl;",
		"    } & Record<string, any>;",
		"    export interface AutoRoutesMiniProgramRouter {",
		"        switchTab: (option: AutoRouteNavigateOption) => unknown;",
		"        reLaunch: (option: AutoRouteNavigateOption) => unknown;",
		"        redirectTo: (option: AutoRouteNavigateOption) => unknown;",
		"        navigateTo: (option: AutoRouteNavigateOption) => unknown;",
		"        navigateBack: (option?: Record<string, any>) => unknown;",
		"    }",
		"    export type AutoRoutesWxRouter = AutoRoutesMiniProgramRouter;",
		"    export const routes: AutoRoutes;",
		"    export const pages: AutoRoutesPages;",
		"    export const entries: AutoRoutesEntries;",
		"    export const subPackages: AutoRoutesSubPackages;",
		"    export const miniProgramRouter: AutoRoutesMiniProgramRouter;",
		"    export const wxRouter: AutoRoutesWxRouter;",
		"    export default routes;",
		"}",
		"",
		"declare module 'wevu/router' {",
		"    interface WevuTypedRouterRouteMap {",
		"        entries: import('weapp-vite/auto-routes').AutoRoutesEntries[number];",
		"    }",
		"}",
		""
	].join("\n");
}
//#endregion
//#region src/runtime/autoRoutesPlugin/routes/resolve.ts
function resolveConfiguredSubPackageRoute(normalizedBase, subPackageRoots) {
	const roots = [...subPackageRoots].sort((a, b) => b.length - a.length);
	for (const root of roots) {
		if (!root || normalizedBase === root || !normalizedBase.startsWith(`${root}/`)) continue;
		const pagePath = normalizedBase.slice(root.length + 1);
		if (!pagePath) continue;
		return {
			root,
			pagePath,
			entry: normalizedBase
		};
	}
}
function resolveRoute(normalizedBase, subPackageRoots = []) {
	if (!normalizedBase) return;
	const configuredSubPackageRoute = resolveConfiguredSubPackageRoute(normalizedBase, subPackageRoots);
	if (configuredSubPackageRoute) return configuredSubPackageRoute;
	if (normalizedBase.startsWith("pages/")) return {
		entry: normalizedBase,
		pagePath: normalizedBase
	};
	const idx = normalizedBase.indexOf("/pages/");
	if (idx === -1) return {
		entry: normalizedBase,
		pagePath: normalizedBase
	};
	const root = normalizedBase.slice(0, idx);
	const pagePath = normalizedBase.slice(idx + 1);
	if (!root || !pagePath.startsWith("pages/")) return;
	return {
		root,
		pagePath,
		entry: `${root}/${pagePath}`
	};
}
//#endregion
//#region src/runtime/buildScope.ts
const MAIN_SCOPE_TOKEN = "main";
const BUILD_SCOPE_CLI_SOURCE = "__weappViteBuildScopeSource";
function normalizeScopeRoot(value) {
	return normalizeRoot(value.trim());
}
function parseScopeTokens(value) {
	const tokens = (Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : []).map((token) => normalizeScopeRoot(token)).filter((token) => token.length > 0);
	return [...new Set(tokens)];
}
function normalizeBuildScopeConfig(config, source) {
	if (!config) return;
	if (typeof config === "string" || Array.isArray(config)) {
		const tokens = parseScopeTokens(config);
		if (tokens.length === 0) return;
		return {
			enabled: true,
			includeMainPackage: true,
			subPackageRoots: tokens.filter((token) => token !== MAIN_SCOPE_TOKEN),
			source
		};
	}
	const include = parseScopeTokens(config.include);
	const includeMainPackage = config.includeMainPackage ?? true;
	const subPackageRoots = include.filter((token) => token !== MAIN_SCOPE_TOKEN);
	if (!includeMainPackage && subPackageRoots.length === 0) return;
	return {
		enabled: true,
		includeMainPackage,
		subPackageRoots,
		source: config[BUILD_SCOPE_CLI_SOURCE] === true ? "cli" : source
	};
}
function resolveBuildScope(config) {
	return normalizeBuildScopeConfig(config, "config");
}
function createBuildScopeConfigFromCli(value) {
	const tokens = parseScopeTokens(value);
	if (tokens.length === 0) return;
	return {
		includeMainPackage: true,
		include: tokens.filter((token) => token !== MAIN_SCOPE_TOKEN),
		[BUILD_SCOPE_CLI_SOURCE]: true
	};
}
function isSubPackageInScope(subPackage, roots) {
	const root = subPackage.root ? normalizeRoot(subPackage.root) : void 0;
	return Boolean(root && roots.has(root));
}
function normalizeScopedSubPackage(subPackage) {
	return {
		...subPackage,
		root: normalizeRoot(subPackage.root ?? ""),
		pages: Array.isArray(subPackage.pages) ? subPackage.pages : []
	};
}
function filterPreloadRule(preloadRule, scopedPages, scopedPackageIdentifiers, includeMainPackage) {
	if (!preloadRule || typeof preloadRule !== "object") return preloadRule;
	const scopedPreloadRule = {};
	for (const [pagePath, rule] of Object.entries(preloadRule)) {
		const normalizedPagePath = normalizeRoot(pagePath);
		if (!scopedPages.has(normalizedPagePath)) continue;
		if (!rule || typeof rule !== "object" || !("packages" in rule)) {
			scopedPreloadRule[pagePath] = rule;
			continue;
		}
		const packages = rule.packages;
		if (!Array.isArray(packages)) {
			scopedPreloadRule[pagePath] = rule;
			continue;
		}
		const filteredPackages = packages.filter((packageRoot) => {
			if (typeof packageRoot !== "string") return false;
			const normalizedPackageRoot = normalizeRoot(packageRoot);
			return normalizedPackageRoot === "__APP__" ? includeMainPackage : scopedPackageIdentifiers.has(normalizedPackageRoot);
		});
		if (filteredPackages.length > 0) scopedPreloadRule[pagePath] = {
			...rule,
			packages: filteredPackages
		};
	}
	return Object.keys(scopedPreloadRule).length > 0 ? scopedPreloadRule : void 0;
}
function collectScopedAppGraph(pages, subPackages) {
	const mainPages = new Set(pages.map((page) => normalizeRoot(page)));
	const allPages = new Set(mainPages);
	const packageIdentifiers = /* @__PURE__ */ new Set();
	for (const subPackage of subPackages) {
		const root = normalizeRoot(subPackage.root ?? "");
		if (!root) continue;
		packageIdentifiers.add(root);
		if (typeof subPackage.name === "string" && subPackage.name.trim()) packageIdentifiers.add(normalizeRoot(subPackage.name));
		for (const page of subPackage.pages ?? []) allPages.add(normalizeRoot(`${root}/${page}`));
	}
	return {
		allPages,
		mainPages,
		packageIdentifiers
	};
}
function filterTabBar(tabBar, mainPages) {
	if (!tabBar || !Array.isArray(tabBar.list)) return tabBar;
	const list = tabBar.list.filter((item) => {
		return typeof item.pagePath === "string" && mainPages.has(normalizeRoot(item.pagePath));
	});
	if (list.length < 2) return;
	return {
		...tabBar,
		list
	};
}
function applyBuildScopeToAppConfig(config, scope) {
	if (!scope?.enabled) return config;
	const scopedRoots = new Set(scope.subPackageRoots);
	const scopedSubPackages = (Array.isArray(config.subPackages) ? config.subPackages : Array.isArray(config.subpackages) ? config.subpackages : []).filter((subPackage) => isSubPackageInScope(subPackage, scopedRoots)).map(normalizeScopedSubPackage);
	config.pages = scope.includeMainPackage && Array.isArray(config.pages) ? config.pages : [];
	config.subPackages = scopedSubPackages;
	delete config.subpackages;
	const scopedGraph = collectScopedAppGraph(config.pages, scopedSubPackages);
	const preloadRule = filterPreloadRule(config.preloadRule, scopedGraph.allPages, scopedGraph.packageIdentifiers, scope.includeMainPackage);
	if (preloadRule) config.preloadRule = preloadRule;
	else delete config.preloadRule;
	const tabBar = filterTabBar(config.tabBar, scopedGraph.mainPages);
	if (tabBar) config.tabBar = tabBar;
	else delete config.tabBar;
	if (typeof config.entryPagePath === "string" && !scopedGraph.mainPages.has(normalizeRoot(config.entryPagePath))) delete config.entryPagePath;
	return config;
}
function applyBuildScopeToAutoRoutes(routes, scope) {
	if (!scope?.enabled) return routes;
	const scopedRoots = new Set(scope.subPackageRoots);
	const subPackages = routes.subPackages.filter((subPackage) => scopedRoots.has(normalizeRoot(subPackage.root))).map((subPackage) => ({
		...subPackage,
		root: normalizeRoot(subPackage.root)
	}));
	const scopedEntries = /* @__PURE__ */ new Set([...scope.includeMainPackage ? routes.pages : [], ...subPackages.flatMap((subPackage) => subPackage.pages.map((page) => `${subPackage.root}/${page}`))]);
	return {
		pages: scope.includeMainPackage ? routes.pages : [],
		entries: routes.entries.filter((entry) => scopedEntries.has(entry)),
		subPackages
	};
}
//#endregion
//#region src/utils/miniProgramGlobals.ts
function getMiniProgramGlobalKeys() {
	return [...getMiniProgramRuntimeGlobalKeysByResolvePriority()];
}
function getRouteRuntimeGlobalKeys() {
	return [...getMiniProgramRouteRuntimeGlobalKeys()];
}
function getMiniProgramPlatformGlobalKey(platform) {
	if (!platform) return;
	const resolvedPlatform = resolveMiniProgramPlatform(platform);
	return resolvedPlatform ? getMiniProgramRuntimeGlobalKey(resolvedPlatform) : platform;
}
function resolveMiniProgramGlobalHostExpression(hostExpression) {
	return hostExpression ?? "globalThis";
}
function createMiniProgramTopLevelAccessChecks(options) {
	return (options?.globalKeys ?? getMiniProgramGlobalKeys()).map((key, index) => {
		return `${index === 0 ? "((" : " || ("}typeof ${key} !== 'undefined' && ${key})`;
	});
}
function createMiniProgramTopLevelResolveExpression(options) {
	return [...createMiniProgramTopLevelAccessChecks({ globalKeys: options?.globalKeys }), ` || ${options?.fallbackExpression ?? "undefined"})`].join("");
}
function createMiniProgramGlobalResolveExpression(options) {
	const globalKeys = options?.globalKeys ?? getMiniProgramGlobalKeys();
	const hostExpression = resolveMiniProgramGlobalHostExpression(options?.hostExpression);
	return `(${globalKeys.map((key) => `${hostExpression}.${key}`).join(" ?? ")})`;
}
//#endregion
//#region src/runtime/autoRoutesPlugin/service/shared.ts
const AUTO_ROUTES_CACHE_FILE = ".weapp-vite/auto-routes.cache.json";
const TYPED_ROUTER_OUTPUT_FILE = ".weapp-vite/typed-router.d.ts";
function updateWatchTargets(target, next) {
	target.clear();
	for (const item of next) target.add(item);
}
function createEmptyAutoRoutesSnapshot() {
	return {
		pages: [],
		entries: [],
		subPackages: []
	};
}
function createAutoRoutesRuntimeLines() {
	return [
		"const pages = routes.pages;",
		"const entries = routes.entries;",
		"const subPackages = routes.subPackages;",
		`const resolveMiniProgramGlobal = () => ${createMiniProgramGlobalResolveExpression({ globalKeys: getRouteRuntimeGlobalKeys() })};`,
		"const callRouteMethod = (methodName, option) => {",
		"  const miniProgramGlobal = resolveMiniProgramGlobal();",
		"  const routeMethod = miniProgramGlobal?.[methodName];",
		"  if (typeof routeMethod !== \"function\") {",
		"    throw new Error(\"[weapp-vite] 当前运行环境不支持路由方法: \" + methodName);",
		"  }",
		"  if (option === undefined) {",
		"    return routeMethod.call(miniProgramGlobal);",
		"  }",
		"  return routeMethod.call(miniProgramGlobal, option);",
		"};",
		"const miniProgramRouter = {",
		"  switchTab(option) { return callRouteMethod(\"switchTab\", option); },",
		"  reLaunch(option) { return callRouteMethod(\"reLaunch\", option); },",
		"  redirectTo(option) { return callRouteMethod(\"redirectTo\", option); },",
		"  navigateTo(option) { return callRouteMethod(\"navigateTo\", option); },",
		"  navigateBack(option) { return callRouteMethod(\"navigateBack\", option); },",
		"};",
		"const wxRouter = miniProgramRouter;",
		"export { routes, pages, entries, subPackages, wxRouter, miniProgramRouter };",
		"export default routes;"
	];
}
function createAutoRoutesModuleCode(serialized) {
	return [
		"const routes = ",
		serialized,
		";",
		...createAutoRoutesRuntimeLines()
	].join("\n");
}
function createAutoRoutesArtifacts(snapshot) {
	const serialized = JSON.stringify(snapshot, null, 2);
	return {
		serialized,
		moduleCode: createAutoRoutesModuleCode(serialized),
		typedDefinition: createTypedRouterDefinition(snapshot)
	};
}
function resetAutoRoutesState(state) {
	const emptySnapshot = createEmptyAutoRoutesSnapshot();
	const artifacts = createAutoRoutesArtifacts(emptySnapshot);
	updateRoutesReference(state.routes, emptySnapshot);
	state.serialized = artifacts.serialized;
	state.typedDefinition = artifacts.typedDefinition;
	state.moduleCode = artifacts.moduleCode;
	updateWatchTargets(state.watchFiles, /* @__PURE__ */ new Set());
	updateWatchTargets(state.watchDirs, /* @__PURE__ */ new Set());
	state.dirty = false;
	state.initialized = true;
	state.candidates.clear();
	state.needsFullRescan = true;
}
function resolveTypedRouterOutputPath(configService) {
	const baseDir = typeof configService.configFilePath === "string" ? path.dirname(configService.configFilePath) : configService.cwd;
	return path.resolve(baseDir, TYPED_ROUTER_OUTPUT_FILE);
}
function resolvePersistentCacheBaseDir(configService) {
	return (typeof configService.configFilePath === "string" ? path.dirname(configService.configFilePath) : configService.cwd) || void 0;
}
function applyPersistentCache(state, cache) {
	const watchFiles = Array.isArray(cache.watchFiles) ? cache.watchFiles : [];
	updateRoutesReference(state.routes, cache.snapshot);
	state.serialized = cache.serialized;
	state.moduleCode = cache.moduleCode;
	state.typedDefinition = cache.typedDefinition;
	updateWatchTargets(state.watchFiles, new Set(watchFiles));
	updateWatchTargets(state.watchDirs, new Set(Array.isArray(cache.watchDirs) ? cache.watchDirs : []));
	state.dirty = false;
	state.initialized = true;
	state.needsFullRescan = true;
}
function createPersistentCachePayload(state, fileMtims) {
	return {
		version: 1,
		snapshot: cloneRoutes(state.routes),
		serialized: state.serialized,
		moduleCode: state.moduleCode,
		typedDefinition: state.typedDefinition,
		watchFiles: [...state.watchFiles],
		watchDirs: [...state.watchDirs],
		fileMtims
	};
}
//#endregion
//#region src/runtime/autoRoutesPlugin/subPackageRoots.ts
function collectAppJsonSubPackageRoots(ctx) {
	const appJson = ctx.runtimeState.scan?.appEntry?.json;
	return [...appJson?.subPackages ?? [], ...appJson?.subpackages ?? []].map((item) => item.root).filter((root) => Boolean(root));
}
function getAutoRoutesSubPackageRoots(ctx) {
	const roots = new Set(Object.keys(ctx.configService?.weappViteConfig?.subPackages ?? {}));
	const npmSubPackageRoots = Object.keys(ctx.configService?.weappViteConfig?.npm?.subPackages ?? {});
	for (const root of npmSubPackageRoots) roots.add(root);
	for (const root of collectAppJsonSubPackageRoots(ctx)) roots.add(root);
	return [...roots];
}
//#endregion
//#region src/runtime/autoRoutesPlugin/shared.ts
/**
* 聚合 auto-routes 配置、分包根目录和 matcher,避免多处重复组装。
*/
function resolveAutoRoutesMatcherContext(ctx) {
	const autoRoutesConfig = resolveWeappAutoRoutesConfig(ctx.configService?.weappViteConfig?.autoRoutes);
	const subPackageRoots = getAutoRoutesSubPackageRoots(ctx);
	return {
		autoRoutesConfig,
		subPackageRoots,
		matcher: createAutoRoutesMatcher(autoRoutesConfig.include, subPackageRoots)
	};
}
/**
* 统一解析 auto-routes 相关文件路径,屏蔽查询串和平台路径分隔符差异。
*/
function resolveAutoRoutesPath(candidate, options) {
	const [pathWithoutQuery] = candidate.split("?");
	if (!pathWithoutQuery) return;
	const normalizedSrcRoot = normalizePath$1(options.absoluteSrcRoot);
	const normalizedCandidate = normalizePath$1(path.isAbsolute(pathWithoutQuery) ? pathWithoutQuery : path.resolve(options.cwd, pathWithoutQuery));
	const relativePath = toPosixPath(path.relative(normalizedSrcRoot, normalizedCandidate));
	if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) return;
	return {
		absolutePath: normalizedCandidate,
		relativePath
	};
}
/**
* 解析 auto-routes 候选文件对应的无扩展 base 路径,供候选收集与增量更新复用。
*/
function resolveAutoRoutesBasePath(candidate, options) {
	const resolvedPath = resolveAutoRoutesPath(candidate, options);
	if (!resolvedPath) return;
	return {
		base: removeExtensionDeep(resolvedPath.absolutePath),
		relativeBase: removeExtensionDeep(resolvedPath.relativePath)
	};
}
/**
* 解析 auto-routes 别名可能指向的编译产物与源码入口。
*/
function resolveAutoRoutesAliasTargets(packageRoot) {
	const targets = /* @__PURE__ */ new Set();
	if (!packageRoot) return targets;
	const candidates = [
		path.resolve(packageRoot, "src/auto-routes.ts"),
		path.resolve(packageRoot, "auto-routes.ts"),
		path.resolve(packageRoot, "dist/auto-routes.mjs"),
		path.resolve(packageRoot, "dist/auto-routes.js")
	];
	for (const candidate of candidates) targets.add(path.normalize(candidate));
	return targets;
}
/**
* 判断文件是否属于 auto-routes 的 pages 关注范围,包括显式 include 和 watch root。
*/
function isAutoRoutesPagesRelatedPath(candidate, options) {
	if (isAutoRoutesGeneratedPath(candidate, options)) return false;
	const resolvedPath = resolveAutoRoutesPath(candidate, options);
	if (!resolvedPath) return false;
	const matcher = createAutoRoutesMatcher(options.include, options.subPackageRoots);
	if (matcher.matches(removeExtensionDeep(resolvedPath.relativePath))) return true;
	return matcher.getWatchRoots(options.absoluteSrcRoot).some((root) => {
		const normalizedRoot = normalizePath$1(root);
		return resolvedPath.absolutePath === normalizedRoot || resolvedPath.absolutePath.startsWith(`${normalizedRoot}/`);
	});
}
/**
* 判断当前文件事件是否属于需要回退为全量重扫的结构性变化。
*/
function shouldAutoRoutesFullRescan(event) {
	return event === "rename";
}
/**
* 判断当前候选是否已不再属于 auto-routes 追踪范围。
*/
function shouldRemoveAutoRoutesCandidate(options) {
	return (!options.hasRouteMatch || !options.matchesInclude) && options.hasCandidateEntry;
}
/**
* 判断重建后的候选内容是否与现有记录一致。
*/
function isAutoRoutesCandidateUnchanged(previous, candidate) {
	return Boolean(previous && previous.jsonPath === candidate.jsonPath && previous.hasScript === candidate.hasScript && previous.hasTemplate === candidate.hasTemplate && areSetsEqual(previous.files, candidate.files));
}
//#endregion
//#region src/runtime/autoRoutesPlugin/routes/scan.ts
function sortAutoRoutesEntries(values) {
	values.sort((a, b) => {
		if (a === "pages/index/index") return -1;
		if (b === "pages/index/index") return 1;
		return a.localeCompare(b);
	});
}
function sortAutoRoutesSubPackages(subPackages) {
	subPackages.sort((a, b) => a.root.localeCompare(b.root));
}
function ensureSubPackage(map, root) {
	let set = map.get(root);
	if (!set) {
		set = /* @__PURE__ */ new Set();
		map.set(root, set);
	}
	return set;
}
function shouldIncludeScanCandidate(candidate, json, route) {
	if (candidate.jsonPath && json === void 0) return false;
	if (json && typeof json === "object" && json.component === true) return false;
	if (route && candidate.hasScript && !candidate.hasTemplate && !candidate.jsonPath) {
		const hasVueEntry = [...candidate.files].some((file) => file.endsWith(".vue"));
		const isIndexEntry = path.basename(route.pagePath) === "index";
		if ((route.root ? !route.pagePath.startsWith("pages/") : route.pagePath.startsWith("pages/") && route.pagePath.slice(6).includes("/")) && !hasVueEntry && !isIndexEntry) return false;
	}
	return candidate.hasScript || candidate.hasTemplate || Boolean(candidate.jsonPath);
}
async function scanRoutes(ctx, candidatesMap) {
	const configService = ctx.configService;
	const jsonService = ctx.jsonService;
	if (!configService || !jsonService) throw new Error("扫描路由前必须初始化 configService/jsonService。");
	const absoluteSrcRoot = configService.absoluteSrcRoot;
	const { matcher, subPackageRoots } = resolveAutoRoutesMatcherContext(ctx);
	const pagesSet = /* @__PURE__ */ new Set();
	const entriesSet = /* @__PURE__ */ new Set();
	const subPackages = /* @__PURE__ */ new Map();
	const watchFiles = /* @__PURE__ */ new Set();
	const watchDirs = /* @__PURE__ */ new Set();
	const candidateList = [...candidatesMap.values()];
	const jsonEntries = await Promise.all(candidateList.map(async (candidate) => {
		if (!candidate.jsonPath) return {
			candidate,
			json: void 0
		};
		return {
			candidate,
			json: await jsonService.read(candidate.jsonPath)
		};
	}));
	const jsonMap = /* @__PURE__ */ new Map();
	for (const { candidate, json } of jsonEntries) jsonMap.set(candidate, json);
	for (const candidate of candidateList) {
		for (const file of candidate.files) watchFiles.add(file);
		const normalizedBase = toPosixPath(path.relative(absoluteSrcRoot, candidate.base));
		if (!normalizedBase || normalizedBase.startsWith("..")) continue;
		const route = resolveRoute(normalizedBase, subPackageRoots);
		if (!route) continue;
		watchDirs.add(path.dirname(candidate.base));
		if (!shouldIncludeScanCandidate(candidate, jsonMap.get(candidate), route)) continue;
		entriesSet.add(route.entry);
		if (route.root) ensureSubPackage(subPackages, route.root).add(route.pagePath);
		else pagesSet.add(route.pagePath);
	}
	for (const dir of matcher.getWatchRoots(absoluteSrcRoot)) watchDirs.add(dir);
	const pages = [...pagesSet];
	const entries = [...entriesSet];
	const subPackageList = Array.from(subPackages.entries(), ([root, value]) => {
		const pagesArray = [...value];
		pagesArray.sort((a, b) => a.localeCompare(b));
		return {
			root,
			pages: pagesArray
		};
	});
	sortAutoRoutesEntries(pages);
	sortAutoRoutesEntries(entries);
	sortAutoRoutesSubPackages(subPackageList);
	const snapshot = applyBuildScopeToAutoRoutes({
		pages,
		entries,
		subPackages: subPackageList
	}, resolveBuildScope(configService.weappViteConfig.buildScope));
	const { serialized, moduleCode, typedDefinition } = createAutoRoutesArtifacts(snapshot);
	return {
		snapshot,
		serialized,
		moduleCode,
		typedDefinition,
		watchFiles,
		watchDirs
	};
}
//#endregion
//#region src/runtime/autoRoutesPlugin/routes/state.ts
function assignArray(target, source) {
	target.splice(0, target.length, ...source);
}
function updateRoutesReference(target, next) {
	assignArray(target.pages, next.pages);
	assignArray(target.entries, next.entries);
	const existing = new Map(target.subPackages.map((pkg) => [pkg.root, pkg]));
	target.subPackages.length = 0;
	for (const pkg of next.subPackages) {
		const preserved = existing.get(pkg.root);
		if (preserved) {
			assignArray(preserved.pages, pkg.pages);
			target.subPackages.push(preserved);
		} else target.subPackages.push({
			root: pkg.root,
			pages: [...pkg.pages]
		});
	}
}
function cloneRoutes(routes) {
	return {
		pages: [...routes.pages],
		entries: [...routes.entries],
		subPackages: routes.subPackages.map((pkg) => {
			return {
				root: pkg.root,
				pages: [...pkg.pages]
			};
		})
	};
}
//#endregion
//#region src/runtime/autoRoutesPlugin/service/persistence.ts
function getResolvedConfig(ctx) {
	return resolveWeappAutoRoutesConfig(ctx.configService?.weappViteConfig?.autoRoutes);
}
function resolvePersistentCachePath(ctx) {
	const autoRoutesConfig = getResolvedConfig(ctx);
	if (!autoRoutesConfig.persistentCache) return;
	const configService = ctx.configService;
	if (!configService) return;
	const baseDir = resolvePersistentCacheBaseDir(configService);
	if (!baseDir) return;
	return path.resolve(baseDir, autoRoutesConfig.persistentCachePath ?? ".weapp-vite/auto-routes.cache.json");
}
function resolveDefaultPersistentCachePath(ctx) {
	const configService = ctx.configService;
	if (!configService) return;
	const baseDir = resolvePersistentCacheBaseDir(configService);
	if (!baseDir) return;
	return path.resolve(baseDir, AUTO_ROUTES_CACHE_FILE);
}
async function hasSameTextContent(filePath, content) {
	try {
		return await fs$1.pathExists(filePath) && await fs$1.readFile(filePath, "utf8") === content;
	} catch {
		return false;
	}
}
async function hasSamePersistentCachePayload(filePath, payload) {
	try {
		if (!await fs$1.pathExists(filePath)) return false;
		const current = await fs$1.readJson(filePath);
		return JSON.stringify(current) === JSON.stringify(payload);
	} catch {
		return false;
	}
}
async function collectWatchFileMtims(watchFiles) {
	const entries = await Promise.all([...watchFiles].map(async (filePath) => {
		return [filePath, (await fs$1.stat(filePath)).mtimeMs];
	}));
	return Object.fromEntries(entries);
}
async function restorePersistentCache(ctx, state) {
	if (!getResolvedConfig(ctx).persistentCache) return false;
	const cachePath = resolvePersistentCachePath(ctx);
	if (!cachePath || !await fs$1.pathExists(cachePath)) return false;
	try {
		const cache = await fs$1.readJson(cachePath);
		if (cache?.version !== 1) return false;
		const watchFiles = Array.isArray(cache.watchFiles) ? cache.watchFiles : [];
		if (watchFiles.length === 0) return false;
		const cachedMtims = cache.fileMtims;
		if (!cachedMtims) return false;
		const fileMtims = await collectWatchFileMtims(watchFiles);
		for (const filePath of watchFiles) {
			const expectedMtime = cachedMtims[filePath];
			if (typeof expectedMtime !== "number" || !Number.isFinite(expectedMtime) || fileMtims[filePath] !== expectedMtime) return false;
		}
		applyPersistentCache(state, cache);
		return true;
	} catch {
		return false;
	}
}
async function writePersistentCache(ctx, state) {
	const cachePath = resolvePersistentCachePath(ctx);
	if (!cachePath || !state.initialized || !getResolvedConfig(ctx).persistentCache) return;
	let fileMtims;
	try {
		fileMtims = await collectWatchFileMtims(state.watchFiles);
	} catch {
		return;
	}
	try {
		const payload = createPersistentCachePayload(state, fileMtims);
		if (await hasSamePersistentCachePayload(cachePath, payload)) return;
		await fs$1.outputJson(cachePath, payload, { spaces: 2 });
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.warn(`写入 auto-routes 缓存失败: ${message}`);
	}
}
async function removePersistentCache(ctx) {
	const cachePath = resolvePersistentCachePath(ctx) ?? resolveDefaultPersistentCachePath(ctx);
	if (!cachePath) return;
	try {
		if (await fs$1.pathExists(cachePath)) await fs$1.remove(cachePath);
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.warn(`移除 auto-routes 缓存失败: ${message}`);
	}
}
async function removeTypedRouterDefinition(ctx) {
	const configService = ctx.configService;
	if (!configService) return false;
	const outputPath = resolveTypedRouterOutputPath(configService);
	try {
		if (await fs$1.pathExists(outputPath)) await fs$1.remove(outputPath);
		return true;
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.error(`移除 ${TYPED_ROUTER_OUTPUT_FILE} 失败: ${message}`);
		return false;
	}
}
async function writeTypedRouterDefinition(ctx, typedDefinition, lastWrittenTypedDefinition) {
	const autoRoutesConfig = getResolvedConfig(ctx);
	if (!autoRoutesConfig.enabled || !autoRoutesConfig.typedRouter) return await removeTypedRouterDefinition(ctx) ? void 0 : lastWrittenTypedDefinition;
	const configService = ctx.configService;
	if (!configService) return lastWrittenTypedDefinition;
	const outputPath = resolveTypedRouterOutputPath(configService);
	if (!typedDefinition || typedDefinition === lastWrittenTypedDefinition) return lastWrittenTypedDefinition;
	try {
		if (await hasSameTextContent(outputPath, typedDefinition)) return typedDefinition;
		await fs$1.outputFile(outputPath, typedDefinition, "utf8");
		return typedDefinition;
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.error(`写入 ${TYPED_ROUTER_OUTPUT_FILE} 失败: ${message}`);
		return lastWrittenTypedDefinition;
	}
}
//#endregion
//#region src/runtime/autoRoutesPlugin/watch.ts
function matchesRouteFile(ctx, candidate) {
	const configService = ctx.configService;
	if (!configService) return false;
	if (isAutoRoutesGeneratedPath(candidate, {
		cwd: configService.cwd,
		absoluteSrcRoot: configService.absoluteSrcRoot,
		managedOutputPaths: resolveAutoRoutesManagedOutputPaths(ctx)
	})) return false;
	const [pathWithoutQuery] = candidate.split("?");
	if (!pathWithoutQuery) return false;
	const resolvedPath = resolveAutoRoutesPath(candidate, {
		cwd: configService.cwd,
		absoluteSrcRoot: configService.absoluteSrcRoot
	});
	if (!resolvedPath) return false;
	const { matcher } = resolveAutoRoutesMatcherContext(ctx);
	if (!matcher.matches(removeExtensionDeep(resolvedPath.relativePath))) return false;
	if (isConfigFile(resolvedPath.absolutePath)) return true;
	if (isVueFile(resolvedPath.absolutePath) || isScriptFile(resolvedPath.absolutePath) || isTemplateFile(resolvedPath.absolutePath) || isStyleFile(resolvedPath.absolutePath)) return true;
	return false;
}
async function rebuildCandidateForBase(base, platform) {
	const files = /* @__PURE__ */ new Set();
	let hasScript = false;
	let hasTemplate = false;
	let jsonPath;
	const [vueEntry, jsEntry, templateEntry, styleEntry, jsonEntry] = await Promise.all([
		findVueEntry(base),
		findJsEntry(base),
		findTemplateEntry(base, platform),
		findCssEntry(base, platform),
		findJsonEntry(base)
	]);
	if (vueEntry) {
		files.add(vueEntry);
		hasScript = true;
	}
	const { path: jsEntryPath } = jsEntry;
	if (jsEntryPath) {
		files.add(jsEntryPath);
		hasScript = true;
	}
	const { path: templateEntryPath } = templateEntry;
	if (templateEntryPath) {
		files.add(templateEntryPath);
		hasTemplate = true;
	}
	const { path: styleEntryPath } = styleEntry;
	if (styleEntryPath) files.add(styleEntryPath);
	const { path: jsonEntryPath } = jsonEntry;
	if (jsonEntryPath) {
		files.add(jsonEntryPath);
		jsonPath = jsonEntryPath;
	}
	if (!files.size && !jsonPath) return;
	return {
		base,
		files,
		hasScript,
		hasTemplate,
		jsonPath
	};
}
async function updateCandidateFromFile(ctx, stateCandidates, filePath, event, markNeedsFullRescan) {
	if (!ctx.configService) return false;
	if (isAutoRoutesGeneratedPath(filePath, {
		cwd: ctx.configService.cwd,
		absoluteSrcRoot: ctx.configService.absoluteSrcRoot,
		managedOutputPaths: resolveAutoRoutesManagedOutputPaths(ctx)
	})) return false;
	if (shouldAutoRoutesFullRescan(event)) {
		markNeedsFullRescan?.();
		return true;
	}
	const resolvedBasePath = resolveAutoRoutesBasePath(filePath, {
		cwd: ctx.configService.cwd,
		absoluteSrcRoot: ctx.configService.absoluteSrcRoot
	});
	if (!resolvedBasePath) {
		markNeedsFullRescan?.();
		return true;
	}
	const { base, relativeBase } = resolvedBasePath;
	const { matcher, subPackageRoots } = resolveAutoRoutesMatcherContext(ctx);
	const route = resolveRoute(relativeBase, subPackageRoots);
	const matchesInclude = matcher.matches(relativeBase);
	if (shouldRemoveAutoRoutesCandidate({
		hasRouteMatch: Boolean(route),
		matchesInclude,
		hasCandidateEntry: stateCandidates.has(base)
	})) return stateCandidates.delete(base);
	const candidate = await rebuildCandidateForBase(base, ctx.configService.platform);
	if (!candidate) return stateCandidates.delete(base);
	if (isAutoRoutesCandidateUnchanged(stateCandidates.get(base), candidate)) return false;
	stateCandidates.set(base, candidate);
	return true;
}
//#endregion
//#region src/runtime/autoRoutesPlugin/service.ts
function createAutoRoutesService(ctx) {
	const state = ctx.runtimeState.autoRoutes;
	let pendingScan;
	let lastWrittenTypedDefinition;
	let mutationVersion = 0;
	function flagDirty() {
		mutationVersion += 1;
		state.dirty = true;
	}
	function getResolvedConfig() {
		return resolveWeappAutoRoutesConfig(ctx.configService?.weappViteConfig?.autoRoutes);
	}
	function getSubPackageRoots() {
		return getAutoRoutesSubPackageRoots(ctx);
	}
	function isEnabled() {
		return Boolean(ctx.configService) && getResolvedConfig().enabled;
	}
	function resetState() {
		resetAutoRoutesState(state);
		pendingScan = void 0;
		mutationVersion = 0;
	}
	function markNeedsFullRescan() {
		state.needsFullRescan = true;
	}
	async function ensureCandidateRegistry() {
		const configService = requireConfigService(ctx, "扫描路由前必须初始化 configService。");
		if (!isEnabled()) {
			if (state.candidates.size > 0) state.candidates.clear();
			state.needsFullRescan = true;
			return false;
		}
		if (!state.needsFullRescan && state.candidates.size > 0) return false;
		state.loadingAppConfig = true;
		try {
			await ctx.scanService?.loadAppEntry?.();
		} catch {} finally {
			state.loadingAppConfig = false;
		}
		const absoluteSrcRoot = configService.absoluteSrcRoot;
		const candidates = await collectCandidates(absoluteSrcRoot, getResolvedConfig().include, getSubPackageRoots());
		state.candidates.clear();
		for (const candidate of candidates.values()) state.candidates.set(candidate.base, cloneCandidate(candidate));
		state.needsFullRescan = false;
		return true;
	}
	async function ensureFresh() {
		if (!isEnabled()) {
			if (state.dirty || !state.initialized || state.routes.pages.length > 0 || state.routes.entries.length > 0 || state.routes.subPackages.length > 0) resetState();
			if (await removeTypedRouterDefinition(ctx)) lastWrittenTypedDefinition = void 0;
			await removePersistentCache(ctx);
			return;
		}
		if (!getResolvedConfig().persistentCache) await removePersistentCache(ctx);
		if (!state.initialized && state.needsFullRescan) {
			if (await restorePersistentCache(ctx, state)) {
				lastWrittenTypedDefinition = await writeTypedRouterDefinition(ctx, state.typedDefinition, lastWrittenTypedDefinition);
				return;
			}
		}
		if (await ensureCandidateRegistry()) flagDirty();
		if (!state.dirty) {
			await (pendingScan ?? Promise.resolve());
			lastWrittenTypedDefinition = await writeTypedRouterDefinition(ctx, state.typedDefinition, lastWrittenTypedDefinition);
			return;
		}
		while (state.dirty) {
			if (!pendingScan) {
				const versionSnapshot = mutationVersion;
				pendingScan = scanRoutes(ctx, state.candidates).then((result) => {
					updateRoutesReference(state.routes, result.snapshot);
					state.serialized = result.serialized;
					state.moduleCode = result.moduleCode;
					state.typedDefinition = result.typedDefinition;
					updateWatchTargets(state.watchFiles, result.watchFiles);
					updateWatchTargets(state.watchDirs, result.watchDirs);
					if (mutationVersion === versionSnapshot) state.dirty = false;
					state.initialized = true;
				}).finally(() => {
					pendingScan = void 0;
				});
			}
			await pendingScan;
			lastWrittenTypedDefinition = await writeTypedRouterDefinition(ctx, state.typedDefinition, lastWrittenTypedDefinition);
			await writePersistentCache(ctx, state);
		}
	}
	return {
		async ensureFresh() {
			await ensureFresh();
		},
		markDirty() {
			markNeedsFullRescan();
			flagDirty();
		},
		getSnapshot() {
			return cloneRoutes(state.routes);
		},
		getReference() {
			return state.routes;
		},
		getSignature() {
			return state.serialized;
		},
		getModuleCode() {
			return state.moduleCode;
		},
		getWatchFiles() {
			return state.watchFiles.values();
		},
		getWatchDirectories() {
			return state.watchDirs.values();
		},
		isRouteFile(filePath) {
			return isEnabled() && matchesRouteFile(ctx, filePath);
		},
		async handleFileChange(filePath, event) {
			if (!isEnabled()) return false;
			if (!matchesRouteFile(ctx, filePath)) return false;
			if (!await updateCandidateFromFile(ctx, state.candidates, filePath, event, markNeedsFullRescan) && !state.needsFullRescan) return false;
			flagDirty();
			await ensureFresh();
			return true;
		},
		isInitialized() {
			return state.initialized && !state.dirty;
		},
		isEnabled() {
			return isEnabled();
		}
	};
}
//#endregion
//#region src/runtime/autoRoutesPlugin/index.ts
function createAutoRoutesServicePlugin(ctx) {
	ctx.autoRoutesService = createAutoRoutesService(ctx);
	return { name: "weapp-runtime:auto-routes-service" };
}
//#endregion
//#region src/runtime/npmPlugin/service/dependencies.ts
const DEFAULT_NPM_STRATEGY = "explicit";
function dedupeDependencies(dependencies) {
	return [...new Set(dependencies)];
}
function matchDependencyName(patterns, dep) {
	return patterns.some((pattern) => {
		if (typeof pattern === "string") return pattern === dep;
		pattern.lastIndex = 0;
		return pattern.test(dep);
	});
}
function createDependencyRecord(dependencies) {
	if (dependencies.length === 0) return;
	return Object.fromEntries(dependencies.map((dep) => [dep, "*"]));
}
function resolveNpmStrategy(ctx) {
	return ctx.configService?.weappViteConfig?.npm?.strategy ?? DEFAULT_NPM_STRATEGY;
}
function resolveConfiguredDependencyPatterns(ctx) {
	const npmConfig = ctx.configService?.weappViteConfig?.npm;
	const patterns = [...npmConfig?.include ?? []];
	if (ctx.configService?.pluginOnly) {
		if (Array.isArray(npmConfig?.pluginPackage?.dependencies)) patterns.push(...npmConfig.pluginPackage.dependencies);
		return patterns;
	}
	if (Array.isArray(npmConfig?.mainPackage?.dependencies)) patterns.push(...npmConfig.mainPackage.dependencies);
	for (const config of Object.values(npmConfig?.subPackages ?? {})) if (Array.isArray(config?.dependencies)) patterns.push(...config.dependencies);
	return patterns;
}
function resolveDeclaredDependencies(pkgJson) {
	return dedupeDependencies([...Object.keys(pkgJson.dependencies ?? {}), ...Object.keys(pkgJson.devDependencies ?? {})]);
}
function isMiniprogramPackage(pkg) {
	return Reflect.has(pkg, "miniprogram") && typeof pkg.miniprogram === "string";
}
function resolveMiniprogramCandidateDependenciesSync(allDependencies, cwd) {
	return allDependencies.filter((dep) => {
		let packageInfo = null;
		try {
			packageInfo = getPackageInfoSync(dep, cwd ? { paths: [cwd] } : void 0);
		} catch {
			packageInfo = null;
		}
		return !!packageInfo && isMiniprogramPackage(packageInfo.packageJson);
	});
}
function resolveMainPackageDependencyPatterns(ctx) {
	return ctx.configService?.weappViteConfig?.npm?.mainPackage?.dependencies;
}
function resolvePluginPackageDependencyPatterns(ctx) {
	return ctx.configService?.weappViteConfig?.npm?.pluginPackage?.dependencies;
}
function resolveTargetDependencies(allDependencies, patterns) {
	if (patterns === false) return [];
	if (!Array.isArray(patterns)) return allDependencies;
	const selected = /* @__PURE__ */ new Set();
	for (const dep of allDependencies) if (matchDependencyName(patterns, dep)) selected.add(dep);
	for (const pattern of patterns) if (typeof pattern === "string") selected.add(pattern);
	return [...selected];
}
function resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson) {
	if (resolveNpmStrategy(ctx) === "legacy") return Object.keys(pkgJson.dependencies ?? {});
	const declaredDependencies = resolveDeclaredDependencies(pkgJson);
	const explicitlyIncludedDependencies = resolveTargetDependencies(declaredDependencies, resolveConfiguredDependencyPatterns(ctx));
	return dedupeDependencies([...resolveMiniprogramCandidateDependenciesSync(declaredDependencies, ctx.configService?.cwd), ...explicitlyIncludedDependencies]);
}
function resolveNpmBuildCandidateDependencyRecordSync(ctx, pkgJson) {
	if (!pkgJson) return;
	return createDependencyRecord(resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson));
}
function hasLocalSubPackageNpmConfig(ctx) {
	const npmSubPackages = ctx.configService?.weappViteConfig?.npm?.subPackages;
	if (npmSubPackages && Object.values(npmSubPackages).some((config) => Array.isArray(config?.dependencies) && config.dependencies.length > 0)) return true;
	return false;
}
function resolveNpmDistDirName(configService) {
	return getPlatformNpmDistDirName(resolveMiniPlatformWithDefault(configService?.platform), { alipayNpmMode: configService?.weappViteConfig?.npm?.alipayNpmMode });
}
function resolveMainBuildDependencyPatterns(ctx) {
	return ctx.configService?.pluginOnly ? resolvePluginPackageDependencyPatterns(ctx) : resolveMainPackageDependencyPatterns(ctx);
}
function dedupeNpmDependencies(dependencies) {
	return dedupeDependencies(dependencies);
}
function resolveConfiguredNpmDependencyPatterns(ctx) {
	return resolveConfiguredDependencyPatterns(ctx);
}
function resolveDeclaredNpmDependencies(pkgJson) {
	return resolveDeclaredDependencies(pkgJson);
}
function resolveNpmStrategyMode(ctx) {
	return resolveNpmStrategy(ctx);
}
//#endregion
//#region src/runtime/watch/options.ts
/**
* 解析主 watcher 与 sidecar watcher 共享的轮询配置。
*/
function resolvePollingWatchOptions(configService) {
	const buildWatch = configService.inlineConfig?.build?.watch;
	const chokidar = buildWatch && typeof buildWatch === "object" && "chokidar" in buildWatch ? buildWatch.chokidar : void 0;
	const serverWatch = configService.inlineConfig?.server?.watch;
	const envUsePolling = process.env.CHOKIDAR_USEPOLLING;
	const envInterval = process.env.CHOKIDAR_INTERVAL;
	const envBinaryInterval = process.env.CHOKIDAR_BINARY_INTERVAL;
	const usePollingCandidate = chokidar?.usePolling ?? serverWatch?.usePolling ?? (envUsePolling === "1" || envUsePolling === "true" ? true : envUsePolling === "0" || envUsePolling === "false" ? false : void 0);
	const intervalCandidate = chokidar?.interval ?? serverWatch?.interval ?? (envInterval ? Number(envInterval) : void 0);
	const binaryIntervalCandidate = chokidar?.binaryInterval ?? serverWatch?.binaryInterval ?? (envBinaryInterval ? Number(envBinaryInterval) : void 0);
	return {
		usePolling: typeof usePollingCandidate === "boolean" ? usePollingCandidate : void 0,
		interval: typeof intervalCandidate === "number" && Number.isFinite(intervalCandidate) ? intervalCandidate : void 0,
		binaryInterval: typeof binaryIntervalCandidate === "number" && Number.isFinite(binaryIntervalCandidate) ? binaryIntervalCandidate : void 0
	};
}
function createSidecarWatchOptions(configService, input) {
	const polling = resolvePollingWatchOptions(configService);
	return {
		...input,
		...polling.usePolling !== void 0 ? { usePolling: polling.usePolling } : {},
		...typeof polling.interval === "number" ? { interval: polling.interval } : {},
		...typeof polling.binaryInterval === "number" ? { binaryInterval: polling.binaryInterval } : {}
	};
}
/**
* 合并用户配置并排除 Vite 开发服务器不应监听的构建输出目录。
*/
function createViteWatchIgnored(root, outDir, ignored) {
	const normalizedRoot = normalizeFsResolvedId(root);
	const normalizedOutDir = normalizeFsResolvedId(path.isAbsolute(outDir) ? outDir : path.resolve(root, outDir));
	return [...ignored === void 0 ? [] : Array.isArray(ignored) ? ignored : [ignored], (id) => {
		const normalizedId = normalizeFsResolvedId(path.isAbsolute(id) ? id : path.resolve(normalizedRoot, id));
		return isPathInside(normalizedOutDir, normalizedId);
	}];
}
//#endregion
//#region src/moduleGraph/logicalEntry.ts
function createLogicalEntryModuleCode(entry, dependencies) {
	const source = JSON.stringify(entry.sourceId);
	const isVueLikeEntry = /\.(?:vue|jsx|tsx)$/.test(entry.sourceId);
	const delegatesComponentRegistration = entry.type === "component" && isVueLikeEntry;
	const forwardsDefault = entry.type !== "app" && isVueLikeEntry;
	const imports = delegatesComponentRegistration ? [
		`import { createWevuComponent as __weappViteCreateWevuComponent } from "wevu";`,
		`import __weappViteComponentOptions from ${source};`,
		`__weappViteCreateWevuComponent(__weappViteComponentOptions);`,
		`export default __weappViteComponentOptions;`
	] : [forwardsDefault ? `export { default } from ${source};` : `import ${source};`];
	const seen = /* @__PURE__ */ new Set();
	for (const dependency of dependencies) {
		const dependencyId = createSidecarModuleId(entry.sourceId, dependency.sourceId, dependency.kind);
		if (seen.has(dependencyId)) continue;
		seen.add(dependencyId);
		imports.push(`import ${JSON.stringify(dependencyId)};`);
	}
	imports.push(`export * from ${source};`);
	return `${imports.join("\n")}\n`;
}
function createSidecarModuleCode(ownerId, sourceId, kind) {
	const sourceRequest = createSidecarSourceSpecifier(ownerId, sourceId, kind);
	return `import ${JSON.stringify(sourceRequest)};\nexport default ${JSON.stringify(sourceId)};\n`;
}
//#endregion
//#region src/moduleGraph/devProvider.ts
const DEV_EXTERNAL_PREFIX = "\0weapp-vite:module-graph-external:";
function isInternalPlugin(plugin) {
	if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
	const name = plugin.name;
	return typeof name === "string" && (name.startsWith("weapp-vite:") || name.startsWith("weapp-runtime:"));
}
function collectResolverPlugins(config) {
	return (Array.isArray(config.plugins) ? config.plugins : config.plugins ? [config.plugins] : []).filter((plugin) => !isInternalPlugin(plugin));
}
async function transformVueSource(code, id) {
	const { descriptor, errors } = parse$1(code, { filename: id });
	if (errors.length) throw errors[0];
	const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => block?.content);
	const source = blocks.map((block) => block.content).join("\n") || "export default {}";
	const lang = blocks.some((block) => block?.lang === "tsx") ? "tsx" : blocks.some((block) => block?.lang === "ts") ? "ts" : "js";
	return await transformWithOxc(source, id, {
		lang,
		sourcemap: false,
		target: "esnext"
	});
}
async function isExternalRequest(source, importer, config) {
	const buildOptions = config.build;
	const external = buildOptions?.rolldownOptions?.external ?? buildOptions?.rollupOptions?.external;
	if (typeof external === "function") return await external(source, importer, false);
	return (Array.isArray(external) ? external : external ? [external] : []).some((pattern) => {
		if (typeof pattern === "string") return pattern === source;
		pattern.lastIndex = 0;
		return pattern.test(source);
	});
}
function createProviderPlugin(ctx, config, onChange) {
	const npmExternalPackages = new Set(ctx.configService?.packageJson ? resolveNpmBuildCandidateDependenciesSync(ctx, ctx.configService.packageJson) : []);
	return {
		name: "weapp-vite:module-graph-provider",
		enforce: "pre",
		async resolveId(id, importer) {
			const virtualId = resolveVirtualModuleId(id);
			if (virtualId) return virtualId;
			if (parseSidecarSourceRequest(id)) return id;
			if (Array.from(npmExternalPackages).some((pkg) => id === pkg || id.startsWith(`${pkg}/`))) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
			if (await isExternalRequest(id, importer, config)) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
			if (!id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !/^[a-z]:[\\/]/i.test(id)) {
				const resolved = await this.resolve(id, importer, { skipSelf: true });
				if (!resolved || resolved.external) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
				return resolved;
			}
			return null;
		},
		load(id) {
			if (id.startsWith(DEV_EXTERNAL_PREFIX)) return "export default {}";
			const logicalEntry = parseLogicalEntryId(id);
			if (logicalEntry) return createLogicalEntryModuleCode(logicalEntry, ctx.moduleGraphService.getEntryDependencies(logicalEntry.sourceId));
			const sidecar = parseSidecarModuleId(id);
			if (sidecar) return createSidecarModuleCode(sidecar.ownerId, sidecar.sourceId, sidecar.kind);
			const sidecarSource = parseSidecarSourceRequest(id);
			if (sidecarSource) {
				if (sidecarSource.kind === "style") return null;
				return `export default ${JSON.stringify(sidecarSource.sourceId)};`;
			}
			return null;
		},
		async transform(code, id) {
			if (!id.endsWith(".vue")) return null;
			return await transformVueSource(code, id);
		},
		async hotUpdate({ type, file, read }) {
			if (this.environment.name !== "client" || type === "delete") return;
			try {
				await read();
			} catch (error) {
				if (error.code === "ENOENT") return;
				throw error;
			}
			onChange({
				event: type,
				file
			});
		}
	};
}
async function createDevModuleGraphProvider(ctx, buildConfig, onChange) {
	const configService = ctx.configService;
	const userWatch = buildConfig.server?.watch;
	const ignored = configService?.outDir ? createViteWatchIgnored(buildConfig.root ?? configService.cwd, configService.outDir, userWatch?.ignored) : userWatch?.ignored;
	const server = await createServer({
		...buildConfig,
		appType: "custom",
		configFile: false,
		customLogger: createLogger("silent"),
		plugins: [createProviderPlugin(ctx, buildConfig, onChange), ...collectResolverPlugins(buildConfig)],
		server: {
			...buildConfig.server ?? {},
			hmr: true,
			middlewareMode: true,
			watch: {
				...userWatch ?? {},
				...ignored !== void 0 ? { ignored } : {}
			}
		},
		build: {
			...buildConfig.build ?? {},
			watch: void 0,
			write: false
		}
	});
	ctx.moduleGraphService.bindDevServer(server);
	return { async close() {
		await server.close();
		ctx.moduleGraphService.bindDevServer(void 0);
	} };
}
//#endregion
//#region src/plugins/utils/invalidateEntry/shared.ts
const watchedCssSuffixes = supportedCssLangs.map((ext) => `.${ext}`);
const watchedTemplateSuffixes = templateExtensions.map((ext) => `.${ext}`);
const watchedCssExts = new Set(watchedCssSuffixes);
const watchedTemplateExts = new Set(watchedTemplateSuffixes);
const watchedScriptModuleSuffixes = [
	".wxs",
	".sjs",
	".wxs.ts",
	".wxs.js",
	".sjs.ts",
	".sjs.js"
];
new Set(watchedScriptModuleSuffixes);
const configSuffixes = configExtensions.map((ext) => `.${ext}`);
const sidecarSuffixes = [
	...configSuffixes,
	...watchedCssSuffixes,
	...watchedTemplateSuffixes,
	...watchedScriptModuleSuffixes
];
const defaultIgnoredDirNames = /* @__PURE__ */ new Set([
	"node_modules",
	"miniprogram_npm",
	".git",
	".hg",
	".svn",
	".turbo",
	".weapp-vite"
]);
const watchLimitErrorCodes = /* @__PURE__ */ new Set(["EMFILE", "ENOSPC"]);
function isSidecarFile(filePath) {
	return sidecarSuffixes.some((suffix) => filePath.endsWith(suffix));
}
function isWatchLimitError(error) {
	if (!error || typeof error !== "object") return false;
	const maybeError = error;
	if (!maybeError.code) return false;
	return watchLimitErrorCodes.has(maybeError.code);
}
//#endregion
//#region src/plugins/utils/layoutSourcePath.ts
const DEFAULT_LAYOUT_SOURCE_ROOT = "layouts";
const LEADING_SLASHES_RE$3 = /^\/+/;
const TRAILING_SLASHES_RE$3 = /\/+$/;
function normalizeRelativePath(value) {
	return toPosixPath(value).replace(LEADING_SLASHES_RE$3, "").replace(TRAILING_SLASHES_RE$3, "");
}
function isLayoutSourcePath(relativeSrc, layoutSourceRoot = DEFAULT_LAYOUT_SOURCE_ROOT) {
	const normalizedRoot = normalizeRelativePath(layoutSourceRoot);
	const normalizedSrc = normalizeRelativePath(relativeSrc);
	return normalizedSrc === normalizedRoot || normalizedSrc.startsWith(`${normalizedRoot}/`);
}
//#endregion
//#region src/utils/hmrProfile.ts
const DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH = ".weapp-vite/hmr-profile.jsonl";
const HMR_PROFILE_JSON_ENV = "WEAPP_VITE_HMR_PROFILE_JSON";
/**
* @description 解析 HMR profile JSONL 输出路径。
*/
function resolveHmrProfileJsonPath(options) {
	const fallbackToDefault = options.fallbackToDefault ?? false;
	if (options.option === true) return path.join(options.cwd, DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH);
	if (typeof options.option === "string") {
		const trimmed = options.option.trim();
		if (trimmed) return path.isAbsolute(trimmed) ? trimmed : path.resolve(options.cwd, trimmed);
	}
	if (fallbackToDefault) return path.join(options.cwd, DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH);
}
/**
* @description 从环境变量解析 HMR profile JSONL 输出选项。
*/
function resolveHmrProfileJsonEnvOption(env = process.env) {
	const raw = env[HMR_PROFILE_JSON_ENV]?.trim();
	if (!raw) return;
	if (raw === "1" || raw.toLowerCase() === "true") return true;
	if (raw === "0" || raw.toLowerCase() === "false") return;
	return raw;
}
let hmrProfileEventSequence = 0;
/**
* @description 创建 HMR profile 事件 id,用于把 watcher 事件、JSONL 样本和外部审计场景稳定关联。
*/
function createHmrProfileEventId() {
	hmrProfileEventSequence += 1;
	return `${Date.now().toString(36)}-${hmrProfileEventSequence.toString(36)}`;
}
/**
* @description 为 HMR profile 累加阶段耗时。
*/
function recordHmrProfileDuration(profile, key, durationMs) {
	if (!profile || !Number.isFinite(durationMs) || durationMs <= 0) return;
	profile[key] = (profile[key] ?? 0) + durationMs;
}
/**
* @description 为 HMR profile 累加操作次数。
*/
function recordHmrProfileOperation(profile, key, count = 1) {
	if (!profile || !Number.isFinite(count) || count <= 0) return;
	profile[key] = (profile[key] ?? 0) + count;
}
//#endregion
//#region src/utils/outputExtensions.ts
function resolveScriptModuleExtension(outputExtensions, options) {
	return outputExtensions?.wxs ?? options?.scriptModuleExtensionFallback;
}
function resolveOutputExtensions(outputExtensions, options) {
	return {
		templateExtension: outputExtensions?.wxml ?? "wxml",
		styleExtension: outputExtensions?.wxss ?? "wxss",
		jsonExtension: outputExtensions?.json ?? "json",
		scriptExtension: outputExtensions?.js ?? "js",
		scriptModuleExtension: resolveScriptModuleExtension(outputExtensions, options)
	};
}
function resolveCompilerOutputExtensions(outputExtensions) {
	return resolveOutputExtensions(outputExtensions, { scriptModuleExtensionFallback: "wxs" });
}
//#endregion
//#region src/runtime/hmrRuntime.ts
function resolveHmrRuntimeDecision(options) {
	const configured = options.configured ?? "auto";
	if (options.platform === "weapp" && options.skyline === true) return {
		configured,
		reason: "skyline-fallback",
		runtime: "classic"
	};
	if (configured === "classic" || configured === "stateful-experimental") return {
		configured,
		reason: "explicit",
		runtime: configured
	};
	if (options.platform === "weapp" && options.compileHotReLoad === true) return {
		configured,
		reason: "auto-stateful",
		runtime: "stateful-experimental"
	};
	return {
		configured,
		reason: options.platform === "weapp" ? "auto-classic" : "auto-non-wechat",
		runtime: "classic"
	};
}
function findSkylineRendererFiles(output) {
	const jsonConfigs = /* @__PURE__ */ new Map();
	for (const item of output) {
		if (item.type !== "asset" || !item.fileName.endsWith(".json")) continue;
		const source = typeof item.source === "string" ? item.source : item.source instanceof Uint8Array ? new TextDecoder().decode(item.source) : void 0;
		if (!source) continue;
		try {
			const config = JSON.parse(source);
			if (config && typeof config === "object" && !Array.isArray(config)) jsonConfigs.set(item.fileName.replaceAll("\\", "/"), config);
		} catch {}
	}
	const appConfig = jsonConfigs.get("app.json");
	if (!appConfig) return [];
	const configFiles = /* @__PURE__ */ new Set(["app.json"]);
	if (Array.isArray(appConfig.pages)) {
		for (const page of appConfig.pages) if (typeof page === "string") configFiles.add(`${page}.json`);
	}
	const subPackages = Array.isArray(appConfig.subPackages) ? appConfig.subPackages : Array.isArray(appConfig.subpackages) ? appConfig.subpackages : [];
	for (const subPackage of subPackages) {
		if (!subPackage || typeof subPackage !== "object" || Array.isArray(subPackage)) continue;
		const { pages, root } = subPackage;
		if (typeof root !== "string" || !Array.isArray(pages)) continue;
		const normalizedRoot = root.replaceAll("\\", "/").replace(/^\/+|\/+$/g, "");
		for (const page of pages) if (typeof page === "string") configFiles.add(`${normalizedRoot}/${page}.json`);
	}
	return [...configFiles].filter((fileName) => jsonConfigs.get(fileName)?.renderer === "skyline");
}
function formatHmrRuntimeStartupMessages(decision) {
	if (decision.reason === "skyline-fallback") return ["HMR 模式:classic(自动降级:Skyline 暂不支持微信开发者工具热重载)", "HMR 切换:切回 WebView 后可手动重新开启微信开发者工具“热重载”。"];
	if (decision.reason === "runtime-compatibility-fallback") return ["HMR 模式:classic(自动降级:stateful HMR 运行时兼容性检查失败)", "HMR 切换:修复兼容性问题后重启 wv dev,或通过 weapp.hmr.runtime 显式配置 classic。"];
	if (decision.reason === "explicit") {
		const alternative = decision.runtime === "classic" ? "stateful-experimental" : "classic";
		return [`HMR 模式:${decision.runtime}(显式配置)`, `HMR 切换:修改 weapp.hmr.runtime 为 auto 或 ${alternative} 后重启 wv dev。`];
	}
	if (decision.reason === "auto-non-wechat") return ["HMR 模式:classic(自动检测:仅微信小程序支持 stateful-experimental)", "HMR 切换:可通过 weapp.hmr.runtime 显式配置 classic。"];
	if (decision.reason === "auto-stateful") return ["HMR 模式:stateful-experimental(自动检测:微信开发者工具热重载已开启)", "HMR 切换:关闭微信开发者工具“热重载”后重启 wv dev,或通过 weapp.hmr.runtime 显式配置。"];
	return ["HMR 模式:classic(自动检测:微信开发者工具热重载未开启或无法确认)", "HMR 切换:开启微信开发者工具“热重载”后重启 wv dev,或通过 weapp.hmr.runtime 显式配置。"];
}
//#endregion
//#region src/runtime/lib.ts
function hasLibEntry(entry) {
	if (!entry) return false;
	if (typeof entry === "string") return entry.trim().length > 0;
	if (Array.isArray(entry)) return entry.length > 0;
	if (isObject(entry)) return Object.keys(entry).length > 0;
	return false;
}
function resolveWeappLibConfig(options) {
	const { cwd, srcRoot, config } = options;
	if (!config) return;
	const root = config.root ?? srcRoot ?? "";
	const resolvedRoot = path.resolve(cwd, root || ".");
	const userDtsOptions = typeof config.dts === "object" && config.dts ? config.dts : void 0;
	const resolvedDtsEnabled = typeof config.dts === "boolean" ? config.dts : userDtsOptions?.enabled !== false;
	const resolvedDtsMode = userDtsOptions?.mode ?? "internal";
	const resolvedDts = {
		...userDtsOptions,
		enabled: resolvedDtsEnabled,
		mode: resolvedDtsMode
	};
	return {
		enabled: hasLibEntry(config.entry),
		entry: config.entry,
		root: resolvedRoot,
		outDir: config.outDir,
		preservePath: config.preservePath !== false,
		fileName: config.fileName,
		componentJson: config.componentJson ?? "auto",
		dts: resolvedDts,
		source: config
	};
}
function normalizeLibName(value) {
	return stripLeadingSlashes(normalizeRelativePath$1(value));
}
async function resolveEntryFile(root, entry) {
	const resolved = path.isAbsolute(entry) ? entry : path.resolve(root, entry);
	if (path.extname(resolved)) {
		if (await fs$1.pathExists(resolved)) return resolved;
	}
	const jsEntry = await findJsEntry(resolved);
	if (jsEntry.path) return jsEntry.path;
	const vueEntry = await findVueEntry(resolved);
	if (vueEntry) return vueEntry;
	if (await fs$1.pathExists(resolved)) return resolved;
}
function resolveEntryName(options) {
	const { explicitName, preservePath, relativeId } = options;
	if (explicitName) return normalizeLibName(explicitName);
	const base = removeExtensionDeep(relativeId);
	if (!preservePath) return normalizeLibName(path.basename(base));
	return normalizeLibName(base);
}
function resolveOutputBase(options) {
	const { entryName, entryPath, config } = options;
	const fileName = config.fileName;
	if (!fileName) return normalizeLibName(entryName);
	let resolved;
	if (typeof fileName === "function") {
		resolved = fileName({
			name: entryName,
			input: entryPath
		});
		if (typeof resolved !== "string") throw new TypeError("`weapp.lib.fileName` 必须返回字符串。");
	} else resolved = fileName.includes("[name]") ? fileName.replace(/\[name\]/g, entryName) : fileName;
	const normalized = normalizeLibName(resolved);
	if (!normalized) throw new Error("`weapp.lib.fileName` 解析结果为空,请检查配置。");
	return normalizeLibName(removeExtensionDeep(normalized));
}
function createLibEntryFileNameResolver(libConfig) {
	if (!libConfig.fileName) return;
	return (chunkInfo) => {
		return `${resolveOutputBase({
			entryName: chunkInfo.name,
			entryPath: chunkInfo.facadeModuleId ?? "",
			config: libConfig
		})}.js`;
	};
}
async function resolveWeappLibEntries(configService, libConfig) {
	const entry = libConfig.entry;
	const root = libConfig.root || configService.absoluteSrcRoot;
	const preservePath = libConfig.preservePath;
	const entries = [];
	if (typeof entry === "string") entries.push({ path: entry });
	else if (Array.isArray(entry)) for (const item of entry) entries.push({ path: item });
	else if (isObject(entry)) for (const [name, value] of Object.entries(entry)) entries.push({
		name,
		path: value
	});
	if (!entries.length) throw new Error("`weapp.lib.entry` 不能为空,请配置库模式入口。");
	if (typeof libConfig.fileName === "string" && !libConfig.fileName.includes("[name]") && entries.length > 1) throw new Error("`weapp.lib.fileName` 在多入口模式下必须包含 `[name]` 占位符。");
	const outputNames = /* @__PURE__ */ new Set();
	const resolved = [];
	for (const item of entries) {
		const entryPath = await resolveEntryFile(root, item.path);
		if (!entryPath) throw new Error(`未找到 lib 入口文件:${item.path}`);
		const relativeId = normalizeRelativePath$1(configService.relativeAbsoluteSrcRoot(entryPath));
		const entryName = resolveEntryName({
			explicitName: item.name,
			preservePath,
			relativeId
		});
		if (!entryName) throw new Error(`lib 入口解析失败:${item.path}`);
		const outputBase = resolveOutputBase({
			entryName,
			entryPath,
			config: libConfig
		});
		if (outputNames.has(outputBase)) throw new Error(`lib 输出路径冲突:${outputBase}`);
		outputNames.add(outputBase);
		const relativeBase = normalizeLibName(removeExtensionDeep(relativeId));
		resolved.push({
			name: entryName,
			input: entryPath,
			relativeBase,
			outputBase
		});
	}
	return resolved;
}
//#endregion
//#region src/runtime/libDts/rewriteWevuComponent.ts
function getVueCompilerLib(value) {
	if (Array.isArray(value)) {
		const resolved = value.filter((item) => typeof item === "string");
		return resolved.length > 0 ? resolved : void 0;
	}
	if (typeof value === "string") return value;
}
function splitTopLevelTypeArgs(value) {
	const args = [];
	let depth = 0;
	let start = 0;
	let quote = null;
	let escape = false;
	for (let i = 0; i < value.length; i += 1) {
		const char = value[i];
		if (quote) {
			if (escape) {
				escape = false;
				continue;
			}
			if (char === "\\") {
				escape = true;
				continue;
			}
			if (char === quote) quote = null;
			continue;
		}
		if (char === "\"" || char === "'" || char === "`") {
			quote = char;
			continue;
		}
		if (char === "<") {
			depth += 1;
			continue;
		}
		if (char === ">") {
			if (depth > 0) depth -= 1;
			continue;
		}
		if (char === "," && depth === 0) {
			args.push(value.slice(start, i).trim());
			start = i + 1;
		}
	}
	const tail = value.slice(start).trim();
	if (tail) args.push(tail);
	return args;
}
function findMatchingAngleBracket(value, start) {
	let depth = 1;
	let quote = null;
	let escape = false;
	for (let i = start; i < value.length; i += 1) {
		const char = value[i];
		if (quote) {
			if (escape) {
				escape = false;
				continue;
			}
			if (char === "\\") {
				escape = true;
				continue;
			}
			if (char === quote) quote = null;
			continue;
		}
		if (char === "\"" || char === "'" || char === "`") {
			quote = char;
			continue;
		}
		if (char === "<") {
			depth += 1;
			continue;
		}
		if (char === ">") {
			depth -= 1;
			if (depth === 0) return i;
		}
	}
	return -1;
}
function rewriteVueComponentTypeToWevu(content) {
	const token = "import(\"vue\").DefineComponent<";
	const tokenSingle = "import('vue').DefineComponent<";
	if (!content.includes(token) && !content.includes(tokenSingle)) return content;
	let result = "";
	let index = 0;
	while (index < content.length) {
		const nextDouble = content.indexOf(token, index);
		const nextSingle = content.indexOf(tokenSingle, index);
		const next = nextDouble === -1 ? nextSingle : nextSingle === -1 ? nextDouble : Math.min(nextDouble, nextSingle);
		if (next === -1) {
			result += content.slice(index);
			break;
		}
		const match = next === nextDouble ? token : tokenSingle;
		result += content.slice(index, next);
		const start = next + match.length;
		const end = findMatchingAngleBracket(content, start);
		if (end === -1) {
			result += content.slice(next);
			break;
		}
		const args = splitTopLevelTypeArgs(content.slice(start, end));
		while (args.length < 5) args.push("any");
		result += `import(\"wevu\").WevuComponentConstructor<${args.slice(0, 5).join(", ")}>`;
		index = end + 1;
	}
	return result;
}
function getVueCompilerLibOrUndefined(value) {
	return getVueCompilerLib(value);
}
function shouldRewriteWevuComponentType(value) {
	if (Array.isArray(value)) return value.includes("wevu");
	if (typeof value === "string") return value === "wevu";
	return true;
}
//#endregion
//#region src/runtime/libDts/shared.ts
const DTS_INPUT_EXTENSIONS = /* @__PURE__ */ new Set([
	".ts",
	".tsx",
	".mts",
	".cts"
]);
const NUMERIC_SUFFIX_RE = /^\d+$/;
const EMPTY_EXPORT_RE = /^export\s*\{\s*\};?\s*$/;
const DTS_OUTPUT_FILE_RE = /\.d\.(?:m|c)?ts$/;
const DTS_MAP_OUTPUT_FILE_RE = /\.d\.(?:m|c)?ts\.map$/;
const SOURCE_MAPPING_URL_RE = /# sourceMappingURL=.*$/gm;
function isBundledDtsEntry(entryPath) {
	const ext = path.extname(entryPath);
	if (entryPath.endsWith(".d.ts")) return true;
	return DTS_INPUT_EXTENSIONS.has(ext);
}
function getStubContent(entryPath) {
	if (entryPath.endsWith(".vue")) return "declare const _default: any\\nexport default _default\\n";
	return "export {}\\n";
}
async function ensureStub(entry, outDir) {
	const outputPath = path.resolve(outDir, `${entry.outputBase}.d.ts`);
	if (await fs$1.pathExists(outputPath)) return;
	await fs$1.ensureDir(path.dirname(outputPath));
	await fs$1.writeFile(outputPath, getStubContent(entry.input));
}
async function findDeconflictedDtsPath(expectedPath) {
	const dir = path.dirname(expectedPath);
	if (!await fs$1.pathExists(dir)) return;
	const baseName = path.basename(expectedPath, ".d.ts");
	const entries = await fs$1.readdir(dir);
	let bestMatch;
	let bestIndex = Number.POSITIVE_INFINITY;
	for (const name of entries) {
		if (!name.startsWith(baseName) || !name.endsWith(".d.ts")) continue;
		if (name === `${baseName}.d.ts`) continue;
		const suffix = name.slice(baseName.length, -5);
		if (!NUMERIC_SUFFIX_RE.test(suffix)) continue;
		const index = Number.parseInt(suffix, 10);
		if (Number.isNaN(index) || index >= bestIndex) continue;
		bestIndex = index;
		bestMatch = path.join(dir, name);
	}
	return bestMatch;
}
async function isStubDts(filePath) {
	const content = await fs$1.readFile(filePath, "utf8");
	return EMPTY_EXPORT_RE.test(content.trim());
}
async function normalizeRolldownDtsOutput(entries, outDir) {
	await Promise.all(entries.map(async (entry) => {
		const expectedPath = path.resolve(outDir, `${entry.outputBase}.d.ts`);
		const candidate = await findDeconflictedDtsPath(expectedPath);
		if (!candidate) return;
		if (!(!await fs$1.pathExists(expectedPath) || await isStubDts(expectedPath))) return;
		await fs$1.ensureDir(path.dirname(expectedPath));
		await fs$1.copy(candidate, expectedPath);
		if (candidate !== expectedPath) await fs$1.remove(candidate);
	}));
}
function normalizePath(value) {
	return value.split(path.sep).join("/");
}
function resolveRelativeBase(entryPath, libRoot, cwd) {
	const relativeToRoot = path.relative(libRoot, entryPath);
	if (!relativeToRoot.startsWith("..") && !path.isAbsolute(relativeToRoot)) return normalizePath(relativeToRoot);
	return normalizePath(path.relative(cwd, entryPath));
}
function runVueTsc(binPath, projectPath, cwd) {
	return new Promise((resolve, reject) => {
		const child = spawn(process.execPath, [
			binPath,
			"--project",
			projectPath
		], {
			cwd,
			stdio: "inherit"
		});
		child.on("error", reject);
		child.on("close", (code) => {
			if (code === 0) {
				resolve();
				return;
			}
			reject(/* @__PURE__ */ new Error(`[lib] vue-tsc 生成 dts 失败,退出码 ${code ?? "null"}`));
		});
	});
}
async function resolveInternalTsconfig(cwd, tsconfig) {
	if (tsconfig === false) return;
	if (tsconfig) {
		const resolved = path.isAbsolute(tsconfig) ? tsconfig : path.resolve(cwd, tsconfig);
		if (!await fs$1.pathExists(resolved)) throw new Error(`[lib] internal 方案未找到 tsconfig:${resolved}`);
		return resolved;
	}
	const defaultPath = path.resolve(cwd, "tsconfig.json");
	return await fs$1.pathExists(defaultPath) ? defaultPath : void 0;
}
async function tsconfigHasProjectReferences(tsconfigPath) {
	if (!tsconfigPath) return false;
	try {
		const config = await fs$1.readJson(tsconfigPath);
		return Array.isArray(config?.references) && config.references.length > 0;
	} catch {
		return false;
	}
}
function ensureModuleResolution(ts, compilerOptions) {
	if (compilerOptions.moduleResolution) return;
	const moduleKind = typeof compilerOptions.module === "number" ? compilerOptions.module : (compilerOptions.target ?? ts.ScriptTarget.ES5) >= ts.ScriptTarget.ES2015 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
	let moduleResolution;
	switch (moduleKind) {
		case ts.ModuleKind.CommonJS:
			moduleResolution = ts.ModuleResolutionKind.Node10;
			break;
		case ts.ModuleKind.Node16:
			moduleResolution = ts.ModuleResolutionKind.Node16;
			break;
		case ts.ModuleKind.NodeNext:
			moduleResolution = ts.ModuleResolutionKind.NodeNext;
			break;
		default: moduleResolution = ts.version.startsWith("5") ? ts.ModuleResolutionKind.Bundler : ts.ModuleResolutionKind.Classic;
	}
	compilerOptions.moduleResolution = moduleResolution;
}
function isDtsOutputFile(filePath) {
	return DTS_OUTPUT_FILE_RE.test(filePath) && !filePath.endsWith(".map");
}
function isDtsMapOutputFile(filePath) {
	return DTS_MAP_OUTPUT_FILE_RE.test(filePath);
}
function replaceSourceMappingUrl(content, mapFileName) {
	return content.replace(SOURCE_MAPPING_URL_RE, `# sourceMappingURL=${mapFileName}`);
}
function resolveVueSourceFile(program, filePath) {
	const normalized = normalizePath(filePath);
	const candidates = [
		filePath,
		normalized,
		`${filePath}.ts`,
		`${filePath}.js`,
		`${filePath}.tsx`,
		`${filePath}.jsx`,
		`${normalized}.ts`,
		`${normalized}.js`,
		`${normalized}.tsx`,
		`${normalized}.jsx`
	];
	for (const candidate of candidates) {
		const sourceFile = program.getSourceFile(candidate);
		if (sourceFile) return sourceFile;
	}
}
//#endregion
//#region src/runtime/libDts/generateVueDts.ts
const FILE_EXTENSION_RE = /\.[^.]+$/;
async function generateVueDtsWithVueTsc(configService, libConfig, vueEntries, dtsOptions) {
	const ts = await import("typescript");
	const vueTscPkg = resolveModule("vue-tsc/package.json", { paths: [configService.cwd, process.cwd()] });
	if (!vueTscPkg) throw new Error("[lib] 生成 Vue SFC 的 dts 需要安装 vue-tsc,请先安装后重试。");
	const vueTscBin = path.resolve(path.dirname(vueTscPkg), "bin/vue-tsc.js");
	const tempRoot = await fs$1.mkdtemp(path.join(os.tmpdir(), "weapp-vite-lib-dts-"));
	const tempOutDir = path.join(tempRoot, "out");
	const tsconfigPath = path.join(tempRoot, "tsconfig.json");
	let libRoot = libConfig.root || configService.absoluteSrcRoot;
	if (vueEntries.some((entry) => {
		const relative = path.relative(libRoot, entry.input);
		return relative.startsWith("..") || path.isAbsolute(relative);
	})) libRoot = configService.cwd;
	const baseVueTsconfig = {
		compilerOptions: {
			declaration: true,
			emitDeclarationOnly: true,
			declarationMap: false,
			outDir: tempOutDir,
			declarationDir: tempOutDir,
			rootDir: libRoot,
			allowJs: true,
			jsx: ts.JsxEmit.Preserve,
			skipLibCheck: true,
			module: ts.ModuleKind.ESNext,
			target: ts.ScriptTarget.ESNext,
			moduleResolution: ts.ModuleResolutionKind.Bundler
		},
		files: vueEntries.map((entry) => entry.input),
		include: vueEntries.map((entry) => entry.input),
		vueCompilerOptions: { lib: "wevu" }
	};
	const vueTscOptions = dtsOptions?.vueTsc;
	const vueTsconfig = {
		...baseVueTsconfig,
		...vueTscOptions?.tsconfig,
		compilerOptions: {
			...baseVueTsconfig.compilerOptions,
			...vueTscOptions?.compilerOptions
		},
		vueCompilerOptions: {
			...baseVueTsconfig.vueCompilerOptions,
			...vueTscOptions?.vueCompilerOptions
		}
	};
	const rewriteWevuComponentType = shouldRewriteWevuComponentType(getVueCompilerLibOrUndefined(vueTsconfig.vueCompilerOptions?.lib));
	await fs$1.ensureDir(tempOutDir);
	await fs$1.writeJson(tsconfigPath, vueTsconfig, { spaces: 2 });
	await runVueTsc(vueTscBin, tsconfigPath, configService.cwd);
	await Promise.all(vueEntries.map(async (entry) => {
		const relativeBase = resolveRelativeBase(entry.input, libRoot, configService.cwd);
		const candidate = path.join(tempOutDir, `${relativeBase.replace(FILE_EXTENSION_RE, "")}.d.ts`);
		const candidateWithExt = path.join(tempOutDir, `${relativeBase}.d.ts`);
		const sourcePath = await fs$1.pathExists(candidate) ? candidate : await fs$1.pathExists(candidateWithExt) ? candidateWithExt : void 0;
		if (!sourcePath) throw new Error(`[lib] 生成 Vue SFC dts 失败,未找到输出:${relativeBase}`);
		const outputPath = path.resolve(configService.outDir, `${entry.outputBase}.d.ts`);
		await fs$1.ensureDir(path.dirname(outputPath));
		const content = await fs$1.readFile(sourcePath, "utf8");
		const normalized = rewriteWevuComponentType ? rewriteVueComponentTypeToWevu(content) : content;
		await fs$1.writeFile(outputPath, normalized);
	}));
	await fs$1.remove(tempRoot);
}
async function generateVueDtsWithInternal(configService, vueEntries, dtsOptions) {
	const languageCorePkg = resolveModule("@vue/language-core/package.json", { paths: [configService.cwd, process.cwd()] });
	const volarTsPkg = resolveModule("@volar/typescript/package.json", { paths: [configService.cwd, process.cwd()] });
	const tsPkg = resolveModule("typescript/package.json", { paths: [configService.cwd, process.cwd()] });
	if (!languageCorePkg || !volarTsPkg || !tsPkg) throw new Error("[lib] internal 方案生成 Vue SFC dts 需要安装 typescript、@vue/language-core 与 @volar/typescript。");
	const ts = await import("typescript");
	const { createParsedCommandLine, createVueLanguagePlugin, getDefaultCompilerOptions } = await import("@vue/language-core");
	const { proxyCreateProgram } = await import("@volar/typescript");
	const internalOptions = dtsOptions?.internal;
	const tsconfigPath = await resolveInternalTsconfig(configService.cwd, internalOptions?.tsconfig);
	const configHost = {
		useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
		readDirectory: ts.sys.readDirectory,
		fileExists: ts.sys.fileExists,
		readFile: ts.sys.readFile,
		getCurrentDirectory: ts.sys.getCurrentDirectory,
		onUnRecoverableConfigFileDiagnostic: () => {}
	};
	const parsedVue = tsconfigPath ? createParsedCommandLine(ts, configHost, normalizePath(tsconfigPath)) : void 0;
	const parsedTs = tsconfigPath ? ts.getParsedCommandLineOfConfigFile(tsconfigPath, void 0, configHost) : void 0;
	const compilerOptions = {
		...parsedVue?.options ?? parsedTs?.options ?? {},
		...internalOptions?.compilerOptions ?? {}
	};
	compilerOptions.noEmit = false;
	compilerOptions.declaration = true;
	compilerOptions.emitDeclarationOnly = true;
	compilerOptions.allowNonTsExtensions = true;
	compilerOptions.allowArbitraryExtensions = true;
	compilerOptions.skipLibCheck = true;
	compilerOptions.checkJs = false;
	compilerOptions.target ??= ts.ScriptTarget.ESNext;
	ensureModuleResolution(ts, compilerOptions);
	const baseVueOptions = parsedVue?.vueOptions ?? getDefaultCompilerOptions();
	const rawVueCompilerOptions = internalOptions?.vueCompilerOptions;
	const vueCompilerOptions = {
		...baseVueOptions,
		lib: "wevu",
		...rawVueCompilerOptions ?? {}
	};
	const rewriteWevuComponentType = shouldRewriteWevuComponentType(vueCompilerOptions.lib);
	const rootNames = Array.from(/* @__PURE__ */ new Set([...(parsedTs?.fileNames ?? []).map((file) => path.isAbsolute(file) ? file : path.resolve(configService.cwd, file)), ...vueEntries.map((entry) => entry.input)])).map(normalizePath);
	const host = ts.createCompilerHost(compilerOptions);
	const program = proxyCreateProgram(ts, ts.createProgram, (tsInstance, options) => {
		return { languagePlugins: [createVueLanguagePlugin(tsInstance, options.options, vueCompilerOptions, (id) => id)] };
	})({
		host,
		rootNames,
		options: compilerOptions,
		projectReferences: parsedTs?.projectReferences
	});
	await Promise.all(vueEntries.map(async (entry) => {
		const sourceFile = resolveVueSourceFile(program, entry.input);
		if (!sourceFile) throw new Error(`[lib] internal 方案生成 Vue SFC dts 失败,未找到源文件:${entry.input}`);
		const outputs = [];
		const emitResult = program.emit(sourceFile, (filePath, content) => {
			outputs.push({
				path: filePath,
				content
			});
		}, void 0, true);
		if (emitResult.emitSkipped && emitResult.diagnostics.length > 0) {
			const hostForDiagnostics = ts.createCompilerHost(compilerOptions);
			throw new Error(ts.formatDiagnosticsWithColorAndContext(emitResult.diagnostics, hostForDiagnostics));
		}
		const dtsOutput = outputs.find((output) => isDtsOutputFile(output.path));
		if (!dtsOutput) throw new Error(`[lib] internal 方案生成 Vue SFC dts 失败,未找到输出:${entry.input}`);
		const mapOutput = outputs.find((output) => isDtsMapOutputFile(output.path));
		const outputPath = path.resolve(configService.outDir, `${entry.outputBase}.d.ts`);
		await fs$1.ensureDir(path.dirname(outputPath));
		let content = dtsOutput.content;
		if (rewriteWevuComponentType) content = rewriteVueComponentTypeToWevu(content);
		if (mapOutput) {
			const mapPath = path.resolve(configService.outDir, `${entry.outputBase}.d.ts.map`);
			await fs$1.writeFile(mapPath, mapOutput.content);
			content = replaceSourceMappingUrl(content, path.basename(mapPath));
		}
		await fs$1.writeFile(outputPath, content);
	}));
}
//#endregion
//#region src/runtime/libDts.ts
async function generateLibDts(configService) {
	const libConfig = configService.weappLibConfig;
	if (!libConfig) return;
	if (!libConfig.enabled) return;
	const dtsOptions = libConfig.dts;
	if (dtsOptions?.enabled === false) return;
	const entries = await resolveWeappLibEntries(configService, libConfig);
	if (entries.length === 0) return;
	const vueEntries = entries.filter((entry) => entry.input.endsWith(".vue"));
	const tsEntries = entries.filter((entry) => !entry.input.endsWith(".vue") && isBundledDtsEntry(entry.input));
	const input = {};
	for (const entry of tsEntries) input[entry.outputBase] = entry.input;
	if (Object.keys(input).length > 0) {
		const tsconfigPath = path.resolve(configService.cwd, "tsconfig.json");
		const hasTsconfig = await fs$1.pathExists(tsconfigPath);
		const userRolldownOptions = dtsOptions?.rolldown ?? {};
		const hasUserTsconfig = hasOwn$5(userRolldownOptions, "tsconfig");
		const hasUserBuild = hasOwn$5(userRolldownOptions, "build");
		const userTsconfig = userRolldownOptions.tsconfig;
		const resolvedTsconfig = hasUserTsconfig ? typeof userTsconfig === "string" || userTsconfig === false ? userTsconfig : hasTsconfig ? tsconfigPath : false : hasTsconfig ? tsconfigPath : false;
		const shouldUseBuildMode = !hasUserBuild && await tsconfigHasProjectReferences(resolvedTsconfig);
		const compilerOptions = {
			allowImportingTsExtensions: true,
			allowJs: true,
			...userRolldownOptions.compilerOptions
		};
		await build$1({
			input,
			plugins: dts({
				...userRolldownOptions,
				tsconfig: resolvedTsconfig,
				build: shouldUseBuildMode ? true : userRolldownOptions.build,
				compilerOptions,
				cwd: configService.cwd,
				emitDtsOnly: true,
				vue: false
			}),
			output: {
				dir: configService.outDir,
				entryFileNames: "[name].d.ts"
			},
			write: true
		});
		await normalizeRolldownDtsOutput(tsEntries, configService.outDir);
	}
	if (vueEntries.length > 0) {
		if (dtsOptions?.mode === "vue-tsc") await generateVueDtsWithVueTsc(configService, libConfig, vueEntries, dtsOptions);
		else await generateVueDtsWithInternal(configService, vueEntries, dtsOptions);
	}
	await Promise.all(entries.map((entry) => ensureStub(entry, configService.outDir)));
	if (vueEntries.length > 0) {
		if (shouldRewriteWevuComponentType(dtsOptions?.mode === "vue-tsc" ? getVueCompilerLibOrUndefined(dtsOptions?.vueTsc?.vueCompilerOptions?.lib) : getVueCompilerLibOrUndefined(dtsOptions?.internal?.vueCompilerOptions?.lib))) await Promise.all(vueEntries.map(async (entry) => {
			const outputPath = path.resolve(configService.outDir, `${entry.outputBase}.d.ts`);
			if (!await fs$1.pathExists(outputPath)) return;
			const content = await fs$1.readFile(outputPath, "utf8");
			const normalized = rewriteVueComponentTypeToWevu(content);
			if (normalized !== content) await fs$1.writeFile(outputPath, normalized);
		}));
	}
}
//#endregion
//#region src/cache/file.ts
const FNV_OFFSET_BASIS = 14695981039346656037n;
const FNV_PRIME = 1099511628211n;
const FNV_MASK = 18446744073709551615n;
function fnv1aStep(hash, byte) {
	hash ^= BigInt(byte & 255);
	return hash * FNV_PRIME & FNV_MASK;
}
function createSignature(content) {
	let hash = FNV_OFFSET_BASIS;
	if (typeof content === "string") for (let i = 0; i < content.length; i++) {
		const code = content.charCodeAt(i);
		hash = fnv1aStep(hash, code & 255);
		const high = code >>> 8;
		if (high > 0) hash = fnv1aStep(hash, high);
	}
	else for (const byte of content) hash = fnv1aStep(hash, byte);
	return hash.toString(36);
}
var FileCache = class {
	cache;
	mtimeMap;
	signatureMap;
	constructor(max = 1024) {
		this.mtimeMap = /* @__PURE__ */ new Map();
		this.signatureMap = /* @__PURE__ */ new Map();
		this.cache = new LRUCache({
			max,
			dispose: (_value, key) => {
				this.mtimeMap.delete(key);
				this.signatureMap.delete(key);
			}
		});
	}
	get(id) {
		return this.cache.get(id);
	}
	set(id, content) {
		return this.cache.set(id, content);
	}
	delete(id) {
		this.mtimeMap.delete(id);
		this.signatureMap.delete(id);
		return this.cache.delete(id);
	}
	async isInvalidate(id, options) {
		const checkMtime = options?.checkMtime ?? true;
		const nextSignature = options?.signature ?? (options?.content !== void 0 ? createSignature(options.content) : void 0);
		if (!checkMtime) {
			if (nextSignature === void 0) return true;
			if (this.signatureMap.get(id) !== nextSignature) {
				this.signatureMap.set(id, nextSignature);
				return true;
			}
			return false;
		}
		let mtimeMs;
		if (typeof options?.mtimeMs === "number" && Number.isFinite(options.mtimeMs)) mtimeMs = options.mtimeMs;
		else try {
			mtimeMs = (await fs$1.stat(id)).mtimeMs;
		} catch (error) {
			if (error && error.code === "ENOENT") {
				this.cache.delete(id);
				this.mtimeMap.delete(id);
				this.signatureMap.delete(id);
				return true;
			}
			throw error;
		}
		if (mtimeMs === void 0) return true;
		const cachedMtime = this.mtimeMap.get(id);
		const updateSignature = () => {
			if (nextSignature !== void 0) this.signatureMap.set(id, nextSignature);
		};
		if (cachedMtime === void 0) {
			this.mtimeMap.set(id, mtimeMs);
			updateSignature();
			return true;
		} else if (cachedMtime > mtimeMs) {
			this.mtimeMap.set(id, mtimeMs);
			updateSignature();
			return true;
		} else if (cachedMtime === mtimeMs) {
			if (nextSignature !== void 0) {
				if (this.signatureMap.get(id) !== nextSignature) {
					updateSignature();
					return true;
				}
			}
			return false;
		} else {
			this.mtimeMap.set(id, mtimeMs);
			updateSignature();
			return true;
		}
	}
};
//#endregion
//#region src/defaults.ts
const defaultExcluded = [
	"**/node_modules/**",
	"**/miniprogram_npm/**",
	"**/.weapp-vite",
	"**/.weapp-vite/**"
];
/**
* 样式扩展名说明:
* - wxss:微信小程序
* - acss:支付宝小程序
* - jxss:京东小程序
* - ttss:头条小程序
* - qss:QQ 小程序
* - css:通用样式文件
* - tyss:涂鸦小程序
*/
/**
* 模板扩展名说明:
* - wxml:微信小程序
* - axml:支付宝小程序
* - jxml:京东小程序
* - ksml:快手小程序
* - ttml:头条小程序
* - qml:QQ 小程序
* - tyml:涂鸦小程序
* - xhsml:小红书小程序
* - swan:百度小程序
*/
function getOutputExtensions(platform) {
	return getPlatformOutputExtensions(platform ?? DEFAULT_MP_PLATFORM);
}
function getWeappViteConfig() {
	return {
		autoRoutes: false,
		wxml: true,
		wxs: true,
		enhance: {
			wxml: true,
			wxs: true
		},
		platform: DEFAULT_MP_PLATFORM,
		multiPlatform: false,
		es5: false,
		packageSizeWarningBytes: 2097152,
		analyze: {
			budgets: {
				totalBytes: 20971520,
				mainBytes: 2097152,
				subPackageBytes: 2097152,
				independentBytes: 2097152,
				warningRatio: .85
			},
			history: {
				enabled: true,
				dir: ".weapp-vite/analyze-history",
				limit: 20
			}
		},
		jsFormat: "cjs",
		isAdditionalWxml: () => {
			return false;
		},
		npm: {
			enable: true,
			cache: true,
			alipayNpmMode: "node_modules"
		},
		hmr: {
			runtime: "auto",
			sharedChunks: "auto",
			touchAppWxss: "auto",
			logLevel: "default",
			profileJson: false
		},
		mcp: {
			enabled: true,
			autoStart: "ai",
			host: "127.0.0.1",
			port: "auto",
			endpoint: "/mcp",
			restEndpoint: "/api/weapp/devtools"
		},
		forwardConsole: {
			enabled: "auto",
			logLevels: [
				"log",
				"info",
				"warn",
				"error"
			],
			unhandledErrors: true
		},
		appPrelude: { mode: "require" },
		wevu: { defaults: { component: { allowNullPropInput: true } } },
		chunks: {
			sharedStrategy: "duplicate",
			sharedMode: "common",
			sharedOverrides: [],
			sharedPathRoot: void 0,
			dynamicImports: "preserve",
			logOptimization: true,
			forceDuplicatePatterns: [],
			duplicateWarningBytes: 524288
		}
	};
}
const defaultAssetExtensions = [
	"png",
	"jpg",
	"jpeg",
	"gif",
	"svg",
	"cer",
	"mp3",
	"aac",
	"m4a",
	"mp4",
	"wav",
	"ogg",
	"silk",
	"wasm",
	"br",
	"cert"
];
//#endregion
//#region src/multiPlatform.ts
const DEFAULT_MULTI_PLATFORM_PROJECT_CONFIG_ROOT = "config";
function normalizeMultiPlatformProjectConfigRoot(input) {
	if (typeof input !== "string") return DEFAULT_MULTI_PLATFORM_PROJECT_CONFIG_ROOT;
	return input.trim() || "config";
}
function resolveMultiPlatformTargets(value) {
	const supportedPlatforms = getSupportedMiniProgramPlatforms$1();
	if (value == null || value === "all") return supportedPlatforms;
	if (!Array.isArray(value)) throw new TypeError("`weapp.multiPlatform.targets` 必须是平台数组或 \"all\"。");
	const resolvedTargets = [];
	const invalidTargets = [];
	for (const rawTarget of value) {
		const resolvedTarget = typeof rawTarget === "string" ? resolveMiniPlatform(rawTarget) : void 0;
		if (!resolvedTarget) {
			invalidTargets.push(String(rawTarget));
			continue;
		}
		if (!resolvedTargets.includes(resolvedTarget)) resolvedTargets.push(resolvedTarget);
	}
	if (invalidTargets.length > 0) throw new Error(`\`weapp.multiPlatform.targets\` 包含不支持的平台:${invalidTargets.join(", ")}`);
	if (resolvedTargets.length === 0) throw new Error("`weapp.multiPlatform.targets` 至少需要包含一个目标平台。");
	return resolvedTargets;
}
function resolveMultiPlatformConfig(value) {
	if (!value) return {
		enabled: false,
		projectConfigRoot: DEFAULT_MULTI_PLATFORM_PROJECT_CONFIG_ROOT,
		targets: getSupportedMiniProgramPlatforms$1()
	};
	if (value === true) return {
		enabled: true,
		projectConfigRoot: DEFAULT_MULTI_PLATFORM_PROJECT_CONFIG_ROOT,
		targets: getSupportedMiniProgramPlatforms$1()
	};
	if (typeof value === "object" && value !== null) {
		const record = value;
		const targets = resolveMultiPlatformTargets(record.targets);
		return {
			enabled: record.enabled !== false,
			projectConfigRoot: normalizeMultiPlatformProjectConfigRoot(record.projectConfigRoot),
			targets
		};
	}
	return {
		enabled: false,
		projectConfigRoot: DEFAULT_MULTI_PLATFORM_PROJECT_CONFIG_ROOT,
		targets: getSupportedMiniProgramPlatforms$1()
	};
}
function supportsMultiPlatformTarget(multiPlatform, platform) {
	return multiPlatform.targets.includes(platform);
}
function resolveMultiPlatformProjectConfigDir(multiPlatform, platform) {
	return path.join(multiPlatform.projectConfigRoot || "config", platform);
}
//#endregion
//#region src/runtime/runtimeState.ts
function createDefaultLoadConfigResult() {
	return {
		config: {},
		loadOptions: {
			cwd: process.cwd(),
			isDev: false,
			mode: "development",
			emitDefaultAutoImportOutputs: true
		},
		aliasEntries: [],
		outputExtensions: getOutputExtensions(DEFAULT_MP_PLATFORM),
		packageJson: {},
		relativeSrcRoot: (p) => p,
		cwd: process.cwd(),
		isDev: false,
		mode: "development",
		emitDefaultAutoImportOutputs: true,
		projectConfig: {},
		projectConfigPath: void 0,
		projectPrivateConfig: {},
		projectPrivateConfigPath: void 0,
		mpDistRoot: "",
		multiPlatform: resolveMultiPlatformConfig(false),
		weappLib: void 0,
		weappLibOutputMap: void 0,
		packageJsonPath: "",
		platform: DEFAULT_MP_PLATFORM,
		srcRoot: "",
		configFilePath: void 0,
		configFileDependencies: [],
		weappWeb: void 0,
		configMergeInfo: void 0
	};
}
function createDefaultPackageInfo() {
	return {
		name: "",
		version: void 0,
		rootPath: "",
		packageJsonPath: "",
		packageJson: {}
	};
}
function createDefaultPackageManager() {
	return {
		agent: "npm",
		name: "npm"
	};
}
function createRuntimeState() {
	const emptyAutoRoutesSnapshot = createEmptyAutoRoutesSnapshot();
	const emptyAutoRoutesArtifacts = createAutoRoutesArtifacts(emptyAutoRoutesSnapshot);
	return {
		glassEasel: {
			detected: false,
			diagnostics: /* @__PURE__ */ new Map(),
			warnedDiagnostics: /* @__PURE__ */ new Set(),
			silent: false
		},
		autoRoutes: {
			routes: emptyAutoRoutesSnapshot,
			serialized: emptyAutoRoutesArtifacts.serialized,
			moduleCode: emptyAutoRoutesArtifacts.moduleCode,
			typedDefinition: "",
			watchFiles: /* @__PURE__ */ new Set(),
			watchDirs: /* @__PURE__ */ new Set(),
			dirty: true,
			initialized: false,
			candidates: /* @__PURE__ */ new Map(),
			needsFullRescan: true,
			loadingAppConfig: false
		},
		autoImport: {
			registry: /* @__PURE__ */ new Map(),
			normalizedLocalComponents: /* @__PURE__ */ new Map(),
			resolvedResolverComponents: /* @__PURE__ */ new Map(),
			matcherKey: "",
			preparedGlobsKey: void 0,
			version: 0,
			pendingEntriesByImporter: /* @__PURE__ */ new Map()
		},
		build: {
			queue: new PQueue({ autoStart: false }),
			npmBuilt: false,
			independent: {
				outputs: /* @__PURE__ */ new Map(),
				pendingOutputs: []
			},
			output: {
				emittedSource: /* @__PURE__ */ new Map(),
				wevuInternalRuntimeFileName: void 0,
				wevuInternalRuntimeFileNames: /* @__PURE__ */ new Map()
			},
			hmr: {
				loadedEntrySet: /* @__PURE__ */ new Set(),
				dirtyEntrySet: /* @__PURE__ */ new Set(),
				dirtyEntryReasons: /* @__PURE__ */ new Map(),
				resolvedEntryMap: /* @__PURE__ */ new Map(),
				externalComponentEntryMap: /* @__PURE__ */ new Map(),
				entriesMap: /* @__PURE__ */ new Map(),
				vueEntryHasTemplate: /* @__PURE__ */ new Map(),
				vueEntrySfcSignatures: /* @__PURE__ */ new Map(),
				vueEntryTailwindContentSignatures: /* @__PURE__ */ new Map(),
				vueEntryTailwindTemplateContentSignatures: /* @__PURE__ */ new Map(),
				vueEntryTailwindScriptContentSignatures: /* @__PURE__ */ new Map(),
				appEntryAutoRoutesSignature: void 0,
				dirtyVueEntryIds: /* @__PURE__ */ new Set(),
				didEmitAllEntries: false,
				lastHmrEntryIds: /* @__PURE__ */ new Set(),
				lastEmittedEntryIds: /* @__PURE__ */ new Set(),
				lastEmittedChunkFileNames: /* @__PURE__ */ new Set(),
				sharedChunkSourceModuleIds: /* @__PURE__ */ new Set(),
				recentProfiles: [],
				profile: {}
			}
		},
		json: {
			cache: new FileCache(),
			emittedSource: /* @__PURE__ */ new Map()
		},
		asset: {
			emittedBuffer: /* @__PURE__ */ new Map(),
			scopedSlotGenerics: /* @__PURE__ */ new Map()
		},
		css: {
			importerToDependencies: /* @__PURE__ */ new Map(),
			dependencyToImporters: /* @__PURE__ */ new Map(),
			transformedSidecarSource: /* @__PURE__ */ new Map(),
			emittedSource: /* @__PURE__ */ new Map(),
			sidecarImports: /* @__PURE__ */ new Set()
		},
		watcher: {
			rollupWatcherMap: /* @__PURE__ */ new Map(),
			sidecarWatcherMap: /* @__PURE__ */ new Map(),
			sidecarDirtyFiles: /* @__PURE__ */ new Map()
		},
		wxml: {
			depsMap: /* @__PURE__ */ new Map(),
			importerMap: /* @__PURE__ */ new Map(),
			depKindMap: /* @__PURE__ */ new Map(),
			tokenMap: /* @__PURE__ */ new Map(),
			componentsMap: /* @__PURE__ */ new Map(),
			aggregatedComponentsMap: /* @__PURE__ */ new Map(),
			templatePathMap: /* @__PURE__ */ new Map(),
			cache: new FileCache(),
			emittedCode: /* @__PURE__ */ new Map()
		},
		scan: {
			mainPackageStyleEntries: void 0,
			subPackageMap: /* @__PURE__ */ new Map(),
			independentSubPackageMap: /* @__PURE__ */ new Map(),
			warnedMessages: /* @__PURE__ */ new Set(),
			isDirty: true,
			independentDirtyRoots: /* @__PURE__ */ new Set(),
			pluginJsonPath: void 0
		},
		lib: {
			enabled: false,
			entries: /* @__PURE__ */ new Map()
		},
		config: {
			packageInfo: createDefaultPackageInfo(),
			defineEnv: {},
			importMetaEnvDefineOverride: void 0,
			packageManager: createDefaultPackageManager(),
			options: createDefaultLoadConfigResult()
		}
	};
}
//#endregion
//#region src/runtime/resetRuntimeState.ts
function resetRuntimeStateForFreshBuild(runtimeState) {
	const fresh = createRuntimeState();
	runtimeState.glassEasel.detected = false;
	runtimeState.glassEasel.diagnostics.clear();
	runtimeState.glassEasel.warnedDiagnostics.clear();
	runtimeState.glassEasel.silent = false;
	const autoRoutes = runtimeState.autoRoutes;
	autoRoutes.routes = fresh.autoRoutes.routes;
	autoRoutes.serialized = fresh.autoRoutes.serialized;
	autoRoutes.moduleCode = fresh.autoRoutes.moduleCode;
	autoRoutes.typedDefinition = fresh.autoRoutes.typedDefinition;
	autoRoutes.watchFiles.clear();
	autoRoutes.watchDirs.clear();
	autoRoutes.dirty = fresh.autoRoutes.dirty;
	autoRoutes.initialized = fresh.autoRoutes.initialized;
	autoRoutes.candidates.clear();
	autoRoutes.needsFullRescan = fresh.autoRoutes.needsFullRescan;
	autoRoutes.loadingAppConfig = fresh.autoRoutes.loadingAppConfig;
	const autoImport = runtimeState.autoImport;
	autoImport.registry.clear();
	autoImport.normalizedLocalComponents.clear();
	autoImport.resolvedResolverComponents.clear();
	autoImport.matcher = void 0;
	autoImport.matcherKey = fresh.autoImport.matcherKey;
	autoImport.version += 1;
	autoImport.pendingEntriesByImporter.clear();
	runtimeState.build.hmr = fresh.build.hmr;
	const json = runtimeState.json;
	json.cache.cache.clear();
	json.cache.mtimeMap.clear();
	json.cache.signatureMap.clear();
	json.emittedSource.clear();
	const asset = runtimeState.asset;
	asset.emittedBuffer.clear();
	asset.scopedSlotGenerics.clear();
	const css = runtimeState.css;
	css.importerToDependencies.clear();
	css.dependencyToImporters.clear();
	css.transformedSidecarSource.clear();
	css.emittedSource.clear();
	const wxml = runtimeState.wxml;
	wxml.depsMap.clear();
	wxml.importerMap.clear();
	wxml.tokenMap.clear();
	wxml.componentsMap.clear();
	wxml.aggregatedComponentsMap.clear();
	wxml.templatePathMap.clear();
	wxml.cache.cache.clear();
	wxml.cache.mtimeMap.clear();
	wxml.cache.signatureMap.clear();
	wxml.emittedCode.clear();
	const scan = runtimeState.scan;
	scan.mainPackageStyleEntries = void 0;
	scan.subPackageMap.clear();
	scan.independentSubPackageMap.clear();
	scan.warnedMessages.clear();
	scan.appEntry = void 0;
	scan.pluginJson = void 0;
	scan.pluginJsonPath = void 0;
	scan.isDirty = fresh.scan.isDirty;
	scan.independentDirtyRoots.clear();
	const lib = runtimeState.lib;
	lib.enabled = fresh.lib.enabled;
	lib.entries.clear();
	runtimeState.watcher.sidecarDirtyFiles.clear();
}
//#endregion
//#region src/plugins/core/lifecycle/emit/constants.ts
const PRETTY_NODE_MODULES_RE = /node_modules\/(?:\.pnpm\/[^/]+\/node_modules\/)?(.+)/;
const REQUEST_GLOBAL_EXPORT_RE = /Object\.defineProperty\(exports,\s*(?:`([^`]+)`|'([^']+)'|"([^"]+)"),\s*\{[\s\S]*?get:function\(\)\{return ([A-Za-z_$][\w$]*)\}\}\)/g;
const REQUEST_GLOBAL_INSTALLER_RE = /function\s+([A-Za-z_$][\w$]*)\([^)]*=\{\}\)\{[\s\S]{0,220}?targets\?\?\[[\s\S]{0,80}?fetch[\s\S]{0,80}?Headers[\s\S]{0,80}?Request[\s\S]{0,80}?Response[\s\S]{0,80}?AbortController[\s\S]{0,80}?AbortSignal[\s\S]{0,80}?XMLHttpRequest[\s\S]{0,80}?WebSocket[\s\S]{0,260}?return [^}]+\}/;
const REQUEST_GLOBAL_ENTRY_NAME_RE = /\.[^/.]+$/;
const REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE = /([A-Za-z_$][\w$]*)\s*=\s*require\((`([^`]+)`|'([^']+)'|"([^"]+)")\)/g;
const REQUEST_GLOBAL_RUNTIME_CHUNK_FILE_BASENAME = "weapp-vendors/request-globals-runtime.js";
const DYNAMIC_GLOBAL_RESOLUTION_RE = /Function\(\s*(?:`return this`|'return this'|"return this")\s*\)\(\)/g;
const BROWSER_GLOBAL_HOST_TERNARY_RE = /typeof self<[`'"]u[`'"]\?self:typeof window<[`'"]u[`'"]\?window:globalThis/g;
const AXIOS_MODULE_ID_RE = /[/\\](?:\.pnpm[/\\][^/\\]+[/\\]node_modules[/\\])?axios[/\\]/u;
const APP_PRELUDE_REQUIRE_FILE_BASENAME = "app.prelude.js";
const DIRECTIVE_PROLOGUE_RE = /^(?:(['"])(?:\\.|(?!\1)[^\\])*\1;?\s*)+/u;
const USE_STRICT_PREFIX_RE = /^(?:['"]use strict['"];\s*)+/u;
//#endregion
//#region src/runtime/chunkStrategy/state.ts
const sharedChunkDiagnostics = /* @__PURE__ */ new Map();
const takeImportersMap = /* @__PURE__ */ new Map();
const forceDuplicateSharedChunks = /* @__PURE__ */ new Set();
const sharedChunkNameCache = /* @__PURE__ */ new Map();
function resetTakeImportRegistry(options = {}) {
	takeImportersMap.clear();
	forceDuplicateSharedChunks.clear();
	sharedChunkDiagnostics.clear();
	if (!options.preserveSharedChunkNameCache) sharedChunkNameCache.clear();
}
function getTakeImporters(moduleId) {
	return takeImportersMap.get(moduleId);
}
function markForceDuplicateSharedChunk(sharedName) {
	if (!sharedName) return;
	forceDuplicateSharedChunks.add(sharedName);
	forceDuplicateSharedChunks.add(`${sharedName}.js`);
}
function isForceDuplicateSharedChunk(fileName) {
	return forceDuplicateSharedChunks.has(fileName);
}
function hasForceDuplicateSharedChunks() {
	return forceDuplicateSharedChunks.size > 0;
}
function recordSharedChunkDiagnostics(sharedName, ignoredMainImporters) {
	if (!sharedName || ignoredMainImporters.length === 0) return;
	const uniqueImporters = Array.from(new Set(ignoredMainImporters));
	sharedChunkDiagnostics.set(sharedName, { ignoredMainImporters: uniqueImporters });
	sharedChunkDiagnostics.set(`${sharedName}.js`, { ignoredMainImporters: uniqueImporters });
}
function consumeSharedChunkDiagnostics(fileName) {
	const direct = sharedChunkDiagnostics.get(fileName);
	if (direct) {
		sharedChunkDiagnostics.delete(fileName);
		return direct;
	}
	const withoutExt = fileName.replace(/\.[^./\\]+$/, "");
	const fallback = sharedChunkDiagnostics.get(withoutExt);
	if (fallback) {
		sharedChunkDiagnostics.delete(withoutExt);
		return fallback;
	}
}
function getCachedSharedChunkName(moduleId) {
	if (!sharedChunkNameCache.has(moduleId)) return;
	return sharedChunkNameCache.get(moduleId) ?? null;
}
function setCachedSharedChunkName(moduleId, value) {
	if (!moduleId) return;
	sharedChunkNameCache.set(moduleId, value ?? null);
}
//#endregion
//#region src/utils/sourcemap.ts
function isEncodedSourceMapLike(value) {
	return Boolean(value && typeof value === "object" && "version" in value && typeof value.version === "number" && "mappings" in value && "names" in value && "sources" in value);
}
function normalizeEncodedSourceMapLike(value) {
	if (!value || typeof value !== "object") return null;
	const sourceMap = value;
	const numericVersion = typeof sourceMap.version === "number" ? sourceMap.version : typeof sourceMap.version === "string" ? Number(sourceMap.version) : NaN;
	if (!Number.isFinite(numericVersion)) return null;
	const normalized = {
		...sourceMap,
		version: numericVersion
	};
	return isEncodedSourceMapLike(normalized) ? normalized : null;
}
function composeSourceMaps(transformedMap, originalMap) {
	if (isEncodedSourceMapLike(transformedMap) && isEncodedSourceMapLike(originalMap)) return remapping([transformedMap, originalMap], () => null);
	if (isEncodedSourceMapLike(transformedMap)) return transformedMap;
	if (isEncodedSourceMapLike(originalMap)) return originalMap;
	return null;
}
//#endregion
//#region src/utils/outputChunk.ts
const INLINE_SOURCE_MAP_RE = /\n?\/\/[#@]\s*sourceMappingURL=(data:application\/json\S*)\s*$/u;
function resolveInlineSourceMap(code) {
	const match = INLINE_SOURCE_MAP_RE.exec(code);
	if (typeof match?.index !== "number") return null;
	const dataUrl = match[1];
	const commaIndex = dataUrl.indexOf(",");
	if (commaIndex < 0) return null;
	try {
		const metadata = dataUrl.slice(0, commaIndex);
		const payload = dataUrl.slice(commaIndex + 1);
		const json = metadata.includes(";base64") ? Buffer.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
		const map = normalizeEncodedSourceMapLike(JSON.parse(json));
		return map ? {
			code: code.slice(0, match.index),
			map,
			start: match.index
		} : null;
	} catch {
		return null;
	}
}
function appendInlineSourceMap(code, map) {
	return `${code}${code.endsWith("\n") ? "" : "\n"}//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(map)).toString("base64")}`;
}
/**
* 返回不含 inline sourcemap 数据 URI 的实际脚本,供 AST 转换使用。
*/
function resolveOutputChunkTransformCode(chunk) {
	return resolveInlineSourceMap(chunk.code)?.code ?? chunk.code;
}
/**
* 应用 MagicString 改写,并把本轮映射与 chunk 既有映射组合。
*/
function applyMagicStringChunkRewrite(chunk, magicString, options) {
	const previousCode = chunk.code;
	const inlineSourceMap = resolveInlineSourceMap(previousCode);
	if (inlineSourceMap) magicString.remove(inlineSourceMap.start, previousCode.length);
	const nextCode = magicString.toString();
	if (nextCode === (inlineSourceMap?.code ?? previousCode)) return false;
	const previousMap = normalizeEncodedSourceMapLike(chunk.map) ?? inlineSourceMap?.map;
	if (previousMap) {
		const composedMap = composeSourceMaps(magicString.generateMap({
			hires: options?.hires ?? "boundary",
			includeContent: true,
			source: chunk.fileName
		}), previousMap);
		chunk.map = composedMap;
		chunk.code = inlineSourceMap && composedMap ? appendInlineSourceMap(nextCode, composedMap) : nextCode;
	} else chunk.code = nextCode;
	return true;
}
/**
* 在 chunk 当前代码上执行一次可追踪编辑。
*/
function editOutputChunkCode(chunk, edit, options) {
	const code = chunk.code;
	const magicString = new MagicString(code);
	edit(magicString, code);
	return applyMagicStringChunkRewrite(chunk, magicString, options);
}
/**
* 在 chunk 前方插入无源代码,同时保留原代码映射。
*/
function prependOutputChunkCode(chunk, code) {
	if (!code) return false;
	return editOutputChunkCode(chunk, (magicString) => magicString.prepend(code));
}
/**
* 在 chunk 后方插入无源代码,同时保留原代码映射。
*/
function appendOutputChunkCode(chunk, code) {
	if (!code) return false;
	return editOutputChunkCode(chunk, (magicString) => magicString.append(code));
}
/**
* 按原始代码坐标批量替换互不重叠的区间。
*/
function replaceOutputChunkCodeRanges(chunk, replacements) {
	if (replacements.length === 0) return false;
	const sorted = [...replacements].sort((left, right) => left.start - right.start);
	let previousEnd = -1;
	for (const replacement of sorted) {
		if (replacement.start < 0 || replacement.end < replacement.start || replacement.end > chunk.code.length || replacement.start < previousEnd) throw new RangeError(`Invalid or overlapping output chunk replacement: ${replacement.start}-${replacement.end}`);
		previousEnd = replacement.end;
	}
	return editOutputChunkCode(chunk, (magicString) => {
		for (const replacement of sorted) magicString.overwrite(replacement.start, replacement.end, replacement.content);
	});
}
/**
* 使用正则匹配的原始坐标改写 chunk,避免整段字符串替换破坏映射。
*/
function replaceOutputChunkCode(chunk, pattern, replace) {
	const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
	const matcher = new RegExp(pattern.source, flags);
	const replacements = [];
	for (const match of chunk.code.matchAll(matcher)) {
		if (typeof match.index !== "number") continue;
		const content = replace(match);
		if (content == null || content === match[0]) continue;
		replacements.push({
			content,
			end: match.index + match[0].length,
			start: match.index
		});
	}
	return replaceOutputChunkCodeRanges(chunk, replacements);
}
/**
* 应用自带映射的完整代码转换,并组合 chunk 既有映射。
*/
function applyOutputChunkTransform(chunk, code, map) {
	const previousInlineSourceMap = resolveInlineSourceMap(chunk.code);
	const transformedInlineSourceMap = resolveInlineSourceMap(code);
	const previousCode = previousInlineSourceMap?.code ?? chunk.code;
	const transformedCode = transformedInlineSourceMap?.code ?? code;
	if (transformedCode === previousCode) return false;
	const previousMap = normalizeEncodedSourceMapLike(chunk.map) ?? previousInlineSourceMap?.map;
	const transformedMap = normalizeEncodedSourceMapLike(map);
	if (previousMap && !transformedMap) throw new Error(`Output chunk transform for ${chunk.fileName} must provide a source map`);
	if (previousMap && transformedMap) {
		const composedMap = composeSourceMaps(transformedMap, previousMap);
		chunk.map = composedMap;
		chunk.code = previousInlineSourceMap && composedMap ? appendInlineSourceMap(transformedCode, composedMap) : transformedCode;
	} else chunk.code = transformedCode;
	return true;
}
/**
* 将 generateBundle 阶段组合后的 chunk map 提交到 Rolldown 管理的 map asset。
*/
function syncOutputChunkSourceMapAssets(bundle) {
	let synced = 0;
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const map = normalizeEncodedSourceMapLike(output.map);
		if (!map) continue;
		const mapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];
		if (!mapAsset || mapAsset.type !== "asset") continue;
		mapAsset.source = JSON.stringify(map);
		synced += 1;
	}
	return synced;
}
//#endregion
//#region src/runtime/chunkStrategy/utils.ts
function createRelativeImport(fromFile, toFile) {
	const relative = posix.relative(posix.dirname(fromFile), toFile);
	if (!relative || relative.startsWith(".")) return relative || "./";
	return `./${relative}`;
}
//#endregion
//#region src/runtime/chunkStrategy/bundle.ts
function escapeRegExp$2(value) {
	return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function replaceChunkCodeAll(chunk, searchValue, replaceValue) {
	if (!searchValue) return false;
	const replaceExact = () => replaceOutputChunkCode(chunk, new RegExp(escapeRegExp$2(searchValue), "g"), () => replaceValue);
	if (chunk.code.includes(searchValue)) return replaceExact();
	if (searchValue.startsWith("./") && replaceValue.startsWith("./")) {
		const trimmedSearch = searchValue.slice(2);
		const trimmedReplace = replaceValue.slice(2);
		if (trimmedSearch && chunk.code.includes(trimmedSearch)) return replaceOutputChunkCode(chunk, new RegExp(escapeRegExp$2(trimmedSearch), "g"), () => trimmedReplace);
	}
	return false;
}
function addDirectImporter(directImporters, imported, importer) {
	if (typeof imported !== "string" || !imported || imported === importer) return;
	let importers = directImporters.get(imported);
	if (!importers) {
		importers = /* @__PURE__ */ new Set();
		directImporters.set(imported, importers);
	}
	importers.add(importer);
}
function removeDirectImporter(directImporters, imported, importer) {
	const importers = directImporters.get(imported);
	if (!importers) return;
	importers.delete(importer);
	if (!importers.size) directImporters.delete(imported);
}
function addCollectionImporters(directImporters, collection, importer) {
	if (collection instanceof Set) {
		for (const imported of collection) addDirectImporter(directImporters, imported, importer);
		return;
	}
	if (Array.isArray(collection)) {
		for (const imported of collection) addDirectImporter(directImporters, imported, importer);
		return;
	}
	if (collection instanceof Map) for (const imported of collection.keys()) addDirectImporter(directImporters, imported, importer);
}
function isIdentifierChar(char) {
	if (!char) return false;
	const code = char.charCodeAt(0);
	return code === 36 || code === 95 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
}
function readQuotedSpecifier(code, fromIndex) {
	let index = fromIndex;
	while (index < code.length && /\s/.test(code[index])) index += 1;
	const quote = code[index];
	if (quote !== "'" && quote !== "\"" && quote !== "`") return;
	let endIndex = index + 1;
	while (endIndex < code.length) {
		if (code[endIndex] === quote && code[endIndex - 1] !== "\\") return code.slice(index + 1, endIndex);
		endIndex += 1;
	}
}
function collectBareImportTargets(code, targets) {
	let searchIndex = 0;
	while (searchIndex < code.length) {
		const importIndex = code.indexOf("import", searchIndex);
		if (importIndex === -1) return;
		if (isIdentifierChar(code[importIndex - 1])) {
			searchIndex = importIndex + 6;
			continue;
		}
		const specifier = readQuotedSpecifier(code, importIndex + 6);
		if (specifier) targets.add(specifier);
		searchIndex = importIndex + 6;
	}
}
function collectImportFromTargets(code, targets) {
	let searchIndex = 0;
	while (searchIndex < code.length) {
		const importIndex = code.indexOf("import", searchIndex);
		if (importIndex === -1) return;
		if (isIdentifierChar(code[importIndex - 1])) {
			searchIndex = importIndex + 6;
			continue;
		}
		const fromIndex = code.indexOf("from", importIndex + 6);
		if (fromIndex !== -1) {
			const specifier = readQuotedSpecifier(code, fromIndex + 4);
			if (specifier) targets.add(specifier);
		}
		searchIndex = importIndex + 6;
	}
}
function collectExportFromTargets(code, targets) {
	let searchIndex = 0;
	while (searchIndex < code.length) {
		const exportIndex = code.indexOf("export", searchIndex);
		if (exportIndex === -1) return;
		if (isIdentifierChar(code[exportIndex - 1])) {
			searchIndex = exportIndex + 6;
			continue;
		}
		const fromIndex = code.indexOf("from", exportIndex + 6);
		if (fromIndex !== -1) {
			const specifier = readQuotedSpecifier(code, fromIndex + 4);
			if (specifier) targets.add(specifier);
		}
		searchIndex = exportIndex + 6;
	}
}
function collectRequireTargets(code, targets) {
	let searchIndex = 0;
	while (searchIndex < code.length) {
		const requireIndex = code.indexOf("require", searchIndex);
		if (requireIndex === -1) return;
		if (isIdentifierChar(code[requireIndex - 1])) {
			searchIndex = requireIndex + 7;
			continue;
		}
		const openParenIndex = code.indexOf("(", requireIndex + 7);
		if (openParenIndex !== -1) {
			const specifier = readQuotedSpecifier(code, openParenIndex + 1);
			if (specifier) targets.add(specifier);
		}
		searchIndex = requireIndex + 7;
	}
}
function collectDynamicImportTargets(code, targets) {
	let searchIndex = 0;
	while (searchIndex < code.length) {
		const importIndex = code.indexOf("import(", searchIndex);
		if (importIndex === -1) return;
		if (isIdentifierChar(code[importIndex - 1])) {
			searchIndex = importIndex + 7;
			continue;
		}
		const specifier = readQuotedSpecifier(code, importIndex + 7);
		if (specifier) targets.add(specifier);
		searchIndex = importIndex + 7;
	}
}
function collectCodeImportTargets(code, targets) {
	collectBareImportTargets(code, targets);
	collectImportFromTargets(code, targets);
	collectExportFromTargets(code, targets);
	collectRequireTargets(code, targets);
	collectDynamicImportTargets(code, targets);
}
function addCodeImporters(codeImporters, code, importer) {
	if (!code) return;
	const targets = /* @__PURE__ */ new Set();
	collectCodeImportTargets(code, targets);
	for (const target of targets) {
		if (!target || !target.startsWith(".")) continue;
		addDirectImporter(codeImporters, posix.normalize(posix.join(posix.dirname(importer), target)), importer);
	}
}
function removeImporterFromCodeImporters(codeImporters, importer) {
	for (const [target, importers] of codeImporters) {
		importers.delete(importer);
		if (!importers.size) codeImporters.delete(target);
	}
}
function replaceInArray(list, searchValues, replaceValue, shouldInsert) {
	const values = Array.isArray(list) ? [...list] : [];
	let replaced = false;
	for (let index = 0; index < values.length; index++) {
		const current = values[index];
		if (searchValues.includes(current)) {
			values[index] = replaceValue;
			replaced = true;
		}
	}
	if ((replaced || shouldInsert) && replaceValue && !values.includes(replaceValue)) values.push(replaceValue);
	return values;
}
function updateViteMetadata(importerChunk, originalFileNames, newChunkFile, shouldInsert) {
	const metadata = importerChunk.viteMetadata;
	if (!metadata || typeof metadata !== "object") return;
	for (const key of [
		"importedChunks",
		"importedScripts",
		"importedScriptsByUrl"
	]) {
		const collection = metadata[key];
		if (collection instanceof Set) {
			let hadOriginal = false;
			for (const originalFileName of originalFileNames) hadOriginal = collection.delete(originalFileName) || hadOriginal;
			if (hadOriginal || shouldInsert) collection.add(newChunkFile);
		} else if (Array.isArray(collection)) metadata[key] = replaceInArray(collection, originalFileNames, newChunkFile, shouldInsert);
		else if (collection instanceof Map) {
			let originalValue;
			let hadOriginal = false;
			for (const originalFileName of originalFileNames) {
				if (!collection.has(originalFileName)) continue;
				if (!hadOriginal) originalValue = collection.get(originalFileName);
				hadOriginal = true;
				collection.delete(originalFileName);
			}
			if (hadOriginal) collection.set(newChunkFile, originalValue);
		}
	}
}
function createChunkImporterIndex(bundle, entries = Object.entries(bundle)) {
	const directImporters = /* @__PURE__ */ new Map();
	const codeImporters = /* @__PURE__ */ new Map();
	const chunks = /* @__PURE__ */ new Map();
	const addImporter = (target, importer) => {
		if (!target || target === importer) return;
		let importers = directImporters.get(target);
		if (!importers) {
			importers = /* @__PURE__ */ new Set();
			directImporters.set(target, importers);
		}
		importers.add(importer);
	};
	for (const [fileName, output] of entries) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		chunks.set(fileName, chunk);
		for (const imported of chunk.imports ?? []) addImporter(imported, fileName);
		for (const imported of chunk.dynamicImports ?? []) addImporter(imported, fileName);
		addCodeImporters(codeImporters, chunk.code, fileName);
		const metadata = chunk.viteMetadata;
		if (metadata) {
			addCollectionImporters(directImporters, metadata.importedChunks, fileName);
			addCollectionImporters(directImporters, metadata.importedScripts ?? metadata.importedScriptsByUrl, fileName);
		}
	}
	return {
		directImporters,
		codeImporters,
		chunks
	};
}
function removeChunkFromImporterIndex(index, fileName) {
	index.chunks.delete(fileName);
	index.directImporters.delete(fileName);
	removeImporterFromCodeImporters(index.codeImporters, fileName);
	for (const [target, importers] of index.directImporters) {
		importers.delete(fileName);
		if (!importers.size) index.directImporters.delete(target);
	}
}
function updateChunkImporterIndex(index, importerFile, originalFileNames, newChunkFile, shouldInsert) {
	if (!newChunkFile || originalFileNames.includes(newChunkFile)) return;
	let hadOriginal = false;
	for (const originalFileName of originalFileNames) {
		hadOriginal = index.directImporters.get(originalFileName)?.has(importerFile) === true || hadOriginal;
		removeDirectImporter(index.directImporters, originalFileName, importerFile);
	}
	if (hadOriginal || shouldInsert) addDirectImporter(index.directImporters, newChunkFile, importerFile);
}
function findChunkImporters(bundle, target, index = createChunkImporterIndex(bundle)) {
	const importers = new Set(index.directImporters.get(target));
	for (const importer of index.codeImporters.get(target) ?? []) importers.add(importer);
	return Array.from(importers);
}
function ensureUniqueFileName(bundle, fileName) {
	if (!bundle[fileName]) return fileName;
	const { dir, name, ext } = posix.parse(fileName);
	let index = 1;
	let candidate = fileName;
	while (bundle[candidate]) {
		const nextName = `${name}.${index}`;
		candidate = dir ? posix.join(dir, `${nextName}${ext}`) : `${nextName}${ext}`;
		index += 1;
	}
	return candidate;
}
function updateImporters(bundle, importerToChunk, originalFileName, index) {
	const originalFileNames = Array.isArray(originalFileName) ? originalFileName : [originalFileName];
	for (const [importerFile, newChunkFile] of importerToChunk.entries()) {
		const importer = bundle[importerFile];
		if (!importer || importer.type !== "chunk") continue;
		const importerChunk = importer;
		const newImportPath = createRelativeImport(importerFile, newChunkFile);
		let codeUpdated = false;
		for (const originalFileName of originalFileNames) {
			const originalImportPath = createRelativeImport(importerFile, originalFileName);
			if (originalImportPath === newImportPath) continue;
			codeUpdated = replaceChunkCodeAll(importerChunk, originalImportPath, newImportPath) || codeUpdated;
		}
		importerChunk.imports = replaceInArray(importerChunk.imports, originalFileNames, newChunkFile, codeUpdated);
		importerChunk.dynamicImports = replaceInArray(importerChunk.dynamicImports, originalFileNames, newChunkFile, codeUpdated);
		const implicitlyLoadedBefore = importerChunk.implicitlyLoadedBefore;
		if (Array.isArray(implicitlyLoadedBefore)) importerChunk.implicitlyLoadedBefore = replaceInArray(implicitlyLoadedBefore, originalFileNames, newChunkFile, codeUpdated);
		const referencedFiles = importerChunk.referencedFiles;
		if (Array.isArray(referencedFiles)) importerChunk.referencedFiles = replaceInArray(referencedFiles, originalFileNames, newChunkFile, codeUpdated);
		updateViteMetadata(importerChunk, originalFileNames, newChunkFile, codeUpdated);
		if (index) {
			updateChunkImporterIndex(index, importerFile, originalFileNames, newChunkFile, codeUpdated);
			if (codeUpdated) {
				removeImporterFromCodeImporters(index.codeImporters, importerFile);
				addCodeImporters(index.codeImporters, importerChunk.code, importerFile);
			}
		}
	}
}
//#endregion
//#region src/runtime/chunkStrategy/collector.ts
function resolveChunkGraphSourceId(id) {
	return parseLogicalEntryId(id)?.sourceId ?? parseSidecarModuleId(id)?.ownerId ?? parseSidecarSourceRequest(id)?.ownerId ?? id;
}
function resolveSubPackagePrefix(fileName, subPackageRoots) {
	for (const root of subPackageRoots) {
		if (!root) continue;
		if (fileName === root || fileName.startsWith(`${root}/`)) return root;
	}
	return "";
}
function collectEffectivePrefixes(importer, options, state) {
	const cached = state.cache.get(importer);
	if (cached) return {
		prefixes: [...cached.prefixes],
		hasRealMain: cached.hasRealMain,
		ignored: [...cached.ignored]
	};
	if (state.stack.has(importer)) return {
		prefixes: [""],
		hasRealMain: true,
		ignored: []
	};
	state.stack.add(importer);
	const { ctx, relativeAbsoluteSrcRoot, subPackageRoots, forceDuplicateTester } = options;
	const sourceImporter = resolveChunkGraphSourceId(importer);
	const relativeId = relativeAbsoluteSrcRoot(sourceImporter);
	const subPackagePrefix = resolveSubPackagePrefix(relativeId, subPackageRoots);
	if (subPackagePrefix) {
		const result = {
			prefixes: [subPackagePrefix],
			hasRealMain: false,
			ignored: []
		};
		state.cache.set(importer, result);
		state.stack.delete(importer);
		return {
			prefixes: [...result.prefixes],
			hasRealMain: result.hasRealMain,
			ignored: []
		};
	}
	const importerParents = ctx.getModuleInfo(importer)?.importers ?? [];
	const forcedDuplicate = forceDuplicateTester?.(relativeId, sourceImporter) ?? false;
	if (!importerParents.length) {
		const result = forcedDuplicate ? {
			prefixes: [],
			hasRealMain: false,
			ignored: [relativeId]
		} : {
			prefixes: [""],
			hasRealMain: true,
			ignored: []
		};
		state.cache.set(importer, result);
		state.stack.delete(importer);
		return {
			prefixes: [...result.prefixes],
			hasRealMain: result.hasRealMain,
			ignored: [...result.ignored]
		};
	}
	const aggregatedPrefixes = /* @__PURE__ */ new Set();
	let hasRealMain = false;
	const aggregatedIgnored = [];
	for (const parent of importerParents) {
		const collectorResult = collectEffectivePrefixes(parent, options, state);
		for (const prefix of collectorResult.prefixes) aggregatedPrefixes.add(prefix);
		if (collectorResult.hasRealMain) hasRealMain = true;
		if (collectorResult.ignored.length) aggregatedIgnored.push(...collectorResult.ignored);
	}
	if (!aggregatedPrefixes.size) {
		aggregatedPrefixes.add("");
		hasRealMain = true;
	}
	const ignored = !aggregatedPrefixes.has("") && importerParents.length > 0 || forcedDuplicate && !aggregatedPrefixes.has("") ? [relativeId] : [];
	const result = {
		prefixes: Array.from(aggregatedPrefixes),
		hasRealMain,
		ignored: Array.from(/* @__PURE__ */ new Set([...aggregatedIgnored, ...ignored]))
	};
	state.cache.set(importer, result);
	state.stack.delete(importer);
	return {
		prefixes: [...result.prefixes],
		hasRealMain: result.hasRealMain,
		ignored: [...result.ignored]
	};
}
function summarizeImportPrefixes(options) {
	const { ctx, importers, relativeAbsoluteSrcRoot, subPackageRoots, forceDuplicateTester } = options;
	const summary = {};
	const ignoredImporters = /* @__PURE__ */ new Set();
	const state = {
		cache: /* @__PURE__ */ new Map(),
		stack: /* @__PURE__ */ new Set()
	};
	for (const importer of importers) {
		const { prefixes, ignored } = collectEffectivePrefixes(importer, {
			ctx,
			relativeAbsoluteSrcRoot,
			subPackageRoots,
			forceDuplicateTester
		}, state);
		for (const prefix of prefixes) summary[prefix] = (summary[prefix] || 0) + 1;
		for (const entry of ignored) ignoredImporters.add(entry);
	}
	return {
		summary,
		ignoredMainImporters: Array.from(ignoredImporters)
	};
}
function assertModuleScopedToRoot(options) {
	const { moduleInfo, moduleRoot, relativeAbsoluteSrcRoot, subPackageRoots, moduleId } = options;
	if (!moduleRoot || !moduleInfo?.importers?.length) return;
	for (const importer of moduleInfo.importers) {
		const sourceImporter = resolveChunkGraphSourceId(importer);
		if (resolveSubPackagePrefix(relativeAbsoluteSrcRoot(sourceImporter), subPackageRoots) !== moduleRoot) {
			const moduleLabel = relativeAbsoluteSrcRoot(moduleId);
			const importerLabel = relativeAbsoluteSrcRoot(sourceImporter);
			throw new Error(`[分包] 模块 "${moduleLabel}" 位于分包 "${moduleRoot}",但被 "${importerLabel}" 引用,请将该模块移动到主包或公共目录以进行跨分包共享。`);
		}
	}
}
//#endregion
//#region src/runtime/chunkStrategy/sourcemap.ts
function isSourceLike(source) {
	return typeof source === "string" || source instanceof Uint8Array || Buffer.isBuffer(source);
}
function cloneSourceLike(source) {
	if (typeof source === "string") return source;
	return Buffer.from(source);
}
function collectSourceMapKeys(fileName, chunk) {
	const keys = /* @__PURE__ */ new Set();
	if (fileName) keys.add(`${fileName}.map`);
	if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) keys.add(chunk.sourcemapFileName);
	return keys;
}
function findSourceMapAsset(bundle, candidateKeys) {
	for (const key of candidateKeys) {
		if (!key) continue;
		const entry = bundle[key];
		if (entry?.type === "asset") return {
			asset: entry,
			key
		};
	}
}
function resolveSourceMapSource(originalMap, assetSource) {
	if (originalMap) {
		if (typeof originalMap === "string") return originalMap;
		if (originalMap instanceof Uint8Array || Buffer.isBuffer(originalMap)) return Buffer.from(originalMap);
		return JSON.stringify(originalMap);
	}
	if (isSourceLike(assetSource)) return cloneSourceLike(assetSource);
}
function resolveEncodedSourceMap(originalMap, assetSource) {
	const chunkMap = normalizeEncodedSourceMapLike(originalMap);
	if (chunkMap) return chunkMap;
	if (!isSourceLike(assetSource)) return null;
	try {
		const source = typeof assetSource === "string" ? assetSource : Buffer.from(assetSource).toString("utf8");
		return normalizeEncodedSourceMapLike(JSON.parse(source));
	} catch {
		return null;
	}
}
function emitSourceMapAsset(ctx, targetFileName, sourceMapAssetInfo, fallbackSource) {
	if (!targetFileName) return;
	if (sourceMapAssetInfo?.asset && isSourceLike(sourceMapAssetInfo.asset.source)) {
		const [name] = sourceMapAssetInfo.asset.names ?? [];
		ctx.emitFile({
			type: "asset",
			fileName: targetFileName,
			source: cloneSourceLike(sourceMapAssetInfo.asset.source),
			...name ? { name } : {}
		});
		return;
	}
	if (fallbackSource) ctx.emitFile({
		type: "asset",
		fileName: targetFileName,
		source: cloneSourceLike(fallbackSource)
	});
}
//#endregion
//#region src/runtime/chunkStrategy/apply/runtime.ts
const ROLLDOWN_RUNTIME_FILE_NAME$2 = "rolldown-runtime.js";
function applyRuntimeChunkLocalization(bundle, options) {
	if (!this) throw new Error("applyRuntimeChunkLocalization 需要 PluginContext。");
	const runtimeFileName = options.runtimeFileName ?? ROLLDOWN_RUNTIME_FILE_NAME$2;
	const runtimeRecord = resolveRuntimeBundleRecord(bundle, runtimeFileName);
	if (!runtimeRecord) return;
	const { output: runtimeOutput, lookupKeys: runtimeLookupKeys } = runtimeRecord;
	const runtimeSource = resolveRuntimeSource(runtimeOutput);
	if (!runtimeSource) return;
	const subPackageRoots = Array.from(options.subPackageRoots).filter(Boolean);
	if (!subPackageRoots.length) return;
	const runtimeLookupSet = new Set(runtimeLookupKeys);
	const rootToImporters = /* @__PURE__ */ new Map();
	for (const [fileName, output] of Object.entries(bundle)) {
		if (output?.type !== "chunk") continue;
		const root = resolveSubPackagePrefix(fileName, subPackageRoots);
		if (!root) continue;
		if (!chunkReferencesRuntime(output, runtimeFileName, runtimeLookupSet)) continue;
		const existing = rootToImporters.get(root);
		if (existing) existing.push(fileName);
		else rootToImporters.set(root, [fileName]);
	}
	const forceRoots = Array.from(options.forceRoots ?? []).filter(Boolean);
	for (const root of forceRoots) {
		if (!subPackageRoots.includes(root)) continue;
		if (!rootToImporters.has(root)) rootToImporters.set(root, []);
	}
	if (!rootToImporters.size) return;
	const importerToRuntime = /* @__PURE__ */ new Map();
	const duplicates = [];
	for (const [root, importerFiles] of rootToImporters.entries()) {
		const duplicateBaseName = posix.basename(runtimeFileName);
		const uniqueFileName = ensureUniqueFileName(bundle, posix.join(root, duplicateBaseName));
		this.emitFile({
			type: "asset",
			fileName: uniqueFileName,
			source: cloneSourceLike(runtimeSource)
		});
		for (const importerFile of importerFiles) importerToRuntime.set(importerFile, uniqueFileName);
		duplicates.push({
			fileName: uniqueFileName,
			importers: [...importerFiles]
		});
	}
	updateImporters(bundle, importerToRuntime, runtimeLookupKeys);
	options.onDuplicate?.({
		runtimeFileName,
		duplicates
	});
}
function chunkReferencesRuntime(chunk, runtimeFileName, runtimeLookupSet) {
	const hasRuntimeReference = (specifier) => runtimeLookupSet.has(specifier) || posix.basename(specifier) === runtimeFileName;
	if (chunk.imports.some(hasRuntimeReference) || chunk.dynamicImports.some(hasRuntimeReference)) return true;
	const metadata = chunk.viteMetadata;
	if (metadata) {
		const importedChunks = metadata.importedChunks;
		if (hasInCollection(importedChunks, runtimeFileName)) return true;
		for (const lookupKey of runtimeLookupSet) if (hasInCollection(importedChunks, lookupKey)) return true;
		const importedScripts = metadata.importedScripts ?? metadata.importedScriptsByUrl;
		if (hasInCollection(importedScripts, runtimeFileName)) return true;
		for (const lookupKey of runtimeLookupSet) if (hasInCollection(importedScripts, lookupKey)) return true;
	}
	return (chunk.code ?? "").includes(runtimeFileName);
}
function resolveRuntimeBundleRecord(bundle, runtimeFileName) {
	const direct = bundle[runtimeFileName];
	if (isRuntimeBundleOutput(direct)) return {
		output: direct,
		lookupKeys: dedupeLookupKeys([runtimeFileName, resolveBundleOutputFileName(direct, runtimeFileName)])
	};
	for (const [key, output] of Object.entries(bundle)) {
		if (!isRuntimeBundleOutput(output)) continue;
		const fileName = resolveBundleOutputFileName(output, key);
		if (fileName !== runtimeFileName && posix.basename(fileName) !== runtimeFileName) continue;
		return {
			output,
			lookupKeys: dedupeLookupKeys([
				runtimeFileName,
				key,
				fileName
			])
		};
	}
}
function resolveRuntimeSource(output) {
	if (output.type === "chunk") return output.code || void 0;
	if (typeof output.source === "string" || output.source instanceof Uint8Array || Buffer.isBuffer(output.source)) return output.source;
	if (output.source == null) return;
	return String(output.source);
}
function hasInCollection(collection, value) {
	if (!collection || !value) return false;
	if (collection instanceof Set) return collection.has(value);
	if (Array.isArray(collection)) return collection.includes(value);
	if (collection instanceof Map) return collection.has(value);
	return false;
}
function resolveBundleOutputFileName(output, fallback) {
	if (typeof output.fileName === "string" && output.fileName) return output.fileName;
	return fallback;
}
function dedupeLookupKeys(values) {
	return Array.from(new Set(values.filter(Boolean)));
}
function isRuntimeBundleOutput(output) {
	return output?.type === "chunk" || output?.type === "asset";
}
//#endregion
//#region src/runtime/chunkStrategy/constants.ts
const SHARED_CHUNK_VIRTUAL_PREFIX = "weapp_shared_virtual";
const SUB_PACKAGE_SHARED_DIR = "weapp-shared";
//#endregion
//#region src/runtime/chunkStrategy/apply/rewrite.ts
const ROLLDOWN_RUNTIME_FILE_NAME$1 = "rolldown-runtime.js";
const REGEXP_ESCAPE_PATTERN = /[.*+?^${}()|[\]\\]/g;
function createChunkSourceFileNameCandidates(fileName) {
	const candidates = [fileName];
	const normalized = resolveChunkSourceFileNameForRewrite(fileName);
	if (normalized !== fileName) candidates.push(normalized);
	return candidates;
}
function reserveUniqueFileName(reservedFileNames, fileName) {
	if (!reservedFileNames.has(fileName)) {
		reservedFileNames.add(fileName);
		return fileName;
	}
	const { dir, name, ext } = posix.parse(fileName);
	let index = 1;
	let candidate = fileName;
	while (reservedFileNames.has(candidate)) {
		const nextName = `${name}.${index}`;
		candidate = dir ? posix.join(dir, `${nextName}${ext}`) : `${nextName}${ext}`;
		index += 1;
	}
	reservedFileNames.add(candidate);
	return candidate;
}
function createChunkImportSpecifiersRewrite(sourceCode, options) {
	const { sourceFileName, sourceFileNames, targetFileName, imports, dynamicImports, runtimeFileName, resolveImportTarget } = options;
	const sourceFileNameCandidates = (sourceFileNames ?? [sourceFileName ?? ""]).filter(Boolean);
	const specifiers = new Set([...imports, ...dynamicImports].filter(Boolean));
	const magicString = new MagicString(sourceCode);
	const rewrittenRanges = /* @__PURE__ */ new Set();
	for (const specifier of specifiers) {
		const targetImportPath = createRelativeImportPath(targetFileName, posix.basename(specifier) === ROLLDOWN_RUNTIME_FILE_NAME$1 ? runtimeFileName : resolveImportTarget?.(specifier) ?? specifier);
		if (!targetImportPath) continue;
		for (const sourceCandidate of sourceFileNameCandidates) {
			const sourceImportPath = createRelativeImportPath(sourceCandidate, specifier);
			if (!sourceImportPath || sourceImportPath === targetImportPath) continue;
			replaceQuotedImportLiteralValue(magicString, sourceCode, sourceImportPath, targetImportPath, rewrittenRanges);
		}
	}
	return magicString;
}
function resolveChunkSourceFileNameForRewrite(fileName) {
	if (!fileName.startsWith(`weapp_shared_virtual/`)) return fileName;
	return fileName.slice(21);
}
function replaceQuotedImportLiteralValue(magicString, sourceCode, sourcePath, targetPath, rewrittenRanges) {
	const escapedSourcePath = escapeRegExpForPattern(sourcePath);
	const pattern = new RegExp(`(['"\`])${escapedSourcePath}\\1`, "g");
	for (const match of sourceCode.matchAll(pattern)) {
		if (typeof match.index !== "number") continue;
		const end = match.index + match[0].length;
		const rangeKey = `${match.index}:${end}`;
		if (rewrittenRanges.has(rangeKey)) continue;
		const quote = match[1];
		magicString.overwrite(match.index, end, `${quote}${targetPath}${quote}`);
		rewrittenRanges.add(rangeKey);
	}
}
function escapeRegExpForPattern(value) {
	return value.replace(REGEXP_ESCAPE_PATTERN, "\\$&");
}
function createRelativeImportPath(fromFileName, toFileName) {
	const relativePath = posix.relative(posix.dirname(fromFileName), toFileName);
	if (!relativePath || relativePath.startsWith(".")) return relativePath || "./";
	return `./${relativePath}`;
}
//#endregion
//#region src/runtime/chunkStrategy/apply/shared/runtime.ts
const ROLLDOWN_RUNTIME_FILE_NAME = "rolldown-runtime.js";
const SLASHES_PATTERN = /[\\/]+/g;
function createCrossSubPackageDuplicateBaseName(sourceRoot, fileName) {
	return `${sourceRoot.replace(SLASHES_PATTERN, "_")}.${posix.basename(fileName)}`;
}
function ensureLocalizedDuplicate(args) {
	const { runtimeContext, pendingLocalizedDuplicates, root, sourceFileName } = args;
	const sourceRoot = resolveSubPackagePrefix(sourceFileName, runtimeContext.subPackageRoots);
	if (!sourceRoot || sourceRoot === root) return sourceFileName;
	const key = `${root}::${sourceFileName}`;
	const existing = runtimeContext.localizedDuplicateFileMap.get(key);
	if (existing) return existing;
	const sourceOutput = runtimeContext.bundle[sourceFileName];
	if (sourceOutput?.type !== "chunk") return sourceFileName;
	const duplicateBaseName = createCrossSubPackageDuplicateBaseName(sourceRoot, sourceFileName);
	const targetFileName = reserveUniqueFileName(runtimeContext.reservedFileNames, posix.join(root, SUB_PACKAGE_SHARED_DIR, duplicateBaseName));
	runtimeContext.localizedDuplicateFileMap.set(key, targetFileName);
	pendingLocalizedDuplicates.push({
		root,
		sourceFileName,
		targetFileName,
		chunk: sourceOutput
	});
	return targetFileName;
}
function rewriteDuplicatedChunkSource(args) {
	const runtimeFileName = posix.join(args.root, ROLLDOWN_RUNTIME_FILE_NAME);
	const sourceMapKeys = collectSourceMapKeys(args.sourceFileName, args.chunk);
	const sourceMapAssetInfo = findSourceMapAsset(args.runtimeContext.bundle, sourceMapKeys);
	const rewrittenChunk = {
		...args.chunk,
		map: resolveEncodedSourceMap(args.chunk.map, sourceMapAssetInfo?.asset.source)
	};
	applyMagicStringChunkRewrite(rewrittenChunk, createChunkImportSpecifiersRewrite(rewrittenChunk.code ?? "", {
		sourceFileNames: createChunkSourceFileNameCandidates(args.sourceFileName),
		targetFileName: args.targetFileName,
		imports: args.chunk.imports,
		dynamicImports: args.chunk.dynamicImports,
		runtimeFileName,
		resolveImportTarget: (specifier) => {
			return ensureLocalizedDuplicate({
				runtimeContext: args.runtimeContext,
				pendingLocalizedDuplicates: args.pendingLocalizedDuplicates,
				root: args.root,
				sourceFileName: specifier
			});
		}
	}));
	for (const specifier of [...args.chunk.imports, ...args.chunk.dynamicImports]) {
		const localizedSpecifier = ensureLocalizedDuplicate({
			runtimeContext: args.runtimeContext,
			pendingLocalizedDuplicates: args.pendingLocalizedDuplicates,
			root: args.root,
			sourceFileName: specifier
		});
		if (!localizedSpecifier || localizedSpecifier === specifier) continue;
		applyMagicStringChunkRewrite(rewrittenChunk, createChunkImportSpecifiersRewrite(rewrittenChunk.code, {
			sourceFileName: args.targetFileName,
			targetFileName: args.targetFileName,
			imports: [specifier],
			dynamicImports: [],
			runtimeFileName,
			resolveImportTarget: () => localizedSpecifier
		}));
	}
	return rewrittenChunk;
}
function emitDuplicatedChunkAsset(args) {
	if (args.emittedLocalizedDuplicateFiles.has(args.targetFileName)) return;
	const duplicatedChunk = rewriteDuplicatedChunkSource({
		runtimeContext: args.runtimeContext,
		pendingLocalizedDuplicates: args.pendingLocalizedDuplicates,
		root: args.root,
		sourceFileName: args.sourceFileName,
		targetFileName: args.targetFileName,
		chunk: args.chunk
	});
	args.runtimeContext.pluginContext.emitFile({
		type: "asset",
		fileName: args.targetFileName,
		source: duplicatedChunk.code
	});
	const sourceMapKeys = collectSourceMapKeys(args.sourceFileName, args.chunk);
	const sourceMapAssetInfo = findSourceMapAsset(args.runtimeContext.bundle, sourceMapKeys);
	const unchangedSourceMap = duplicatedChunk.code === args.chunk.code ? resolveSourceMapSource(args.chunk.map, sourceMapAssetInfo?.asset.source) : void 0;
	if (duplicatedChunk.map) {
		const sourceMapFileName = reserveUniqueFileName(args.runtimeContext.reservedFileNames, `${args.targetFileName}.map`);
		args.runtimeContext.pluginContext.emitFile({
			type: "asset",
			fileName: sourceMapFileName,
			source: JSON.stringify(duplicatedChunk.map)
		});
	} else if (unchangedSourceMap) {
		const sourceMapFileName = reserveUniqueFileName(args.runtimeContext.reservedFileNames, `${args.targetFileName}.map`);
		args.runtimeContext.pluginContext.emitFile({
			type: "asset",
			fileName: sourceMapFileName,
			source: cloneSourceLike(unchangedSourceMap)
		});
	}
	args.emittedLocalizedDuplicateFiles.add(args.targetFileName);
}
function buildDuplicateDiagnostics(args) {
	const chunkBytes = typeof args.chunk.code === "string" ? Buffer.byteLength(args.chunk.code, "utf8") : void 0;
	return {
		chunkBytes,
		redundantBytes: typeof chunkBytes === "number" ? chunkBytes * Math.max(args.redundantDuplicateCount, 0) : void 0,
		requiresRuntimeLocalization: chunkReferencesRuntime(args.chunk, ROLLDOWN_RUNTIME_FILE_NAME, new Set(args.sourceRoot ? [posix.join(args.sourceRoot, ROLLDOWN_RUNTIME_FILE_NAME), ROLLDOWN_RUNTIME_FILE_NAME] : [ROLLDOWN_RUNTIME_FILE_NAME]))
	};
}
//#endregion
//#region src/runtime/chunkStrategy/apply/shared/leaks.ts
function localizeCrossSubPackageChunkLeaks(bundle, options) {
	const { subPackageRoots, reservedFileNames, localizedDuplicateFileMap, onDuplicate } = options;
	if (subPackageRoots.length === 0) return;
	const entries = Object.entries(bundle);
	const importerIndex = options.importerIndex ?? createChunkImporterIndex(bundle, entries);
	for (const [fileName, output] of entries) {
		if (output?.type !== "chunk") continue;
		if (fileName.startsWith(`weapp_shared_virtual/`)) continue;
		if (posix.basename(fileName) === "rolldown-runtime.js") continue;
		const sourceRoot = resolveSubPackagePrefix(fileName, subPackageRoots);
		if (!sourceRoot) continue;
		const importers = findChunkImporters(bundle, fileName, importerIndex);
		if (importers.length === 0) continue;
		const crossRootImporters = /* @__PURE__ */ new Map();
		for (const importerFile of importers) {
			const importerRoot = resolveSubPackagePrefix(importerFile, subPackageRoots);
			if (!importerRoot || importerRoot === sourceRoot) continue;
			const list = crossRootImporters.get(importerRoot);
			if (list) list.push(importerFile);
			else crossRootImporters.set(importerRoot, [importerFile]);
		}
		if (crossRootImporters.size === 0) continue;
		const chunk = output;
		const sourceMapAssetInfo = findSourceMapAsset(bundle, collectSourceMapKeys(fileName, chunk));
		const resolvedSourceMap = resolveEncodedSourceMap(chunk.map, sourceMapAssetInfo?.asset.source);
		const importerToChunk = /* @__PURE__ */ new Map();
		const duplicates = [];
		for (const [targetRoot, importerFiles] of crossRootImporters.entries()) {
			const duplicateKey = `${targetRoot}::${fileName}`;
			const existingDuplicateFileName = localizedDuplicateFileMap.get(duplicateKey);
			const uniqueFileName = existingDuplicateFileName ?? (() => {
				const duplicateBaseName = createCrossSubPackageDuplicateBaseName(sourceRoot, fileName);
				const intendedFileName = posix.join(targetRoot, "weapp-shared", duplicateBaseName);
				const createdFileName = reserveUniqueFileName(reservedFileNames, intendedFileName);
				localizedDuplicateFileMap.set(duplicateKey, createdFileName);
				return createdFileName;
			})();
			const runtimeFileName = posix.join(targetRoot, ROLLDOWN_RUNTIME_FILE_NAME);
			if (!existingDuplicateFileName) {
				const duplicatedChunk = {
					...chunk,
					map: resolvedSourceMap
				};
				applyMagicStringChunkRewrite(duplicatedChunk, createChunkImportSpecifiersRewrite(duplicatedChunk.code ?? "", {
					sourceFileName: fileName,
					targetFileName: uniqueFileName,
					imports: chunk.imports,
					dynamicImports: chunk.dynamicImports,
					runtimeFileName
				}));
				this.emitFile({
					type: "asset",
					fileName: uniqueFileName,
					source: duplicatedChunk.code
				});
				if (duplicatedChunk.map) {
					const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
					this.emitFile({
						type: "asset",
						fileName: sourceMapFileName,
						source: JSON.stringify(duplicatedChunk.map)
					});
				} else if (duplicatedChunk.code === chunk.code) {
					const unchangedSourceMap = resolveSourceMapSource(chunk.map, sourceMapAssetInfo?.asset.source);
					if (unchangedSourceMap) {
						const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
						this.emitFile({
							type: "asset",
							fileName: sourceMapFileName,
							source: cloneSourceLike(unchangedSourceMap)
						});
					}
				}
			}
			for (const importerFile of importerFiles) importerToChunk.set(importerFile, uniqueFileName);
			duplicates.push({
				fileName: uniqueFileName,
				importers: [...importerFiles]
			});
		}
		updateImporters(bundle, importerToChunk, fileName, importerIndex);
		const diagnostics = buildDuplicateDiagnostics({
			chunk,
			duplicates,
			redundantDuplicateCount: duplicates.length,
			sourceRoot
		});
		onDuplicate?.({
			sharedFileName: fileName,
			duplicates,
			requiresRuntimeLocalization: diagnostics.requiresRuntimeLocalization,
			chunkBytes: diagnostics.chunkBytes,
			redundantBytes: diagnostics.redundantBytes,
			retainedInMain: true
		});
	}
}
//#endregion
//#region src/runtime/chunkStrategy/apply/shared.ts
function applySharedChunkStrategy(bundle, options) {
	if (options.strategy !== "duplicate" && !hasForceDuplicateSharedChunks()) return;
	if (!this) throw new Error("applySharedChunkStrategy 需要 PluginContext。");
	const subPackageRoots = Array.from(options.subPackageRoots).filter(Boolean);
	const entries = Object.entries(bundle);
	if (!shouldAnalyzeSharedChunkBundle(entries, subPackageRoots)) return;
	const reservedFileNames = new Set(entries.map(([fileName]) => fileName));
	const localizedDuplicateFileMap = /* @__PURE__ */ new Map();
	const runtimeContext = {
		pluginContext: this,
		bundle,
		subPackageRoots,
		reservedFileNames,
		localizedDuplicateFileMap
	};
	const pendingLocalizedDuplicates = [];
	const emittedLocalizedDuplicateFiles = /* @__PURE__ */ new Set();
	const importerIndex = createChunkImporterIndex(bundle, entries);
	for (const [fileName, output] of entries) {
		if (!isSharedVirtualChunk(fileName, output)) continue;
		const originalSharedFileName = fileName;
		const chunk = output;
		const importers = findChunkImporters(bundle, fileName, importerIndex);
		if (importers.length === 0) continue;
		const sourceMapKeys = collectSourceMapKeys(fileName, chunk);
		const sourceMapAssetInfo = findSourceMapAsset(bundle, sourceMapKeys);
		const resolvedSourceMap = resolveEncodedSourceMap(chunk.map, sourceMapAssetInfo?.asset.source);
		if (resolvedSourceMap) chunk.map = resolvedSourceMap;
		const importerMap = /* @__PURE__ */ new Map();
		const mainImporters = [];
		let hasMainImporter = false;
		const shouldForceDuplicate = isForceDuplicateSharedChunk(originalSharedFileName);
		for (const importerFile of importers) {
			const root = resolveSubPackagePrefix(importerFile, subPackageRoots);
			if (!root) {
				hasMainImporter = true;
				mainImporters.push(importerFile);
				continue;
			}
			const duplicateBaseName = posix.basename(fileName);
			const uniqueFileName = reserveUniqueFileName(reservedFileNames, posix.join(root, SUB_PACKAGE_SHARED_DIR, duplicateBaseName));
			const existing = importerMap.get(root);
			if (existing) existing.importers.push(importerFile);
			else importerMap.set(root, {
				newFileName: uniqueFileName,
				importers: [importerFile]
			});
		}
		const importerToChunk = /* @__PURE__ */ new Map();
		const duplicates = [];
		const diagnostics = consumeSharedChunkDiagnostics(originalSharedFileName);
		const shouldRetainOriginalChunk = shouldForceDuplicate && hasMainImporter;
		if ((hasMainImporter || importerMap.size === 0) && (!shouldForceDuplicate || importerMap.size === 0)) {
			let finalFileName = chunk.fileName;
			if (fileName.startsWith(`weapp_shared_virtual/`)) {
				const newFileName = fileName.slice(21);
				const codeRewritten = applyMagicStringChunkRewrite(chunk, createChunkImportSpecifiersRewrite(chunk.code ?? "", {
					sourceFileNames: createChunkSourceFileNameCandidates(fileName),
					targetFileName: newFileName,
					imports: chunk.imports,
					dynamicImports: chunk.dynamicImports,
					runtimeFileName: ROLLDOWN_RUNTIME_FILE_NAME
				}));
				chunk.fileName = newFileName;
				if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) chunk.sourcemapFileName = `${newFileName}.map`;
				const targetKey = `${newFileName}.map`;
				emitSourceMapAsset(this, targetKey, codeRewritten ? void 0 : sourceMapAssetInfo, resolveSourceMapSource(chunk.map, void 0));
				for (const mapKey of sourceMapKeys) {
					if (!mapKey || mapKey === targetKey) continue;
					if (bundle[mapKey]) delete bundle[mapKey];
				}
				finalFileName = newFileName;
			}
			if (finalFileName !== originalSharedFileName) {
				const fallbackImporterMap = /* @__PURE__ */ new Map();
				for (const importerFile of importers) fallbackImporterMap.set(importerFile, finalFileName);
				updateImporters(bundle, fallbackImporterMap, originalSharedFileName, importerIndex);
			}
			options.onFallback?.({
				sharedFileName: originalSharedFileName,
				finalFileName,
				reason: hasMainImporter ? "main-package" : "no-subpackage",
				importers: [...importers]
			});
			continue;
		}
		if (shouldRetainOriginalChunk && fileName.startsWith(`weapp_shared_virtual/`)) {
			const newFileName = fileName.slice(21);
			const codeRewritten = applyMagicStringChunkRewrite(chunk, createChunkImportSpecifiersRewrite(chunk.code ?? "", {
				sourceFileNames: createChunkSourceFileNameCandidates(fileName),
				targetFileName: newFileName,
				imports: chunk.imports,
				dynamicImports: chunk.dynamicImports,
				runtimeFileName: ROLLDOWN_RUNTIME_FILE_NAME
			}));
			chunk.fileName = newFileName;
			if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) chunk.sourcemapFileName = `${newFileName}.map`;
			const targetKey = `${newFileName}.map`;
			emitSourceMapAsset(this, targetKey, codeRewritten ? void 0 : sourceMapAssetInfo, resolveSourceMapSource(chunk.map, void 0));
			for (const mapKey of sourceMapKeys) {
				if (!mapKey || mapKey === targetKey) continue;
				if (bundle[mapKey]) delete bundle[mapKey];
			}
			if (mainImporters.length) {
				const mainImporterMap = /* @__PURE__ */ new Map();
				for (const importerFile of mainImporters) mainImporterMap.set(importerFile, newFileName);
				updateImporters(bundle, mainImporterMap, originalSharedFileName, importerIndex);
			}
			options.onFallback?.({
				sharedFileName: originalSharedFileName,
				finalFileName: newFileName,
				reason: "main-package",
				importers: [...importers]
			});
		}
		for (const [root, { newFileName, importers: importerFiles }] of importerMap.entries()) {
			emitDuplicatedChunkAsset({
				runtimeContext,
				pendingLocalizedDuplicates,
				emittedLocalizedDuplicateFiles,
				root,
				sourceFileName: fileName,
				targetFileName: newFileName,
				chunk
			});
			for (const importerFile of importerFiles) importerToChunk.set(importerFile, newFileName);
			duplicates.push({
				fileName: newFileName,
				importers: [...importerFiles]
			});
		}
		updateImporters(bundle, importerToChunk, fileName, importerIndex);
		if (!shouldRetainOriginalChunk) {
			delete bundle[fileName];
			removeChunkFromImporterIndex(importerIndex, fileName);
			for (const mapKey of sourceMapKeys) if (mapKey && bundle[mapKey]) delete bundle[mapKey];
		}
		const duplicateDiagnostics = buildDuplicateDiagnostics({
			chunk,
			duplicates,
			redundantDuplicateCount: Math.max(duplicates.length - 1, 0)
		});
		options.onDuplicate?.({
			sharedFileName: originalSharedFileName,
			duplicates,
			ignoredMainImporters: diagnostics?.ignoredMainImporters,
			requiresRuntimeLocalization: duplicateDiagnostics.requiresRuntimeLocalization,
			chunkBytes: duplicateDiagnostics.chunkBytes,
			redundantBytes: duplicateDiagnostics.redundantBytes,
			retainedInMain: shouldRetainOriginalChunk
		});
	}
	localizeCrossSubPackageChunkLeaks.call(this, bundle, {
		subPackageRoots,
		reservedFileNames,
		localizedDuplicateFileMap,
		importerIndex,
		onDuplicate: options.onDuplicate
	});
	for (const task of pendingLocalizedDuplicates) emitDuplicatedChunkAsset({
		runtimeContext,
		pendingLocalizedDuplicates,
		emittedLocalizedDuplicateFiles,
		...task
	});
}
function isSharedVirtualChunk(fileName, output) {
	return output?.type === "chunk" && fileName.startsWith(`weapp_shared_virtual/`);
}
function shouldAnalyzeSharedChunkBundle(entries, subPackageRoots) {
	for (const [fileName, output] of entries) {
		if (isSharedVirtualChunk(fileName, output)) return true;
		if (subPackageRoots.length && output?.type === "chunk" && resolveSubPackagePrefix(fileName, subPackageRoots)) return true;
	}
	return false;
}
//#endregion
//#region src/runtime/chunkStrategy/naming.ts
function resolveTakeSharedChunkName(options) {
	const { ctx, relativeAbsoluteSrcRoot, subPackageRoots, importers } = options;
	if (!importers.length) return;
	const { summary } = summarizeImportPrefixes({
		ctx,
		importers,
		relativeAbsoluteSrcRoot,
		subPackageRoots
	});
	const keys = Object.keys(summary).filter(Boolean);
	if (!keys.length) return;
	const sharedName = createSharedChunkNameFromKeys(keys);
	markForceDuplicateSharedChunk(sharedName);
	return sharedName;
}
function createSharedChunkNameFromKeys(keys) {
	const sanitize = (value) => value.replace(/[\\/]+/g, "_");
	const combination = keys.filter(Boolean).map(sanitize).sort().join("+");
	const combinationSegment = combination ? `${combination}/` : "";
	return `${SHARED_CHUNK_VIRTUAL_PREFIX}/${combinationSegment}common`;
}
function resolveSharedChunkName(options) {
	const { id, ctx, relativeAbsoluteSrcRoot, subPackageRoots, strategy, sharedMode, resolveSharedMode, resolveSharedPath, forceDuplicateTester } = options;
	const cached = getCachedSharedChunkName(id);
	if (cached !== void 0) return cached ?? void 0;
	const subPackageRootList = Array.from(subPackageRoots);
	const moduleInfo = ctx.getModuleInfo(id);
	const relativeId = relativeAbsoluteSrcRoot(id);
	const resolvedMode = resolveSharedMode?.(relativeId, id) ?? sharedMode ?? "common";
	if (resolvedMode === "inline") {
		setCachedSharedChunkName(id, void 0);
		return;
	}
	if (resolvedMode === "path") {
		if (!moduleInfo?.importers || moduleInfo.importers.length <= 1) {
			setCachedSharedChunkName(id, void 0);
			return;
		}
		const moduleRoot = resolveSubPackagePrefix(relativeId, subPackageRootList);
		if (moduleRoot) assertModuleScopedToRoot({
			moduleInfo,
			moduleRoot,
			relativeAbsoluteSrcRoot,
			subPackageRoots: subPackageRootList,
			moduleId: id
		});
		const normalized = normalizeRelativePath$1(resolveSharedPath?.(id, relativeId) ?? relativeId);
		if (!normalized || normalized.startsWith("..")) {
			setCachedSharedChunkName(id, void 0);
			return;
		}
		const sharedName = removeExtensionDeep(normalized);
		if (!sharedName || sharedName === ".") {
			setCachedSharedChunkName(id, void 0);
			return;
		}
		setCachedSharedChunkName(id, sharedName);
		return sharedName;
	}
	const takeImporters = getTakeImporters(id);
	if (takeImporters?.size) {
		const takeSharedName = resolveTakeSharedChunkName({
			id,
			ctx,
			relativeAbsoluteSrcRoot,
			subPackageRoots: subPackageRootList,
			importers: Array.from(takeImporters)
		});
		if (takeSharedName) {
			setCachedSharedChunkName(id, takeSharedName);
			return takeSharedName;
		}
	}
	if (strategy === "hoist") {
		const moduleRoot = resolveSubPackagePrefix(relativeId, subPackageRootList);
		if (moduleRoot) {
			assertModuleScopedToRoot({
				moduleInfo,
				moduleRoot,
				relativeAbsoluteSrcRoot,
				subPackageRoots: subPackageRootList,
				moduleId: id
			});
			if (!moduleInfo?.importers || moduleInfo.importers.length <= 1) {
				setCachedSharedChunkName(id, void 0);
				return;
			}
			const sharedName = posix.join(moduleRoot, "common");
			setCachedSharedChunkName(id, sharedName);
			return sharedName;
		}
		if (!moduleInfo?.importers || moduleInfo.importers.length <= 1) {
			setCachedSharedChunkName(id, void 0);
			return;
		}
		setCachedSharedChunkName(id, "common");
		return "common";
	}
	if (!moduleInfo?.importers || moduleInfo.importers.length <= 1) {
		setCachedSharedChunkName(id, void 0);
		return;
	}
	const { summary, ignoredMainImporters } = summarizeImportPrefixes({
		ctx,
		importers: moduleInfo.importers,
		relativeAbsoluteSrcRoot,
		subPackageRoots: subPackageRootList,
		forceDuplicateTester
	});
	const keys = Object.keys(summary);
	if (keys.length === 0) {
		setCachedSharedChunkName(id, void 0);
		return;
	}
	if (keys.length === 1) {
		const prefix = keys[0];
		const sharedName = prefix ? posix.join(prefix, "common") : "common";
		setCachedSharedChunkName(id, sharedName);
		return sharedName;
	}
	const hasMainImporter = keys.includes("");
	if (strategy === "duplicate" && !hasMainImporter) {
		const sharedName = createSharedChunkNameFromKeys(keys);
		if (ignoredMainImporters.length) recordSharedChunkDiagnostics(sharedName, ignoredMainImporters);
		setCachedSharedChunkName(id, sharedName);
		return sharedName;
	}
	setCachedSharedChunkName(id, "common");
	return "common";
}
//#endregion
//#region src/runtime/advancedChunks.ts
function testByReg2DExpList(reg2DExpList) {
	return (id) => reg2DExpList.some((regExpList) => regExpList.some((regExp) => {
		regExp.lastIndex = 0;
		return regExp.test(id);
	}));
}
function createAdvancedChunkNameResolver(options) {
	const { relativeAbsoluteSrcRoot, getSubPackageRoots, strategy, vendorsMatchers, forceDuplicateTester, sharedMode, resolveSharedMode, resolveSharedPath } = options;
	const isVendor = testByReg2DExpList(vendorsMatchers);
	return (id, ctx) => {
		if (parseSidecarSourceRequest(id)) return;
		if (ctx.getModuleInfo(id)?.importers?.some((importer) => {
			return parseLogicalEntryId(importer)?.sourceId === id;
		})) return;
		const subPackageRoots = Array.from(getSubPackageRoots());
		const relativeId = relativeAbsoluteSrcRoot(id);
		const resolvedMode = resolveSharedMode ? resolveSharedMode(relativeId, id) : sharedMode;
		const sharedName = resolveSharedChunkName({
			id,
			ctx,
			relativeAbsoluteSrcRoot,
			subPackageRoots,
			strategy,
			forceDuplicateTester,
			sharedMode: resolvedMode,
			resolveSharedMode,
			resolveSharedPath
		});
		if (!isVendor(id)) return sharedName;
		if (strategy === "hoist" && (resolvedMode ?? "common") === "common") return "vendors";
		return sharedName;
	};
}
//#endregion
//#region src/runtime/preserveModules.ts
const PRESERVED_MODULE_GROUP_PRIORITY = 100;
function createPatternMatcher(pattern) {
	if (typeof pattern === "string") {
		const matcher = picomatch(pattern, { dot: true });
		return (value) => matcher(value);
	}
	if (isRegexp(pattern)) return (value) => {
		pattern.lastIndex = 0;
		return pattern.test(value);
	};
}
function createPreserveModuleMatcher(patterns) {
	const matchers = patterns?.map((pattern) => createPatternMatcher(pattern)).filter((matcher) => typeof matcher === "function");
	if (!matchers?.length) return;
	return (relativeId, absoluteId) => {
		return matchers.some((matcher) => matcher(relativeId) || matcher(absoluteId));
	};
}
function normalizePreservedSourceId(id) {
	return normalizeViteId(id, {
		stripQuery: true,
		fileProtocolToPath: true,
		stripAtFsPrefix: true,
		stripLeadingNullByte: true
	});
}
function normalizePreserveModulesRolldownOptions(configService, rolldownOptions) {
	if (configService.weappViteConfig?.chunks?.preserveModules?.length && (rolldownOptions.preserveEntrySignatures === void 0 || rolldownOptions.preserveEntrySignatures === "exports-only")) rolldownOptions.preserveEntrySignatures = "allow-extension";
	return rolldownOptions;
}
function resolvePreservedModuleName(options) {
	const { configService, ctx, getSubPackageRoots, id } = options;
	if (parseSidecarSourceRequest(id)) return;
	const absoluteId = normalizePreservedSourceId(id);
	if (!path.isAbsolute(absoluteId) || !isPathInside(configService.absoluteSrcRoot, absoluteId)) return;
	const moduleInfo = ctx.getModuleInfo(id);
	if (moduleInfo?.importers?.some((importer) => {
		return parseLogicalEntryId(importer)?.sourceId === absoluteId;
	})) return;
	const relativeId = normalizeRelativePath$1(path.relative(configService.absoluteSrcRoot, absoluteId));
	if (!relativeId || relativeId.startsWith("..")) return;
	const subPackageRoots = Array.from(getSubPackageRoots());
	const moduleRoot = resolveSubPackagePrefix(relativeId, subPackageRoots);
	if (moduleRoot) assertModuleScopedToRoot({
		moduleInfo,
		moduleRoot,
		relativeAbsoluteSrcRoot: configService.relativeAbsoluteSrcRoot,
		subPackageRoots,
		moduleId: id
	});
	const name = removeExtensionDeep(relativeId);
	return name && name !== "." ? name : void 0;
}
function createPreserveModulesGroup(configService, getSubPackageRoots) {
	const matches = createPreserveModuleMatcher(configService.weappViteConfig?.chunks?.preserveModules);
	if (!matches) return;
	return {
		name: (id, ctx) => resolvePreservedModuleName({
			configService,
			ctx,
			getSubPackageRoots,
			id
		}),
		test: (id) => {
			const absoluteId = normalizePreservedSourceId(id);
			const relativeId = configService.relativeAbsoluteSrcRoot(absoluteId);
			return matches(relativeId, absoluteId);
		},
		priority: PRESERVED_MODULE_GROUP_PRIORITY,
		minShareCount: 1,
		minSize: 0,
		minModuleSize: 0,
		includeDependenciesRecursively: false
	};
}
//#endregion
//#region src/runtime/wevuModules.ts
const WEVU_RUNTIME_MODULE_IDS = [
	"wevu",
	"wevu/router",
	"wevu/store",
	"wevu/api",
	"wevu/fetch",
	"wevu/web-apis",
	"wevu/internal-runtime",
	"wevu/internal-reactivity",
	"wevu/internal-template"
];
const WEVU_ENTRY_MODULE_IDS = {
	"api": "wevu/api",
	"fetch": "wevu/fetch",
	"index": "wevu",
	"internal-reactivity": "wevu/internal-reactivity",
	"internal-runtime": "wevu/internal-runtime",
	"internal-template": "wevu/internal-template",
	"router": "wevu/router",
	"store": "wevu/store",
	"web-apis": "wevu/web-apis"
};
const WEVU_STABLE_VENDOR_FILE_RE = /^weapp-vendors\/wevu-[^/]+\.js$/;
const HASHED_MODULE_BASENAME_RE = /-[\w-]{8}$/;
const WEVU_RUNTIME_MODULE_ID_BY_FAMILY = {
	"api": "wevu/api",
	"fetch": "wevu/fetch",
	"reactivity": "wevu/internal-reactivity",
	"router": "wevu/router",
	"runtime": "wevu/internal-runtime",
	"store": "wevu/store",
	"template": "wevu/internal-template",
	"web-apis": "wevu/web-apis"
};
function isWevuEntryModulePath(value) {
	return Object.prototype.hasOwnProperty.call(WEVU_ENTRY_MODULE_IDS, value);
}
function normalizeModuleId(id) {
	return normalizeViteId(id, {
		stripQuery: true,
		fileProtocolToPath: true,
		stripAtFsPrefix: true,
		stripLeadingNullByte: true
	}).replaceAll("\\", "/");
}
function resolveWevuPreservedModulePath(id) {
	const normalized = normalizeModuleId(id);
	const sourceMarker = "/packages-runtime/wevu/src/";
	const distMarker = "/wevu/dist/";
	const sourceIndex = normalized.lastIndexOf(sourceMarker);
	if (sourceIndex >= 0) return normalized.slice(sourceIndex + 27).replace(/\.[cm]?[jt]s$/, "");
	const distIndex = normalized.lastIndexOf(distMarker);
	if (distIndex < 0) return;
	const modulePath = normalized.slice(distIndex + 11).replace(/^dev\//, "").replace(/\.[cm]?[jt]s$/, "");
	if (!isWevuEntryModulePath(modulePath) && HASHED_MODULE_BASENAME_RE.test(modulePath)) return;
	return modulePath;
}
function resolveWevuRuntimeModuleId(id) {
	if (WEVU_RUNTIME_MODULE_IDS.includes(id)) return id;
	const modulePath = resolveWevuPreservedModulePath(id);
	if (!modulePath || modulePath.includes("/")) return;
	return WEVU_ENTRY_MODULE_IDS[modulePath];
}
function resolveWevuRuntimeModuleFamily(id) {
	const bareModuleId = resolveWevuRuntimeModuleId(id);
	if (bareModuleId) {
		if (bareModuleId === "wevu/internal-reactivity") return "reactivity";
		if (bareModuleId === "wevu/internal-template") return "template";
		if (bareModuleId === "wevu/internal-runtime" || bareModuleId === "wevu") return "runtime";
		return bareModuleId.slice(5);
	}
	const modulePath = resolveWevuPreservedModulePath(id);
	if (!modulePath) return;
	if (modulePath.startsWith("reactivity/") || modulePath === "scheduler") return "reactivity";
	if (modulePath === "runtime/template") return "template";
	if (modulePath.startsWith("router/") || modulePath.startsWith("routerInternal/")) return "router";
	if (modulePath.startsWith("store/")) return "store";
	if (modulePath.startsWith("compiler/")) return "compiler";
	if (modulePath === "jsx-runtime" || modulePath === "vue-demi") return modulePath;
	if (modulePath === "api" || modulePath === "fetch" || modulePath === "web-apis") return modulePath;
	return "runtime";
}
function resolveWevuStableVendorFileName(id) {
	const family = resolveWevuRuntimeModuleFamily(id);
	return family ? `weapp-vendors/wevu-${family}.js` : void 0;
}
function isWevuStableVendorFileName(fileName) {
	return WEVU_STABLE_VENDOR_FILE_RE.test(fileName.replaceAll("\\", "/"));
}
function resolveWevuRuntimeModuleIdFromStableVendorFileName(fileName) {
	const normalized = fileName.replaceAll("\\", "/");
	if (!isWevuStableVendorFileName(normalized)) return;
	const family = normalized.slice(19, -3);
	return WEVU_RUNTIME_MODULE_ID_BY_FAMILY[family];
}
//#endregion
//#region src/runtime/sharedBuildConfig.ts
const REG_NODE_MODULES_DIR = /[\\/]node_modules[\\/]/gi;
const REG_COMMONJS_HELPERS = /commonjsHelpers\.js$/;
const REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID = /(?:^|[/\\])(?:@wevu[/\\]web-apis|web-apis[/\\]dist[/\\]index\.(?:m?js|cjs)|weapp-vite[/\\](?:dist[/\\]web-apis\.mjs|src[/\\](?:webApis\.ts|runtime[/\\]webApis[/\\]index\.ts)))(?:$|[?#])/;
const REG_WEAPP_VITE_RUNTIME_VENDOR_ID = /(?:^|[/\\])weapp-vite[/\\](?:dist[/\\]runtime\.mjs|src[/\\]plugins[/\\]vue[/\\]runtime\.ts)(?:$|[?#])/;
const REG_HASHED_DIST_CHUNK_ID = /(?:^|[/\\])dist[/\\](?:dev[/\\])?([^/\\-]+)-([\w-]{6,})\.(?:m?js|cjs)(?:$|[?#])/;
const STABLE_HASHED_DIST_CHUNK_PRIORITY = ["src"];
const STABLE_HASHED_DIST_CHUNK_PRIORITY_BY_PACKAGE = { wevu: [
	"index",
	"internal-runtime",
	"watch",
	"templateRef",
	"router",
	"base",
	"computed",
	"toRefs",
	"store",
	"template",
	"ref"
] };
function resolveSharedPathRoot(configService, sharedPathRoot) {
	const absoluteSrcRoot = configService.absoluteSrcRoot;
	const configuredRoot = sharedPathRoot ? path.resolve(configService.cwd, sharedPathRoot) : absoluteSrcRoot;
	return {
		configuredRoot,
		resolvedRoot: isPathInside(absoluteSrcRoot, configuredRoot) ? configuredRoot : absoluteSrcRoot
	};
}
function normalizeSharedPathCandidate(absoluteId) {
	return normalizeViteId(absoluteId, {
		stripQuery: true,
		fileProtocolToPath: true,
		stripAtFsPrefix: true,
		stripLeadingNullByte: true
	});
}
function resolveNodeModulesSharedPath(cleanedAbsoluteId) {
	const normalized = cleanedAbsoluteId.replaceAll("\\", "/");
	const markerIndex = normalized.lastIndexOf("/node_modules/");
	if (markerIndex < 0) return;
	const packageRelativePath = normalizeNpmImportLookupPath(normalized.slice(markerIndex));
	return packageRelativePath ? normalizeRelativePath$1(packageRelativePath) : void 0;
}
function createStringOrRegExpMatcher(pattern) {
	if (typeof pattern === "string") {
		const matcher = picomatch(pattern, { dot: true });
		return (value) => matcher(value);
	}
	if (isRegexp(pattern)) return (value) => {
		pattern.lastIndex = 0;
		return pattern.test(value);
	};
}
function createDualIdMatcher(matchers) {
	if (!matchers.length) return;
	return (relativeId, absoluteId) => {
		for (const matcher of matchers) if (matcher(relativeId) || matcher(absoluteId)) return true;
		return false;
	};
}
function createForceDuplicateTester(patterns) {
	if (!patterns || patterns.length === 0) return;
	return createDualIdMatcher(patterns.map((pattern) => createStringOrRegExpMatcher(pattern)).filter((matcher) => typeof matcher === "function"));
}
function createSharedModeResolver(sharedMode, overrides) {
	if (!overrides || overrides.length === 0) return;
	const matchers = overrides.map((override) => {
		const { test, mode } = override;
		const matches = createStringOrRegExpMatcher(test);
		if (matches) return {
			mode,
			matches
		};
	}).filter((entry) => !!entry);
	if (!matchers.length) return;
	return (relativeId, absoluteId) => {
		return matchers.find(({ matches }) => matches(relativeId) || matches(absoluteId))?.mode ?? sharedMode;
	};
}
function createSharedPathResolver(configService, sharedPathRoot) {
	const { configuredRoot, resolvedRoot } = resolveSharedPathRoot(configService, sharedPathRoot);
	if (configuredRoot !== resolvedRoot) logger_default.warn(`[chunks] sharedPathRoot "${sharedPathRoot}" 不在 srcRoot 内,已回退到 srcRoot。`);
	return (absoluteId) => {
		const cleaned = normalizeSharedPathCandidate(absoluteId);
		if (!path.isAbsolute(cleaned)) return;
		if (!isPathInside(resolvedRoot, cleaned)) return resolveNodeModulesSharedPath(cleaned);
		return normalizeRelativePath$1(path.relative(resolvedRoot, cleaned));
	};
}
function resolveSharedBuildChunksOptions(configService) {
	const chunksConfig = configService.weappViteConfig?.chunks;
	return {
		sharedStrategy: chunksConfig?.sharedStrategy ?? "hoist",
		forceDuplicatePatterns: chunksConfig?.forceDuplicatePatterns,
		sharedMode: chunksConfig?.sharedMode ?? "common",
		sharedOverrides: chunksConfig?.sharedOverrides,
		sharedPathRoot: chunksConfig?.sharedPathRoot
	};
}
function isRequestGlobalsRuntimeChunk(chunk) {
	if (chunk.name !== "dist") return false;
	return [chunk.facadeModuleId, ...chunk.moduleIds ?? []].filter((id) => typeof id === "string").some((id) => {
		REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID.lastIndex = 0;
		return REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID.test(id);
	});
}
function sanitizePackageToken(value) {
	return value.replace(/^@/, "").replaceAll(/[\\/]/g, "-").replaceAll(/[^\w-]/g, "-").replaceAll(/-+/g, "-").replace(/^-|-$/g, "");
}
function resolveDistChunkPackageToken(cleanedAbsoluteId) {
	const npmRelativePath = resolveNodeModulesSharedPath(cleanedAbsoluteId);
	if (npmRelativePath) {
		const [packagePath] = npmRelativePath.split("/dist/");
		if (packagePath) return sanitizePackageToken(packagePath);
	}
	const segments = cleanedAbsoluteId.replaceAll("\\", "/").split("/");
	const distIndex = segments.lastIndexOf("dist");
	if (distIndex <= 0) return;
	const packageToken = segments[distIndex - 1];
	if (!packageToken) return;
	return sanitizePackageToken(packageToken);
}
function isRequestGlobalsRuntimeModuleId(id) {
	const cleanedAbsoluteId = normalizeSharedPathCandidate(id);
	REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID.lastIndex = 0;
	if (REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID.test(cleanedAbsoluteId)) return true;
	return resolveDistChunkPackageToken(cleanedAbsoluteId)?.endsWith("web-apis") === true;
}
function isWeappViteRuntimeModuleId(id) {
	const cleanedAbsoluteId = normalizeSharedPathCandidate(id);
	REG_WEAPP_VITE_RUNTIME_VENDOR_ID.lastIndex = 0;
	return REG_WEAPP_VITE_RUNTIME_VENDOR_ID.test(cleanedAbsoluteId);
}
function resolveStableHashedDistChunkFileName(chunk) {
	const candidateIds = [chunk.facadeModuleId, ...chunk.moduleIds ?? []].filter((id) => typeof id === "string");
	const matchedChunks = [];
	let facadeMatchedChunk;
	for (const id of candidateIds) {
		const fileName = resolveWevuStableVendorFileName(id);
		if (fileName) return fileName;
	}
	for (const id of candidateIds) {
		if (isWeappViteRuntimeModuleId(id)) return "weapp-vendors/weapp-vite-runtime.js";
		const cleanedAbsoluteId = normalizeSharedPathCandidate(id);
		if (!path.isAbsolute(cleanedAbsoluteId)) continue;
		const matched = cleanedAbsoluteId.match(REG_HASHED_DIST_CHUNK_ID);
		if (!matched) continue;
		const baseName = matched[1];
		const packageToken = resolveDistChunkPackageToken(cleanedAbsoluteId);
		if (!baseName || !packageToken) continue;
		REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID.lastIndex = 0;
		if (REG_REQUEST_GLOBAL_RUNTIME_VENDOR_ID.test(cleanedAbsoluteId) || packageToken.endsWith("web-apis")) return `weapp-vendors/request-globals-${packageToken}-${baseName}.js`;
		const matchedChunk = {
			baseName,
			fileName: `weapp-vendors/${packageToken}-${baseName}.js`
		};
		matchedChunks.push(matchedChunk);
		if (id === chunk.facadeModuleId) facadeMatchedChunk = matchedChunk;
	}
	const packageTokens = /* @__PURE__ */ new Set();
	for (const { fileName } of matchedChunks) {
		const fileNameBase = fileName.replace(/^weapp-vendors\//, "").replace(/\.js$/, "");
		const packageToken = Object.keys(STABLE_HASHED_DIST_CHUNK_PRIORITY_BY_PACKAGE).find((token) => fileNameBase.startsWith(`${token}-`));
		if (packageToken) packageTokens.add(packageToken);
	}
	for (const packageToken of packageTokens) {
		const priorityBaseNames = STABLE_HASHED_DIST_CHUNK_PRIORITY_BY_PACKAGE[packageToken];
		for (const priorityBaseName of priorityBaseNames) {
			const matched = matchedChunks.find((chunk) => chunk.fileName === `weapp-vendors/${packageToken}-${priorityBaseName}.js`);
			if (matched) return matched.fileName;
		}
	}
	if (facadeMatchedChunk) return facadeMatchedChunk.fileName;
	for (const priorityBaseName of STABLE_HASHED_DIST_CHUNK_PRIORITY) {
		const matched = matchedChunks.find((chunk) => chunk.baseName === priorityBaseName);
		if (matched) return matched.fileName;
	}
	if (matchedChunks[0]) return matchedChunks[0].fileName;
}
function resolveStableHashedDistChunkName(chunk) {
	return resolveStableHashedDistChunkFileName(chunk)?.replace(/\.js$/, "");
}
function isStableHashedDistChunkModule(id) {
	return Boolean(resolveStableHashedDistChunkName({ facadeModuleId: id }));
}
function createSharedBuildResolver(configService, getSubPackageRoots) {
	const nodeModulesDeps = [REG_NODE_MODULES_DIR];
	const commonjsHelpersDeps = [REG_COMMONJS_HELPERS];
	const { sharedStrategy, forceDuplicatePatterns, sharedMode, sharedOverrides, sharedPathRoot } = resolveSharedBuildChunksOptions(configService);
	const forceDuplicateTester = createForceDuplicateTester(forceDuplicatePatterns);
	const resolveSharedMode = createSharedModeResolver(sharedMode, sharedOverrides);
	const resolveSharedPath = createSharedPathResolver(configService, sharedPathRoot);
	const resolveAdvancedChunkName = createAdvancedChunkNameResolver({
		vendorsMatchers: [nodeModulesDeps, commonjsHelpersDeps],
		relativeAbsoluteSrcRoot: configService.relativeAbsoluteSrcRoot,
		getSubPackageRoots,
		strategy: sharedStrategy,
		forceDuplicateTester,
		sharedMode,
		resolveSharedMode,
		resolveSharedPath
	});
	const resolveSharedBuildChunkName = (id, ctx) => {
		if (isRequestGlobalsRuntimeModuleId(id)) return REQUEST_GLOBAL_RUNTIME_CHUNK_FILE_BASENAME.replace(/\.js$/, "");
		if (isWeappViteRuntimeModuleId(id)) return "weapp-vendors/weapp-vite-runtime";
		if (configService.isDev) {
			const stableHashedDistChunkName = resolveStableHashedDistChunkName({ facadeModuleId: id });
			if (stableHashedDistChunkName) return stableHashedDistChunkName;
		}
		return resolveAdvancedChunkName(id, ctx);
	};
	return { resolveAdvancedChunkName: resolveSharedBuildChunkName };
}
function createSharedBuildOutput(configService, getSubPackageRoots, options = {}) {
	const preserveModulesGroup = createPreserveModulesGroup(configService, getSubPackageRoots);
	const { resolveAdvancedChunkName } = createSharedBuildResolver(configService, getSubPackageRoots);
	return {
		codeSplitting: { groups: [
			...preserveModulesGroup ? [preserveModulesGroup] : [],
			...configService.isDev ? [{
				test: isStableHashedDistChunkModule,
				minShareCount: 1,
				minSize: 0,
				minModuleSize: 0,
				name: (id) => resolveStableHashedDistChunkName({ facadeModuleId: id })
			}] : [],
			{ name: (id, ctx) => resolveAdvancedChunkName(id, ctx) }
		] },
		minifyInternalExports: false,
		chunkFileNames: (chunk) => {
			if (isRequestGlobalsRuntimeChunk(chunk)) return REQUEST_GLOBAL_RUNTIME_CHUNK_FILE_BASENAME;
			if (options.runtime !== "web") {
				const namedStableVendorFileName = `${chunk.name}.js`;
				if (isWevuStableVendorFileName(namedStableVendorFileName)) return namedStableVendorFileName;
				const stableHashedDistChunkFileName = resolveStableHashedDistChunkFileName(chunk);
				if (stableHashedDistChunkFileName) return stableHashedDistChunkFileName;
			}
			return "[name].js";
		}
	};
}
function createSharedBuildConfig(configService, scanService) {
	const output = createSharedBuildOutput(configService, () => scanService.subPackageMap.keys());
	const preserveEntrySignatures = configService.weappViteConfig?.chunks?.preserveModules?.length ? "allow-extension" : void 0;
	return { build: { rolldownOptions: {
		...preserveEntrySignatures ? { preserveEntrySignatures } : {},
		output
	} } };
}
//#endregion
//#region src/runtime/statefulHmr/runtimeSource.ts
const statefulHmrRolldownRuntimeSource = `
var BaseDevRuntime = DevRuntime;
class WeappViteHotContext {
  callbacks = [];
  data = {};
  _internal = { updateStyle() {}, removeStyle() {} };
  constructor(moduleId) { this.moduleId = moduleId; }
  accept(...args) {
    if (args.length === 0) this.callbacks.push({ deps: this.moduleId, callback: undefined });
    else if (args.length === 1 && typeof args[0] === 'function') this.callbacks.push({ deps: this.moduleId, callback: args[0] });
    else if (args.length === 1) this.callbacks.push({ deps: args[0], callback: undefined });
    else this.callbacks.push({ deps: args[0], callback: args[1] });
  }
  acceptExports(_exports, callback) { this.accept(callback); }
  dispose() {}
  prune() {}
  invalidate() {}
  on() {}
  off() {}
  send() {}
}
class WeappViteDevRuntime extends BaseDevRuntime {
  contexts = new Map();
  patchedModules = new Set();
  applyingPatch = false;
  currentModuleId = '';
  registrationModuleId = '';
  createEsmInitializer = (id, initialize, _deduplicate, result) => () => {
    if (!initialize) return result;
    const callback = initialize;
    initialize = undefined;
    const previousId = this.currentModuleId;
    this.currentModuleId = id;
    try { result = callback(id); }
    finally { this.currentModuleId = previousId; }
    if (this.applyingPatch) this.patchedModules.add(id);
    return result;
  };
  createCjsInitializer = (id, initialize, _deduplicate, module) => () => {
    if (module) return module.exports;
    module = { exports: {} };
    const previousId = this.currentModuleId;
    this.currentModuleId = id;
    try { initialize(module.exports, module, id); }
    finally { this.currentModuleId = previousId; }
    if (this.applyingPatch) this.patchedModules.add(id);
    return module.exports;
  };
  createModuleHotContext(moduleId) {
    const previous = this.contexts.get(moduleId);
    const context = new WeappViteHotContext(moduleId);
    this.registrationModuleId = moduleId;
    if (previous) {
      context.callbacks = previous.callbacks;
      context.data = previous.data;
    }
    this.contexts.set(moduleId, context);
    return context;
  }
  registerModule(id, exportsHolder) {
    this.registrationModuleId = id;
    return super.registerModule(id, exportsHolder);
  }
  initModule(id) {
    const previousId = this.currentModuleId;
    this.currentModuleId = id;
    try {
      const result = super.initModule(id);
      if (this.applyingPatch) this.patchedModules.add(id);
      return result;
    }
    finally { this.currentModuleId = previousId; }
  }
  beginPatch() { this.applyingPatch = true; }
  endPatch() { this.applyingPatch = false; }
  applyUpdates(boundaries) {
    for (const [boundary, acceptedVia] of boundaries) {
      const context = this.contexts.get(boundary);
      if (!context) continue;
      const callbacks = [...context.callbacks];
      if (boundary === acceptedVia) context.callbacks = [];
      for (const { deps, callback } of callbacks) {
        if (!callback) continue;
        if (Array.isArray(deps)) {
          if (deps.includes(acceptedVia)) callback(deps.map((id) => this.loadExports(id)));
        } else if (deps === acceptedVia) callback(this.loadExports(acceptedVia));
      }
    }
  }
}
const runtime = new WeappViteDevRuntime(undefined, 'weapp-vite-stateful');
globalThis.__rolldown_runtime__ = runtime;
const bridgeKey = ${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)};
const definitions = new Map();
const registered = new Set();
const instances = new Map();
const instanceSnapshots = new WeakMap();
const moduleSnapshots = new Map();
const pendingNativeDefinitions = new Map();
const wevuRefreshes = new Map();
const wevuRefreshGenerations = new Map();
const wevuInstanceGenerations = new WeakMap();
let suppressLifecycles = false;
const nativeRegistrations = {};
function getInstances(moduleId) {
  let values = instances.get(moduleId);
  if (!values) instances.set(moduleId, values = new Set());
  return values;
}
function cloneInstanceData(value) {
  if (Array.isArray(value)) return value.map(cloneInstanceData);
  if (!value || typeof value !== 'object') return value;
  const result = {};
  for (const [key, child] of Object.entries(value)) result[key] = cloneInstanceData(child);
  return result;
}
function countChangedDataKeys(data, initialData) {
  let changed = 0;
  for (const [key, value] of Object.entries(data)) {
    if (!Object.prototype.hasOwnProperty.call(initialData, key)) {
      changed++;
      continue;
    }
    try {
      if (JSON.stringify(value) !== JSON.stringify(initialData[key])) changed++;
    } catch {
      if (value !== initialData[key]) changed++;
    }
  }
  return changed;
}
function rememberInstanceState(instance, moduleId) {
  if (!instance?.data || typeof instance.data !== 'object') return;
  const data = cloneInstanceData(instance.data);
  const definitionData = definitions.get(moduleId)?.data;
  const initialData = definitionData && typeof definitionData === 'object' ? definitionData : {};
  const changedKeys = countChangedDataKeys(data, initialData);
  const previous = instanceSnapshots.get(instance) || moduleSnapshots.get(moduleId);
  if (!previous || changedKeys >= previous.changedKeys) {
    const snapshot = { changedKeys, data, moduleId };
    instanceSnapshots.set(instance, snapshot);
    moduleSnapshots.set(moduleId, snapshot);
  }
}
function trackInstance(instance, moduleId) {
  getInstances(moduleId).add(instance);
  if (instanceSnapshots.has(instance)) return;
  if ((wevuRefreshGenerations.get(moduleId) || 0) > 0) {
    rememberInstanceState(instance, moduleId);
    return;
  }
  const snapshot = moduleSnapshots.get(moduleId);
  if (snapshot) {
    instanceSnapshots.set(instance, snapshot);
    restoreInstanceState(instance, moduleId);
  } else {
    rememberInstanceState(instance, moduleId);
  }
}
function forgetInstance(instance, moduleId) {
  getInstances(moduleId).delete(instance);
  instanceSnapshots.delete(instance);
  if (!suppressLifecycles) moduleSnapshots.delete(moduleId);
}
function restoreInstanceState(instance, moduleId) {
  const snapshot = instanceSnapshots.get(instance);
  if (!snapshot || snapshot.moduleId !== moduleId) return;
  const data = cloneInstanceData(snapshot.data);
  if (instance.data && typeof instance.data === 'object') Object.assign(instance.data, data);
  if (typeof instance.setData === 'function') instance.setData(data);
}
function rememberTrackedInstances() {
  for (const [moduleId, values] of instances) {
    for (const instance of values) rememberInstanceState(instance, moduleId);
  }
}
function restoreTrackedInstances() {
  for (const [moduleId, values] of instances) {
    for (const instance of values) {
      const generation = wevuRefreshGenerations.get(moduleId) || 0;
      if (generation > 0 && wevuInstanceGenerations.get(instance)?.get(moduleId) === generation) continue;
      restoreInstanceState(instance, moduleId);
    }
  }
}
function refreshWevuInstance(instance, moduleId) {
  if (!instance || (typeof instance !== 'object' && typeof instance !== 'function')) return;
  const generation = wevuRefreshGenerations.get(moduleId) || 0;
  if (generation === 0) return;
  let generations = wevuInstanceGenerations.get(instance);
  if (generations?.get(moduleId) === generation) return;
  const refresh = wevuRefreshes.get(moduleId);
  if (typeof refresh !== 'function') return;
  restoreInstanceState(instance, moduleId);
  const snapshot = instanceSnapshots.get(instance) || moduleSnapshots.get(moduleId);
  refresh(instance, cloneInstanceData(snapshot?.data));
  rememberInstanceState(instance, moduleId);
  if (!generations) wevuInstanceGenerations.set(instance, generations = new Map());
  generations.set(moduleId, generation);
}
function proxyFunction(moduleId, path, fallback) {
  return function (...args) {
    if (suppressLifecycles && /(?:created|attached|ready|detached|onLoad|onShow|onHide|onUnload)$/.test(path)) return;
    const definition = definitions.get(moduleId);
    const segments = path.split('.');
    let value = definition;
    for (const segment of segments) value = value && value[segment];
    trackInstance(this, moduleId);
    try {
      return (typeof value === 'function' ? value : fallback)?.apply(this, args);
    } finally {
      rememberInstanceState(this, moduleId);
    }
  };
}
function decorateObject(value, moduleId, prefix = '', trackLifecycle = false) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
  const result = { ...value };
  for (const [key, child] of Object.entries(value)) {
    const path = prefix ? prefix + '.' + key : key;
    if (typeof child === 'function') result[key] = proxyFunction(moduleId, path, child);
    else if (child && typeof child === 'object' && ['lifetimes', 'methods', 'pageLifetimes'].includes(key)) {
      result[key] = decorateObject(child, moduleId, path);
    }
  }
  if (!prefix && typeof value.onLoad === 'function') {
    const onLoad = result.onLoad;
    result.onLoad = function (...args) {
      trackInstance(this, moduleId);
      return onLoad.apply(this, args);
    };
  }
  if (!prefix && (trackLifecycle || (result.lifetimes && typeof result.lifetimes === 'object'))) {
    const lifetimes = { ...(result.lifetimes || {}) };
    const attached = lifetimes.attached;
    const detached = lifetimes.detached;
    result.lifetimes = lifetimes;
    if (trackLifecycle || typeof attached === 'function') {
      result.lifetimes.attached = function (...args) {
        trackInstance(this, moduleId);
        return attached?.apply(this, args);
      };
    }
    if (trackLifecycle || typeof detached === 'function') {
      result.lifetimes.detached = function (...args) {
        try {
          return detached?.apply(this, args);
        } finally {
          forgetInstance(this, moduleId);
        }
      };
    }
  }
  return result;
}
function decorateWevuComponent(definition, moduleId) {
  const result = { ...definition };
  const resolveWevuDefinition = () => definitions.get(moduleId) || definition;
  const callLatestWevuFunction = (instance, path, fallback, args) => {
    const segments = path.split('.');
    let value = resolveWevuDefinition();
    for (const segment of segments) value = value && value[segment];
    return (typeof value === 'function' ? value : fallback)?.apply(instance, args);
  };
  const methods = { ...(definition.methods || {}) };
  for (const name of Object.keys(methods)) {
    const fallback = methods[name];
    if (typeof fallback !== 'function') continue;
    methods[name] = function (...args) {
      trackInstance(this, moduleId);
      refreshWevuInstance(this, moduleId);
      try {
        return callLatestWevuFunction(this, 'methods.' + name, fallback, args);
      } finally {
        rememberInstanceState(this, moduleId);
      }
    };
  }
  result.methods = methods;
  const pageHookNames = ['onLoad', 'onShow', 'onReady', 'onHide', 'onResize', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onShareTimeline', 'onAddToFavorites'];
  for (const name of pageHookNames) {
    const fallback = result[name];
    if (typeof fallback !== 'function') continue;
    result[name] = function (...args) {
      trackInstance(this, moduleId);
      refreshWevuInstance(this, moduleId);
      if (suppressLifecycles && /^(?:onLoad|onShow|onHide|onUnload)$/.test(name)) return;
      try {
        return callLatestWevuFunction(this, name, fallback, args);
      } finally {
        rememberInstanceState(this, moduleId);
        if (name === 'onUnload') forgetInstance(this, moduleId);
      }
    };
  }
  const lifetimes = { ...(definition.lifetimes || {}) };
  for (const name of Object.keys(lifetimes)) {
    const fallback = lifetimes[name];
    if (typeof fallback !== 'function') continue;
    lifetimes[name] = function (...args) {
      if (suppressLifecycles) return;
      if (name === 'created' || name === 'attached') {
        trackInstance(this, moduleId);
        refreshWevuInstance(this, moduleId);
      }
      try {
        return callLatestWevuFunction(this, 'lifetimes.' + name, fallback, args);
      } finally {
        if (name === 'detached') forgetInstance(this, moduleId);
      }
    };
  }
  const pageLifetimes = { ...(definition.pageLifetimes || {}) };
  for (const name of Object.keys(pageLifetimes)) {
    const fallback = pageLifetimes[name];
    if (typeof fallback !== 'function') continue;
    pageLifetimes[name] = function (...args) {
      trackInstance(this, moduleId);
      refreshWevuInstance(this, moduleId);
      try {
        return callLatestWevuFunction(this, 'pageLifetimes.' + name, fallback, args);
      } finally {
        rememberInstanceState(this, moduleId);
      }
    };
  }
  return { ...result, lifetimes, pageLifetimes };
}
function registerDefinition(name, definition, nativeRegistration) {
  const moduleId = runtime.currentModuleId || runtime.registrationModuleId || name;
  if (!runtime.applyingPatch && runtime.patchedModules.has(moduleId)) return;
  if (!wevuRefreshes.has(moduleId)) definitions.set(moduleId, definition);
  if (registered.has(moduleId)) {
    return;
  }
  if (name === 'Component') {
    let pending = pendingNativeDefinitions.get(name);
    if (!pending) pendingNativeDefinitions.set(name, pending = []);
    pending.push(decorateObject(definition, moduleId, '', true));
    registered.add(moduleId);
    return;
  }
  const original = nativeRegistration || nativeRegistrations[name];
  if (typeof original !== 'function') throw new Error(name + ' registration API is unavailable');
  registered.add(moduleId);
  return original.call(globalThis, decorateObject(definition, moduleId));
}
globalThis[bridgeKey] = {
  App(definition) { return registerDefinition('App', definition); },
  Page(definition) { return registerDefinition('Page', definition); },
  Component(definition, nativeRegistration) { return registerDefinition('Component', definition, nativeRegistration); },
  installNative(name, registration) {
    if (typeof registration === 'function') nativeRegistrations[name] = registration;
  },
  takeNativeDefinitions(name) {
    const pending = pendingNativeDefinitions.get(name) || [];
    pendingNativeDefinitions.delete(name);
    return pending;
  },
  isApplying() { return runtime.applyingPatch; },
  getDebugSnapshot() {
    return {
      definitions: [...definitions.keys()],
      instances: [...instances.entries()].map(([moduleId, values]) => ({ moduleId, count: values.size })),
      registered: [...registered.values()],
      refreshes: [...wevuRefreshes.keys()],
      refreshGenerations: [...wevuRefreshGenerations.entries()],
    };
  },
  trackWevuComponent(definition, refresh) {
    const moduleId = runtime.currentModuleId || runtime.registrationModuleId || 'Component';
    if (!runtime.applyingPatch && runtime.patchedModules.has(moduleId)) {
      return decorateWevuComponent(definition, moduleId);
    }
    definitions.set(moduleId, definition);
    if (typeof refresh === 'function') wevuRefreshes.set(moduleId, refresh);
    if (runtime.applyingPatch) {
      wevuRefreshGenerations.set(moduleId, (wevuRefreshGenerations.get(moduleId) || 0) + 1);
      for (const instance of [...getInstances(moduleId)]) refreshWevuInstance(instance, moduleId);
      return definition;
    }
    return decorateWevuComponent(definition, moduleId);
  },
  ready: true,
  beginUpdate() {
    suppressLifecycles = true;
    rememberTrackedInstances();
    runtime.beginPatch();
  },
  endUpdate() {
    runtime.endPatch();
    restoreTrackedInstances();
    setTimeout(() => { suppressLifecycles = false; });
  }
};
const runtimeGlobal = globalThis.wx || globalThis.my || globalThis.swan || globalThis.tt || globalThis.ali || globalThis.hd || globalThis.qq || globalThis.ks || globalThis.zfb || globalThis.jd || globalThis.xhs;
if (runtimeGlobal && !runtimeGlobal[bridgeKey]) runtimeGlobal[bridgeKey] = globalThis[bridgeKey];
`;
function createStatefulHmrControlSource(control) {
	return `
globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stringify(control)};
(() => {
  const control = globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}];
  globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}]?.stop?.();
  let version = 0;
  let phase = 'registering';
  let pendingBatch;
  let requestGeneration = 0;
  let activeRequest;
  let lastRequestError;
  let lastResponse;
  let timer;
  const sessionId = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
  const schedule = (delay) => {
    if (timer) clearTimeout(timer);
    const expectedPhase = phase;
    const expectedVersion = version;
    timer = setTimeout(() => {
      timer = undefined;
      if (phase !== expectedPhase || version !== expectedVersion) return;
      send(phase === 'registering' ? 'register' : 'poll');
    }, delay);
  };
  const send = (action) => {
    activeRequest?.abort?.();
    const generation = ++requestGeneration;
    activeRequest = wx.request({
      url: control.url,
      method: 'POST',
      data: { token: control.token, action, buildId: control.buildId, sessionId, version },
      timeout: 30000,
      success(result) {
        if (generation !== requestGeneration) return;
        activeRequest = undefined;
        lastRequestError = undefined;
        const type = result?.data?.type;
        lastResponse = { action, statusCode: result?.statusCode, type };
        if (action === 'register' && type === 'registered') {
          phase = 'polling';
          if (pendingBatch) globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}].receiveBatch(pendingBatch.meta, pendingBatch.apply);
          else send('poll');
        } else if (type === 'idle' || type === 'changed') send('poll');
        else if (type === 'batch-published') schedule(2000);
        else if (type === 'rebuilding') schedule(1000);
        else schedule(500);
      },
      fail(error) {
        if (generation !== requestGeneration) return;
        activeRequest = undefined;
        lastRequestError = {
          action,
          errMsg: String(error?.errMsg || ''),
          errno: error?.errno,
        };
        schedule(500);
      }
    });
  };
  const relaunch = () => {
    const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
    const page = pages[pages.length - 1];
    const route = page?.route || page?.__route__;
    if (!route) return send('poll');
    const query = Object.entries(page?.options || {})
      .filter(([, value]) => value !== undefined)
      .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(String(value)))
      .join('&');
    wx.reLaunch({ url: '/' + route + (query ? '?' + query : ''), complete: () => send('poll') });
  };
  globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}] = {
    lastApply: undefined,
    getVersion() { return version; },
    getLastApply() { return this.lastApply; },
    getTransportState() { return { phase, version, lastRequestError, lastResponse }; },
    stop() {
      phase = 'stopped';
      if (timer) {
        clearTimeout(timer);
        timer = undefined;
      }
      activeRequest?.abort?.();
      activeRequest = undefined;
    },
    applyChangedModules(changedIds) {
      const runtime = globalThis.__rolldown_runtime__;
      if (!runtime || !Array.isArray(changedIds)) return;
      const uniqueIds = [...new Set(changedIds.filter((id) => typeof id === 'string'))];
      const summary = { changedIds: uniqueIds, initialized: [], missing: [], executedBefore: [], executedAfterRemove: [] };
      for (const id of uniqueIds) {
        if (typeof runtime.isExecuted === 'function' && runtime.isExecuted(id)) summary.executedBefore.push(id);
        if (typeof runtime.removeModuleCache === 'function') runtime.removeModuleCache.call(runtime, id);
        if (typeof runtime.isExecuted === 'function' && runtime.isExecuted(id)) summary.executedAfterRemove.push(id);
      }
      for (const id of uniqueIds) {
        if (typeof runtime.hasFactory === 'function' && !runtime.hasFactory(id)) {
          summary.missing.push(id);
          continue;
        }
        if (typeof runtime.initModule === 'function') runtime.initModule.call(runtime, id);
        summary.initialized.push(id);
      }
      this.lastApply = summary;
    },
    receiveBatch(meta, apply) {
      if (phase === 'registering') {
        pendingBatch = { meta, apply };
        return;
      }
      pendingBatch = undefined;
      if (phase !== 'polling' || meta.buildId !== control.buildId || meta.fromVersion !== version) return send('poll');
      phase = 'applying';
      const bridge = globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}];
      if (!bridge?.ready) {
        phase = 'polling';
        return send('rebuild');
      }
      bridge.beginUpdate?.();
      try {
        apply();
        globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}].applyChangedModules(meta.changedIds);
        version = meta.targetVersion;
        phase = meta.compatible === false ? 'relaunching' : 'polling';
      } catch (error) {
        console.error('[weapp-vite] stateful HMR patch failed', error);
        phase = 'polling';
        return send('rebuild');
      } finally {
        bridge.endUpdate?.();
      }
      if (phase === 'relaunching') relaunch();
      else send('poll');
    }
  };
  send('register');
})();
`;
}
//#endregion
//#region src/runtime/statefulHmr/commonRuntime.ts
const require$1 = createRequire(import.meta.url);
const STATIC_IMPORT_RE = /^import\s+(?:\{[^}\n]*\}|[A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"](?:;\s*)?$/gm;
const EXPORT_PREFIX_RE = /^export\s+/gm;
const STATEFUL_HMR_RUNTIME_COMPATIBILITY_ERROR_CODE = "WEAPP_VITE_STATEFUL_HMR_RUNTIME_INCOMPATIBLE";
var StatefulHmrRuntimeCompatibilityError = class extends Error {
	code = STATEFUL_HMR_RUNTIME_COMPATIBILITY_ERROR_CODE;
	constructor(message) {
		super(message);
		this.name = "StatefulHmrRuntimeCompatibilityError";
	}
};
function readRolldownRuntimeSource(subpath) {
	try {
		const filePath = require$1.resolve(subpath);
		return {
			filePath,
			source: readFileSync(filePath, "utf8")
		};
	} catch (error) {
		throw new StatefulHmrRuntimeCompatibilityError(`无法读取 Rolldown 状态保持 HMR 基础运行时 ${subpath}:${error instanceof Error ? error.message : String(error)}`);
	}
}
function stripModuleSyntax(source) {
	return source.replace(STATIC_IMPORT_RE, "").replace(EXPORT_PREFIX_RE, "");
}
function resolveRuntimeHelpers(runtime) {
	return [...runtime.source.matchAll(STATIC_IMPORT_RE)].map((match) => match[1]).filter((specifier) => Boolean(specifier && specifier.startsWith("."))).map((specifier) => {
		const helperPath = path$1.resolve(path$1.dirname(runtime.filePath), specifier);
		try {
			return readFileSync(helperPath, "utf8");
		} catch (error) {
			throw new StatefulHmrRuntimeCompatibilityError(`无法读取 Rolldown dev runtime helper ${specifier}:${error instanceof Error ? error.message : String(error)}`);
		}
	}).map(stripModuleSyntax).join("\n");
}
function assertRolldownRuntimeContract(runtime, helpers) {
	const missing = [
		[
			runtime.source,
			/(?:class\s+DevRuntime|(?:var|let|const)\s+DevRuntime\s*=)/,
			"DevRuntime"
		],
		[
			runtime.source,
			/(?:class\s+Module|(?:var|let|const)\s+Module\s*=)/,
			"Module"
		],
		[
			helpers,
			/(?:var|let|const)\s+__exportAll\s*=|function\s+__exportAll\b/,
			"common runtime helpers"
		]
	].filter(([source, pattern]) => !pattern.test(source));
	if (missing.length > 0) throw new StatefulHmrRuntimeCompatibilityError(`Rolldown dev runtime ${runtime.filePath} 缺少稳定契约:${missing.map(([, , name]) => name).join("、")}。`);
}
function composeStatefulHmrRuntimeSource(runtime, helpers) {
	assertRolldownRuntimeContract(runtime, helpers);
	return `${helpers}\n${stripModuleSyntax(runtime.source)}\n${statefulHmrRolldownRuntimeSource}`;
}
function createStatefulHmrRolldownRuntimeSource() {
	const runtime = readRolldownRuntimeSource("rolldown/experimental/runtime");
	return composeStatefulHmrRuntimeSource(runtime, resolveRuntimeHelpers(runtime));
}
function assertStatefulHmrRuntimeOutput(output) {
	const runtime = output.find((item) => item.type === "chunk" && item.fileName === "rolldown-runtime.js");
	if (!runtime || runtime.type !== "chunk") throw new StatefulHmrRuntimeCompatibilityError("stateful HMR 初始构建未生成 rolldown-runtime.js。");
	const missing = [
		/(?:class|var) DevRuntime(?:\s*=\s*class)?/,
		/(?:class|var) WeappViteDevRuntime(?:\s*=\s*class)?/,
		"new WeappViteDevRuntime",
		"__WEAPP_VITE_STATEFUL_HMR_BRIDGE__"
	].filter((contract) => typeof contract === "string" ? !runtime.code.includes(contract) : !contract.test(runtime.code));
	if (missing.length > 0) throw new StatefulHmrRuntimeCompatibilityError(`stateful HMR runtime 不完整,缺少 ${missing.length} 项必要契约。`);
}
function isStatefulHmrRuntimeCompatibilityError(error) {
	return error instanceof StatefulHmrRuntimeCompatibilityError || typeof error === "object" && error !== null && Reflect.get(error, "code") === "WEAPP_VITE_STATEFUL_HMR_RUNTIME_INCOMPATIBLE";
}
//#endregion
//#region src/plugins/react/baseTemplate.ts
const MAX_TEMPLATE_DEPTH = 4;
function renderHostAttributes(tag) {
	const common = "id=\"{{i.p.id}}\" class=\"{{i.cl}}\" style=\"{{i.st}}\" data-sid=\"{{i.sid}}\"";
	if (tag === "button") return `${common} disabled="{{i.p.disabled}}" bindtap="${WEAPP_REACT_EVENT_METHOD_NAME}"`;
	if (tag === "input") return `${common} value="{{i.p.value}}" type="{{i.p.type}}" checked="{{i.p.checked}}" disabled="{{i.p.disabled}}" placeholder="{{i.p.placeholder}}" bindinput="${WEAPP_REACT_EVENT_METHOD_NAME}" bindchange="${WEAPP_REACT_EVENT_METHOD_NAME}"`;
	return `${common} hidden="{{i.p.hidden}}" bindtap="${WEAPP_REACT_EVENT_METHOD_NAME}"`;
}
function renderHost(tag, depth) {
	const attributes = renderHostAttributes(tag);
	if (tag === "input" || depth === MAX_TEMPLATE_DEPTH) return `  <${tag} wx:elif="{{i.nn === '${tag}'}}" ${attributes} />`;
	return [
		`  <${tag} wx:elif="{{i.nn === '${tag}'}}" ${attributes}>`,
		"    <block wx:for=\"{{i.cn}}\" wx:key=\"sid\" wx:for-item=\"child\">",
		`      <template is="react_node_${depth + 1}" data="{{i:child}}" />`,
		"    </block>",
		`  </${tag}>`
	].join("\n");
}
function renderNodeTemplate(depth) {
	return [
		`<template name="react_node_${depth}">`,
		"  <block wx:if=\"{{i.nn === '#text'}}\">{{i.v}}</block>",
		renderHost("view", depth),
		renderHost("text", depth),
		renderHost("button", depth),
		renderHost("input", depth),
		"</template>"
	].join("\n");
}
const baseTemplate = [
	"<template name=\"react_root\">",
	"  <block wx:for=\"{{root.cn}}\" wx:key=\"sid\" wx:for-item=\"child\">",
	"    <template is=\"react_node_0\" data=\"{{i:child}}\" />",
	"  </block>",
	"</template>",
	"",
	...Array.from({ length: 5 }, (_, depth) => renderNodeTemplate(depth)),
	""
].join("\n");
//#endregion
//#region src/plugins/react/staticTemplate/style.ts
const UNITLESS_STYLE_PROPERTIES = /* @__PURE__ */ new Set([
	"flex",
	"flexGrow",
	"flexShrink",
	"fontWeight",
	"lineHeight",
	"opacity",
	"order",
	"zIndex"
]);
function toKebabCase$2(value) {
	return value.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
}
function readPropertyName(node) {
	if (t.isIdentifier(node)) return node.name;
	if (t.isStringLiteral(node)) return node.value;
}
function readPropertyValue(node) {
	if (t.isStringLiteral(node) || t.isNumericLiteral(node)) return node.value;
}
function compileStaticStyle(expression) {
	const declarations = [];
	for (const property of expression.properties) {
		if (!t.isObjectProperty(property) || property.computed) return;
		const name = readPropertyName(property.key);
		const value = readPropertyValue(property.value);
		if (!name || value === void 0) return;
		const normalized = typeof value === "number" && !UNITLESS_STYLE_PROPERTIES.has(name) ? `${value}px` : String(value);
		declarations.push(`${toKebabCase$2(name)}:${normalized}`);
	}
	return declarations.join(";");
}
//#endregion
//#region src/plugins/react/staticTemplate/render.ts
const HOST_TAGS = {
	Button: "button",
	Input: "input",
	Text: "text",
	View: "view",
	button: "button",
	input: "input",
	text: "text",
	view: "view"
};
const EVENT_NAMES = {
	onChange: "bindchange",
	onInput: "bindinput",
	onTap: "bindtap",
	onTapCapture: "capture-bind:tap"
};
const EVENT_PROP_RE = /^on[A-Z]/;
const IDENTIFIER_RE$1 = /^[A-Z_$][\w$]*$/i;
function normalizeJsxText(value) {
	return value.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).join(" ");
}
function readTagName(node, context) {
	if (!t.isJSXIdentifier(node)) throw new Error("static template 暂不支持 member/namespaced JSX tag");
	const tag = HOST_TAGS[node.name];
	if (tag) return {
		kind: "host",
		tag
	};
	if (context.slotComponentNames.has(node.name) || node.name === "slot") return {
		kind: "slot",
		tag: "slot"
	};
	const nativeTag = context.nativeComponentTags.get(node.name);
	if (nativeTag) {
		context.usedNativeComponents.add(nativeTag);
		return {
			kind: "native",
			tag: nativeTag
		};
	}
	throw new Error(`static template 暂不支持动态组件 <${node.name}>`);
}
function readAttributeExpression(attribute) {
	if (!attribute.value) return t.booleanLiteral(true);
	if (t.isStringLiteral(attribute.value)) return attribute.value;
	if (!t.isJSXExpressionContainer(attribute.value) || t.isJSXEmptyExpression(attribute.value.expression)) return;
	return attribute.value.expression;
}
function readStaticPrimitive(expression) {
	if (t.isStringLiteral(expression) || t.isNumericLiteral(expression) || t.isBooleanLiteral(expression)) return expression.value;
	if (t.isTemplateLiteral(expression) && expression.expressions.length === 0) return expression.quasis[0]?.value.cooked ?? "";
}
function appendInternalAttribute(element, name, value) {
	element.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(name), t.stringLiteral(value)));
}
function toKebabCase$1(value) {
	return value.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
}
function resolveNativeEvent(name) {
	if (!EVENT_PROP_RE.test(name)) return;
	const capture = name.endsWith("Capture");
	const eventName = name.slice(2, capture ? -7 : void 0);
	if (!eventName) return;
	return `${capture ? "capture-bind" : "bind"}:${toKebabCase$1(eventName)}`;
}
function renderBindingExpression(slot, name) {
	return IDENTIFIER_RE$1.test(name) ? `slots.${slot}.${name}` : `slots.${slot}['${name}']`;
}
function compileAttributes(element, slot, bindingFields, tagKind) {
	const output = [];
	let hasEvent = false;
	for (const attribute of element.openingElement.attributes) {
		if (!t.isJSXAttribute(attribute) || !t.isJSXIdentifier(attribute.name)) throw new Error("static template 暂不支持 JSX spread 或动态属性名");
		const name = attribute.name.name;
		if (name === "key") continue;
		const eventName = tagKind === "native" ? resolveNativeEvent(name) : EVENT_NAMES[name];
		if (eventName) {
			hasEvent = true;
			output.push(`${eventName}="${WEAPP_REACT_EVENT_METHOD_NAME}"`);
			continue;
		}
		if (EVENT_PROP_RE.test(name)) throw new Error(`static template 暂不支持事件 ${name}`);
		const expression = readAttributeExpression(attribute);
		if (!expression) continue;
		const outputName = name === "className" ? "class" : name;
		if (name === "style" && t.isObjectExpression(expression)) {
			const style = compileStaticStyle(expression);
			if (style !== void 0) {
				output.push(`style="${escapeWxmlAttribute(style)}"`);
				continue;
			}
		}
		const staticValue = readStaticPrimitive(expression);
		if (staticValue !== void 0) {
			output.push(`${outputName}="${escapeWxmlAttribute(String(staticValue))}"`);
			continue;
		}
		bindingFields.add(name);
		output.push(`${outputName}="{{${renderBindingExpression(slot, name)}}}"`);
	}
	if (hasEvent) output.push(`data-sid="${slot}"`);
	return output;
}
function isDynamicTextExpression(node) {
	return !t.isJSXEmptyExpression(node.expression) && readStaticPrimitive(node.expression) === void 0;
}
function compileStaticChildren(children, context) {
	return children.map((child) => {
		if (t.isJSXText(child)) return escapeWxmlText(normalizeJsxText(child.value));
		if (t.isJSXElement(child)) return compileStaticElement(child, context);
		if (t.isJSXFragment(child)) return compileStaticFragment(child, context);
		if (t.isJSXExpressionContainer(child)) {
			if (t.isJSXEmptyExpression(child.expression)) return "";
			const value = readStaticPrimitive(child.expression);
			if (value !== void 0) return escapeWxmlText(String(value));
			throw new Error("static template 的容器节点暂不支持动态结构表达式");
		}
		return "";
	}).join("");
}
function compileStaticFragment(fragment, context) {
	return compileStaticChildren(fragment.children, context);
}
function compileStaticElement(element, context) {
	const resolvedTag = readTagName(element.openingElement.name, context);
	const { tag } = resolvedTag;
	const slot = `s${context.slotSeed++}`;
	const bindingFields = /* @__PURE__ */ new Set();
	const slotRecord = {
		bindings: [],
		id: slot,
		tag
	};
	context.slots.push(slotRecord);
	const attributes = compileAttributes(element, slot, bindingFields, resolvedTag.kind);
	const children = element.children;
	const hasDynamicText = (tag === "text" || tag === "button") && children.some((child) => t.isJSXExpressionContainer(child) && isDynamicTextExpression(child));
	let content;
	if (hasDynamicText) {
		if (children.some((child) => t.isJSXElement(child) || t.isJSXFragment(child))) throw new Error(`static template 的 <${tag}> 不支持动态文本与元素子节点混用`);
		bindingFields.add("text");
		content = `{{slots.${slot}.text}}`;
	} else content = compileStaticChildren(children, context);
	appendInternalAttribute(element, "__slot", slot);
	if (bindingFields.size > 0) appendInternalAttribute(element, "__bindingFields", [...bindingFields].join(","));
	slotRecord.bindings = [...bindingFields];
	const attributeSegment = attributes.length > 0 ? ` ${attributes.join(" ")}` : "";
	if (resolvedTag.kind === "slot" && children.length > 0) throw new Error("static template 的 <Slot> 不支持子节点");
	if (element.openingElement.selfClosing) return `<${tag}${attributeSegment} />`;
	return `<${tag}${attributeSegment}>${content}</${tag}>`;
}
function renderStaticTemplate(root, context) {
	return t.isJSXElement(root) ? compileStaticElement(root, context) : compileStaticFragment(root, context);
}
//#endregion
//#region src/plugins/react/staticTemplate/index.ts
const REACT_RUNTIME_MODULE_ID = "@weapp-vite/react";
var ReactNativeBridgeStaticError = class extends Error {
	constructor(filename, cause) {
		const message = cause instanceof Error ? cause.message : String(cause);
		super(`[react] ${filename} 使用了原生组件 bridge,组件结构必须可静态分析:${message}`, { cause });
		this.name = "ReactNativeBridgeStaticError";
	}
};
function collectRuntimeImportNames(ast, importedName) {
	const names = /* @__PURE__ */ new Set();
	for (const statement of ast.program.body) {
		if (!t.isImportDeclaration(statement) || statement.source.value !== REACT_RUNTIME_MODULE_ID) continue;
		for (const specifier of statement.specifiers) if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, { name: importedName })) names.add(specifier.local.name);
	}
	return names;
}
function collectNativeComponentTags(ast, factoryNames) {
	const tags = /* @__PURE__ */ new Map();
	for (const statement of ast.program.body) {
		const declaration = t.isVariableDeclaration(statement) ? statement : t.isExportNamedDeclaration(statement) && t.isVariableDeclaration(statement.declaration) ? statement.declaration : void 0;
		if (!declaration) continue;
		for (const item of declaration.declarations) {
			if (!t.isIdentifier(item.id) || !t.isCallExpression(item.init) || !t.isIdentifier(item.init.callee) || !factoryNames.has(item.init.callee.name)) continue;
			const [tagArgument] = item.init.arguments;
			if (!t.isStringLiteral(tagArgument) || !tagArgument.value) throw new Error("createNativeComponent 的 tagName 必须是非空字符串字面量");
			tags.set(item.id.name, tagArgument.value);
		}
	}
	return tags;
}
function collectNativeBridgeContext(ast) {
	return {
		nativeComponentTags: collectNativeComponentTags(ast, collectRuntimeImportNames(ast, "createNativeComponent")),
		slotComponentNames: collectRuntimeImportNames(ast, "Slot")
	};
}
function hasNativeComponentBridge(source) {
	return collectNativeBridgeContext(parse$2(source, BABEL_TS_MODULE_PARSER_OPTIONS)).nativeComponentTags.size > 0;
}
function findFunctionDeclaration(ast, componentName) {
	for (const statement of ast.program.body) {
		if (t.isFunctionDeclaration(statement) && statement.id?.name === componentName) return statement;
		if (t.isExportNamedDeclaration(statement) && t.isFunctionDeclaration(statement.declaration) && statement.declaration.id?.name === componentName) return statement.declaration;
	}
}
function findReturnedTemplate(component) {
	for (const statement of component.body.body) {
		if (!t.isReturnStatement(statement) || !statement.argument) continue;
		if (t.isJSXElement(statement.argument) || t.isJSXFragment(statement.argument)) return statement.argument;
	}
}
function findFirstFunctionDeclaration(ast) {
	for (const statement of ast.program.body) {
		const candidate = t.isFunctionDeclaration(statement) ? statement : t.isExportNamedDeclaration(statement) && t.isFunctionDeclaration(statement.declaration) ? statement.declaration : void 0;
		if (candidate?.id && findReturnedTemplate(candidate)) return candidate;
	}
}
function compileStaticReactPage(source, filename, componentName) {
	const ast = parse$2(source, BABEL_TS_MODULE_PARSER_OPTIONS);
	const bridgeContext = collectNativeBridgeContext(ast);
	try {
		const component = componentName ? findFunctionDeclaration(ast, componentName) : findFirstFunctionDeclaration(ast);
		if (!component) throw new Error(`未找到直接 return JSX 的 static template 组件${componentName ? ` ${componentName}` : ""}`);
		const root = findReturnedTemplate(component);
		if (!root) throw new Error(`static template 组件 ${componentName ?? component.id?.name ?? ""} 必须直接 return JSX`);
		const context = {
			...bridgeContext,
			slots: [],
			slotSeed: 0,
			usedNativeComponents: /* @__PURE__ */ new Set()
		};
		const template = renderStaticTemplate(root, context);
		return {
			code: generate(ast, {
				sourceFileName: filename,
				sourceMaps: true
			}, source).code,
			nativeComponents: [...context.usedNativeComponents].sort(),
			slots: context.slots,
			template
		};
	} catch (error) {
		if (bridgeContext.nativeComponentTags.size > 0 && !(error instanceof ReactNativeBridgeStaticError)) throw new ReactNativeBridgeStaticError(filename, error);
		throw error;
	}
}
//#endregion
//#region src/plugins/react/index.ts
const REACT_PLUGIN_NAME = "weapp-vite:react";
const REACT_FILE_RE = /\.(?:jsx|tsx)(?:\?.*)?$/;
function resolveStaticTemplateFileName(cwd, id) {
	const cleanId = id.split("?", 1)[0] ?? id;
	let fileName = path$1.relative(cwd, cleanId).replaceAll("\\", "/").replace(/\.(?:jsx|tsx)$/, ".wxml").replace(/^src\//, "");
	if (fileName.endsWith("/view.wxml")) fileName = fileName.replace(/\/view\.wxml$/, "/index.wxml");
	return fileName;
}
function createDynamicTemplate(fileName) {
	const relative = path$1.posix.relative(path$1.posix.dirname(fileName), "runtime/base.wxml");
	return `<import src="${relative.startsWith(".") ? relative : `./${relative}`}" />\n<template is="react_root" data="{{root:root}}" />`;
}
function resolveReactConfig(value) {
	if (!value) return;
	return value === true ? {} : value;
}
function isReactEnabled(ctx) {
	return Boolean(resolveReactConfig(ctx.configService?.weappViteConfig?.react));
}
function resolveReactConfigValue(value) {
	const config = resolveReactConfig(value);
	if (!config) return;
	return {
		compiler: config.compiler ?? false,
		renderMode: config.renderMode ?? "auto",
		devWarnings: config.devWarnings ?? true
	};
}
function isReactStaticTemplateSource(value, id) {
	const config = resolveReactConfigValue(value);
	return Boolean(config && config.renderMode !== "dynamic" && REACT_FILE_RE.test(id) && !id.includes("/node_modules/"));
}
async function transformWithSwc$1(source, id, compilationMode) {
	try {
		const { transform } = await import("@swc/core");
		const result = await transform(source, {
			filename: id,
			jsc: {
				parser: {
					syntax: "typescript",
					tsx: true
				},
				target: "es2020",
				transform: {
					react: {
						importSource: "react",
						runtime: "automatic"
					},
					reactCompiler: { compilationMode }
				}
			},
			module: { type: "es6" },
			sourceMaps: true
		});
		return {
			code: result.code,
			map: result.map
		};
	} catch (error) {
		return {
			fallback: true,
			warning: `[react] React Compiler transform failed for ${id}; falling back to Oxc: ${error instanceof Error ? error.message : String(error)}`
		};
	}
}
function createReactPlugin(ctx) {
	const resolved = resolveReactConfigValue(ctx.configService?.weappViteConfig?.react);
	if (!resolved) return [];
	const reactConfig = resolved;
	let config;
	const templates = /* @__PURE__ */ new Map();
	async function refreshStaticTemplate(id, event, warn) {
		if (!isReactStaticTemplateSource(reactConfig, id)) return;
		const cleanId = id.split("?", 1)[0] ?? id;
		const fileName = resolveStaticTemplateFileName(ctx.configService?.cwd ?? process.cwd(), cleanId);
		if (event === "delete") {
			templates.delete(fileName);
			return;
		}
		try {
			const compiled = compileStaticReactPage(await readFile(cleanId, "utf8"), cleanId);
			templates.set(fileName, {
				nativeComponents: compiled.nativeComponents,
				source: compiled.template
			});
		} catch (error) {
			if (error instanceof ReactNativeBridgeStaticError) throw error;
			if (reactConfig.renderMode === "static") throw error;
			templates.set(fileName, {
				nativeComponents: [],
				source: createDynamicTemplate(fileName)
			});
			if (reactConfig.devWarnings && error instanceof Error) warn(`[react] dynamic island fallback for ${cleanId}: ${error.message}`);
		}
	}
	return [{
		name: REACT_PLUGIN_NAME,
		enforce: "pre",
		configResolved(next) {
			config = next;
		},
		async watchChange(id, change) {
			await refreshStaticTemplate(id, change.event, (message) => this.warn(message));
		},
		async handleHotUpdate(context) {
			await refreshStaticTemplate(context.file, "update", (message) => this.warn(message));
		},
		transform: async function transformReact(source, id) {
			if (!REACT_FILE_RE.test(id) || id.includes("/node_modules/")) return null;
			let transformedSource = source;
			const fileName = resolveStaticTemplateFileName(ctx.configService?.cwd ?? process.cwd(), id);
			if (resolved.renderMode === "dynamic" && hasNativeComponentBridge(source)) throw new Error(`[react] ${id} 使用了原生组件 bridge,renderMode: 'dynamic' 不支持自定义组件`);
			if (resolved.renderMode !== "dynamic") try {
				const compiled = compileStaticReactPage(source, id);
				templates.set(fileName, {
					nativeComponents: compiled.nativeComponents,
					source: compiled.template
				});
				transformedSource = compiled.code;
			} catch (error) {
				if (resolved.renderMode === "static" || error instanceof ReactNativeBridgeStaticError) throw error;
				templates.set(fileName, {
					nativeComponents: [],
					source: createDynamicTemplate(fileName)
				});
				if (resolved.devWarnings && error instanceof Error) this.warn(`[react] dynamic island fallback for ${id}: ${error.message}`);
			}
			else templates.set(fileName, {
				nativeComponents: [],
				source: createDynamicTemplate(fileName)
			});
			if (resolved.compiler !== false) {
				const compilerConfig = typeof resolved.compiler === "object" ? resolved.compiler : {};
				const result = await transformWithSwc$1(transformedSource, id, compilerConfig.compilationMode ?? "infer");
				if (!result.fallback) return result;
				if (resolved.devWarnings !== false) this.warn(result.warning);
			}
			return await transformWithOxc(transformedSource, id, {
				jsx: {
					importSource: "react",
					runtime: "automatic"
				},
				lang: "tsx",
				sourcemap: Boolean(config?.command === "serve")
			});
		},
		generateBundle(_options, bundle) {
			for (const [fileName, template] of templates) {
				if (template.nativeComponents.length > 0) {
					const jsonFileName = fileName.replace(/\.wxml$/, ".json");
					const jsonAsset = bundle[jsonFileName];
					if (jsonAsset?.type !== "asset") throw new Error(`[react] ${fileName} 使用了原生组件 bridge,但缺少对应配置 ${jsonFileName}`);
					let json;
					try {
						json = JSON.parse(String(jsonAsset.source));
					} catch (error) {
						throw new Error(`[react] 无法解析原生组件配置 ${jsonFileName}`, { cause: error });
					}
					const usingComponents = json.usingComponents;
					const registered = usingComponents && typeof usingComponents === "object" && !Array.isArray(usingComponents) ? usingComponents : {};
					const missing = template.nativeComponents.filter((tag) => typeof registered[tag] !== "string");
					if (missing.length > 0) throw new Error(`[react] ${fileName} 的原生组件 bridge 未在 ${jsonFileName} 的 usingComponents 注册:${missing.join(", ")}`);
				}
				const existing = bundle[fileName];
				if (existing?.type === "asset") existing.source = template.source;
				else this.emitFile({
					type: "asset",
					fileName,
					source: template.source
				});
			}
			if (resolved.renderMode !== "static" && !bundle["runtime/base.wxml"]) this.emitFile({
				type: "asset",
				fileName: "runtime/base.wxml",
				source: baseTemplate
			});
		}
	}];
}
//#endregion
//#region src/runtime/statefulHmr/outputWriter.ts
/**
* @description 通过独立的 Vite write 阶段持久化 DevEngine 已生成的文件,不重新解析业务源码。
*/
async function writeStatefulHmrOutput(outDir, output) {
	const virtualEntry = "\0weapp-vite-stateful-hmr-output";
	await build({
		configFile: false,
		logLevel: "silent",
		build: {
			emptyOutDir: false,
			minify: false,
			outDir,
			rolldownOptions: { input: virtualEntry },
			write: true
		},
		plugins: [{
			name: "weapp-vite:stateful-hmr-output-writer",
			resolveId(id) {
				return id === virtualEntry ? virtualEntry : void 0;
			},
			load(id) {
				return id === virtualEntry ? "export {}" : void 0;
			},
			buildStart() {
				for (const item of output) this.emitFile({
					type: "asset",
					fileName: item.fileName.replaceAll("\\", "/"),
					source: item.type === "chunk" ? item.code : item.source
				});
			},
			generateBundle(_options, bundle) {
				for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk" && item.facadeModuleId === virtualEntry) delete bundle[fileName];
			}
		}],
		root: path$1.dirname(outDir)
	});
}
//#endregion
//#region src/runtime/statefulHmr/sidecarPlugin.ts
function createStatefulHmrSidecarModuleCode(id, source) {
	const request = parseSidecarSourceRequest(id);
	if (!request || request.kind === "style") return;
	const digest = createHash("sha256").update(source).digest("hex");
	return `export default ${JSON.stringify(digest)};\n`;
}
function createStatefulHmrSidecarPlugin() {
	return {
		name: "weapp-vite:stateful-hmr-sidecar",
		enforce: "pre",
		async load(id) {
			if (id.includes("\0")) return;
			const request = parseSidecarSourceRequest(id);
			if (!request) return;
			this.addWatchFile(request.sourceId);
			const source = await readFile(request.sourceId, "utf8");
			if (request.kind === "style") return source;
			const code = createStatefulHmrSidecarModuleCode(id, source);
			return code ? {
				code,
				moduleSideEffects: "no-treeshake"
			} : void 0;
		}
	};
}
//#endregion
//#region src/runtime/statefulHmr/snapshotScheduler.ts
const DEFAULT_SNAPSHOT_DEBOUNCE_MS = 40;
var StatefulHmrSnapshotScheduler = class {
	closed = false;
	debounceMs;
	execute;
	onError;
	pendingFiles = /* @__PURE__ */ new Set();
	pendingMode;
	revision = 0;
	runningPromise;
	timer;
	constructor(options) {
		this.debounceMs = options.debounceMs ?? DEFAULT_SNAPSHOT_DEBOUNCE_MS;
		this.execute = options.execute;
		this.onError = options.onError;
	}
	request(mode, files = []) {
		if (this.closed) return;
		for (const file of files) this.pendingFiles.add(file);
		this.pendingMode = this.pendingMode === "full" || mode === "full" ? "full" : "refresh";
		this.revision += 1;
		if (!this.runningPromise) this.schedule();
	}
	isPending() {
		return Boolean(this.timer || this.runningPromise || this.pendingMode);
	}
	async close() {
		this.closed = true;
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = void 0;
		}
		this.pendingFiles.clear();
		this.pendingMode = void 0;
		await this.runningPromise;
	}
	schedule() {
		if (this.closed) return;
		if (this.timer) clearTimeout(this.timer);
		this.timer = setTimeout(() => {
			this.timer = void 0;
			this.startPendingBatch();
		}, this.debounceMs);
	}
	startPendingBatch() {
		if (this.closed || this.runningPromise || !this.pendingMode) return;
		const batchRevision = this.revision;
		const batchFiles = [...this.pendingFiles];
		const batchMode = this.pendingMode;
		this.pendingFiles.clear();
		this.pendingMode = void 0;
		const isSuperseded = () => this.closed || this.revision !== batchRevision;
		this.runningPromise = this.execute({
			files: batchFiles,
			isSuperseded,
			mode: batchMode
		}).catch((error) => this.onError?.(error)).finally(() => {
			if (!this.closed && isSuperseded()) {
				for (const file of batchFiles) this.pendingFiles.add(file);
				this.pendingMode = this.pendingMode === "full" || batchMode === "full" ? "full" : "refresh";
			}
			this.runningPromise = void 0;
			if (this.pendingMode) this.schedule();
		});
	}
};
//#endregion
//#region src/runtime/statefulHmr/serverState.ts
function createStatefulHmrServerState(buildId) {
	return {
		buildId,
		deltas: [],
		hostVersion: 0,
		retainedDeltaBytes: 0,
		retiredSessionIds: []
	};
}
function transitionStatefulHmrServer(state, event) {
	switch (event.type) {
		case "delta-added": {
			const version = state.hostVersion + 1;
			return unchanged({
				...state,
				deltas: [...state.deltas, {
					changedIds: event.changedIds,
					code: event.code,
					version
				}],
				hostVersion: version,
				retainedDeltaBytes: state.retainedDeltaBytes + event.bytes
			});
		}
		case "client-registered": return registerClient(state, event);
		case "client-reported": return reportClient(state, event);
		case "batch-publish-failed":
			if (state.inFlight?.sessionId !== event.sessionId || state.inFlight.targetVersion !== event.targetVersion) return unchanged(state);
			return unchanged({
				...state,
				inFlight: void 0
			});
		case "full-build-committed": return unchanged(createStatefulHmrServerState(event.buildId));
	}
}
function registerClient(state, client) {
	const rejected = rejectClient(state, client);
	if (rejected) return rejected;
	if (state.retiredSessionIds.includes(client.sessionId)) return withCommand(state, {
		type: "ignore-client",
		reason: "retired-session"
	});
	if (state.activeSessionId === client.sessionId) return unchanged(state);
	const retiredSessionIds = state.activeSessionId ? [.../* @__PURE__ */ new Set([...state.retiredSessionIds, state.activeSessionId])] : state.retiredSessionIds;
	return unchanged({
		...state,
		activeSessionId: client.sessionId,
		inFlight: void 0,
		retiredSessionIds
	});
}
function reportClient(state, client) {
	const rejected = rejectClient(state, client);
	if (rejected) return rejected;
	if (state.retiredSessionIds.includes(client.sessionId)) return withCommand(state, {
		type: "ignore-client",
		reason: "retired-session"
	});
	if (client.sessionId !== state.activeSessionId) return withCommand(state, {
		type: "ignore-client",
		reason: "unknown-session"
	});
	return synchronizeClient(state, client.version);
}
function rejectClient(state, client) {
	if (client.buildId !== state.buildId) return withCommand(state, {
		type: "ignore-client",
		reason: "stale-build"
	});
	if (!Number.isInteger(client.version) || client.version < 0) return withCommand(state, {
		type: "request-full-build",
		reason: "invalid-client-version"
	});
	if (client.version > state.hostVersion) return withCommand(state, {
		type: "request-full-build",
		reason: "client-version-ahead"
	});
}
function synchronizeClient(state, clientVersion) {
	let synchronized = state;
	if (state.inFlight) {
		if (clientVersion === state.inFlight.fromVersion) return publishMissingRange(state, clientVersion, state.inFlight.targetVersion);
		if (clientVersion !== state.inFlight.targetVersion) return withCommand(state, {
			type: "request-full-build",
			reason: "invalid-client-version"
		});
		synchronized = {
			...state,
			inFlight: void 0
		};
	}
	if (clientVersion >= synchronized.hostVersion) return unchanged(synchronized);
	return publishMissingRange(synchronized, clientVersion, synchronized.hostVersion, true);
}
function publishMissingRange(state, fromVersion, targetVersion, trackInFlight = false) {
	const deltas = state.deltas.filter((delta) => delta.version > fromVersion && delta.version <= targetVersion);
	if (deltas.length !== targetVersion - fromVersion) return withCommand(state, {
		type: "request-full-build",
		reason: "missing-delta-history"
	});
	const batch = {
		buildId: state.buildId,
		deltas,
		fromVersion,
		sessionId: state.activeSessionId,
		targetVersion
	};
	return withCommand(trackInFlight ? {
		...state,
		inFlight: {
			fromVersion,
			sessionId: batch.sessionId,
			targetVersion
		}
	} : state, {
		type: "publish-batch",
		batch
	});
}
function unchanged(state) {
	return {
		commands: [],
		state
	};
}
function withCommand(state, command) {
	return {
		commands: [command],
		state
	};
}
//#endregion
//#region src/runtime/statefulHmr/transport.ts
const endpointPath = "/__weapp_vite_stateful_hmr__";
const pollTimeout = 25e3;
var StatefulHmrTransport = class {
	server;
	publishUpdate;
	requestFullBuild;
	state = createStatefulHmrServerState(createId());
	token = createId();
	pendingPolls = /* @__PURE__ */ new Map();
	closed = false;
	constructor(server, publishUpdate, requestFullBuild) {
		this.server = server;
		this.publishUpdate = publishUpdate;
		this.requestFullBuild = requestFullBuild;
	}
	get retainedDeltaBytes() {
		return this.state.retainedDeltaBytes;
	}
	get retainedDeltaCount() {
		return this.state.hostVersion;
	}
	install() {
		this.server.middlewares.use(endpointPath, this.handleRequest);
	}
	close() {
		this.closed = true;
		this.respondToAll({ type: "rebuilding" });
	}
	addDelta(code, changedIds) {
		this.apply({
			type: "delta-added",
			bytes: Buffer.byteLength(code),
			changedIds,
			code
		});
		this.respondToAll({ type: "changed" });
	}
	createBuildId() {
		return createId();
	}
	commitFullBuild(buildId) {
		this.apply({
			type: "full-build-committed",
			buildId
		});
		this.respondToAll({ type: "rebuilding" });
	}
	isCurrentBuild(buildId) {
		return this.state.buildId === buildId;
	}
	createControl() {
		const address = this.server.httpServer?.address();
		const port = address && typeof address !== "string" ? address.port : this.server.config.server.port;
		return {
			buildId: this.state.buildId,
			token: this.token,
			url: `http://localhost:${port}${endpointPath}`
		};
	}
	handleRequest = async (request, response) => {
		if (this.closed || request.method !== "POST") {
			respond(response, 404, { type: "not-found" });
			return;
		}
		let body;
		try {
			body = JSON.parse(await readBody(request));
		} catch {
			respond(response, 400, { type: "invalid-request" });
			return;
		}
		if (!isClientReport(body) || body.token !== this.token) {
			respond(response, 403, { type: "forbidden" });
			return;
		}
		if (body.action === "rebuild") {
			this.requestFullBuild();
			respond(response, 202, { type: "rebuilding" });
			return;
		}
		if (body.action === "register") {
			if (this.apply({
				type: "client-registered",
				buildId: body.buildId,
				sessionId: body.sessionId,
				version: body.version
			}).some((command) => command.type === "request-full-build")) this.requestFullBuild();
			respond(response, 200, { type: "registered" });
			return;
		}
		const commands = this.apply({
			type: "client-reported",
			buildId: body.buildId,
			sessionId: body.sessionId,
			version: body.version
		});
		const publish = commands.find((command) => command.type === "publish-batch");
		if (publish?.type === "publish-batch") {
			try {
				await this.publishUpdate(publish.batch.buildId, renderBatch(publish.batch, createId()));
				respond(response, 200, {
					type: "batch-published",
					targetVersion: publish.batch.targetVersion
				});
			} catch {
				this.apply({
					type: "batch-publish-failed",
					sessionId: publish.batch.sessionId,
					targetVersion: publish.batch.targetVersion
				});
				respond(response, 500, { type: "publish-failed" });
			}
			return;
		}
		if (commands.some((command) => command.type === "request-full-build")) {
			this.requestFullBuild();
			respond(response, 202, { type: "rebuilding" });
			return;
		}
		if (commands.some((command) => command.type === "ignore-client")) {
			respond(response, 409, { type: "rebuilding" });
			return;
		}
		this.holdPoll(body.sessionId, response);
	};
	apply(event) {
		const transition = transitionStatefulHmrServer(this.state, event);
		this.state = transition.state;
		return transition.commands;
	}
	holdPoll(sessionId, response) {
		const previous = this.pendingPolls.get(sessionId);
		if (previous) this.finishPoll(sessionId, previous, { type: "changed" });
		const pending = {
			response,
			timeout: setTimeout(() => this.finishPoll(sessionId, pending, { type: "idle" }), pollTimeout)
		};
		this.pendingPolls.set(sessionId, pending);
		response.on("close", () => this.finishPoll(sessionId, pending));
	}
	finishPoll(sessionId, pending, value) {
		if (this.pendingPolls.get(sessionId) !== pending) return;
		clearTimeout(pending.timeout);
		this.pendingPolls.delete(sessionId);
		if (value) respond(pending.response, 200, value);
	}
	respondToAll(value) {
		for (const [sessionId, pending] of this.pendingPolls) this.finishPoll(sessionId, pending, value);
	}
};
function renderBatch(batch, nonce) {
	const changedIds = [...new Set(batch.deltas.flatMap((delta) => delta.changedIds))];
	const metadata = {
		buildId: batch.buildId,
		changedIds,
		compatible: true,
		fromVersion: batch.fromVersion,
		targetVersion: batch.targetVersion
	};
	const code = batch.deltas.map((delta) => delta.code).join("\n");
	return `// ${nonce}\nglobalThis.__WEAPP_VITE_STATEFUL_HMR_CLIENT__.receiveBatch(${JSON.stringify(metadata)}, () => {\n${indent(code, 2)}\n});\n`;
}
function indent(value, spaces) {
	const prefix = " ".repeat(spaces);
	return value.split("\n").map((line) => `${prefix}${line}`).join("\n");
}
function isClientReport(value) {
	if (!value || typeof value !== "object") return false;
	const candidate = value;
	return (candidate.action === "poll" || candidate.action === "rebuild" || candidate.action === "register") && typeof candidate.buildId === "string" && typeof candidate.sessionId === "string" && typeof candidate.token === "string" && typeof candidate.version === "number";
}
async function readBody(request) {
	const chunks = [];
	let size = 0;
	for await (const chunk of request) {
		const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
		size += buffer.length;
		if (size > 65536) throw new Error("stateful HMR request body is too large");
		chunks.push(buffer);
	}
	return Buffer.concat(chunks).toString("utf8");
}
function respond(response, status, body) {
	if (response.writableEnded) return;
	response.statusCode = status;
	response.setHeader("content-type", "application/json");
	response.end(JSON.stringify(body));
}
function createId() {
	return randomBytes(16).toString("hex");
}
//#endregion
//#region src/runtime/statefulHmr/viteAdapter.ts
const clientId = "weapp-vite-stateful-hmr";
const initialBuildTimeoutMs = 6e4;
const require = createRequire(import.meta.url);
function resolveViteDevEngine() {
	try {
		const vitePackagePath = require.resolve("vite/package.json");
		const viteRolldown = createRequire(vitePackagePath)("rolldown/experimental");
		if (typeof viteRolldown.dev === "function") return viteRolldown.dev;
	} catch {}
	return dev;
}
async function withInitialBuildTimeout(task, timeoutMs = initialBuildTimeoutMs) {
	let timeout;
	try {
		return await Promise.race([task, new Promise((_resolve, reject) => {
			timeout = setTimeout(() => {
				reject(/* @__PURE__ */ new Error(`stateful-experimental HMR 初始构建超时(>${timeoutMs}ms)。`));
			}, timeoutMs);
		})]);
	} finally {
		if (timeout) clearTimeout(timeout);
	}
}
var StatefulHmrViteAdapter = class {
	config;
	server;
	callbacks;
	watchOptions;
	createDevEngine;
	initialBuildTimeout;
	bundledDev;
	initialOutputError;
	initialRuntimeValidated = false;
	constructor(config, server, callbacks, watchOptions = {}, createDevEngine = resolveViteDevEngine(), initialBuildTimeout = initialBuildTimeoutMs) {
		this.config = config;
		this.server = server;
		this.callbacks = callbacks;
		this.watchOptions = watchOptions;
		this.createDevEngine = createDevEngine;
		this.initialBuildTimeout = initialBuildTimeout;
	}
	install() {
		const bundledDev = this.server.environments.client.bundledDev;
		if (!bundledDev) throw new Error("stateful-experimental HMR 需要 Vite experimental.bundledDev。");
		if (typeof bundledDev.getRolldownOptions !== "function" || typeof bundledDev.storeOutputFiles !== "function") throw new TypeError("当前 Vite bundled-development 私有 API 与 weapp-vite 不兼容。");
		this.bundledDev = bundledDev;
		this.installOptions(bundledDev);
		this.installOutput(bundledDev);
		this.installListener(bundledDev);
	}
	async rebuild(prepare) {
		const engine = this.bundledDev?._devEngine;
		if (!engine) throw new Error("Vite DevEngine 未初始化,无法执行 stateful HMR 完整刷新。");
		await prepare?.();
		engine.triggerFullBuild();
		await engine.ensureLatestBuildOutput();
	}
	async registerBundleModules(output) {
		const moduleIds = /* @__PURE__ */ new Set();
		const payloadFilenames = [];
		for (const item of output) {
			if (item.type !== "chunk") continue;
			payloadFilenames.push(item.fileName);
			for (const match of item.code.matchAll(/registerModule\("([^"]+)"/g)) moduleIds.add(match[1]);
			for (const id of Object.keys(item.modules ?? {})) {
				const normalized = toStableModuleId(id, this.config.root);
				if (!moduleIds.has(normalized)) moduleIds.add(normalized);
			}
		}
		await this.registerModules([...moduleIds]);
		await this.markPayloadsDelivered(payloadFilenames);
		return moduleIds.size;
	}
	async registerPatchModules(code) {
		const moduleIds = /* @__PURE__ */ new Set();
		for (const match of code.matchAll(/create(?:Esm|Cjs)Initializer\("([^"]+)"/g)) moduleIds.add(match[1]);
		await this.registerModules([...moduleIds]);
	}
	async markPayloadDelivered(filename) {
		await this.markPayloadsDelivered([filename]);
	}
	async registerModules(moduleIds) {
		const engine = this.bundledDev?._devEngine;
		if (moduleIds.length && typeof engine?.registerModules === "function") await engine.registerModules(clientId, moduleIds);
	}
	async markPayloadsDelivered(filenames) {
		const engine = this.bundledDev?._devEngine;
		if (typeof engine?.notifyPayloadDelivered !== "function") return;
		for (const filename of filenames) await engine.notifyPayloadDelivered(filename);
	}
	installOptions(bundledDev) {
		const original = bundledDev.getRolldownOptions.bind(bundledDev);
		bundledDev.getRolldownOptions = async () => {
			const options = await original();
			const output = Array.isArray(options.output) ? options.output[0] ??= {} : options.output ??= {};
			const configuredOutput = this.config.build.rolldownOptions.output;
			const desiredOutput = Array.isArray(configuredOutput) ? configuredOutput[0] : configuredOutput;
			Object.assign(output, desiredOutput);
			const userBanner = output.banner;
			const userFooter = output.footer;
			output.format = "cjs";
			output.minify = false;
			output.sourcemap = false;
			output.banner = async (chunk) => {
				const existing = typeof userBanner === "function" ? await userBanner(chunk) : userBanner ?? "";
				return `${existing}${existing ? "\n" : ""}${createStatefulHmrBanner(chunk)}`;
			};
			output.footer = async (chunk) => {
				const statefulFooter = createStatefulHmrFooter(chunk);
				const existing = typeof userFooter === "function" ? await userFooter(chunk) : userFooter ?? "";
				return `${statefulFooter}${statefulFooter && existing ? "\n" : ""}${existing}`;
			};
			options.experimental ??= {};
			options.experimental.devMode = {
				...typeof options.experimental.devMode === "object" ? options.experimental.devMode : {},
				implement: createStatefulHmrRolldownRuntimeSource(),
				lazy: false,
				skipCommonRuntimeInjection: true
			};
			return options;
		};
	}
	installOutput(bundledDev) {
		const original = bundledDev.storeOutputFiles.bind(bundledDev);
		bundledDev.storeOutputFiles = (output) => {
			try {
				if (!this.initialRuntimeValidated && output.some((item) => item.fileName === "app.js")) {
					assertStatefulHmrRuntimeOutput(output);
					this.initialRuntimeValidated = true;
				}
				original(output);
				this.callbacks.onOutput(output);
			} catch (error) {
				this.initialOutputError = error instanceof Error ? error : new Error(String(error));
				throw error;
			}
		};
	}
	installListener(bundledDev) {
		bundledDev.listen = async () => {
			const rolldownOptions = await bundledDev.getRolldownOptions();
			if (Array.isArray(rolldownOptions.output) && rolldownOptions.output.length > 1) throw new Error("stateful-experimental HMR 不支持多组 Rolldown output 配置。");
			const outputOptions = Array.isArray(rolldownOptions.output) ? rolldownOptions.output[0] : rolldownOptions.output;
			const engine = await this.createDevEngine(rolldownOptions, outputOptions, {
				onAdditionalAssets: (result) => bundledDev.storeOutputFiles(result.output),
				onHmrUpdates: (result) => this.handleHmrUpdates(result),
				onOutput: (result) => {
					if (result instanceof Error) {
						this.initialOutputError = result;
						this.callbacks.onError(result.message);
						return;
					}
					bundledDev.storeOutputFiles(result.output);
				},
				watch: {
					skipWrite: true,
					...this.watchOptions
				}
			});
			bundledDev._devEngine = engine;
			engine.run().catch((error) => {
				const message = error instanceof Error ? error.message : String(error);
				this.callbacks.onError(message);
			});
			await engine.registerClient(clientId);
			await withInitialBuildTimeout(engine.ensureCurrentBuildFinish(), this.initialBuildTimeout);
			if (this.initialOutputError) throw this.initialOutputError;
			if ((await engine.getBundleState()).lastBuildErrored) throw new Error("微信状态保持 HMR 初次构建失败。");
			await withInitialBuildTimeout(this.callbacks.waitForInitialBundle(), this.initialBuildTimeout);
		};
	}
	handleHmrUpdates(result) {
		if (result instanceof Error) {
			this.callbacks.onError(result.message);
			return;
		}
		if (result.changedFiles.length === 0) return;
		for (const { clientId: updateClientId, update } of result.updates) if (updateClientId === clientId) this.callbacks.onPatch(result.changedFiles, update);
	}
};
function createStatefulHmrBanner(chunk) {
	if (chunk.fileName === "app.js") return [
		`require(${JSON.stringify(`./${WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE}`)});`,
		"require(\"./rolldown-runtime.js\");",
		`globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].installNative('App', definition => App(definition));`
	].join("");
	if (!chunk.isEntry || !chunk.fileName.endsWith(".js")) return "";
	const prefix = "../".repeat(chunk.fileName.split("/").length - 1);
	return [
		`require(${JSON.stringify(`${prefix}rolldown-runtime.js`)});`,
		`globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].installNative('Page', definition => Page(definition));`,
		`globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].installNative('Component', definition => Component(definition));`,
		`require(${JSON.stringify(`${prefix}${WEAPP_VITE_STATEFUL_HMR_PRELOAD_FILE}`)});`,
		`require(${JSON.stringify(`${prefix}${WEAPP_VITE_STATEFUL_HMR_UPDATE_FILE}`)});`
	].join("");
}
function createStatefulHmrFooter(chunk) {
	if (!chunk.isEntry || chunk.fileName === "app.js" || !chunk.fileName.endsWith(".js")) return "";
	return `for (const definition of globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].takeNativeDefinitions('Component')) Component(definition);`;
}
function toStableModuleId(id, root) {
	const normalizedId = id.replaceAll("\\", "/");
	const absolute = path$1.posix.isAbsolute(normalizedId) || /^[A-Z]:\//i.test(normalizedId);
	if (normalizedId.startsWith("\0") || !absolute) return normalizedId;
	return path$1.posix.relative(root.replaceAll("\\", "/"), normalizedId);
}
//#endregion
//#region src/runtime/statefulHmr/session.ts
const maxRetainedDeltaCount = 1e3;
const maxRetainedDeltaBytes = 16777216;
async function runStatefulHmrDev(ctx, buildOptions, restart, snapshots) {
	const configService = ctx.configService;
	if (configService.platform !== "weapp") throw new Error("weapp.hmr.runtime=\"stateful-experimental\" 目前仅支持微信小程序平台。");
	let session;
	const entryIds = new Set(Array.from(snapshots.entryIds, (id) => normalizeFsResolvedId(id)));
	const pollingWatchOptions = resolvePollingWatchOptions(configService);
	const installPlugin = {
		name: "weapp-vite:stateful-hmr-session",
		enforce: "post",
		configureServer(server) {
			const currentSession = new StatefulHmrSession(ctx, server, restart, entryIds, snapshots, {
				compareContentsForPolling: pollingWatchOptions.usePolling === true ? true : void 0,
				pollInterval: pollingWatchOptions.interval,
				usePolling: pollingWatchOptions.usePolling
			});
			session = currentSession;
			currentSession.install();
		},
		transform(code, id) {
			if (!isStatefulHmrBoundary(id, configService.absoluteSrcRoot, entryIds) || code.includes("import.meta.hot.accept")) return;
			return `${id.endsWith(".vue") ? code : redirectNativeComponentRegistration(code)}\nif (import.meta.hot) import.meta.hot.accept();\n`;
		}
	};
	const server = await createServer({
		...buildOptions,
		appType: "custom",
		configFile: false,
		define: {
			...buildOptions.define ?? {},
			App: `globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].App`,
			Page: `globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].Page`
		},
		experimental: {
			...buildOptions.experimental ?? {},
			bundledDev: true
		},
		plugins: [
			createStatefulHmrSidecarPlugin(),
			installPlugin,
			...buildOptions.plugins ?? []
		],
		server: {
			...buildOptions.server ?? {},
			host: "127.0.0.1",
			port: 0,
			watch: {
				...buildOptions.server?.watch ?? {},
				ignored: createViteWatchIgnored(buildOptions.root ?? configService.cwd, configService.outDir, buildOptions.server?.watch?.ignored)
			}
		},
		build: {
			...buildOptions.build ?? {},
			watch: void 0,
			write: false
		}
	});
	try {
		await server.listen();
		if (!session) throw new Error("微信状态保持 HMR session 未完成初始化。");
		await session.refreshControl();
		return createWatcherAdapter(server, session);
	} catch (error) {
		await session?.close().catch(() => {});
		await server.close().catch(() => {});
		throw error;
	}
}
var StatefulHmrSession = class {
	ctx;
	server;
	restart;
	entryIds;
	snapshots;
	activeSnapshotBatch;
	adapter;
	initialBundle = Promise.withResolvers();
	snapshotScheduler;
	transport;
	outputChain = Promise.resolve();
	restartTimer;
	snapshotAssets = /* @__PURE__ */ new Map();
	sourceChangeListener = (file, dirtyReasonSummary) => {
		this.handleSourceUpdate(file, dirtyReasonSummary);
	};
	constructor(ctx, server, restart, entryIds, snapshots, devWatchOptions) {
		this.ctx = ctx;
		this.server = server;
		this.restart = restart;
		this.entryIds = entryIds;
		this.snapshots = snapshots;
		this.replaceSnapshotAssets(snapshots.initial);
		this.transport = new StatefulHmrTransport(server, async (buildId, source) => {
			await this.enqueueOutput(async () => {
				if (!this.transport.isCurrentBuild(buildId)) return;
				await writeStatefulHmrOutput(this.ctx.configService.outDir, [{
					type: "asset",
					fileName: WEAPP_VITE_STATEFUL_HMR_UPDATE_FILE,
					source
				}]);
			});
		}, () => this.requestFullBuild());
		this.adapter = new StatefulHmrViteAdapter(server.config, server, {
			onError: (message) => server.config.logger.error(`[weapp-vite] stateful HMR: ${message}`),
			onOutput: (output) => this.handleOutput(output),
			onPatch: (files, output) => this.handlePatch(files, output),
			waitForInitialBundle: () => this.waitForInitialBundle()
		}, devWatchOptions);
		this.snapshotScheduler = new StatefulHmrSnapshotScheduler({
			execute: (batch) => this.executeSnapshotBatch(batch),
			onError: (error) => this.server.config.logger.error("[weapp-vite] stateful HMR snapshot refresh failed", { error: error instanceof Error ? error : new Error(String(error)) })
		});
	}
	install() {
		this.transport.install();
		this.adapter.install();
		this.ctx.onStatefulHmrSourceChange = this.sourceChangeListener;
	}
	async close() {
		if (this.restartTimer) clearTimeout(this.restartTimer);
		if (this.ctx.onStatefulHmrSourceChange === this.sourceChangeListener) this.ctx.onStatefulHmrSourceChange = void 0;
		this.transport.close();
		await this.snapshotScheduler.close();
		await this.outputChain;
	}
	async refreshControl() {
		await this.enqueueOutput(async () => {
			await writeStatefulHmrOutput(this.ctx.configService.outDir, [{
				type: "asset",
				fileName: WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE,
				source: createStatefulHmrControlSource(this.transport.createControl())
			}]);
		});
	}
	handleSourceUpdate(file, dirtyReasonSummary = []) {
		const normalizedFile = normalizeFsResolvedId(path.isAbsolute(file) ? file : path.resolve(this.server.config.root, file));
		const normalizedOutDir = normalizeFsResolvedId(this.ctx.configService.outDir).replace(/\/$/, "");
		if (normalizedFile === normalizedOutDir || normalizedFile.startsWith(`${normalizedOutDir}/`)) return;
		if (shouldRestartStatefulHmrServer([normalizedFile], this.ctx.configService?.configFileDependencies, this.ctx.configService?.weappViteConfig?.react)) {
			this.requestServerRestart();
			return;
		}
		if (requiresStatefulHmrSnapshot(normalizedFile, dirtyReasonSummary)) {
			if (!this.snapshotScheduler.isPending()) logger_default.info("HMR 更新:正在同步模板、样式与静态资源...");
			this.requestSnapshotRefresh([normalizedFile]);
		}
	}
	handleOutput(output) {
		const snapshotBatch = this.activeSnapshotBatch;
		this.enqueueOutput(async () => {
			if (snapshotBatch?.isSuperseded()) return;
			const compatibleOutput = await transformOutput(output);
			const fullBuild = compatibleOutput.some((item) => item.fileName === "app.js");
			if (fullBuild) {
				mergeStatefulHmrSnapshotAssets(compatibleOutput, this.snapshotAssets.values());
				const buildId = this.transport.createBuildId();
				this.transport.commitFullBuild(buildId);
				stampStatefulHmrFullBuild(compatibleOutput, buildId);
				setAsset(compatibleOutput, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, createStatefulHmrControlSource({
					...this.transport.createControl(),
					buildId
				}));
				setAsset(compatibleOutput, WEAPP_VITE_STATEFUL_HMR_PRELOAD_FILE, "void 0;\n");
				setAsset(compatibleOutput, WEAPP_VITE_STATEFUL_HMR_UPDATE_FILE, "void 0;\n");
			}
			await writeStatefulHmrOutput(this.ctx.configService.outDir, compatibleOutput);
			if (fullBuild) {
				const moduleCount = await this.adapter.registerBundleModules(compatibleOutput);
				this.server.config.logger.info(`[weapp-vite] 微信状态保持 HMR 已就绪(${moduleCount} modules)`);
				this.initialBundle.resolve();
			}
		});
	}
	handlePatch(files, output) {
		if (output.type === "Noop") return false;
		const dirtyReasonSummary = this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary ?? [];
		const allowTailwindContentPatch = dirtyReasonSummary.some((reason) => reason.startsWith("tailwind-content:"));
		if (!isSafeJavaScriptPatch(files, output, dirtyReasonSummary, this.entryIds, this.server.config.root, { allowTailwindContent: allowTailwindContentPatch })) {
			if (shouldRestartStatefulHmrServer(files, this.ctx.configService?.configFileDependencies)) this.requestServerRestart();
			else if (this.snapshotScheduler.isPending() || files.length > 0 && files.every(isStatefulHmrAssetFile) || shouldUseStatefulHmrSnapshotOnly(this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary ?? [])) {
				if (!this.snapshotScheduler.isPending()) this.requestSnapshotRefresh(files);
			} else this.requestFullBuild(files);
			return false;
		}
		if (allowTailwindContentPatch) this.requestSnapshotRefresh(files);
		this.adapter.registerPatchModules(output.code).then(async () => {
			const code = await transformJavaScript(output.code, output.filename);
			if (shouldResetStatefulHmrRetention(this.transport.retainedDeltaCount, this.transport.retainedDeltaBytes, Buffer.byteLength(code))) {
				this.requestFullBuild();
				return;
			}
			this.transport.addDelta(code, output.changedIds ?? []);
			return this.adapter.markPayloadDelivered(output.filename);
		}).catch((error) => {
			this.server.config.logger.error("[weapp-vite] stateful HMR patch transform failed", { error });
			this.requestFullBuild();
		});
		return true;
	}
	requestFullBuild(files = []) {
		this.snapshotScheduler.request("full", files);
	}
	requestSnapshotRefresh(files = []) {
		this.snapshotScheduler.request("refresh", files);
	}
	requestServerRestart() {
		if (this.restartTimer) return;
		this.restartTimer = setTimeout(() => {
			this.restartTimer = void 0;
			this.restart().catch((error) => {
				this.server.config.logger.error("[weapp-vite] stateful HMR server restart failed", { error });
			});
		}, 100);
	}
	enqueueOutput(task) {
		this.outputChain = this.outputChain.then(task, task).catch((error) => {
			this.server.config.logger.error(`[weapp-vite] stateful HMR output failed: ${formatStatefulHmrError(error)}`);
		});
		return this.outputChain;
	}
	async executeSnapshotBatch(batch) {
		const output = await this.snapshots.rebuild(batch.files);
		if (batch.isSuperseded()) return;
		if (batch.mode === "full") {
			this.replaceSnapshotAssets(output);
			this.activeSnapshotBatch = batch;
			try {
				await this.adapter.rebuild();
				await this.outputChain;
			} finally {
				if (this.activeSnapshotBatch === batch) this.activeSnapshotBatch = void 0;
			}
			return;
		}
		const changedOutput = getChangedStatefulHmrSnapshotAssets(this.snapshotAssets.values(), output);
		this.replaceSnapshotAssets(output);
		await this.enqueueOutput(async () => {
			if (!batch.isSuperseded()) await writeStatefulHmrOutput(this.ctx.configService.outDir, changedOutput);
		});
	}
	replaceSnapshotAssets(output) {
		this.snapshotAssets = new Map(output.filter((item) => item.type === "asset").map((item) => [item.fileName, item]));
	}
	async waitForInitialBundle() {
		await this.initialBundle.promise;
		await this.outputChain;
	}
};
function shouldRestartStatefulHmrServer(files, configFileDependencies = [], react) {
	const normalizedConfigDependencies = new Set(Array.from(configFileDependencies, (dependency) => normalizeFsResolvedId(dependency)));
	return Array.from(files).some((file) => normalizedConfigDependencies.has(normalizeFsResolvedId(file)) || isReactStaticTemplateSource(react, file));
}
function mergeStatefulHmrSnapshotAssets(output, snapshotAssets) {
	for (const asset of snapshotAssets) {
		if (asset.type !== "asset") continue;
		const index = output.findIndex((item) => item.fileName === asset.fileName);
		if (index >= 0) output[index] = asset;
		else output.push(asset);
	}
}
function getChangedStatefulHmrSnapshotAssets(previous, next) {
	const previousAssets = new Map(Array.from(previous).flatMap((item) => item.type === "asset" ? [[item.fileName, item.source]] : []));
	return Array.from(next).filter((item) => {
		if (item.type !== "asset") return true;
		const previousSource = previousAssets.get(item.fileName);
		return previousSource === void 0 || !statefulHmrAssetSourcesEqual(previousSource, item.source);
	});
}
function statefulHmrAssetSourcesEqual(left, right) {
	if (left === right) return true;
	const leftBuffer = Buffer.isBuffer(left) ? left : Buffer.from(left);
	const rightBuffer = Buffer.isBuffer(right) ? right : Buffer.from(right);
	return leftBuffer.equals(rightBuffer);
}
function createWatcherAdapter(server, session) {
	return {
		close: async () => {
			await session.close();
			await server.close();
		},
		on() {
			return this;
		}
	};
}
function isStatefulHmrBoundary(id, srcRoot, entryIds) {
	const sidecar = parseSidecarSourceRequest(id);
	const sourceId = sidecar?.kind === "script" ? sidecar.sourceId : id.includes("?") ? void 0 : id;
	if (!sourceId) return false;
	const normalizedSourceId = normalizeFsResolvedId(sourceId);
	const normalizedSrcRoot = normalizeFsResolvedId(srcRoot).replace(/\/$/, "");
	if (!normalizedSourceId.startsWith(`${normalizedSrcRoot}/`) || !/\.(?:[cm]?[jt]sx?|vue)$/.test(normalizedSourceId)) return false;
	if (!entryIds) return true;
	for (const entryId of entryIds) if (normalizeFsResolvedId(entryId) === normalizedSourceId) return true;
	return false;
}
function redirectNativeComponentRegistration(code) {
	if (!code.includes("Component")) return code;
	const ast = parseJsLike(code);
	const magicString = new MagicString(code);
	let changed = false;
	traverse(ast, { CallExpression(path) {
		const callee = path.node.callee;
		if (callee.type !== "Identifier" || callee.name !== "Component" || path.scope.hasBinding("Component") || callee.start == null || callee.end == null) return;
		magicString.overwrite(callee.start, callee.end, `globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY)}].Component`);
		changed = true;
	} });
	return changed ? magicString.toString() : code;
}
function isSafeJavaScriptPatch(files, output, dirtyReasonSummary = [], entryIds, root, options = {}) {
	const normalizedEntryIds = entryIds ? new Set(Array.from(entryIds, (entryId) => normalizeFsResolvedId(entryId))) : void 0;
	return output.type === "Patch" && files.every((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file)) && (!normalizedEntryIds || files.every((file) => {
		const absoluteFile = path.isAbsolute(file) || !root ? file : path.resolve(root, file);
		return normalizedEntryIds.has(normalizeFsResolvedId(absoluteFile));
	})) && !output.changedIds?.some(isNonJavaScriptSidecarId) && !dirtyReasonSummary.some((reason) => isUnsafeStatefulHmrReason(reason, options.allowTailwindContent === true));
}
function requiresStatefulHmrSnapshot(file, dirtyReasonSummary = []) {
	return /\.(?:jsx|tsx)$/.test(file) || !/\.(?:[cm]?[jt]sx?|vue)$/.test(file) || dirtyReasonSummary.some((reason) => isUnsafeStatefulHmrReason(reason));
}
function isStatefulHmrAssetFile(file) {
	return !/\.(?:[cm]?[jt]sx?|vue)$/.test(file);
}
function isUnsafeStatefulHmrReason(reason, allowTailwindContent = false) {
	if (allowTailwindContent && reason.startsWith("tailwind-content:")) return false;
	return /^(?:entry-json-only|entry-local-asset|entry-style-only|react-template|tailwind-content):/.test(reason);
}
function shouldUseStatefulHmrSnapshotOnly(dirtyReasonSummary) {
	return dirtyReasonSummary.some((reason) => /^(?:entry-json-only|entry-local-asset|entry-style-only):/.test(reason)) && dirtyReasonSummary.every((reason) => /^(?:entry-json-only|entry-local-asset|entry-style-only|tailwind-content):/.test(reason));
}
function isNonJavaScriptSidecarId(id) {
	const sidecar = parseSidecarSourceRequest(id) ?? parseSidecarModuleId(id);
	return sidecar !== void 0 && sidecar.kind !== "script";
}
function shouldResetStatefulHmrRetention(retainedDeltaCount, retainedDeltaBytes, nextDeltaBytes) {
	return retainedDeltaCount >= maxRetainedDeltaCount || retainedDeltaBytes + nextDeltaBytes >= maxRetainedDeltaBytes;
}
async function transformOutput(output) {
	return await Promise.all(output.map(async (item) => {
		if (item.type !== "chunk") return item;
		return {
			...item,
			code: await transformJavaScript(item.code, item.fileName)
		};
	}));
}
async function transformJavaScript(code, filename) {
	return (await transformWithOxc(code, filename, {
		assumptions: { setPublicClassFields: true },
		lang: "js",
		sourcemap: false,
		target: "es2018"
	})).code;
}
function setAsset(output, fileName, source) {
	const index = output.findIndex((item) => item.fileName === fileName);
	const asset = {
		type: "asset",
		fileName,
		source
	};
	if (index >= 0) output[index] = asset;
	else output.push(asset);
}
function stampStatefulHmrFullBuild(output, buildId) {
	for (const item of output) if (item.type === "chunk" && item.fileName.endsWith(".js")) item.code = `// weapp-vite-stateful-build:${buildId}\n${item.code}`;
}
function formatStatefulHmrError(error) {
	if (error instanceof Error) return error.stack || error.message;
	return String(error);
}
//#endregion
//#region src/plugins/autoImport.ts
const LEADING_DOT_SLASH_RE$2 = /^\.\//;
const LEADING_SLASHES_RE$2 = /^\/+/;
const GLOB_WILDCARD_RE$1 = /[*?[{]/;
const TRAILING_SLASHES_RE$2 = /\/+$/;
const AUTO_IMPORT_WATCHER_KEY = "__auto-import-vue-watcher__";
const AUTO_IMPORT_CONFIG_SUFFIXES = configExtensions.map((ext) => `.${ext}`);
const AUTO_IMPORT_JS_SUFFIXES = new Set(scriptExtensions.map((ext) => `.${ext}`));
const AUTO_IMPORT_TEMPLATE_SUFFIXES = new Set(templateExtensions.map((ext) => `.${ext}`));
const AUTO_IMPORT_VUE_SUFFIXES = new Set(vueExtensions.map((ext) => `.${ext}`));
function hasOwn$4(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
function isEnabledOutputOption(option) {
	if (option === true) return true;
	if (typeof option === "string") return option.trim().length > 0;
	return false;
}
function shouldBootstrapAutoImportWithoutGlobs(autoImportConfig) {
	if (!autoImportConfig) return false;
	const resolvers = autoImportConfig.resolvers;
	if (Array.isArray(resolvers) && resolvers.length > 0) return true;
	if (autoImportConfig.output !== false) return true;
	if (isEnabledOutputOption(autoImportConfig.typedComponents)) return true;
	if (isEnabledOutputOption(autoImportConfig.htmlCustomData)) return true;
	if (isEnabledOutputOption(autoImportConfig.vueComponents)) return true;
	return false;
}
function createAutoImportGlobsKey(globs) {
	return globs?.join("\0") ?? "";
}
function normalizeChangedPath(id) {
	if (!id || id.startsWith("\0")) return;
	const [pathWithoutQuery] = id.split("?");
	return pathWithoutQuery;
}
function getAutoImportCandidateKind(filePath) {
	if (AUTO_IMPORT_CONFIG_SUFFIXES.some((suffix) => filePath.endsWith(suffix))) return "config";
	if (AUTO_IMPORT_VUE_SUFFIXES.has(path.extname(filePath))) return "vue";
	if (AUTO_IMPORT_TEMPLATE_SUFFIXES.has(path.extname(filePath))) return "template";
	if (AUTO_IMPORT_JS_SUFFIXES.has(path.extname(filePath))) return "script";
}
function getAutoImportCandidateBase(filePath, kind) {
	if (!kind) return;
	if (kind === "config") {
		const suffix = AUTO_IMPORT_CONFIG_SUFFIXES.find((item) => filePath.endsWith(item));
		return suffix ? filePath.slice(0, -suffix.length) : void 0;
	}
	return filePath.slice(0, -path.extname(filePath).length);
}
function rankAutoImportCandidate(kind) {
	switch (kind) {
		case "vue": return 4;
		case "template": return 3;
		case "script": return 2;
		case "config": return 1;
		default: return 0;
	}
}
function collectDistinctAutoImportCandidates(files) {
	const bestByBase = /* @__PURE__ */ new Map();
	for (const filePath of files) {
		const kind = getAutoImportCandidateKind(filePath);
		const base = getAutoImportCandidateBase(filePath, kind);
		if (!kind || !base) continue;
		const rank = rankAutoImportCandidate(kind);
		const existing = bestByBase.get(base);
		if (!existing || rank > existing.rank || rank === existing.rank && filePath < existing.filePath) bestByBase.set(base, {
			filePath,
			rank
		});
	}
	return Array.from(bestByBase.values(), (entry) => entry.filePath).sort((a, b) => a.localeCompare(b));
}
function resolveAbsolutePath(ctx, candidate) {
	const { configService } = ctx;
	if (!configService) return;
	if (path.isAbsolute(candidate)) return candidate;
	const resolvedFromSrc = path.resolve(configService.absoluteSrcRoot, candidate);
	if (resolvedFromSrc.startsWith(configService.absoluteSrcRoot)) return resolvedFromSrc;
	return path.resolve(configService.cwd, candidate);
}
function matchesAutoImportGlobs(ctx, candidate) {
	const { autoImportService, configService } = ctx;
	if (!autoImportService || !configService) return false;
	const targets = /* @__PURE__ */ new Set([
		candidate,
		configService.relativeCwd(candidate),
		configService.relativeAbsoluteSrcRoot(candidate)
	]);
	targets.add(`/${configService.relativeAbsoluteSrcRoot(candidate)}`);
	targets.add(toPosixPath(candidate));
	for (const target of targets) {
		if (!target) continue;
		if (autoImportService.filter(target)) return true;
	}
	return false;
}
async function findAutoImportCandidates(state, globs) {
	const { ctx, resolvedConfig } = state;
	const { configService } = ctx;
	if (!resolvedConfig) return [];
	const ignore = [...defaultExcluded, `${resolvedConfig.build.outDir}/**`];
	return collectDistinctAutoImportCandidates(await new fdir({
		includeDirs: false,
		pathSeparator: "/"
	}).withFullPaths().globWithOptions(globs.map((pattern) => path.resolve(configService.absoluteSrcRoot, pattern)), { ignore }).crawl(configService.absoluteSrcRoot).withPromise());
}
function registerAutoImportWatchTargets(state, globs, registrar, options = {}) {
	const { configService } = state.ctx;
	if (!configService) return /* @__PURE__ */ new Set();
	const watchTargets = /* @__PURE__ */ new Set();
	if (options.includeSrcRoot !== false) watchTargets.add(configService.absoluteSrcRoot);
	for (const pattern of globs ?? []) {
		const normalizedPattern = toPosixPath(pattern).replace(LEADING_DOT_SLASH_RE$2, "").replace(LEADING_SLASHES_RE$2, "");
		const wildcardIndex = normalizedPattern.search(GLOB_WILDCARD_RE$1);
		const cleanedBase = (wildcardIndex >= 0 ? normalizedPattern.slice(0, wildcardIndex) : normalizedPattern).replace(TRAILING_SLASHES_RE$2, "");
		if (!cleanedBase) continue;
		watchTargets.add(path.resolve(configService.absoluteSrcRoot, cleanedBase));
	}
	if (typeof registrar?.addWatchFile !== "function") return watchTargets;
	for (const target of watchTargets) registrar.addWatchFile(target);
	return watchTargets;
}
async function runAutoImportBatch(autoImportService, task) {
	if (typeof autoImportService?.runInBatch === "function") return await autoImportService.runInBatch(task);
	return await task();
}
function findMatchingComponentName(components, componentName) {
	if (hasOwn$4(components, componentName)) return componentName;
	const normalizedComponentName = toKebabCaseComponentName(componentName);
	for (const candidateName in components) if (hasOwn$4(components, candidateName) && toKebabCaseComponentName(candidateName) === normalizedComponentName) return candidateName;
}
async function refreshAutoImportImporters(ctx, filePath) {
	const { wxmlService, configService, autoImportService } = ctx;
	if (!wxmlService || !configService) return;
	const { componentName } = resolvedComponentName(removeExtensionDeep(filePath));
	if (!componentName) return;
	const touchedImporters = /* @__PURE__ */ new Set();
	const entries = Array.from(wxmlService.wxmlComponentsMap.entries());
	for (const [baseName, components] of entries) {
		const matchingComponentName = findMatchingComponentName(components, componentName);
		if (!matchingComponentName) continue;
		const pendingEntriesByImporter = ctx.runtimeState?.autoImport?.pendingEntriesByImporter;
		const pendingEntry = (autoImportService?.resolve(matchingComponentName, baseName))?.value.from;
		if (pendingEntriesByImporter && pendingEntry) {
			const pendingEntries = pendingEntriesByImporter.get(baseName) ?? /* @__PURE__ */ new Set();
			pendingEntries.add(pendingEntry);
			pendingEntriesByImporter.set(baseName, pendingEntries);
		}
		const vueEntry = await findVueEntry(baseName);
		if (vueEntry) {
			touchedImporters.add(vueEntry);
			continue;
		}
		const scriptEntry = await findJsEntry(baseName);
		if (scriptEntry.path) touchedImporters.add(scriptEntry.path);
	}
	if (touchedImporters.size === 0) return;
	for (const importer of touchedImporters) try {
		await touch(importer);
	} catch {}
	logger_default.info(`[auto-import:watch] 刷新组件引用方 ${Array.from(touchedImporters, (importer) => configService.relativeCwd(importer)).join(", ")}`);
}
function createAutoImportPlugin(state) {
	const { ctx } = state;
	const { configService, autoImportService } = ctx;
	let fileWatcherStarted = false;
	function waitForSidecarWatcherReady(watcher) {
		if (typeof watcher.getWatched !== "function") return Promise.resolve();
		return new Promise((resolve) => {
			watcher.once("ready", () => {
				resolve();
			});
		});
	}
	async function startAutoImportFileWatcher(globs) {
		if (fileWatcherStarted || !configService?.isDev || !globs?.length) return;
		const watchTargets = registerAutoImportWatchTargets(state, globs, void 0, { includeSrcRoot: false });
		if (!watchTargets?.size) return;
		const watcher = chokidar.watch(Array.from(watchTargets, (target) => String(target)), createSidecarWatchOptions(configService, {
			ignoreInitial: true,
			persistent: true,
			awaitWriteFinish: {
				stabilityThreshold: 80,
				pollInterval: 20
			}
		}));
		const registerAndRefreshComponent = (filePath, action) => {
			if (!getAutoImportCandidateKind(filePath)) return;
			if (!matchesAutoImportGlobs(ctx, filePath)) return;
			logger_default.info(`[auto-import:watch] ${action}组件文件 ${configService.relativeCwd(filePath)}`);
			autoImportService.registerPotentialComponent(filePath).then(async () => {
				await refreshAutoImportImporters(ctx, filePath);
			});
		};
		watcher.on("add", (filePath) => {
			registerAndRefreshComponent(filePath, "新增");
		});
		watcher.on("change", (filePath) => {
			registerAndRefreshComponent(filePath, "变更");
		});
		watcher.on("unlink", (filePath) => {
			if (!getAutoImportCandidateKind(filePath)) return;
			if (!matchesAutoImportGlobs(ctx, filePath)) return;
			logger_default.info(`[auto-import:watch] 删除组件文件 ${configService.relativeCwd(filePath)}`);
			autoImportService.removePotentialComponent(filePath);
			refreshAutoImportImporters(ctx, filePath);
		});
		const sidecarWatcherMap = ctx.runtimeState?.watcher?.sidecarWatcherMap;
		if (!sidecarWatcherMap) return;
		sidecarWatcherMap.set(AUTO_IMPORT_WATCHER_KEY, { close: () => void watcher.close() });
		fileWatcherStarted = true;
		await waitForSidecarWatcherReady(watcher);
	}
	return {
		name: "weapp-vite:auto-import",
		enforce: "pre",
		configResolved(config) {
			state.resolvedConfig = config;
		},
		async buildStart() {
			if (!state.resolvedConfig) return;
			const autoImportConfig = getAutoImportConfig(configService);
			const globs = autoImportConfig?.globs;
			registerAutoImportWatchTargets(state, globs, this);
			const sidecarWatcherReady = startAutoImportFileWatcher(globs);
			const globsKey = createAutoImportGlobsKey(globs);
			if (globsKey !== state.lastGlobsKey) {
				state.initialScanDone = false;
				state.lastGlobsKey = globsKey;
			}
			if (configService?.isDev && !state.initialScanDone && ctx.runtimeState?.autoImport?.preparedGlobsKey === globsKey) state.initialScanDone = true;
			if (!globs?.length) {
				if (!state.initialScanDone && shouldBootstrapAutoImportWithoutGlobs(autoImportConfig)) {
					await runAutoImportBatch(autoImportService, () => {
						autoImportService.reset();
					});
					state.initialScanDone = true;
				}
				await sidecarWatcherReady;
				return;
			}
			if (state.initialScanDone) {
				await sidecarWatcherReady;
				return;
			}
			await runAutoImportBatch(autoImportService, async () => {
				autoImportService.reset();
				const files = await findAutoImportCandidates(state, globs);
				await Promise.all(files.map((file) => autoImportService.registerPotentialComponent(file)));
			});
			await sidecarWatcherReady;
			state.initialScanDone = true;
		},
		async closeBundle() {
			await autoImportService.awaitManifestWrites();
		},
		async watchChange(id, change) {
			if (!state.initialScanDone || !state.resolvedConfig) return;
			const filePath = normalizeChangedPath(id);
			if (!filePath) return;
			const absolutePath = resolveAbsolutePath(ctx, filePath);
			if (!absolutePath) return;
			if (!matchesAutoImportGlobs(ctx, absolutePath)) return;
			if (!getAutoImportCandidateKind(absolutePath)) return;
			if (change.event === "delete") {
				autoImportService.removePotentialComponent(absolutePath);
				await refreshAutoImportImporters(ctx, absolutePath);
				return;
			}
			await autoImportService.registerPotentialComponent(absolutePath);
			await refreshAutoImportImporters(ctx, absolutePath);
		}
	};
}
function autoImport(ctx) {
	return [createAutoImportPlugin({ ctx })];
}
//#endregion
//#region src/plugins/utils/vueSfc.ts
function createSfcResolveSrcOptions(pluginCtx, configService) {
	return {
		resolveId: async (source, importer) => {
			if (typeof pluginCtx.resolve !== "function") return;
			return (await pluginCtx.resolve(source, importer))?.id;
		},
		checkMtime: getSfcCheckMtime(configService)
	};
}
function createReadAndParseSfcOptions(pluginCtx, configService, options) {
	const resolveCheckMtime = getSfcCheckMtime(configService);
	return {
		source: options?.source,
		checkMtime: options?.checkMtime ?? resolveCheckMtime,
		resolveSrc: createSfcResolveSrcOptions(pluginCtx, configService)
	};
}
//#endregion
//#region src/plugins/vue/transform/usingComponentResolver.ts
const JS_LIKE_FILE_RE = /\.(?:[cm]?ts|[cm]?js)$/;
async function resolveUsingComponentReference(ctx, configService, reExportResolutionCache, importSource, importerFilename, info) {
	const resolved = await ctx.resolve(importSource, importerFilename);
	let clean = resolved?.id ? normalizeFsResolvedId(resolved.id) : void 0;
	if ((!clean || !path.isAbsolute(clean)) && info?.fallbackRelativeImporterDir && importSource.startsWith(".")) clean = path.resolve(path.dirname(importerFilename), importSource);
	if (!clean) return {
		resolvedId: void 0,
		from: void 0
	};
	if (isSkippableResolvedId(clean)) return {
		resolvedId: void 0,
		from: void 0
	};
	if (path.isAbsolute(clean)) {
		const resolvedEntry = await resolveEntryPath(clean, createCachedEntryResolveOptions(configService ?? {}, { kind: info?.kind ?? "default" }));
		if (resolvedEntry) clean = resolvedEntry;
	}
	if (info?.kind === "named" && info.importedName && JS_LIKE_FILE_RE.test(clean)) {
		const exportName = info.importedName;
		const mapped = await resolveReExportedName(clean, exportName, {
			astEngine: resolveAstEngine(configService.weappViteConfig),
			cache: reExportResolutionCache,
			maxDepth: 4,
			readFile: (file) => readFile$1(file, { checkMtime: getReadFileCheckMtime(configService) }),
			resolveId: async (source, importer) => {
				const hop = await ctx.resolve(source, importer);
				const hopId = hop?.id ? normalizeFsResolvedId(hop.id) : void 0;
				if (isSkippableResolvedId(hopId)) return;
				return hopId;
			}
		});
		if (mapped) clean = mapped;
	}
	return {
		resolvedId: clean,
		from: usingComponentFromResolvedFile(clean, configService)
	};
}
async function resolveUsingComponentPath(ctx, configService, reExportResolutionCache, importSource, importerFilename, info) {
	if (!info) return;
	const resolved = await resolveUsingComponentReference(ctx, configService, reExportResolutionCache, importSource, importerFilename, info);
	const sourceType = resolved.resolvedId?.endsWith(".vue") ? "wevu-sfc" : "native";
	return {
		from: resolved.from,
		resolvedId: resolved.resolvedId,
		sourceType
	};
}
function createUsingComponentPathResolver(ctx, configService, reExportResolutionCache) {
	return async (importSource, importerFilename, info) => {
		return resolveUsingComponentPath(ctx, configService, reExportResolutionCache, importSource, importerFilename, info);
	};
}
//#endregion
//#region src/plugins/utils/watchFiles.ts
function addNormalizedWatchFile(pluginCtx, file) {
	if (!file || typeof pluginCtx.addWatchFile !== "function") return false;
	pluginCtx.addWatchFile(normalizeWatchPath(file));
	return true;
}
function addNormalizedWatchFiles(pluginCtx, files) {
	let count = 0;
	for (const file of files ?? []) if (addNormalizedWatchFile(pluginCtx, file)) count += 1;
	return count;
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/loadEntry/watch.ts
async function addWatchTarget(pluginCtx, target, existsCache, ttlMs) {
	if (!target) return false;
	if (existsCache.has(target)) {
		const cached = existsCache.get(target);
		if (!cached) addNormalizedWatchFile(pluginCtx, target);
		return cached;
	}
	const exists = await pathExists(target, { ttlMs });
	if (!exists) addNormalizedWatchFile(pluginCtx, target);
	existsCache.set(target, exists);
	return exists;
}
async function addPredictedWatchTargets(pluginCtx, predictions, existsCache, ttlMs, knownExistingPath) {
	await Promise.all(Array.from(new Set(predictions)).map(async (prediction) => {
		if (prediction && prediction === knownExistingPath) {
			existsCache.set(prediction, true);
			return;
		}
		await addWatchTarget(pluginCtx, prediction, existsCache, ttlMs);
	}));
}
async function collectStyleImports(pluginCtx, id, existsCache, ttlMs) {
	return (await Promise.all(supportedCssLangs.map(async (ext) => {
		const mayBeCssPath = changeFileExtension(id, ext);
		return await addWatchTarget(pluginCtx, mayBeCssPath, existsCache, ttlMs) ? mayBeCssPath : void 0;
	}))).filter((entry) => Boolean(entry));
}
async function collectAppSideFiles(pluginCtx, id, json, jsonService, registerJsonAsset, existsCache, ttlMs) {
	const { sitemapLocation = "sitemap.json", themeLocation = "theme.json" } = json;
	const processSideJson = async (location) => {
		if (!location) return;
		const { path: jsonPath, predictions } = await findJsonEntry(path.resolve(path.dirname(id), location));
		await addPredictedWatchTargets(pluginCtx, predictions, existsCache, ttlMs, jsonPath);
		if (!jsonPath) return;
		registerJsonAsset({
			json: await jsonService.read(jsonPath),
			jsonPath,
			type: "page"
		});
	};
	await Promise.all([processSideJson(sitemapLocation), processSideJson(themeLocation)]);
}
async function collectMiniappConfigFile(pluginCtx, id, configService, jsonService, registerJsonAsset, existsCache, ttlMs) {
	if (configService.platform !== "weapp") return;
	const runtimeMiniappConfigPath = path.resolve(path.dirname(id), "app.miniapp.json");
	const miniappConfigPath = path.resolve(configService.cwd, "project.miniapp.json");
	const [runtimeConfigExists, projectConfigExists] = await Promise.all([addWatchTarget(pluginCtx, runtimeMiniappConfigPath, existsCache, ttlMs), addWatchTarget(pluginCtx, miniappConfigPath, existsCache, ttlMs)]);
	if (runtimeConfigExists) {
		registerJsonAsset({
			fileName: "app.miniapp.json",
			json: await jsonService.read(runtimeMiniappConfigPath),
			jsonPath: runtimeMiniappConfigPath,
			type: "page"
		});
		return;
	}
	if (!projectConfigExists) return;
	registerJsonAsset({
		fileName: "app.miniapp.json",
		json: await jsonService.read(miniappConfigPath),
		jsonPath: miniappConfigPath,
		type: "page"
	});
}
async function ensureTemplateScanned(pluginCtx, id, scanTemplateEntry, existsCache, ttlMs, platform) {
	const { path: templateEntry, predictions } = await findTemplateEntry(id, platform);
	await addPredictedWatchTargets(pluginCtx, predictions, existsCache, ttlMs, templateEntry);
	if (!templateEntry) return "";
	await scanTemplateEntry(templateEntry);
	return templateEntry;
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/loadEntry/template.ts
const TEMPLATE_COMPONENT_TAG_HINT_RE = /<\s*(?:[A-Z_$]|[a-z][\w$]*-)/;
function hasTemplateComponentTagHint(source) {
	return TEMPLATE_COMPONENT_TAG_HINT_RE.test(source);
}
function kebabToCamel(name) {
	return name.replace(/-([a-z0-9])/g, (_, character) => character.toUpperCase());
}
function capitalize(name) {
	return name ? `${name.charAt(0).toUpperCase()}${name.slice(1)}` : name;
}
function collectVueTemplateComponentTagInfo(template, filename) {
	const templateTags = collectVueTemplateTags(template, {
		filename,
		warnLabel: "自动 usingComponents",
		shouldCollect: (tag) => VUE_COMPONENT_TAG_RE.test(tag) || isAutoImportCandidateTag(tag)
	});
	const componentNames = /* @__PURE__ */ new Set();
	const tagsByComponentName = /* @__PURE__ */ new Map();
	for (const tag of templateTags) {
		const camelName = kebabToCamel(tag);
		for (const componentName of [
			tag,
			camelName,
			capitalize(camelName)
		]) {
			componentNames.add(componentName);
			const matchedTags = tagsByComponentName.get(componentName) ?? /* @__PURE__ */ new Set();
			matchedTags.add(tag);
			tagsByComponentName.set(componentName, matchedTags);
		}
	}
	return {
		componentNames,
		tagsByComponentName
	};
}
function collectVueTemplateAutoImportTags(template, filename) {
	return collectVueTemplateTags(template, {
		filename,
		warnLabel: "自动导入标签",
		shouldCollect: isAutoImportCandidateTag
	});
}
function collectScriptSetupImports(scriptSetup, templateComponentNames, options) {
	return collectScriptSetupImportsFromCode(scriptSetup, templateComponentNames, options);
}
async function scanTemplateEntry(pluginCtx, id, scanTemplateEntryFn, existsCache, ttlMs, platform) {
	return ensureTemplateScanned(pluginCtx, id, scanTemplateEntryFn, existsCache, ttlMs, platform);
}
async function applyScriptSetupUsingComponents(options) {
	const { pluginCtx, vueEntryPath, source, templatePath, json, configService, wxmlService, reExportResolutionCache, externalComponentEntryMap } = options;
	try {
		if (source !== void 0 && !hasTemplateComponentTagHint(source)) return;
		const { descriptor, errors } = await readAndParseSfc(vueEntryPath, { ...createReadAndParseSfcOptions(pluginCtx, configService, source === void 0 ? void 0 : { source }) });
		if (!errors?.length && descriptor?.template && !templatePath) {
			const tags = collectVueTemplateAutoImportTags(descriptor.template.content, vueEntryPath);
			if (tags.size) {
				const components = Object.fromEntries(Array.from(tags, (tag) => [tag, [{
					start: 0,
					end: 0
				}]]));
				wxmlService?.setWxmlComponentsMap(vueEntryPath, components);
			}
		}
		if (!errors?.length && descriptor?.scriptSetup && descriptor?.template) {
			const templateComponentTagInfo = collectVueTemplateComponentTagInfo(descriptor.template.content, vueEntryPath);
			const templateComponentNames = templateComponentTagInfo.componentNames;
			if (templateComponentNames.size) {
				const astEngine = resolveAstEngine(configService.weappViteConfig);
				const imports = collectScriptSetupImports(descriptor.scriptSetup.content, templateComponentNames, { astEngine });
				if (imports.length) {
					const usingComponents = json && typeof json.usingComponents === "object" && json.usingComponents && !Array.isArray(json.usingComponents) ? json.usingComponents : {};
					const resolvedImports = await Promise.all(imports.map(async ({ localName, importSource, importedName, kind }) => {
						const { resolvedId, from: resolvedFrom } = await resolveUsingComponentReference(pluginCtx, configService, reExportResolutionCache, importSource, vueEntryPath, {
							localName,
							kind,
							importedName,
							fallbackRelativeImporterDir: true
						});
						return {
							localName,
							importSource,
							resolvedId,
							from: resolvedFrom,
							templateTags: [...templateComponentTagInfo.tagsByComponentName.get(localName) ?? [localName]]
						};
					}));
					for (const { importSource, resolvedId, from: resolvedFrom, templateTags } of resolvedImports) {
						let from = resolvedFrom;
						if (!from && importSource.startsWith("/")) from = removeExtensionDeep(importSource);
						if (!from) continue;
						for (const tag of templateTags) {
							if (Reflect.has(usingComponents, tag) && usingComponents[tag] !== from) logger_default.warn(`[自动 usingComponents] 冲突:${vueEntryPath} 中 usingComponents['${tag}']='${usingComponents[tag]}' 将被 <script setup> 导入覆盖为 '${from}'`);
							usingComponents[tag] = from;
						}
						if (resolvedId) externalComponentEntryMap?.set(removeExtensionDeep(from).replace(/^\/+/, ""), resolvedId);
					}
					json.usingComponents = usingComponents;
				}
			}
		}
	} catch (error) {
		if (error && typeof error === "object" && "code" in error && error.code === "ENOENT" && configService?.isDev && !await fs$1.pathExists(vueEntryPath)) return;
		const message = error instanceof Error ? error.message : String(error);
		logger_default.warn(`[自动 usingComponents] 解析失败:${vueEntryPath}:${message}`);
	}
}
//#endregion
//#region src/utils/importMeta.ts
const IMPORT_META_ENV_PREFIX = "import.meta.env.";
function parseImportMetaDefineValue(value) {
	if (typeof value !== "string") return value;
	try {
		return JSON.parse(value);
	} catch {
		return value;
	}
}
function extractImportMetaEnvJson(value) {
	const normalized = value.trim();
	const matched = normalized.match(/^JSON\.parse\((.+)\)$/s);
	if (!matched) return normalized;
	const parsed = parseImportMetaDefineValue(matched[1]);
	return typeof parsed === "string" ? parsed : normalized;
}
function parseImportMetaEnvObject(value) {
	const parsed = parseImportMetaDefineValue(typeof value === "string" ? extractImportMetaEnvJson(value) : value);
	if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
	return parsed;
}
function pickImportMetaEnvDefineEntries(define) {
	if (!define) return {};
	return Object.fromEntries(Object.entries(define).filter(([key]) => {
		return key === "import.meta.env" || key.startsWith(IMPORT_META_ENV_PREFIX);
	}));
}
function resolveImportMetaEnvObject(defineImportMetaEnv, fallbackEnv = {}) {
	return parseImportMetaEnvObject(defineImportMetaEnv?.["import.meta.env"]) ?? fallbackEnv;
}
function resolveImportMetaEnvExpression(defineImportMetaEnv, fallbackEnv = {}) {
	const rawEnv = defineImportMetaEnv?.["import.meta.env"];
	if (typeof rawEnv === "string" && rawEnv.trim()) return rawEnv;
	return JSON.stringify(resolveImportMetaEnvObject(defineImportMetaEnv, fallbackEnv));
}
function resolveImportMetaEnvMemberValues(defineImportMetaEnv, fallbackEnv = {}) {
	const values = { ...resolveImportMetaEnvObject(defineImportMetaEnv, fallbackEnv) };
	for (const [key, value] of Object.entries(defineImportMetaEnv ?? {})) {
		if (key === "import.meta.env" || !key.startsWith(IMPORT_META_ENV_PREFIX)) continue;
		values[key.slice(16)] = parseImportMetaDefineValue(value);
	}
	return values;
}
function createImportMetaDefineRegistry(options) {
	const baseEnv = { ...options?.baseEnv ?? {} };
	const explicitDefineEntries = pickImportMetaEnvDefineEntries(options?.defineEntries);
	const defaultDefineEntries = {};
	for (const [key, value] of Object.entries(baseEnv)) defaultDefineEntries[`${IMPORT_META_ENV_PREFIX}${key}`] = JSON.stringify(value);
	defaultDefineEntries["import.meta.env"] = resolveImportMetaEnvExpression(void 0, baseEnv);
	const defineEntries = {
		...defaultDefineEntries,
		...explicitDefineEntries
	};
	return {
		defineEntries,
		envObject: resolveImportMetaEnvObject(defineEntries, baseEnv),
		envMemberAccess: resolveImportMetaEnvMemberValues(defineEntries, baseEnv)
	};
}
function createStaticImportMetaValues(options) {
	const normalizedRelativePath = normalizeRelativePath$1(path.extname(options.relativePath) ? options.relativePath.slice(0, -path.extname(options.relativePath).length) : options.relativePath);
	const normalizedExtension = options.extension.startsWith(".") ? options.extension.slice(1) : options.extension;
	const url = `/${normalizedRelativePath}${normalizedExtension ? `.${normalizedExtension}` : ""}`;
	const dirname = normalizeRelativePath$1(path.dirname(url)) || "/";
	return {
		filename: url,
		url,
		dirname: dirname === "." ? "/" : dirname,
		env: options.importMetaDefineRegistry?.envObject ?? {},
		envAccess: options.importMetaDefineRegistry?.envMemberAccess ?? {}
	};
}
function createStaticImportMetaReplacementMap(options) {
	const values = createStaticImportMetaValues(options);
	const defineEntries = options.importMetaDefineRegistry?.defineEntries ?? {};
	const envJson = resolveImportMetaEnvExpression(defineEntries, values.env);
	return {
		...defineEntries,
		"import.meta.filename": JSON.stringify(values.filename),
		"import.meta.url": JSON.stringify(values.url),
		"import.meta.dirname": JSON.stringify(values.dirname),
		"import.meta": `{"filename":${JSON.stringify(values.filename)},"url":${JSON.stringify(values.url)},"dirname":${JSON.stringify(values.dirname)},"env":${envJson}}`
	};
}
//#endregion
//#region src/utils/wxmlScriptModule.ts
const IMPORT_SJS_TAG_RE = /<import-sjs([\s\S]*?)>/g;
const IMPORT_SJS_SRC_RE = /\bsrc\s*=\s*/g;
const IMPORT_SJS_MODULE_RE = /\bmodule\s*=\s*/g;
const DEFAULT_SCRIPT_MODULE_TAG_NAMES = ["wxs", "sjs"];
const DEFAULT_SCRIPT_MODULE_TAG_BY_EXTENSION = Object.freeze({
	wxs: "wxs",
	sjs: "sjs"
});
const SCRIPT_MODULE_IMPORT_ATTRS = Object.freeze({
	"wxs": ["src"],
	"sjs": ["src"],
	"import-sjs": ["from"]
});
function resolveScriptModuleTagByPlatform(platform, scriptModuleExtension) {
	return getPlatformScriptModuleTag(platform, scriptModuleExtension);
}
function normalizeScriptModuleExtension(scriptModuleExtension) {
	if (!scriptModuleExtension) return;
	return scriptModuleExtension.startsWith(".") ? scriptModuleExtension.slice(1) : scriptModuleExtension;
}
function getDefaultScriptModuleTagByExtension(scriptModuleExtension) {
	if (!scriptModuleExtension) return "wxs";
	const normalizedExtension = normalizeScriptModuleExtension(scriptModuleExtension);
	if (!normalizedExtension || !(normalizedExtension in DEFAULT_SCRIPT_MODULE_TAG_BY_EXTENSION)) return "wxs";
	return DEFAULT_SCRIPT_MODULE_TAG_BY_EXTENSION[normalizedExtension];
}
function resolveScriptModuleTagName(options) {
	if (options?.scriptModuleTag) return options.scriptModuleTag;
	return resolveScriptModuleTagByPlatform(options?.platform, options?.scriptModuleExtension) ?? getDefaultScriptModuleTagByExtension(options?.scriptModuleExtension);
}
function getDerivedScriptModuleTagNames() {
	return MINI_PROGRAM_PLATFORM_ADAPTERS.flatMap((adapter) => Object.values(adapter.scriptModuleTagByExtension ?? {})).filter((value) => typeof value === "string" && value.length > 0);
}
function getScriptModuleTagNames() {
	return [.../* @__PURE__ */ new Set([...DEFAULT_SCRIPT_MODULE_TAG_NAMES, ...getDerivedScriptModuleTagNames()])];
}
function isScriptModuleTagName(tagName) {
	return typeof tagName === "string" && getScriptModuleTagNames().includes(tagName);
}
function getScriptModuleImportAttrs(tagName) {
	if (!tagName) return;
	if (!(tagName in SCRIPT_MODULE_IMPORT_ATTRS)) return;
	return SCRIPT_MODULE_IMPORT_ATTRS[tagName];
}
function isScriptModuleImportAttr(tagName, attrName) {
	if (!tagName) return false;
	return getScriptModuleImportAttrs(tagName)?.includes(attrName) === true;
}
function shouldNormalizeScriptModuleAttributes(tagName) {
	return tagName === "import-sjs";
}
function normalizeImportSjsAttributes(source) {
	return source.replace(IMPORT_SJS_TAG_RE, (tag) => {
		return tag.replace(IMPORT_SJS_SRC_RE, "from=").replace(IMPORT_SJS_MODULE_RE, "name=");
	});
}
//#endregion
//#region src/wxs/utils.ts
function normalizeWxsFilename(value, extension = "wxs") {
	const normalized = extension.startsWith(".") ? extension.slice(1) : extension;
	let filename = value;
	filename = filename.replace(/\.[jt]s$/i, "");
	filename = filename.replace(/\.(wxs|sjs)$/i, "");
	return addExtension(filename, `.${normalized}`);
}
//#endregion
//#region src/wxs/index.ts
function transformWxsCode(code, options) {
	const filename = options?.filename ?? "script.ts";
	const extension = options?.extension ?? "wxs";
	const preserveEsmExports = extension.replace(/^\./, "") === "sjs";
	const importees = [];
	const maybePushImportee = (value) => {
		if (typeof value !== "string" || !value) return;
		importees.push({ source: value });
	};
	const tryCollectArgument = (path) => {
		const node = path.node;
		if (t.isStringLiteral(node)) {
			maybePushImportee(node.value);
			return;
		}
		if (t.isTemplateLiteral(node) && node.expressions.length === 0) {
			const value = node.quasis.map((q) => q.value.cooked ?? q.value.raw ?? "").join("");
			maybePushImportee(value);
			return;
		}
		try {
			const evaluated = path.evaluate();
			if (evaluated.confident) maybePushImportee(evaluated.value);
		} catch {}
	};
	return {
		result: babel.transformSync(code, {
			babelrc: false,
			configFile: false,
			presets: [[babelPresetEnv, {
				modules: preserveEsmExports ? false : "commonjs",
				targets: { ie: "11" }
			}], babelPresetTypescript],
			filename,
			plugins: [{ visitor: {
				Directive: { enter(p) {
					p.remove();
				} },
				CallExpression: { enter(p) {
					const node = p.node;
					if (!t.isIdentifier(node.callee, { name: "require" })) return;
					if (node.arguments.length !== 1) return;
					const argPath = p.get("arguments.0");
					tryCollectArgument(argPath);
					const arg = node.arguments[0];
					if (t.isStringLiteral(arg)) arg.value = normalizeWxsFilename(arg.value, extension);
				} },
				ExpressionStatement(p) {
					const expression = p.node.expression;
					if (expression.type === "CallExpression" && expression.callee.type === "MemberExpression" && t.isIdentifier(expression.callee.object) && expression.callee.object.name === "Object" && t.isIdentifier(expression.callee.property) && expression.callee.property.name === "defineProperty" && expression.arguments.length >= 2 && t.isIdentifier(expression.arguments[0]) && expression.arguments[0].name === "exports" && t.isStringLiteral(expression.arguments[1]) && expression.arguments[1].value === "__esModule") p.remove();
				},
				AssignmentExpression: { enter(p) {
					if (!preserveEsmExports || p.node.operator !== "=") return;
					const left = p.node.left;
					if (!t.isMemberExpression(left) || left.computed || !t.isIdentifier(left.object, { name: "module" }) || !t.isIdentifier(left.property, { name: "exports" }) || !p.parentPath.isExpressionStatement()) return;
					p.parentPath.replaceWith(t.exportDefaultDeclaration(p.node.right));
				} },
				NewExpression: { enter(p) {
					const node = p.node;
					if (t.isIdentifier(node.callee, { name: "RegExp" })) p.replaceWith(t.callExpression(t.identifier("getRegExp"), node.arguments));
					else if (t.isIdentifier(node.callee, { name: "Date" })) p.replaceWith(t.callExpression(t.identifier("getDate"), node.arguments));
				} },
				RegExpLiteral: { enter(p) {
					const args = [t.stringLiteral(p.node.pattern)];
					if (p.node.flags) args.push(t.stringLiteral(p.node.flags));
					p.replaceWith(t.callExpression(t.identifier("getRegExp"), args));
				} },
				MemberExpression: { enter(p) {
					if (preserveEsmExports) return;
					const node = p.node;
					if (!t.isIdentifier(node.object, { name: "exports" })) return;
					const moduleExports = t.memberExpression(t.identifier("module"), t.identifier("exports"));
					p.replaceWith(t.memberExpression(moduleExports, node.property, node.computed));
				} },
				ImportDeclaration: { enter(p) {
					maybePushImportee(p.node.source.value);
				} }
			} }]
		}),
		importees
	};
}
//#endregion
//#region src/wxml/handle.ts
const handleCache = /* @__PURE__ */ new WeakMap();
const inlineWxsTransformCache = /* @__PURE__ */ new Map();
const INLINE_WXS_CACHE_LIMIT = 256;
const IDENTIFIER_CHAR_RE = /[\w$]/;
function escapeRegExp$1(source) {
	return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function isInsideMustache(code, start, end) {
	const open = code.lastIndexOf("{{", start);
	if (open < 0) return false;
	return code.indexOf("}}", open + 2) >= end;
}
function getMustacheBounds(code, start, end) {
	const open = code.lastIndexOf("{{", start);
	if (open < 0) return null;
	const close = code.indexOf("}}", end);
	if (close < 0) return null;
	return {
		open,
		close
	};
}
function isWholeMustacheExpression(code, start, end, expression) {
	const bounds = getMustacheBounds(code, start, end);
	if (!bounds) return false;
	return code.slice(bounds.open + 2, bounds.close).trim() === expression;
}
function getMustacheOuterQuote(code, start) {
	const open = code.lastIndexOf("{{", start);
	if (open <= 0) return null;
	for (let index = open - 1; index >= 0; index--) {
		const char = code[index];
		if (char === "\"" || char === "'") return char;
		if (char === "<" || char === ">" || char === "\n" || char === "\r") break;
	}
	return null;
}
function toQuotedLiteral(value, quote, outerQuote = null) {
	try {
		const parsed = JSON.parse(value);
		let escaped = (typeof parsed === "string" ? parsed : JSON.stringify(parsed)).replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
		if (outerQuote === "\"") escaped = escaped.replace(/"/g, "&quot;");
		else if (outerQuote === "'") escaped = escaped.replace(/'/g, "&apos;");
		return quote === "'" ? `'${escaped.replace(/'/g, "\\'")}'` : `"${escaped.replace(/"/g, "\\\"")}"`;
	} catch {
		return value;
	}
}
function toMustacheReplacementValue(code, start, end, expression, value) {
	try {
		const parsed = JSON.parse(value);
		const outerQuote = getMustacheOuterQuote(code, start);
		if (typeof parsed === "string") return toQuotedLiteral(value, outerQuote === "'" ? "\"" : "'", outerQuote);
		if (isWholeMustacheExpression(code, start, end, expression)) {
			if (typeof parsed === "number") return Number.isFinite(parsed) ? String(parsed) : value;
			if (typeof parsed === "boolean") return parsed ? "true" : "false";
			if (parsed == null) return "null";
		}
		return String(value);
	} catch {
		return value;
	}
}
function replaceDefineImportMetaEnv(code, defineImportMetaEnv) {
	if (!defineImportMetaEnv || Object.keys(defineImportMetaEnv).length === 0) return code;
	const entries = Object.entries(defineImportMetaEnv).sort(([leftKey], [rightKey]) => rightKey.length - leftKey.length);
	const replacementRanges = [];
	for (const [key, value] of entries) {
		if (!(key === "import.meta.url" || key === "import.meta.dirname" || key.startsWith("import.meta.env.")) || key === "import.meta.env") continue;
		const pattern = new RegExp(escapeRegExp$1(key), "g");
		for (const match of code.matchAll(pattern)) {
			const start = match.index ?? -1;
			if (start < 0) continue;
			const end = start + key.length;
			const previous = start > 0 ? code[start - 1] : "";
			const next = end < code.length ? code[end] : "";
			if (previous && IDENTIFIER_CHAR_RE.test(previous) || next && IDENTIFIER_CHAR_RE.test(next)) continue;
			if (replacementRanges.some((range) => !(end <= range.start || start >= range.end))) continue;
			replacementRanges.push({
				start,
				end,
				value: isInsideMustache(code, start, end) ? toMustacheReplacementValue(code, start, end, key, String(value)) : String(value)
			});
		}
	}
	if (replacementRanges.length === 0) return code;
	const ms = new MagicString(code);
	for (const range of replacementRanges.sort((left, right) => left.start - right.start)) ms.update(range.start, range.end, range.value);
	return ms.toString();
}
function resolveDefineImportMetaEnv(options) {
	if (options.importMetaDefineRegistry && options.importMetaRelativePath) return createStaticImportMetaReplacementMap({
		importMetaDefineRegistry: options.importMetaDefineRegistry,
		extension: options.importMetaExtension ?? options.templateExtension ?? "",
		relativePath: options.importMetaRelativePath
	});
	return options.defineImportMetaEnv;
}
function createCacheKey$1(options) {
	const extension = options.scriptModuleExtension ?? "";
	const tag = options.scriptModuleTag ?? "";
	const templateExt = options.templateExtension ?? "";
	const importMetaRelativePath = options.importMetaRelativePath ?? "";
	const importMetaExtension = options.importMetaExtension ?? "";
	const resolvedDefineImportMetaEnv = resolveDefineImportMetaEnv(options);
	const defineKeys = resolvedDefineImportMetaEnv ? Object.keys(resolvedDefineImportMetaEnv).sort().map((key) => `${key}:${String(resolvedDefineImportMetaEnv[key])}`).join(",") : "";
	return `${options.removeComment ? 1 : 0}|${options.transformEvent ? 1 : 0}|${options.transformPlatformSyntax ? 1 : 0}|${extension}|${tag}|${templateExt}|${importMetaExtension}|${importMetaRelativePath}|${defineKeys}`;
}
function getCachedResult(data, cacheKey) {
	return handleCache.get(data)?.get(cacheKey);
}
function setCachedResult(data, cacheKey, result) {
	let cacheForToken = handleCache.get(data);
	if (!cacheForToken) {
		cacheForToken = /* @__PURE__ */ new Map();
		handleCache.set(data, cacheForToken);
	}
	cacheForToken.set(cacheKey, result);
	return result;
}
function getCachedInlineWxsTransform(code, extension) {
	const key = `${extension}::${code}`;
	const cached = inlineWxsTransformCache.get(key);
	if (cached) {
		inlineWxsTransformCache.delete(key);
		inlineWxsTransformCache.set(key, cached);
		return cached;
	}
	const transformed = transformWxsCode(code, { extension });
	inlineWxsTransformCache.set(key, transformed);
	if (inlineWxsTransformCache.size > INLINE_WXS_CACHE_LIMIT) {
		const firstKey = inlineWxsTransformCache.keys().next().value;
		if (firstKey) inlineWxsTransformCache.delete(firstKey);
	}
	return transformed;
}
function handleWxml(data, options) {
	const opts = defu(options, {
		defineImportMetaEnv: void 0,
		importMetaDefineRegistry: void 0,
		importMetaRelativePath: void 0,
		importMetaExtension: void 0,
		removeComment: true,
		transformEvent: true,
		transformPlatformSyntax: true,
		scriptModuleExtension: void 0,
		scriptModuleTag: void 0,
		templateExtension: void 0
	});
	const cacheKey = createCacheKey$1(opts);
	const cached = getCachedResult(data, cacheKey);
	if (cached) return cached;
	const { code, removalRanges = [], commentTokens = [], eventTokens = [], directiveTokens = [], tagNameTokens = [], inlineWxsTokens = [], removeWxsLangAttrTokens = [], scriptModuleTagTokens = [], wxsImportNormalizeTokens = [], templateImportNormalizeTokens = [], components, deps } = data;
	const normalizedScriptExtension = opts.scriptModuleExtension?.startsWith(".") ? opts.scriptModuleExtension.slice(1) : opts.scriptModuleExtension;
	const normalizedTemplateExtension = opts.templateExtension?.startsWith(".") ? opts.templateExtension.slice(1) : opts.templateExtension;
	const resolvedScriptTag = resolveScriptModuleTagName({
		scriptModuleExtension: normalizedScriptExtension,
		scriptModuleTag: opts.scriptModuleTag
	});
	const shouldTransformPlatformSyntax = opts.transformPlatformSyntax;
	const shouldNormalizeImports = shouldTransformPlatformSyntax && wxsImportNormalizeTokens.length > 0;
	const shouldNormalizeTemplateImports = shouldTransformPlatformSyntax && templateImportNormalizeTokens.length > 0 && normalizedTemplateExtension;
	const shouldRemoveLang = shouldTransformPlatformSyntax && removeWxsLangAttrTokens.length > 0;
	const shouldTransformInlineWxs = shouldTransformPlatformSyntax && inlineWxsTokens.length > 0;
	const shouldTransformEvents = shouldTransformPlatformSyntax && opts.transformEvent && eventTokens.length > 0;
	const shouldTransformDirectives = shouldTransformPlatformSyntax && directiveTokens.length > 0;
	const shouldTransformTagNames = shouldTransformPlatformSyntax && tagNameTokens.length > 0;
	const shouldTransformScriptModuleTags = shouldTransformPlatformSyntax && resolvedScriptTag !== "wxs" && scriptModuleTagTokens.length > 0;
	const shouldRemoveConditionals = removalRanges.length > 0;
	const shouldRemoveComments = opts.removeComment && commentTokens.length > 0;
	const resolvedDefineImportMetaEnv = resolveDefineImportMetaEnv(opts);
	const shouldReplaceDefineImportMetaEnv = !!resolvedDefineImportMetaEnv && Object.keys(resolvedDefineImportMetaEnv).length > 0;
	if (!shouldNormalizeImports && !shouldNormalizeTemplateImports && !shouldRemoveLang && !shouldTransformInlineWxs && !shouldTransformEvents && !shouldTransformDirectives && !shouldTransformTagNames && !shouldTransformScriptModuleTags && !shouldRemoveConditionals && !shouldRemoveComments && !shouldReplaceDefineImportMetaEnv) return setCachedResult(data, cacheKey, {
		code,
		components,
		deps
	});
	const ms = new MagicString(code);
	if (shouldNormalizeImports) for (const { start, end, value } of wxsImportNormalizeTokens) ms.update(start, end, normalizeWxsFilename(value, normalizedScriptExtension ?? "wxs"));
	if (shouldNormalizeTemplateImports) for (const { start, end, value } of templateImportNormalizeTokens) {
		let nextValue = changeFileExtension(value, normalizedTemplateExtension);
		if (value.startsWith("./") && !nextValue.startsWith("./") && !nextValue.startsWith("../") && !nextValue.startsWith("/")) nextValue = `./${nextValue}`;
		ms.update(start, end, nextValue);
	}
	if (shouldRemoveLang) for (const { start, end } of removeWxsLangAttrTokens) ms.update(start, end, "");
	if (shouldTransformInlineWxs) for (const { end, start, value } of inlineWxsTokens) {
		const { result } = getCachedInlineWxsTransform(value, normalizedScriptExtension ?? "wxs");
		if (result?.code) ms.update(start, end, `\n${result.code}`);
	}
	if (shouldTransformScriptModuleTags) {
		const visited = /* @__PURE__ */ new Set();
		for (const { start, end } of scriptModuleTagTokens) {
			const key = `${start}:${end}`;
			if (visited.has(key)) continue;
			visited.add(key);
			ms.update(start, end, resolvedScriptTag);
		}
	}
	if (shouldTransformEvents) for (const { end, start, value } of eventTokens) ms.update(start, end, value);
	if (shouldTransformDirectives) for (const { end, start, value } of directiveTokens) ms.update(start, end, value);
	if (shouldTransformTagNames) for (const { end, start, value } of tagNameTokens) ms.update(start, end, value);
	if (shouldRemoveConditionals) {
		for (const { start, end } of removalRanges) if (end > start) ms.remove(start, end);
	}
	if (shouldRemoveComments) for (const { end, start } of commentTokens) ms.remove(start, end);
	return setCachedResult(data, cacheKey, {
		code: replaceDefineImportMetaEnv(shouldTransformPlatformSyntax && shouldNormalizeScriptModuleAttributes(resolvedScriptTag) ? normalizeImportSjsAttributes(ms.toString()) : ms.toString(), resolvedDefineImportMetaEnv),
		components,
		deps
	});
}
//#endregion
//#region src/wxml/scan/cache.ts
const scanWxmlCache = new LRUCache({ max: 512 });
function fnv1aHash(input) {
	let hash = 2166136261;
	for (let i = 0; i < input.length; i++) {
		hash ^= input.charCodeAt(i);
		hash = Math.imul(hash, 16777619);
	}
	return (hash >>> 0).toString(36);
}
function createCacheKey(source, platform) {
	return `${platform}:${source.length.toString(36)}:${fnv1aHash(source)}`;
}
//#endregion
//#region src/wxml/scan/events.ts
const ALIPAY_COLON_EVENT_RE = /^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;
const ALIPAY_PLAIN_EVENT_RE = /^(bind|catch)([A-Za-z].*)$/;
function toPascalCaseEvent(eventName) {
	return `${(eventName[0] ?? "").toUpperCase()}${eventName.slice(1)}`;
}
function resolveAlipayEventName(prefix, eventName) {
	const pascalEvent = toPascalCaseEvent(eventName);
	switch (prefix) {
		case "bind": return `on${pascalEvent}`;
		case "catch": return `catch${pascalEvent}`;
		case "capture-bind": return `capture${pascalEvent}`;
		case "capture-catch": return `captureCatch${pascalEvent}`;
		default: return `on${pascalEvent}`;
	}
}
function resolveAlipayNativeEventBinding(raw) {
	const colonMatch = ALIPAY_COLON_EVENT_RE.exec(raw);
	if (colonMatch) {
		const prefix = colonMatch[1];
		const eventName = colonMatch[2];
		return resolveAlipayEventName(prefix, eventName);
	}
	const plainMatch = ALIPAY_PLAIN_EVENT_RE.exec(raw);
	if (plainMatch) {
		const prefix = plainMatch[1];
		const eventName = plainMatch[2];
		return resolveAlipayEventName(prefix, eventName[0].toLowerCase() + eventName.slice(1));
	}
}
function resolveEventDirective(raw, platform) {
	if (!raw.startsWith("@")) return;
	const { eventBindingStyle } = getWxmlPlatformTransformOptions(platform);
	let dir = "";
	let segment = "";
	let hasCatch = false;
	let hasStop = false;
	let hasCapture = false;
	let hasMut = false;
	const flush = () => {
		if (!segment) return;
		if (!dir) dir = segment;
		else if (segment === "catch") hasCatch = true;
		else if (segment === "stop") hasStop = true;
		else if (segment === "capture") hasCapture = true;
		else if (segment === "mut") hasMut = true;
		segment = "";
	};
	for (let i = 1; i < raw.length; i++) {
		const ch = raw[i];
		if (ch === ".") flush();
		else segment += ch;
	}
	flush();
	if (!dir) return;
	let prefix = "bind";
	if ((hasCatch || hasStop) && hasCapture) prefix = "capture-catch";
	else if (hasCatch || hasStop) prefix = "catch";
	else if (hasMut) prefix = "mut-bind";
	else if (hasCapture) prefix = "capture-bind";
	if (eventBindingStyle === "alipay") return resolveAlipayEventName(prefix, dir);
	return `${prefix}:${dir}`;
}
function defaultExcludeComponent(tagName) {
	return isBuiltinComponent(tagName);
}
function resolveEventDirectiveName(raw, platform) {
	const resolvedPlatform = resolveMiniPlatformWithDefault(platform);
	const directive = resolveEventDirective(raw, resolvedPlatform);
	if (directive) return directive;
	if (getWxmlPlatformTransformOptions(resolvedPlatform).eventBindingStyle === "alipay") return resolveAlipayNativeEventBinding(raw);
}
//#endregion
//#region src/wxml/shared.ts
const TEMPLATE_IMPORT_RE = /\.(?:wxml|html)$/i;
const TEMPLATE_IMPORT_TAG_NAMES = ["import", "include"];
const TEMPLATE_IMPORT_ATTRS = Object.freeze({
	import: ["src"],
	include: ["src"]
});
function isTemplateImportTag(tagName) {
	return typeof tagName === "string" && TEMPLATE_IMPORT_TAG_NAMES.includes(tagName);
}
function getTemplateImportAttrs(tagName) {
	if (!tagName) return;
	if (!(tagName in TEMPLATE_IMPORT_ATTRS)) return;
	return TEMPLATE_IMPORT_ATTRS[tagName];
}
function isTemplateImportAttr(tagName, attrName) {
	if (!tagName) return false;
	return getTemplateImportAttrs(tagName)?.includes(attrName) === true;
}
function shouldNormalizeTemplateImportSource(value) {
	return TEMPLATE_IMPORT_RE.test(value);
}
//#endregion
//#region src/wxml/scan/parser.ts
const wxsScriptExtensions = /* @__PURE__ */ new Set(["js", "ts"]);
const TAG_NAME_LOWER_TO_UPPER_RE = /([a-z0-9])([A-Z])/g;
const TAG_NAME_MULTI_UPPER_RE = /([A-Z]+)([A-Z][a-z])/g;
const TAG_NAME_HAS_UPPER_RE = /[A-Z]/;
const SCRIPT_MODULE_IMPORT_RE = /\.(?:wxs|sjs)(?:\.[jt]s)?$/i;
const COMMENT_IFDEF_RE = /#ifdef\s+(\w+)/;
const COMMENT_ENDIF_RE = /#endif/;
const MP_DIRECTIVE_NAME_RE = /^([a-z]+):(if|elif|else|for|for-item|for-index|key)$/;
const LEGACY_WEAPP_DIRECTIVE_NAME_RE = /^wx-(if|for)$/;
const GLASS_EASEL_ESCAPE_RE = /\\["']/;
const SUPPORTED_MP_DIRECTIVE_PREFIXES = new Set(getSupportedMiniProgramDirectivePrefixes());
function toKebabCaseTagName(tagName) {
	return tagName.replace(TAG_NAME_LOWER_TO_UPPER_RE, "$1-$2").replace(TAG_NAME_MULTI_UPPER_RE, "$1-$2").toLowerCase();
}
function shouldNormalizeTagName(tagName) {
	return TAG_NAME_HAS_UPPER_RE.test(tagName);
}
function parseWxml(options) {
	const { source, platform, excludeComponent } = options;
	const { directivePrefix, normalizeComponentTagName } = getWxmlPlatformTransformOptions(platform);
	const deps = [];
	let currentTagName;
	let importAttrs;
	let attrs = {};
	const components = {};
	const autoImportComponents = {};
	let tagStartIndex = 0;
	const removalRanges = [];
	const conditionalStack = [];
	const commentTokens = [];
	const inlineWxsTokens = [];
	const templateTokens = [];
	const scriptModules = [];
	const scriptModuleTagTokens = [];
	const wxsImportNormalizeTokens = [];
	const removeWxsLangAttrTokens = [];
	const templateImportNormalizeTokens = [];
	const eventTokens = [];
	const directiveTokens = [];
	const glassEaselFindings = [];
	const tagNameTokens = [];
	const tagStack = [];
	const loopStack = [];
	let loopDepth = 0;
	let currentHasLoopDirective = false;
	const parser = new Parser({
		onopentagname(name) {
			tagStack.push(name);
			currentTagName = name;
			importAttrs = getScriptModuleImportAttrs(currentTagName) ?? getTemplateImportAttrs(currentTagName);
			tagStartIndex = parser.startIndex;
			currentHasLoopDirective = false;
			if (normalizeComponentTagName && shouldNormalizeTagName(name)) {
				const normalized = toKebabCaseTagName(name);
				if (normalized !== name) tagNameTokens.push({
					start: parser.startIndex + 1,
					end: parser.startIndex + 1 + name.length,
					value: normalized
				});
			}
			if (isScriptModuleTagName(name)) scriptModuleTagTokens.push({
				start: parser.startIndex + 1,
				end: parser.startIndex + 1 + name.length,
				value: name
			});
		},
		onattribute(name, value, quote) {
			attrs[name] = value;
			const legacyDirectiveMatch = LEGACY_WEAPP_DIRECTIVE_NAME_RE.exec(name);
			if (legacyDirectiveMatch) {
				const start = parser.startIndex;
				const end = start + name.length;
				directiveTokens.push({
					start,
					end,
					value: `${directivePrefix}:${legacyDirectiveMatch[1]}`
				});
				glassEaselFindings.push({
					code: "GE002",
					severity: "warning",
					message: `${name} 不受 glass-easel 支持,已安全归一化为 ${directivePrefix}:${legacyDirectiveMatch[1]}。`,
					start,
					normalized: true
				});
			}
			if (name === "wx:for" || name === "wx-for" || name === "let:for") currentHasLoopDirective = true;
			const rawAttribute = source.slice(parser.startIndex, parser.endIndex + 1);
			if (GLASS_EASEL_ESCAPE_RE.test(rawAttribute)) glassEaselFindings.push({
				code: "GE004",
				severity: "error",
				message: "属性仍使用反斜杠转义引号,请改用 &quot;、&apos; 或调整属性外层引号。",
				start: parser.startIndex
			});
			if (!currentTagName || !isScriptModuleTagName(currentTagName)) templateTokens.push({
				start: parser.startIndex,
				end: parser.endIndex + 1,
				value
			});
			if (importAttrs && currentTagName) {
				for (const attrName of importAttrs) if (attrName === name) {
					deps.push({
						name,
						value,
						quote,
						tagName: currentTagName,
						start: parser.startIndex,
						end: parser.endIndex,
						attrs
					});
					if (isScriptModuleImportAttr(currentTagName, name)) {
						if (SCRIPT_MODULE_IMPORT_RE.test(value)) {
							const valueStart = parser.startIndex + name.length + 2;
							wxsImportNormalizeTokens.push({
								start: valueStart,
								end: parser.endIndex - 1,
								value
							});
						}
					}
					if (isTemplateImportAttr(currentTagName, name) && shouldNormalizeTemplateImportSource(value)) {
						const valueStart = parser.startIndex + name.length + 2;
						templateImportNormalizeTokens.push({
							start: valueStart,
							end: parser.endIndex - 1,
							value
						});
					}
				}
			}
			{
				const start = parser.startIndex;
				const end = parser.startIndex + name.length;
				const rep = resolveEventDirectiveName(name, platform);
				if (rep && rep !== name) eventTokens.push({
					start,
					end,
					value: rep
				});
			}
			{
				const directiveMatch = MP_DIRECTIVE_NAME_RE.exec(name);
				if (directiveMatch && directiveMatch[1] !== directivePrefix && SUPPORTED_MP_DIRECTIVE_PREFIXES.has(directiveMatch[1])) {
					const start = parser.startIndex;
					const end = parser.startIndex + name.length;
					directiveTokens.push({
						start,
						end,
						value: `${directivePrefix}:${directiveMatch[2]}`
					});
				}
			}
			if (currentTagName && isScriptModuleTagName(currentTagName) && name === "lang" && wxsScriptExtensions.has(value)) removeWxsLangAttrTokens.push({
				start: parser.startIndex,
				end: parser.endIndex,
				value
			});
		},
		onopentag(name, attributes) {
			if (name === "include" && loopDepth > 0) glassEaselFindings.push({
				code: "GE003",
				severity: "error",
				message: "wx:for 作用域内的 <include> 无法向 glass-easel 传递循环变量,请改用 <template>。",
				start: tagStartIndex
			});
			loopStack.push(currentHasLoopDirective);
			if (currentHasLoopDirective) loopDepth += 1;
			if (isScriptModuleTagName(name)) scriptModules.push({
				attrs: attributes,
				tagName: name
			});
		},
		onclosetag(name) {
			if (loopStack.pop()) loopDepth -= 1;
			currentTagName = tagStack.pop();
			if (currentTagName) {
				const componentName = normalizeComponentTagName && shouldNormalizeTagName(currentTagName) ? toKebabCaseTagName(currentTagName) : currentTagName;
				const range = {
					start: tagStartIndex,
					end: parser.endIndex + 1
				};
				if (Array.isArray(autoImportComponents[componentName])) autoImportComponents[componentName].push(range);
				else autoImportComponents[componentName] = [range];
				if (!excludeComponent(currentTagName)) {
					if (Array.isArray(components[componentName])) components[componentName].push(range);
					else components[componentName] = [range];
				}
			}
			if (normalizeComponentTagName && shouldNormalizeTagName(name)) {
				const normalized = toKebabCaseTagName(name);
				if (normalized !== name && parser.startIndex !== tagStartIndex) {
					const nameStart = parser.startIndex + 2;
					tagNameTokens.push({
						start: nameStart,
						end: nameStart + name.length,
						value: normalized
					});
				}
			}
			if (currentTagName && isScriptModuleTagName(currentTagName)) {
				if (parser.startIndex !== tagStartIndex) {
					const nameStart = parser.startIndex + 2;
					scriptModuleTagTokens.push({
						start: nameStart,
						end: nameStart + currentTagName.length,
						value: currentTagName
					});
				}
			}
			currentTagName = "";
			attrs = {};
			importAttrs = void 0;
			tagStartIndex = 0;
		},
		ontext(data) {
			if (currentTagName && isScriptModuleTagName(currentTagName) && wxsScriptExtensions.has(attrs.lang)) inlineWxsTokens.push({
				start: parser.startIndex,
				end: parser.endIndex,
				value: data
			});
			else templateTokens.push({
				start: parser.startIndex,
				end: parser.endIndex + 1,
				value: data
			});
		},
		oncomment(data) {
			let match = COMMENT_IFDEF_RE.exec(data);
			if (match) {
				if (match[1] !== platform) conditionalStack.push(parser.startIndex);
			}
			match = COMMENT_ENDIF_RE.exec(data);
			if (match) {
				const start = conditionalStack.pop();
				if (start !== void 0) removalRanges.push({
					start,
					end: parser.endIndex + 1
				});
			}
			commentTokens.push({
				start: parser.startIndex,
				end: parser.endIndex + 1,
				value: ""
			});
		}
	}, {
		lowerCaseTags: false,
		xmlMode: true
	});
	parser.write(source);
	parser.end();
	if (removalRanges.length > 1) removalRanges.sort((a, b) => b.start - a.start);
	return { token: {
		components,
		autoImportComponents,
		deps,
		removalRanges,
		commentTokens,
		inlineWxsTokens,
		scriptModules,
		templateTokens,
		wxsImportNormalizeTokens,
		removeWxsLangAttrTokens,
		templateImportNormalizeTokens,
		scriptModuleTagTokens,
		eventTokens,
		directiveTokens,
		tagNameTokens,
		glassEaselFindings,
		code: source
	} };
}
//#endregion
//#region src/wxml/scan/index.ts
function scanWxml(wxml, options) {
	const source = typeof wxml === "string" ? wxml : wxml.toString();
	const opts = defu(options, {
		excludeComponent: defaultExcludeComponent,
		platform: "weapp"
	});
	const cacheKey = opts.excludeComponent === defaultExcludeComponent ? createCacheKey(source, opts.platform) : void 0;
	if (cacheKey) {
		const cached = scanWxmlCache.get(cacheKey);
		if (cached) return cached;
	}
	const { token } = parseWxml({
		source,
		platform: opts.platform,
		excludeComponent: opts.excludeComponent
	});
	if (cacheKey) scanWxmlCache.set(cacheKey, token);
	return token;
}
//#endregion
//#region src/runtime/tsconfigSupport/shared.ts
const DEFAULT_APP_EXTRA_INCLUDE = [
	"../types/**/*.d.ts",
	"../env.d.ts",
	"./**/*.d.ts"
];
const DEFAULT_NODE_INCLUDE = [
	"../vite.config.ts",
	"../vite.config.*.ts",
	"../vite.config.mts",
	"../vite.config.*.mts",
	"../weapp-vite.config.ts",
	"../weapp-vite.config.*.ts",
	"../weapp-vite.config.mts",
	"../weapp-vite.config.*.mts",
	"../*.config.ts",
	"../*.config.mts",
	"../config/**/*.ts",
	"../config/**/*.mts",
	"../scripts/**/*.ts",
	"../scripts/**/*.mts"
];
const WINDOWS_PATH_SEPARATOR_PATTERN = /\\/g;
const LEADING_DOT_SLASH_PATTERN = /^\.\/+/;
const TRAILING_SLASH_PATTERN = /\/+$/;
function hasDependency(packageJson, name) {
	return Boolean(packageJson?.dependencies?.[name] || packageJson?.devDependencies?.[name] || packageJson?.peerDependencies?.[name]);
}
function unique$1(values) {
	return [...new Set(values)];
}
function rebaseManagedPathValue(root, managedDir, value) {
	if (!value.startsWith("./") && !value.startsWith("../")) return value;
	return path.relative(managedDir, path.resolve(root, value)).replace(WINDOWS_PATH_SEPARATOR_PATTERN, "/");
}
function rebaseManagedPaths(root, managedDir, paths) {
	if (!paths) return;
	return Object.fromEntries(Object.entries(paths).map(([key, values]) => [key, Array.isArray(values) ? values.map((value) => rebaseManagedPathValue(root, managedDir, value)) : []]));
}
function mergePaths(...entries) {
	const merged = {};
	for (const entry of entries) {
		if (!entry) continue;
		for (const [key, value] of Object.entries(entry)) merged[key] = Array.isArray(value) ? [...value] : [];
	}
	return merged;
}
function toJson(content) {
	return `${JSON.stringify(content, null, 2)}\n`;
}
function resolveManagedDir(ctx) {
	return path.resolve(resolveBaseDir(requireConfigService(ctx, "生成托管 tsconfig 前必须初始化 configService。")), WEAPP_VITE_INTERNAL_DIRNAME);
}
function getManagedTypeScriptConfig(ctx) {
	return requireConfigService(ctx, "读取托管 tsconfig 配置前必须初始化 configService。").weappViteConfig.typescript;
}
async function readLegacyManagedTsconfigFile(filePath) {
	try {
		const content = await fs$1.readFile(filePath, "utf8");
		const parsed = parse(content, void 0, true);
		if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
		return parsed;
	} catch {
		return;
	}
}
async function getLegacyManagedTypeScriptConfig(ctx) {
	const root = resolveBaseDir(requireConfigService(ctx, "读取旧 tsconfig 配置前必须初始化 configService。"));
	const [shared, app, node, server] = await Promise.all([
		readLegacyManagedTsconfigFile(path.join(root, "tsconfig.shared.json")),
		readLegacyManagedTsconfigFile(path.join(root, "tsconfig.app.json")),
		readLegacyManagedTsconfigFile(path.join(root, "tsconfig.node.json")),
		readLegacyManagedTsconfigFile(path.join(root, "tsconfig.server.json"))
	]);
	return {
		shared,
		app,
		node,
		server
	};
}
function normalizeSrcRoot(srcRoot) {
	return typeof srcRoot === "string" ? srcRoot.replace(WINDOWS_PATH_SEPARATOR_PATTERN, "/").replace(LEADING_DOT_SLASH_PATTERN, "").replace(TRAILING_SLASH_PATTERN, "") || "src" : "src";
}
function createDefaultAppInclude(srcRoot) {
	return [`../${normalizeSrcRoot(srcRoot)}/**/*`, ...DEFAULT_APP_EXTRA_INCLUDE];
}
//#endregion
//#region src/runtime/tsconfigSupport/configs.ts
function omitDeprecatedCompilerOptions(compilerOptions) {
	if (!compilerOptions || !("baseUrl" in compilerOptions)) return compilerOptions;
	const { baseUrl: _baseUrl, ...rest } = compilerOptions;
	return rest;
}
function getAppTypes(ctx, legacyConfig) {
	const configService = requireConfigService(ctx, "生成 app tsconfig 前必须初始化 configService。");
	const packageJson = configService.packageJson;
	const config = configService.weappViteConfig;
	const userTypes = getManagedTypeScriptConfig(ctx)?.app?.compilerOptions?.types;
	const legacyTypes = legacyConfig?.app?.compilerOptions?.types;
	const platformAppTypesPackage = getPlatformAppTypesPackage(config.platform);
	const types = [platformAppTypesPackage !== "miniprogram-api-typings" && hasDependency(packageJson, platformAppTypesPackage) ? platformAppTypesPackage : "miniprogram-api-typings", "weapp-vite/client"];
	if (Array.isArray(legacyTypes) && legacyTypes.length > 0) types.push(...legacyTypes);
	if (Array.isArray(userTypes) && userTypes.length > 0) types.push(...userTypes);
	return unique$1(types);
}
function getAppPaths(ctx, legacyConfig) {
	const configService = requireConfigService(ctx, "生成 app paths 前必须初始化 configService。");
	const root = resolveBaseDir(configService);
	const managedDir = resolveManagedDir(ctx);
	const userConfig = getManagedTypeScriptConfig(ctx);
	const defaultPaths = { "@/*": [`../${normalizeSrcRoot(configService.srcRoot)}/*`] };
	if (hasDependency(configService.packageJson, "wevu")) defaultPaths["weapp-vite/typed-components"] = ["./typed-components.d.ts"];
	return mergePaths(defaultPaths, rebaseManagedPaths(root, managedDir, legacyConfig?.shared?.compilerOptions?.paths), rebaseManagedPaths(root, managedDir, legacyConfig?.app?.compilerOptions?.paths), rebaseManagedPaths(root, managedDir, userConfig?.shared?.compilerOptions?.paths), rebaseManagedPaths(root, managedDir, userConfig?.app?.compilerOptions?.paths));
}
function createSharedTsconfig(ctx, legacyConfig) {
	const userConfig = getManagedTypeScriptConfig(ctx);
	return {
		compilerOptions: {
			target: "ES2023",
			module: "ESNext",
			moduleResolution: "bundler",
			moduleDetection: "force",
			resolveJsonModule: true,
			allowImportingTsExtensions: true,
			strict: true,
			noFallthroughCasesInSwitch: true,
			noUnusedLocals: true,
			noUnusedParameters: true,
			noEmit: true,
			verbatimModuleSyntax: true,
			noUncheckedSideEffectImports: true,
			erasableSyntaxOnly: true,
			skipLibCheck: true,
			...omitDeprecatedCompilerOptions(legacyConfig?.shared?.compilerOptions) ?? {},
			...omitDeprecatedCompilerOptions(userConfig?.shared?.compilerOptions) ?? {}
		},
		files: ["./tsconfig.shared.empty.d.ts"]
	};
}
function createAppTsconfig(ctx, legacyConfig) {
	const userConfig = getManagedTypeScriptConfig(ctx);
	const legacyAppCompilerOptions = omitDeprecatedCompilerOptions(legacyConfig?.app?.compilerOptions) ?? {};
	const userAppCompilerOptions = omitDeprecatedCompilerOptions(userConfig?.app?.compilerOptions) ?? {};
	const compilerOptions = {
		tsBuildInfoFile: "../node_modules/.tmp/tsconfig.app.tsbuildinfo",
		target: "ES2023",
		lib: ["ES2023", "DOM"],
		jsx: "preserve",
		resolveJsonModule: true,
		allowJs: true,
		allowSyntheticDefaultImports: true,
		esModuleInterop: true,
		isolatedModules: true,
		...legacyAppCompilerOptions,
		...userAppCompilerOptions,
		types: getAppTypes(ctx, legacyConfig),
		paths: getAppPaths(ctx, legacyConfig)
	};
	const vueCompilerOptions = {
		plugins: ["weapp-vite/volar"],
		...hasDependency(requireConfigService(ctx, "生成 Vue tsconfig 前必须初始化 configService。").packageJson, "wevu") ? { lib: "wevu" } : {},
		...legacyConfig?.app?.vueCompilerOptions ?? {},
		...userConfig?.app?.vueCompilerOptions ?? {}
	};
	const include = unique$1([
		...createDefaultAppInclude(requireConfigService(ctx, "生成 app include 前必须初始化 configService。").srcRoot),
		...legacyConfig?.app?.include ?? [],
		...userConfig?.app?.include ?? []
	]);
	const exclude = unique$1([...legacyConfig?.app?.exclude ?? [], ...userConfig?.app?.exclude ?? []]);
	const files = unique$1([...legacyConfig?.app?.files ?? [], ...userConfig?.app?.files ?? []]);
	return {
		extends: "./tsconfig.shared.json",
		compilerOptions,
		vueCompilerOptions,
		include,
		...exclude.length ? { exclude } : {},
		...files.length ? { files } : {}
	};
}
function createNodeTsconfig(ctx, legacyConfig) {
	const userConfig = getManagedTypeScriptConfig(ctx);
	const compilerOptions = {
		tsBuildInfoFile: "../node_modules/.tmp/tsconfig.node.tsbuildinfo",
		target: "ES2023",
		lib: ["ES2023"],
		types: ["node"],
		...omitDeprecatedCompilerOptions(legacyConfig?.node?.compilerOptions) ?? {},
		...omitDeprecatedCompilerOptions(userConfig?.node?.compilerOptions) ?? {}
	};
	const include = unique$1([
		...DEFAULT_NODE_INCLUDE,
		...legacyConfig?.node?.include ?? [],
		...userConfig?.node?.include ?? []
	]);
	const exclude = unique$1([...legacyConfig?.node?.exclude ?? [], ...userConfig?.node?.exclude ?? []]);
	const files = unique$1([...legacyConfig?.node?.files ?? [], ...userConfig?.node?.files ?? []]);
	return {
		extends: "./tsconfig.shared.json",
		compilerOptions,
		include,
		...exclude.length ? { exclude } : {},
		...files.length ? { files } : {}
	};
}
function createServerTsconfig(ctx, legacyConfig) {
	const userConfig = getManagedTypeScriptConfig(ctx);
	const compilerOptions = {
		tsBuildInfoFile: "../node_modules/.tmp/tsconfig.server.tsbuildinfo",
		target: "ES2023",
		lib: ["ES2023"],
		types: ["node"],
		...omitDeprecatedCompilerOptions(legacyConfig?.server?.compilerOptions) ?? {},
		...omitDeprecatedCompilerOptions(userConfig?.server?.compilerOptions) ?? {}
	};
	const files = unique$1([...legacyConfig?.server?.files ?? [], ...userConfig?.server?.files ?? []]);
	const include = unique$1([...legacyConfig?.server?.include ?? [], ...userConfig?.server?.include ?? []]);
	const exclude = unique$1([...legacyConfig?.server?.exclude ?? [], ...userConfig?.server?.exclude ?? []]);
	return {
		extends: "./tsconfig.shared.json",
		compilerOptions,
		files,
		...include.length ? { include } : {},
		...exclude.length ? { exclude } : {}
	};
}
//#endregion
//#region src/runtime/tsconfigSupport/index.ts
async function createManagedTsconfigFiles(ctx) {
	const managedDir = resolveManagedDir(ctx);
	const legacyConfig = await getLegacyManagedTypeScriptConfig(ctx);
	const sharedPath = path.join(managedDir, "tsconfig.shared.json");
	const appPath = path.join(managedDir, "tsconfig.app.json");
	const nodePath = path.join(managedDir, "tsconfig.node.json");
	const serverPath = path.join(managedDir, "tsconfig.server.json");
	const sharedEmptyPath = path.join(managedDir, "tsconfig.shared.empty.d.ts");
	const uniAppTypesPath = path.join(managedDir, "uni-app.d.ts");
	const uniAppEnabled = Boolean(ctx.configService?.weappViteConfig.uniApp);
	return [
		{
			path: sharedEmptyPath,
			content: "export {}\n"
		},
		{
			path: uniAppTypesPath,
			content: uniAppEnabled ? "export {}\n\ndeclare global {\n  const uni: typeof wx\n}\n" : "export {}\n"
		},
		{
			path: sharedPath,
			content: toJson(createSharedTsconfig(ctx, legacyConfig))
		},
		{
			path: appPath,
			content: toJson(createAppTsconfig(ctx, legacyConfig))
		},
		{
			path: nodePath,
			content: toJson(createNodeTsconfig(ctx, legacyConfig))
		},
		{
			path: serverPath,
			content: toJson(createServerTsconfig(ctx, legacyConfig))
		}
	];
}
function createManagedRootTsconfig() {
	return toJson({
		references: [
			{ path: "./.weapp-vite/tsconfig.app.json" },
			{ path: "./.weapp-vite/tsconfig.server.json" },
			{ path: "./.weapp-vite/tsconfig.node.json" },
			{ path: "./.weapp-vite/tsconfig.shared.json" }
		],
		files: []
	});
}
async function outputFileIfChanged(file, existingContents) {
	if ((existingContents?.has(file.path) ? existingContents.get(file.path) : await fs$1.readFile(file.path, "utf8").catch(() => void 0)) === file.content) return false;
	await fs$1.outputFile(file.path, file.content, "utf8");
	return true;
}
async function syncManagedTsconfigFiles(ctx, files, existingContents) {
	const targetFiles = files ?? await createManagedTsconfigFiles(ctx);
	return (await Promise.all(targetFiles.map((file) => outputFileIfChanged(file, existingContents)))).some(Boolean);
}
const MANAGED_TSCONFIG_MARKERS = [".weapp-vite/tsconfig.app.json", ".weapp-vite/tsconfig.shared.json"];
const bootstrappedManagedTsconfigRoots = /* @__PURE__ */ new Set();
function markManagedTsconfigBootstrapComplete(cwd) {
	bootstrappedManagedTsconfigRoots.add(path.resolve(cwd));
}
function hasManagedTsconfigBootstrapCompleted(cwd) {
	return Boolean(cwd && bootstrappedManagedTsconfigRoots.has(path.resolve(cwd)));
}
async function readTsconfigData(filePath) {
	const content = await fs$1.readFile(filePath, "utf8").catch(() => void 0);
	if (!content) return;
	try {
		const parsed = parse(content, void 0, true);
		return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
	} catch {
		return;
	}
}
function normalizeReferencePath(value) {
	return value.replace(/\\/g, "/").replace(/^\.\//, "");
}
function getTsconfigReferences(data) {
	return (Array.isArray(data?.references) ? data.references : []).filter((reference) => {
		return Boolean(reference && typeof reference === "object" && typeof reference.path === "string");
	});
}
function resolveReferenceProjectRoot(baseDir, value) {
	const resolved = path.resolve(baseDir, value);
	return path.basename(resolved).endsWith(".json") ? path.dirname(resolved) : resolved;
}
async function isManagedTsconfigProject(projectRoot) {
	const data = await readTsconfigData(path.resolve(projectRoot, "tsconfig.json"));
	if (!data) return false;
	if (typeof data.extends === "string") {
		const normalizedExtends = normalizeReferencePath(data.extends);
		if (MANAGED_TSCONFIG_MARKERS.some((marker) => normalizedExtends.includes(marker))) return true;
	}
	return getTsconfigReferences(data).some((reference) => {
		const normalizedPath = normalizeReferencePath(reference.path);
		return MANAGED_TSCONFIG_MARKERS.some((marker) => normalizedPath.includes(marker));
	});
}
async function findReferencingWorkspaceTsconfig(cwd) {
	const targetRoot = path.resolve(cwd);
	let current = path.dirname(targetRoot);
	while (current && current !== path.dirname(current)) {
		const references = getTsconfigReferences(await readTsconfigData(path.join(current, "tsconfig.json")));
		if (references.some((reference) => resolveReferenceProjectRoot(current, reference.path) === targetRoot)) return {
			root: current,
			references
		};
		current = path.dirname(current);
	}
}
async function syncSingleProjectManagedTsconfigBootstrapFiles(cwd) {
	const packageJsonPath = path.resolve(cwd, "package.json");
	const bootstrapCtx = { configService: {
		cwd,
		configFilePath: void 0,
		packageJson: await fs$1.readJson(packageJsonPath, { throws: false }).catch(() => void 0) ?? {},
		weappViteConfig: {}
	} };
	let changed = false;
	const rootTsconfigPath = path.resolve(cwd, "tsconfig.json");
	const rootJsconfigPath = path.resolve(cwd, "jsconfig.json");
	const [hasRootTsconfig, hasRootJsconfig] = await Promise.all([fs$1.pathExists(rootTsconfigPath), fs$1.pathExists(rootJsconfigPath)]);
	if (!(hasRootTsconfig || hasRootJsconfig)) {
		await fs$1.outputFile(rootTsconfigPath, createManagedRootTsconfig(), "utf8");
		changed = true;
	}
	changed = (await Promise.all((await createManagedTsconfigFiles(bootstrapCtx)).map(async (file) => {
		if (await fs$1.readFile(file.path, "utf8").catch(() => void 0) != null) return false;
		await fs$1.outputFile(file.path, file.content, "utf8");
		return true;
	}))).some(Boolean) || changed;
	return changed;
}
async function syncManagedTsconfigBootstrapFiles(cwd) {
	let changed = await syncSingleProjectManagedTsconfigBootstrapFiles(cwd);
	const workspace = await findReferencingWorkspaceTsconfig(cwd);
	if (!workspace) {
		markManagedTsconfigBootstrapComplete(cwd);
		return changed;
	}
	for (const reference of workspace.references) {
		const projectRoot = resolveReferenceProjectRoot(workspace.root, reference.path);
		if (projectRoot === path.resolve(cwd) || !await isManagedTsconfigProject(projectRoot)) continue;
		changed = await syncSingleProjectManagedTsconfigBootstrapFiles(projectRoot) || changed;
	}
	markManagedTsconfigBootstrapComplete(cwd);
	return changed;
}
//#endregion
//#region src/runtime/supportFiles.ts
function parseJsonObject(content) {
	if (!content) return;
	try {
		const parsed = parse(content, void 0, true);
		return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
	} catch {
		return;
	}
}
function readStringArray(value) {
	return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function shouldCollectAutoImportTemplateTags(autoImportConfig) {
	const resolvers = autoImportConfig.resolvers;
	if (!Array.isArray(resolvers) || resolvers.length === 0) return false;
	return resolvers.some((resolver) => {
		return resolver?.supportFilesStrategy !== "full" || !resolver?.components || typeof resolver.components !== "object" || Array.isArray(resolver.components);
	});
}
function getExpectedAppSrcInclude(expectedAppTsconfig) {
	return readStringArray(expectedAppTsconfig?.include)[0];
}
function createManagedTsconfigWarnings(ctx, expectedAppContent, existingAppContent) {
	const expectedAppTsconfig = parseJsonObject(expectedAppContent);
	const existingAppTsconfig = parseJsonObject(existingAppContent);
	const expectedSrcInclude = getExpectedAppSrcInclude(expectedAppTsconfig);
	const existingIncludes = readStringArray(existingAppTsconfig?.include);
	if (!existingAppContent || !expectedSrcInclude || existingIncludes.includes(expectedSrcInclude)) return [];
	const srcRoot = ctx.configService?.srcRoot ?? "src";
	const existingSrcIncludes = existingIncludes.filter((include) => include.endsWith("/**/*"));
	return [`[prepare] 检测到 .weapp-vite/tsconfig.app.json include 与 weapp.srcRoot 不匹配:srcRoot 为 \`${srcRoot}\`,期望包含 \`${expectedSrcInclude}\`,${existingSrcIncludes.length > 0 ? `当前为 ${existingSrcIncludes.map((include) => `\`${include}\``).join("、")}` : "当前未包含源码目录"}。已自动重新生成支持文件并使用最新配置继续运行。`];
}
async function inspectManagedTsconfigFiles(ctx) {
	const files = await createManagedTsconfigFiles(ctx);
	let expectedAppContent;
	let existingAppContent;
	const inspections = await Promise.all(files.map(async (file) => {
		return {
			existing: await readFile(file.path, "utf8").catch(() => void 0),
			file
		};
	}));
	const managedTsconfigChanged = inspections.some(({ existing, file }) => existing !== file.content);
	const existingContents = /* @__PURE__ */ new Map();
	for (const { existing, file } of inspections) {
		existingContents.set(file.path, existing);
		if (file.path.endsWith("tsconfig.app.json")) {
			expectedAppContent = file.content;
			existingAppContent = existing;
		}
	}
	return {
		existingContents,
		files,
		managedTsconfigChanged,
		managedTsconfigWarnings: createManagedTsconfigWarnings(ctx, expectedAppContent, existingAppContent)
	};
}
async function collectAutoImportTemplateTags(ctx) {
	const srcRoot = ctx.configService?.absoluteSrcRoot;
	if (!srcRoot) return [];
	const files = await new fdir({
		includeDirs: false,
		pathSeparator: "/"
	}).withFullPaths().filter((filePath) => filePath.endsWith(".vue") || filePath.endsWith(".wxml") || filePath.endsWith(".axml")).crawl(srcRoot).withPromise();
	const tags = /* @__PURE__ */ new Map();
	const platform = resolveMiniPlatformWithDefault(ctx.configService?.platform);
	await Promise.all(files.map(async (filePath) => {
		const source = await readFile(filePath, "utf8").catch(() => void 0);
		if (!source) return;
		if (filePath.endsWith(".vue")) {
			const { descriptor, errors } = parse$1(source, { filename: filePath });
			if (errors.length > 0 || !descriptor.template?.content) return;
			for (const tag of collectVueTemplateAutoImportTags(descriptor.template.content, filePath)) tags.set(tag, removeExtensionDeep(filePath));
			return;
		}
		for (const tag of Object.keys(scanWxml(source, { platform }).components)) tags.set(tag, removeExtensionDeep(filePath));
	}));
	return Array.from(tags.entries(), ([tag, importerBaseName]) => ({
		tag,
		importerBaseName
	}));
}
async function syncManagedTsconfigSupportFiles(ctx) {
	const managedTsconfigInspection = await inspectManagedTsconfigFiles(ctx);
	await syncManagedTsconfigFiles(ctx, managedTsconfigInspection.files, managedTsconfigInspection.existingContents);
	return {
		managedTsconfigChanged: managedTsconfigInspection.managedTsconfigChanged,
		managedTsconfigWarnings: managedTsconfigInspection.managedTsconfigWarnings
	};
}
async function syncAutoRoutesSupportFiles(ctx) {
	if (ctx.autoRoutesService?.isEnabled()) await ctx.autoRoutesService.ensureFresh();
}
async function syncAutoImportSupportFiles(ctx, syncAutoImport, configService) {
	const autoImportConfig = syncAutoImport ? getAutoImportConfig(configService) : void 0;
	if (autoImportConfig && ctx.autoImportService && ctx.configService) {
		await ctx.autoImportService.runInBatch(async () => {
			ctx.autoImportService.reset();
			const globs = autoImportConfig.globs;
			if (Array.isArray(globs) && globs.length > 0) {
				const files = await findAutoImportCandidates({
					ctx: {
						...ctx,
						configService
					},
					resolvedConfig: { build: { outDir: configService.outDir } }
				}, globs);
				await Promise.all(files.map((file) => ctx.autoImportService.registerPotentialComponent(file)));
			} else if (!shouldBootstrapAutoImportWithoutGlobs(autoImportConfig)) {}
			if (shouldCollectAutoImportTemplateTags(autoImportConfig)) {
				const templateTags = await collectAutoImportTemplateTags(ctx);
				for (const { tag, importerBaseName } of templateTags) ctx.autoImportService.resolve(tag, importerBaseName);
			}
			ctx.autoImportService.setSupportFileResolverComponents(ctx.autoImportService.collectStaticResolverComponentsForSupportFiles());
			ctx.runtimeState.autoImport.preparedGlobsKey = createAutoImportGlobsKey(globs);
		});
		try {
			await ctx.autoImportService.awaitManifestWrites();
		} finally {
			ctx.autoImportService.clearSupportFileResolverComponents();
		}
	} else if (ctx.runtimeState?.autoImport) ctx.runtimeState.autoImport.preparedGlobsKey = void 0;
}
async function syncProjectSupportFiles(ctx, options = {}) {
	const configService = requireConfigService(ctx, "同步 support files 前必须初始化 configService。");
	const syncAutoImport = options.syncAutoImport ?? true;
	const [managedTsconfigResult] = await Promise.all([
		syncManagedTsconfigSupportFiles(ctx),
		syncAutoRoutesSupportFiles(ctx),
		syncAutoImportSupportFiles(ctx, syncAutoImport, configService)
	]);
	return {
		managedTsconfigChanged: managedTsconfigResult.managedTsconfigChanged,
		managedTsconfigWarnings: managedTsconfigResult.managedTsconfigWarnings
	};
}
//#endregion
//#region src/runtime/buildPlugin/devBuildWatcher.ts
/**
* 为 provider 驱动的一次性构建提供 Rolldown watcher 兼容事件接口。
*/
function createDevBuildWatcher() {
	const listeners = /* @__PURE__ */ new Map();
	const pendingEvents = [];
	let closed = false;
	const watcher = {
		on(event, listener) {
			let eventListeners = listeners.get(event);
			if (!eventListeners) {
				eventListeners = /* @__PURE__ */ new Set();
				listeners.set(event, eventListeners);
			}
			eventListeners.add(listener);
			if (event === "event" && pendingEvents.length) {
				const queuedEvents = pendingEvents.splice(0);
				for (const queuedEvent of queuedEvents) Promise.resolve(listener(queuedEvent)).catch(() => {});
			}
			return watcher;
		},
		off(event, listener) {
			listeners.get(event)?.delete(listener);
			return watcher;
		},
		clear(event) {
			listeners.delete(event);
		},
		async close() {
			if (closed) return;
			closed = true;
			const closeListeners = Array.from(listeners.get("close") ?? []);
			listeners.clear();
			await Promise.all(closeListeners.map((listener) => listener()));
		}
	};
	function emit(event, ...args) {
		if (closed) return;
		for (const listener of listeners.get(event) ?? []) Promise.resolve(listener(...args)).catch(() => {});
	}
	return {
		watcher,
		emitEvent(event) {
			if (!listeners.get("event")?.size) {
				pendingEvents.push(event);
				return;
			}
			emit("event", event);
		}
	};
}
//#endregion
//#region src/runtime/buildPlugin/hmrProfileMetricsPlugin.ts
/**
* @description 在 generateBundle 与 writeBundle 之间测量开发态写盘尾段。
*/
function createHmrProfileMetricsPlugin(ctx) {
	let writeStartAt;
	return {
		name: "weapp-vite:hmr-profile-metrics",
		enforce: "post",
		generateBundle(_options, _bundle, isWrite) {
			if (!ctx.configService?.isDev || !isWrite) return;
			writeStartAt = performance.now();
		},
		writeBundle() {
			if (!ctx.configService?.isDev || writeStartAt === void 0) return;
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "writeMs", performance.now() - writeStartAt);
			writeStartAt = void 0;
		},
		buildEnd() {
			writeStartAt = void 0;
		},
		closeBundle() {
			writeStartAt = void 0;
		}
	};
}
//#endregion
//#region src/runtime/independentError.ts
const ANSI_ESCAPE_PATTERN = /\u001B\[[0-9;]*m/g;
function stripAnsi(value) {
	return value.replace(ANSI_ESCAPE_PATTERN, "");
}
function isErrorInstance(value) {
	return value instanceof Error;
}
function formatSummary(payload) {
	const parts = [];
	const code = payload.code;
	if (typeof code === "string" && code.trim()) parts.push(`code: ${code.trim()}`);
	const plugin = payload.plugin;
	if (typeof plugin === "string" && plugin.trim()) parts.push(`plugin: ${plugin.trim()}`);
	const id = payload.id;
	if (typeof id === "string" && id.trim()) parts.push(`id: ${id.trim()}`);
	if (!parts.length) return "";
	return ` (${parts.join(", ")})`;
}
function collectDetails(payload) {
	const details = [];
	const frame = payload.frame;
	if (typeof frame === "string" && frame.trim()) details.push(frame.trim());
	const stack = payload.stack;
	if (typeof stack === "string" && stack.trim()) details.push(stack.trim());
	return details;
}
function extractMessage(value, seen) {
	if (!value || seen.has(value)) return;
	if (typeof value === "string") return stripAnsi(value).trim() || void 0;
	if (isErrorInstance(value)) {
		const trimmed = stripAnsi(value.message ?? "").trim();
		if (trimmed) return trimmed;
		if (value.cause) return extractMessage(value.cause, seen);
		return;
	}
	if (typeof value === "object") {
		const record = value;
		seen.add(record);
		const directMessage = extractMessage(record.message, seen);
		if (directMessage) return directMessage;
		for (const key of [
			"reason",
			"detail",
			"details",
			"error",
			"field0",
			"field1",
			"cause"
		]) if (key in record) {
			const nestedMessage = extractMessage(record[key], seen);
			if (nestedMessage) return nestedMessage;
		}
	}
}
function createIndependentBuildError(root, cause) {
	const fallback = `Independent bundle for ${root} failed`;
	if (isErrorInstance(cause)) {
		if (!cause.message || cause.message.trim() === "") return new Error(fallback, { cause });
		return cause;
	}
	if (!cause) return new Error(fallback);
	if (typeof cause === "string") {
		const trimmed = stripAnsi(cause).trim();
		if (!trimmed) return new Error(fallback, { cause });
		return new Error(trimmed, { cause });
	}
	if (typeof cause === "object") {
		const payload = cause;
		const extracted = extractMessage(payload, /* @__PURE__ */ new Set());
		const summary = formatSummary(payload);
		const detailLines = collectDetails(payload);
		if (extracted) {
			let composedMessage = extracted;
			if (summary) composedMessage += summary;
			if (detailLines.length) composedMessage += `\n${detailLines.join("\n")}`;
			return new Error(composedMessage, { cause });
		}
		if (summary || detailLines.length) {
			const composed = detailLines.length ? `${fallback}${summary}\n${detailLines.join("\n")}` : `${fallback}${summary}`;
			if (composed.trim()) return new Error(composed, { cause });
		}
	}
	try {
		const serialized = JSON.stringify(cause);
		if (serialized && serialized !== "{}") return new Error(`${fallback}: ${serialized}`, { cause });
	} catch {}
	return new Error(fallback, { cause });
}
//#endregion
//#region src/runtime/buildPlugin/independent.ts
function syncImportMetaEnvDefineOverride(configService, define) {
	const previous = configService.importMetaEnvDefineOverride;
	const next = pickImportMetaEnvDefineEntries(define);
	configService.setImportMetaEnvDefineOverride(next);
	return () => {
		configService.setImportMetaEnvDefineOverride(previous);
	};
}
function createIndependentBuilder(configService, buildState) {
	const independentState = buildState.independent;
	const independentBuildTasks = /* @__PURE__ */ new Map();
	function storeIndependentOutput(root, output) {
		independentState.outputs.set(root, output);
	}
	function invalidateIndependentOutput(root) {
		independentState.outputs.delete(root);
	}
	function getIndependentOutput(root) {
		return independentState.outputs.get(root);
	}
	async function buildIndependentBundle(root, meta) {
		const existingTask = independentBuildTasks.get(root);
		if (existingTask) return existingTask;
		const task = (async () => {
			try {
				const chunkRoot = meta.subPackage.root ?? root;
				const isolatedCtx = createCompilerContextInstance();
				await isolatedCtx.configService.load({
					cwd: configService.cwd,
					isDev: configService.isDev,
					mode: configService.mode,
					configFile: configService.configFilePath,
					cliPlatform: configService.platform,
					inlineConfig: { weapp: { platform: configService.platform } },
					projectConfigPath: configService.projectConfigPath
				});
				const isolatedConfigService = isolatedCtx.configService;
				isolatedConfigService.options = {
					...isolatedConfigService.options,
					currentSubPackageRoot: chunkRoot
				};
				const inlineConfig = isolatedConfigService.merge(meta, meta.subPackage.inlineConfig, { build: {
					write: false,
					watch: null,
					rolldownOptions: { output: { chunkFileNames() {
						return `${chunkRoot}/[name].js`;
					} } }
				} });
				const autoImportGlobs = getAutoImportConfig(isolatedConfigService)?.globs;
				if (autoImportGlobs?.length) {
					const candidates = await findAutoImportCandidates({
						ctx: isolatedCtx,
						resolvedConfig: { build: { outDir: isolatedConfigService.outDir } }
					}, autoImportGlobs);
					await isolatedCtx.autoImportService.runWithoutOutputWrites(async () => {
						await Promise.all(candidates.map((candidate) => isolatedCtx.autoImportService.registerPotentialComponent(candidate)));
					});
				}
				const restoreDefineEnv = syncImportMetaEnvDefineOverride(isolatedConfigService, inlineConfig.define);
				let result;
				try {
					result = await build(inlineConfig);
				} finally {
					restoreDefineEnv();
				}
				const output = Array.isArray(result) ? result[0] : result;
				if (!output) throw new Error(`独立分包 ${root} 未产生输出`);
				storeIndependentOutput(root, output);
				return output;
			} catch (error) {
				const normalized = createIndependentBuildError(root, error);
				invalidateIndependentOutput(root);
				logger_default.error(`[独立分包] ${root} 构建失败:${normalized.message}`);
				throw normalized;
			} finally {
				independentBuildTasks.delete(root);
			}
		})();
		independentBuildTasks.set(root, task);
		return task;
	}
	return {
		buildIndependentBundle,
		getIndependentOutput,
		invalidateIndependentOutput
	};
}
//#endregion
//#region src/runtime/buildPlugin/outputs.ts
function resolvePreservedNpmDirNames(configService) {
	return new Set(getPreservedNpmDirNames(configService.platform, { alipayNpmMode: configService.weappViteConfig?.npm?.alipayNpmMode }));
}
function isOutputRootInsideOutDir(outDir, pluginOutputRoot) {
	const relativeToOutDir = path.relative(outDir, pluginOutputRoot);
	return relativeToOutDir === "" || !relativeToOutDir.startsWith("..") && !path.isAbsolute(relativeToOutDir);
}
async function removeDirectoryEntries(root, options = {}) {
	const entries = await readdir(root, { withFileTypes: true }).catch((error) => {
		if (error?.code === "ENOENT") return [];
		throw error;
	});
	const deletedPaths = [];
	await Promise.all(entries.map(async (entry) => {
		if (options.preserveDirNames?.has(entry.name)) return;
		const absolutePath = path.resolve(root, entry.name);
		await rm(absolutePath, {
			recursive: true,
			force: true
		});
		deletedPaths.push(absolutePath);
	}));
	return deletedPaths.sort();
}
function resetEmittedOutputCaches(runtimeState) {
	runtimeState.json.emittedSource.clear();
	runtimeState.asset.emittedBuffer.clear();
	runtimeState.asset.scopedSlotGenerics.clear();
	runtimeState.build?.output?.emittedSource.clear();
	runtimeState.css.emittedSource.clear();
	runtimeState.css.transformedSidecarSource.clear();
	runtimeState.wxml.emittedCode.clear();
}
async function cleanOutputs(configService) {
	if (configService.mpDistRoot) {
		const preservedNpmDirNames = resolvePreservedNpmDirNames(configService);
		const deletedFilePaths = await removeDirectoryEntries(configService.outDir, { preserveDirNames: preservedNpmDirNames });
		debug$2?.("deletedFilePaths", deletedFilePaths);
		logger_default.success(`已清空 ${configService.mpDistRoot} 目录`);
	}
	const pluginOutputRoot = configService.absolutePluginOutputRoot;
	if (pluginOutputRoot) {
		if (!isOutputRootInsideOutDir(configService.outDir, pluginOutputRoot)) {
			const deletedPluginFiles = await removeDirectoryEntries(pluginOutputRoot);
			debug$2?.("deletedPluginOutput", deletedPluginFiles);
			logger_default.success(`已清空 ${configService.relativeCwd(pluginOutputRoot)} 目录`);
		}
	}
}
//#endregion
//#region src/runtime/buildPlugin/touchAppWxss.ts
const tailwindPackageName = "weapp-tailwindcss";
function hasTailwindcssDependency(packageJson) {
	return Boolean(packageJson.dependencies?.[tailwindPackageName] || packageJson.devDependencies?.[tailwindPackageName]);
}
function shouldAutoTouchAppWxssForPlatform(platform) {
	return supportsMiniProgramAutoTouchAppStyle(platform);
}
function resolveTouchAppWxssEnabled(options) {
	const resolvedOption = options.option ?? "auto";
	if (resolvedOption === true) return true;
	if (resolvedOption === false) return false;
	if (!shouldAutoTouchAppWxssForPlatform(options.platform)) return false;
	if (hasTailwindcssDependency(options.packageJson)) return true;
	const resolve = options.resolve ?? createRequire(path.resolve(options.cwd, "package.json")).resolve;
	try {
		resolve(tailwindPackageName);
		return true;
	} catch {
		return false;
	}
}
//#endregion
//#region src/runtime/buildPlugin/workers.ts
function resolveWorkerRenamePath(rawPath, options) {
	const candidate = typeof rawPath === "string" ? rawPath : rawPath && typeof rawPath.toString === "function" ? rawPath.toString() : "";
	if (!candidate) return "";
	const baseDir = options.watchedPath ?? options.fallbackRoot;
	return path.isAbsolute(candidate) ? candidate : path.resolve(baseDir, candidate);
}
function checkWorkersOptions(target, configService, scanService) {
	if (target === "plugin") return {
		hasWorkersDir: false,
		workersDir: void 0
	};
	const workersDir = scanService.workersDir;
	const hasWorkersDir = Boolean(workersDir);
	if (hasWorkersDir && configService.weappViteConfig?.worker?.entry === void 0) {
		logger_default.error("检测到已经开启了 `worker`,请在 `vite.config.ts` / `weapp-vite.config.ts` 中设置 `weapp.worker.entry` 路径");
		logger_default.error("比如引入的 `worker` 路径为 `workers/index`, 此时 `weapp.worker.entry` 设置为 `[index]` ");
		throw new Error("请在 `vite.config.ts` / `weapp-vite.config.ts` 中设置 `weapp.worker.entry` 路径");
	}
	return {
		hasWorkersDir,
		workersDir
	};
}
async function devWorkers(configService, watcherService, workersRoot) {
	const workersWatcher = await build(configService.mergeWorkers());
	watcherService.setRollupWatcher(workersWatcher, workersRoot);
}
async function buildWorkers(configService) {
	await build(configService.mergeWorkers());
}
function watchWorkers(configService, watcherService, workersDir) {
	const absWorkerRoot = path.resolve(configService.absoluteSrcRoot, workersDir);
	const workerWatcher = chokidar.watch(absWorkerRoot, createSidecarWatchOptions(configService, {
		persistent: true,
		ignoreInitial: true
	}));
	const logWorkerEvent = (type, targetPath, level = "info") => {
		if (!targetPath) return;
		const message = `[workers:${type}] ${configService.relativeCwd(targetPath)}`;
		if (level === "success") logger_default.success(message);
		else logger_default.info(message);
	};
	workerWatcher.on("all", (event, id) => {
		if (!id) return;
		if (event === "add") {
			logWorkerEvent(event, id, "success");
			devWorkers(configService, watcherService, workersDir);
			return;
		}
		logWorkerEvent(event, id);
	});
	workerWatcher.on("raw", (eventName, rawPath, details) => {
		if (eventName !== "rename") return;
		const resolved = resolveWorkerRenamePath(rawPath, {
			watchedPath: typeof details === "object" && details && "watchedPath" in details ? details.watchedPath : void 0,
			fallbackRoot: absWorkerRoot
		});
		if (!resolved) return;
		const exists = fs.existsSync(resolved);
		logWorkerEvent(exists ? "rename->add" : "rename->unlink", resolved, exists ? "success" : "info");
	});
	watcherService.sidecarWatcherMap.set(absWorkerRoot, { close: () => workerWatcher.close() });
}
//#endregion
//#region src/runtime/buildPlugin/service.ts
function toStatefulHmrOutput(output) {
	if (!Array.isArray(output) && !("output" in output)) throw new TypeError("stateful HMR snapshot build unexpectedly returned a watcher");
	return (Array.isArray(output) ? output : [output]).flatMap((result) => result.output);
}
function collectStatefulHmrEntryIds(initialEntryIds, snapshot, cwd, srcRoot) {
	const entryIds = new Set(Array.from(initialEntryIds, (id) => normalizeFsResolvedId(id)));
	const normalizedSrcRoot = normalizeFsResolvedId(srcRoot).replace(/\/$/, "");
	for (const item of snapshot) {
		if (item.type !== "chunk") continue;
		for (const moduleId of Object.keys(item.modules ?? {})) {
			const sourceId = moduleId.split("?")[0];
			const normalizedId = normalizeFsResolvedId(path.isAbsolute(sourceId) ? sourceId : path.resolve(cwd, sourceId));
			if (normalizedId.startsWith(`${normalizedSrcRoot}/`) && /\.(?:[cm]?[jt]sx?|vue)$/.test(normalizedId)) entryIds.add(normalizedId);
		}
	}
	return entryIds;
}
function resolveSnapshotSidecarDirtySummary(filePath, affectedEntries) {
	const normalizedFile = normalizeFsResolvedId(filePath);
	if (configSuffixes.find((suffix) => normalizedFile.endsWith(suffix))) return "json-sidecar:1";
	const ext = path.extname(normalizedFile);
	if (ext && watchedCssExts.has(ext)) {
		const styleBase = removeExtensionDeep(normalizedFile);
		return (affectedEntries ? Array.from(affectedEntries).some((entryId) => {
			return removeExtensionDeep(normalizeFsResolvedId(entryId)) === styleBase;
		}) : true) ? "style-sidecar:1" : "css-importer:1";
	}
	if (ext && watchedTemplateExts.has(ext)) return "sidecar-direct:1";
	return "importer-graph:1";
}
const watchedSnapshotScriptExts = /* @__PURE__ */ new Set([
	".ts",
	".tsx",
	".js",
	".jsx",
	".mts",
	".cts",
	".mjs",
	".cjs"
]);
const SNAPSHOT_BUILD_BATCH_DELAY_MS = 8;
const SIDECAR_WATCHER_READY_TIMEOUT_MS = 3e4;
function waitForSidecarWatcherReady(watcher) {
	const candidate = watcher;
	if (typeof candidate.once !== "function" || typeof candidate.off !== "function") return Promise.resolve();
	return new Promise((resolve, reject) => {
		let settled = false;
		let timer;
		let cleanup = () => {};
		const finish = (error) => {
			if (settled) return;
			settled = true;
			cleanup();
			if (error) reject(error);
			else resolve();
		};
		const onReady = () => finish();
		const onError = (error) => finish(error);
		cleanup = () => {
			clearTimeout(timer);
			watcher.off("ready", onReady);
			watcher.off("error", onError);
		};
		timer = setTimeout(() => {
			finish(/* @__PURE__ */ new Error("Sidecar watcher ready timed out"));
		}, SIDECAR_WATCHER_READY_TIMEOUT_MS);
		watcher.once("ready", onReady);
		watcher.once("error", onError);
	});
}
function shouldHandleSnapshotSidecarFile(filePath, ctx) {
	const configService = ctx.configService;
	if (isSidecarFile(filePath)) return true;
	const normalizedFile = normalizeFsResolvedId(filePath);
	const normalizedSrcRoot = normalizeFsResolvedId(configService.absoluteSrcRoot);
	if (normalizedFile === normalizedSrcRoot || normalizedFile.startsWith(`${normalizedSrcRoot}/`)) return ctx.runtimeState.build.hmr.sharedChunkSourceModuleIds.has(normalizedFile);
	return path.extname(filePath) !== "";
}
function isGeneratedMiniprogramWatchInclude(pattern, configService) {
	if (pattern === "**") return true;
	const normalizedPattern = normalizeFsResolvedId(path.isAbsolute(pattern) ? pattern : path.resolve(configService.cwd, pattern));
	const normalizedSrcRoot = normalizeFsResolvedId(configService.absoluteSrcRoot);
	if (normalizedPattern === normalizedSrcRoot || normalizedPattern.startsWith(`${normalizedSrcRoot}/`)) return true;
	if (configService.absolutePluginRoot) {
		const normalizedPluginRoot = normalizeFsResolvedId(configService.absolutePluginRoot);
		if (normalizedPattern === normalizedPluginRoot || normalizedPattern.startsWith(`${normalizedPluginRoot}/`)) return true;
	}
	return (configService.configFileDependencies ?? []).some((dependency) => {
		const normalizedDependency = normalizeFsResolvedId(dependency);
		return normalizedPattern === normalizedDependency;
	});
}
function resolveUserBuildWatchInclude(configService, inlineConfig) {
	const buildWatch = inlineConfig?.build?.watch ?? configService?.inlineConfig?.build?.watch;
	if (!buildWatch || typeof buildWatch !== "object") return [];
	const include = buildWatch.include;
	return (Array.isArray(include) ? include : include ? [include] : []).filter((pattern) => typeof pattern === "string").filter((pattern) => !isGeneratedMiniprogramWatchInclude(pattern, configService)).map((pattern) => path.normalize(path.isAbsolute(pattern) ? pattern : path.resolve(configService.cwd, pattern)));
}
function createSnapshotSidecarWatchPatterns(configService, inlineConfig) {
	const root = configService.absoluteSrcRoot;
	const patterns = [
		...configSuffixes.map((suffix) => path.join(root, `**/*${suffix}`)),
		...watchedCssSuffixes.map((ext) => path.join(root, `**/*${ext}`)),
		...watchedTemplateSuffixes.map((ext) => path.join(root, `**/*${ext}`)),
		...watchedScriptModuleSuffixes.map((ext) => path.join(root, `**/*${ext}`)),
		...Array.from(watchedSnapshotScriptExts).map((ext) => path.join(root, `**/*${ext}`)),
		...(configService.configFileDependencies ?? []).map((dependency) => path.normalize(dependency))
	];
	for (const include of resolveUserBuildWatchInclude(configService, inlineConfig)) patterns.push(include);
	return patterns;
}
function createSnapshotSidecarIgnoredMatcher(ctx) {
	const configService = ctx.configService;
	if (!configService) return;
	const ignoredRoots = /* @__PURE__ */ new Set();
	const watchRoot = normalizeFsResolvedId(configService.absoluteSrcRoot);
	for (const dirName of defaultIgnoredDirNames) ignoredRoots.add(normalizeFsResolvedId(path.join(configService.absoluteSrcRoot, dirName)));
	ignoredRoots.add(normalizeFsResolvedId(configService.outDir));
	if (configService.mpDistRoot) ignoredRoots.add(normalizeFsResolvedId(path.resolve(configService.cwd, configService.mpDistRoot)));
	return (candidate) => {
		const normalized = normalizeFsResolvedId(candidate);
		if (normalized === watchRoot) return false;
		for (const ignored of ignoredRoots) if (normalized === ignored || normalized.startsWith(`${ignored}/`)) return true;
		return false;
	};
}
function createBuildService(ctx) {
	let lastHmrSlowTipProfileCount = 0;
	let devHmrDecision;
	let devHmrRuntimeNoticeLogged = false;
	let skylineHmrFallbackApplied = false;
	const SKYLINE_HMR_COMPATIBILITY_URL = "https://developers.weixin.qq.com/miniprogram/dev/framework/runtime/skyline/migration/compatibility.html#%E5%B8%B8%E8%A7%81%E7%9A%84%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98";
	function logHmrRuntimeDecision(decision) {
		if (devHmrRuntimeNoticeLogged) return;
		devHmrRuntimeNoticeLogged = true;
		for (const message of formatHmrRuntimeStartupMessages(decision)) logger_default.info(message);
	}
	async function applySkylineHmrFallback(options) {
		const configService = ctx.configService;
		if (!configService) return false;
		const currentDecision = devHmrDecision ?? resolveHmrRuntimeDecision({
			platform: configService.platform,
			configured: options.configured,
			compileHotReLoad: options.compileHotReLoad
		});
		if (skylineHmrFallbackApplied || currentDecision.runtime === "classic" && options.compileHotReLoad !== true) return false;
		skylineHmrFallbackApplied = true;
		devHmrDecision = resolveHmrRuntimeDecision({
			platform: configService.platform,
			configured: currentDecision.configured,
			compileHotReLoad: options.compileHotReLoad,
			skyline: true
		});
		const detectedFiles = options.files.slice(0, 3).join("、");
		const detectedSuffix = detectedFiles ? `(${detectedFiles})` : "";
		const privateConfigPath = configService.projectPrivateConfigPath;
		const privateConfigDisplay = privateConfigPath ? configService.relativeCwd(privateConfigPath) : "project.private.config.json";
		if (options.compileHotReLoad === true) try {
			if (!privateConfigPath) throw new Error("无法解析项目私有配置路径");
			await disableProjectPrivateConfigHotReload(privateConfigPath);
			const privateConfig = configService.projectPrivateConfig;
			privateConfig.setting = {
				...privateConfig.setting && typeof privateConfig.setting === "object" && !Array.isArray(privateConfig.setting) ? privateConfig.setting : {},
				compileHotReLoad: false
			};
			logger_default.warn(`检测到 Skyline 渲染配置${detectedSuffix}。微信开发者工具暂不支持 Skyline 热重载,已将 ${privateConfigDisplay} 中的 setting.compileHotReLoad 设为 false,并降级为 classic。详情:${SKYLINE_HMR_COMPATIBILITY_URL}`);
		} catch (error) {
			logger_default.warn(`检测到 Skyline 渲染配置${detectedSuffix}。已降级为 classic,但无法自动关闭 ${privateConfigDisplay} 中的 setting.compileHotReLoad:${error instanceof Error ? error.message : String(error)}。请手动关闭微信开发者工具“热重载”。详情:${SKYLINE_HMR_COMPATIBILITY_URL}`);
		}
		else logger_default.warn(`检测到 Skyline 渲染配置${detectedSuffix}。微信开发者工具暂不支持 Skyline 热重载,weapp.hmr.runtime="stateful-experimental" 已自动降级为 classic。详情:${SKYLINE_HMR_COMPATIBILITY_URL}`);
		return true;
	}
	function createHmrProfileJsonSample(totalMs) {
		const profile = ctx.runtimeState.build.hmr.profile;
		const relativeFile = profile.file && ctx.configService ? ctx.configService.relativeCwd(profile.file) : void 0;
		const sourceRootFile = profile.file && ctx.configService ? ctx.configService.relativeAbsoluteSrcRoot(profile.file) : void 0;
		return {
			timestamp: (/* @__PURE__ */ new Date()).toISOString(),
			totalMs,
			eventId: profile.eventId,
			event: profile.event,
			file: profile.file,
			relativeFile,
			sourceRootFile,
			buildCoreMs: profile.buildCoreMs,
			buildStartMs: profile.buildStartMs,
			pluginResolveMs: profile.pluginResolveMs,
			transformMs: profile.transformMs,
			coreTransformMs: profile.coreTransformMs,
			wevuTransformMs: profile.wevuTransformMs,
			vueTransformMs: profile.vueTransformMs,
			vueReadSourceMs: profile.vueReadSourceMs,
			vueCompileMs: profile.vueCompileMs,
			vueFinalizeCompiledMs: profile.vueFinalizeCompiledMs,
			vueFinalizeCodeMs: profile.vueFinalizeCodeMs,
			coreLoadMs: profile.coreLoadMs,
			entryLoadMs: profile.entryLoadMs,
			entryCodeReadMs: profile.entryCodeReadMs,
			entrySidecarResolveMs: profile.entrySidecarResolveMs,
			entryJsonReadMs: profile.entryJsonReadMs,
			entryVueConfigMs: profile.entryVueConfigMs,
			entryTemplateScanMs: profile.entryTemplateScanMs,
			entryScriptSetupMs: profile.entryScriptSetupMs,
			entryVueSignatureMs: profile.entryVueSignatureMs,
			entryAutoImportMs: profile.entryAutoImportMs,
			entryPrepareMs: profile.entryPrepareMs,
			entryEmitOutputMs: profile.entryEmitOutputMs,
			entryStyleScanMs: profile.entryStyleScanMs,
			entryStyleReadMs: profile.entryStyleReadMs,
			entryResolveMs: profile.entryResolveMs,
			entryChunkEmitMs: profile.entryChunkEmitMs,
			entryChunkLoadMs: profile.entryChunkLoadMs,
			entryChunkEmitFileMs: profile.entryChunkEmitFileMs,
			entryLayoutMs: profile.entryLayoutMs,
			requestGlobalsMs: profile.requestGlobalsMs,
			weapiResolveMs: profile.weapiResolveMs,
			bundlerMs: profile.bundlerMs,
			renderStartMs: profile.renderStartMs,
			generateBundleMs: profile.generateBundleMs,
			generateSharedMs: profile.generateSharedMs,
			generateRewriteMs: profile.generateRewriteMs,
			generateModuleGraphMs: profile.generateModuleGraphMs,
			snapshotResolveMs: profile.snapshotResolveMs,
			snapshotBuildMs: profile.snapshotBuildMs,
			writeMs: profile.writeMs,
			watchToDirtyMs: profile.watchToDirtyMs,
			emitMs: profile.emitMs,
			sharedChunkResolveMs: profile.sharedChunkResolveMs,
			chunkEmitCount: profile.chunkEmitCount,
			loadCount: profile.loadCount,
			resolveCount: profile.resolveCount,
			skippedLoadedCount: profile.skippedLoadedCount,
			dirtyCount: profile.dirtyCount,
			pendingCount: profile.pendingCount,
			emittedCount: profile.emittedCount,
			dirtyReasonSummary: profile.dirtyReasonSummary,
			pendingReasonSummary: profile.pendingReasonSummary
		};
	}
	function recordHmrProfile(totalMs) {
		const hmrState = ctx.runtimeState.build.hmr;
		hmrState.recentProfiles.push(createHmrProfileJsonSample(totalMs));
		if (hmrState.recentProfiles.length > 5) hmrState.recentProfiles.splice(0, hmrState.recentProfiles.length - 5);
	}
	function resetHmrProfile() {
		ctx.runtimeState.build.hmr.profile = {};
	}
	function resolveHmrProfileJsonPath$1() {
		const envOption = resolveHmrProfileJsonEnvOption();
		return resolveHmrProfileJsonPath({
			cwd: ctx.configService?.cwd ?? process.cwd(),
			option: envOption ?? ctx.configService?.weappViteConfig.hmr?.profileJson
		});
	}
	function finalizeHmrProfile(totalMs) {
		const profile = ctx.runtimeState.build.hmr.profile;
		const measuredMs = [
			profile.transformMs,
			profile.buildStartMs,
			profile.pluginResolveMs,
			profile.coreLoadMs,
			profile.renderStartMs,
			profile.generateBundleMs,
			profile.watchToDirtyMs,
			profile.emitMs,
			profile.writeMs
		].reduce((sum, value) => sum + (typeof value === "number" ? value : 0), 0);
		profile.buildCoreMs = Math.max(0, totalMs - measuredMs);
	}
	function appendHmrMetricsPlugin(config) {
		if (!ctx.configService?.isDev) return config;
		const plugins = config.plugins;
		return {
			...config,
			plugins: [...plugins ? Array.isArray(plugins) ? plugins : [plugins] : [], createHmrProfileMetricsPlugin(ctx)]
		};
	}
	function formatReasonLabel(reason) {
		if (reason.startsWith("entry-direct:")) return "entry";
		if (reason.startsWith("sidecar-direct:")) return "sidecar";
		if (reason.startsWith("importer-graph:")) return "importer";
		if (reason.startsWith("layout-self:")) return "layout-self";
		if (reason.startsWith("layout-dependent:")) return "layout-dependent";
		if (reason.startsWith("layout-propagation:")) return "layout";
		if (reason.startsWith("layout-fallback-full:")) return "layout-full";
		if (reason.startsWith("auto-routes-topology:")) return "routes-topology";
		if (reason.startsWith("shared-chunk(")) {
			const countMatch = reason.match(/\+(\d+):/);
			return countMatch ? `shared+${countMatch[1]}` : "shared";
		}
		return reason;
	}
	function formatReasonSummary(reasons) {
		if (!reasons?.length) return;
		const [first, ...rest] = reasons.map(formatReasonLabel);
		return rest.length ? `${first}+${rest.length}` : first;
	}
	function formatHmrRecentSummary() {
		const recentProfiles = ctx.runtimeState.build.hmr.recentProfiles;
		if (recentProfiles.length < 2) return "";
		const average = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
		const totalValues = recentProfiles.map((item) => item.totalMs);
		return `;${[`近${recentProfiles.length}次 avg ${average(totalValues).toFixed(0)} ms`, `max ${Math.max(...totalValues).toFixed(2)} ms`].join(",")}`;
	}
	function resolveHmrLogLevel() {
		return ctx.configService?.weappViteConfig.hmr?.logLevel ?? "default";
	}
	function formatHmrLogLine(durationMs) {
		const duration = durationMs.toFixed(2);
		const profile = ctx.runtimeState.build.hmr.profile;
		const logLevel = resolveHmrLogLevel();
		if (logLevel === "default") return `小程序已重新构建(${duration} ms)`;
		if (logLevel === "concise") {
			const conciseSegments = [
				typeof profile.buildCoreMs === "number" ? `build-core ${profile.buildCoreMs.toFixed(2)} ms` : void 0,
				typeof profile.buildStartMs === "number" ? `build-start ${profile.buildStartMs.toFixed(2)} ms` : void 0,
				typeof profile.pluginResolveMs === "number" ? `plugin-resolve ${profile.pluginResolveMs.toFixed(2)} ms` : void 0,
				typeof profile.bundlerMs === "number" ? `bundler ${profile.bundlerMs.toFixed(2)} ms` : void 0,
				typeof profile.renderStartMs === "number" ? `render-start ${profile.renderStartMs.toFixed(2)} ms` : void 0,
				typeof profile.generateBundleMs === "number" ? `generate ${profile.generateBundleMs.toFixed(2)} ms` : void 0,
				typeof profile.generateSharedMs === "number" ? `generate-shared ${profile.generateSharedMs.toFixed(2)} ms` : void 0,
				typeof profile.generateRewriteMs === "number" ? `generate-rewrite ${profile.generateRewriteMs.toFixed(2)} ms` : void 0,
				typeof profile.generateModuleGraphMs === "number" ? `module-graph ${profile.generateModuleGraphMs.toFixed(2)} ms` : void 0,
				typeof profile.snapshotResolveMs === "number" ? `snapshot-resolve ${profile.snapshotResolveMs.toFixed(2)} ms` : void 0,
				typeof profile.snapshotBuildMs === "number" ? `snapshot-build ${profile.snapshotBuildMs.toFixed(2)} ms` : void 0,
				typeof profile.coreLoadMs === "number" ? `core-load ${profile.coreLoadMs.toFixed(2)} ms` : void 0,
				typeof profile.entryLoadMs === "number" ? `entry-load ${profile.entryLoadMs.toFixed(2)} ms` : void 0,
				typeof profile.entryEmitOutputMs === "number" ? `entry-emit-output ${profile.entryEmitOutputMs.toFixed(2)} ms` : void 0,
				typeof profile.entryTemplateScanMs === "number" ? `entry-template-scan ${profile.entryTemplateScanMs.toFixed(2)} ms` : void 0,
				typeof profile.entryAutoImportMs === "number" ? `entry-auto-import ${profile.entryAutoImportMs.toFixed(2)} ms` : void 0,
				typeof profile.entryScriptSetupMs === "number" ? `entry-script-setup ${profile.entryScriptSetupMs.toFixed(2)} ms` : void 0,
				typeof profile.entryVueSignatureMs === "number" ? `entry-vue-signature ${profile.entryVueSignatureMs.toFixed(2)} ms` : void 0,
				typeof profile.entrySidecarResolveMs === "number" ? `entry-sidecar-resolve ${profile.entrySidecarResolveMs.toFixed(2)} ms` : void 0,
				typeof profile.entryJsonReadMs === "number" ? `entry-json-read ${profile.entryJsonReadMs.toFixed(2)} ms` : void 0,
				typeof profile.entryVueConfigMs === "number" ? `entry-vue-config ${profile.entryVueConfigMs.toFixed(2)} ms` : void 0,
				typeof profile.entryPrepareMs === "number" ? `entry-prepare ${profile.entryPrepareMs.toFixed(2)} ms` : void 0,
				typeof profile.entryResolveMs === "number" ? `entry-resolve ${profile.entryResolveMs.toFixed(2)} ms` : void 0,
				typeof profile.entryStyleScanMs === "number" ? `entry-style-scan ${profile.entryStyleScanMs.toFixed(2)} ms` : void 0,
				typeof profile.entryStyleReadMs === "number" ? `entry-style-read ${profile.entryStyleReadMs.toFixed(2)} ms` : void 0,
				typeof profile.entryCodeReadMs === "number" ? `entry-code-read ${profile.entryCodeReadMs.toFixed(2)} ms` : void 0,
				typeof profile.entryChunkEmitMs === "number" ? `entry-chunk-emit ${profile.entryChunkEmitMs.toFixed(2)} ms` : void 0,
				typeof profile.entryChunkLoadMs === "number" ? `entry-chunk-load ${profile.entryChunkLoadMs.toFixed(2)} ms` : void 0,
				typeof profile.entryChunkEmitFileMs === "number" ? `entry-chunk-emit-file ${profile.entryChunkEmitFileMs.toFixed(2)} ms` : void 0,
				typeof profile.entryLayoutMs === "number" ? `entry-layout ${profile.entryLayoutMs.toFixed(2)} ms` : void 0,
				typeof profile.requestGlobalsMs === "number" ? `request-globals ${profile.requestGlobalsMs.toFixed(2)} ms` : void 0,
				typeof profile.weapiResolveMs === "number" ? `weapi-resolve ${profile.weapiResolveMs.toFixed(2)} ms` : void 0,
				typeof profile.transformMs === "number" ? `transform ${profile.transformMs.toFixed(2)} ms` : void 0,
				typeof profile.vueReadSourceMs === "number" ? `vue-read ${profile.vueReadSourceMs.toFixed(2)} ms` : void 0,
				typeof profile.vueCompileMs === "number" ? `vue-compile ${profile.vueCompileMs.toFixed(2)} ms` : void 0,
				typeof profile.vueFinalizeCompiledMs === "number" ? `vue-finalize-compiled ${profile.vueFinalizeCompiledMs.toFixed(2)} ms` : void 0,
				typeof profile.vueFinalizeCodeMs === "number" ? `vue-finalize-code ${profile.vueFinalizeCodeMs.toFixed(2)} ms` : void 0,
				typeof profile.writeMs === "number" ? `write ${profile.writeMs.toFixed(2)} ms` : void 0
			].filter((segment) => Boolean(segment));
			return conciseSegments.length ? `小程序已重新构建(${duration} ms,${conciseSegments.join(",")})` : `小程序已重新构建(${duration} ms)`;
		}
		const verboseSegments = [];
		if (profile.buildCoreMs !== void 0) verboseSegments.push(`build-core ${profile.buildCoreMs.toFixed(2)} ms`);
		if (profile.transformMs !== void 0) verboseSegments.push(`transform ${profile.transformMs.toFixed(2)} ms`);
		if (profile.vueReadSourceMs !== void 0) verboseSegments.push(`vue-read ${profile.vueReadSourceMs.toFixed(2)} ms`);
		if (profile.vueCompileMs !== void 0) verboseSegments.push(`vue-compile ${profile.vueCompileMs.toFixed(2)} ms`);
		if (profile.vueFinalizeCompiledMs !== void 0) verboseSegments.push(`vue-finalize-compiled ${profile.vueFinalizeCompiledMs.toFixed(2)} ms`);
		if (profile.vueFinalizeCodeMs !== void 0) verboseSegments.push(`vue-finalize-code ${profile.vueFinalizeCodeMs.toFixed(2)} ms`);
		if (profile.buildStartMs !== void 0) verboseSegments.push(`build-start ${profile.buildStartMs.toFixed(2)} ms`);
		if (profile.pluginResolveMs !== void 0) verboseSegments.push(`plugin-resolve ${profile.pluginResolveMs.toFixed(2)} ms`);
		if (profile.bundlerMs !== void 0) verboseSegments.push(`bundler ${profile.bundlerMs.toFixed(2)} ms`);
		if (profile.coreLoadMs !== void 0) verboseSegments.push(`core-load ${profile.coreLoadMs.toFixed(2)} ms`);
		if (profile.entryLoadMs !== void 0) verboseSegments.push(`entry-load ${profile.entryLoadMs.toFixed(2)} ms`);
		if (profile.entryEmitOutputMs !== void 0) verboseSegments.push(`entry-emit-output ${profile.entryEmitOutputMs.toFixed(2)} ms`);
		if (profile.entryTemplateScanMs !== void 0) verboseSegments.push(`entry-template-scan ${profile.entryTemplateScanMs.toFixed(2)} ms`);
		if (profile.entryAutoImportMs !== void 0) verboseSegments.push(`entry-auto-import ${profile.entryAutoImportMs.toFixed(2)} ms`);
		if (profile.entryScriptSetupMs !== void 0) verboseSegments.push(`entry-script-setup ${profile.entryScriptSetupMs.toFixed(2)} ms`);
		if (profile.entryVueSignatureMs !== void 0) verboseSegments.push(`entry-vue-signature ${profile.entryVueSignatureMs.toFixed(2)} ms`);
		if (profile.entrySidecarResolveMs !== void 0) verboseSegments.push(`entry-sidecar-resolve ${profile.entrySidecarResolveMs.toFixed(2)} ms`);
		if (profile.entryJsonReadMs !== void 0) verboseSegments.push(`entry-json-read ${profile.entryJsonReadMs.toFixed(2)} ms`);
		if (profile.entryVueConfigMs !== void 0) verboseSegments.push(`entry-vue-config ${profile.entryVueConfigMs.toFixed(2)} ms`);
		if (profile.entryPrepareMs !== void 0) verboseSegments.push(`entry-prepare ${profile.entryPrepareMs.toFixed(2)} ms`);
		if (profile.entryResolveMs !== void 0) verboseSegments.push(`entry-resolve ${profile.entryResolveMs.toFixed(2)} ms`);
		if (profile.entryStyleScanMs !== void 0) verboseSegments.push(`entry-style-scan ${profile.entryStyleScanMs.toFixed(2)} ms`);
		if (profile.entryStyleReadMs !== void 0) verboseSegments.push(`entry-style-read ${profile.entryStyleReadMs.toFixed(2)} ms`);
		if (profile.entryCodeReadMs !== void 0) verboseSegments.push(`entry-code-read ${profile.entryCodeReadMs.toFixed(2)} ms`);
		if (profile.entryChunkEmitMs !== void 0) verboseSegments.push(`entry-chunk-emit ${profile.entryChunkEmitMs.toFixed(2)} ms`);
		if (profile.entryChunkLoadMs !== void 0) verboseSegments.push(`entry-chunk-load ${profile.entryChunkLoadMs.toFixed(2)} ms`);
		if (profile.entryChunkEmitFileMs !== void 0) verboseSegments.push(`entry-chunk-emit-file ${profile.entryChunkEmitFileMs.toFixed(2)} ms`);
		if (profile.entryLayoutMs !== void 0) verboseSegments.push(`entry-layout ${profile.entryLayoutMs.toFixed(2)} ms`);
		if (profile.requestGlobalsMs !== void 0) verboseSegments.push(`request-globals ${profile.requestGlobalsMs.toFixed(2)} ms`);
		if (profile.weapiResolveMs !== void 0) verboseSegments.push(`weapi-resolve ${profile.weapiResolveMs.toFixed(2)} ms`);
		if (profile.renderStartMs !== void 0) verboseSegments.push(`render-start ${profile.renderStartMs.toFixed(2)} ms`);
		if (profile.generateBundleMs !== void 0) verboseSegments.push(`generate ${profile.generateBundleMs.toFixed(2)} ms`);
		if (profile.generateSharedMs !== void 0) verboseSegments.push(`generate-shared ${profile.generateSharedMs.toFixed(2)} ms`);
		if (profile.generateRewriteMs !== void 0) verboseSegments.push(`generate-rewrite ${profile.generateRewriteMs.toFixed(2)} ms`);
		if (profile.generateModuleGraphMs !== void 0) verboseSegments.push(`module-graph ${profile.generateModuleGraphMs.toFixed(2)} ms`);
		if (profile.snapshotResolveMs !== void 0) verboseSegments.push(`snapshot-resolve ${profile.snapshotResolveMs.toFixed(2)} ms`);
		if (profile.snapshotBuildMs !== void 0) verboseSegments.push(`snapshot-build ${profile.snapshotBuildMs.toFixed(2)} ms`);
		if (profile.writeMs !== void 0) verboseSegments.push(`write ${profile.writeMs.toFixed(2)} ms`);
		if (profile.watchToDirtyMs !== void 0) verboseSegments.push(`watch->dirty ${profile.watchToDirtyMs.toFixed(2)} ms`);
		if (profile.emitMs !== void 0) verboseSegments.push(`emit ${profile.emitMs.toFixed(2)} ms`);
		if (profile.sharedChunkResolveMs !== void 0) verboseSegments.push(`shared ${profile.sharedChunkResolveMs.toFixed(2)} ms`);
		if (profile.loadCount !== void 0 || profile.resolveCount !== void 0 || profile.chunkEmitCount !== void 0 || profile.skippedLoadedCount !== void 0) verboseSegments.push(`load/resolve/chunk/skip ${profile.loadCount ?? 0}/${profile.resolveCount ?? 0}/${profile.chunkEmitCount ?? 0}/${profile.skippedLoadedCount ?? 0}`);
		if (profile.dirtyCount !== void 0 || profile.pendingCount !== void 0 || profile.emittedCount !== void 0) verboseSegments.push(`d/p/e ${profile.dirtyCount ?? 0}/${profile.pendingCount ?? 0}/${profile.emittedCount ?? 0}`);
		const dirtyReason = formatReasonSummary(profile.dirtyReasonSummary);
		const pendingReason = formatReasonSummary(profile.pendingReasonSummary);
		if (dirtyReason || pendingReason) verboseSegments.push(`cause ${dirtyReason ?? "-"} -> ${pendingReason ?? "-"}`);
		return verboseSegments.length ? `小程序已重新构建(${duration} ms,${verboseSegments.join(",")}${formatHmrRecentSummary()})` : `小程序已重新构建(${duration} ms)`;
	}
	function formatHmrPhaseRegressionHint(currentProfile, previousProfiles) {
		const candidates = [];
		const phasePriority = {
			"emit": 0,
			"shared": 1,
			"write": 2,
			"build-start": 3,
			"plugin-resolve": 4,
			"transform": 5,
			"core-transform": 6,
			"wevu-transform": 7,
			"vue-transform": 8,
			"vue-read": 9,
			"vue-compile": 10,
			"vue-finalize-compiled": 11,
			"vue-finalize-code": 12,
			"core-load": 13,
			"entry-load": 14,
			"entry-emit-output": 15,
			"entry-template-scan": 16,
			"entry-auto-import": 17,
			"entry-script-setup": 18,
			"entry-vue-signature": 19,
			"entry-sidecar-resolve": 20,
			"entry-json-read": 21,
			"entry-vue-config": 22,
			"entry-prepare": 23,
			"entry-resolve": 24,
			"entry-style-scan": 25,
			"entry-style-read": 26,
			"entry-code-read": 27,
			"entry-chunk-emit": 28,
			"entry-chunk-load": 29,
			"entry-chunk-emit-file": 30,
			"entry-layout": 31,
			"request-globals": 32,
			"weapi-resolve": 33,
			"render-start": 34,
			"generate": 35,
			"generate-shared": 36,
			"generate-rewrite": 37,
			"module-graph": 38,
			"snapshot-resolve": 39,
			"snapshot-build": 40,
			"watch->dirty": 41,
			"build-core": 42
		};
		for (const phase of [
			{
				key: "buildCoreMs",
				label: "build-core"
			},
			{
				key: "transformMs",
				label: "transform"
			},
			{
				key: "buildStartMs",
				label: "build-start"
			},
			{
				key: "pluginResolveMs",
				label: "plugin-resolve"
			},
			{
				key: "coreTransformMs",
				label: "core-transform"
			},
			{
				key: "wevuTransformMs",
				label: "wevu-transform"
			},
			{
				key: "vueTransformMs",
				label: "vue-transform"
			},
			{
				key: "vueReadSourceMs",
				label: "vue-read"
			},
			{
				key: "vueCompileMs",
				label: "vue-compile"
			},
			{
				key: "vueFinalizeCompiledMs",
				label: "vue-finalize-compiled"
			},
			{
				key: "vueFinalizeCodeMs",
				label: "vue-finalize-code"
			},
			{
				key: "coreLoadMs",
				label: "core-load"
			},
			{
				key: "entryLoadMs",
				label: "entry-load"
			},
			{
				key: "entryEmitOutputMs",
				label: "entry-emit-output"
			},
			{
				key: "entryTemplateScanMs",
				label: "entry-template-scan"
			},
			{
				key: "entryAutoImportMs",
				label: "entry-auto-import"
			},
			{
				key: "entryScriptSetupMs",
				label: "entry-script-setup"
			},
			{
				key: "entryVueSignatureMs",
				label: "entry-vue-signature"
			},
			{
				key: "entrySidecarResolveMs",
				label: "entry-sidecar-resolve"
			},
			{
				key: "entryJsonReadMs",
				label: "entry-json-read"
			},
			{
				key: "entryVueConfigMs",
				label: "entry-vue-config"
			},
			{
				key: "entryPrepareMs",
				label: "entry-prepare"
			},
			{
				key: "entryResolveMs",
				label: "entry-resolve"
			},
			{
				key: "entryStyleScanMs",
				label: "entry-style-scan"
			},
			{
				key: "entryStyleReadMs",
				label: "entry-style-read"
			},
			{
				key: "entryCodeReadMs",
				label: "entry-code-read"
			},
			{
				key: "entryChunkEmitMs",
				label: "entry-chunk-emit"
			},
			{
				key: "entryChunkLoadMs",
				label: "entry-chunk-load"
			},
			{
				key: "entryChunkEmitFileMs",
				label: "entry-chunk-emit-file"
			},
			{
				key: "entryLayoutMs",
				label: "entry-layout"
			},
			{
				key: "requestGlobalsMs",
				label: "request-globals"
			},
			{
				key: "weapiResolveMs",
				label: "weapi-resolve"
			},
			{
				key: "renderStartMs",
				label: "render-start"
			},
			{
				key: "generateBundleMs",
				label: "generate"
			},
			{
				key: "generateSharedMs",
				label: "generate-shared"
			},
			{
				key: "generateRewriteMs",
				label: "generate-rewrite"
			},
			{
				key: "generateModuleGraphMs",
				label: "module-graph"
			},
			{
				key: "snapshotResolveMs",
				label: "snapshot-resolve"
			},
			{
				key: "snapshotBuildMs",
				label: "snapshot-build"
			},
			{
				key: "watchToDirtyMs",
				label: "watch->dirty"
			},
			{
				key: "emitMs",
				label: "emit"
			},
			{
				key: "sharedChunkResolveMs",
				label: "shared"
			},
			{
				key: "writeMs",
				label: "write"
			}
		]) {
			const currentValue = currentProfile[phase.key];
			if (currentValue === void 0 || currentValue < 5) continue;
			const previousValues = previousProfiles.flatMap((item) => {
				const value = item[phase.key];
				return value === void 0 ? [] : [value];
			});
			if (!previousValues.length) continue;
			const averageMs = previousValues.reduce((sum, value) => sum + value, 0) / previousValues.length;
			if (averageMs <= 0) continue;
			candidates.push({
				label: phase.label,
				currentMs: currentValue,
				averageMs,
				ratio: currentValue / averageMs
			});
		}
		const bestCandidate = candidates.filter((candidate) => candidate.currentMs >= 10 && candidate.ratio >= 1.3).sort((left, right) => {
			return right.ratio - left.ratio || right.currentMs - left.currentMs || phasePriority[left.label] - phasePriority[right.label];
		})[0];
		if (!bestCandidate) return "";
		return `;疑似慢段 ${bestCandidate.label} ${bestCandidate.currentMs.toFixed(2)} ms(近${previousProfiles.length}次均值 ${bestCandidate.averageMs.toFixed(2)} ms)`;
	}
	function shouldLogSlowHmrTip() {
		if (!resolveHmrProfileJsonPath$1()) return false;
		const recentProfiles = ctx.runtimeState.build.hmr.recentProfiles;
		if (recentProfiles.length < 4) return false;
		if (recentProfiles.length - lastHmrSlowTipProfileCount < 3) return false;
		const currentProfile = recentProfiles[recentProfiles.length - 1];
		if (!currentProfile) return false;
		const previousProfiles = recentProfiles.slice(0, -1);
		const previousAverage = previousProfiles.reduce((sum, item) => sum + item.totalMs, 0) / previousProfiles.length;
		if (currentProfile.totalMs < 120) return false;
		if (currentProfile.totalMs < previousAverage * 1.5) return false;
		lastHmrSlowTipProfileCount = recentProfiles.length;
		logger_default.info(`检测到 HMR 重建明显变慢:当前 ${currentProfile.totalMs.toFixed(2)} ms,近${previousProfiles.length}次均值 ${previousAverage.toFixed(2)} ms${formatHmrPhaseRegressionHint(currentProfile, previousProfiles)};建议运行 weapp-vite analyze --hmr-profile 查看阶段统计。`);
		return true;
	}
	async function writeHmrProfileJsonSample(totalMs) {
		const outputPath = resolveHmrProfileJsonPath$1();
		if (!outputPath) return;
		await mkdir(path.dirname(outputPath), { recursive: true });
		await appendFile(outputPath, `${JSON.stringify(createHmrProfileJsonSample(totalMs))}\n`, "utf8");
	}
	function assertRuntimeServices(target) {
		if (!target.configService || !target.watcherService || !target.npmService || !target.scanService) throw new Error("构建服务需要先初始化 config、watcher、npm 和 scan 服务。");
	}
	assertRuntimeServices(ctx);
	const { configService, watcherService, npmService, scanService } = ctx;
	function attachSidecarWatcherToWatcherClose(options) {
		const { watcher, watcherRoot, sidecarRoot, waitForPendingSnapshotBuilds, markClosed } = options;
		const originalClose = watcher.close.bind(watcher);
		let closePromise;
		watcher.close = () => {
			if (!closePromise) closePromise = (async () => {
				markClosed();
				await waitForPendingSnapshotBuilds().catch(() => {});
				const sidecarWatcher = watcherService.sidecarWatcherMap.get(sidecarRoot);
				if (sidecarWatcher) {
					watcherService.sidecarWatcherMap.delete(sidecarRoot);
					await Promise.resolve(sidecarWatcher.close()).catch(() => {});
				}
				watcherService.rollupWatcherMap.delete(watcherRoot);
				await originalClose();
			})();
			return closePromise;
		};
	}
	const buildState = ctx.runtimeState.build;
	const { queue } = buildState;
	const requestedConfigRestartBuilds = /* @__PURE__ */ new Set();
	let autoTouchResolved = false;
	let autoTouchChecked = false;
	function hasAutoTouchAppWxssReason() {
		return (ctx.runtimeState.build.hmr.profile.dirtyReasonSummary ?? []).some((reason) => {
			return reason.startsWith("tailwind-content:") || reason.startsWith("style-sidecar:") || reason.startsWith("entry-style-only:");
		});
	}
	const { buildIndependentBundle, getIndependentOutput, invalidateIndependentOutput } = createIndependentBuilder(configService, buildState);
	function shouldTouchAppWxss() {
		const option = configService.weappViteConfig.hmr?.touchAppWxss ?? "auto";
		if (option === true) return true;
		if (option === false) return false;
		if (!hasAutoTouchAppWxssReason()) return false;
		if (!autoTouchChecked) {
			autoTouchChecked = true;
			autoTouchResolved = resolveTouchAppWxssEnabled({
				option,
				platform: configService.platform,
				packageJson: configService.packageJson,
				cwd: configService.cwd
			});
		}
		return autoTouchResolved;
	}
	function isDevOutputFile(filePath) {
		const normalizedOutDir = normalizeFsResolvedId(configService.outDir);
		const normalizedFile = normalizeFsResolvedId(filePath);
		return normalizedFile === normalizedOutDir || normalizedFile.startsWith(`${normalizedOutDir}/`);
	}
	function shouldRestartDevBuild(target) {
		if (!configService.isDev) return false;
		return requestedConfigRestartBuilds.delete(target);
	}
	async function runDev(target) {
		if (process.env.NODE_ENV === void 0) process.env.NODE_ENV = "development";
		debug$2?.(`[${target}] dev build watcher start`);
		const { hasWorkersDir, workersDir } = checkWorkersOptions(target, configService, scanService);
		const configuredHmrRuntime = configService.weappViteConfig.hmr?.runtime;
		const compileHotReLoad = configService.projectPrivateConfig.setting?.compileHotReLoad;
		devHmrDecision ??= resolveHmrRuntimeDecision({
			platform: configService.platform,
			configured: configuredHmrRuntime,
			compileHotReLoad
		});
		const createDevBuildOptions = () => {
			const options = applyTargetBuildOverride(configService.merge(void 0, createSharedBuildConfig(configService, scanService), resolveTargetBuildOverride(target)), target);
			if (target === "app" && devHmrDecision?.runtime === "classic") {
				let skylineFiles = [];
				options.plugins = [...options.plugins ?? [], {
					name: "weapp-vite:skyline-hmr-compatibility",
					enforce: "post",
					generateBundle(_options, bundle) {
						skylineFiles = findSkylineRendererFiles(Object.values(bundle));
					},
					writeBundle() {
						if (skylineFiles.length === 0) return;
						const detectedFiles = skylineFiles;
						skylineFiles = [];
						setTimeout(() => {
							applySkylineHmrFallback({
								compileHotReLoad,
								configured: devHmrDecision?.configured,
								files: detectedFiles
							});
						}, 0);
					}
				}];
			}
			return appendHmrMetricsPlugin(options);
		};
		let buildOptions = createDevBuildOptions();
		buildOptions.build = {
			...buildOptions.build ?? {},
			write: true
		};
		const hmrDecision = devHmrDecision;
		if (target === "app" && hmrDecision.runtime !== "stateful-experimental") logHmrRuntimeDecision(hmrDecision);
		if (target === "app" && hmrDecision.runtime === "stateful-experimental") try {
			const snapshotBuildOptions = {
				...buildOptions,
				build: {
					...buildOptions.build ?? {},
					watch: void 0,
					write: false
				}
			};
			const initialSnapshot = toStatefulHmrOutput(await build(snapshotBuildOptions));
			const initialEntryIds = collectStatefulHmrEntryIds(ctx.runtimeState.build.hmr.resolvedEntryMap.keys(), initialSnapshot, configService.cwd, configService.absoluteSrcRoot);
			const skylineFiles = findSkylineRendererFiles(initialSnapshot);
			if (skylineFiles.length > 0) await applySkylineHmrFallback({
				compileHotReLoad,
				configured: hmrDecision.configured,
				files: skylineFiles
			});
			if (devHmrDecision?.runtime === "classic") {
				resetRuntimeStateForFreshBuild(ctx.runtimeState);
				await configService.load(configService.loadOptions);
				await scanService.loadAppEntry();
				scanService.loadSubPackages();
				return await runDev(target);
			}
			logHmrRuntimeDecision(hmrDecision);
			await configService.load(configService.loadOptions);
			resetRuntimeStateForFreshBuild(ctx.runtimeState);
			await scanService.loadAppEntry();
			scanService.loadSubPackages();
			buildOptions = createDevBuildOptions();
			buildOptions.build = {
				...buildOptions.build ?? {},
				write: true
			};
			const workerPromise = hasWorkersDir && workersDir ? devWorkers(configService, watcherService, workersDir) : Promise.resolve();
			let statefulWatcher;
			const [watcher] = await Promise.all([runStatefulHmrDev(ctx, buildOptions, async () => {
				await statefulWatcher?.close();
				logger_default.info("检测到非兼容更新,正在重启微信状态保持 HMR 构建...");
				resetRuntimeStateForFreshBuild(ctx.runtimeState);
				await configService.load(configService.loadOptions);
				await scanService.loadAppEntry();
				scanService.loadSubPackages();
				await runDev(target);
				logger_default.success("微信状态保持 HMR 构建已完成完整重载。");
			}, {
				entryIds: initialEntryIds,
				initial: initialSnapshot,
				rebuild: async (files) => {
					for (const file of files) invalidateFileCache(file);
					resetRuntimeStateForFreshBuild(ctx.runtimeState);
					await configService.load(configService.loadOptions);
					await scanService.loadAppEntry();
					scanService.loadSubPackages();
					const snapshotOptions = createDevBuildOptions();
					snapshotOptions.build = {
						...snapshotOptions.build ?? {},
						emptyOutDir: false,
						watch: void 0,
						write: false
					};
					snapshotOptions.plugins = [...snapshotOptions.plugins ?? [], {
						name: "weapp-vite:stateful-hmr-snapshot-assets",
						enforce: "post",
						generateBundle(_options, bundle) {
							for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk") delete bundle[fileName];
						}
					}];
					return toStatefulHmrOutput(await build(snapshotOptions));
				}
			}), workerPromise]);
			statefulWatcher = watcher;
			watcherService.setRollupWatcher(watcher, "/");
			return watcher;
		} catch (error) {
			if (hmrDecision.configured !== "auto" || !isStatefulHmrRuntimeCompatibilityError(error)) throw error;
			devHmrDecision = {
				configured: hmrDecision.configured,
				reason: "runtime-compatibility-fallback",
				runtime: "classic"
			};
			logger_default.warn(`微信状态保持 HMR 运行时不可用,已自动降级为 classic:${error instanceof Error ? error.message : String(error)}`);
			logger_default.info(formatHmrRuntimeStartupMessages(devHmrDecision)[0]);
			resetRuntimeStateForFreshBuild(ctx.runtimeState);
			await configService.load(configService.loadOptions);
			await scanService.loadAppEntry();
			scanService.loadSubPackages();
			return await runDev(target);
		}
		const snapshotBuildOptions = {
			...buildOptions,
			build: {
				...buildOptions.build ?? {},
				emptyOutDir: false
			}
		};
		delete snapshotBuildOptions.build?.watch;
		const snapshotWatcherRoot = `${configService.absoluteSrcRoot}::dev-snapshot`;
		let snapshotBuildChain = Promise.resolve(void 0);
		let devWatcherClosed = false;
		let pendingSnapshotBatch;
		let snapshotBatchTimer;
		const devBuildWatcher = target === "app" ? createDevBuildWatcher() : void 0;
		function markSnapshotEntriesFullDirty() {
			for (const entryId of ctx.runtimeState.build.hmr.resolvedEntryMap.keys()) {
				ctx.runtimeState.build.hmr.dirtyEntrySet.add(entryId);
				ctx.runtimeState.build.hmr.dirtyEntryReasons.set(entryId, "direct");
				ctx.runtimeState.build.hmr.loadedEntrySet.delete(entryId);
				if (entryId.endsWith(".vue")) ctx.runtimeState.build.hmr.dirtyVueEntryIds.add(entryId);
			}
			ctx.runtimeState.build.hmr.profile = {
				...ctx.runtimeState.build.hmr.profile,
				dirtyCount: ctx.runtimeState.build.hmr.dirtyEntrySet.size,
				dirtyReasonSummary: [`snapshot-full:${ctx.runtimeState.build.hmr.resolvedEntryMap.size}`]
			};
		}
		function markSnapshotEntryDirty(entryId, reason, dirtyReason = "metadata") {
			ctx.runtimeState.build.hmr.dirtyEntrySet.add(entryId);
			ctx.runtimeState.build.hmr.dirtyEntryReasons.set(entryId, dirtyReason);
			ctx.runtimeState.build.hmr.loadedEntrySet.delete(entryId);
			if (entryId.endsWith(".vue") && dirtyReason !== "dependency") ctx.runtimeState.build.hmr.dirtyVueEntryIds.add(entryId);
			ctx.runtimeState.build.hmr.profile = {
				...ctx.runtimeState.build.hmr.profile,
				dirtyCount: ctx.runtimeState.build.hmr.dirtyEntrySet.size,
				dirtyReasonSummary: reason?.file ? [resolveSnapshotSidecarDirtySummary(reason.file)] : ["sidecar-direct:1"]
			};
		}
		function resolveSnapshotDirtyReason(reason) {
			if (!reason?.file) return "direct";
			if (isLayoutSourcePath(configService.relativeAbsoluteSrcRoot(reason.file))) return "dependency";
			return isSidecarFile(reason.file) ? "metadata" : "direct";
		}
		const runSnapshotBuild = (reason, batchReasons = reason ? [reason] : [], eventStartedAt = reason ? performance.now() : 0) => {
			if (devWatcherClosed) return snapshotBuildChain;
			const currentSnapshotBuild = snapshotBuildChain.then(async () => {
				if (devWatcherClosed) return;
				if (reason?.event || reason?.file) {
					if (reason.file) invalidateFileCache(reason.file);
					ctx.runtimeState.build.hmr.profile = {
						...ctx.runtimeState.build.hmr.profile,
						eventId: createHmrProfileEventId(),
						event: reason.event,
						file: reason.file,
						watchToDirtyMs: performance.now() - eventStartedAt
					};
				}
				const snapshotResolveStartedAt = performance.now();
				const graphAffectedEntries = /* @__PURE__ */ new Set();
				const graphAffectedEntriesByFile = /* @__PURE__ */ new Map();
				for (const batchReason of batchReasons) {
					if (!batchReason.file) continue;
					const affectedForFile = ctx.moduleGraphService.collectAffectedEntries(batchReason.file);
					graphAffectedEntriesByFile.set(normalizeFsResolvedId(batchReason.file), affectedForFile);
					for (const entryId of affectedForFile) graphAffectedEntries.add(entryId);
				}
				debug$2?.(`[module-graph-provider] affected=${graphAffectedEntries.size} files=${batchReasons.length}`);
				recordHmrProfileDuration(ctx.runtimeState.build.hmr.profile, "snapshotResolveMs", performance.now() - snapshotResolveStartedAt);
				const snapshotBuildStartedAt = performance.now();
				const requiresFullRescan = batchReasons.some((batchReason) => batchReason.forceFullRescan || batchReason.event === "create" || batchReason.event === "delete");
				if (!requiresFullRescan && graphAffectedEntries.size) {
					const dirtyReasons = batchReasons.map(resolveSnapshotDirtyReason);
					const dirtyReason = dirtyReasons.includes("direct") ? "direct" : dirtyReasons.includes("dependency") ? "dependency" : "metadata";
					for (const entryId of graphAffectedEntries) if (ctx.runtimeState.build.hmr.resolvedEntryMap.has(entryId)) markSnapshotEntryDirty(entryId, reason, dirtyReason);
					const summaryCounts = /* @__PURE__ */ new Map();
					for (const batchReason of batchReasons) {
						if (!batchReason.file) continue;
						const summary = resolveSnapshotSidecarDirtySummary(batchReason.file, graphAffectedEntriesByFile.get(normalizeFsResolvedId(batchReason.file))).replace(/:\d+$/, "");
						summaryCounts.set(summary, (summaryCounts.get(summary) ?? 0) + 1);
					}
					ctx.runtimeState.build.hmr.profile.dirtyReasonSummary = Array.from(summaryCounts, ([summary, count]) => `${summary}:${count}`);
					try {
						devBuildWatcher?.emitEvent({ code: "START" });
						await build(snapshotBuildOptions);
						devBuildWatcher?.emitEvent({ code: "END" });
					} catch (error) {
						devBuildWatcher?.emitEvent({
							code: "ERROR",
							error: error instanceof Error ? error : new Error(String(error)),
							result: void 0
						});
						throw error;
					} finally {
						recordHmrProfileDuration(ctx.runtimeState.build.hmr.profile, "snapshotBuildMs", performance.now() - snapshotBuildStartedAt);
					}
					return "snapshot";
				}
				if (!requiresFullRescan && batchReasons.length && batchReasons.every((batchReason) => batchReason.event === "update")) return;
				markSnapshotEntriesFullDirty();
				process.env.WEAPP_VITE_FORCE_FULL_HMR_SHARED_CHUNKS = "1";
				try {
					devBuildWatcher?.emitEvent({ code: "START" });
					await build({
						...snapshotBuildOptions,
						build: {
							...snapshotBuildOptions.build ?? {},
							emptyOutDir: true
						}
					});
					devBuildWatcher?.emitEvent({ code: "END" });
					return "snapshot";
				} catch (error) {
					devBuildWatcher?.emitEvent({
						code: "ERROR",
						error: error instanceof Error ? error : new Error(String(error)),
						result: void 0
					});
					throw error;
				} finally {
					recordHmrProfileDuration(ctx.runtimeState.build.hmr.profile, "snapshotBuildMs", performance.now() - snapshotBuildStartedAt);
					delete process.env.WEAPP_VITE_FORCE_FULL_HMR_SHARED_CHUNKS;
				}
			});
			snapshotBuildChain = currentSnapshotBuild.catch(() => void 0);
			return currentSnapshotBuild;
		};
		function resolveSnapshotBatchReason(batch) {
			const [firstReason] = batch.reasons;
			if (!firstReason) return;
			if (batch.reasons.length === 1) return firstReason;
			return batch.reasons.every((reason) => {
				return reason.event === firstReason.event && reason.file === firstReason.file;
			}) ? firstReason : void 0;
		}
		function scheduleSnapshotBuild(reason, startedAt) {
			if (devWatcherClosed) return;
			if (reason.file) ctx.moduleGraphService?.recordChangedFile(reason.file, reason.event ?? "update");
			if (pendingSnapshotBatch) {
				pendingSnapshotBatch.reasons.push(reason);
				pendingSnapshotBatch.startedAt = Math.min(pendingSnapshotBatch.startedAt, startedAt);
			} else pendingSnapshotBatch = {
				reasons: [reason],
				startedAt
			};
			if (snapshotBatchTimer) return;
			snapshotBatchTimer = setTimeout(() => {
				snapshotBatchTimer = void 0;
				const batch = pendingSnapshotBatch;
				pendingSnapshotBatch = void 0;
				if (!batch || devWatcherClosed) return;
				const batchReason = resolveSnapshotBatchReason(batch);
				runSnapshotBuild(batchReason, batch.reasons, batch.startedAt).catch((error) => {
					resetHmrProfile();
					logger_default.error(error);
				});
			}, SNAPSHOT_BUILD_BATCH_DELAY_MS);
		}
		const moduleGraphProvider = target === "app" ? await createDevModuleGraphProvider(ctx, buildOptions, ({ event, file: id }) => {
			if (isDevOutputFile(id)) return;
			const hasModule = ctx.moduleGraphService.hasModule(id);
			debug$2?.(`[module-graph-provider] event=${event} change=${configService.relativeAbsoluteSrcRoot(id)} module=${hasModule}`);
			if (!hasModule) return;
			const startedAt = performance.now();
			scheduleSnapshotBuild({
				event,
				file: id
			}, startedAt);
		}) : void 0;
		const watcherPromise = target === "app" ? (async () => {
			devBuildWatcher.emitEvent({ code: "START" });
			try {
				await build(snapshotBuildOptions);
				devBuildWatcher.emitEvent({ code: "END" });
				return devBuildWatcher.watcher;
			} catch (error) {
				devBuildWatcher.emitEvent({
					code: "ERROR",
					error: error instanceof Error ? error : new Error(String(error)),
					result: void 0
				});
				await moduleGraphProvider?.close();
				throw error;
			}
		})() : build(buildOptions);
		const workerPromise = target === "app" && hasWorkersDir && workersDir ? devWorkers(configService, watcherService, workersDir) : Promise.resolve();
		const [watcher] = await Promise.all([watcherPromise, workerPromise]);
		const isTestEnv = process.env.VITEST === "true" || process.env.NODE_ENV === "test";
		if (target === "app" && hasWorkersDir && workersDir && !isTestEnv) watchWorkers(configService, watcherService, workersDir);
		debug$2?.("dev build watcher end");
		debug$2?.("dev watcher listen start");
		let startTime;
		let firstBuildCompleted = false;
		let resolveWatcher;
		let rejectWatcher;
		const promise = new Promise((res, rej) => {
			resolveWatcher = res;
			rejectWatcher = rej;
		});
		const { styleExtension } = resolveCompilerOutputExtensions(configService.outputExtensions);
		const appWxssPath = target === "app" ? path.join(configService.outDir, `app.${styleExtension}`) : void 0;
		watcher.on("event", (e) => {
			if (devWatcherClosed) return;
			if (e.code === "START") startTime = performance.now();
			else if (e.code === "END") {
				const bundlerDurationMs = performance.now() - startTime;
				const durationMs = bundlerDurationMs + (target === "app" ? ctx.runtimeState.build.hmr.profile.watchToDirtyMs ?? 0 : 0);
				recordHmrProfileDuration(ctx.runtimeState.build.hmr.profile, "bundlerMs", bundlerDurationMs);
				(async () => {
					if (shouldRestartDevBuild(target)) {
						await watcher.close();
						logger_default.info("检测到 Vite 配置变更,正在重启小程序开发构建...");
						resetRuntimeStateForFreshBuild(ctx.runtimeState);
						await configService.load(configService.loadOptions);
						try {
							const supportFiles = await syncProjectSupportFiles(ctx);
							for (const warning of supportFiles.managedTsconfigWarnings) logger_default.warn(warning);
						} catch (error) {
							const message = error instanceof Error ? error.message : String(error);
							logger_default.warn(`[prepare] 自动同步 .weapp-vite 支持文件失败:${message}`);
						}
						await scanService.loadAppEntry();
						scanService.loadSubPackages();
						await runDev(target);
						logger_default.success("Vite 配置已重新加载,小程序开发构建已重启。");
						resolveWatcher(e);
						return;
					}
					if (firstBuildCompleted) {
						finalizeHmrProfile(bundlerDurationMs);
						recordHmrProfile(durationMs);
						await writeHmrProfileJsonSample(durationMs).catch((error) => {
							debug$2?.(`write hmr profile json failed: ${String(error)}`);
						});
						logger_default.success(formatHmrLogLine(durationMs));
						shouldLogSlowHmrTip();
						if (appWxssPath && shouldTouchAppWxss()) touch(appWxssPath).catch(() => {});
					} else firstBuildCompleted = true;
					resetHmrProfile();
					resolveWatcher(e);
				})().catch((error) => {
					resetHmrProfile();
					rejectWatcher(error);
				});
			} else if (e.code === "ERROR") {
				resetHmrProfile();
				if (target !== "app") rejectWatcher(e);
			}
		});
		if (target !== "app") await promise;
		const watcherRoot = target === "plugin" ? configService.absolutePluginRoot ?? configService.absoluteSrcRoot : "/";
		if (target === "app" && !watcherService.sidecarWatcherMap.has(snapshotWatcherRoot)) {
			const snapshotWatcher = chokidar.watch(createSnapshotSidecarWatchPatterns(configService, buildOptions), createSidecarWatchOptions(configService, {
				persistent: true,
				ignoreInitial: true,
				ignored: createSnapshotSidecarIgnoredMatcher(ctx)
			}));
			snapshotWatcher.on("all", (event, id) => {
				if (!id) return;
				if (isDevOutputFile(id)) return;
				if (!shouldHandleSnapshotSidecarFile(id, ctx)) return;
				const normalizedId = normalizeFsResolvedId(id);
				const isConfigDependency = (configService.configFileDependencies ?? []).some((dependency) => normalizeFsResolvedId(dependency) === normalizedId);
				if (!event.startsWith("add") && !event.startsWith("unlink") && !isConfigDependency) return;
				if (event.startsWith("add") && !isConfigDependency && ctx.moduleGraphService.hasModule(id)) return;
				if (isConfigDependency) requestedConfigRestartBuilds.add(target);
				const sidecarStartedAt = performance.now();
				scheduleSnapshotBuild({
					event: event.startsWith("unlink") ? "delete" : event.startsWith("add") ? "create" : "update",
					file: id,
					forceFullRescan: true
				}, sidecarStartedAt);
			});
			watcherService.sidecarWatcherMap.set(snapshotWatcherRoot, { close: async () => {
				await snapshotWatcher.close();
				await moduleGraphProvider?.close();
			} });
			attachSidecarWatcherToWatcherClose({
				watcher,
				watcherRoot,
				sidecarRoot: snapshotWatcherRoot,
				waitForPendingSnapshotBuilds: () => snapshotBuildChain,
				markClosed: () => {
					devWatcherClosed = true;
				}
			});
			await waitForSidecarWatcherReady(snapshotWatcher);
		}
		watcherService.setRollupWatcher(watcher, watcherRoot);
		return watcher;
	}
	async function runProd(target) {
		debug$2?.(`[${target}] prod build start`);
		const { hasWorkersDir } = checkWorkersOptions(target, configService, scanService);
		const bundlerPromise = build(applyTargetBuildOverride(configService.merge(void 0, createSharedBuildConfig(configService, scanService), resolveTargetBuildOverride(target)), target));
		const workerPromise = target === "app" && hasWorkersDir ? buildWorkers(configService) : Promise.resolve();
		const [output] = await Promise.all([bundlerPromise, workerPromise]);
		debug$2?.(`[${target}] prod build end`);
		return output;
	}
	function scheduleNpmBuild(options) {
		if (options?.skipNpm) return Promise.resolve();
		const runTask = () => queue.add(async () => {
			await npmService.build();
			if (configService.isDev) buildState.npmBuilt = true;
		});
		if (configService.isDev) return (async () => {
			const isDependenciesOutdated = await npmService.checkDependenciesCacheOutdate();
			if (!isDependenciesOutdated && buildState.npmBuilt) return;
			if (isDependenciesOutdated) buildState.npmBuilt = false;
			const task = runTask();
			queue.start();
			await task;
		})();
		const task = runTask();
		queue.start();
		return task;
	}
	function resolveTargetBuildOverride(target) {
		if (target !== "plugin") return;
		const pluginOutputRoot = configService.absolutePluginOutputRoot;
		if (!pluginOutputRoot) return;
		if (isOutputRootInsideOutDir(configService.outDir, pluginOutputRoot)) return;
		return { build: { outDir: pluginOutputRoot } };
	}
	function applyTargetBuildOverride(config, target) {
		const override = resolveTargetBuildOverride(target);
		if (!override?.build?.outDir) return config;
		return {
			...config,
			build: {
				...config.build ?? {},
				outDir: override.build.outDir
			}
		};
	}
	async function runIsolatedPluginBuild(options) {
		const pluginOutputRoot = configService.absolutePluginOutputRoot;
		if (!pluginOutputRoot) return;
		const inlineConfig = { build: { outDir: pluginOutputRoot } };
		const isolatedCtx = await createCompilerContext({
			key: `plugin-build:${configService.cwd}`,
			cwd: configService.cwd,
			isDev: configService.isDev,
			mode: configService.mode,
			pluginOnly: true,
			configFile: configService.configFilePath,
			cliPlatform: configService.platform,
			projectConfigPath: configService.projectConfigPath,
			inlineConfig
		});
		isolatedCtx.currentBuildTarget = "plugin";
		const result = await isolatedCtx.buildService.build(options);
		if (configService.isDev && result && typeof result.on === "function") {
			const watcherRoot = configService.absolutePluginRoot ?? configService.absoluteSrcRoot;
			watcherService.setRollupWatcher(result, watcherRoot);
		}
		return result;
	}
	async function runBuildTarget(target) {
		ctx.currentBuildTarget = target;
		if (configService.isDev) {
			requestedConfigRestartBuilds.delete(target);
			return await runDev(target);
		}
		return await runProd(target);
	}
	async function buildEntry(options) {
		if (!configService.isDev || configService.weappViteConfig.cleanOutputsInDev !== false) {
			await cleanOutputs(configService);
			resetEmittedOutputCaches(ctx.runtimeState);
		}
		const pluginOnly = configService.pluginOnly;
		const isMultiPlatformEnabled = configService.multiPlatform.enabled;
		const isLibMode = configService.weappLibConfig?.enabled;
		const shouldEmitLibDts = Boolean(isLibMode && configService.weappLibConfig?.dts?.enabled !== false && !configService.isDev);
		const projectConfigSyncTask = !isLibMode && !pluginOnly ? syncProjectConfigToOutput({
			outDir: configService.outDir,
			projectConfigPath: configService.projectConfigPath,
			projectPrivateConfigPath: configService.projectPrivateConfigPath,
			enabled: isMultiPlatformEnabled
		}) : Promise.resolve();
		if (!configService.isDev && !isLibMode && !pluginOnly && configService.weappViteConfig.worker?.entry !== void 0) {
			await scanService.loadAppEntry();
			scanService.loadSubPackages();
		}
		debug$2?.("build start");
		const npmBuildTask = isLibMode ? Promise.resolve() : scheduleNpmBuild(options);
		const result = await runBuildTarget(pluginOnly ? "plugin" : "app");
		if (shouldEmitLibDts) await generateLibDts(configService);
		await projectConfigSyncTask;
		await npmBuildTask;
		if (!pluginOnly && !isLibMode && configService.absolutePluginRoot) await runIsolatedPluginBuild(options);
		debug$2?.("build end");
		return result;
	}
	return {
		queue,
		build: buildEntry,
		requestConfigRestart(target = "app") {
			requestedConfigRestartBuilds.add(target);
		},
		buildIndependentBundle,
		getIndependentOutput,
		invalidateIndependentOutput
	};
}
//#endregion
//#region src/runtime/buildPlugin/index.ts
function createBuildServicePlugin(ctx) {
	ctx.buildService = createBuildService(ctx);
	return { name: "weapp-runtime:build-service" };
}
//#endregion
//#region src/runtime/localPkg.ts
function captureConsoleError(runner) {
	const originalConsoleError = console.error;
	const capturedErrors = [];
	console.error = (...args) => {
		capturedErrors.push(args);
	};
	try {
		return {
			value: runner(),
			capturedErrors
		};
	} finally {
		console.error = originalConsoleError;
	}
}
function shouldLogSuppressedResolutionError() {
	return process.env.WEAPP_VITE_DEBUG_PACKAGE_RESOLVE === "1";
}
function formatCapturedErrorMessage(args) {
	return args.map((value) => {
		if (value instanceof Error) return value.stack ?? value.message;
		if (typeof value === "string") return value;
		try {
			return JSON.stringify(value);
		} catch {
			return String(value);
		}
	}).join(" ");
}
/**
* @description 安全执行 local-pkg 同步解析,避免其内部 console.error 污染 CLI 输出
*/
function safeGetPackageInfoSync(packageName, options) {
	const { value, capturedErrors } = captureConsoleError(() => {
		try {
			return getPackageInfoSync(packageName, options);
		} catch {
			return;
		}
	});
	if (capturedErrors.length > 0 && shouldLogSuppressedResolutionError()) for (const entry of capturedErrors) process.stderr.write(`[weapp-vite:package-resolve] ${packageName}: ${formatCapturedErrorMessage(entry)}\n`);
	return value ?? void 0;
}
//#endregion
//#region src/runtime/oxcRuntime.ts
const NULL_BYTE = "\0";
const OXC_RUNTIME_HELPER_ALIAS = new RegExp(`^(?:${NULL_BYTE})?@oxc-project(?:/|\\+)runtime(?:@[^/]+)?/helpers/(.+)\\.js$`);
const FALLBACK_HELPER_PREFIX = `${NULL_BYTE}weapp-vite:oxc-helper:`;
const fallbackHelpers = {
	objectWithoutProperties: `export default function _objectWithoutProperties(source, excluded) {\n  if (source == null) return {};\n  var target = {};\n  var sourceKeys = Object.keys(source);\n  var key;\n  for (var i = 0; i < sourceKeys.length; i++) {\n    key = sourceKeys[i];\n    if (excluded.indexOf(key) >= 0) continue;\n    if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n    target[key] = source[key];\n  }\n  if (Object.getOwnPropertySymbols) {\n    var symbolKeys = Object.getOwnPropertySymbols(source);\n    for (var i = 0; i < symbolKeys.length; i++) {\n      key = symbolKeys[i];\n      if (excluded.indexOf(key) >= 0) continue;\n      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n      target[key] = source[key];\n    }\n  }\n  return target;\n}`,
	objectSpread2: `function ownKeys(object, enumerableOnly) {\n  var keys = Object.keys(object);\n  if (Object.getOwnPropertySymbols) {\n    var symbols = Object.getOwnPropertySymbols(object);\n    if (enumerableOnly) {\n      symbols = symbols.filter(function(symbol) {\n        return Object.getOwnPropertyDescriptor(object, symbol).enumerable;\n      });\n    }\n    keys.push.apply(keys, symbols);\n  }\n  return keys;\n}\nfunction _objectSpread2(target) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i] != null ? arguments[i] : {};\n    if (i % 2) {\n      ownKeys(Object(source), true).forEach(function(key) {\n        target[key] = source[key];\n      });\n    } else {\n      if (Object.getOwnPropertyDescriptors) {\n        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n      } else {\n        ownKeys(Object(source)).forEach(function(key) {\n          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n        });\n      }\n    }\n  }\n  return target;\n}\nexport default _objectSpread2;`
};
function getOxcHelperName(id) {
	OXC_RUNTIME_HELPER_ALIAS.lastIndex = 0;
	return OXC_RUNTIME_HELPER_ALIAS.exec(id)?.[1];
}
function createOxcRuntimeSupport() {
	const oxcRuntimeInfo = safeGetPackageInfoSync("@oxc-project/runtime");
	const oxcRuntimeHelpersRoot = oxcRuntimeInfo ? path.resolve(oxcRuntimeInfo.rootPath, "src/helpers/esm") : void 0;
	const alias = {
		find: OXC_RUNTIME_HELPER_ALIAS,
		replacement: "@oxc-project/runtime/src/helpers/esm/$1.js"
	};
	if (!oxcRuntimeHelpersRoot) return { alias };
	return {
		alias,
		rolldownPlugin: {
			name: "weapp-vite:rolldown-oxc-runtime",
			resolveId(source) {
				if (source.startsWith(NULL_BYTE)) return null;
				const helperName = getOxcHelperName(source);
				if (!helperName) return null;
				const helpersRoot = oxcRuntimeHelpersRoot;
				if (!helpersRoot) {
					if (helperName in fallbackHelpers) return `${FALLBACK_HELPER_PREFIX}${helperName}`;
					return null;
				}
				return path.resolve(helpersRoot, `${helperName}.js`);
			},
			async load(id) {
				if (id.startsWith(FALLBACK_HELPER_PREFIX)) {
					const helperName = id.slice(FALLBACK_HELPER_PREFIX.length);
					const code = fallbackHelpers[helperName];
					if (code) return code;
					return null;
				}
				const helperName = getOxcHelperName(id);
				if (helperName) {
					const helperPath = id.startsWith(NULL_BYTE) ? path.resolve(oxcRuntimeHelpersRoot, `${helperName}.js`) : id;
					if (await fs$1.pathExists(helperPath)) {
						logger_default.warn(`[weapp-vite] 通过 Rolldown 插件解析 oxc helper:${helperName}`);
						return fs$1.readFile(helperPath, "utf8");
					}
					const fallback = fallbackHelpers[helperName];
					if (fallback) return fallback;
				}
				return null;
			}
		},
		vitePlugin: {
			name: "weapp-vite:oxc-runtime-helpers",
			enforce: "pre",
			resolveId(source) {
				if (source.startsWith(NULL_BYTE)) return null;
				if (source.includes("@oxc-project/runtime/helpers")) logger_default.warn(`[weapp-vite] resolveId 已拦截:${source}`);
				const helperName = getOxcHelperName(source);
				if (helperName) return path.resolve(oxcRuntimeHelpersRoot, `${helperName}.js`);
				return null;
			},
			async load(id) {
				if (!id.startsWith(NULL_BYTE)) return null;
				const helperName = getOxcHelperName(id);
				if (!helperName) return null;
				const helperPath = path.resolve(oxcRuntimeHelpersRoot, `${helperName}.js`);
				logger_default.warn(`[weapp-vite] 通过 Vite 插件解析 oxc helper:${helperName}`);
				return fs$1.readFile(helperPath, "utf8");
			}
		}
	};
}
//#endregion
//#region src/runtime/packageAliases.ts
const WEVU_WORKSPACE_PACKAGE_PATH = "packages-runtime/wevu";
const SHARED_WORKSPACE_PACKAGE_PATH = "@weapp-core/shared";
const PACKAGE_ALIAS_MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
const PACKAGE_ALIASES = [
	{
		find: "@weapp-core/shared/platforms",
		packageName: "@weapp-core/shared",
		distEntry: "dist/platforms/index.js",
		fallbackWorkspacePackagePath: SHARED_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "class-variance-authority",
		packageName: "class-variance-authority",
		distEntry: "dist/index.js"
	},
	{
		find: "wevu",
		packageName: "wevu",
		distEntry: "dist/index.mjs",
		devDistEntry: "dist/dev/index.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/compiler",
		packageName: "wevu",
		distEntry: "dist/compiler.mjs",
		devDistEntry: "dist/dev/compiler.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/internal-runtime",
		packageName: "wevu",
		distEntry: "dist/internal-runtime.mjs",
		devDistEntry: "dist/dev/internal-runtime.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/internal-reactivity",
		packageName: "wevu",
		distEntry: "dist/internal-reactivity.mjs",
		devDistEntry: "dist/dev/internal-reactivity.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/internal-template",
		packageName: "wevu",
		distEntry: "dist/internal-template.mjs",
		devDistEntry: "dist/dev/internal-template.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/jsx-runtime",
		packageName: "wevu",
		distEntry: "dist/jsx-runtime.mjs",
		devDistEntry: "dist/dev/jsx-runtime.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/store",
		packageName: "wevu",
		distEntry: "dist/store.mjs",
		devDistEntry: "dist/dev/store.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/api",
		packageName: "wevu",
		distEntry: "dist/api.mjs",
		devDistEntry: "dist/dev/api.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/fetch",
		packageName: "wevu",
		distEntry: "dist/fetch.mjs",
		devDistEntry: "dist/dev/fetch.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/web-apis",
		packageName: "wevu",
		distEntry: "dist/web-apis.mjs",
		devDistEntry: "dist/dev/web-apis.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "wevu/router",
		packageName: "wevu",
		distEntry: "dist/router.mjs",
		devDistEntry: "dist/dev/router.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	},
	{
		find: "vue-demi",
		packageName: "wevu",
		distEntry: "dist/vue-demi.mjs",
		devDistEntry: "dist/dev/vue-demi.mjs",
		fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
	}
];
function resolveWevuRuntimeDistEntries(target, options) {
	if (!target.devDistEntry || target.packageName !== "wevu") return [target.distEntry];
	const mode = options.wevuRuntime ?? "auto";
	if (mode === "dev" || mode === "auto" && options.isDev) return [target.devDistEntry];
	return [target.distEntry];
}
function resolveRepoRoot(fromDir) {
	let currentDir = fromDir;
	while (true) {
		if (existsSync(path.join(currentDir, "pnpm-workspace.yaml"))) return currentDir;
		const parentDir = path.dirname(currentDir);
		if (parentDir === currentDir) return;
		currentDir = parentDir;
	}
}
function resolvePackageEntry(packageName, distEntries, fallbackWorkspacePackagePath, cwd) {
	const packageInfo = safeGetPackageInfoSync(packageName, cwd ? { paths: [cwd] } : void 0);
	if (packageInfo) for (const distEntry of distEntries) {
		const resolvedEntry = path.resolve(packageInfo.rootPath, distEntry);
		if (existsSync(resolvedEntry)) return resolvedEntry;
	}
	if (!fallbackWorkspacePackagePath) return;
	const fallbackRoots = new Set([cwd, PACKAGE_ALIAS_MODULE_DIR].filter((value) => Boolean(value)));
	for (const fromDir of fallbackRoots) {
		const repoRoot = resolveRepoRoot(fromDir);
		if (!repoRoot) continue;
		for (const distEntry of distEntries) {
			const fallbackEntry = path.resolve(repoRoot, fallbackWorkspacePackagePath, distEntry);
			if (existsSync(fallbackEntry)) return fallbackEntry;
		}
	}
}
function resolveBuiltinPackageAliases(options = {}) {
	const aliases = [];
	for (const target of PACKAGE_ALIASES) {
		const { find, packageName, fallbackWorkspacePackagePath } = target;
		const resolvedEntry = resolvePackageEntry(packageName, resolveWevuRuntimeDistEntries(target, options), fallbackWorkspacePackagePath, options.cwd);
		if (!resolvedEntry) continue;
		aliases.push({
			find,
			replacement: resolvedEntry
		});
	}
	return aliases;
}
//#endregion
//#region src/runtime/config/internal/alias.ts
function normalizeAliasOptions(alias) {
	if (!alias) return [];
	if (Array.isArray(alias)) return alias.filter((entry) => {
		return Boolean(entry && typeof entry === "object" && "find" in entry && "replacement" in entry);
	});
	return Object.entries(alias).map(([find, replacement]) => {
		return {
			find,
			replacement
		};
	});
}
function createAliasManager(oxcAlias, defaultBuiltinAliases) {
	function injectBuiltinAliases(config, builtinAliases = defaultBuiltinAliases) {
		const resolve = config.resolve ?? (config.resolve = {});
		const aliasArray = normalizeAliasOptions(resolve.alias);
		if (!aliasArray.some((entry) => {
			return entry.find instanceof RegExp && entry.find.source === oxcAlias.find.source;
		})) aliasArray.unshift(oxcAlias);
		for (const builtin of builtinAliases) if (!aliasArray.some((entry) => {
			return typeof entry.find === "string" && entry.find === builtin.find;
		})) aliasArray.unshift(builtin);
		resolve.alias = aliasArray;
	}
	return { injectBuiltinAliases };
}
//#endregion
//#region src/runtime/config/enhance.ts
const enhanceKeys = [
	"wxml",
	"wxs",
	"autoImportComponents"
];
let hasLoggedEnhanceDeprecation = false;
function hasDeprecatedEnhanceUsage(enhance) {
	if (!enhance || typeof enhance !== "object") return false;
	return enhanceKeys.some((key) => hasOwn$5(enhance, key));
}
function migrateEnhanceOptions(target, options) {
	if (!target) return;
	const enhance = target.enhance;
	const userConfigured = options.userConfigured ?? {};
	if (!userConfigured.wxml && enhance?.wxml !== void 0) target.wxml = enhance.wxml;
	if (!userConfigured.wxs && enhance?.wxs !== void 0) target.wxs = enhance.wxs;
	if (!userConfigured.autoImportComponents && enhance?.autoImportComponents !== void 0) target.autoImportComponents = enhance.autoImportComponents;
	if (options.warn && !hasLoggedEnhanceDeprecation) {
		hasLoggedEnhanceDeprecation = true;
		logger_default.warn("`weapp.enhance` 已废弃,将在 weapp-vite@6 移除,请改用顶层的 `weapp.wxml`、`weapp.wxs` 与 `weapp.autoImportComponents`。");
	}
}
//#endregion
//#region src/runtime/config/web.ts
function normalizeSrcDir(root, cwd, srcRoot, config) {
	if (!config) {
		const absoluteSrc = path.resolve(cwd, srcRoot);
		return path.relative(root, absoluteSrc) || "";
	}
	if (config.srcDir) {
		if (path.isAbsolute(config.srcDir)) return path.relative(root, config.srcDir);
		return config.srcDir;
	}
	const absoluteSrc = path.resolve(cwd, srcRoot);
	return path.relative(root, absoluteSrc) || "";
}
function normalizeOutDir(root, config) {
	if (!config?.outDir) return path.resolve(root, "dist/web");
	if (path.isAbsolute(config.outDir)) return config.outDir;
	return path.resolve(root, config.outDir);
}
function resolveWeappWebConfig(options) {
	const { cwd, srcRoot, enableByCli } = options;
	const config = options.config ?? (enableByCli ? {} : void 0);
	if (!config) return;
	if (!(config.enable !== false)) return;
	const root = config.root ? path.resolve(cwd, config.root) : cwd;
	const srcDir = normalizeSrcDir(root, cwd, srcRoot, config);
	return {
		enabled: true,
		root,
		srcDir,
		outDir: normalizeOutDir(root, config),
		pluginOptions: {
			...config.pluginOptions ?? {},
			srcDir
		},
		userConfig: config.vite,
		source: config
	};
}
const miniprogramBackend = {
	descriptor: {
		id: "miniprogram",
		aliases: Object.freeze(Array.from(new Set(MINI_PROGRAM_PLATFORM_DESCRIPTORS.flatMap((descriptor) => descriptor.aliases)))),
		runtime: "miniprogram",
		capabilities: Object.freeze({
			build: true,
			dev: true,
			ide: true,
			analyze: true,
			npm: true,
			workers: true,
			lib: true
		})
	},
	driver: {
		createInlineConfig({ execution, platform, scope }) {
			const buildScope = createBuildScopeConfigFromCli(scope);
			const runsWeb = execution.get("web") !== void 0;
			const miniPlatform = platform === "web" ? void 0 : platform;
			return miniPlatform || buildScope || runsWeb ? {
				...miniPlatform || buildScope ? { weapp: {
					...miniPlatform ? { platform: miniPlatform } : {},
					...buildScope ? { buildScope } : {}
				} } : {},
				...runsWeb ? {
					build: { watch: {} },
					server: {
						port: 0,
						watch: {
							usePolling: true,
							interval: 100
						}
					}
				} : {}
			} : void 0;
		},
		mergeConfig(context, ...configs) {
			return context.merge(...configs);
		},
		async build(ctx, options) {
			return await ctx.buildService.build(options);
		},
		async dev(ctx, options) {
			return await ctx.buildService.build(options);
		},
		close(ctx) {
			ctx.watcherService.closeAll();
		},
		resolvePlatformAlias(input) {
			return resolveMiniProgramPlatform(input);
		}
	}
};
//#endregion
//#region src/backends/registry.ts
const RESERVED_COMBINED_TARGETS = /* @__PURE__ */ new Set(["all", "both"]);
function normalizeBackendKey(value) {
	return value.trim().toLowerCase();
}
function createExecution(entries, options) {
	return {
		...options,
		entries,
		get: (backendId) => entries.find((entry) => entry.descriptor.id === backendId),
		has: (capability) => entries.some((entry) => entry.descriptor.capabilities[capability]),
		select: (capability) => entries.filter((entry) => entry.descriptor.capabilities[capability])
	};
}
var PlatformBackendRegistry = class {
	backends = [];
	backendById = /* @__PURE__ */ new Map();
	backendByAlias = /* @__PURE__ */ new Map();
	register(backend) {
		const id = normalizeBackendKey(backend.descriptor.id);
		if (!id) throw new Error("平台后端 id 不能为空。");
		if (this.backendById.has(id)) throw new Error(`平台后端 id "${id}" 已注册。`);
		const aliases = [id, ...backend.descriptor.aliases.map(normalizeBackendKey)];
		const uniqueAliases = /* @__PURE__ */ new Set();
		for (const alias of aliases) {
			if (!alias) continue;
			if (RESERVED_COMBINED_TARGETS.has(alias)) throw new Error(`平台后端别名 "${alias}" 为保留目标。`);
			if (uniqueAliases.has(alias)) continue;
			const existing = this.backendByAlias.get(alias);
			if (existing) throw new Error(`平台后端别名 "${alias}" 已由 "${existing.descriptor.id}" 注册。`);
			uniqueAliases.add(alias);
		}
		this.backends.push(backend);
		this.backendById.set(id, backend);
		for (const alias of uniqueAliases) this.backendByAlias.set(alias, backend);
	}
	getExecutionOrder(capability) {
		if (!capability) return this.backends;
		return this.backends.filter((backend) => backend.descriptor.capabilities[capability]);
	}
	get(backendId) {
		return this.backendById.get(normalizeBackendKey(backendId));
	}
	resolve(input, options = { fallbackBackendId: "miniprogram" }) {
		const raw = typeof input === "string" ? input : void 0;
		const normalized = raw ? normalizeBackendKey(raw) : void 0;
		const fallbackBackend = this.backendById.get(normalizeBackendKey(options.fallbackBackendId));
		if (!fallbackBackend) throw new Error(`默认平台后端 "${options.fallbackBackendId}" 未注册。`);
		if (!raw) return createExecution([{
			descriptor: fallbackBackend.descriptor,
			driver: fallbackBackend.driver
		}], {
			kind: fallbackBackend.descriptor.runtime,
			label: "config",
			raw
		});
		const targetKey = normalized;
		if (RESERVED_COMBINED_TARGETS.has(targetKey)) return createExecution(this.backends.map((backend) => ({
			descriptor: backend.descriptor,
			driver: backend.driver,
			platform: backend.descriptor.runtime === "web" ? backend.driver.resolvePlatformAlias?.(backend.descriptor.aliases[0] ?? backend.descriptor.id) : void 0
		})), {
			kind: "all",
			label: "weapp + web",
			raw
		});
		const backend = this.backendByAlias.get(targetKey);
		if (backend) {
			const platform = backend.driver.resolvePlatformAlias?.(targetKey);
			return createExecution([{
				descriptor: backend.descriptor,
				driver: backend.driver,
				platform
			}], {
				kind: backend.descriptor.runtime,
				label: platform ?? backend.descriptor.runtime,
				raw
			});
		}
		const fallbackPlatform = options.fallbackPlatform ? fallbackBackend.driver.resolvePlatformAlias?.(options.fallbackPlatform) : void 0;
		const fallbackLabel = fallbackPlatform ?? fallbackBackend.descriptor.runtime;
		options.warn?.(`未识别的平台 "${raw}",已回退到 ${fallbackLabel}`);
		return createExecution([{
			descriptor: fallbackBackend.descriptor,
			driver: fallbackBackend.driver,
			platform: fallbackPlatform
		}], {
			kind: fallbackBackend.descriptor.runtime,
			label: fallbackLabel,
			raw
		});
	}
};
//#endregion
//#region src/backends/web.ts
const webBackend = {
	descriptor: {
		id: "web",
		aliases: Object.freeze(["web", "h5"]),
		runtime: "web",
		capabilities: Object.freeze({
			build: true,
			dev: true,
			ide: false,
			analyze: true,
			npm: false,
			workers: false,
			lib: false
		})
	},
	driver: {
		createInlineConfig({ host }) {
			if (host === void 0) return;
			return { server: { host } };
		},
		mergeConfig(context, ...configs) {
			return context.merge(...configs);
		},
		async build(ctx) {
			return await ctx.webService.build();
		},
		async dev(ctx) {
			return await ctx.webService.startDevServer();
		},
		async close(ctx) {
			await ctx.webService.close();
		},
		resolvePlatformAlias() {
			return "web";
		}
	}
};
//#endregion
//#region src/backends/index.ts
const platformBackendRegistry = new PlatformBackendRegistry();
platformBackendRegistry.register(miniprogramBackend);
platformBackendRegistry.register(webBackend);
function resolveBackendExecution(input, options = {}) {
	return platformBackendRegistry.resolve(input, {
		fallbackBackendId: "miniprogram",
		fallbackPlatform: options.fallbackMiniPlatform ?? DEFAULT_MP_PLATFORM,
		warn: options.warn
	});
}
function getBackendForCapability(execution, backendId, capability) {
	const backend = execution.get(backendId);
	return backend?.descriptor.capabilities[capability] ? backend : void 0;
}
//#endregion
//#region src/runtimeTarget.ts
const WEB_PLATFORM_ALIASES = Object.freeze(["web", "h5"]);
function isWebPlatform(input) {
	if (!input) return false;
	return resolveBackendExecution(input).kind === "web";
}
function getSupportedWeappViteTargetDescriptors() {
	const supportedBackends = platformBackendRegistry.getExecutionOrder();
	const miniprogramBackend = supportedBackends.find((backend) => backend.descriptor.runtime === "miniprogram");
	const webBackend = supportedBackends.find((backend) => backend.descriptor.runtime === "web");
	return [...MINI_PROGRAM_PLATFORM_DESCRIPTORS.map((descriptor) => ({
		platform: descriptor.id,
		runtime: "miniprogram",
		aliases: miniprogramBackend?.descriptor.aliases.includes(descriptor.id) ? [descriptor.id] : [],
		label: descriptor.id
	})), ...webBackend ? [{
		platform: "web",
		runtime: "web",
		aliases: webBackend.descriptor.aliases,
		label: "web"
	}] : []];
}
function getSupportedWeappVitePlatforms() {
	return getSupportedWeappViteTargetDescriptors().map((descriptor) => descriptor.platform);
}
function resolveWeappViteTarget(input, options = {}) {
	const execution = resolveBackendExecution(input, {
		fallbackMiniPlatform: options.fallbackMiniPlatform ?? DEFAULT_MP_PLATFORM,
		warn: options.warn
	});
	const mini = execution.get("miniprogram");
	const web = execution.get("web");
	return {
		kind: execution.kind,
		runMini: Boolean(mini),
		runWeb: Boolean(web),
		platform: mini?.platform ?? web?.platform,
		label: execution.label,
		raw: execution.raw
	};
}
//#endregion
//#region src/runtime/config/legacyEs5.ts
function importSwcCore() {
	return import("@swc/core");
}
async function loadSwcTransformModule(importer = importSwcCore) {
	try {
		const module = await importer();
		if (typeof module.transform !== "function") throw new TypeError("`@swc/core` 模块缺少 `transform` 方法。");
		return module;
	} catch (error) {
		const hint = /* @__PURE__ */ new Error("启用了已废弃的 `weapp.es5`,但项目中未安装 `@swc/core`。请优先迁移到 `build.target >= es2020`,并在开发者工具中开启“将 JS 编译成 ES5”功能;如需临时兼容,再执行 `pnpm add -D @swc/core`。");
		hint.cause = error;
		throw hint;
	}
}
function resolveSourceMapOption(outputOptions) {
	const sourcemap = outputOptions.sourcemap;
	if (sourcemap === false || sourcemap === void 0) return false;
	if (sourcemap === "inline") return "inline";
	return true;
}
async function transformWithSwc(code, chunk, outputOptions, importer) {
	const result = await (await loadSwcTransformModule(importer)).transform(code, {
		filename: chunk.fileName,
		sourceMaps: resolveSourceMapOption(outputOptions),
		module: { type: "commonjs" },
		jsc: {
			parser: {
				syntax: "ecmascript",
				jsx: true,
				dynamicImport: true
			},
			target: "es5"
		}
	});
	const map = result.map ? typeof result.map === "string" ? JSON.parse(result.map) : result.map : null;
	return {
		code: result.code,
		map
	};
}
function createLegacyEs5Plugin() {
	return {
		name: "weapp-runtime:swc-es5-transform",
		async renderChunk(code, chunk, outputOptions) {
			if (!code) return null;
			return await transformWithSwc(code, chunk, outputOptions);
		}
	};
}
//#endregion
//#region src/runtime/config/targets.ts
const ECMASCRIPT_SHORTHAND_YEAR_MAP = {
	6: 2015,
	7: 2016,
	8: 2017,
	9: 2018,
	10: 2019,
	11: 2020,
	12: 2021,
	13: 2022,
	14: 2023,
	15: 2024
};
const MIN_SUPPORTED_ECMA_YEAR = 2015;
const NON_CONCRETE_BUILD_TARGETS = /* @__PURE__ */ new Set([
	"esnext",
	"latest",
	"modules"
]);
const ECMASCRIPT_YEAR_TARGET_RE = /^es(\d{4})$/;
const ECMASCRIPT_SHORTHAND_TARGET_RE = /^es(\d{1,2})$/;
function unsupportedTargetMessage(target) {
	return `build.target "${target}" 低于 ES2015。Rolldown 仅支持 ES2015 及以上;\`weapp.es5\` / \`@swc/core\` 方案已废弃,请改为保持 \`build.target >= es2020\`,并在开发者工具中开启“将 JS 编译成 ES5”功能。`;
}
function getDefaultBuildTarget(platform) {
	return getMiniProgramDefaultBuildTarget(platform);
}
function isNonConcreteBuildTarget(target) {
	if (target === false || target === void 0) return false;
	return (Array.isArray(target) ? target : [target]).some((value) => {
		const normalized = String(value).toLowerCase();
		return NON_CONCRETE_BUILD_TARGETS.has(normalized);
	});
}
function sanitizeEcmaTarget(rawTarget, options) {
	const normalized = rawTarget.toLowerCase();
	if (normalized === "esnext" || normalized === "latest" || normalized === "modules") return rawTarget;
	if (normalized === "es3" || normalized === "es4" || normalized === "es5") {
		if (options.allowEs5) return "es2015";
		throw new Error(unsupportedTargetMessage(rawTarget));
	}
	const yearMatch = normalized.match(ECMASCRIPT_YEAR_TARGET_RE);
	if (yearMatch) {
		const year = Number(yearMatch[1]);
		if (Number.isFinite(year) && year < MIN_SUPPORTED_ECMA_YEAR) {
			if (options.allowEs5) return "es2015";
			throw new Error(unsupportedTargetMessage(rawTarget));
		}
		return `es${year}`;
	}
	const shorthandMatch = normalized.match(ECMASCRIPT_SHORTHAND_TARGET_RE);
	if (shorthandMatch) {
		const edition = Number(shorthandMatch[1]);
		if (Number.isNaN(edition)) return rawTarget;
		if (edition <= 5) {
			if (options.allowEs5) return "es2015";
			throw new Error(unsupportedTargetMessage(rawTarget));
		}
		const mappedYear = ECMASCRIPT_SHORTHAND_YEAR_MAP[edition];
		return mappedYear ? `es${mappedYear}` : rawTarget;
	}
	return rawTarget;
}
function sanitizeBuildTarget(target, options) {
	if (target === void 0) return {
		sanitized: void 0,
		hasTarget: false
	};
	if (target === false) return {
		sanitized: false,
		hasTarget: true
	};
	const sanitizedArray = (Array.isArray(target) ? [...target] : [target]).map((value) => sanitizeEcmaTarget(String(value), options));
	return {
		sanitized: Array.isArray(target) ? sanitizedArray : sanitizedArray[0],
		hasTarget: true
	};
}
//#endregion
//#region src/runtime/config/internal/loadConfig/shared.ts
const TRAILING_SLASH_RE = /\/+$/;
function pluginMatchesName(plugin, targetName) {
	if (Array.isArray(plugin)) return plugin.some((entry) => pluginMatchesName(entry, targetName));
	if (plugin && typeof plugin === "object" && "name" in plugin) {
		const pluginName = plugin.name;
		return typeof pluginName === "string" && pluginName === targetName;
	}
	return false;
}
function resolveProjectConfigPaths(options) {
	if (options.isWebRuntime) return {};
	const projectConfigFileName = getProjectConfigFileName(options.platform);
	const projectPrivateConfigFileName = getProjectPrivateConfigFileName(options.platform);
	if (options.projectConfigPath) {
		const basePath = options.projectConfigPath;
		return {
			basePath,
			privatePath: path.join(path.dirname(basePath), `project.private.config.${options.platform}.json`)
		};
	}
	if (!options.multiPlatform.enabled) return {
		basePath: projectConfigFileName,
		privatePath: projectPrivateConfigFileName
	};
	const rootDir = resolveMultiPlatformProjectConfigDir(options.multiPlatform, options.platform);
	return {
		basePath: path.join(rootDir, projectConfigFileName),
		privatePath: path.join(rootDir, projectPrivateConfigFileName)
	};
}
function formatProjectConfigPath(cwd, target) {
	if (!target) return "project.config.json";
	const resolved = path.resolve(cwd, target);
	const relative = path.relative(cwd, resolved);
	return relative && !relative.startsWith("..") ? relative : resolved;
}
function normalizeRelativeDistRoot(value) {
	const normalized = toPosixPath(value).replace(TRAILING_SLASH_RE, "");
	return normalized.startsWith("./") ? normalized.slice(2) : normalized;
}
async function loadPackageJson(cwd) {
	const packageJsonPath = path.resolve(cwd, "package.json");
	let packageJson = {};
	try {
		const content = await fs$2.readFile(packageJsonPath, "utf8");
		packageJson = JSON.parse(content);
	} catch {
		packageJson = {};
	}
	return {
		packageJson,
		packageJsonPath
	};
}
//#endregion
//#region src/runtime/config/internal/loadConfig/build.ts
function resolveCliPlatformRuntime(cliPlatform) {
	const target = resolveWeappViteTarget(cliPlatform);
	return {
		normalizedCliPlatform: target.platform ?? (target.runWeb ? target.label : void 0),
		isWebRuntime: target.runWeb && !target.runMini
	};
}
function resolveMultiPlatformProjectConfigHint(platform, projectConfigRoot = "config") {
	return `${projectConfigRoot}/${platform}/${getProjectConfigFileName(platform)}`;
}
function configureBuildAndPlugins(options) {
	const { config, oxcRolldownPlugin, oxcVitePlugin, injectBuiltinAliases, resolvedLibConfig, cliPlatform, projectConfigPath, cwd } = options;
	const buildConfig = config.build ?? (config.build = {});
	const jsFormat = config.weapp?.jsFormat ?? "cjs";
	const enableLegacyEs5 = config.weapp?.es5 === true;
	if (enableLegacyEs5) logger_default.warn("`weapp.es5` / `@swc/core` 降级方案已废弃,建议改为保持 `build.target >= es2020`,并在开发者工具中开启“将 JS 编译成 ES5”功能。");
	if (resolvedLibConfig?.enabled && resolvedLibConfig.outDir) buildConfig.outDir = resolvedLibConfig.outDir;
	if ("rollupOptions" in buildConfig) delete buildConfig.rollupOptions;
	if (enableLegacyEs5 && jsFormat !== "cjs") throw new Error("`weapp.es5` 仅支持在 `weapp.jsFormat` 为 \"cjs\" 时使用,请切换到 CommonJS 或关闭该选项。");
	const originalTarget = buildConfig.target;
	const targetInfo = sanitizeBuildTarget(originalTarget, { allowEs5: enableLegacyEs5 });
	if (enableLegacyEs5) buildConfig.target = "es2015";
	else if (targetInfo.hasTarget && targetInfo.sanitized !== void 0) {
		const defaultTarget = getDefaultBuildTarget(config.weapp?.platform);
		buildConfig.target = Boolean(defaultTarget && isNonConcreteBuildTarget(originalTarget)) ? defaultTarget : targetInfo.sanitized;
	} else if (!targetInfo.hasTarget) {
		const defaultTarget = getDefaultBuildTarget(config.weapp?.platform);
		if (defaultTarget) buildConfig.target = defaultTarget;
	}
	const rdOptions = buildConfig.rolldownOptions ?? (buildConfig.rolldownOptions = {});
	if (config.oxc !== false) {
		const oxcOptions = config.oxc ?? {};
		if (!Object.prototype.hasOwnProperty.call(oxcOptions, "tsconfig")) oxcOptions.tsconfig = false;
		if (config.esbuild !== false && config.esbuild?.jsx === "preserve" && !Object.prototype.hasOwnProperty.call(oxcOptions, "jsx")) oxcOptions.jsx = "preserve";
		config.oxc = oxcOptions;
	}
	const rdTransform = rdOptions.transform ?? {};
	if (!Object.prototype.hasOwnProperty.call(rdTransform, "tsconfig")) rdTransform.tsconfig = false;
	rdOptions.transform = rdTransform;
	if (config.weapp?.chunks?.preserveModules?.length && (rdOptions.preserveEntrySignatures === void 0 || rdOptions.preserveEntrySignatures === "exports-only")) rdOptions.preserveEntrySignatures = "allow-extension";
	else rdOptions.preserveEntrySignatures ??= "exports-only";
	if (Array.isArray(rdOptions.output)) rdOptions.output = rdOptions.output.map((output) => ({
		...output,
		format: jsFormat
	}));
	else {
		const output = rdOptions.output ?? (rdOptions.output = {});
		output.format = jsFormat;
	}
	if (resolvedLibConfig?.enabled) {
		const entryFileNames = createLibEntryFileNameResolver(resolvedLibConfig);
		if (entryFileNames) {
			if (Array.isArray(rdOptions.output)) rdOptions.output = rdOptions.output.map((output) => ({
				...output,
				entryFileNames
			}));
			else {
				const output = rdOptions.output ?? (rdOptions.output = {});
				output.entryFileNames = entryFileNames;
			}
		}
	}
	const rawPlugins = rdOptions.plugins;
	const pluginArray = rawPlugins == null ? [] : Array.isArray(rawPlugins) ? [...rawPlugins] : [rawPlugins];
	if (enableLegacyEs5) {
		const swcPluginName = "weapp-runtime:swc-es5-transform";
		if (!pluginArray.some((plugin) => pluginMatchesName(plugin, swcPluginName))) pluginArray.push(createLegacyEs5Plugin());
	}
	if (pluginArray.length > 0) rdOptions.plugins = pluginArray;
	if (oxcRolldownPlugin) {
		const rd = buildConfig.rolldownOptions ?? (buildConfig.rolldownOptions = {});
		const raw = rd.plugins;
		const arr = raw == null ? [] : Array.isArray(raw) ? [...raw] : [raw];
		rd.plugins = arr.includes(oxcRolldownPlugin) ? arr : [oxcRolldownPlugin, ...arr];
	}
	const { normalizedCliPlatform, isWebRuntime } = resolveCliPlatformRuntime(cliPlatform);
	injectBuiltinAliases(config, isWebRuntime ? "build" : void 0);
	if (oxcVitePlugin) {
		config.plugins ??= [];
		config.plugins.unshift(oxcVitePlugin);
	}
	const platform = config.weapp?.platform ?? DEFAULT_MP_PLATFORM;
	const multiPlatform = resolveMultiPlatformConfig(config.weapp?.multiPlatform);
	if (multiPlatform.enabled && !isWebRuntime && !normalizedCliPlatform) throw new Error("已开启 weapp.multiPlatform,请通过 --platform 指定目标小程序平台,例如:weapp-vite dev -p weapp");
	if (multiPlatform.enabled && !isWebRuntime && !supportsMultiPlatformTarget(multiPlatform, platform)) throw new Error(`当前平台 "${platform}" 不在 weapp.multiPlatform.targets 配置中,可选平台:${multiPlatform.targets.join(", ")}`);
	if (multiPlatform.enabled && !isWebRuntime && projectConfigPath) {
		const expectedPath = resolveMultiPlatformProjectConfigHint(platform, multiPlatform.projectConfigRoot);
		throw new Error(`已开启 weapp.multiPlatform,--project-config 不再支持,请使用 ${formatProjectConfigPath(cwd, expectedPath)}`);
	}
	return {
		buildConfig,
		platform,
		multiPlatform,
		normalizedCliPlatform,
		isWebRuntime
	};
}
//#endregion
//#region src/runtime/config/internal/tsconfigPaths.ts
const PATHS_RE = /"paths"\s*:/;
const BASE_URL_RE = /"baseUrl"\s*:/;
function withJsonExtension(filePath) {
	return path.extname(filePath) ? filePath : `${filePath}.json`;
}
function resolveReferencePath(baseDir, referencePath) {
	const resolved = path.resolve(baseDir, referencePath);
	if (path.extname(resolved)) return resolved;
	return path.join(resolved, "tsconfig.json");
}
function resolveExtendsPath(baseDir, extendsPath) {
	if (!extendsPath) return;
	if (extendsPath.startsWith(".") || path.isAbsolute(extendsPath)) return withJsonExtension(path.isAbsolute(extendsPath) ? extendsPath : path.resolve(baseDir, extendsPath));
}
function normalizePathAliasKey(key) {
	if (!key || key.includes("*") && !key.endsWith("/*")) return;
	return key.endsWith("/*") ? key.slice(0, -2) : key;
}
function normalizePathAliasTarget(target) {
	if (!target || target.includes("*") && !(target === "*" || target.endsWith("/*"))) return;
	if (target === "*") return "";
	return target.endsWith("/*") ? target.slice(0, -2) : target;
}
function resolvePathAliasBaseDir(configDir, compilerOptions) {
	const baseUrl = compilerOptions?.baseUrl;
	return typeof baseUrl === "string" && baseUrl ? path.resolve(configDir, baseUrl) : configDir;
}
function extractPathAliases(configDir, compilerOptions) {
	const aliases = [];
	const paths = compilerOptions?.paths;
	if (!paths || typeof paths !== "object") return aliases;
	const baseDir = resolvePathAliasBaseDir(configDir, compilerOptions);
	for (const [key, value] of Object.entries(paths)) {
		const find = normalizePathAliasKey(key);
		const target = Array.isArray(value) ? value.find((item) => typeof item === "string") : void 0;
		const normalizedTarget = typeof target === "string" ? normalizePathAliasTarget(target) : void 0;
		if (!find || normalizedTarget === void 0) continue;
		aliases.push({
			find,
			replacement: path.resolve(baseDir, normalizedTarget)
		});
	}
	return aliases;
}
function mergeAliases(current, incoming) {
	const merged = [...current];
	for (const entry of incoming) {
		if (merged.some((existing) => existing.find === entry.find)) continue;
		merged.push(entry);
	}
	return merged;
}
async function inspectTsconfigPathsState(filePath, visited) {
	if (visited.has(filePath)) return {
		root: false,
		references: false,
		aliases: []
	};
	visited.add(filePath);
	try {
		await fs$2.access(filePath);
	} catch {
		return {
			root: false,
			references: false,
			aliases: []
		};
	}
	let content = "";
	try {
		content = await fs$2.readFile(filePath, "utf8");
	} catch {
		return {
			root: false,
			references: false,
			aliases: []
		};
	}
	let parsed;
	try {
		parsed = parse(content);
	} catch {
		return {
			root: false,
			references: false,
			aliases: []
		};
	}
	const compilerOptions = parsed?.compilerOptions;
	let aliases = extractPathAliases(path.dirname(filePath), compilerOptions);
	let root = Boolean(PATHS_RE.test(content) || BASE_URL_RE.test(content) || compilerOptions?.paths || compilerOptions?.baseUrl);
	const baseDir = path.dirname(filePath);
	const extendsPath = typeof parsed?.extends === "string" ? resolveExtendsPath(baseDir, parsed.extends) : void 0;
	if (extendsPath) {
		const extendsState = await inspectTsconfigPathsState(extendsPath, visited);
		root = root || extendsState.root;
		aliases = mergeAliases(aliases, extendsState.aliases);
	}
	let references = false;
	const refs = Array.isArray(parsed?.references) ? parsed.references : [];
	for (const ref of refs) {
		if (!ref || typeof ref !== "object" || typeof ref.path !== "string") continue;
		const referenceState = await inspectTsconfigPathsState(resolveReferencePath(baseDir, ref.path), visited);
		if (referenceState.root || referenceState.references) references = true;
		aliases = mergeAliases(aliases, referenceState.aliases);
	}
	return {
		root,
		references,
		aliases
	};
}
async function inspectTsconfigPathsUsage(cwd) {
	const candidates = [path.resolve(cwd, "tsconfig.json"), path.resolve(cwd, "jsconfig.json")];
	let root = false;
	let references = false;
	let referenceAliases = [];
	for (const filePath of candidates) {
		const state = await inspectTsconfigPathsState(filePath, /* @__PURE__ */ new Set());
		root = root || state.root;
		references = references || state.references;
		referenceAliases = mergeAliases(referenceAliases, state.aliases);
	}
	return {
		enabled: root || references,
		root,
		references,
		aliases: referenceAliases,
		referenceAliases
	};
}
//#endregion
//#region src/runtime/config/internal/loadConfig.ts
function resolveConfigFilePath(cwd, configFile) {
	if (!configFile) return configFile;
	return path.isAbsolute(configFile) ? configFile : path.resolve(cwd, configFile);
}
function shouldReuseLoadedWeappConfig(weappConfigFilePath, loadedPath) {
	if (!weappConfigFilePath || !loadedPath) return false;
	return path.resolve(loadedPath) === path.resolve(weappConfigFilePath);
}
function collectConfigFileDependencies(cwd, ...entries) {
	const dependencySet = /* @__PURE__ */ new Set();
	const add = (filePath) => {
		if (!filePath) return;
		dependencySet.add(path.isAbsolute(filePath) ? path.normalize(filePath) : path.resolve(cwd, filePath));
	};
	for (const entry of entries) {
		if (!entry) continue;
		if (typeof entry === "string") {
			add(entry);
			continue;
		}
		add(entry.path);
		for (const dependency of entry.dependencies ?? []) add(dependency);
	}
	return Array.from(dependencySet);
}
function injectDefaultSrcAlias(config, cwd, srcRoot) {
	if (!srcRoot) return;
	const resolve = config.resolve ?? (config.resolve = {});
	const currentAlias = resolve.alias;
	const aliasArray = Array.isArray(currentAlias) ? currentAlias.filter((entry) => {
		return Boolean(entry && typeof entry === "object" && "find" in entry && "replacement" in entry);
	}) : currentAlias ? Object.entries(currentAlias).map(([find, replacement]) => ({
		find,
		replacement
	})) : [];
	if (aliasArray.some((entry) => {
		return typeof entry.find === "string" && entry.find === "@";
	})) {
		resolve.alias = aliasArray;
		return;
	}
	aliasArray.unshift({
		find: "@",
		replacement: path.resolve(cwd, srcRoot)
	});
	resolve.alias = aliasArray;
}
function injectResolvedAliases(config, aliases) {
	if (aliases.length === 0) return;
	const resolve = config.resolve ?? (config.resolve = {});
	const currentAlias = resolve.alias;
	const aliasArray = Array.isArray(currentAlias) ? currentAlias.filter((entry) => {
		return Boolean(entry && typeof entry === "object" && "find" in entry && "replacement" in entry);
	}) : currentAlias ? Object.entries(currentAlias).map(([find, replacement]) => ({
		find,
		replacement
	})) : [];
	for (const entry of aliases) {
		if (aliasArray.some((existing) => typeof existing.find === "string" && existing.find === entry.find)) continue;
		aliasArray.unshift(entry);
	}
	resolve.alias = aliasArray;
}
function mergeJsonAliasEntries(userAlias) {
	if (userAlias === false) return [];
	return getAliasEntries(userAlias);
}
function normalizeManagedPathAliasKey(key) {
	if (!key || key.includes("*") && !key.endsWith("/*")) return;
	return key.endsWith("/*") ? key.slice(0, -2) : key;
}
function normalizeManagedPathAliasTarget(target) {
	if (!target || target.includes("*") && !target.endsWith("/*")) return;
	return target.endsWith("/*") ? target.slice(0, -2) : target;
}
function collectManagedTsconfigAliases(config, cwd) {
	const weappTypeScript = config.weapp?.typescript;
	const pathSources = [weappTypeScript?.shared?.compilerOptions?.paths, weappTypeScript?.app?.compilerOptions?.paths];
	const aliasMap = /* @__PURE__ */ new Map();
	for (const pathsConfig of pathSources) {
		if (!pathsConfig || typeof pathsConfig !== "object") continue;
		for (const [key, value] of Object.entries(pathsConfig)) {
			const find = normalizeManagedPathAliasKey(key);
			const target = Array.isArray(value) ? value.find((item) => typeof item === "string") : void 0;
			const normalizedTarget = typeof target === "string" ? normalizeManagedPathAliasTarget(target) : void 0;
			if (!find || !normalizedTarget) continue;
			aliasMap.set(find, path.resolve(cwd, normalizedTarget));
		}
	}
	return Array.from(aliasMap, ([find, replacement]) => ({
		find,
		replacement
	}));
}
async function loadConfigFileWithFallback(configEnv, configFile, cwd, configLoader) {
	const suppressedWarningCodes = configLoader === "native" ? [TYPELESS_PACKAGE_JSON_WARNING_CODE] : void 0;
	try {
		return await loadViteConfigFile(configEnv, configFile, cwd, void 0, void 0, configLoader, suppressedWarningCodes, configLoader === "native" ? "silent" : void 0);
	} catch (error) {
		if (configLoader !== "native") throw error;
		const message = error instanceof Error ? error.message : String(error);
		logger_default.warn(`[prepare] 原生配置加载失败,已回退到 runner:${message}`);
		return loadConfigFileWithFallback(configEnv, configFile, cwd, "runner");
	}
}
function createLoadConfig(options) {
	const { injectBuiltinAliases, oxcRolldownPlugin, oxcVitePlugin } = options;
	return async function loadConfig(opts) {
		const { cwd, isDev, mode, outputRoot, pluginOnly = false, inlineConfig, configFile, configLoader = "runner", cliPlatform, projectConfigPath } = opts;
		const { packageJson, packageJsonPath } = await loadPackageJson(cwd);
		const resolvedConfigFile = resolveConfigFilePath(cwd, configFile);
		const weappConfigFilePath = await resolveWeappConfigFile({
			root: cwd,
			specified: resolvedConfigFile
		});
		let loaded;
		try {
			loaded = await loadConfigFileWithFallback({
				command: isDev ? "serve" : "build",
				mode
			}, resolvedConfigFile, cwd, configLoader);
		} catch (error) {
			const cjsError = createCjsConfigLoadError({
				error,
				configPath: resolvedConfigFile,
				cwd
			});
			if (cjsError) throw cjsError;
			throw error;
		}
		const loadedConfig = loaded?.config ?? {};
		let weappLoaded;
		const reuseLoadedWeappConfig = shouldReuseLoadedWeappConfig(weappConfigFilePath, loaded?.path);
		if (weappConfigFilePath) {
			if (reuseLoadedWeappConfig) weappLoaded = loaded;
			else try {
				weappLoaded = await loadConfigFileWithFallback({
					command: isDev ? "serve" : "build",
					mode
				}, weappConfigFilePath, cwd, configLoader);
			} catch (error) {
				const cjsError = createCjsConfigLoadError({
					error,
					configPath: weappConfigFilePath,
					cwd
				});
				if (cjsError) throw cjsError;
				throw error;
			}
		}
		const mergedLoadedConfig = weappLoaded?.config ? reuseLoadedWeappConfig ? loadedConfig : defu(weappLoaded.config, loadedConfig) : loadedConfig;
		const config = defu(inlineConfig, {
			mode,
			configFile: false
		}, mergedLoadedConfig, {
			build: {
				rolldownOptions: { output: {
					entryFileNames: (chunkInfo) => {
						return `${chunkInfo.name}.js`;
					},
					hashCharacters: "base36"
				} },
				assetsDir: "."
			},
			logLevel: "warn",
			weapp: getWeappViteConfig()
		});
		const chunksConfigured = Boolean(inlineConfig?.weapp?.chunks || loadedConfig.weapp?.chunks || weappLoaded?.config?.weapp?.chunks);
		const shouldWarnEnhance = [
			inlineConfig?.weapp?.enhance,
			loadedConfig.weapp?.enhance,
			weappLoaded?.config?.weapp?.enhance
		].some(hasDeprecatedEnhanceUsage);
		const userConfiguredTopLevel = {
			wxml: [
				inlineConfig?.weapp?.wxml,
				loadedConfig.weapp?.wxml,
				weappLoaded?.config?.weapp?.wxml
			].some((value) => value !== void 0),
			wxs: [
				inlineConfig?.weapp?.wxs,
				loadedConfig.weapp?.wxs,
				weappLoaded?.config?.weapp?.wxs
			].some((value) => value !== void 0),
			autoImportComponents: [
				inlineConfig?.weapp?.autoImportComponents,
				loadedConfig.weapp?.autoImportComponents,
				weappLoaded?.config?.weapp?.autoImportComponents
			].some((value) => value !== void 0)
		};
		migrateEnhanceOptions(config.weapp, {
			warn: shouldWarnEnhance,
			userConfigured: userConfiguredTopLevel
		});
		const rawLibConfig = config.weapp?.lib;
		const libEntryConfigured = hasLibEntry(rawLibConfig?.entry);
		if (rawLibConfig && !libEntryConfigured) throw new Error("已配置 weapp.lib,但未提供有效的 entry。");
		if (libEntryConfigured && rawLibConfig?.root) config.weapp = {
			...config.weapp,
			srcRoot: rawLibConfig.root
		};
		const srcRoot = config.weapp?.srcRoot ?? "";
		injectResolvedAliases(config, collectManagedTsconfigAliases(config, cwd));
		const tsconfigPathsOptions = config.weapp?.tsconfigPaths;
		const tsconfigPathsUsage = await inspectTsconfigPathsUsage(cwd);
		const tsconfigUsageAliases = tsconfigPathsUsage.aliases ?? [];
		const tsconfigReferenceAliases = tsconfigPathsUsage.referenceAliases ?? [];
		const tsconfigAliases = tsconfigUsageAliases.length > 0 ? tsconfigUsageAliases : tsconfigReferenceAliases;
		const shouldDelegateToNativeTsconfigPaths = tsconfigPathsOptions === true;
		if (!tsconfigPathsUsage.enabled) injectDefaultSrcAlias(config, cwd, srcRoot);
		else if (!shouldDelegateToNativeTsconfigPaths) {
			injectResolvedAliases(config, tsconfigAliases);
			injectDefaultSrcAlias(config, cwd, srcRoot);
		}
		const resolvedLibConfig = libEntryConfigured ? resolveWeappLibConfig({
			cwd,
			srcRoot,
			config: rawLibConfig
		}) : void 0;
		const resolvedWebConfig = resolveWeappWebConfig({
			cwd,
			srcRoot,
			config: config.weapp?.web,
			enableByCli: resolveCliPlatformRuntime(cliPlatform).isWebRuntime
		});
		const { buildConfig, platform, multiPlatform, isWebRuntime } = configureBuildAndPlugins({
			config,
			pluginOnly,
			oxcRolldownPlugin,
			oxcVitePlugin,
			injectBuiltinAliases,
			resolvedLibConfig,
			cliPlatform,
			projectConfigPath,
			cwd
		});
		let projectConfig = {};
		let projectPrivateConfig = {};
		let projectConfigPathResolved;
		let projectPrivateConfigPathResolved;
		let mpDistRoot = "";
		const isLibMode = Boolean(resolvedLibConfig?.enabled);
		if (!isWebRuntime && !isLibMode) {
			const { basePath, privatePath } = resolveProjectConfigPaths({
				platform,
				multiPlatform,
				projectConfigPath,
				isWebRuntime
			});
			projectConfig = await getProjectConfig(cwd, {
				basePath,
				privatePath
			});
			projectPrivateConfig = await getProjectPrivateConfig(cwd, { privatePath });
			mpDistRoot = resolveProjectConfigRoot(projectConfig, platform) ?? "";
			if (!mpDistRoot) {
				const displayPath = formatProjectConfigPath(cwd, basePath ?? getProjectConfigFileName(platform));
				const hint = getProjectConfigRootKeys(platform).join(" 或 ");
				throw new Error(`请在 ${displayPath} 里设置 ${hint}, 比如可以设置为 dist/`);
			}
			if (multiPlatform.enabled && !path.isAbsolute(mpDistRoot)) {
				const normalizedDistRoot = normalizeRelativeDistRoot(mpDistRoot);
				if (normalizedDistRoot === "dist") mpDistRoot = path.join("dist", platform, normalizedDistRoot);
			}
			if (outputRoot) {
				mpDistRoot = outputRoot;
				buildConfig.outDir = outputRoot;
			} else buildConfig.outDir ??= mpDistRoot;
			projectConfigPathResolved = path.resolve(cwd, basePath ?? getProjectConfigFileName(platform));
			projectPrivateConfigPathResolved = path.resolve(cwd, privatePath ?? getProjectPrivateConfigFileName(platform));
		} else if (isLibMode) {
			const libOutDir = buildConfig.outDir ?? resolvedLibConfig?.outDir ?? "dist";
			buildConfig.outDir ??= libOutDir;
			mpDistRoot = libOutDir;
		}
		if (pluginOnly && buildConfig.outDir) mpDistRoot = buildConfig.outDir;
		const aliasEntries = mergeJsonAliasEntries(config.weapp?.jsonAlias);
		config.plugins ??= [];
		if (tsconfigPathsOptions !== false) {
			if (typeof tsconfigPathsOptions === "object" && tsconfigPathsOptions !== null) config.plugins.push(tsconfigPaths(tsconfigPathsOptions));
			else if (shouldDelegateToNativeTsconfigPaths) {
				config.resolve ??= {};
				config.resolve.tsconfigPaths ??= true;
			}
		}
		const configFilePath = weappLoaded?.path ?? loaded?.path ?? resolvedConfigFile;
		const configFileDependencies = collectConfigFileDependencies(cwd, loaded, weappLoaded, resolvedConfigFile);
		const configMergeInfo = loaded?.path && weappLoaded?.path && !shouldReuseLoadedWeappConfig(weappLoaded.path, loaded.path) ? {
			merged: true,
			viteConfigPath: loaded.path,
			weappConfigPath: weappLoaded.path
		} : {
			merged: false,
			viteConfigPath: loaded?.path,
			weappConfigPath: shouldReuseLoadedWeappConfig(weappLoaded?.path, loaded?.path) ? void 0 : weappLoaded?.path
		};
		const outputExtensions = getOutputExtensions(platform);
		const relativeSrcRoot = (p) => {
			if (srcRoot) return path.relative(srcRoot, p);
			return p;
		};
		return {
			config,
			loadOptions: opts,
			aliasEntries,
			outputExtensions,
			packageJson,
			relativeSrcRoot,
			cwd,
			isDev,
			mode,
			emitDefaultAutoImportOutputs: opts.emitDefaultAutoImportOutputs ?? true,
			chunksConfigured,
			projectConfig,
			projectPrivateConfig,
			projectConfigPath: projectConfigPathResolved,
			projectPrivateConfigPath: projectPrivateConfigPathResolved,
			mpDistRoot,
			multiPlatform,
			packageJsonPath,
			platform,
			srcRoot,
			pluginOnly,
			configFilePath,
			configFileDependencies,
			currentSubPackageRoot: void 0,
			weappWeb: resolvedWebConfig,
			weappLib: resolvedLibConfig,
			configMergeInfo
		};
	};
}
//#endregion
//#region src/runtime/config/internal/merge/inline.ts
function ensureConfigService(ctx) {
	requireConfigService(ctx, "合并配置前必须初始化 configService。");
}
function stripRollupOptions(config) {
	if (config.build && "rollupOptions" in config.build) delete config.build.rollupOptions;
}
function mergeInlineConfig(config, injectBuiltinAliases, ...configs) {
	const merged = defu(config, ...configs);
	stripRollupOptions(merged);
	injectBuiltinAliases(merged);
	return merged;
}
//#endregion
//#region src/runtime/npmPlugin/builder/alipayTemplate.ts
const WXS_TAG_RE = /<\s*(?:\/\s*)?wxs\b/g;
const ELSE_ATTRIBUTE_RE = /\selse(?=[\s/>])/;
const TEMPLATE_IMPORT_TAG_RE = /<\s*(import|include)\b[^>]*>/g;
const TEMPLATE_IMPORT_SRC_RE = /\bsrc\s*=\s*(['"])([^'"]+)\1/;
const WXS_LITERAL_RE = /wxs/g;
const NON_ALIPAY_DIRECTIVE_PREFIX_PATTERN = getSupportedMiniProgramDirectivePrefixes().filter((prefix) => prefix !== "a").join("|");
const MP_DIRECTIVE_PREFIX_PATTERN = getSupportedMiniProgramDirectivePrefixes().join("|");
const NON_ALIPAY_DIRECTIVE_RE = new RegExp(`\\b(?:${NON_ALIPAY_DIRECTIVE_PREFIX_PATTERN}):(?:if|elif|else|for|for-item|for-index|key)\\b`);
const MP_DIRECTIVE_CAPTURE_RE = new RegExp(`\\b(?:${MP_DIRECTIVE_PREFIX_PATTERN}):(if|elif|else|for|for-item|for-index|key)\\b`, "g");
const ALIPAY_TEMPLATE_EXTENSION_MAP = Object.freeze({
	".wxml": ".axml",
	".wxss": ".acss",
	".wxs": ".sjs"
});
const ALIPAY_REFERENCE_EXTENSION_RE = new RegExp(Object.keys(ALIPAY_TEMPLATE_EXTENSION_MAP).map((ext) => ext.replace(".", "\\.")).join("|"), "g");
function containsIncompatibleAlipayTemplateSyntax(source) {
	return NON_ALIPAY_DIRECTIVE_RE.test(source) || WXS_TAG_RE.test(source) || ELSE_ATTRIBUTE_RE.test(source);
}
function rewriteTemplateImportExtensionsForAlipay(source) {
	return source.replace(TEMPLATE_IMPORT_TAG_RE, (tag) => {
		return tag.replace(TEMPLATE_IMPORT_SRC_RE, (attr, quote, value) => {
			if (!shouldNormalizeTemplateImportSource(value)) return attr;
			let nextValue = changeFileExtension(value, ".axml");
			if (value.startsWith("./") && !nextValue.startsWith("./") && !nextValue.startsWith("../") && !nextValue.startsWith("/")) nextValue = `./${nextValue}`;
			return `src=${quote}${nextValue}${quote}`;
		});
	});
}
function rewriteAlipayReferenceExtensions(source) {
	return source.replace(ALIPAY_REFERENCE_EXTENSION_RE, (ext) => {
		return ALIPAY_TEMPLATE_EXTENSION_MAP[ext] ?? ext;
	});
}
function rewriteAlipayTemplateSyntax(source) {
	return source.replace(MP_DIRECTIVE_CAPTURE_RE, (_, directive) => `a:${directive}`).replace(WXS_TAG_RE, (match) => match.replace(WXS_LITERAL_RE, "import-sjs")).replace(ELSE_ATTRIBUTE_RE, " a:else");
}
function transformTemplateForAlipay(source) {
	return rewriteAlipayReferenceExtensions(normalizeImportSjsAttributes(rewriteTemplateImportExtensionsForAlipay(rewriteAlipayTemplateSyntax(source))));
}
//#endregion
//#region src/runtime/npmPlugin/builder/jsModule/helpers.ts
const ESM_SYNTAX_RE$1 = /\bimport(?=[\s{'"*])|\bexport(?=[\s{*])/;
function hasEsmSyntax(source) {
	return ESM_SYNTAX_RE$1.test(source);
}
function createExportAllStatements(source, scope) {
	const requireId = scope.generateUidIdentifier("reExported");
	const exportKeyId = scope.generateUidIdentifier("exportKey");
	return [t.variableDeclaration("const", [t.variableDeclarator(requireId, t.callExpression(t.identifier("require"), [source]))]), t.expressionStatement(t.callExpression(t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [requireId]), t.identifier("forEach")), [t.arrowFunctionExpression([exportKeyId], t.blockStatement([t.ifStatement(t.logicalExpression("||", t.binaryExpression("===", exportKeyId, t.stringLiteral("default")), t.binaryExpression("===", exportKeyId, t.stringLiteral("__esModule"))), t.returnStatement()), t.expressionStatement(t.assignmentExpression("=", t.memberExpression(t.identifier("exports"), exportKeyId, true), t.memberExpression(requireId, exportKeyId, true)))]))]))];
}
//#endregion
//#region src/runtime/npmPlugin/builder/shared.ts
async function collectFiles(root) {
	const files = [];
	let pendingDirs = [root];
	while (pendingDirs.length > 0) {
		const currentDirs = pendingDirs;
		pendingDirs = [];
		const batches = await Promise.all(currentDirs.map(async (current) => {
			const dirs = [];
			const currentFiles = [];
			const entries = await fs$1.readdir(current, { withFileTypes: true });
			for (const entry of entries) {
				const filePath = path.resolve(current, entry.name);
				if (entry.isDirectory()) dirs.push(filePath);
				else if (entry.isFile()) currentFiles.push(filePath);
			}
			return {
				dirs,
				files: currentFiles
			};
		}));
		for (const batch of batches) {
			files.push(...batch.files);
			pendingDirs.push(...batch.dirs);
		}
	}
	return files;
}
function resolveExportPath(entry) {
	if (!entry) return;
	if (typeof entry === "string") return entry;
	return resolveExportPath(entry.import) ?? resolveExportPath(entry.module) ?? resolveExportPath(entry.default) ?? resolveExportPath(entry.browser) ?? resolveExportPath(entry.development) ?? resolveExportPath(entry.production);
}
async function resolvePreferredPackageEntry(rootPath, pkg) {
	const exportsField = pkg.exports;
	const candidates = [
		resolveExportPath(typeof exportsField === "string" ? exportsField : exportsField && !Array.isArray(exportsField) && "." in exportsField ? exportsField["."] : void 0),
		typeof pkg.module === "string" ? pkg.module : void 0,
		typeof pkg["jsnext:main"] === "string" ? pkg["jsnext:main"] : void 0,
		typeof pkg.main === "string" ? pkg.main : void 0
	].filter((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
	for (const candidate of candidates) {
		const resolved = path.resolve(rootPath, candidate);
		if (await fs$1.pathExists(resolved)) return resolved;
	}
}
//#endregion
//#region src/runtime/npmPlugin/builder/jsModule.ts
function createExportsMember(name) {
	return t.memberExpression(t.identifier("exports"), t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name), !t.isValidIdentifier(name));
}
function createExportsAssignment(name, value) {
	return t.expressionStatement(t.assignmentExpression("=", createExportsMember(name), value));
}
function createRequireMemberExpression(base, name) {
	return t.memberExpression(base, t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name), !t.isValidIdentifier(name));
}
function getModuleExportName(name) {
	return t.isIdentifier(name) ? name.name : name.value;
}
function getExportedDeclarationNames(declaration) {
	if (t.isFunctionDeclaration(declaration) || t.isClassDeclaration(declaration)) return declaration.id ? [declaration.id.name] : [];
	if (t.isVariableDeclaration(declaration)) return declaration.declarations.flatMap((item) => Object.keys(t.getBindingIdentifiers(item.id)));
	return Object.keys(t.getBindingIdentifiers(declaration));
}
function createEsModuleMarker() {
	return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("defineProperty")), [
		t.identifier("exports"),
		t.stringLiteral("__esModule"),
		t.objectExpression([t.objectProperty(t.identifier("value"), t.booleanLiteral(true))])
	]));
}
async function transformJsModuleToCjs(source, options) {
	if (!hasEsmSyntax(source)) return source;
	try {
		const ast = parseJsLike(source);
		let transformed = false;
		let hasConvertedExport = false;
		const exportAssignments = [];
		traverse(ast, {
			ImportDeclaration(path) {
				const sourceLiteral = t.stringLiteral(path.node.source.value);
				const specifiers = path.node.specifiers ?? [];
				if (specifiers.length === 0) {
					path.replaceWith(t.expressionStatement(t.callExpression(t.identifier("require"), [sourceLiteral])));
					transformed = true;
					return;
				}
				const requireId = path.scope.generateUidIdentifier("imported");
				const statements = [t.variableDeclaration("const", [t.variableDeclarator(requireId, t.callExpression(t.identifier("require"), [sourceLiteral]))])];
				for (const specifier of specifiers) {
					if (t.isImportDefaultSpecifier(specifier)) {
						statements.push(t.variableDeclaration("const", [t.variableDeclarator(specifier.local, t.conditionalExpression(t.binaryExpression("!==", createRequireMemberExpression(requireId, "default"), t.identifier("undefined")), createRequireMemberExpression(requireId, "default"), requireId))]));
						continue;
					}
					if (t.isImportNamespaceSpecifier(specifier)) {
						statements.push(t.variableDeclaration("const", [t.variableDeclarator(specifier.local, requireId)]));
						continue;
					}
					const importedName = t.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value;
					statements.push(t.variableDeclaration("const", [t.variableDeclarator(specifier.local, createRequireMemberExpression(requireId, importedName))]));
				}
				path.replaceWithMultiple(statements);
				transformed = true;
			},
			ExportDefaultDeclaration(path) {
				const declaration = path.node.declaration;
				hasConvertedExport = true;
				if (t.isFunctionDeclaration(declaration) || t.isClassDeclaration(declaration)) {
					const exportId = declaration.id ?? path.scope.generateUidIdentifier("defaultExport");
					if (!declaration.id) declaration.id = exportId;
					path.replaceWith(declaration);
					exportAssignments.push(createExportsAssignment("default", exportId));
					transformed = true;
					return;
				}
				const targetId = path.scope.generateUidIdentifier("defaultExport");
				path.replaceWith(t.variableDeclaration("const", [t.variableDeclarator(targetId, declaration)]));
				exportAssignments.push(createExportsAssignment("default", targetId));
				transformed = true;
			},
			ExportNamedDeclaration(path) {
				const declaration = path.node.declaration;
				if (declaration) {
					hasConvertedExport = true;
					path.replaceWith(declaration);
					const names = getExportedDeclarationNames(declaration);
					for (const name of names) exportAssignments.push(createExportsAssignment(name, t.identifier(name)));
					transformed = true;
					return;
				}
				const specifiers = path.node.specifiers ?? [];
				if (specifiers.length === 0) {
					path.remove();
					transformed = true;
					return;
				}
				if (path.node.source) {
					hasConvertedExport = true;
					const requireId = path.scope.generateUidIdentifier("reExported");
					const exportSpecifiers = specifiers.filter(t.isExportSpecifier);
					const statements = [t.variableDeclaration("const", [t.variableDeclarator(requireId, t.callExpression(t.identifier("require"), [t.stringLiteral(path.node.source.value)]))])];
					for (const specifier of exportSpecifiers) {
						const localName = specifier.local.name;
						const exportedName = getModuleExportName(specifier.exported);
						statements.push(createExportsAssignment(exportedName, createRequireMemberExpression(requireId, localName)));
					}
					path.replaceWithMultiple(statements);
					transformed = true;
					return;
				}
				const exportSpecifiers = specifiers.filter(t.isExportSpecifier);
				if (exportSpecifiers.length > 0) hasConvertedExport = true;
				const statements = [];
				for (const specifier of exportSpecifiers) {
					const localName = specifier.local.name;
					const exportedName = getModuleExportName(specifier.exported);
					statements.push(createExportsAssignment(exportedName, t.identifier(localName)));
				}
				path.replaceWithMultiple(statements);
				transformed = true;
			},
			ExportAllDeclaration(path) {
				hasConvertedExport = true;
				path.replaceWithMultiple(createExportAllStatements(t.stringLiteral(path.node.source.value), path.scope));
				transformed = true;
			}
		});
		if (exportAssignments.length > 0) {
			ast.program.body.push(...exportAssignments);
			transformed = true;
		}
		if (!transformed) return source;
		if (options?.markEsModule && hasConvertedExport) ast.program.body.unshift(createEsModuleMarker());
		return generate$1(ast).code;
	} catch {
		return source;
	}
}
async function normalizeMiniprogramPackageJsModules(pkgRoot, options) {
	if (!await fs$1.pathExists(pkgRoot)) return;
	const files = await collectFiles(pkgRoot);
	await Promise.all(files.map(async (filePath) => {
		if (path.extname(filePath) !== ".js") return;
		let source = "";
		try {
			source = await fs$1.readFile(filePath, "utf8");
		} catch {
			return;
		}
		const nextSource = await transformJsModuleToCjs(source, options);
		if (nextSource !== source) await fs$1.writeFile(filePath, nextSource);
	}));
}
//#endregion
//#region src/runtime/npmPlugin/builder/alipay.ts
const WX_TEMPLATE_REFERENCE_RE = /\.wxml\b|\.wxss\b|\.wxs\b/;
const ESM_SYNTAX_RE = /\bimport\s|\bexport\s/;
const NULLISH_COALESCING_RE = /\?\?/;
const ALIPAY_TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
	".js",
	".json",
	".axml",
	".acss",
	".sjs",
	".wxml",
	".wxss",
	".wxs"
]);
async function shouldRebuildCachedAlipayMiniprogramPackage(pkgRoot, outDir, sourceRoot, alipayNpmDistDirName = "miniprogram_npm") {
	if (!await fs$1.pathExists(pkgRoot)) return true;
	if (sourceRoot && alipayNpmDistDirName === "node_modules") {
		const sourceEsRoot = path.resolve(sourceRoot, "es");
		const targetEsRoot = path.resolve(pkgRoot, "es");
		if (await fs$1.pathExists(sourceEsRoot) && !await fs$1.pathExists(targetEsRoot)) return true;
	}
	const files = await collectFiles(pkgRoot);
	const textFiles = [];
	for (const filePath of files) {
		const ext = path.extname(filePath);
		if (ext === ".wxml" || ext === ".wxss" || ext === ".wxs") return true;
		if (!ALIPAY_TEXT_FILE_EXTENSIONS.has(ext)) continue;
		textFiles.push(filePath);
	}
	if ((await Promise.all(textFiles.map(async (filePath) => {
		const ext = path.extname(filePath);
		let source = "";
		try {
			source = await fs$1.readFile(filePath, "utf8");
		} catch {
			return false;
		}
		if (WX_TEMPLATE_REFERENCE_RE.test(source)) return true;
		if (ext === ".js" && (ESM_SYNTAX_RE.test(source) || NULLISH_COALESCING_RE.test(source))) return true;
		if ((ext === ".axml" || ext === ".wxml") && containsIncompatibleAlipayTemplateSyntax(source)) return true;
		return false;
	}))).some(Boolean)) return true;
	const nestedRoot = path.resolve(pkgRoot, "miniprogram_npm");
	if (!await fs$1.pathExists(nestedRoot)) return false;
	const entries = await fs$1.readdir(nestedRoot);
	if ((await Promise.all(entries.map(async (name) => {
		const target = path.resolve(outDir, name);
		return !await fs$1.pathExists(target);
	}))).some(Boolean)) return true;
	return false;
}
async function normalizeMiniprogramPackageForAlipay(pkgRoot) {
	if (!await fs$1.pathExists(pkgRoot)) return;
	const renameTasks = (await collectFiles(pkgRoot)).map((filePath) => {
		const ext = path.extname(filePath);
		const nextExt = ALIPAY_TEMPLATE_EXTENSION_MAP[ext];
		if (!nextExt) return null;
		return {
			from: filePath,
			to: `${filePath.slice(0, -ext.length)}${nextExt}`
		};
	}).filter((item) => item !== null);
	await Promise.all(renameTasks.map((task) => {
		return fs$1.move(task.from, task.to, { overwrite: true });
	}));
	await normalizeMiniprogramPackageJsModules(pkgRoot, { markEsModule: true });
	const normalizedFiles = await collectFiles(pkgRoot);
	await Promise.all(normalizedFiles.map(async (filePath) => {
		const ext = path.extname(filePath);
		if (!ALIPAY_TEXT_FILE_EXTENSIONS.has(ext)) return;
		const source = await fs$1.readFile(filePath, "utf8");
		let nextSource = source;
		if (ext === ".axml" || ext === ".wxml") nextSource = transformTemplateForAlipay(nextSource);
		nextSource = rewriteAlipayReferenceExtensions(nextSource);
		if (nextSource !== source) await fs$1.writeFile(filePath, nextSource);
	}));
}
async function hoistNestedMiniprogramDependenciesForAlipay(pkgRoot, outDir) {
	const nestedRoot = path.resolve(pkgRoot, "miniprogram_npm");
	if (!await fs$1.pathExists(nestedRoot)) return;
	const entries = await fs$1.readdir(nestedRoot);
	await Promise.all(entries.map(async (name) => {
		const source = path.resolve(nestedRoot, name);
		const target = path.resolve(outDir, name);
		if (await fs$1.pathExists(target)) return;
		await fs$1.copy(source, target, {
			overwrite: false,
			errorOnExist: false
		});
		await normalizeMiniprogramPackageForAlipay(target);
	}));
}
async function copyEsModuleDirectoryForAlipay(sourceRoot, targetRoot) {
	const sourceDir = path.resolve(sourceRoot, "es");
	if (!await fs$1.pathExists(sourceDir)) return false;
	await fs$1.copy(sourceDir, path.resolve(targetRoot, "es"), { overwrite: true });
	return true;
}
//#endregion
//#region src/runtime/npmPlugin/builder/packageFiles.ts
function normalizePattern$1(pattern) {
	return pattern.replaceAll("\\", "/");
}
function createNpmPackageFileMatcher(config) {
	const include = config?.include?.length ? picomatch(config.include.map(normalizePattern$1), { dot: true }) : () => true;
	const exclude = config?.exclude?.length ? picomatch(config.exclude.map(normalizePattern$1), { dot: true }) : () => false;
	return (relativePath) => {
		const normalizedPath = normalizePattern$1(relativePath);
		return include(normalizedPath) && !exclude(normalizedPath);
	};
}
function createNpmPackageCopyFilter(sourceRoot, config) {
	if (!config?.include?.length && !config?.exclude?.length) return;
	const matches = createNpmPackageFileMatcher(config);
	return async (sourcePath) => {
		const relativePath = path.relative(sourceRoot, sourcePath);
		if (!relativePath) return true;
		return (await fs$1.stat(sourcePath)).isDirectory() || matches(relativePath);
	};
}
//#endregion
//#region src/runtime/npmPlugin/builder/packageBuilder.ts
function toPluginArray(plugins) {
	const queue = [];
	const result = [];
	if (plugins) queue.push(plugins);
	while (queue.length > 0) {
		const current = queue.shift();
		if (!current) continue;
		if (Array.isArray(current)) {
			queue.unshift(...current);
			continue;
		}
		result.push(current);
	}
	return result;
}
function resolveDefaultNpmBuildTsconfig(cwd) {
	const appTsconfig = path.resolve(cwd, ".weapp-vite/tsconfig.app.json");
	if (existsSync(appTsconfig)) return appTsconfig;
	const rootTsconfig = path.resolve(cwd, "tsconfig.json");
	if (existsSync(rootTsconfig)) return rootTsconfig;
	return false;
}
function createPackageBuilder(ctx, oxcVitePlugin) {
	const npmLogger = typeof logger_default.withTag === "function" ? logger_default.withTag("npm") : logger_default;
	const packageBuildInFlight = /* @__PURE__ */ new Map();
	function isMiniprogramPackage(pkg) {
		return Reflect.has(pkg, "miniprogram") && typeof pkg.miniprogram === "string";
	}
	async function shouldSkipBuild(outDir, isOutdated) {
		return !isOutdated && await fs$1.pathExists(outDir);
	}
	function resolveBuildOutDir(options, fallbackOutDir) {
		const rawOutDir = options?.build?.outDir;
		if (typeof rawOutDir !== "string" || !rawOutDir.trim()) return fallbackOutDir;
		if (path.isAbsolute(rawOutDir)) return rawOutDir;
		const root = typeof options?.root === "string" && options.root ? options.root : ctx.configService?.cwd ?? process.cwd();
		return path.resolve(root, rawOutDir);
	}
	function resolvePackageBuildTarget({ entry, name, options, outDir }) {
		const importMetaDefineEntries = ctx.configService?.importMetaDefineEntries ?? {};
		const cwd = ctx.configService?.cwd ?? process.cwd();
		const defaultTsconfig = resolveDefaultNpmBuildTsconfig(cwd);
		const mergedOptions = defu(options, {
			configFile: false,
			publicDir: false,
			logLevel: "silent",
			root: cwd,
			define: {
				...importMetaDefineEntries,
				"process.env.NODE_ENV": JSON.stringify("production")
			},
			oxc: { tsconfig: false },
			plugins: [],
			build: {
				lib: {
					entry,
					formats: ["cjs"],
					fileName: (_format, entryName) => `${entryName}.js`
				},
				outDir,
				emptyOutDir: true,
				sourcemap: false,
				minify: false,
				target: "es6",
				rolldownOptions: {
					external: [],
					tsconfig: defaultTsconfig,
					transform: { tsconfig: false },
					output: { exports: "named" }
				}
			}
		});
		const resolvedOptions = ctx.configService?.weappViteConfig?.npm?.buildOptions?.(mergedOptions, {
			name,
			entry
		});
		let finalOptions;
		if (resolvedOptions === void 0) finalOptions = mergedOptions;
		else if (isObject(resolvedOptions)) finalOptions = resolvedOptions;
		return {
			outDir: resolveBuildOutDir(finalOptions ?? mergedOptions, outDir),
			options: finalOptions
		};
	}
	async function runResolvedBundleBuild(finalOptions) {
		if (!finalOptions) return;
		if (oxcVitePlugin) {
			const existing = toPluginArray(finalOptions.plugins);
			finalOptions.plugins = existing.includes(oxcVitePlugin) ? existing : [oxcVitePlugin, ...existing];
		}
		await build(finalOptions);
	}
	async function bundleBuild({ entry, name, options, outDir }) {
		await runResolvedBundleBuild(resolvePackageBuildTarget({
			entry,
			name,
			options,
			outDir
		}).options);
	}
	async function copyBuild({ from, to, name }) {
		await fs$1.remove(to);
		await fs$1.copy(from, to, {
			filter: createNpmPackageCopyFilter(from, ctx.configService?.weappViteConfig?.npm?.packageFiles?.[name]),
			overwrite: true
		});
	}
	let buildPackage;
	async function runBuildPackage({ dep, outDir, options, isDependenciesCacheOutdate }) {
		const packageInfo = await getPackageInfo(dep);
		if (!packageInfo || !ctx.configService) return;
		const { packageJson: targetJson, rootPath } = packageInfo;
		const dependencies = targetJson.dependencies ?? {};
		const keys = Object.keys(dependencies);
		if (isMiniprogramPackage(targetJson)) {
			const sourceDir = path.resolve(rootPath, targetJson.miniprogram);
			const resolvedTarget = resolvePackageBuildTarget({
				entry: { index: sourceDir },
				name: dep,
				options,
				outDir: path.resolve(outDir, dep)
			});
			const destOutDir = resolvedTarget.outDir;
			if (!resolvedTarget.options) {
				npmLogger.info(`[npm] 依赖 \`${dep}\` 被 npm.buildOptions 跳过处理!`);
				return;
			}
			if (await shouldSkipBuild(destOutDir, isDependenciesCacheOutdate)) {
				await normalizeMiniprogramPackageJsModules(destOutDir, { markEsModule: true });
				const platformNpmDistDirName = getPlatformNpmDistDirName(ctx.configService.platform, { alipayNpmMode: ctx.configService.weappViteConfig?.npm?.alipayNpmMode });
				if (!(shouldRebuildCachedMiniprogramPackage(ctx.configService.platform) ? await shouldRebuildCachedAlipayMiniprogramPackage(destOutDir, outDir, rootPath, platformNpmDistDirName) : false)) {
					npmLogger.info(`[npm] 依赖 \`${dep}\` 未发生变化,跳过处理!`);
					return;
				}
			}
			await copyBuild({
				from: sourceDir,
				to: destOutDir,
				name: dep
			});
			await normalizeMiniprogramPackageJsModules(destOutDir, { markEsModule: true });
			if (shouldNormalizeMiniprogramPackage(ctx.configService.platform)) {
				const platformNpmDistDirName = getPlatformNpmDistDirName(ctx.configService.platform, { alipayNpmMode: ctx.configService.weappViteConfig?.npm?.alipayNpmMode });
				if (shouldCopyEsModuleDirectory(ctx.configService.platform) && platformNpmDistDirName === "node_modules") await copyEsModuleDirectoryForAlipay(rootPath, destOutDir);
				await normalizeMiniprogramPackageForAlipay(destOutDir);
				if (shouldHoistNestedMiniprogramDependencies(ctx.configService.platform)) await hoistNestedMiniprogramDependenciesForAlipay(destOutDir, outDir);
			}
			if (keys.length > 0) await Promise.all(keys.map((x) => {
				return buildPackage({
					dep: x,
					outDir,
					options,
					isDependenciesCacheOutdate
				});
			}));
		} else {
			const index = await resolvePreferredPackageEntry(rootPath, targetJson) ?? resolveModule(dep);
			if (!index) {
				npmLogger.warn(`[npm] 无法解析模块 \`${dep}\`,跳过处理!`);
				return;
			}
			const resolvedTarget = resolvePackageBuildTarget({
				entry: { index },
				name: dep,
				options,
				outDir: path.resolve(outDir, dep)
			});
			const destOutDir = resolvedTarget.outDir;
			if (!resolvedTarget.options) {
				npmLogger.info(`[npm] 依赖 \`${dep}\` 被 npm.buildOptions 跳过处理!`);
				return;
			}
			if (!isDependenciesCacheOutdate && await fs$1.pathExists(destOutDir)) {
				const destEntry = path.resolve(destOutDir, "index.js");
				if (await fs$1.pathExists(destEntry)) {
					const [srcStat, destStat] = await Promise.all([fs$1.stat(index), fs$1.stat(destEntry)]);
					if (srcStat.mtimeMs <= destStat.mtimeMs) {
						npmLogger.info(`[npm] 依赖 \`${dep}\` 未发生变化,跳过处理!`);
						return;
					}
				}
			}
			await runResolvedBundleBuild(resolvedTarget.options);
			if (keys.length > 0) await Promise.all(keys.filter((x) => isBuiltin(x)).map((x) => {
				return buildPackage({
					dep: `${x}/`,
					outDir,
					options,
					isDependenciesCacheOutdate
				});
			}));
		}
		npmLogger.success(`[npm] \`${dep}\` 依赖处理完成!`);
	}
	buildPackage = async ({ dep, outDir, options, isDependenciesCacheOutdate }) => {
		const taskKey = `${path.resolve(outDir)}::${dep}`;
		const pending = packageBuildInFlight.get(taskKey);
		if (pending) return pending;
		const task = runBuildPackage({
			dep,
			outDir,
			options,
			isDependenciesCacheOutdate
		}).finally(() => {
			if (packageBuildInFlight.get(taskKey) === task) packageBuildInFlight.delete(taskKey);
		});
		packageBuildInFlight.set(taskKey, task);
		return task;
	};
	return {
		isMiniprogramPackage,
		shouldSkipBuild,
		bundleBuild,
		copyBuild,
		buildPackage
	};
}
//#endregion
//#region src/runtime/npmPlugin/cache.ts
const CACHE_KEY_RE = /[\\/]/;
function serializeDependencyScope(scope) {
	if (scope === false) return false;
	if (!Array.isArray(scope)) return;
	return scope.map((item) => {
		return typeof item === "string" ? item : item.toString();
	});
}
function resolveMainPackageDependencyScope(ctx) {
	return requireConfigService(ctx, "读取主包 npm 依赖范围前必须初始化 configService。").weappViteConfig?.npm?.mainPackage?.dependencies;
}
function resolvePluginPackageDependencyScope(ctx) {
	return requireConfigService(ctx, "读取插件包 npm 依赖范围前必须初始化 configService。").weappViteConfig?.npm?.pluginPackage?.dependencies;
}
function createDependenciesCache(ctx) {
	function getDependenciesCacheFilePath(key = "/") {
		const configService = requireConfigService(ctx, "生成 npm 缓存路径前必须初始化 configService。");
		return path.resolve(configService.cwd, `node_modules/weapp-vite/.cache/${key.replace(CACHE_KEY_RE, "-")}.json`);
	}
	function resolveDependencyScope(root) {
		if (root === "__all__") return;
		if (root === "__plugin__") return resolvePluginPackageDependencyScope(ctx);
		if (root && root !== "/") return ctx.scanService?.subPackageMap.get(root)?.subPackage.dependencies;
		return resolveMainPackageDependencyScope(ctx);
	}
	function dependenciesCacheHash(root) {
		const configService = requireConfigService(ctx, "读取依赖缓存哈希前必须初始化 configService。");
		return objectHash({
			dependencies: configService.packageJson.dependencies ?? {},
			packageFiles: configService.weappViteConfig?.npm?.packageFiles ?? {},
			scope: serializeDependencyScope(resolveDependencyScope(root))
		});
	}
	async function writeDependenciesCache(root) {
		if (requireConfigService(ctx, "写入 npm 缓存前必须初始化 configService。").weappViteConfig?.npm?.cache) await fs$1.outputJSON(getDependenciesCacheFilePath(root), { hash: dependenciesCacheHash(root) });
	}
	async function readDependenciesCache(root) {
		const cachePath = getDependenciesCacheFilePath(root);
		if (await fs$1.pathExists(cachePath)) return await fs$1.readJson(cachePath, { throws: false });
	}
	async function checkDependenciesCacheOutdate(root) {
		if (ctx.configService?.weappViteConfig?.npm?.cache) {
			const json = await readDependenciesCache(root);
			if (isObject(json)) return dependenciesCacheHash(root) !== json.hash;
			return true;
		}
		return true;
	}
	return {
		getDependenciesCacheFilePath,
		dependenciesCacheHash: () => dependenciesCacheHash(),
		writeDependenciesCache,
		readDependenciesCache,
		checkDependenciesCacheOutdate
	};
}
//#endregion
//#region src/runtime/npmPlugin/relations.ts
const TRAILING_SLASHES_RE$1 = /\/+$/;
const EMPTY_VALUE_RE = /^$/;
function normalizeRelativeDir(value) {
	const normalized = toPosixPath(value).replace(TRAILING_SLASHES_RE$1, "");
	return (normalized.startsWith("./") ? normalized.slice(2) : normalized).replace(EMPTY_VALUE_RE, ".");
}
function resolvePlatformProjectRoot(configService) {
	if (!configService) return "dist";
	return normalizeRelativeDir(resolveProjectConfigRoot(configService.projectConfig, configService.platform) ?? "dist");
}
function resolveDefaultNpmDistDir(configService) {
	if (!configService) return ".";
	if (typeof configService.outDir === "string" && configService.outDir) {
		if (path.isAbsolute(configService.outDir)) {
			const relativeOutDir = path.relative(configService.cwd, configService.outDir);
			if (relativeOutDir && !relativeOutDir.startsWith("..") && !path.isAbsolute(relativeOutDir)) return normalizeRelativeDir(relativeOutDir);
			return configService.outDir;
		}
		return normalizeRelativeDir(configService.outDir);
	}
	if (shouldUseProjectRootNpmDir(configService.platform)) return resolvePlatformProjectRoot(configService);
	return ".";
}
function getPackNpmRelationList(ctx) {
	const configService = requireConfigService(ctx, "解析 npm 关联列表前必须初始化 configService。");
	const isMultiPlatformEnabled = configService.multiPlatform.enabled;
	const hasManualRelations = Boolean(configService.projectConfig.setting?.packNpmManually && Array.isArray(configService.projectConfig.setting.packNpmRelationList));
	const packNpmRelationList = hasManualRelations ? configService.projectConfig.setting.packNpmRelationList : [{
		miniprogramNpmDistDir: ".",
		packageJsonPath: "./package.json"
	}];
	if (configService.pluginOnly) {
		const pluginOutputRoot = configService.absolutePluginOutputRoot ?? configService.outDir;
		const [mainRelation] = packNpmRelationList;
		if (!mainRelation) return [];
		return [{
			...mainRelation,
			miniprogramNpmDistDir: pluginOutputRoot
		}];
	}
	if (!isMultiPlatformEnabled) {
		if (!hasManualRelations) return [{
			...packNpmRelationList[0],
			miniprogramNpmDistDir: shouldUseProjectRootNpmDir(configService.platform) ? resolvePlatformProjectRoot(configService) : resolveDefaultNpmDistDir(configService)
		}];
		return packNpmRelationList;
	}
	if (!hasManualRelations && shouldUseProjectRootNpmDir(configService.platform)) return [{
		...packNpmRelationList[0],
		miniprogramNpmDistDir: path.join("dist", configService.platform, resolvePlatformProjectRoot(configService))
	}];
	return packNpmRelationList.map((entry) => {
		const rawDir = entry.miniprogramNpmDistDir;
		if (!rawDir || path.isAbsolute(rawDir)) return entry;
		const trimmed = normalizeRelativeDir(rawDir);
		const shouldRewriteRootDir = shouldUseProjectRootNpmDir(configService.platform);
		if (!(trimmed === "dist" || shouldRewriteRootDir && trimmed === ".")) return entry;
		return {
			...entry,
			miniprogramNpmDistDir: path.join("dist", configService.platform, trimmed)
		};
	});
}
//#endregion
//#region src/runtime/npmPlugin/service/paths.ts
const LEADING_SLASHES_RE$1 = /^\/+/;
const WINDOWS_PATH_RE = /\\|^[A-Z]:[\\/]/i;
const TRAILING_SLASHES_RE = /\/+$/;
function matchDependencyPath(patterns, value) {
	const dependencyId = resolveNpmDependencyId(toPosixPath(value).replace(LEADING_SLASHES_RE$1, ""));
	return patterns.some((pattern) => {
		if (typeof pattern === "string") return dependencyId === pattern || value === pattern || value.startsWith(`${pattern}/`);
		pattern.lastIndex = 0;
		if (pattern.test(dependencyId)) return true;
		pattern.lastIndex = 0;
		return pattern.test(value);
	});
}
function resolveCopyFilterRelativePath(sourceRoot, sourcePath) {
	const normalizedRoot = normalizePath$1(sourceRoot).replace(TRAILING_SLASHES_RE, "");
	const normalizedPath = normalizePath$1(sourcePath);
	if (normalizedPath === normalizedRoot) return "";
	if (normalizedPath.startsWith(`${normalizedRoot}/`)) return normalizedPath.slice(normalizedRoot.length + 1);
	return toPosixPath(WINDOWS_PATH_RE.test(sourceRoot) || WINDOWS_PATH_RE.test(sourcePath) ? win32.relative(sourceRoot, sourcePath) : relative(sourceRoot, sourcePath));
}
function resolveNpmSourceCacheOutDir(cwd, npmDistDirName) {
	return path.resolve(cwd, ".weapp-vite/npm-source", npmDistDirName);
}
function matchDependencyCopyPath(patterns, value) {
	return matchDependencyPath(patterns, value);
}
//#endregion
//#region src/runtime/npmPlugin/service/build.ts
function hasSameDependencySet(source, target) {
	if (source.length !== target.length) return false;
	return source.every((dep) => target.includes(dep));
}
async function loadPackageInfo(dep, cwd) {
	try {
		return await getPackageInfo(dep, cwd ? { paths: [cwd] } : void 0);
	} catch {
		return null;
	}
}
async function resolvePackageDependencyClosure(dependencies, cwd, resolvePackageInfo = loadPackageInfo) {
	const visited = /* @__PURE__ */ new Set();
	async function visit(dep) {
		if (visited.has(dep)) return;
		visited.add(dep);
		const packageInfo = await resolvePackageInfo(dep, cwd);
		const transitiveDependencies = Object.keys(packageInfo?.packageJson.dependencies ?? {});
		await Promise.all(transitiveDependencies.map((childDep) => visit(childDep)));
	}
	await Promise.all(dependencies.map((dep) => visit(dep)));
	return [...visited];
}
async function copyDirectoryWithFilter(sourceDir, targetDir, filter) {
	await fs$1.ensureDir(targetDir);
	const entries = await fs$1.readdir(sourceDir, { withFileTypes: true });
	await Promise.all(entries.map(async (entry) => {
		const sourcePath = path.resolve(sourceDir, entry.name);
		if (!filter(sourcePath)) return;
		const targetPath = path.resolve(targetDir, entry.name);
		if (entry.isDirectory()) {
			await copyDirectoryWithFilter(sourcePath, targetPath, filter);
			return;
		}
		await fs$1.ensureDir(path.dirname(targetPath));
		await copyFile(sourcePath, targetPath);
	}));
}
function createNpmBuildService(options) {
	const { ctx, builder, cache } = options;
	const packageInfoPromiseCache = /* @__PURE__ */ new Map();
	function getPackageInfoCached(dep, cwd) {
		const cacheKey = `${cwd ?? ""}\0${dep}`;
		let packageInfoPromise = packageInfoPromiseCache.get(cacheKey);
		if (!packageInfoPromise) {
			packageInfoPromise = loadPackageInfo(dep, cwd);
			packageInfoPromiseCache.set(cacheKey, packageInfoPromise);
		}
		return packageInfoPromise;
	}
	async function resolveMiniprogramCandidateDependencies(allDependencies, cwd) {
		return (await Promise.all(allDependencies.map(async (dep) => {
			const packageInfo = await getPackageInfoCached(dep, cwd);
			if (packageInfo && builder.isMiniprogramPackage(packageInfo.packageJson)) return dep;
			return null;
		}))).filter((dep) => typeof dep === "string");
	}
	async function resolveBuildCandidateDependencies(pkgJson) {
		const syncCandidates = resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson);
		if (resolveNpmStrategyMode(ctx) === "legacy") return syncCandidates;
		const declaredDependencies = resolveDeclaredNpmDependencies(pkgJson);
		const miniprogramDependencies = await resolveMiniprogramCandidateDependencies(declaredDependencies, ctx.configService?.cwd);
		const explicitlyIncludedDependencies = resolveTargetDependencies(declaredDependencies, resolveConfiguredNpmDependencyPatterns(ctx));
		return dedupeNpmDependencies([...miniprogramDependencies, ...explicitlyIncludedDependencies]);
	}
	async function buildTargetDependencies(args) {
		const isDependenciesCacheOutdate = !await fs$1.pathExists(args.npmDistDir) || await cache.checkDependenciesCacheOutdate(args.cacheKey);
		if (isDependenciesCacheOutdate) await fs$1.remove(args.npmDistDir);
		if (args.dependencies.length === 0) {
			await fs$1.remove(args.npmDistDir);
			await cache.writeDependenciesCache(args.cacheKey);
			return;
		}
		await Promise.all(args.dependencies.map((dep) => {
			return builder.buildPackage({
				dep,
				outDir: args.npmDistDir,
				options: args.options,
				isDependenciesCacheOutdate
			});
		}));
		await cache.writeDependenciesCache(args.cacheKey);
	}
	async function build(options) {
		if (!ctx.configService?.weappViteConfig?.npm?.enable) return;
		const configService = ctx.configService;
		debug$2?.("buildNpm start");
		if (ctx.scanService && hasLocalSubPackageNpmConfig(ctx) && typeof ctx.scanService.loadAppEntry === "function") {
			await ctx.scanService.loadAppEntry();
			if (typeof ctx.scanService.loadSubPackages === "function") ctx.scanService.loadSubPackages();
		}
		const [mainRelation, ...subRelations] = getPackNpmRelationList(ctx);
		const packageJsonPath = path.resolve(configService.cwd, mainRelation.packageJsonPath);
		if (await fs$1.pathExists(packageJsonPath)) {
			const pkgJson = await fs$1.readJson(packageJsonPath) ?? {};
			const npmDistDirName = resolveNpmDistDirName(configService);
			const outDir = path.resolve(configService.cwd, mainRelation.miniprogramNpmDistDir, npmDistDirName);
			const cachedSourceOutDir = resolveNpmSourceCacheOutDir(configService.cwd, npmDistDirName);
			const localSubPackageOutRoot = configService.outDir || path.resolve(configService.cwd, mainRelation.miniprogramNpmDistDir);
			const allDependencies = await resolveBuildCandidateDependencies(pkgJson);
			const mainDependencies = resolveTargetDependencies(allDependencies, resolveMainBuildDependencyPatterns(ctx));
			const sourceOutDir = hasSameDependencySet(allDependencies, mainDependencies) ? outDir : cachedSourceOutDir;
			const localSubPackageMetas = [...ctx.scanService?.subPackageMap.values() ?? []].filter((meta) => Array.isArray(meta.subPackage.dependencies) && meta.subPackage.dependencies.length > 0);
			const sourceBuildPromise = sourceOutDir !== outDir ? buildTargetDependencies({
				cacheKey: "__all__",
				dependencies: allDependencies,
				npmDistDir: sourceOutDir,
				options
			}) : Promise.resolve();
			const mainBuildPromise = buildTargetDependencies({
				cacheKey: configService.pluginOnly ? "__plugin__" : void 0,
				dependencies: mainDependencies,
				npmDistDir: outDir,
				options
			});
			await Promise.all([sourceBuildPromise, mainBuildPromise]);
			if (mainDependencies.length === 0) await Promise.all(subRelations.map((relation) => {
				return fs$1.remove(path.resolve(configService.cwd, relation.miniprogramNpmDistDir, npmDistDirName));
			}));
			else await Promise.all(subRelations.map(async (relation) => {
				const targetDir = path.resolve(configService.cwd, relation.miniprogramNpmDistDir, npmDistDirName);
				await fs$1.remove(targetDir);
				await fs$1.copy(outDir, targetDir, { overwrite: true });
			}));
			await Promise.all(localSubPackageMetas.map(async (meta) => {
				const targetDir = path.resolve(localSubPackageOutRoot, meta.subPackage.root, npmDistDirName);
				if (await cache.checkDependenciesCacheOutdate(meta.subPackage.root) || !await fs$1.pathExists(targetDir)) {
					const subPackageDependencies = Array.isArray(meta.subPackage.dependencies) ? await resolvePackageDependencyClosure(resolveTargetDependencies(allDependencies, meta.subPackage.dependencies), configService.cwd, getPackageInfoCached) : [];
					await fs$1.remove(targetDir);
					await copyDirectoryWithFilter(sourceOutDir, targetDir, (sourcePath) => {
						if (subPackageDependencies.length > 0) {
							const relPath = resolveCopyFilterRelativePath(sourceOutDir, sourcePath);
							if (relPath === "") return true;
							return matchDependencyCopyPath(subPackageDependencies, relPath);
						}
						return true;
					});
				}
				await cache.writeDependenciesCache(meta.subPackage.root);
			}));
		}
		debug$2?.("buildNpm end");
	}
	return { build };
}
//#endregion
//#region src/runtime/npmPlugin/service/index.ts
function createNpmService(ctx) {
	const oxcVitePlugin = createOxcRuntimeSupport().vitePlugin;
	const cache = createDependenciesCache(ctx);
	const builder = createPackageBuilder(ctx, oxcVitePlugin);
	const buildService = createNpmBuildService({
		ctx,
		builder,
		cache
	});
	return {
		getDependenciesCacheFilePath: cache.getDependenciesCacheFilePath,
		get dependenciesCacheHash() {
			return cache.dependenciesCacheHash();
		},
		isMiniprogramPackage: builder.isMiniprogramPackage,
		shouldSkipBuild: builder.shouldSkipBuild,
		writeDependenciesCache: cache.writeDependenciesCache,
		readDependenciesCache: cache.readDependenciesCache,
		checkDependenciesCacheOutdate: cache.checkDependenciesCacheOutdate,
		bundleBuild: builder.bundleBuild,
		copyBuild: builder.copyBuild,
		buildPackage: builder.buildPackage,
		getPackNpmRelationList: () => getPackNpmRelationList(ctx),
		build: buildService.build
	};
}
const nativeMiniprogramRuntimeProvider = { descriptor: {
	id: "native-miniprogram",
	backend: "miniprogram",
	compilation: "native",
	injection: "none",
	entries: Object.freeze({}),
	capabilities: Object.freeze({
		framework: false,
		hmr: false,
		nativeHost: true,
		webHost: false
	}),
	hmr: Object.freeze({ mode: "none" }),
	contractVersion: WEAPP_VITE_RUNTIME_CONTRACT_VERSION
} };
const wevuMiniprogramRuntimeProvider = { descriptor: {
	id: "wevu-miniprogram",
	backend: "miniprogram",
	compilation: "vue",
	injection: "virtual-module",
	entries: Object.freeze({
		runtime: Object.freeze({
			development: "wevu/internal-runtime",
			production: "wevu/internal-runtime"
		}),
		reactivity: Object.freeze({
			development: "wevu/internal-reactivity",
			production: "wevu/internal-reactivity"
		}),
		template: Object.freeze({
			development: "wevu/internal-template",
			production: "wevu/internal-template"
		})
	}),
	capabilities: Object.freeze({
		framework: true,
		hmr: true,
		nativeHost: true,
		webHost: false
	}),
	hmr: Object.freeze({ mode: "host-reload" }),
	contractVersion: WEAPP_VITE_RUNTIME_CONTRACT_VERSION
} };
const webRuntimeProvider = {
	descriptor: {
		id: "web-runtime",
		backend: "web",
		compilation: "web",
		injection: "virtual-module",
		entries: Object.freeze({
			runtime: Object.freeze({
				development: "@weapp-vite/web/runtime",
				production: "@weapp-vite/web/runtime"
			}),
			reactivity: Object.freeze({
				development: "wevu/internal-reactivity",
				production: "wevu/internal-reactivity"
			}),
			template: Object.freeze({
				development: "wevu/internal-template",
				production: "wevu/internal-template"
			})
		}),
		capabilities: Object.freeze({
			framework: false,
			hmr: true,
			nativeHost: false,
			webHost: true
		}),
		hmr: Object.freeze({
			mode: "module-accept",
			acceptCode: "if (import.meta.hot) { import.meta.hot.accept() }"
		}),
		contractVersion: WEAPP_VITE_RUNTIME_CONTRACT_VERSION
	},
	resolveModuleId(entry) {
		if (entry.kind !== "runtime") return entry.moduleId;
		return fileURLToPath(import.meta.resolve(entry.moduleId));
	}
};
//#endregion
//#region src/runtimeProviders/plugin.ts
const runtimeKindByVirtualId = new Map(Object.entries(WEAPP_VITE_RUNTIME_VIRTUAL_IDS).map(([kind, id]) => [id, kind]));
const WEB_RUNTIME_COMPAT_ENTRY = "weapp-vite/runtime";
function resolveRuntimeProviderEntry(provider, kind, variant) {
	const { descriptor } = provider;
	if (descriptor.contractVersion !== WEAPP_VITE_RUNTIME_CONTRACT_VERSION) throw new Error(`运行时 provider "${descriptor.id}" 的 contract version 为 ${descriptor.contractVersion},当前编译器要求 ${WEAPP_VITE_RUNTIME_CONTRACT_VERSION}。`);
	if (descriptor.injection === "none") throw new Error(`运行时 provider "${descriptor.id}" 不允许注入框架运行时。`);
	const entry = descriptor.entries[kind];
	if (!entry) throw new Error(`运行时 provider "${descriptor.id}" 未声明 ${kind} 入口。`);
	return {
		kind,
		moduleId: entry[variant],
		provider,
		variant
	};
}
function resolveRuntimeProviderHmrFooter(provider) {
	const { hmr } = provider.descriptor;
	return hmr.mode === "module-accept" ? hmr.acceptCode : void 0;
}
function createRuntimeProviderPlugin(provider, variant) {
	return {
		name: `weapp-vite:runtime-provider:${provider.descriptor.id}`,
		enforce: "pre",
		async resolveId(id, importer) {
			const kind = runtimeKindByVirtualId.get(id) ?? (provider.descriptor.backend === "web" && id === WEB_RUNTIME_COMPAT_ENTRY ? "runtime" : void 0);
			if (!kind) return null;
			const entry = resolveRuntimeProviderEntry(provider, kind, variant);
			let moduleId = entry.moduleId;
			try {
				moduleId = await provider.resolveModuleId?.(entry) ?? moduleId;
			} catch (cause) {
				throw new Error(`运行时 provider "${provider.descriptor.id}" 无法定位 ${variant} ${kind} 入口 "${entry.moduleId}"。`, { cause });
			}
			const resolved = await this.resolve(moduleId, importer, { skipSelf: true });
			if (!resolved) throw new Error(`运行时 provider "${provider.descriptor.id}" 无法解析 ${variant} ${kind} 入口 "${entry.moduleId}"。`);
			return resolved;
		}
	};
}
//#endregion
//#region src/runtimeProviders/registry.ts
function selectionKey(selection) {
	return `${selection.backend}:${selection.compilation}`;
}
var RuntimeProviderRegistry = class {
	providers = [];
	providerById = /* @__PURE__ */ new Map();
	providerBySelection = /* @__PURE__ */ new Map();
	register(provider) {
		const id = provider.descriptor.id.trim();
		if (!id) throw new Error("运行时 provider id 不能为空。");
		if (this.providerById.has(id)) throw new Error(`运行时 provider id "${id}" 已注册。`);
		const key = selectionKey(provider.descriptor);
		const existing = this.providerBySelection.get(key);
		if (existing) throw new Error(`运行时 provider 选择 "${key}" 已由 "${existing.descriptor.id}" 注册。`);
		this.providers.push(provider);
		this.providerById.set(id, provider);
		this.providerBySelection.set(key, provider);
	}
	get(id) {
		return this.providerById.get(id.trim());
	}
	getAll() {
		return this.providers;
	}
	resolve(selection) {
		const provider = this.providerBySelection.get(selectionKey(selection));
		if (!provider) throw new Error(`没有可用于 ${selection.backend}/${selection.compilation} 的运行时 provider。`);
		return provider;
	}
};
//#endregion
//#region src/runtimeProviders/index.ts
const runtimeProviderRegistry = new RuntimeProviderRegistry();
runtimeProviderRegistry.register(nativeMiniprogramRuntimeProvider);
runtimeProviderRegistry.register(wevuMiniprogramRuntimeProvider);
runtimeProviderRegistry.register(webRuntimeProvider);
function resolveRuntimeProvider(backend, compilation) {
	return runtimeProviderRegistry.resolve({
		backend,
		compilation
	});
}
function createSelectedRuntimeProviderPlugin(provider, isDev) {
	return createRuntimeProviderPlugin(provider, isDev ? "development" : "production");
}
//#endregion
//#region src/plugins/utils/scriptlessComponent.ts
const SCRIPTLESS_COMPONENT_STUB = "Component({})";
const SLOT_HOST_SCRIPTLESS_COMPONENT_STUB = "Component({properties:{vueSlots:{type:null,value:null},__wvSlotOwnerId:{type:String,value:\"\"},__wvSlotScope:{type:null,value:null}}})";
/**
* 统一生成无脚本组件的脚本产物文件名。
*/
function resolveScriptlessComponentFileName(relativeBase, scriptExtension) {
	return `${relativeBase}.${scriptExtension}`;
}
function emitScriptlessComponentAsset(pluginCtx, fileName, source = SCRIPTLESS_COMPONENT_STUB) {
	pluginCtx.emitFile({
		type: "asset",
		fileName,
		source
	});
}
/**
* 在 bundle 中补齐或覆盖无脚本组件占位脚本。
*/
function ensureScriptlessComponentAsset(pluginCtx, bundle, relativeBase, scriptExtension, source = SCRIPTLESS_COMPONENT_STUB) {
	const fileName = resolveScriptlessComponentFileName(relativeBase, scriptExtension);
	const existing = bundle[fileName];
	if (existing) {
		if (existing.type === "asset") {
			if ((existing.source?.toString?.() ?? "") !== source) existing.source = source;
		}
		return fileName;
	}
	emitScriptlessComponentAsset(pluginCtx, fileName, source);
	return fileName;
}
//#endregion
//#region src/plugins/vue/transform/emitAssets.ts
let emittedAssetSourceCacheByBundle = /* @__PURE__ */ new WeakMap();
function hasOwn$3(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
function getEmittedAssetSourceCache(bundle) {
	let cache = emittedAssetSourceCacheByBundle.get(bundle);
	if (!cache) {
		cache = /* @__PURE__ */ new Map();
		emittedAssetSourceCacheByBundle.set(bundle, cache);
	}
	return cache;
}
/**
* 统一拼接 SFC 相关产物文件名。
*/
function resolveSfcAssetFileName(relativeBase, extension) {
	return `${relativeBase}.${extension}`;
}
function parseJsonSafely$2(source) {
	if (!source) return;
	try {
		return JSON.parse(source);
	} catch {
		return;
	}
}
function emitSfcTemplateIfMissing(ctx, bundle, relativeBase, template, extension = "wxml") {
	const fileName = resolveSfcAssetFileName(relativeBase, extension);
	const cacheKey = `asset:${fileName}`;
	const emittedAssetSourceCache = getEmittedAssetSourceCache(bundle);
	const existing = bundle[fileName];
	if (existing && existing.type === "asset") {
		if ((existing.source?.toString?.() ?? "") !== template) existing.source = template;
		emittedAssetSourceCache.set(cacheKey, template);
		return;
	}
	if (emittedAssetSourceCache.get(cacheKey) === template) return;
	ctx.emitFile({
		type: "asset",
		fileName,
		source: template
	});
	emittedAssetSourceCache.set(cacheKey, template);
}
function emitSfcStyleIfMissing(ctx, bundle, relativeBase, style, extension = "wxss", options) {
	const fileName = resolveSfcAssetFileName(relativeBase, extension);
	const cacheKey = `asset:${fileName}`;
	const emittedAssetSourceCache = getEmittedAssetSourceCache(bundle);
	const existing = bundle[fileName];
	if (existing && existing.type === "asset") {
		if (options?.updateExisting === false) {
			emittedAssetSourceCache.set(cacheKey, existing.source?.toString?.() ?? "");
			return;
		}
		if ((existing.source?.toString?.() ?? "") !== style) existing.source = style;
		emittedAssetSourceCache.set(cacheKey, style);
		return;
	}
	if (emittedAssetSourceCache.get(cacheKey) === style) return;
	ctx.emitFile({
		type: "asset",
		fileName,
		source: style
	});
	emittedAssetSourceCache.set(cacheKey, style);
}
function emitSfcJsonAsset(ctx, bundle, relativeBase, result, options) {
	const jsonFileName = resolveSfcAssetFileName(relativeBase, options.extension ?? "json");
	const cacheKey = `asset:${jsonFileName}`;
	const emittedAssetSourceCache = getEmittedAssetSourceCache(bundle);
	const existing = bundle[jsonFileName];
	const mergeJson = createJsonMerger(options.mergeStrategy, {
		filename: jsonFileName,
		kind: options.kind ?? "unknown"
	});
	const defaultConfig = options.defaultConfig;
	let nextConfig = parseJsonSafely$2(result.config);
	if (!nextConfig && options.defaults) nextConfig = mergeJson({}, options.defaults, "defaults");
	if (defaultConfig) nextConfig = mergeJson(defaultConfig, nextConfig ?? {}, "emit");
	if (defaultConfig && nextConfig) {
		if (hasOwn$3(defaultConfig, "component") && !hasOwn$3(nextConfig, "component")) nextConfig.component = true;
	}
	if (!nextConfig && defaultConfig) nextConfig = defaultConfig;
	if (!nextConfig) return;
	if (options.emitIfMissingOnly) {
		if (!bundle[jsonFileName]) {
			nextConfig = options.finalizeConfig?.(nextConfig) ?? nextConfig;
			const nextSource = JSON.stringify(nextConfig, null, 2);
			if (emittedAssetSourceCache.get(cacheKey) !== nextSource) {
				ctx.emitFile({
					type: "asset",
					fileName: jsonFileName,
					source: nextSource
				});
				emittedAssetSourceCache.set(cacheKey, nextSource);
			}
		}
		return;
	}
	if (options.mergeExistingAsset && existing && existing.type === "asset") {
		try {
			const mergedConfig = mergeJson(JSON.parse(existing.source.toString()), nextConfig, "merge-existing");
			const merged = options.finalizeConfig?.(mergedConfig) ?? mergedConfig;
			existing.source = JSON.stringify(merged, null, 2);
		} catch {
			nextConfig = options.finalizeConfig?.(nextConfig) ?? nextConfig;
			existing.source = JSON.stringify(nextConfig, null, 2);
		}
		return;
	}
	if (existing && existing.type === "asset") {
		nextConfig = options.finalizeConfig?.(nextConfig) ?? nextConfig;
		const nextSource = JSON.stringify(nextConfig, null, 2);
		if ((existing.source?.toString?.() ?? "") !== nextSource) existing.source = nextSource;
		emittedAssetSourceCache.set(cacheKey, nextSource);
		return;
	}
	nextConfig = options.finalizeConfig?.(nextConfig) ?? nextConfig;
	const nextSource = JSON.stringify(nextConfig, null, 2);
	if (emittedAssetSourceCache.get(cacheKey) === nextSource) return;
	ctx.emitFile({
		type: "asset",
		fileName: jsonFileName,
		source: nextSource
	});
	emittedAssetSourceCache.set(cacheKey, nextSource);
}
function emitSfcScriptAssetReplacingBundleEntry(ctx, bundle, relativeBase, code, extension = "js") {
	const jsFileName = resolveSfcAssetFileName(relativeBase, extension);
	const existing = bundle[jsFileName];
	if (existing) {
		if (existing.type === "chunk") existing.code = code;
		else existing.source = code;
		return;
	}
	ctx.emitFile({
		type: "asset",
		fileName: jsFileName,
		source: code
	});
}
function emitClassStyleWxsAssetIfMissing(ctx, bundle, fileName, source) {
	const existing = bundle[fileName];
	const cacheKey = `asset:${fileName}`;
	const emittedAssetSourceCache = getEmittedAssetSourceCache(bundle);
	if (existing && existing.type === "asset") {
		if ((existing.source?.toString?.() ?? "") !== source) existing.source = source;
		emittedAssetSourceCache.set(cacheKey, source);
		return;
	}
	if (emittedAssetSourceCache.get(cacheKey) === source) return;
	ctx.emitFile({
		type: "asset",
		fileName,
		source
	});
	emittedAssetSourceCache.set(cacheKey, source);
}
//#endregion
//#region src/plugins/vue/transform/platform.ts
function resolveVueTransformJsonPlatformOptions(configService) {
	const platform = resolveMiniPlatformWithDefault(configService?.platform);
	return {
		platform,
		normalizeUsingComponents: getJsonPlatformOptions(platform).normalizeUsingComponents,
		dependencies: configService?.packageJson?.dependencies,
		alipayNpmMode: configService?.weappViteConfig?.npm?.alipayNpmMode
	};
}
//#endregion
//#region src/plugins/vue/transform/shared.ts
const VUE_LIKE_EXTENSIONS$1 = [
	".vue",
	".tsx",
	".jsx"
];
function isVueLikeFile(id) {
	return VUE_LIKE_EXTENSIONS$1.some((ext) => id.endsWith(ext));
}
function stripVueLikeExtension(filePath) {
	for (const ext of VUE_LIKE_EXTENSIONS$1) if (filePath.endsWith(ext)) return filePath.slice(0, -ext.length);
	return filePath;
}
function resolveVueLikeEntryCandidates(entryId) {
	return VUE_LIKE_EXTENSIONS$1.map((ext) => `${entryId}${ext}`);
}
async function findFirstResolvedVueLikeEntry(entryId, options) {
	for (const candidate of resolveVueLikeEntryCandidates(entryId)) {
		const resolved = await options.resolve(candidate);
		if (resolved !== void 0) return resolved;
	}
}
function resolveVueOutputBase(configService, filePath) {
	const extIndex = filePath.lastIndexOf(".");
	const basePath = extIndex >= 0 ? filePath.slice(0, extIndex) : filePath;
	return configService.relativeOutputPath(basePath);
}
function registerVueTemplateToken(ctx, filename, template) {
	if (!template) return;
	const wxmlService = ctx.wxmlService;
	if (!wxmlService) return;
	try {
		const token = wxmlService.analyze(template);
		wxmlService.tokenMap.set(filename, token);
		if (typeof wxmlService.setTokenDeps === "function") wxmlService.setTokenDeps(filename, token.deps);
		else if (typeof wxmlService.collectDepsFromToken === "function" && typeof wxmlService.setDeps === "function") wxmlService.setDeps(filename, wxmlService.collectDepsFromToken(filename, token.deps));
		wxmlService.setWxmlComponentsMap(filename, token.components);
	} catch {}
}
//#endregion
//#region src/plugins/vue/transform/bundle/platform.ts
const LEADING_DOT_SLASH_RE$1 = /^\.\//;
const SCOPED_SLOT_GENERIC_KEY_RE = /^scoped-slots-/;
const WEAPP_SCOPED_SLOT_GENERIC_PLACEHOLDER_TEMPLATE = "<view wx:if=\"{{false}}\" />";
function resolveVueBundlePlatformOptions(options) {
	return {
		normalizeUsingComponents: resolveVueTransformJsonPlatformOptions({
			platform: options.platform,
			weappViteConfig: {},
			packageJson: {}
		}).normalizeUsingComponents,
		normalizeTemplate: shouldNormalizeVueTemplateForPlatform(options.platform),
		emitGenericPlaceholder: shouldEmitGenericPlaceholderAsset(options.platform),
		scriptModuleTag: resolveScriptModuleTagByPlatform(options.platform, options.scriptModuleExtension)
	};
}
function resolveVueBundlePlatformAssetOptions(options) {
	return {
		platform: resolveMiniPlatformWithDefault(options.configService?.platform),
		templateExtension: options.templateExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		dependencies: options.configService?.packageJson?.dependencies,
		alipayNpmMode: options.configService?.weappViteConfig?.npm?.alipayNpmMode
	};
}
function shouldNormalizeWeappScopedSlotGenericPlaceholder(config) {
	if (!config || typeof config !== "object" || Array.isArray(config)) return false;
	const componentGenerics = config.componentGenerics;
	if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return false;
	return Object.entries(componentGenerics).some(([key, value]) => {
		if (!SCOPED_SLOT_GENERIC_KEY_RE.test(key)) return false;
		if (value === true) return true;
		if (!value || typeof value !== "object" || Array.isArray(value)) return false;
		const defaultValue = value.default;
		return typeof defaultValue !== "string" || !defaultValue.trim();
	});
}
function normalizeVueConfigForPlatform(config, options) {
	const jsonPlatformOptions = resolveVueTransformJsonPlatformOptions({
		platform: options.platform,
		packageJson: { dependencies: options.dependencies },
		weappViteConfig: { npm: { alipayNpmMode: options.alipayNpmMode } }
	});
	if (!config) return config;
	try {
		const parsed = JSON.parse(config);
		const normalized = options.kind === "app" ? normalizeAppJson(parsed) : parsed;
		if (!(jsonPlatformOptions.normalizeUsingComponents || options.kind === "app" || options.platform === "weapp" && shouldNormalizeWeappScopedSlotGenericPlaceholder(parsed))) return config;
		return resolveJson({
			json: normalized,
			type: options.kind
		}, void 0, options.platform, {
			dependencies: jsonPlatformOptions.dependencies,
			alipayNpmMode: jsonPlatformOptions.alipayNpmMode
		}) ?? config;
	} catch {
		return config;
	}
}
function transformVueTemplateForPlatform(template, options) {
	return handleWxml(scanWxml(template, { platform: options.platform }), {
		templateExtension: options.templateExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		scriptModuleTag: options.scriptModuleTag
	}).code;
}
function normalizeVueTemplateForPlatform(template, options) {
	const platformOptions = resolveVueBundlePlatformOptions({
		platform: options.platform,
		scriptModuleExtension: options.scriptModuleExtension
	});
	if (!platformOptions.normalizeTemplate) return template;
	try {
		return transformVueTemplateForPlatform(template, {
			platform: options.platform,
			templateExtension: options.templateExtension,
			scriptModuleExtension: options.scriptModuleExtension,
			scriptModuleTag: platformOptions.scriptModuleTag
		});
	} catch {
		return template;
	}
}
const trackPlatformTemplateAnalysis = registerVueTemplateToken;
function emitPlatformTemplateAsset(bundle, options) {
	const normalizedTemplate = normalizeVueTemplateForPlatform(options.template, {
		platform: options.platform,
		templateExtension: options.templateExtension,
		scriptModuleExtension: options.scriptModuleExtension
	});
	trackPlatformTemplateAnalysis(options.ctx, options.filename, normalizedTemplate);
	emitSfcTemplateIfMissing(options.pluginCtx, bundle, options.relativeBase, normalizedTemplate, options.templateExtension);
	return normalizedTemplate;
}
function resolveGenericPlaceholderBase(relativeBase, placeholder) {
	const dirIndex = relativeBase.lastIndexOf("/");
	const dir = dirIndex >= 0 ? relativeBase.slice(0, dirIndex) : "";
	const placeholderName = placeholder.replace(LEADING_DOT_SLASH_RE$1, "");
	return dir ? `${dir}/${placeholderName}` : placeholderName;
}
function resolveAlipayGenericPlaceholderBase(relativeBase) {
	return resolveGenericPlaceholderBase(relativeBase, ALIPAY_GENERIC_COMPONENT_PLACEHOLDER);
}
function resolveWeappScopedSlotGenericPlaceholderBase(relativeBase) {
	return resolveGenericPlaceholderBase(relativeBase, WEAPP_SCOPED_SLOT_GENERIC_COMPONENT_PLACEHOLDER);
}
function emitAlipayGenericPlaceholderAssetsByBase(ctx, bundle, placeholderBase, outputExtensions, options) {
	const templateExtension = outputExtensions?.wxml ?? "wxml";
	const jsonExtension = outputExtensions?.json ?? "json";
	const scriptExtension = outputExtensions?.js ?? "js";
	emitSfcTemplateIfMissing(ctx, bundle, placeholderBase, options?.templateSource ?? "<view />", templateExtension);
	emitSfcJsonAsset(ctx, bundle, placeholderBase, { config: JSON.stringify(options?.jsonConfig ?? { component: true }) }, {
		extension: jsonExtension,
		kind: "component"
	});
	ensureScriptlessComponentAsset(ctx, bundle, placeholderBase, scriptExtension);
}
function shouldEmitAlipayGenericPlaceholder(configSource) {
	if (!configSource) return false;
	let config;
	try {
		const parsed = JSON.parse(configSource);
		if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
		config = parsed;
	} catch {
		return false;
	}
	const componentGenerics = config.componentGenerics;
	if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return false;
	return Object.values(componentGenerics).some((value) => {
		if (value === true) return true;
		if (!value || typeof value !== "object" || Array.isArray(value)) return false;
		return value.default === ALIPAY_GENERIC_COMPONENT_PLACEHOLDER;
	});
}
function shouldEmitWeappScopedSlotGenericPlaceholder(configSource) {
	if (!configSource) return false;
	let config;
	try {
		const parsed = JSON.parse(configSource);
		if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
		config = parsed;
	} catch {
		return false;
	}
	const componentGenerics = config.componentGenerics;
	if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return false;
	return Object.entries(componentGenerics).some(([key, value]) => {
		if (!SCOPED_SLOT_GENERIC_KEY_RE.test(key)) return false;
		if (!value || typeof value !== "object" || Array.isArray(value)) return false;
		return value.default === WEAPP_SCOPED_SLOT_GENERIC_COMPONENT_PLACEHOLDER;
	});
}
function resolveGenericPlaceholderBaseForPlatform(relativeBase, configSource, platform) {
	if (platform === "weapp") return shouldEmitWeappScopedSlotGenericPlaceholder(configSource) ? resolveWeappScopedSlotGenericPlaceholderBase(relativeBase) : void 0;
	if (!resolveVueBundlePlatformOptions({ platform }).emitGenericPlaceholder || !configSource) return;
	if (!shouldEmitAlipayGenericPlaceholder(configSource)) return;
	return resolveAlipayGenericPlaceholderBase(relativeBase);
}
function emitAlipayGenericPlaceholderAssets(ctx, bundle, relativeBase, configSource, outputExtensions, platform) {
	const placeholderBase = resolveGenericPlaceholderBaseForPlatform(relativeBase, configSource, platform);
	if (!placeholderBase) return;
	emitAlipayGenericPlaceholderAssetsByBase(ctx, bundle, placeholderBase, outputExtensions, platform === "weapp" ? {
		jsonConfig: {
			component: true,
			options: { virtualHost: true }
		},
		templateSource: WEAPP_SCOPED_SLOT_GENERIC_PLACEHOLDER_TEMPLATE
	} : void 0);
}
function prepareNormalizedVueConfigForPlatform(options) {
	return normalizeVueConfigForPlatform(options.config, {
		platform: options.platform,
		kind: options.kind,
		dependencies: options.dependencies,
		alipayNpmMode: options.alipayNpmMode
	});
}
function resolvePlatformConfigAssetState(options) {
	const normalizedConfig = prepareNormalizedVueConfigForPlatform({
		config: options.config,
		platform: options.platform,
		kind: options.kind,
		dependencies: options.dependencies,
		alipayNpmMode: options.alipayNpmMode
	});
	return {
		normalizedConfig,
		genericPlaceholderBase: resolveGenericPlaceholderBaseForPlatform(options.relativeBase, normalizedConfig, options.platform)
	};
}
function emitPlatformConfigSideEffects(bundle, options) {
	if (options.genericPlaceholderBase) {
		emitAlipayGenericPlaceholderAssetsByBase(options.pluginCtx, bundle, options.genericPlaceholderBase, options.outputExtensions, options.platform === "weapp" ? {
			jsonConfig: {
				component: true,
				options: { virtualHost: true }
			},
			templateSource: WEAPP_SCOPED_SLOT_GENERIC_PLACEHOLDER_TEMPLATE
		} : void 0);
		return;
	}
	emitAlipayGenericPlaceholderAssets(options.pluginCtx, bundle, options.relativeBase, options.config, options.outputExtensions, options.platform);
}
function preparePlatformConfigAsset(bundle, options) {
	const { normalizedConfig, genericPlaceholderBase } = resolvePlatformConfigAssetState({
		relativeBase: options.relativeBase,
		config: options.config,
		kind: options.kind,
		platform: options.platform,
		dependencies: options.dependencies,
		alipayNpmMode: options.alipayNpmMode
	});
	emitPlatformConfigSideEffects(bundle, {
		pluginCtx: options.pluginCtx,
		relativeBase: options.relativeBase,
		config: normalizedConfig,
		outputExtensions: options.outputExtensions,
		platform: options.platform,
		genericPlaceholderBase
	});
	return normalizedConfig;
}
//#endregion
//#region src/plugins/vue/transform/wevuPreset.ts
const PERFORMANCE_PRESET_DEFAULTS = {
	app: { setData: {
		strategy: "patch",
		suspendWhenHidden: true,
		diagnostics: "fallback",
		highFrequencyWarning: {
			enabled: true,
			devOnly: true
		}
	} },
	component: { setData: {
		strategy: "patch",
		suspendWhenHidden: true,
		diagnostics: "fallback",
		highFrequencyWarning: {
			enabled: true,
			devOnly: true
		}
	} }
};
function getPlainRecord(value) {
	if (!value || typeof value !== "object" || Array.isArray(value)) return;
	return value;
}
function mergeDefaults(defaults, options) {
	if (!defaults) return options;
	if (!options) return defaults;
	const merged = {
		...defaults,
		...options
	};
	const defaultSetData = getPlainRecord(defaults.setData);
	const optionSetData = getPlainRecord(options.setData);
	if (defaultSetData || optionSetData) merged.setData = {
		...defaultSetData ?? {},
		...optionSetData ?? {}
	};
	const defaultOptions = getPlainRecord(defaults.options);
	const optionOptions = getPlainRecord(options.options);
	if (defaultOptions || optionOptions) merged.options = {
		...defaultOptions ?? {},
		...optionOptions ?? {}
	};
	return merged;
}
function mergeWevuDefaults(base, next) {
	return {
		app: mergeDefaults(base.app, next.app),
		component: mergeDefaults(base.component, next.component)
	};
}
/**
* 读取 wevu 预设名称。
*/
function resolveWevuPreset(config) {
	return config?.wevu?.preset;
}
/**
* 根据配置解析最终的 wevu defaults(预设 + 用户配置)。
*/
function resolveWevuDefaultsWithPreset(config) {
	const userDefaults = config?.wevu?.defaults;
	if (resolveWevuPreset(config) !== "performance") return userDefaults;
	return mergeWevuDefaults(PERFORMANCE_PRESET_DEFAULTS, userDefaults ?? {});
}
/**
* 根据配置判断是否启用自动 setData.pick 注入。
*/
function isAutoSetDataPickEnabledWithPreset(config) {
	const explicit = config?.wevu?.autoSetDataPick;
	if (typeof explicit === "boolean") return explicit;
	return resolveWevuPreset(config) === "performance";
}
/**
* 读取 wevu 输出是否压缩。
*/
function isWevuMinifyEnabled(config, isDev = false) {
	const explicit = config?.wevu?.minify;
	if (typeof explicit === "boolean") return explicit;
	return !isDev;
}
//#endregion
//#region src/plugins/vue/transform/injectSetDataPick.ts
const SCOPED_SLOT_OWNER_AUTO_PICK_BIND_KEY_LIMIT = 200;
const AUTO_BIND_PICK_KEY_PREFIX = "__wv_bind_";
/**
* 根据配置判断是否启用自动 setData.pick 注入。
*/
function isAutoSetDataPickEnabled(config) {
	return isAutoSetDataPickEnabledWithPreset(config);
}
function isKnownWevuComponentCallee(callee) {
	if (!t.isExpression(callee) && !t.isV8IntrinsicIdentifier(callee)) return false;
	if (callee.type === "Identifier") return callee.name === "createWevuComponent" || callee.name === "defineComponent";
	if (callee.type !== "MemberExpression" || callee.computed) return false;
	return callee.property.type === "Identifier" && (callee.property.name === "createWevuComponent" || callee.property.name === "defineComponent" || callee.property.name === "so");
}
/**
* 通过轻量字符串特征快速判断脚本是否可能需要注入 setData.pick。
*/
function mayNeedInjectSetDataPickInJs(source) {
	return source.includes("createWevuComponent") || source.includes("defineComponent") || source.includes("__wevu_isPage") || source.includes(".so(") || source.includes("export default");
}
/**
* 判断脚本 setup 阶段是否会读取编译期 slot 名元数据。
*/
function mayNeedScopedSlotHostPropertiesForSetupSlotsInJs(source) {
	if (!source.includes("useSlots")) return false;
	const ast = parseJsLike(source);
	const useSlotsLocals = /* @__PURE__ */ new Set();
	traverse(ast, { ImportDeclaration(path) {
		const sourceValue = path.node.source.value;
		if (sourceValue !== "wevu" && sourceValue !== "vue" && sourceValue !== "wevu/internal-runtime" && sourceValue !== WEAPP_VITE_RUNTIME_VIRTUAL_ID) return;
		for (const specifier of path.node.specifiers) if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "useSlots" && specifier.local.type === "Identifier") useSlotsLocals.add(specifier.local.name);
	} });
	if (!useSlotsLocals.size) return false;
	let hasSetupSlotsCall = false;
	traverse(ast, { CallExpression(path) {
		if (path.node.callee.type === "Identifier" && useSlotsLocals.has(path.node.callee.name)) hasSetupSlotsCall = true;
	} });
	return hasSetupSlotsCall;
}
function getObjectPropertyByKey$1(objectExpression, key) {
	for (const member of objectExpression.properties) {
		if (member.type !== "ObjectProperty") continue;
		if (member.key.type === "Identifier" && member.key.name === key) return member;
		if (member.key.type === "StringLiteral" && member.key.value === key) return member;
	}
}
function hasCompiledWevuOptionsMarker(optionsObject) {
	return Boolean(getObjectPropertyByKey$1(optionsObject, "__wevu_isPage"));
}
function unwrapExpression(node) {
	let current = node;
	while (true) {
		if (current.type === "TSAsExpression" || current.type === "TSTypeAssertion" || current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression" || current.type === "TSSatisfiesExpression") {
			current = current.expression;
			continue;
		}
		return current;
	}
}
function resolveOptionsObjectExpression(expression, scope) {
	if (!expression) return;
	const unwrapped = unwrapExpression(expression);
	if (unwrapped.type === "ObjectExpression") return unwrapped;
	if (unwrapped.type === "Identifier") {
		const binding = scope.getBinding(unwrapped.name);
		if (!binding || !binding.path.isVariableDeclarator()) return;
		const init = binding.path.node.init;
		if (!init || init.type !== "ObjectExpression" && init.type !== "CallExpression" && init.type !== "Identifier") return;
		return resolveOptionsObjectExpression(init, binding.path.scope);
	}
	if (unwrapped.type === "CallExpression" && unwrapped.callee.type === "MemberExpression" && !unwrapped.callee.computed && unwrapped.callee.object.type === "Identifier" && unwrapped.callee.object.name === "Object" && unwrapped.callee.property.type === "Identifier" && unwrapped.callee.property.name === "assign") for (let i = unwrapped.arguments.length - 1; i >= 0; i--) {
		const arg = unwrapped.arguments[i];
		if (arg.type !== "SpreadElement") {
			const resolved = resolveOptionsObjectExpression(arg, scope);
			if (resolved) return resolved;
		}
	}
}
function createPickArrayExpression(keys) {
	return {
		type: "ArrayExpression",
		elements: keys.map((key) => ({
			type: "StringLiteral",
			value: key
		}))
	};
}
function mergeStableKeys(keys, stableKeys) {
	const merged = [];
	const seen = /* @__PURE__ */ new Set();
	for (const key of [...keys, ...stableKeys]) {
		if (seen.has(key)) continue;
		seen.add(key);
		merged.push(key);
	}
	return merged;
}
function mergePickArrayExpression(arrayExpression, keys) {
	const existing = /* @__PURE__ */ new Set();
	for (const element of arrayExpression.elements) if (element && element.type === "StringLiteral") existing.add(element.value);
	let changed = false;
	for (const key of keys) {
		if (existing.has(key)) continue;
		arrayExpression.elements.push({
			type: "StringLiteral",
			value: key
		});
		existing.add(key);
		changed = true;
	}
	return changed;
}
function injectPickIntoSetDataObject(setDataObject, keys) {
	const pickProp = getObjectPropertyByKey$1(setDataObject, "pick");
	if (!pickProp) {
		setDataObject.properties.unshift({
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: "pick"
			},
			computed: false,
			shorthand: false,
			value: createPickArrayExpression(keys)
		});
		return true;
	}
	if (pickProp.value.type !== "ArrayExpression") return false;
	return mergePickArrayExpression(pickProp.value, keys);
}
function injectPickIntoOptionsObject(optionsObject, keys) {
	const setDataProp = getObjectPropertyByKey$1(optionsObject, "setData");
	if (!setDataProp) {
		optionsObject.properties.unshift({
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: "setData"
			},
			computed: false,
			shorthand: false,
			value: {
				type: "ObjectExpression",
				properties: [{
					type: "ObjectProperty",
					key: {
						type: "Identifier",
						name: "pick"
					},
					computed: false,
					shorthand: false,
					value: createPickArrayExpression(keys)
				}]
			}
		});
		return true;
	}
	const setDataValue = unwrapExpression(setDataProp.value);
	if (setDataValue.type === "ObjectExpression") return injectPickIntoSetDataObject(setDataValue, keys);
	if (setDataValue.type === "Identifier" || setDataValue.type === "MemberExpression" || setDataValue.type === "CallExpression") {
		setDataProp.value = {
			type: "ObjectExpression",
			properties: [{
				type: "ObjectProperty",
				key: {
					type: "Identifier",
					name: "pick"
				},
				computed: false,
				shorthand: false,
				value: createPickArrayExpression(keys)
			}, {
				type: "SpreadElement",
				argument: setDataValue
			}]
		};
		return true;
	}
	return false;
}
function createScopedSlotHostPropertyDefinition(typeName, value) {
	return {
		type: "ObjectExpression",
		properties: [{
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: "type"
			},
			computed: false,
			shorthand: false,
			value: typeName === "String" ? {
				type: "Identifier",
				name: "String"
			} : { type: "NullLiteral" }
		}, {
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: "value"
			},
			computed: false,
			shorthand: false,
			value: value === null ? { type: "NullLiteral" } : {
				type: "StringLiteral",
				value
			}
		}]
	};
}
function createScopedSlotHostProperties() {
	return [
		{
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: WEVU_SLOT_NAMES_PROP
			},
			computed: false,
			shorthand: false,
			value: createScopedSlotHostPropertyDefinition("null", null)
		},
		{
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: WEVU_SLOT_OWNER_ID_PROP
			},
			computed: false,
			shorthand: false,
			value: createScopedSlotHostPropertyDefinition("String", "")
		},
		{
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: WEVU_SLOT_SCOPE_KEY
			},
			computed: false,
			shorthand: false,
			value: createScopedSlotHostPropertyDefinition("null", null)
		}
	];
}
function injectScopedSlotHostPropertiesIntoObject(propertiesObject) {
	let changed = false;
	for (const prop of createScopedSlotHostProperties().reverse()) {
		const key = prop.key.type === "Identifier" ? prop.key.name : void 0;
		if (!key || getObjectPropertyByKey$1(propertiesObject, key)) continue;
		propertiesObject.properties.unshift(prop);
		changed = true;
	}
	return changed;
}
function injectScopedSlotHostPropertiesIntoOptionsObject(optionsObject) {
	const propertiesProp = getObjectPropertyByKey$1(optionsObject, "properties");
	if (!propertiesProp) {
		optionsObject.properties.unshift({
			type: "ObjectProperty",
			key: {
				type: "Identifier",
				name: "properties"
			},
			computed: false,
			shorthand: false,
			value: {
				type: "ObjectExpression",
				properties: createScopedSlotHostProperties()
			}
		});
		return true;
	}
	const propertiesValue = unwrapExpression(propertiesProp.value);
	if (propertiesValue.type === "ObjectExpression") return injectScopedSlotHostPropertiesIntoObject(propertiesValue);
	if (propertiesValue.type === "Identifier" || propertiesValue.type === "MemberExpression" || propertiesValue.type === "CallExpression") {
		propertiesProp.value = {
			type: "ObjectExpression",
			properties: [{
				type: "SpreadElement",
				argument: propertiesValue
			}, ...createScopedSlotHostProperties()]
		};
		return true;
	}
	return false;
}
function transformTargetWevuOptionsInJs(source, transformOptions, options) {
	if (!mayNeedInjectSetDataPickInJs(source)) return {
		code: source,
		transformed: false
	};
	const ast = parseJsLike(source);
	const candidateOptions = /* @__PURE__ */ new Set();
	traverse(ast, {
		CallExpression(path) {
			const firstArg = path.node.arguments[0];
			if (!firstArg || firstArg.type === "SpreadElement") return;
			const resolvedOptions = t.isExpression(firstArg) ? resolveOptionsObjectExpression(firstArg, path.scope) : null;
			if (resolvedOptions && (isKnownWevuComponentCallee(path.node.callee) || hasCompiledWevuOptionsMarker(resolvedOptions))) candidateOptions.add(resolvedOptions);
		},
		ExportDefaultDeclaration(path) {
			const declaration = path.node.declaration;
			if (!t.isExpression(declaration)) return;
			const resolvedOptions = resolveOptionsObjectExpression(declaration, path.scope);
			if (resolvedOptions) candidateOptions.add(resolvedOptions);
		}
	});
	if (!candidateOptions.size) return {
		code: source,
		transformed: false
	};
	let changed = false;
	for (const optionsObject of candidateOptions) changed = transformOptions(optionsObject) || changed;
	if (!changed) return {
		code: source,
		transformed: false
	};
	const sourceMap = options?.sourceMap !== false;
	const generated = generate$1(ast, {
		retainLines: true,
		sourceMaps: sourceMap,
		sourceFileName: "inline.js"
	}, source);
	return {
		code: generated.code,
		transformed: true,
		map: sourceMap ? generated.map : null
	};
}
/**
* 从编译后的 WXML 模板提取渲染相关的顶层 key。
*/
function collectSetDataPickKeysFromTemplate(template, options) {
	return collectSetDataPickKeysFromTemplateCode(template, options);
}
/**
* 判断 scoped slot 宿主页是否应该跳过大规模模板 bind 自动 pick。
*/
function shouldUseScopedSlotOwnerOnlySetDataPick(pickKeys) {
	let bindKeyCount = 0;
	for (const key of pickKeys) if (key.startsWith(AUTO_BIND_PICK_KEY_PREFIX)) {
		bindKeyCount += 1;
		if (bindKeyCount > SCOPED_SLOT_OWNER_AUTO_PICK_BIND_KEY_LIMIT) return true;
	}
	return false;
}
/**
* 裁剪 scoped slot 宿主页中过量的自动 bind key,同时保留业务状态 key。
*/
function pruneScopedSlotOwnerAutoSetDataPickKeys(pickKeys) {
	if (!shouldUseScopedSlotOwnerOnlySetDataPick(pickKeys)) return pickKeys;
	return pickKeys.filter((key) => !key.startsWith(AUTO_BIND_PICK_KEY_PREFIX));
}
/**
* 在 wevu 组件脚本中注入 setData.pick。
*/
function injectSetDataPickInJs(source, pickKeys, options) {
	const mergedPickKeys = mergeStableKeys(pickKeys, [
		WEVU_SLOT_NAMES_PROP,
		WEVU_SLOT_OWNER_ID_PROP,
		WEVU_SLOT_SCOPE_KEY
	]);
	if (!mergedPickKeys.length) return {
		code: source,
		transformed: false
	};
	return transformTargetWevuOptionsInJs(source, (optionsObject) => injectPickIntoOptionsObject(optionsObject, mergedPickKeys), options);
}
/**
* 只为 scoped slot 宿主首屏同步注入必要的 setData.pick 字段。
*/
function injectScopedSlotOwnerSetDataPickInJs(source, pickKeys = [], options) {
	const mergedPickKeys = mergeStableKeys(pickKeys, [
		WEVU_SLOT_OWNER_ID_KEY,
		WEVU_SLOT_NAMES_PROP,
		WEVU_SLOT_OWNER_ID_PROP,
		WEVU_SLOT_SCOPE_KEY
	]);
	return transformTargetWevuOptionsInJs(source, (optionsObject) => injectPickIntoOptionsObject(optionsObject, mergedPickKeys), options);
}
/**
* 在含有 scoped slot outlet 的 wevu 组件脚本中注入宿主内部属性。
*/
function injectScopedSlotHostPropertiesInJs(source, options) {
	return transformTargetWevuOptionsInJs(source, injectScopedSlotHostPropertiesIntoOptionsObject, options);
}
//#endregion
//#region src/plugins/asset.ts
function normalizeCopyGlobs(globs) {
	return Array.isArray(globs) ? globs : [];
}
function stripQueryAndHash(value) {
	const endIndex = [value.indexOf("?"), value.indexOf("#")].filter((index) => index >= 0).reduce((min, index) => Math.min(min, index), Number.POSITIVE_INFINITY);
	return Number.isFinite(endIndex) ? value.slice(0, endIndex) : value;
}
function createPathMatcher(patterns, options) {
	if (!patterns.length) return () => false;
	return picomatch(patterns.map((pattern) => normalizePath$1(pattern)), options);
}
function createAssetPathVariants(file, roots) {
	const variants = [file];
	for (const root of roots) {
		const relative = path.relative(root, file);
		if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) variants.push(relative);
	}
	return variants.map((variant) => normalizePath$1(variant));
}
function parseJsonBuffer(buffer) {
	try {
		const parsed = JSON.parse(buffer.toString("utf8"));
		if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
		return parsed;
	} catch {
		return;
	}
}
function getScopedSlotGenericKeys(ctx, fileName) {
	const componentBase = `/${toPosixPath(fileName.replace(/\.(?:json|wxml|js)$/, ""))}`;
	return ctx.runtimeState.asset.scopedSlotGenerics.get(componentBase);
}
function withScopedSlotComponentGenerics(ctx, fileName, buffer) {
	const keys = getScopedSlotGenericKeys(ctx, fileName);
	if (!keys?.size) return buffer;
	const parsed = parseJsonBuffer(buffer);
	if (!parsed) return buffer;
	const componentGenerics = parsed.componentGenerics && typeof parsed.componentGenerics === "object" && !Array.isArray(parsed.componentGenerics) ? { ...parsed.componentGenerics } : {};
	for (const key of keys) {
		if (!componentGenerics[key]) {
			componentGenerics[key] = { default: WEAPP_SCOPED_SLOT_GENERIC_COMPONENT_PLACEHOLDER };
			continue;
		}
		if (componentGenerics[key] === true) continue;
		if (typeof componentGenerics[key] === "object" && !Array.isArray(componentGenerics[key])) {
			const value = componentGenerics[key];
			componentGenerics[key] = typeof value.default === "string" && value.default.trim() ? { ...value } : {
				...value,
				default: WEAPP_SCOPED_SLOT_GENERIC_COMPONENT_PLACEHOLDER
			};
			continue;
		}
	}
	parsed.componentGenerics = componentGenerics;
	const normalized = resolveJson({ json: parsed }, void 0, ctx.configService.platform);
	return Buffer.from(normalized ?? JSON.stringify(parsed, null, 2));
}
function createScopedSlotGenericTag(key) {
	return `<${key} wx:if="{{${WEVU_SLOT_OWNER_ID_PROP}}}" ${WEVU_SLOT_OWNER_ID_ATTR}="{{${WEVU_SLOT_OWNER_ID_PROP}}}" ${WEVU_SLOT_PROPS_ATTR}="{{[]}}" ${WEVU_SLOT_SCOPE_ATTR}="{{${WEVU_SLOT_SCOPE_KEY}}}" />`;
}
function createSlotPatchPattern(key) {
	const slotName = key.replace(/^scoped-slots-/, "");
	if (slotName === "default") return /<slot(\s*)\/>|<slot(\s*)><\/slot>/g;
	const escapedSlotName = slotName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
	return new RegExp(`<slot(?=[^>]*\\bname=["']${escapedSlotName}["'])((?:\\s+[^>]*)?)\\/>|<slot(?=[^>]*\\bname=["']${escapedSlotName}["'])((?:\\s+[^>]*)?)><\\/slot>`, "g");
}
function withScopedSlotGenericSlots(ctx, fileName, buffer) {
	const keys = getScopedSlotGenericKeys(ctx, fileName);
	if (!keys?.size || ctx.configService.platform !== "weapp") return buffer;
	let source = buffer.toString("utf8");
	let changed = false;
	for (const key of keys) {
		if (source.includes(`<${key} `) || source.includes(`<${key}>`)) continue;
		const tag = createScopedSlotGenericTag(key);
		source = source.replace(createSlotPatchPattern(key), (matched) => {
			changed = true;
			return `${matched}${tag}`;
		});
	}
	return changed ? Buffer.from(source) : buffer;
}
function createScopedSlotHostPropertiesSource() {
	return `${WEVU_SLOT_NAMES_PROP}: { type: null, value: null }, ${WEVU_SLOT_OWNER_ID_PROP}: { type: String, value: "" }, ${WEVU_SLOT_SCOPE_KEY}: { type: null, value: null }`;
}
function withScopedSlotHostProperties(ctx, fileName, source) {
	if (!getScopedSlotGenericKeys(ctx, fileName)?.size || ctx.configService.platform !== "weapp" || source.includes(WEVU_SLOT_OWNER_ID_PROP)) return source;
	const injected = injectScopedSlotHostPropertiesInJs(source, { sourceMap: false });
	if (injected.transformed) return injected.code;
	const propertySource = createScopedSlotHostPropertiesSource();
	return source.replace(/Component\(\s*\{/, (matched) => `${matched} properties: { ${propertySource} },`);
}
function withScopedSlotHostAsset(ctx, fileName, buffer) {
	if (fileName.endsWith(".json")) return withScopedSlotComponentGenerics(ctx, fileName, buffer);
	if (fileName.endsWith(".wxml")) return withScopedSlotGenericSlots(ctx, fileName, buffer);
	if (fileName.endsWith(".js")) {
		const source = buffer.toString("utf8");
		const next = withScopedSlotHostProperties(ctx, fileName, source);
		return next === source ? buffer : Buffer.from(next);
	}
	return buffer;
}
function patchScopedSlotHostAssetForBundle(ctx, fileName, output) {
	if (output.type === "chunk") {
		const chunk = output;
		const current = chunk.code;
		if (typeof current !== "string") return false;
		if (!getScopedSlotGenericKeys(ctx, fileName)?.size || ctx.configService.platform !== "weapp" || current.includes(WEVU_SLOT_OWNER_ID_PROP)) return false;
		const transformCode = resolveOutputChunkTransformCode(chunk);
		const injected = injectScopedSlotHostPropertiesInJs(transformCode, { sourceMap: Boolean(normalizeEncodedSourceMapLike(chunk.map)) || transformCode !== current });
		if (injected.transformed) return applyOutputChunkTransform(chunk, injected.code, injected.map);
		const propertySource = createScopedSlotHostPropertiesSource();
		return replaceOutputChunkCode(chunk, /Component\(\s*\{/, (match) => `${match[0]} properties: { ${propertySource} },`);
	}
	const current = output.source;
	if (typeof current !== "string" && !Buffer.isBuffer(current) && !(current instanceof Uint8Array)) return false;
	const currentBuffer = Buffer.from(current);
	const next = withScopedSlotHostAsset(ctx, fileName, currentBuffer);
	if (Buffer.compare(currentBuffer, next) === 0) return false;
	output.source = next.toString("utf8");
	return true;
}
function emitScopedSlotGenericPlaceholderAssets(ctx, pluginContext, bundle, fileName) {
	if (!getScopedSlotGenericKeys(ctx, fileName)?.size || ctx.configService.platform !== "weapp") return;
	emitAlipayGenericPlaceholderAssetsByBase(pluginContext, bundle, resolveWeappScopedSlotGenericPlaceholderBase(toPosixPath(fileName.replace(/\.json$/, ""))), ctx.configService.outputExtensions, {
		jsonConfig: {
			component: true,
			options: { virtualHost: true }
		},
		templateSource: "<view wx:if=\"{{false}}\" />"
	});
}
function patchScopedSlotHostAssetsInBundle(ctx, pluginContext, bundle) {
	for (const [fileName, output] of Object.entries(bundle)) {
		if (!/\.(?:json|wxml|js)$/.test(fileName) || !output) continue;
		if (!patchScopedSlotHostAssetForBundle(ctx, fileName, output)) continue;
		if (fileName.endsWith(".json")) emitScopedSlotGenericPlaceholderAssets(ctx, pluginContext, bundle, fileName);
		const source = output.type === "chunk" ? output.code : output.source;
		ctx.runtimeState.asset.emittedBuffer.set(fileName, Buffer.from(source));
	}
}
function collectBundledAssetSourcePaths(bundle) {
	const sources = /* @__PURE__ */ new Set();
	for (const output of Object.values(bundle)) {
		if (!output || output.type !== "asset") continue;
		for (const originalFile of output.originalFileNames ?? []) if (typeof originalFile === "string" && originalFile) sources.add(normalizePath$1(originalFile));
	}
	return sources;
}
function collectAssetModuleSourcePaths(moduleIds) {
	const sources = /* @__PURE__ */ new Set();
	for (const moduleId of moduleIds) {
		if (typeof moduleId !== "string" || !moduleId) continue;
		sources.add(normalizePath$1(stripQueryAndHash(moduleId)));
	}
	return sources;
}
function resolvePendingAssetFiles(files, bundle, getModuleIds) {
	if (!files?.length) return [];
	const bundledSources = collectBundledAssetSourcePaths(bundle);
	const pendingAfterBundle = files.filter((file) => {
		return !bundledSources.has(normalizePath$1(file));
	});
	if (!pendingAfterBundle.length) return [];
	const moduleSources = collectAssetModuleSourcePaths(getModuleIds());
	return pendingAfterBundle.filter((file) => {
		return !moduleSources.has(normalizePath$1(file));
	});
}
function scanAssetFiles(configService, config, buildTarget) {
	const weappViteConfig = configService.weappViteConfig;
	const include = normalizeCopyGlobs(weappViteConfig?.copy?.include);
	const exclude = normalizeCopyGlobs(weappViteConfig?.copy?.exclude);
	const filter = weappViteConfig?.copy?.filter ?? (() => true);
	const ignore = [
		...defaultExcluded,
		path.resolve(configService.cwd, `${config.build.outDir}/**/*`),
		...exclude
	];
	const includeMatcher = createPathMatcher([`**/*.{${defaultAssetExtensions.join(",")}}`, ...include], { dot: false });
	const ignoreMatcher = createPathMatcher(ignore, { dot: true });
	const roots = /* @__PURE__ */ new Set();
	if (buildTarget !== "plugin") roots.add(configService.absoluteSrcRoot);
	if (configService.absolutePluginRoot && buildTarget === "plugin") roots.add(configService.absolutePluginRoot);
	if (!roots.size) return Promise.resolve([]);
	const crawlPromises = Array.from(roots).map((root) => {
		return new fdir({
			includeDirs: false,
			pathSeparator: "/"
		}).withFullPaths().crawl(root).withPromise().then((files) => {
			return files.filter((file) => {
				const variants = createAssetPathVariants(file, [
					root,
					configService.absoluteSrcRoot,
					configService.cwd
				]);
				return variants.some((variant) => includeMatcher(variant)) && !variants.some((variant) => ignoreMatcher(variant));
			});
		});
	});
	return Promise.all(crawlPromises).then((groups) => {
		const files = /* @__PURE__ */ new Set();
		for (const group of groups) for (const file of group) files.add(file);
		return Array.from(files).filter(filter);
	});
}
async function emitAssets(ctx, pluginContext, bundle, files, concurrency) {
	if (!files.length) return;
	const workerCount = Math.min(Number.isFinite(concurrency) && concurrency > 0 ? Math.floor(concurrency) : 8, files.length);
	let index = 0;
	await Promise.all(Array.from({ length: workerCount }).map(async () => {
		while (index < files.length) {
			const file = files[index++];
			const fileName = ctx.configService.relativeOutputPath(file);
			const buffer = withScopedSlotHostAsset(ctx, fileName, await fs$1.readFile(file));
			const previous = ctx.runtimeState.asset.emittedBuffer.get(fileName);
			if (previous && Buffer.compare(previous, buffer) === 0) continue;
			if (fileName.endsWith(".json")) emitScopedSlotGenericPlaceholderAssets(ctx, pluginContext, bundle, fileName);
			pluginContext.emitFile({
				type: "asset",
				fileName,
				source: buffer
			});
			ctx.runtimeState.asset.emittedBuffer.set(fileName, buffer);
		}
	}));
}
function createAssetCollector(state) {
	const { ctx } = state;
	const { configService } = ctx;
	return {
		name: "weapp-vite:asset",
		enforce: "post",
		configResolved(config) {
			state.resolvedConfig = config;
		},
		buildStart() {
			if (!state.resolvedConfig) {
				state.pendingAssets = Promise.resolve([]);
				return;
			}
			state.pendingAssets = scanAssetFiles(configService, state.resolvedConfig, state.buildTarget);
		},
		async generateBundle(_options, bundle) {
			patchScopedSlotHostAssetsInBundle(ctx, this, bundle);
			const pending = resolvePendingAssetFiles(await state.pendingAssets, bundle, () => this.getModuleIds());
			await emitAssets(ctx, this, bundle, pending, 8);
		}
	};
}
function asset(ctx) {
	return [createAssetCollector({
		ctx,
		buildTarget: ctx.currentBuildTarget ?? "app"
	})];
}
const RESOLVED_VIRTUAL_ID = "\0weapp-vite:auto-routes";
/**
* 判断当前是否应按 watch 模式为 auto-routes 注册依赖文件。
*/
function isAutoRoutesWatchMode(configService) {
	return Boolean(configService?.isDev || configService?.inlineConfig?.build?.watch);
}
/**
* 合并 service 与 matcher 提供的监听目录,并去重保留顺序。
*/
function collectAutoRoutesWatchDirs(watchDirectories, matcherWatchRoots) {
	const watchDirs = /* @__PURE__ */ new Set();
	for (const dir of watchDirectories) watchDirs.add(dir);
	for (const dir of matcherWatchRoots) watchDirs.add(dir);
	return [...watchDirs];
}
/**
* 过滤出真正需要交给 auto-routes watcher 处理的路由 Vue 文件。
*/
function isAutoRoutesWatchFile(filePath, allowedExtensions, isPagesRelatedPath) {
	return !isAutoRoutesGeneratedFileName(path.basename(filePath)) && allowedExtensions.has(path.extname(filePath)) && isPagesRelatedPath(filePath);
}
/**
* 判断是否满足 auto-routes sidecar watcher 的启动前置条件。
*/
function shouldStartAutoRoutesWatcher(options) {
	if (options.routeWatcherStarted) return false;
	if (!options.isDev) return false;
	if (!options.autoRoutesEnabled || !options.autoRoutesWatch || !options.serviceEnabled) return false;
	return options.watchDirsLength > 0;
}
/**
* 生成 sidecar watcher map 使用的关闭句柄。
*/
function createAutoRoutesSidecarWatcher(watcher) {
	return { close: () => void watcher.close() };
}
/**
* 向插件上下文注册 auto-routes 相关 watch 目标,忽略单个 addWatchFile 失败。
*/
function addAutoRoutesWatchTargets(pluginCtx, targets) {
	for (const file of targets.files) try {
		pluginCtx.addWatchFile?.(normalizeWatchPath(file));
	} catch {}
	for (const dir of targets.directories) try {
		pluginCtx.addWatchFile?.(normalizeWatchPath(dir));
	} catch {}
}
/**
* 统一解析 auto-routes 虚拟模块与 alias 入口的命中关系。
*/
function resolveAutoRoutesVirtualId(id, aliasTargets) {
	if (id === "weapp-vite/auto-routes" || id === "virtual:weapp-vite-auto-routes" || id === "\0weapp-vite:auto-routes") return RESOLVED_VIRTUAL_ID;
	return aliasTargets.has(id) ? RESOLVED_VIRTUAL_ID : null;
}
/**
* 将 create/delete 这类结构性变化映射为 auto-routes 的全量重扫语义。
*/
function resolveAutoRoutesWatchChangeEvent(event) {
	if (event === "create" || event === "delete") return "rename";
}
/**
* 判断某次热更新是否需要触发 auto-routes 虚拟模块失效。
*/
function resolveAutoRoutesHotUpdateAction(command, options) {
	if (command === "serve") return options.isRouteFile ? {
		shouldHandle: true,
		shouldUpdateRouteFile: true
	} : {
		shouldHandle: false,
		shouldUpdateRouteFile: false
	};
	if (options.isRouteFile || options.isPagesRelatedPath) return {
		shouldHandle: true,
		shouldUpdateRouteFile: false
	};
	return {
		shouldHandle: false,
		shouldUpdateRouteFile: false
	};
}
//#endregion
//#region src/plugins/core/lifecycle/autoRoutesTopology.ts
/**
* 标记 app 入口依赖的 auto-routes 拓扑已变化。
*/
function markAppEntryForAutoRoutesTopology(ctx, options) {
	const appEntryId = ctx.scanService?.appEntry?.path ? normalizeFsResolvedId(ctx.scanService.appEntry.path) : void 0;
	if (appEntryId) invalidateFileCache(appEntryId);
	invalidateFileCache("weapp-vite/auto-routes");
	invalidateFileCache("virtual:weapp-vite-auto-routes");
	invalidateFileCache("\0weapp-vite:auto-routes");
	for (const target of resolveAutoRoutesAliasTargets(ctx.configService?.packageInfo?.rootPath)) invalidateFileCache(normalizeFsResolvedId(target));
	options.loadEntry?.invalidateResolveCache?.();
	ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature = void 0;
	if (!appEntryId || !options.resolvedEntryMap.has(appEntryId)) return false;
	options.markEntryDirty(appEntryId, "direct");
	return true;
}
//#endregion
//#region src/plugins/autoRoutes.ts
/**
* 路由文件监听器的唯一标识,用于在 sidecarWatcherMap 中注册。
*/
const ROUTE_WATCHER_KEY = "__auto-routes-vue-watcher__";
function createAutoRoutesPlugin(ctx) {
	const service = ctx.autoRoutesService;
	let resolvedConfig;
	let devServer;
	const autoRoutesAliasTargets = /* @__PURE__ */ new Set();
	const autoRoutesTopologyDirtyEntries = /* @__PURE__ */ new Set();
	let routeWatcherStarted = false;
	const refreshAutoRoutesAliasTargets = () => {
		autoRoutesAliasTargets.clear();
		for (const target of resolveAutoRoutesAliasTargets(ctx.configService?.packageInfo?.rootPath)) autoRoutesAliasTargets.add(target);
	};
	function isPagesRelatedPath(id) {
		const configService = ctx.configService;
		if (!configService) return false;
		const { autoRoutesConfig, subPackageRoots } = resolveAutoRoutesMatcherContext(ctx);
		return isAutoRoutesPagesRelatedPath(id, {
			cwd: configService.cwd,
			absoluteSrcRoot: configService.absoluteSrcRoot,
			include: autoRoutesConfig.include,
			managedOutputPaths: resolveAutoRoutesManagedOutputPaths(ctx),
			subPackageRoots
		});
	}
	/**
	* 启动 chokidar 监听 pages 目录下的路由文件增删。
	* Rolldown 的 watcher 不会为新建文件触发 watchChange,
	* 因此需要独立的文件监听来补偿。
	*
	* 注意:chokidar v5 在 macOS 上使用 glob 模式时无法检测新建文件,
	* 必须直接监听目录,然后在事件回调中按扩展名过滤。
	*
	* 生命周期:watcher 注册到 sidecarWatcherMap,由 watcherService.closeAll()
	* 统一回收,不在 closeBundle 中销毁(build watch 模式下 closeBundle 每次
	* 重编译都会触发,提前销毁会导致后续文件变更无法感知)。
	*/
	function invalidateAutoRoutesVirtualModule() {
		const server = devServer;
		const virtualModule = server?.moduleGraph.getModuleById(RESOLVED_VIRTUAL_ID);
		if (!virtualModule || !server) return;
		const seen = /* @__PURE__ */ new Set();
		const invalidateModuleWithImporters = (module) => {
			if (seen.has(module)) return;
			seen.add(module);
			server.moduleGraph.invalidateModule(module);
			for (const importer of module.importers) invalidateModuleWithImporters(importer);
		};
		invalidateModuleWithImporters(virtualModule);
	}
	function markAutoRoutesTopologyDirty() {
		return markAppEntryForAutoRoutesTopology(ctx, {
			resolvedEntryMap: ctx.runtimeState.build.hmr.resolvedEntryMap,
			markEntryDirty(entryId) {
				const hmr = ctx.runtimeState.build.hmr;
				autoRoutesTopologyDirtyEntries.add(entryId);
				hmr.dirtyEntrySet.add(entryId);
				hmr.dirtyEntryReasons.set(entryId, "direct");
				hmr.loadedEntrySet.delete(entryId);
				hmr.dirtyVueEntryIds ??= /* @__PURE__ */ new Set();
				hmr.dirtyVueEntryIds.add(entryId);
			}
		});
	}
	function notifyAppEntryChange() {
		const appEntryPath = ctx.scanService?.appEntry?.path;
		if (!appEntryPath || !devServer) return;
		devServer.watcher.emit("change", appEntryPath);
	}
	async function handleRouteStructureChange(filePath, event) {
		if (await service.handleFileChange(filePath, event)) {
			invalidateAutoRoutesVirtualModule();
			markAutoRoutesTopologyDirty();
			notifyAppEntryChange();
		}
	}
	function startRouteFileWatcher() {
		const configService = ctx.configService;
		if (!configService) return;
		const { autoRoutesConfig, matcher: resolvedMatcher } = resolveAutoRoutesMatcherContext(ctx);
		const allowedExtensions = new Set(vueExtensions.map((ext) => `.${ext}`));
		const watchDirs = collectAutoRoutesWatchDirs(service.getWatchDirectories(), resolvedMatcher.getWatchRoots(configService.absoluteSrcRoot));
		if (!shouldStartAutoRoutesWatcher({
			routeWatcherStarted,
			isDev: configService.isDev,
			autoRoutesEnabled: autoRoutesConfig.enabled,
			autoRoutesWatch: autoRoutesConfig.watch,
			serviceEnabled: service.isEnabled(),
			watchDirsLength: watchDirs.length
		})) return;
		const watcher = chokidar.watch(watchDirs, createSidecarWatchOptions(configService, {
			ignoreInitial: true,
			persistent: true,
			awaitWriteFinish: {
				stabilityThreshold: 80,
				pollInterval: 20
			}
		}));
		watcher.on("add", (filePath) => {
			if (!isAutoRoutesWatchFile(filePath, allowedExtensions, isPagesRelatedPath)) return;
			logger_default.info(`[auto-routes:watch] 新增路由文件 ${configService.relativeCwd(filePath)}`);
			handleRouteStructureChange(filePath, "create");
		});
		watcher.on("unlink", (filePath) => {
			if (!isAutoRoutesWatchFile(filePath, allowedExtensions, isPagesRelatedPath)) return;
			logger_default.info(`[auto-routes:watch] 删除路由文件 ${configService.relativeCwd(filePath)}`);
			handleRouteStructureChange(filePath, "delete");
		});
		const { sidecarWatcherMap } = ctx.runtimeState.watcher;
		sidecarWatcherMap.set(ROUTE_WATCHER_KEY, createAutoRoutesSidecarWatcher(watcher));
		routeWatcherStarted = true;
	}
	return {
		name: "weapp-vite:auto-routes",
		enforce: "pre",
		configResolved(config) {
			resolvedConfig = config;
			refreshAutoRoutesAliasTargets();
		},
		configureServer(server) {
			devServer = server;
		},
		buildStart() {
			refreshAutoRoutesAliasTargets();
			startRouteFileWatcher();
		},
		resolveId(id) {
			const startedAt = performance.now();
			try {
				return resolveAutoRoutesVirtualId(id, autoRoutesAliasTargets);
			} finally {
				const profile = ctx.runtimeState?.build?.hmr?.profile;
				recordHmrProfileDuration(profile, "pluginResolveMs", performance.now() - startedAt);
				recordHmrProfileOperation(profile, "resolveCount");
			}
		},
		async load(id) {
			if (resolveAutoRoutesVirtualId(id, autoRoutesAliasTargets) !== "\0weapp-vite:auto-routes") return null;
			await service.ensureFresh();
			if (isAutoRoutesWatchMode(ctx.configService)) addAutoRoutesWatchTargets(this, {
				files: service.getWatchFiles(),
				directories: service.getWatchDirectories()
			});
			startRouteFileWatcher();
			return {
				code: service.getModuleCode(),
				map: { mappings: "" }
			};
		},
		shouldTransformCachedModule({ id }) {
			return autoRoutesTopologyDirtyEntries.delete(id) || void 0;
		},
		async watchChange(id, change) {
			const event = change?.event;
			if (service.isRouteFile(id)) {
				if (resolvedConfig?.command === "serve" && event === "update") return;
				await service.handleFileChange(id, event);
				return;
			}
			if (!isPagesRelatedPath(id)) return;
			const resolvedEvent = resolveAutoRoutesWatchChangeEvent(event);
			if (resolvedEvent) await service.handleFileChange(id, resolvedEvent);
		},
		async handleHotUpdate(context) {
			const routeFile = service.isRouteFile(context.file);
			const hotUpdateAction = resolveAutoRoutesHotUpdateAction(resolvedConfig?.command, {
				isRouteFile: routeFile,
				isPagesRelatedPath: routeFile ? false : isPagesRelatedPath(context.file)
			});
			if (!hotUpdateAction.shouldHandle) return;
			let didChangeRoutes = false;
			if (hotUpdateAction.shouldUpdateRouteFile) didChangeRoutes = await service.handleFileChange(context.file, "update");
			if (resolvedConfig?.command === "serve" && routeFile && !didChangeRoutes) return;
			const virtualModule = context.server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_ID);
			if (virtualModule) return [virtualModule];
			return context.modules.filter((module) => module.id === RESOLVED_VIRTUAL_ID);
		}
	};
}
function autoRoutes(ctx) {
	return [createAutoRoutesPlugin(ctx)];
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/autoImport.ts
const GLOB_WILDCARD_RE = /[*?[{]/;
const AUTO_IMPORT_LOCAL_EXTENSIONS = [
	"vue",
	"wxml",
	"js",
	"ts",
	"json"
];
function toPascalTagName(name) {
	if (!name.includes("-")) return name;
	return name.split("-").filter(Boolean).map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("");
}
function resolveAutoImportGlobBase(glob, absoluteSrcRoot) {
	const wildcardIndex = glob.search(GLOB_WILDCARD_RE);
	const trimmed = (wildcardIndex >= 0 ? glob.slice(0, wildcardIndex) : glob).replace(/\/+$/, "");
	const base = path.extname(trimmed) ? path.dirname(trimmed) : trimmed;
	if (!base || base === ".") return absoluteSrcRoot;
	return path.isAbsolute(base) ? base : path.resolve(absoluteSrcRoot, base);
}
function collectAutoImportGlobExtensions(glob) {
	return AUTO_IMPORT_LOCAL_EXTENSIONS.filter((ext) => glob.includes(`.${ext}`));
}
function collectLocalCandidatePaths(componentName, globs, absoluteSrcRoot) {
	const names = /* @__PURE__ */ new Set([
		componentName,
		toPascalTagName(componentName),
		toKebabCaseComponentName(componentName)
	]);
	const candidates = /* @__PURE__ */ new Set();
	for (const glob of globs) {
		const extensions = collectAutoImportGlobExtensions(glob);
		if (!extensions.length) continue;
		const base = resolveAutoImportGlobBase(glob, absoluteSrcRoot);
		for (const name of names) for (const ext of extensions) {
			candidates.add(path.join(base, name, `index.${ext}`));
			candidates.add(path.join(base, `${name}.${ext}`));
		}
	}
	return [...candidates];
}
async function registerExistingLocalCandidates(options) {
	const { autoImportService, configService, componentNames } = options;
	if (!configService || typeof autoImportService.registerPotentialComponent !== "function") return false;
	const globs = getAutoImportConfig(configService)?.globs;
	if (!globs?.length) return false;
	let registered = false;
	const candidates = /* @__PURE__ */ new Set();
	for (const componentName of componentNames) for (const candidate of collectLocalCandidatePaths(componentName, globs, configService.absoluteSrcRoot)) candidates.add(candidate);
	for (const candidate of candidates) {
		if (!await fs$1.pathExists(candidate)) continue;
		await autoImportService.registerPotentialComponent(candidate);
		registered = true;
	}
	return registered;
}
function createAutoImportAugmenter(autoImportService, wxmlService, externalComponentEntryMap, configService) {
	const cache = /* @__PURE__ */ new Map();
	function injectResolvedComponents(json, resolvedComponents) {
		const injectedEntries = [];
		for (const [name, resolved] of Object.entries(resolvedComponents)) {
			const trackResolvedId = () => {
				if (resolved.resolvedId) externalComponentEntryMap?.set(resolved.from.replace(/^\/+/, ""), resolved.resolvedId);
			};
			const usingComponents = get(json, "usingComponents");
			if (isObject(usingComponents) && Reflect.has(usingComponents, name)) {
				if (usingComponents[name] === resolved.from) {
					trackResolvedId();
					injectedEntries.push(resolved.from);
				}
				continue;
			}
			set(json, `usingComponents.${name}`, resolved.from);
			injectedEntries.push(resolved.from);
			trackResolvedId();
		}
		return injectedEntries;
	}
	return function applyAutoImports(baseName, json, retryMissing = true) {
		const hit = wxmlService.getAggregatedAutoImportComponents?.(baseName) ?? wxmlService.getAggregatedComponents(baseName);
		if (!hit) return [];
		const version = autoImportService.getVersion();
		const cached = cache.get(baseName);
		if (cached && cached.hit === hit && cached.version === version) return injectResolvedComponents(json, cached.resolvedComponents);
		const resolvedComponents = {};
		const missingComponentNames = [];
		for (const depComponentName of Object.keys(hit)) {
			const match = autoImportService.resolve(depComponentName, baseName);
			if (!match) {
				missingComponentNames.push(depComponentName);
				continue;
			}
			resolvedComponents[match.value.name] = {
				from: match.value.from,
				resolvedId: match.value.resolvedId
			};
		}
		cache.set(baseName, {
			hit,
			version,
			resolvedComponents
		});
		if (missingComponentNames.length && retryMissing && configService && typeof autoImportService.registerPotentialComponent === "function") return registerExistingLocalCandidates({
			autoImportService,
			configService,
			componentNames: missingComponentNames
		}).then((registered) => {
			if (!registered) return injectResolvedComponents(json, resolvedComponents);
			return applyAutoImports(baseName, json, false);
		});
		return injectResolvedComponents(json, resolvedComponents);
	};
}
//#endregion
//#region src/plugins/utils/outputFileName.ts
/**
* 统一生成相对输出文件名,避免各插件重复拼接。
*/
function resolveRelativeOutputFileName(configService, filePath) {
	return configService.relativeOutputPath(filePath);
}
/**
* 基于源码路径生成带目标扩展名的相对输出文件名。
*/
function resolveRelativeOutputFileNameWithExtension(configService, filePath, extension) {
	return changeFileExtension(resolveRelativeOutputFileName(configService, filePath), extension);
}
/**
* 统一处理 json 入口可能残留的 `.js` 后缀。
*/
function resolveRelativeJsonOutputFileName(configService, filePath) {
	return resolveRelativeOutputFileName(configService, jsonFileRemoveJsExtension(filePath));
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/chunkEmitter.ts
function createChunkEmitter(configService, loadedEntrySet, debug, trackEmittedEntryId, trackEmittedChunkId, shouldEmitEntryChunk, preloadAssetOnlyEntry, trackEmittedChunkFileName, trackChunkEmitStats, resolveEntryChunkId = (_entryId, resolvedId) => resolvedId.id) {
	return function emitEntriesChunks(resolvedIds) {
		return resolvedIds.map(async (resolvedId) => {
			const stats = {
				chunkEmitCount: 0,
				emitFileMs: 0,
				loadCount: 0,
				loadMs: 0,
				skippedLoadedCount: 0
			};
			if (!resolvedId) return stats;
			const normalizedId = normalizeFsResolvedId(resolvedId.id);
			const entryChunkId = resolveEntryChunkId(normalizedId, resolvedId);
			const shouldPreload = !loadedEntrySet.has(normalizedId);
			if (!shouldPreload) stats.skippedLoadedCount += 1;
			loadedEntrySet.add(normalizedId);
			const start = shouldPreload ? performance$1.now() : 0;
			const shouldEmitChunk = shouldEmitEntryChunk?.(normalizedId, resolvedId) ?? true;
			if (shouldPreload) {
				const loadStartedAt = performance$1.now();
				if (!shouldEmitChunk && preloadAssetOnlyEntry) await preloadAssetOnlyEntry.call(this, resolvedId, normalizedId);
				else await this.load({ id: entryChunkId });
				stats.loadCount += 1;
				stats.loadMs += performance$1.now() - loadStartedAt;
			}
			const fileName = resolveRelativeOutputFileNameWithExtension(configService, resolvedId.id, ".js");
			if (shouldEmitChunk) {
				const emitFileStartedAt = performance$1.now();
				this.emitFile({
					type: "chunk",
					id: entryChunkId,
					fileName,
					preserveSignature: "exports-only"
				});
				trackEmittedChunkId?.(normalizedId);
				trackEmittedChunkFileName?.(fileName);
				stats.chunkEmitCount += 1;
				stats.emitFileMs += performance$1.now() - emitFileStartedAt;
			}
			trackEmittedEntryId?.(normalizedId);
			if (shouldPreload) debug?.(`load ${fileName} 耗时 ${(performance$1.now() - start).toFixed(2)}ms`);
			trackChunkEmitStats?.(stats);
			return stats;
		});
	};
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/extendedLib.ts
const EXTENDED_LIB_DESCRIPTORS = { weui: { componentPrefixes: ["weui-miniprogram/"] } };
function isBareSpecifier(value) {
	return Boolean(value) && !value.startsWith(".") && !value.startsWith("/");
}
function createExtendedLibManager() {
	let enabledLibs = /* @__PURE__ */ new Set();
	return {
		syncFromAppJson(json) {
			const nextEnabled = /* @__PURE__ */ new Set();
			const extendedLib = json?.useExtendedLib;
			if (isObject(extendedLib)) for (const [libName, enabled] of Object.entries(extendedLib)) {
				if (!enabled) continue;
				if (EXTENDED_LIB_DESCRIPTORS[libName]) nextEnabled.add(libName);
			}
			enabledLibs = nextEnabled;
		},
		shouldIgnoreEntry(entry) {
			if (!isBareSpecifier(entry) || entry.includes(":") || enabledLibs.size === 0) return false;
			for (const libName of enabledLibs) {
				const descriptor = EXTENDED_LIB_DESCRIPTORS[libName];
				if (!descriptor) continue;
				if (descriptor.componentPrefixes.some((prefix) => entry === prefix || entry.startsWith(prefix))) return true;
			}
			return false;
		}
	};
}
//#endregion
//#region src/runtime/appConfig.ts
function finalizeAppConfigForBuild(config, options) {
	return applyBuildScopeToAppConfig(applyPreloadRulesToAppJson(normalizeAppJson(config), options.routeRules, options.platform), resolveBuildScope(options.buildScope));
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/jsonEmit.ts
function createJsonEmitManager(configService) {
	const map = /* @__PURE__ */ new Map();
	function register(entry) {
		if (!entry.jsonPath && !entry.fileName) return;
		const fileName = entry.fileName ?? resolveRelativeJsonOutputFileName(configService, entry.jsonPath);
		const shouldNormalizeAppJson = entry.type === "app" && fileName === "app.json";
		const weappViteConfig = configService.weappViteConfig ?? {};
		const normalizedEntry = shouldNormalizeAppJson ? {
			...entry,
			json: finalizeAppConfigForBuild(entry.json, {
				buildScope: weappViteConfig.buildScope,
				platform: configService.platform,
				routeRules: weappViteConfig.routeRules
			})
		} : entry;
		map.set(fileName, {
			fileName,
			entry: normalizedEntry
		});
	}
	return {
		map,
		register
	};
}
//#endregion
//#region src/runtime/storeVueSfcHmrSignatures.ts
/**
* 把编译器生成的 SFC 语义快照注册到 Vite HMR 运行状态。
*/
function storeVueSfcHmrSignatures(hmr, filename, signatures) {
	if (signatures.blockSignatures) hmr.vueEntrySfcSignatures.set(filename, signatures.blockSignatures);
	if (signatures.tailwindContentSignature) hmr.vueEntryTailwindContentSignatures.set(filename, signatures.tailwindContentSignature);
	if (signatures.tailwindTemplateContentSignature) hmr.vueEntryTailwindTemplateContentSignatures.set(filename, signatures.tailwindTemplateContentSignature);
	if (signatures.tailwindScriptContentSignature) hmr.vueEntryTailwindScriptContentSignatures.set(filename, signatures.tailwindScriptContentSignature);
	if (signatures.hasTemplate !== void 0) hmr.vueEntryHasTemplate.set(filename, signatures.hasTemplate);
}
//#endregion
//#region src/plugins/utils/analyze.ts
function collectPluginExportEntries(plugins, root) {
	if (!isObject(plugins)) return [];
	const entries = [];
	for (const plugin of Object.values(plugins)) {
		if (!isObject(plugin)) continue;
		const exportPath = typeof plugin.export === "string" ? plugin.export.trim() : "";
		if (!exportPath) continue;
		const normalized = removeExtension(exportPath);
		entries.push(root ? path.join(root, normalized) : normalized);
	}
	return entries;
}
function analyzeAppJson(json) {
	const entries = [];
	const pages = json.pages ?? [];
	const components = Object.values(get(json, "usingComponents") ?? {});
	const subPackages = [...json.subPackages ?? [], ...json.subpackages ?? []].filter((x) => !x.independent).reduce((acc, cur) => {
		acc.push(...(cur.pages ?? []).map((x) => `${cur.root}/${x}`));
		if (cur.entry) acc.push(`${cur.root}/${removeExtension(cur.entry)}`);
		acc.push(...collectPluginExportEntries(get(cur, "plugins"), cur.root));
		return acc;
	}, []) ?? [];
	if (get(json, "tabBar.custom")) entries.push("custom-tab-bar/index");
	if (get(json, "appBar")) entries.push("app-bar/index");
	entries.push(...collectPluginExportEntries(get(json, "plugins")));
	entries.push(...pages, ...components, ...subPackages);
	return entries;
}
function analyzePluginJson(json) {
	const entries = [];
	const main = json.main;
	const pages = Object.values(get(json, "pages") ?? {});
	const publicComponents = Object.values(get(json, "publicComponents") ?? {});
	entries.push(...pages, ...publicComponents);
	main && entries.push(main);
	return entries;
}
function analyzeCommonJson(json) {
	const entries = [];
	const components = Object.values(get(json, "usingComponents") ?? {});
	entries.push(...components);
	return entries;
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/shared.ts
const CAMEL_TO_KEBAB_RE = /([a-z0-9])([A-Z])/g;
const LAYOUT_NAME_SEPARATORS_RE = /[_\s]+/g;
const DUPLICATE_DASH_RE = /-+/g;
const EDGE_DASH_RE = /^-|-$/g;
const PATH_SEGMENT_RE$1 = /[\\/]/;
function normalizeComparablePath(input) {
	const resolved = path.resolve(input);
	try {
		return toPosixPath(fs.realpathSync.native(resolved));
	} catch {
		const suffixParts = [];
		let cursor = resolved;
		let parent = path.dirname(cursor);
		while (parent !== cursor && !fs.existsSync(cursor)) {
			suffixParts.unshift(path.basename(cursor));
			cursor = parent;
			parent = path.dirname(cursor);
		}
		try {
			const normalizedBase = toPosixPath(fs.realpathSync.native(cursor));
			return suffixParts.length > 0 ? toPosixPath(path.join(normalizedBase, ...suffixParts)) : normalizedBase;
		} catch {
			return toPosixPath(resolved);
		}
	}
}
function toKebabCase(input) {
	return input.replace(CAMEL_TO_KEBAB_RE, "$1-$2").replace(LAYOUT_NAME_SEPARATORS_RE, "-").replace(DUPLICATE_DASH_RE, "-").replace(EDGE_DASH_RE, "").toLowerCase();
}
function normalizeLayoutName(input) {
	return input.split(PATH_SEGMENT_RE$1).filter(Boolean).map((segment) => toKebabCase(segment)).filter(Boolean).join("-");
}
function toLayoutTagName(layoutName) {
	return `weapp-layout-${layoutName}`;
}
function escapeDoubleQuotedAttr(value) {
	return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
}
function removeFileExtension(filename) {
	const ext = path.extname(filename);
	return ext ? filename.slice(0, -ext.length) : filename;
}
function getLayoutConditionalDirective(index, directivePrefix = getWxmlDirectivePrefix()) {
	return `${directivePrefix}:${index === 0 ? "if" : "elif"}`;
}
function getLayoutElseDirective(directivePrefix = getWxmlDirectivePrefix()) {
	return `${directivePrefix}:else`;
}
function getPlatformLayoutConditionalDirective(index, platform) {
	return getLayoutConditionalDirective(index, getWxmlDirectivePrefix(platform));
}
function getPlatformLayoutElseDirective(platform) {
	return getLayoutElseDirective(getWxmlDirectivePrefix(platform));
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/template.ts
function toKebabAttrName(key) {
	return toKebabCase(key);
}
const LAYOUT_SLOT_OWNER_ATTR = `${WEVU_SLOT_OWNER_ID_ATTR}="{{${WEVU_SLOT_OWNER_ID_PROP} || ${WEVU_SLOT_OWNER_ID_KEY} || ''}}"`;
function hasDynamicExpressionLayoutProps(props) {
	if (!props) return false;
	return Object.values(props).some((value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "expression");
}
function serializeLayoutProps(props) {
	const attrs = [LAYOUT_SLOT_OWNER_ATTR];
	if (!props || Object.keys(props).length === 0) return ` ${attrs.join(" ")}`;
	attrs.push(...Object.entries(props).map(([key, value]) => {
		const attrName = toKebabAttrName(key);
		if (typeof value === "string") return `${attrName}="${escapeDoubleQuotedAttr(value)}"`;
		if (typeof value === "object" && value && "kind" in value && value.kind === "expression") return `${attrName}="{{${WEVU_LAYOUT_BIND_PREFIX}${key}}}"`;
		if (typeof value === "number" || typeof value === "boolean" || value === null) return `${attrName}="{{${String(value)}}}"`;
		return "";
	}).filter(Boolean));
	return attrs.length > 0 ? ` ${attrs.join(" ")}` : "";
}
function collapseNestedLayoutWrapper(template, tagName) {
	const closeTag = `</${tagName}>`;
	let next = template;
	while (next.startsWith(`<${tagName}`) && next.endsWith(closeTag)) {
		const openTagEnd = next.indexOf(">");
		if (openTagEnd < 0) break;
		const inner = next.slice(openTagEnd + 1, -closeTag.length);
		if (!inner.startsWith(`<${tagName}`)) break;
		next = inner;
	}
	return next;
}
function serializeFallbackLayoutValue(value, keyName) {
	if (value === void 0) return `(${WEVU_PAGE_LAYOUT_PROPS_KEY}&&${WEVU_PAGE_LAYOUT_PROPS_KEY}.${keyName})`;
	if (typeof value === "object" && value && "kind" in value && value.kind === "expression") return `(${WEVU_PAGE_LAYOUT_PROPS_KEY}&&${WEVU_PAGE_LAYOUT_PROPS_KEY}.${keyName})!==undefined?${WEVU_PAGE_LAYOUT_PROPS_KEY}.${keyName}:${WEVU_LAYOUT_BIND_PREFIX}${keyName}`;
	return `(${WEVU_PAGE_LAYOUT_PROPS_KEY}&&${WEVU_PAGE_LAYOUT_PROPS_KEY}.${keyName})!==undefined?${WEVU_PAGE_LAYOUT_PROPS_KEY}.${keyName}:${JSON.stringify(value)}`;
}
function buildDynamicLayoutAttrs(propKeys, currentLayout) {
	const attrs = [LAYOUT_SLOT_OWNER_ATTR];
	if (propKeys.length === 0) return ` ${attrs.join(" ")}`;
	attrs.push(...propKeys.map((key) => {
		return `${toKebabAttrName(key)}="{{${serializeFallbackLayoutValue(currentLayout?.props?.[key], key)}}}"`;
	}));
	return ` ${attrs.join(" ")}`;
}
function buildDynamicLayoutTemplate(innerTemplate, currentLayout, layouts, propKeys, platform) {
	return `${layouts.map((layout, index) => {
		const attrs = buildDynamicLayoutAttrs(propKeys, currentLayout);
		const condition = currentLayout?.layoutName === layout.layoutName ? `{{!${WEVU_PAGE_LAYOUT_NAME_KEY} || ${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}` : `{{${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`;
		return `<block ${getPlatformLayoutConditionalDirective(index, platform)}="${condition}"><${layout.tagName}${attrs}>${innerTemplate}</${layout.tagName}></block>`;
	}).join("")}<block ${getPlatformLayoutElseDirective(platform)}>${innerTemplate}</block>`;
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/apply/config.ts
function mergeLayoutUsingComponent(config, tagName, importPath) {
	const parsed = config ? JSON.parse(config) : {};
	const usingComponents = parsed.usingComponents && typeof parsed.usingComponents === "object" && !Array.isArray(parsed.usingComponents) ? parsed.usingComponents : {};
	usingComponents[tagName] = importPath;
	parsed.usingComponents = usingComponents;
	return JSON.stringify(parsed, null, 2);
}
function mergeLayoutUsingComponents(config, layouts) {
	let next = config;
	for (const layout of layouts) next = mergeLayoutUsingComponent(next, layout.tagName, layout.importPath);
	return next;
}
function mergeSingleLayoutUsingComponent(config, layout) {
	return mergeLayoutUsingComponent(config, layout.tagName, layout.importPath);
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/ast.ts
function stripTypeSyntaxFromAst(ast) {
	traverse(ast, {
		CallExpression(path) {
			if (path.node.typeParameters) path.node.typeParameters = null;
		},
		NewExpression(path) {
			if (path.node.typeParameters) path.node.typeParameters = null;
		},
		TSAsExpression(path) {
			path.replaceWith(path.node.expression);
		},
		TSSatisfiesExpression(path) {
			path.replaceWith(path.node.expression);
		},
		TSTypeAssertion(path) {
			path.replaceWith(path.node.expression);
		},
		TSNonNullExpression(path) {
			path.replaceWith(path.node.expression);
		}
	});
}
function parseExpressionAst(expression) {
	const file = parse$3(`const __wv_layout_expr__ = ${expression}`, BABEL_TS_MODULE_PARSER_OPTIONS$1);
	stripTypeSyntaxFromAst(file);
	const stmt = file.program.body[0];
	if (!stmt || !t.isVariableDeclaration(stmt)) return null;
	const declarator = stmt.declarations[0];
	if (!declarator || !declarator.init || !t.isExpression(declarator.init)) return null;
	return declarator.init;
}
function createStaticObjectKey(key) {
	return t.isValidIdentifier(key) ? t.identifier(key) : t.stringLiteral(key);
}
function getObjectPropertyByKey(node, key) {
	for (const prop of node.properties) {
		if (!t.isObjectProperty(prop) || prop.computed) continue;
		if (t.isIdentifier(prop.key) && prop.key.name === key || t.isStringLiteral(prop.key) && prop.key.value === key) return prop;
	}
	return null;
}
function findWevuOptionsObject(ast) {
	let matched = null;
	traverse(ast, {
		VariableDeclarator(path) {
			if (!t.isIdentifier(path.node.id, { name: "__wevuOptions" }) || !t.isObjectExpression(path.node.init)) return;
			matched = path.node.init;
			path.stop();
		},
		ExportDefaultDeclaration(path) {
			if (matched || !t.isObjectExpression(path.node.declaration)) return;
			matched = path.node.declaration;
			path.stop();
		}
	});
	return matched;
}
function findNativePageOptionsObject(ast) {
	let matched = null;
	traverse(ast, { CallExpression(path) {
		if (!t.isIdentifier(path.node.callee, { name: "Page" })) return;
		const firstArg = path.node.arguments[0];
		if (!firstArg || t.isSpreadElement(firstArg) || !t.isObjectExpression(firstArg)) return;
		matched = firstArg;
		path.stop();
	} });
	return matched;
}
function stripDefinePageMetaCalls(ast) {
	let mutated = false;
	traverse(ast, { ExpressionStatement(path) {
		const expression = path.node.expression;
		if (!t.isCallExpression(expression) || !t.isIdentifier(expression.callee, { name: "definePageMeta" })) return;
		mutated = true;
		path.remove();
	} });
	return mutated;
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/apply/script.ts
function injectLayoutBindingComputed(script, props) {
	if (!script || !props) return script;
	const runtimeEntries = Object.entries(props).filter((entry) => typeof entry[1] === "object" && entry[1] !== null && "kind" in entry[1] && entry[1].kind === "expression");
	if (runtimeEntries.length === 0) return script;
	const ast = parse$3(script, BABEL_TS_MODULE_PARSER_OPTIONS$1);
	const optionsObject = findWevuOptionsObject(ast);
	if (!optionsObject) return script;
	const computedEntries = runtimeEntries.map(([key, value]) => {
		const expressionAst = parseExpressionAst(value.expression) ?? t.identifier("undefined");
		return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`), t.functionExpression(null, [], t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(expressionAst)]), t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER), t.blockStatement([t.returnStatement(t.identifier("undefined"))])), null)])));
	});
	const computedProp = getObjectPropertyByKey(optionsObject, "computed");
	if (!computedProp) optionsObject.properties.unshift(t.objectProperty(createStaticObjectKey("computed"), t.objectExpression(computedEntries)));
	else if (t.isObjectExpression(computedProp.value)) computedProp.value.properties.push(...computedEntries);
	else if (t.isIdentifier(computedProp.value) || t.isMemberExpression(computedProp.value)) computedProp.value = t.objectExpression([...computedEntries, t.spreadElement(t.cloneNode(computedProp.value, true))]);
	else return script;
	return generate$1(ast, { retainLines: true }).code;
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/apply/native.ts
function injectNativePageLayoutSetter(pageOptions) {
	if (getObjectPropertyByKey(pageOptions, WEVU_PAGE_LAYOUT_SETTER_KEY)) return;
	pageOptions.properties.push(t.objectMethod("method", createStaticObjectKey(WEVU_PAGE_LAYOUT_SETTER_KEY), [t.identifier("layout"), t.identifier("props")], t.blockStatement([
		t.variableDeclaration("const", [t.variableDeclarator(t.identifier(WEVU_PAGE_LAYOUT_NEXT_NAME_IDENTIFIER), t.conditionalExpression(t.binaryExpression("===", t.identifier("layout"), t.booleanLiteral(false)), t.stringLiteral(WEVU_PAGE_LAYOUT_NONE), t.identifier("layout")))]),
		t.variableDeclaration("const", [t.variableDeclarator(t.identifier(WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER), t.conditionalExpression(t.binaryExpression("===", t.identifier("layout"), t.booleanLiteral(false)), t.objectExpression([]), t.logicalExpression("||", t.identifier("props"), t.objectExpression([]))))]),
		t.variableDeclaration("const", [t.variableDeclarator(t.identifier(WEVU_PAGE_LAYOUT_CURRENT_NAME_IDENTIFIER), t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier("data")), t.identifier(WEVU_PAGE_LAYOUT_NAME_KEY)))]),
		t.variableDeclaration("const", [t.variableDeclarator(t.identifier(WEVU_PAGE_LAYOUT_CURRENT_PROPS_IDENTIFIER), t.logicalExpression("||", t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier("data")), t.identifier(WEVU_PAGE_LAYOUT_PROPS_KEY)), t.objectExpression([])))]),
		t.ifStatement(t.logicalExpression("&&", t.binaryExpression("===", t.identifier(WEVU_PAGE_LAYOUT_CURRENT_NAME_IDENTIFIER), t.identifier(WEVU_PAGE_LAYOUT_NEXT_NAME_IDENTIFIER)), t.callExpression(t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [t.identifier(WEVU_PAGE_LAYOUT_CURRENT_PROPS_IDENTIFIER)]), t.identifier("every")), [t.arrowFunctionExpression([t.identifier(WEVU_INTERNAL_KEY_IDENTIFIER)], t.logicalExpression("&&", t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Object"), t.identifier("prototype")), t.identifier("hasOwnProperty")), t.identifier("call")), [t.identifier(WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER), t.identifier(WEVU_INTERNAL_KEY_IDENTIFIER)]), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("is")), [t.memberExpression(t.identifier(WEVU_PAGE_LAYOUT_CURRENT_PROPS_IDENTIFIER), t.identifier(WEVU_INTERNAL_KEY_IDENTIFIER), true), t.memberExpression(t.identifier(WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER), t.identifier(WEVU_INTERNAL_KEY_IDENTIFIER), true)])))])), t.blockStatement([t.ifStatement(t.binaryExpression("===", t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [t.identifier(WEVU_PAGE_LAYOUT_CURRENT_PROPS_IDENTIFIER)]), t.identifier("length")), t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [t.identifier(WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER)]), t.identifier("length"))), t.blockStatement([t.returnStatement()]))])),
		t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("setData")), [t.objectExpression([t.objectProperty(t.identifier(WEVU_PAGE_LAYOUT_NAME_KEY), t.identifier(WEVU_PAGE_LAYOUT_NEXT_NAME_IDENTIFIER)), t.objectProperty(t.identifier(WEVU_PAGE_LAYOUT_PROPS_KEY), t.identifier(WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER))])]))
	])));
}
function toStaticLayoutValueExpression(value) {
	if (typeof value === "string") return t.stringLiteral(value);
	if (typeof value === "number") return t.numericLiteral(value);
	if (typeof value === "boolean") return t.booleanLiteral(value);
	if (value === null) return t.nullLiteral();
	return t.identifier("undefined");
}
function buildInitialNativePageLayoutState(currentLayout) {
	const layoutName = currentLayout?.layoutName;
	const layoutProps = currentLayout?.props ?? {};
	return t.objectExpression([t.objectProperty(t.identifier(WEVU_PAGE_LAYOUT_NAME_KEY), layoutName ? t.stringLiteral(layoutName) : t.identifier("undefined")), t.objectProperty(t.identifier(WEVU_PAGE_LAYOUT_PROPS_KEY), t.objectExpression(Object.entries(layoutProps).filter(([, value]) => !(typeof value === "object" && value && "kind" in value && value.kind === "expression")).map(([key, value]) => t.objectProperty(createStaticObjectKey(key), toStaticLayoutValueExpression(value)))))]);
}
function buildInitialNativePageLayoutNameExpression(currentLayout) {
	return currentLayout?.layoutName ? t.stringLiteral(currentLayout.layoutName) : t.identifier("undefined");
}
function buildInitialNativePageLayoutPropsExpression(currentLayout) {
	const layoutProps = currentLayout?.props ?? {};
	return t.objectExpression(Object.entries(layoutProps).filter(([, value]) => !(typeof value === "object" && value && "kind" in value && value.kind === "expression")).map(([key, value]) => t.objectProperty(createStaticObjectKey(key), toStaticLayoutValueExpression(value))));
}
function injectNativePageLayoutState(pageOptions, currentLayout) {
	const initialState = buildInitialNativePageLayoutState(currentLayout);
	const existingData = getObjectPropertyByKey(pageOptions, "data");
	if (!existingData) {
		pageOptions.properties.unshift(t.objectProperty(createStaticObjectKey("data"), initialState));
		return;
	}
	if (t.isObjectExpression(existingData.value)) {
		const dataObject = existingData.value;
		const layoutNameProp = getObjectPropertyByKey(dataObject, WEVU_PAGE_LAYOUT_NAME_KEY);
		const layoutPropsProp = getObjectPropertyByKey(dataObject, WEVU_PAGE_LAYOUT_PROPS_KEY);
		if (!layoutNameProp) dataObject.properties.unshift(t.objectProperty(t.identifier(WEVU_PAGE_LAYOUT_NAME_KEY), buildInitialNativePageLayoutNameExpression(currentLayout)));
		if (!layoutPropsProp) dataObject.properties.push(t.objectProperty(t.identifier(WEVU_PAGE_LAYOUT_PROPS_KEY), buildInitialNativePageLayoutPropsExpression(currentLayout)));
		return;
	}
	existingData.value = t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("assign")), [
		t.objectExpression([]),
		existingData.value,
		initialState
	]);
}
function injectNativePageLayoutRuntime(script, filename, plan) {
	if (!script) return script;
	const ast = parse$3(script, BABEL_TS_MODULE_PARSER_OPTIONS$1);
	stripTypeSyntaxFromAst(ast);
	const strippedMeta = stripDefinePageMetaCalls(ast);
	const shouldInjectSetter = Boolean(plan?.dynamicSwitch);
	if (!shouldInjectSetter && !strippedMeta) return script;
	if (!shouldInjectSetter) return generate$1(ast, { retainLines: true }).code;
	const pageOptions = findNativePageOptionsObject(ast);
	if (!pageOptions) throw new Error(`${filename} 中未找到可注入 layout 运行时的 Page({}) 定义。`);
	injectNativePageLayoutState(pageOptions, plan?.currentLayout);
	injectNativePageLayoutSetter(pageOptions);
	return generate$1(ast, { retainLines: true }).code;
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/apply/index.ts
function hasDynamicLayoutTemplateWrapper(template, plan, platform) {
	const firstDirective = getPlatformLayoutConditionalDirective(0, platform);
	if (!plan.layouts.length || !template.startsWith(`<block ${firstDirective}=`)) return false;
	return plan.layouts.every((layout, index) => {
		const condition = plan.currentLayout?.layoutName === layout.layoutName ? `{{!${WEVU_PAGE_LAYOUT_NAME_KEY} || ${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}` : `{{${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`;
		const directive = getPlatformLayoutConditionalDirective(index, platform);
		return template.includes(`<block ${directive}="${condition}"><${layout.tagName}`);
	}) && template.includes(`<block ${getPlatformLayoutElseDirective(platform)}>`);
}
function applyPageLayout(result, _filename, layout) {
	if (!layout || !result.template) return result;
	const serializedProps = serializeLayoutProps(layout.props);
	if (result.template.startsWith(`<${layout.tagName}`)) {
		result.template = collapseNestedLayoutWrapper(result.template, layout.tagName);
		result.script = injectLayoutBindingComputed(result.script, layout.props);
		result.config = mergeSingleLayoutUsingComponent(result.config, layout);
		return result;
	}
	result.template = `<${layout.tagName}${serializedProps}>${result.template}</${layout.tagName}>`;
	result.script = injectLayoutBindingComputed(result.script, layout.props);
	result.config = mergeSingleLayoutUsingComponent(result.config, layout);
	return result;
}
function applyPageLayoutPlan(result, filename, plan, options) {
	if (!plan || !result.template) return result;
	if (!plan.dynamicSwitch) return applyPageLayout(result, filename, plan.currentLayout);
	if (hasDynamicLayoutTemplateWrapper(result.template, plan, options?.platform)) {
		result.script = injectLayoutBindingComputed(result.script, plan.currentLayout?.props);
		result.config = mergeLayoutUsingComponents(result.config, plan.layouts);
		return result;
	}
	result.template = buildDynamicLayoutTemplate(result.template, plan.currentLayout, plan.layouts, plan.dynamicPropKeys, options?.platform);
	result.script = injectLayoutBindingComputed(result.script, plan.currentLayout?.props);
	result.config = mergeLayoutUsingComponents(result.config, plan.layouts);
	return result;
}
function applyPageLayoutPlanToNativePage(result, filename, plan, options) {
	if (!plan || !result.template) return result;
	if (hasDynamicExpressionLayoutProps(plan.currentLayout?.props)) throw new Error(`${filename} 中原生 Page 的 layout.props 暂不支持表达式,请改用静态字面量或在运行时调用 setPageLayout()。`);
	return applyPageLayoutPlan(result, filename, plan, options);
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/meta.ts
const PAGE_META_MACRO_NAME = "definePageMeta";
const analyzedPageLayoutSourceCache = /* @__PURE__ */ new Map();
function unwrapStaticExpression(node) {
	if (t.isTSAsExpression(node) || t.isTSSatisfiesExpression(node) || t.isTSNonNullExpression(node) || t.isTypeCastExpression(node)) return unwrapStaticExpression(node.expression);
	if (t.isParenthesizedExpression(node)) return unwrapStaticExpression(node.expression);
	return node;
}
function extractStaticLayoutPropValue(node, filename, keyName) {
	const normalized = unwrapStaticExpression(node);
	if (t.isStringLiteral(normalized)) return normalized.value;
	if (t.isNumericLiteral(normalized)) return normalized.value;
	if (t.isBooleanLiteral(normalized)) return normalized.value;
	if (t.isNullLiteral(normalized)) return null;
	const expression = generate$1(normalized, { compact: true }).code;
	if (!expression) throw new Error(`${filename} 中 definePageMeta().layout.props.${keyName} 无法解析为表达式。`);
	return {
		kind: "expression",
		expression
	};
}
function extractLayoutPropsFromObject(node, filename) {
	const props = {};
	for (const property of node.properties) {
		if (!t.isObjectProperty(property) || property.computed || !t.isExpression(property.value)) throw new Error(`${filename} 中 definePageMeta().layout.props 仅支持普通对象字面量。`);
		const key = property.key;
		const keyName = t.isIdentifier(key) ? key.name : t.isStringLiteral(key) ? key.value : void 0;
		if (!keyName) throw new Error(`${filename} 中 definePageMeta().layout.props 仅支持静态键名。`);
		props[keyName] = extractStaticLayoutPropValue(property.value, filename, keyName);
	}
	return props;
}
function extractLayoutValueFromObject(node, filename) {
	let layout;
	for (const property of node.properties) {
		if (!t.isObjectProperty(property) || property.computed) continue;
		const key = property.key;
		if (!(t.isIdentifier(key) && key.name === "layout" || t.isStringLiteral(key) && key.value === "layout") || !t.isExpression(property.value)) continue;
		const normalized = unwrapStaticExpression(property.value);
		if (t.isBooleanLiteral(normalized, { value: false })) {
			layout = { disabled: true };
			continue;
		}
		if (t.isStringLiteral(normalized)) {
			const next = normalizeLayoutName(normalized.value);
			if (!next) throw new Error(`${filename} 中 definePageMeta().layout 不能为空字符串。`);
			layout = { name: next };
			continue;
		}
		if (t.isObjectExpression(normalized)) {
			let nextName;
			let nextProps;
			for (const nestedProperty of normalized.properties) {
				if (!t.isObjectProperty(nestedProperty) || nestedProperty.computed || !t.isExpression(nestedProperty.value)) throw new Error(`${filename} 中 definePageMeta().layout 对象仅支持静态字面量字段。`);
				const nestedKey = nestedProperty.key;
				const nestedKeyName = t.isIdentifier(nestedKey) ? nestedKey.name : t.isStringLiteral(nestedKey) ? nestedKey.value : void 0;
				if (!nestedKeyName) throw new Error(`${filename} 中 definePageMeta().layout 对象仅支持静态键名。`);
				if (nestedKeyName === "name") {
					const nameValue = unwrapStaticExpression(nestedProperty.value);
					if (!t.isStringLiteral(nameValue)) throw new Error(`${filename} 中 definePageMeta().layout.name 必须是静态字符串。`);
					const normalizedName = normalizeLayoutName(nameValue.value);
					if (!normalizedName) throw new Error(`${filename} 中 definePageMeta().layout.name 不能为空字符串。`);
					nextName = normalizedName;
					continue;
				}
				if (nestedKeyName === "props") {
					const propsValue = unwrapStaticExpression(nestedProperty.value);
					if (!t.isObjectExpression(propsValue)) throw new Error(`${filename} 中 definePageMeta().layout.props 必须是对象字面量。`);
					nextProps = extractLayoutPropsFromObject(propsValue, filename);
					continue;
				}
			}
			if (!nextName) throw new Error(`${filename} 中 definePageMeta().layout 对象必须提供 name 字段。`);
			layout = {
				name: nextName,
				props: nextProps
			};
			continue;
		}
		throw new Error(`${filename} 中 definePageMeta().layout 仅支持静态字符串、false,或 { name, props } 对象。`);
	}
	return layout;
}
function extractLayoutFromProgram(ast, filename) {
	let layout;
	let macroCount = 0;
	for (const statement of ast.program.body) {
		if (!t.isExpressionStatement(statement) || !t.isCallExpression(statement.expression)) continue;
		const call = statement.expression;
		if (!t.isIdentifier(call.callee, { name: PAGE_META_MACRO_NAME })) continue;
		macroCount += 1;
		if (call.arguments.length !== 1) throw new Error(`${filename} 中 definePageMeta() 必须且只能接收一个对象参数。`);
		const firstArg = call.arguments[0];
		if (t.isSpreadElement(firstArg) || !t.isExpression(firstArg)) throw new Error(`${filename} 中 definePageMeta() 仅支持对象字面量参数。`);
		const normalized = unwrapStaticExpression(firstArg);
		if (!t.isObjectExpression(normalized)) throw new Error(`${filename} 中 definePageMeta() 仅支持对象字面量参数。`);
		layout = extractLayoutValueFromObject(normalized, filename);
	}
	if (macroCount > 1) throw new Error(`${filename} 中 definePageMeta() 只能声明一次。`);
	return layout;
}
function hasSetPageLayoutCallInProgram(ast) {
	let matched = false;
	traverse(ast, { CallExpression(path) {
		if (t.isIdentifier(path.node.callee, { name: "setPageLayout" })) {
			matched = true;
			path.stop();
		}
	} });
	return matched;
}
function collectSetPageLayoutPropKeysFromProgram(ast) {
	const keys = /* @__PURE__ */ new Set();
	traverse(ast, { CallExpression(path) {
		if (!t.isIdentifier(path.node.callee, { name: "setPageLayout" })) return;
		const secondArg = path.node.arguments[1];
		if (!secondArg || t.isSpreadElement(secondArg) || !t.isObjectExpression(secondArg)) return;
		for (const property of secondArg.properties) {
			if (!t.isObjectProperty(property) || property.computed) continue;
			const key = property.key;
			const keyName = t.isIdentifier(key) ? key.name : t.isStringLiteral(key) ? key.value : void 0;
			if (keyName) keys.add(keyName);
		}
	} });
	return [...keys];
}
function parseScriptAst(content) {
	return parse$3(content, BABEL_TS_MODULE_PARSER_OPTIONS$1);
}
function analyzeVueScriptBlocks(source, filename) {
	const { descriptor } = parse$1(source, { filename });
	return {
		descriptor,
		scriptAst: descriptor.script?.content ? parseScriptAst(descriptor.script.content) : void 0,
		scriptSetupAst: descriptor.scriptSetup?.content ? parseScriptAst(descriptor.scriptSetup.content) : void 0
	};
}
function analyzePageLayoutSourceUncached(source, filename) {
	if (filename.endsWith(".vue")) {
		const { scriptAst, scriptSetupAst } = analyzeVueScriptBlocks(source, filename);
		let layoutMeta;
		if (scriptAst) layoutMeta = extractLayoutFromProgram(scriptAst, filename);
		if (scriptSetupAst) {
			const setupLayout = extractLayoutFromProgram(scriptSetupAst, filename);
			if (layoutMeta !== void 0 && setupLayout !== void 0) throw new Error(`${filename} 中的 <script> 与 <script setup> 不能同时声明 definePageMeta().`);
			if (setupLayout !== void 0) layoutMeta = setupLayout;
		}
		const dynamicSwitch = Boolean(scriptAst && hasSetPageLayoutCallInProgram(scriptAst) || scriptSetupAst && hasSetPageLayoutCallInProgram(scriptSetupAst));
		const dynamicPropKeys = dynamicSwitch ? Array.from(/* @__PURE__ */ new Set([...scriptAst ? collectSetPageLayoutPropKeysFromProgram(scriptAst) : [], ...scriptSetupAst ? collectSetPageLayoutPropKeysFromProgram(scriptSetupAst) : []])) : [];
		return {
			layoutMeta,
			dynamicSwitch,
			dynamicPropKeys
		};
	}
	const ast = parseScriptAst(source);
	const dynamicSwitch = hasSetPageLayoutCallInProgram(ast);
	return {
		layoutMeta: extractLayoutFromProgram(ast, filename),
		dynamicSwitch,
		dynamicPropKeys: dynamicSwitch ? collectSetPageLayoutPropKeysFromProgram(ast) : []
	};
}
function analyzePageLayoutSource(source, filename) {
	const cached = analyzedPageLayoutSourceCache.get(filename);
	if (cached?.source === source) return cached.result;
	const result = analyzePageLayoutSourceUncached(source, filename);
	analyzedPageLayoutSourceCache.set(filename, {
		source,
		result
	});
	return result;
}
function invalidatePageLayoutSourceAnalysisCache(filename) {
	if (!filename) {
		analyzedPageLayoutSourceCache.clear();
		return;
	}
	analyzedPageLayoutSourceCache.delete(filename);
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/resolve.ts
const VUE_LIKE_EXTENSIONS = [
	".vue",
	".tsx",
	".jsx"
];
const PATH_SEGMENT_RE = /[\\/]/;
const TRAILING_INDEX_RE = /\/index$/;
const LEADING_SLASHES_RE = /^\/+/;
const ROUTE_RULE_GLOB_TOKEN_RE = /[*?[\]{}()!+@]/g;
const resolvedLayoutsCache = /* @__PURE__ */ new Map();
const PAGE_META_HINT = "definePageMeta";
const SET_PAGE_LAYOUT_HINT = "setPageLayout";
function normalizePageRouteCandidates(filename, configService) {
	const fullPath = `/${toPosixPath(configService.relativeOutputPath(removeFileExtension(filename))).replace(LEADING_SLASHES_RE, "")}`;
	const shorthand = (() => {
		let next = fullPath;
		if (next.startsWith("/pages/")) next = next.slice(6);
		else next = next.replace("/pages/", "/");
		next = next.replace(TRAILING_INDEX_RE, "");
		return next === "" ? "/" : next;
	})();
	return Array.from(/* @__PURE__ */ new Set([shorthand, fullPath]));
}
function normalizeRouteRuleLayoutMeta(input) {
	if (input === false) return { disabled: true };
	if (typeof input === "string") return { name: normalizeLayoutName(input) };
	if (!input || typeof input !== "object") return;
	const record = input;
	return {
		name: typeof record.name === "string" ? normalizeLayoutName(record.name) : void 0,
		props: record.props && typeof record.props === "object" ? record.props : void 0,
		disabled: record.disabled === true
	};
}
function compareRuleScore(left, right) {
	const maxLength = Math.max(left.length, right.length);
	for (let index = 0; index < maxLength; index += 1) {
		const leftValue = left[index] ?? 0;
		const rightValue = right[index] ?? 0;
		if (leftValue === rightValue) continue;
		return leftValue > rightValue ? 1 : -1;
	}
	return 0;
}
function resolveRouteRuleLayoutMeta(filename, configService) {
	const routeRules = configService.weappViteConfig?.routeRules;
	if (!routeRules) return;
	const routeCandidates = normalizePageRouteCandidates(filename, configService);
	let matched;
	for (const [pattern, rule] of Object.entries(routeRules)) {
		if (!routeCandidates.some((candidate) => picomatch(pattern)(candidate))) continue;
		const normalizedMeta = normalizeRouteRuleLayoutMeta(rule?.appLayout);
		const patternSegments = pattern.split("/").filter(Boolean);
		const wildcardMatches = pattern.match(ROUTE_RULE_GLOB_TOKEN_RE) ?? [];
		const score = [
			patternSegments.filter((segment) => !ROUTE_RULE_GLOB_TOKEN_RE.test(segment)).length,
			pattern.replace(ROUTE_RULE_GLOB_TOKEN_RE, "").length,
			-wildcardMatches.length,
			patternSegments.length,
			pattern.length
		];
		if (!matched || compareRuleScore(score, matched.score) > 0) matched = {
			meta: normalizedMeta,
			score
		};
	}
	return matched?.meta;
}
async function collectLayoutFiles(root) {
	const layoutMap = /* @__PURE__ */ new Map();
	const comparableRoot = normalizeComparablePath(root);
	async function walk(dir) {
		let entries;
		try {
			entries = await fs$1.readdir(dir);
		} catch {
			return;
		}
		for (const entry of entries) {
			const full = path.join(dir, entry);
			if ((await fs$1.stat(full)).isDirectory()) {
				await walk(full);
				continue;
			}
			if (!VUE_LIKE_EXTENSIONS.some((ext) => full.endsWith(ext))) {
				const templateEntry = await findTemplateEntry(full);
				if (!templateEntry.path || templateEntry.path !== full) continue;
				const base = full.slice(0, -path.extname(full).length);
				if (!(await findJsonEntry(base)).path) continue;
				const parts = path.relative(comparableRoot, normalizeComparablePath(base)).split(PATH_SEGMENT_RE).filter(Boolean);
				if (parts[parts.length - 1] === "index") parts.pop();
				const layoutName = normalizeLayoutName(parts.join("/"));
				if (!layoutName) continue;
				const duplicated = layoutMap.get(layoutName);
				if (duplicated && duplicated.file !== base) throw new Error(`layouts 目录中存在重复布局名 "${layoutName}":${duplicated.file} 与 ${base}`);
				layoutMap.set(layoutName, {
					file: base,
					kind: "native",
					layoutName,
					tagName: toLayoutTagName(layoutName)
				});
				continue;
			}
			const relativePath = path.relative(comparableRoot, normalizeComparablePath(full));
			const ext = path.extname(relativePath);
			const parts = relativePath.slice(0, -ext.length).split(PATH_SEGMENT_RE).filter(Boolean);
			if (parts[parts.length - 1] === "index") parts.pop();
			const layoutName = normalizeLayoutName(parts.join("/"));
			if (!layoutName) continue;
			const duplicated = layoutMap.get(layoutName);
			if (duplicated && duplicated.file !== full) throw new Error(`layouts 目录中存在重复布局名 "${layoutName}":${duplicated.file} 与 ${full}`);
			layoutMap.set(layoutName, {
				file: full,
				kind: "vue",
				layoutName,
				tagName: toLayoutTagName(layoutName)
			});
		}
	}
	await walk(root);
	return layoutMap;
}
async function resolveAllLayouts(configService) {
	const cacheKey = normalizeComparablePath(configService.absoluteSrcRoot);
	const cached = resolvedLayoutsCache.get(cacheKey);
	if (cached) return await cached;
	const task = (async () => {
		const layoutFiles = await collectLayoutFiles(path.join(configService.absoluteSrcRoot, "layouts"));
		const resolvedLayouts = [];
		for (const layoutFile of layoutFiles.values()) {
			const importPath = usingComponentFromResolvedFile(layoutFile.file, configService);
			if (!importPath) continue;
			resolvedLayouts.push({
				...layoutFile,
				importPath
			});
		}
		return resolvedLayouts;
	})();
	resolvedLayoutsCache.set(cacheKey, task);
	try {
		return await task;
	} catch (error) {
		resolvedLayoutsCache.delete(cacheKey);
		throw error;
	}
}
function invalidateResolvedPageLayoutsCache(absoluteSrcRoot) {
	invalidatePageLayoutSourceAnalysisCache();
	if (!absoluteSrcRoot) {
		resolvedLayoutsCache.clear();
		return;
	}
	resolvedLayoutsCache.delete(normalizeComparablePath(absoluteSrcRoot));
}
async function resolvePageLayoutPlan(source, filename, configService) {
	const hasPageMetaHint = source.includes(PAGE_META_HINT);
	const hasDynamicLayoutHint = source.includes(SET_PAGE_LAYOUT_HINT);
	const analyzedSource = hasPageMetaHint || hasDynamicLayoutHint ? analyzePageLayoutSource(source, filename) : void 0;
	const layoutMeta = (hasPageMetaHint ? analyzedSource?.layoutMeta : void 0) ?? resolveRouteRuleLayoutMeta(filename, configService);
	const dynamicSwitch = hasDynamicLayoutHint ? Boolean(analyzedSource?.dynamicSwitch) : false;
	if (layoutMeta?.disabled && !dynamicSwitch) return;
	const layouts = await resolveAllLayouts(configService);
	const layoutMap = new Map(layouts.map((layout) => [layout.layoutName, layout]));
	const defaultLayout = layoutMap.get("default");
	const selectedName = typeof layoutMeta?.name === "string" ? layoutMeta.name : defaultLayout?.layoutName;
	if (typeof selectedName === "string" && !layoutMap.has(selectedName)) throw new Error(`${filename} 指定的 layout "${selectedName}" 不存在,请检查 ${path.join(configService.absoluteSrcRoot, "layouts")} 目录。`);
	const currentLayout = selectedName ? {
		...layoutMap.get(selectedName),
		props: layoutMeta?.props
	} : void 0;
	if (!currentLayout && !dynamicSwitch) return;
	return {
		currentLayout,
		dynamicSwitch,
		layouts,
		dynamicPropKeys: dynamicSwitch ? Array.from(/* @__PURE__ */ new Set([...Object.keys(currentLayout?.props ?? {}), ...analyzedSource?.dynamicPropKeys ?? []])) : []
	};
}
function isLayoutFile(filename, configService) {
	const layoutsRoot = `${normalizeWatchPath(path.join(configService.absoluteSrcRoot, "layouts"))}/`;
	return normalizeWatchPath(filename).startsWith(layoutsRoot);
}
async function collectNativeLayoutAssets(basePath, platform) {
	const [jsonEntry, templateEntry, styleEntry, scriptEntry] = await Promise.all([
		findJsonEntry(basePath),
		findTemplateEntry(basePath, platform),
		findCssEntry(basePath, platform),
		findJsEntry(basePath)
	]);
	return {
		json: jsonEntry.path,
		template: templateEntry.path,
		style: styleEntry.path,
		script: scriptEntry.path
	};
}
//#endregion
//#region src/plugins/vue/transform/pageLayout/slot.ts
const SLOT_OPEN_TAG_RE = /<slot\b([^>]*)>/gi;
const DEFAULT_SLOT_NAME_RE = /(?:^|\s)name\s*=/;
function hasDefaultSlotTemplate(template) {
	if (!template) return false;
	for (const match of template.matchAll(SLOT_OPEN_TAG_RE)) {
		const attrs = match[1] ?? "";
		if (!DEFAULT_SLOT_NAME_RE.test(attrs)) return true;
	}
	return false;
}
function assertTemplateHasDefaultSlot(options) {
	if (hasDefaultSlotTemplate(options.template)) return;
	if (options.kind === "app-shell") throw new Error(`${options.filename} 中 app.vue <template> 必须包含默认 <slot />,否则页面内容无法渲染到应用外壳内。`);
	throw new Error(`${options.filename} 对应的 layout template 必须包含默认 <slot />,否则页面内容无法渲染到布局内。`);
}
//#endregion
//#region src/plugins/utils/layoutEntries.ts
async function registerResolvedPageLayoutEntries(options) {
	const { layouts, entries, explicitEntryTypes, nativeScriptEntries, normalizeEntry, jsonPath, platform } = options;
	for (const layout of layouts) {
		if (layout.kind === "native") {
			if (!(await collectNativeLayoutAssets(layout.file, platform)).script) continue;
		}
		entries.push(layout.importPath);
		const normalizedEntry = normalizeEntry(layout.importPath, jsonPath);
		explicitEntryTypes.set(normalizedEntry, "component");
		if (layout.kind === "native") nativeScriptEntries?.add(normalizedEntry);
	}
}
function markComponentEntries(entriesMap, entries) {
	for (const entry of entries) {
		const mapped = entriesMap.get(entry);
		if (mapped) mapped.type = "component";
	}
}
//#endregion
//#region src/plugins/utils/pageLayout.ts
async function expandResolvedPageLayoutFiles(layouts, platform) {
	const files = [];
	for (const layout of layouts) {
		if (layout.kind !== "native") {
			files.push(layout.file);
			continue;
		}
		const nativeAssets = await collectNativeLayoutAssets(layout.file, platform);
		for (const asset of Object.values(nativeAssets)) if (asset) files.push(asset);
	}
	return files;
}
async function registerResolvedPageLayoutDependencies(ctx, ownerId, layouts) {
	const dependencies = await expandResolvedPageLayoutFiles(layouts, ctx.configService.platform);
	const transitiveDependencies = new Set(dependencies);
	for (const file of dependencies) {
		if (!isTemplate(file)) continue;
		await ctx.wxmlService?.scan(file);
		for (const dependency of ctx.wxmlService?.depsMap.get(file) ?? []) transitiveDependencies.add(dependency);
	}
	ctx.moduleGraphService.replaceEntryDependencies(ownerId, "layout", transitiveDependencies);
}
//#endregion
//#region src/plugins/utils/scriptlessVueLayout.ts
const WEVU_TEMPLATE_RUNTIME_BINDING_ATTR_RE = /(?:^|[\s<])(?:ref|:ref|v-bind:ref|layout-host|:layout-host|v-bind:layout-host)\s*=/;
function hasWevuTemplateRuntimeBindings(template) {
	return typeof template === "string" && WEVU_TEMPLATE_RUNTIME_BINDING_ATTR_RE.test(template);
}
function isDefineComponentJsonOnlyScript(content) {
	const ast = parse$3(content, BABEL_TS_MODULE_PARSER_OPTIONS$1);
	let hasDefineComponentJson = false;
	for (const statement of ast.program.body) {
		if (t.isEmptyStatement(statement)) continue;
		if (!t.isExpressionStatement(statement) || !t.isCallExpression(statement.expression)) return false;
		const call = statement.expression;
		if (!t.isIdentifier(call.callee, { name: "defineComponentJson" })) return false;
		hasDefineComponentJson = true;
	}
	return hasDefineComponentJson;
}
function shouldEmitScriptlessVueLayoutJs(source, filename) {
	const { descriptor } = parse$1(source, { filename });
	if (hasWevuTemplateRuntimeBindings(descriptor.template?.content)) return false;
	const blocks = [descriptor.script?.content, descriptor.scriptSetup?.content].filter((content) => typeof content === "string" && content.trim().length > 0);
	if (blocks.length === 0) return true;
	return blocks.every(isDefineComponentJsonOnlyScript);
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/loadEntry/app.ts
function createJsonSignature(value) {
	let raw = "";
	try {
		raw = JSON.stringify(value) ?? "";
	} catch {
		raw = String(value ?? "");
	}
	return createHash("sha256").update(raw).digest("hex").slice(0, 12);
}
async function collectAppEntries(options) {
	const { pluginCtx, id, json, ctx, isPluginBuild, registerJsonAsset, existsCache, pathExistsTtlMs, normalizeEntry, resolveEntryWithCache, extendedLibManager, cache } = options;
	const { jsonService, configService, scanService } = ctx;
	const entries = [];
	const appSignature = createJsonSignature(json);
	const useCache = configService.isDev && !isPluginBuild;
	let pluginResolvedRecords;
	let pluginEntryTypes;
	let pluginJsonPathForRegistration;
	let pluginJsonForRegistration;
	let pluginSignature;
	let appJson;
	if (!isPluginBuild) {
		extendedLibManager.syncFromAppJson(json);
		await Promise.all([collectAppSideFiles(pluginCtx, id, json, jsonService, registerJsonAsset, existsCache, pathExistsTtlMs), collectMiniappConfigFile(pluginCtx, id, configService, jsonService, registerJsonAsset, existsCache, pathExistsTtlMs)]);
	}
	const pluginJsonPath = scanService?.pluginJsonPath;
	if (isPluginBuild && configService.absolutePluginRoot && pluginJsonPath) {
		pluginCtx.addWatchFile(normalizeWatchPath(pluginJsonPath));
		const pluginJson = await jsonService.read(pluginJsonPath);
		if (pluginJson && typeof pluginJson === "object") {
			pluginSignature = createJsonSignature(pluginJson);
			if (scanService) scanService.pluginJson = pluginJson;
			pluginJsonPathForRegistration = pluginJsonPath;
			pluginJsonForRegistration = pluginJson;
		}
	}
	if (useCache && cache?.current) {
		const cached = cache.current;
		const pluginPathMatches = cached.pluginJsonPath === pluginJsonPath;
		const pluginSignatureMatches = cached.pluginSignature === pluginSignature;
		if (cached.appSignature === appSignature && pluginPathMatches && pluginSignatureMatches) return {
			entries: cached.entries,
			appJson: cached.appJson,
			pluginResolvedRecords: cached.pluginResolvedRecords,
			pluginEntryTypes: cached.pluginEntryTypes,
			pluginJsonPathForRegistration: cached.pluginJsonPathForRegistration,
			pluginJsonForRegistration: cached.pluginJsonForRegistration,
			appSignature,
			pluginSignature,
			pluginJsonPath,
			cacheHit: true
		};
	}
	if (!isPluginBuild) {
		appJson = finalizeAppConfigForBuild(json, {
			buildScope: configService.weappViteConfig.buildScope,
			platform: configService.platform,
			routeRules: configService.weappViteConfig.routeRules
		});
		entries.push(...analyzeAppJson(appJson));
	}
	if (isPluginBuild && pluginJsonForRegistration && pluginJsonPathForRegistration) {
		const pluginPages = Object.values(get(pluginJsonForRegistration, "pages") ?? {});
		const pluginComponents = Object.values(get(pluginJsonForRegistration, "publicComponents") ?? {});
		const pluginEntries = analyzePluginJson(pluginJsonForRegistration);
		const pluginBaseDir = path.dirname(pluginJsonPathForRegistration);
		const rootEntry = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(id));
		pluginEntryTypes = [...pluginPages.map((entry) => ({
			entry: normalizeEntry(entry, pluginJsonPathForRegistration),
			type: "page"
		})), ...pluginComponents.map((entry) => ({
			entry: normalizeEntry(entry, pluginJsonPathForRegistration),
			type: "component"
		}))];
		pluginResolvedRecords = (await Promise.all(pluginEntries.map(async (entry) => {
			const normalizedEntry = normalizeEntry(entry, pluginJsonPathForRegistration);
			if (removeExtensionDeep(normalizedEntry) === rootEntry) return null;
			if (normalizedEntry.includes(":")) return null;
			const absPath = path.resolve(pluginBaseDir, entry);
			return {
				entry: normalizedEntry,
				resolvedId: await resolveEntryWithCache(pluginCtx, absPath)
			};
		}))).filter((record) => Boolean(record));
	}
	if (useCache && cache) cache.current = {
		appSignature,
		appJson,
		pluginSignature,
		pluginJsonPath,
		entries: [...entries],
		pluginResolvedRecords,
		pluginEntryTypes,
		pluginJsonPathForRegistration,
		pluginJsonForRegistration
	};
	return {
		entries,
		appJson,
		pluginResolvedRecords,
		pluginEntryTypes,
		pluginJsonPathForRegistration,
		pluginJsonForRegistration,
		appSignature,
		pluginSignature,
		pluginJsonPath,
		cacheHit: false
	};
}
//#endregion
//#region src/plugins/outputFinalizer/pageLayout.ts
const nativePageLayoutOutputs = /* @__PURE__ */ new WeakMap();
function registerNativePageLayoutOutput(options) {
	const { configService, runtimeState, pageId, templatePath, plan } = options;
	const { templateExtension } = resolveCompilerOutputExtensions(configService.outputExtensions);
	const fileName = resolveRelativeOutputFileNameWithExtension(configService, templatePath, templateExtension);
	const outputs = nativePageLayoutOutputs.get(runtimeState) ?? /* @__PURE__ */ new Map();
	if (plan) {
		outputs.set(fileName, {
			pageId,
			plan
		});
		nativePageLayoutOutputs.set(runtimeState, outputs);
	} else outputs.delete(fileName);
}
function restoreNativePageLayoutOutputs(ctx, bundle) {
	const outputs = nativePageLayoutOutputs.get(ctx.runtimeState);
	if (!outputs?.size) return;
	for (const [fileName, { pageId, plan }] of outputs) {
		const output = bundle[fileName];
		if (output?.type !== "asset") continue;
		const transformed = applyPageLayoutPlanToNativePage({ template: typeof output.source === "string" ? output.source : Buffer.from(output.source).toString("utf8") }, pageId, plan, { platform: ctx.configService.platform });
		if (transformed.template) output.source = transformed.template;
	}
}
//#endregion
//#region src/plugins/utils/invalidateEntry/cssGraph.ts
const importProtocols = /^(?:https?:|data:|blob:|\/)/i;
const cssImportRE = /@(?:import|wv-keep-import|use|forward)\s+(?:url\()?['"]?([^'")\s]+)['"]?\)?/gi;
function ensureCssGraph(ctx) {
	const graph = ctx.runtimeState?.css;
	if (!graph?.importerToDependencies || !graph.dependencyToImporters) return;
	return graph;
}
function cleanupImporterGraph(ctx, importer) {
	const graph = ensureCssGraph(ctx);
	if (!graph) return;
	const normalizedImporter = normalizePath$1(importer);
	const existingDeps = graph.importerToDependencies.get(normalizedImporter);
	if (!existingDeps) return;
	graph.importerToDependencies.delete(normalizedImporter);
	for (const dep of existingDeps) {
		const importers = graph.dependencyToImporters.get(dep);
		if (!importers) continue;
		importers.delete(normalizedImporter);
		if (importers.size === 0) graph.dependencyToImporters.delete(dep);
	}
}
function registerCssImports(ctx, importer, dependencies) {
	const graph = ensureCssGraph(ctx);
	if (!graph) return;
	const normalizedImporter = normalizePath$1(importer);
	const normalizedDeps = /* @__PURE__ */ new Set();
	for (const dependency of dependencies) {
		if (!dependency) continue;
		normalizedDeps.add(normalizePath$1(dependency));
	}
	const existingDeps = graph.importerToDependencies.get(normalizedImporter);
	const previousDeps = existingDeps ?? /* @__PURE__ */ new Set();
	if (existingDeps && previousDeps.size === normalizedDeps.size) {
		let unchanged = true;
		for (const dependency of normalizedDeps) if (!previousDeps.has(dependency) || !graph.dependencyToImporters.get(dependency)?.has(normalizedImporter)) {
			unchanged = false;
			break;
		}
		if (unchanged) return;
	}
	if (previousDeps.size) for (const previous of previousDeps) {
		if (normalizedDeps.has(previous)) continue;
		const importers = graph.dependencyToImporters.get(previous);
		if (!importers) continue;
		importers.delete(normalizedImporter);
		if (importers.size === 0) graph.dependencyToImporters.delete(previous);
	}
	graph.importerToDependencies.set(normalizedImporter, normalizedDeps);
	for (const dependency of normalizedDeps) {
		let importers = graph.dependencyToImporters.get(dependency);
		if (!importers) {
			importers = /* @__PURE__ */ new Set();
			graph.dependencyToImporters.set(dependency, importers);
		}
		importers.add(normalizedImporter);
	}
}
function addResolvedCssSpecifier(ctx, dependencies, importer, rawSpecifier) {
	if (!rawSpecifier) return;
	if (importProtocols.test(rawSpecifier)) {
		if (rawSpecifier.startsWith("/")) {
			const absolute = path.resolve(ctx.configService.absoluteSrcRoot, rawSpecifier.slice(1));
			dependencies.add(absolute);
			const ext = path.extname(absolute);
			if (ext) dependencies.add(absolute.slice(0, -ext.length));
		}
		return;
	}
	let specifier = rawSpecifier;
	if (specifier.startsWith("@/")) specifier = path.join(ctx.configService.absoluteSrcRoot, specifier.slice(2));
	else if (specifier === "@") specifier = ctx.configService.absoluteSrcRoot;
	if (specifier.startsWith("~")) specifier = specifier.slice(1);
	const cleaned = specifier.replace(/[?#].*$/, "");
	const resolved = path.resolve(path.dirname(importer), cleaned);
	dependencies.add(resolved);
	const ext = path.extname(resolved);
	if (!ext) dependencies.add(resolved);
	else dependencies.add(resolved.slice(0, -ext.length));
}
function collectCssDependenciesFromContent(ctx, importer, cssContent) {
	cssImportRE.lastIndex = 0;
	const dependencies = /* @__PURE__ */ new Set();
	while (true) {
		const match = cssImportRE.exec(cssContent);
		if (!match) break;
		const rawSpecifier = match[1]?.trim();
		if (!rawSpecifier) continue;
		addResolvedCssSpecifier(ctx, dependencies, importer, rawSpecifier);
	}
	return dependencies;
}
async function extractCssImportDependencies(ctx, importer) {
	try {
		if (!(await fs.promises.stat(importer)).isFile()) {
			cleanupImporterGraph(ctx, importer);
			return;
		}
	} catch {
		cleanupImporterGraph(ctx, importer);
		return;
	}
	let cssContent;
	try {
		cssContent = await fs.promises.readFile(importer, "utf8");
	} catch {
		cleanupImporterGraph(ctx, importer);
		return;
	}
	registerCssImports(ctx, importer, collectCssDependenciesFromContent(ctx, importer, cssContent));
}
function syncCssImportDependencies(ctx, importer, cssContent, extraDependencies = []) {
	const dependencies = collectCssDependenciesFromContent(ctx, importer, cssContent);
	for (const dependency of extraDependencies) if (dependency) {
		dependencies.add(dependency);
		const ext = path.extname(dependency);
		if (ext) dependencies.add(dependency.slice(0, -ext.length));
	}
	registerCssImports(ctx, importer, dependencies);
	return dependencies;
}
function syncVueSfcStyleDependencies(ctx, filename, styleBlocks) {
	const graphDependencies = /* @__PURE__ */ new Set();
	const moduleDependencies = /* @__PURE__ */ new Set();
	const addDependencies = (dependencies) => {
		for (const dependency of dependencies) {
			graphDependencies.add(dependency);
			if (path.extname(dependency)) moduleDependencies.add(dependency);
		}
	};
	for (const block of styleBlocks ?? []) {
		if (block.content) addDependencies(collectCssDependenciesFromContent(ctx, filename, block.content));
		if (typeof block.src === "string" && block.src.trim()) {
			const dependencies = /* @__PURE__ */ new Set();
			addResolvedCssSpecifier(ctx, dependencies, filename, block.src.trim());
			addDependencies(dependencies);
		}
	}
	registerCssImports(ctx, filename, graphDependencies);
	return moduleDependencies;
}
function collectCssImporters(ctx, dependency) {
	const graph = ensureCssGraph(ctx);
	if (!graph) return /* @__PURE__ */ new Set();
	const normalizedDependency = normalizePath$1(dependency);
	const matches = /* @__PURE__ */ new Set();
	const direct = graph.dependencyToImporters.get(normalizedDependency);
	if (direct) for (const importer of direct) matches.add(importer);
	const ext = path.extname(normalizedDependency);
	if (ext) {
		const base = normalizedDependency.slice(0, -ext.length);
		const baseMatches = graph.dependencyToImporters.get(base);
		if (baseMatches) for (const importer of baseMatches) matches.add(importer);
	}
	return matches;
}
async function resolveScriptForCss(cache, basePath) {
	if (cache.has(basePath)) return cache.get(basePath);
	const scriptPath = (await findJsEntry(basePath)).path;
	cache.set(basePath, scriptPath);
	return scriptPath;
}
async function collectAffectedScriptsAndImporters(ctx, startCssFile) {
	const queue = [normalizePath$1(startCssFile)];
	const visitedCss = /* @__PURE__ */ new Set();
	const affectedImporters = /* @__PURE__ */ new Set();
	const affectedScripts = /* @__PURE__ */ new Set();
	const scriptCache = /* @__PURE__ */ new Map();
	while (queue.length) {
		const layer = queue.splice(0);
		const pendingItems = [];
		const pendingScripts = /* @__PURE__ */ new Map();
		for (const current of layer) {
			if (visitedCss.has(current)) continue;
			visitedCss.add(current);
			const ext = path.extname(current);
			const item = { current };
			if (ext) {
				const base = current.slice(0, -ext.length);
				item.scriptBase = base;
				if (!pendingScripts.has(base)) pendingScripts.set(base, resolveScriptForCss(scriptCache, base));
			}
			pendingItems.push(item);
		}
		const resolvedScripts = /* @__PURE__ */ new Map();
		await Promise.all([...pendingScripts].map(async ([base, script]) => {
			resolvedScripts.set(base, await script);
		}));
		for (const item of pendingItems) {
			if (item.scriptBase) {
				const script = resolvedScripts.get(item.scriptBase);
				if (script) affectedScripts.add(script);
			}
			const importers = collectCssImporters(ctx, item.current);
			for (const importer of importers) {
				if (!visitedCss.has(importer)) queue.push(importer);
				affectedImporters.add(importer);
			}
		}
	}
	return {
		importers: affectedImporters,
		scripts: affectedScripts
	};
}
function cleanupCssImporterGraph(ctx, importer) {
	cleanupImporterGraph(ctx, importer);
}
//#endregion
//#region src/plugins/utils/invalidateEntry/sidecar.ts
async function invalidateEntryForSidecar(ctx, filePath, event = "update") {
	const configSuffix = configSuffixes.find((suffix) => filePath.endsWith(suffix));
	const ext = path.extname(filePath);
	const normalizedPath = normalizePath$1(filePath);
	let scriptBasePath;
	if (configSuffix) scriptBasePath = filePath.slice(0, -configSuffix.length);
	else if (ext && watchedCssExts.has(ext)) scriptBasePath = filePath.slice(0, -ext.length);
	else if (ext && watchedTemplateExts.has(ext)) scriptBasePath = filePath.slice(0, -ext.length);
	const isScriptModuleSidecar = watchedScriptModuleSuffixes.some((suffix) => normalizedPath.endsWith(suffix));
	if (!scriptBasePath && !isScriptModuleSidecar) return;
	const touchedTargets = /* @__PURE__ */ new Set();
	const touchedScripts = /* @__PURE__ */ new Set();
	if (isScriptModuleSidecar || ext && watchedTemplateExts.has(ext)) {
		const importers = ctx.wxmlService?.getImporters(normalizedPath) ?? /* @__PURE__ */ new Set();
		for (const importer of importers) touchedTargets.add(importer);
	}
	if (scriptBasePath) {
		const primaryScript = await findJsEntry(scriptBasePath);
		const shouldSkipPrimaryTemplateTouch = event === "update" && Boolean(ext && watchedTemplateExts.has(ext));
		if (primaryScript.path) {
			if (!shouldSkipPrimaryTemplateTouch) touchedScripts.add(primaryScript.path);
		} else if (ext && watchedTemplateExts.has(ext)) {
			const primaryVueEntry = await findVueEntry(scriptBasePath);
			if (primaryVueEntry && !shouldSkipPrimaryTemplateTouch) touchedTargets.add(primaryVueEntry);
		}
		if (!primaryScript.path && ext && watchedCssExts.has(ext)) {
			const { importers, scripts } = await collectAffectedScriptsAndImporters(ctx, normalizedPath);
			for (const importer of importers) touchedTargets.add(importer);
			for (const script of scripts) touchedScripts.add(script);
		}
	}
	const isCssSidecar = Boolean(ext && watchedCssExts.has(ext));
	const isTemplateSidecar = Boolean(ext && watchedTemplateExts.has(ext));
	if (isCssSidecar) ctx.runtimeState?.css?.transformedSidecarSource.delete(normalizedPath);
	const sidecarCause = configSuffix ? "json-sidecar" : isCssSidecar ? "style-sidecar" : "sidecar-direct";
	const configService = ctx.configService;
	const relativeSource = configService.relativeCwd(normalizedPath);
	const sidecarDirtyFiles = ctx.runtimeState?.watcher?.sidecarDirtyFiles;
	for (const target of touchedTargets) {
		sidecarDirtyFiles?.set(normalizePath$1(target), sidecarCause);
		try {
			await touch(target);
		} catch {}
	}
	for (const script of touchedScripts) {
		sidecarDirtyFiles?.set(normalizePath$1(script), sidecarCause);
		try {
			await touch(script);
		} catch {}
	}
	if (!touchedTargets.size && !touchedScripts.size) {
		if (event === "create" && (isCssSidecar || isTemplateSidecar || isScriptModuleSidecar)) logger_default.info(`[sidecar:${event}] ${relativeSource} 新增,但未找到引用方,等待后续关联`);
		return;
	}
	const touchedList = [];
	for (const target of touchedTargets) touchedList.push(configService.relativeCwd(target));
	for (const script of touchedScripts) touchedList.push(configService.relativeCwd(script));
	const uniqueTouched = Array.from(new Set(touchedList));
	logger_default.success(`[sidecar:${event}] ${relativeSource} -> 刷新 ${uniqueTouched.join(", ")}`);
}
//#endregion
//#region src/plugins/utils/invalidateEntry/watcher.ts
function ensureSidecarWatcher(ctx, rootDir) {
	if (!ctx.configService.isDev || !rootDir || process.env.VITEST === "true" || process.env.NODE_ENV === "test" || process.env.WEAPP_VITE_DISABLE_SIDECAR_WATCH === "1") return;
	const { sidecarWatcherMap } = ctx.runtimeState.watcher;
	const absRoot = path.normalize(rootDir);
	if (!fs.existsSync(absRoot)) return;
	if (sidecarWatcherMap.has(absRoot)) return;
	let isReady = false;
	const knownSidecarFiles = /* @__PURE__ */ new Set();
	const preReadyDeletedKnownFiles = /* @__PURE__ */ new Set();
	const renameTimers = /* @__PURE__ */ new Map();
	const RENAME_SETTLE_MS = 120;
	const handleSidecarChange = (event, filePath, ready) => {
		if (!isSidecarFile(filePath)) return;
		const ext = path.extname(filePath);
		const isCssFile = Boolean(ext && watchedCssExts.has(ext));
		const isTemplateFile = Boolean(ext && watchedTemplateExts.has(ext));
		const isConfigFile = configExtensions.some((suffix) => filePath.endsWith(suffix));
		const isScriptModuleFile = watchedScriptModuleSuffixes.some((suffix) => filePath.endsWith(suffix));
		const hasReverseImporters = Boolean(isTemplateFile || isScriptModuleFile) && (ctx.wxmlService?.getImporters(filePath).size ?? 0) > 0;
		if (isCssFile && (event === "create" || event === "update")) extractCssImportDependencies(ctx, filePath);
		const isDeleteEvent = event === "delete";
		const isOwnedByModuleGraph = event === "update" && ctx.moduleGraphService?.hasModule?.(filePath) === true;
		if (event === "create" && ready || isDeleteEvent || event === "update" && (isCssFile || hasReverseImporters || isTemplateFile || isConfigFile)) {
			(async () => {
				if (isTemplateFile && event !== "delete") await ctx.wxmlService?.scan(filePath);
				if (isOwnedByModuleGraph) return;
				await invalidateEntryForSidecar(ctx, filePath, event);
				if (isCssFile && isDeleteEvent) cleanupCssImporterGraph(ctx, filePath);
			})();
			return;
		}
		if (isCssFile && isDeleteEvent) cleanupCssImporterGraph(ctx, filePath);
	};
	const patterns = [
		...configExtensions.map((ext) => path.join(absRoot, `**/*.${ext}`)),
		...watchedCssSuffixes.map((ext) => path.join(absRoot, `**/*${ext}`)),
		...watchedTemplateSuffixes.map((ext) => path.join(absRoot, `**/*${ext}`)),
		...watchedScriptModuleSuffixes.map((ext) => path.join(absRoot, `**/*${ext}`))
	];
	const ignoredMatcher = createSidecarIgnoredMatcher(ctx, absRoot);
	const watcher = chokidar.watch(patterns, createSidecarWatchOptions(ctx.configService, {
		ignoreInitial: false,
		persistent: true,
		awaitWriteFinish: {
			stabilityThreshold: 100,
			pollInterval: 20
		},
		ignored: ignoredMatcher
	}));
	const forwardChange = (event, input, options) => {
		if (!input) return;
		const normalizedPath = path.normalize(input);
		const wasKnown = knownSidecarFiles.has(normalizedPath);
		const isPreReadyAtomicRestore = event === "create" && preReadyDeletedKnownFiles.has(normalizedPath);
		if (event === "create" || event === "update") {
			knownSidecarFiles.add(normalizedPath);
			preReadyDeletedKnownFiles.delete(normalizedPath);
		} else if (event === "delete") {
			if (!isReady && wasKnown) preReadyDeletedKnownFiles.add(normalizedPath);
			knownSidecarFiles.delete(normalizedPath);
		}
		if (!options?.silent) logger_default.info(`[watch:${event}] ${ctx.configService.relativeCwd(normalizedPath)}`);
		handleSidecarChange(event, normalizedPath, isReady || isPreReadyAtomicRestore);
	};
	watcher.on("add", (path) => forwardChange("create", path));
	watcher.on("change", (path) => forwardChange("update", path));
	watcher.on("unlink", (path) => forwardChange("delete", path));
	watcher.on("raw", (eventName, rawPath, details) => {
		if (eventName !== "rename") return;
		const candidate = typeof rawPath === "string" ? rawPath : rawPath && typeof rawPath.toString === "function" ? rawPath.toString() : "";
		if (!candidate) return;
		const baseDir = typeof details === "object" && details && "watchedPath" in details ? details.watchedPath ?? absRoot : absRoot;
		const resolved = path.isAbsolute(candidate) ? candidate : path.resolve(baseDir, candidate);
		if (ignoredMatcher(resolved)) return;
		const pending = renameTimers.get(resolved);
		if (pending) clearTimeout(pending);
		renameTimers.set(resolved, setTimeout(() => {
			renameTimers.delete(resolved);
			const exists = fs.existsSync(resolved);
			const wasKnown = knownSidecarFiles.has(resolved);
			let derivedEvent;
			if (exists) {
				derivedEvent = wasKnown || isReady ? "update" : "create";
				knownSidecarFiles.add(resolved);
			} else if (wasKnown) {
				derivedEvent = "delete";
				knownSidecarFiles.delete(resolved);
			}
			if (!derivedEvent) return;
			const relativeResolved = ctx.configService.relativeCwd(resolved);
			logger_default.info(`[watch:rename->${derivedEvent}] ${relativeResolved}`);
			if (derivedEvent === "update") {
				handleSidecarChange("update", resolved, true);
				return;
			}
			forwardChange(derivedEvent, resolved, { silent: true });
		}, RENAME_SETTLE_MS));
	});
	watcher.on("ready", () => {
		isReady = true;
	});
	watcher.on("error", (error) => {
		if (!isWatchLimitError(error)) return;
		const relativeRoot = ctx.configService.relativeCwd(absRoot);
		const code = error?.code ?? "UNKNOWN";
		logger_default.warn(`[监听] ${relativeRoot} 监听数量达到上限 (${code}),侧车文件监听已停用`);
	});
	sidecarWatcherMap.set(absRoot, { close: () => {
		for (const timer of renameTimers.values()) clearTimeout(timer);
		renameTimers.clear();
		preReadyDeletedKnownFiles.clear();
		return watcher.close();
	} });
}
function createSidecarIgnoredMatcher(ctx, rootDir) {
	const configService = ctx.configService;
	const ignoredRoots = /* @__PURE__ */ new Set();
	const normalizedRoot = path.normalize(rootDir);
	for (const dirName of defaultIgnoredDirNames) ignoredRoots.add(path.join(normalizedRoot, dirName));
	if (configService?.mpDistRoot) ignoredRoots.add(path.resolve(configService.cwd, configService.mpDistRoot));
	else ignoredRoots.add(path.join(normalizedRoot, "dist"));
	if (configService?.outDir) ignoredRoots.add(path.resolve(configService.cwd, configService.outDir));
	return (candidate) => {
		const normalized = path.normalize(candidate);
		for (const ignored of ignoredRoots) if (normalized === ignored || normalized.startsWith(`${ignored}${path.sep}`)) return true;
		return false;
	};
}
//#endregion
//#region src/plugins/utils/nativeLayout.ts
function resolveNativeLayoutOutputOptions(options) {
	const relativeBase = options.configService.relativeOutputPath(options.layoutBasePath);
	if (!relativeBase) return;
	return {
		relativeBase,
		...resolveCompilerOutputExtensions(options.outputExtensions)
	};
}
async function resolveNativeLayoutStaticAssetEntries(options) {
	const entries = [];
	const { assets, resolvedOptions, readFile } = options;
	if (assets.template) entries.push({
		kind: "template",
		fileName: `${resolvedOptions.relativeBase}.${resolvedOptions.templateExtension}`,
		source: await readFile(assets.template, "utf8")
	});
	if (assets.style) entries.push({
		kind: "style",
		fileName: `${resolvedOptions.relativeBase}.${resolvedOptions.styleExtension}`,
		source: await readFile(assets.style, "utf8")
	});
	return entries;
}
//#endregion
//#region src/plugins/utils/wxmlEmit.ts
function resolveWxmlEmitContext(compiler) {
	const { wxmlService, configService, scanService } = compiler;
	if (!wxmlService || !configService || !scanService) throw new Error("emitWxmlAssets 需要先初始化 wxmlService、configService 和 scanService。");
	const { templateExtension, scriptModuleExtension } = resolveCompilerOutputExtensions(configService.outputExtensions);
	return {
		wxmlService,
		configService,
		scanService,
		templateExtension,
		scriptModuleExtension,
		scriptModuleTag: resolveScriptModuleTagName({
			platform: configService.platform,
			scriptModuleExtension
		})
	};
}
function resolveWxmlEmitTargets(options) {
	const { compiler, subPackageMeta, buildTarget = "app" } = options;
	const { wxmlService, configService, scanService, templateExtension } = resolveWxmlEmitContext(compiler);
	const targetIds = options.targetIds?.size ? new Set(Array.from(options.targetIds, normalizeWatchPath)) : void 0;
	const isAllowedTarget = (id, fileName) => {
		if (subPackageMeta) return fileName.startsWith(subPackageMeta.subPackage.root);
		if (buildTarget === "plugin") {
			const pluginRoot = configService.absolutePluginRoot;
			if (!pluginRoot) return false;
			return isPathInside(pluginRoot, id);
		}
		return scanService.isMainPackageFileName(fileName);
	};
	const resolveTarget = (id, token) => {
		if (!isTemplate(id)) return;
		const fileName = resolveRelativeOutputFileNameWithExtension(configService, id, templateExtension);
		if (!isAllowedTarget(id, fileName)) return;
		return {
			id,
			token,
			fileName
		};
	};
	if (targetIds?.size) {
		const targets = [];
		for (const targetId of targetIds) {
			const token = wxmlService.tokenMap.get(targetId);
			if (!token) continue;
			const target = resolveTarget(targetId, token);
			if (target) targets.push(target);
		}
		return targets;
	}
	return Array.from(wxmlService.tokenMap.entries()).map(([id, token]) => resolveTarget(id, token)).filter((target) => Boolean(target));
}
function emitWxmlAssetFile(options) {
	const { runtime, id, fileName, token, deps, emittedCodeCache, importMetaDefineRegistry, scriptModuleExtension, scriptModuleTag, templateExtension, platform } = options;
	runtime.addWatchFile?.(normalizeWatchPath(id));
	if (deps) for (const dep of deps) runtime.addWatchFile?.(normalizeWatchPath(dep));
	const result = handleWxml(token, {
		importMetaDefineRegistry,
		importMetaExtension: templateExtension,
		importMetaRelativePath: fileName,
		scriptModuleExtension,
		scriptModuleTag,
		templateExtension,
		transformPlatformSyntax: !isNativeTemplateSource(id, platform)
	});
	if (emittedCodeCache.get(fileName) === result.code) return false;
	emittedCodeCache.set(fileName, result.code);
	runtime.emitFile({
		type: "asset",
		fileName,
		source: result.code
	});
	return true;
}
function emitWxmlAssetsWithCache(options) {
	const { runtime, compiler, subPackageMeta, emittedCodeCache, buildTarget = "app" } = options;
	const { wxmlService, configService, templateExtension, scriptModuleExtension, scriptModuleTag } = resolveWxmlEmitContext(compiler);
	const currentPackageWxmls = resolveWxmlEmitTargets({
		compiler,
		subPackageMeta,
		buildTarget,
		targetIds: options.targetIds
	});
	const emittedFiles = [];
	for (const { id, fileName, token } of currentPackageWxmls) {
		emittedFiles.push(fileName);
		emitWxmlAssetFile({
			runtime,
			id,
			fileName,
			token,
			deps: wxmlService.depsMap.get(id),
			emittedCodeCache,
			importMetaDefineRegistry: configService.importMetaDefineRegistry,
			scriptModuleExtension,
			scriptModuleTag,
			templateExtension,
			platform: configService.platform
		});
	}
	return emittedFiles;
}
function emitJsonAsset(runtime, fileName, source, extension = "json") {
	runtime.emitFile({
		type: "asset",
		fileName: changeFileExtension(fileName, extension),
		source
	});
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/loadEntry/emit.ts
const NON_VUE_PAGE_RE = /\.vue$|\.jsx$|\.tsx$/;
const nativeLayoutAssetSourceCache = /* @__PURE__ */ new Map();
function prefetch(task) {
	return task.then((value) => ({
		ok: true,
		value
	}), (error) => ({
		ok: false,
		error
	}));
}
function prepareNormalizedEntries(options) {
	const { entries, json, jsonPath, templatePath, id, skipOwnEntries, entriesMap, normalizeEntry, extendedLibManager, entryType, explicitEntryTypes } = options;
	const filteredEntries = skipOwnEntries ? [] : entries.filter((entry) => !extendedLibManager.shouldIgnoreEntry(entry));
	const normalizedEntries = skipOwnEntries ? [] : Array.from(new Set(filteredEntries.map((entry) => normalizeEntry(entry, jsonPath))));
	if (!skipOwnEntries) for (const normalizedEntry of normalizedEntries) {
		const resolvedEntryType = explicitEntryTypes?.get(normalizedEntry) ?? entryType ?? (json.component ? "component" : "page");
		entriesMap.set(normalizedEntry, {
			type: resolvedEntryType,
			templatePath,
			jsonPath,
			json,
			path: id
		});
	}
	return normalizedEntries;
}
function isEntryStyleStableHmr(runtimeState) {
	const profile = runtimeState?.build?.hmr?.profile;
	if (profile?.event === void 0) return false;
	const dirtyReasonSummary = profile.dirtyReasonSummary;
	if (!dirtyReasonSummary?.length) return false;
	return dirtyReasonSummary.every((reason) => reason.startsWith("entry-direct:") || reason.startsWith("importer-graph:") || reason.startsWith("shared-chunk-source:") || reason.startsWith("json-sidecar:") || reason.startsWith("sidecar-direct:") || reason.startsWith("entry-local-asset:") || reason.startsWith("tailwind-content:"));
}
async function emitEntryOutput(options) {
	const { pluginCtx, id, type, json: initialJson, jsonPath, templatePath, isPluginBuild, normalizedEntries, entriesMap, pluginResolvedRecords, pluginJsonPathForRegistration, pluginJsonForRegistration, resolveEntriesWithCache, resolveMappedEntry, entryResolveRoot, configService, runtimeState, wxmlService, resolvedEntryMap, loadedEntrySet, dirtyEntrySet, forceEmitEntrySet, forceReloadEntrySet, replaceLayoutDependencies, replaceEntryDependencies, emitEntriesChunks, registerJsonAsset, existsCache, pathExistsTtlMs, debug, relativeCwdId, getTime, emittedWxmlCodeCache, styleImportsCache, resolvedPageLayoutPlan, entryCodeSource, metadataOnly } = options;
	let json = initialJson;
	function recordEntryDuration(key, startedAt) {
		recordHmrProfileDuration(runtimeState?.build?.hmr?.profile, key, performance$1.now() - startedAt);
	}
	const entryCodeTask = entryCodeSource === void 0 ? prefetch((async () => {
		const startedAt = performance$1.now();
		try {
			return await readFile$1(id, { checkMtime: configService.isDev });
		} finally {
			recordEntryDuration("entryCodeReadMs", startedAt);
		}
	})()) : prefetch(Promise.resolve(entryCodeSource));
	const cachedStyleImports = configService.isDev && isEntryStyleStableHmr(runtimeState) ? styleImportsCache?.get(id) : void 0;
	const styleImportsTask = prefetch((async () => {
		if (cachedStyleImports) return cachedStyleImports;
		const startedAt = performance$1.now();
		try {
			const styleImports = await collectStyleImports(pluginCtx, id, existsCache, pathExistsTtlMs);
			for (const styleImport of styleImports) runtimeState?.css?.sidecarImports.add(styleImport);
			styleImportsCache?.set(id, styleImports);
			return styleImports;
		} finally {
			recordEntryDuration("entryStyleScanMs", startedAt);
		}
	})());
	const styleImportSourcesTask = prefetch((async () => {
		const styleImportsResult = await styleImportsTask;
		if (!styleImportsResult.ok) throw styleImportsResult.error;
		const styleReadStartedAt = performance$1.now();
		let styleSources;
		try {
			styleSources = cachedStyleImports ? [] : await Promise.all(styleImportsResult.value.map(async (styleImport) => {
				return {
					styleImport,
					source: await readFile$1(styleImport, { checkMtime: configService.isDev })
				};
			}));
		} finally {
			recordEntryDuration("entryStyleReadMs", styleReadStartedAt);
		}
		return {
			styleImports: styleImportsResult.value,
			styleSources
		};
	})());
	async function emitNativeLayoutAssets(layoutBasePath) {
		if (typeof pluginCtx.emitFile !== "function") return;
		const resolvedOptions = resolveNativeLayoutOutputOptions({
			configService,
			layoutBasePath,
			outputExtensions: configService.outputExtensions
		});
		if (!resolvedOptions) return;
		const assets = await collectNativeLayoutAssets(layoutBasePath, configService.platform);
		const emittedLayoutAssets = pluginCtx.__weappViteNativeLayoutAssets ?? (pluginCtx.__weappViteNativeLayoutAssets = /* @__PURE__ */ new Set());
		if (assets.json) registerJsonAsset({
			jsonPath: assets.json,
			json: JSON.parse(await fs$2.readFile(assets.json, "utf8")),
			type: "component"
		});
		const assetEntries = await resolveNativeLayoutStaticAssetEntries({
			assets,
			resolvedOptions,
			readFile: fs$2.readFile
		});
		const emittedCodeCache = emittedWxmlCodeCache ?? /* @__PURE__ */ new Map();
		const wxmlEmitContext = wxmlService ? resolveWxmlEmitContext({
			wxmlService,
			configService,
			scanService: { isMainPackageFileName: () => true }
		}) : void 0;
		for (const asset of assetEntries) {
			if (emittedLayoutAssets.has(asset.fileName)) continue;
			if (asset.kind === "template" && assets.template && wxmlService && wxmlEmitContext) {
				const token = wxmlService.analyze(asset.source);
				wxmlService.tokenMap.set(assets.template, token);
				await wxmlService.setTokenDeps(assets.template, token.deps);
				wxmlService.setWxmlComponentsMap(assets.template, token.components);
				emitWxmlAssetFile({
					runtime: { emitFile: (payload) => pluginCtx.emitFile(payload) },
					id: assets.template,
					fileName: asset.fileName,
					token,
					deps: wxmlService.depsMap.get(assets.template),
					emittedCodeCache,
					scriptModuleExtension: wxmlEmitContext.scriptModuleExtension,
					scriptModuleTag: wxmlEmitContext.scriptModuleTag,
					templateExtension: wxmlEmitContext.templateExtension
				});
				emittedLayoutAssets.add(asset.fileName);
				continue;
			}
			const cacheKey = `asset:${asset.fileName}`;
			if (nativeLayoutAssetSourceCache.get(cacheKey) === asset.source) {
				emittedLayoutAssets.add(asset.fileName);
				continue;
			}
			emittedLayoutAssets.add(asset.fileName);
			pluginCtx.emitFile({
				type: "asset",
				fileName: asset.fileName,
				source: asset.source
			});
			nativeLayoutAssetSourceCache.set(cacheKey, asset.source);
		}
	}
	const shouldSkipEntries = Boolean(options.skipEntries);
	const resolvedIds = shouldSkipEntries ? [] : normalizedEntries.length ? await (async () => {
		const startedAt = performance$1.now();
		try {
			return await resolveEntriesWithCache(pluginCtx, normalizedEntries, entryResolveRoot, {
				fallbackRoots: [configService.cwd],
				resolveMappedEntry
			});
		} finally {
			recordEntryDuration("entryResolveMs", startedAt);
		}
	})() : [];
	debug?.(`resolvedIds ${relativeCwdId} 耗时 ${getTime()}`);
	const pendingResolvedIds = [];
	const combinedResolved = shouldSkipEntries ? [] : pluginResolvedRecords ? isPluginBuild ? pluginResolvedRecords : [...resolvedIds, ...pluginResolvedRecords] : resolvedIds;
	const pluginEntrySet = shouldSkipEntries || !pluginResolvedRecords ? void 0 : new Set(pluginResolvedRecords.map((record) => record.entry));
	replaceEntryDependencies(id, "using-component", combinedResolved.flatMap(({ entry, resolvedId }) => {
		if (!resolvedId || entriesMap.get(entry)?.type !== "component") return [];
		const resolvedSourceId = normalizeFsResolvedId(resolvedId.id);
		return isSkippableResolvedId(resolvedSourceId) ? [] : [resolvedSourceId];
	}));
	for (const { entry, resolvedId } of combinedResolved) {
		if (!resolvedId) {
			const missingAbsoluteEntryPath = path.resolve(entryResolveRoot, entry);
			if (configService.isDev && path.isAbsolute(missingAbsoluteEntryPath) && !await fs$1.pathExists(missingAbsoluteEntryPath)) continue;
			if (pluginEntrySet?.has(entry)) logger_default.warn(`没有找到插件入口 \`${entry}\` 对应的脚本文件,请检查路径是否正确!`);
			else logger_default.warn(`没有找到 \`${entry}\` 的入口文件,请检查路径是否正确!`);
			continue;
		}
		const normalizedResolvedId = normalizeFsResolvedId(resolvedId.id);
		if (normalizedResolvedId && !isSkippableResolvedId(normalizedResolvedId)) {
			resolvedEntryMap.set(normalizedResolvedId, resolvedId);
			if (/\.(?:jsx|tsx)$/.test(normalizedResolvedId)) addNormalizedWatchFile(pluginCtx, normalizedResolvedId);
		}
		const isForcedEntry = forceEmitEntrySet?.has(entry) === true || forceEmitEntrySet?.has(normalizedResolvedId) === true;
		const isForcedReloadEntry = forceReloadEntrySet?.has(entry) === true || forceReloadEntrySet?.has(normalizedResolvedId) === true;
		const isDirtyEntry = dirtyEntrySet.has(normalizedResolvedId);
		if (!isDirtyEntry && !isForcedEntry && loadedEntrySet.has(normalizedResolvedId)) continue;
		if (isForcedReloadEntry) loadedEntrySet.delete(normalizedResolvedId);
		pendingResolvedIds.push(resolvedId);
		if (isDirtyEntry || isForcedEntry) dirtyEntrySet.delete(normalizedResolvedId);
	}
	if (pendingResolvedIds.length && !metadataOnly) {
		const startedAt = performance$1.now();
		try {
			await Promise.all(emitEntriesChunks.call(pluginCtx, pendingResolvedIds));
		} finally {
			recordEntryDuration("entryChunkEmitMs", startedAt);
		}
	}
	debug?.(`emitEntriesChunks ${relativeCwdId} 耗时 ${getTime()}`);
	let code;
	const entryCodeResult = await entryCodeTask;
	if (entryCodeResult.ok) code = entryCodeResult.value;
	else {
		const { error } = entryCodeResult;
		if (error && typeof error === "object" && "code" in error && error.code === "ENOENT" && configService.isDev && !await fs$1.pathExists(id)) return;
		throw error;
	}
	if (type === "page" && templatePath && !NON_VUE_PAGE_RE.test(id)) {
		const layoutStartedAt = performance$1.now();
		try {
			replaceLayoutDependencies(id, []);
			const layoutPlan = resolvedPageLayoutPlan === void 0 ? await resolvePageLayoutPlan(code, id, configService) : resolvedPageLayoutPlan ?? void 0;
			registerNativePageLayoutOutput({
				configService,
				runtimeState,
				pageId: id,
				templatePath,
				plan: layoutPlan
			});
			if (layoutPlan) {
				const layoutDependencies = /* @__PURE__ */ new Set();
				for (const file of await expandResolvedPageLayoutFiles(layoutPlan.layouts, configService.platform)) layoutDependencies.add(normalizeFsResolvedId(file));
				replaceLayoutDependencies(id, layoutDependencies);
				const nativeTemplate = await readFile$1(templatePath, { checkMtime: configService.isDev });
				const transformed = applyPageLayoutPlanToNativePage({
					script: code,
					template: nativeTemplate,
					config: JSON.stringify(json)
				}, id, layoutPlan, { platform: configService.platform });
				code = transformed.script ?? code;
				if (transformed.config) json = JSON.parse(transformed.config);
				if (transformed.template && wxmlService) {
					const token = wxmlService.analyze(transformed.template);
					wxmlService.tokenMap.set(templatePath, token);
					wxmlService.setTokenDeps(templatePath, token.deps);
					wxmlService.setWxmlComponentsMap(templatePath, token.components);
				}
				for (const layout of layoutPlan.layouts) if (layout.kind === "native") await emitNativeLayoutAssets(layout.file);
			}
			code = injectNativePageLayoutRuntime(code, id, layoutPlan) ?? code;
		} finally {
			recordEntryDuration("entryLayoutMs", layoutStartedAt);
		}
	}
	if (!isPluginBuild || type !== "app") registerJsonAsset({
		jsonPath: type === "app" ? id : jsonPath,
		json,
		type
	});
	if (pluginJsonPathForRegistration && pluginJsonForRegistration) registerJsonAsset({
		jsonPath: pluginJsonPathForRegistration,
		json: pluginJsonForRegistration,
		type: "plugin"
	});
	const styleImportSourcesResult = await styleImportSourcesTask;
	if (!styleImportSourcesResult.ok) throw styleImportSourcesResult.error;
	const { styleImports, styleSources } = styleImportSourcesResult.value;
	for (const { styleImport, source } of styleSources) syncCssImportDependencies({
		configService,
		runtimeState
	}, styleImport, source);
	debug?.(`loadEntry ${relativeCwdId} 耗时 ${getTime()}`);
	if (styleImports.length === 0) return { code };
	const ms = new MagicString(code);
	for (const styleImport of styleImports) ms.prepend(`import '${styleImport}';\n`);
	const result = { code: ms.toString() };
	if (configService.inlineConfig?.build?.sourcemap) result.map = ms.generateMap({
		hires: true,
		includeContent: true,
		source: id
	});
	return result;
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/loadEntry/resolve.ts
const LEADING_ROOT_SLASH_RE = /^[/\\]+/;
function createEntryResolver(configService) {
	const entryResolutionCache = /* @__PURE__ */ new Map();
	async function resolveEntryWithCache(pluginCtx, absPath) {
		const normalized = path.normalize(absPath);
		if (entryResolutionCache.has(normalized)) return entryResolutionCache.get(normalized) ?? null;
		let resolvedSource = normalized;
		if (!path.extname(normalized)) {
			const matched = await resolveEntryPath(normalized, createCachedEntryResolveOptions(configService ?? {}, { kind: "default" }));
			if (matched) resolvedSource = matched;
		}
		const resolved = await pluginCtx.resolve(resolvedSource);
		if (resolved?.id && configService?.isDev && path.isAbsolute(resolved.id)) {
			const [resolvedPathWithoutQuery] = resolved.id.split("?");
			if (!resolvedPathWithoutQuery || !await fs$1.pathExists(resolvedPathWithoutQuery)) return null;
		}
		const resolvedId = resolved ?? (path.isAbsolute(resolvedSource) && await fs$1.pathExists(resolvedSource) ? { id: resolvedSource } : null);
		if (resolvedId || !configService?.isDev) entryResolutionCache.set(normalized, resolvedId);
		return resolvedId;
	}
	async function resolveEntriesWithCache(pluginCtx, entries, absoluteRoot, options) {
		return Promise.all(entries.filter((entry) => !entry.includes(":")).map(async (entry) => {
			const cleanedEntry = entry.replace(LEADING_ROOT_SLASH_RE, "");
			const mappedEntry = options?.resolveMappedEntry?.(cleanedEntry);
			if (mappedEntry) return {
				entry,
				resolvedId: await resolveEntryWithCache(pluginCtx, mappedEntry)
			};
			let resolvedId = await resolveEntryWithCache(pluginCtx, path.isAbsolute(entry) && await fs$1.pathExists(entry) ? entry : path.resolve(absoluteRoot, cleanedEntry));
			if (!resolvedId) for (const fallbackRoot of options?.fallbackRoots ?? []) {
				resolvedId = await resolveEntryWithCache(pluginCtx, path.resolve(fallbackRoot, cleanedEntry));
				if (resolvedId) break;
			}
			return {
				entry,
				resolvedId
			};
		}));
	}
	return {
		resolveEntryWithCache,
		resolveEntriesWithCache,
		invalidate() {
			entryResolutionCache.clear();
		}
	};
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/loadEntry/index.ts
const VUE_LIKE_PAGE_ENTRY_RE = /\.(?:vue|jsx|tsx)$/;
const VUE_JSON_BLOCK_RE = /<json\b[^>]*>[\s\S]*?<\/json>/gi;
const VUE_JSON_MACRO_HINT_RE = /\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;
const NO_VUE_CONFIG_SIGNATURE = "no-vue-config";
function hasPageLayoutSourceHint(source) {
	return source.includes("definePageMeta") || source.includes("setPageLayout");
}
function hashText(value) {
	return createHash("sha256").update(value).digest("hex").slice(0, 16);
}
function collectMatches(source, pattern) {
	return source.match(pattern) ?? [];
}
function resolveCacheableVueConfigSignature(source) {
	if (VUE_JSON_MACRO_HINT_RE.test(source)) return;
	const jsonBlocks = collectMatches(source, VUE_JSON_BLOCK_RE);
	if (jsonBlocks.length === 0) return NO_VUE_CONFIG_SIGNATURE;
	return hashText(jsonBlocks.join("\0"));
}
function cloneJsonValue(value) {
	try {
		return structuredClone(value);
	} catch {
		return value;
	}
}
function createStopwatch() {
	const start = performance$1.now();
	return () => `${(performance$1.now() - start).toFixed(2)}ms`;
}
function isEntryJsonStableHmr(ctx) {
	const profile = ctx.runtimeState?.build?.hmr?.profile;
	if (!ctx.configService.isDev || profile?.event === void 0) return false;
	const dirtyReasonSummary = profile.dirtyReasonSummary;
	if (!dirtyReasonSummary?.length) return false;
	return dirtyReasonSummary.every((reason) => reason.startsWith("entry-direct:") || reason.startsWith("importer-graph:") || reason.startsWith("shared-chunk-source:") || reason.startsWith("css-importer:") || reason.startsWith("css-importer-fallback:") || reason.startsWith("tailwind-content:") || reason.startsWith("entry-style-only:") || reason.startsWith("style-sidecar:") || reason.startsWith("entry-local-asset:"));
}
function createEntryLoader(options) {
	const { ctx, entriesMap, loadedEntrySet, dirtyEntrySet, resolvedEntryMap, replaceLayoutDependencies, normalizeEntry, registerJsonAsset, scanTemplateEntry: scanTemplateEntryFn, emitEntriesChunks, applyAutoImports, extendedLibManager, debug } = options;
	const isPluginBuild = (options.buildTarget ?? "app") === "plugin";
	const { jsonService, configService, wxmlService } = ctx;
	const existsCache = /* @__PURE__ */ new Map();
	const pathExistsTtlMs = getPathExistsTtlMs(configService);
	const reExportResolutionCache = /* @__PURE__ */ new Map();
	const entryResolver = createEntryResolver(configService);
	const appEntriesCache = {};
	const appEntryOutputCache = {};
	const emittedScriptlessVueLayoutJs = /* @__PURE__ */ new Set();
	const scriptlessVueLayoutDecisionCache = /* @__PURE__ */ new Map();
	const entrySidecarResolutionCache = /* @__PURE__ */ new Map();
	const entryJsonCache = /* @__PURE__ */ new Map();
	const vueConfigCache = /* @__PURE__ */ new Map();
	const staticPageLayoutPlanCache = /* @__PURE__ */ new Map();
	const templateEntryPathCache = /* @__PURE__ */ new Map();
	const styleImportsCache = /* @__PURE__ */ new Map();
	let resolveCacheVersion = 0;
	async function materializeVueAutoImportEntries(pluginCtx, importer, json, injectedEntries) {
		const usingComponents = get(json, "usingComponents");
		if (!isObject(usingComponents) || !injectedEntries.length) {
			if (!isObject(usingComponents) || !configService.weappViteConfig?.uniApp) return injectedEntries;
		}
		const candidateEntries = Array.from(/* @__PURE__ */ new Set([...injectedEntries, ...Object.values(usingComponents).filter((entry) => typeof entry === "string" && entry.endsWith(".vue"))]));
		const rewritten = /* @__PURE__ */ new Map();
		for (const entry of candidateEntries) {
			const resolved = await pluginCtx.resolve(entry, importer);
			const resolvedId = resolved?.id ? normalizeFsResolvedId(resolved.id) : void 0;
			if (!resolvedId?.endsWith(".vue")) {
				if (configService.weappViteConfig?.uniApp && entry.endsWith(".vue")) throw new Error(`[uni-app] 无法解析外部 Vue 组件: importer=${importer} request=${entry}`);
				continue;
			}
			const outputPath = usingComponentFromResolvedFile(resolvedId, configService);
			if (!outputPath) throw new Error(`[uni-app] 无法生成外部 Vue 组件输出路径: importer=${importer} resolvedId=${resolvedId}`);
			for (const [name, value] of Object.entries(usingComponents)) if (value === entry) usingComponents[name] = outputPath;
			ctx.runtimeState.build.hmr.externalComponentEntryMap.set(removeExtensionDeep(outputPath).replace(/^\/+/, ""), resolvedId);
			rewritten.set(entry, outputPath);
		}
		return Array.from(/* @__PURE__ */ new Set([...injectedEntries.map((entry) => rewritten.get(entry) ?? entry), ...candidateEntries.map((entry) => rewritten.get(entry) ?? entry)]));
	}
	const shouldEmitScriptlessVueLayoutJs$1 = async (layoutFile) => {
		const cached = scriptlessVueLayoutDecisionCache.get(layoutFile);
		if (cached) return await cached;
		const task = (async () => {
			return shouldEmitScriptlessVueLayoutJs(await fs$1.readFile(layoutFile, "utf-8"), layoutFile);
		})();
		scriptlessVueLayoutDecisionCache.set(layoutFile, task);
		try {
			return await task;
		} catch (error) {
			scriptlessVueLayoutDecisionCache.delete(layoutFile);
			throw error;
		}
	};
	return Object.assign(async function loadEntry(id, type, loadOptions) {
		if (configService.isDev) existsCache.clear();
		const stopwatch = debug ? createStopwatch() : void 0;
		const getTime = () => stopwatch ? stopwatch() : "0.00ms";
		const relativeCwdId = configService.relativeCwd(id);
		const normalizedId = normalizeFsResolvedId(id);
		const libConfig = configService.weappLibConfig;
		let appVueNonJsonSignature;
		const libEntry = libConfig?.enabled && normalizedId ? ctx.runtimeState.lib.entries.get(normalizedId) : void 0;
		const baseName = removeExtensionDeep(id);
		function recordEntryDuration(key, startedAt) {
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, key, performance$1.now() - startedAt);
		}
		const sidecarResolveStartedAt = performance$1.now();
		let jsonEntry;
		let vueEntryPath;
		const isStableHmr = type !== "app" && isEntryJsonStableHmr(ctx);
		try {
			const cachedSidecarResolution = isStableHmr ? entrySidecarResolutionCache.get(normalizedId) : void 0;
			if (cachedSidecarResolution) ({jsonEntry, vueEntryPath} = cachedSidecarResolution);
			else {
				[jsonEntry, vueEntryPath] = await Promise.all([findJsonEntry(id), id.endsWith(".vue") ? Promise.resolve(id) : findVueEntry(baseName)]);
				entrySidecarResolutionCache.set(normalizedId, {
					jsonEntry,
					vueEntryPath
				});
			}
		} finally {
			recordEntryDuration("entrySidecarResolveMs", sidecarResolveStartedAt);
		}
		let jsonPath = jsonEntry.path;
		let hasJsonEntry = Boolean(jsonPath);
		let json = {};
		const isJsonStableHmr = isStableHmr;
		const addJsonWatchTargets = isJsonStableHmr ? Promise.resolve() : addPredictedWatchTargets(this, jsonEntry.predictions, existsCache, pathExistsTtlMs, jsonEntry.path);
		const cachedJson = jsonPath && isJsonStableHmr ? jsonService.cache.get(jsonPath) : void 0;
		const cachedEntryJson = jsonPath && isJsonStableHmr && cachedJson === void 0 ? entryJsonCache.get(jsonPath) : void 0;
		const readJsonEntry = jsonPath ? cachedJson === void 0 ? cachedEntryJson === void 0 ? jsonService.read(jsonPath) : Promise.resolve(cloneJsonValue(cachedEntryJson)) : Promise.resolve(cachedJson) : void 0;
		const jsonReadStartedAt = performance$1.now();
		if (jsonPath) try {
			[json] = await Promise.all([readJsonEntry, addJsonWatchTargets]);
			if (json !== void 0 && cachedJson === void 0 && cachedEntryJson === void 0) entryJsonCache.set(jsonPath, cloneJsonValue(json));
		} finally {
			recordEntryDuration("entryJsonReadMs", jsonReadStartedAt);
		}
		else {
			try {
				await addJsonWatchTargets;
			} finally {
				recordEntryDuration("entryJsonReadMs", jsonReadStartedAt);
			}
			jsonPath = changeFileExtension(id, ".json");
		}
		let vueSource;
		const readVueSource = async () => {
			if (!vueEntryPath) return;
			if (vueSource !== void 0) return vueSource;
			try {
				vueSource = await fs$1.readFile(vueEntryPath, "utf-8");
			} catch (error) {
				if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT" && configService.isDev && !await fs$1.pathExists(vueEntryPath))) throw error;
			}
			return vueSource;
		};
		if (!jsonEntry.path) {
			if (vueEntryPath) {
				const vueConfigStartedAt = performance$1.now();
				const configFromVue = await (async () => {
					try {
						const source = await readVueSource();
						const cacheSignature = source === void 0 ? void 0 : resolveCacheableVueConfigSignature(source);
						const cachedVueConfig = isJsonStableHmr && cacheSignature ? vueConfigCache.get(vueEntryPath) : void 0;
						if (cachedVueConfig && cachedVueConfig.signature === cacheSignature) return cloneJsonValue(cachedVueConfig.config);
						if (isJsonStableHmr && cacheSignature === NO_VUE_CONFIG_SIGNATURE) {
							vueConfigCache.set(vueEntryPath, {
								signature: cacheSignature,
								config: void 0
							});
							return;
						}
						const config = await extractConfigFromVue(vueEntryPath, { ...source === void 0 ? { readSource: readVueSource } : { source } });
						if (cacheSignature) vueConfigCache.set(vueEntryPath, {
							signature: cacheSignature,
							config: cloneJsonValue(config)
						});
						return config;
					} finally {
						recordEntryDuration("entryVueConfigMs", vueConfigStartedAt);
					}
				})();
				if (configFromVue && typeof configFromVue === "object") {
					json = configFromVue;
					hasJsonEntry = true;
				}
			}
		}
		const entries = [];
		const explicitEntryTypes = /* @__PURE__ */ new Map();
		let templatePath = "";
		let entryTypeOverride;
		let pluginResolvedRecords;
		let pluginJsonPathForRegistration;
		let pluginJsonForRegistration;
		let appResult;
		let shouldSkipAppEntries = false;
		const forceEmitEntrySet = /* @__PURE__ */ new Set();
		const forceReloadEntrySet = /* @__PURE__ */ new Set();
		const nativeLayoutScriptEntries = /* @__PURE__ */ new Set();
		let resolvedPageLayoutPlan;
		let entryCodeSource;
		let autoRoutesSignature = configService.isDev ? ctx.autoRoutesService?.getSignature?.() : void 0;
		const normalizedVueEntryPath = vueEntryPath ? normalizeFsResolvedId(vueEntryPath) : void 0;
		const registerPageLayoutComponentEntries = async (layoutPlan, options) => {
			if (options?.trackLayoutDependencies) {
				const layoutDependencies = /* @__PURE__ */ new Set();
				for (const file of await expandResolvedPageLayoutFiles(layoutPlan.layouts, configService.platform)) layoutDependencies.add(normalizeFsResolvedId(file));
				replaceLayoutDependencies(normalizedId, layoutDependencies);
			}
			await registerResolvedPageLayoutDependencies(ctx, normalizedId, layoutPlan.layouts);
			await registerResolvedPageLayoutEntries({
				layouts: layoutPlan.layouts,
				entries,
				explicitEntryTypes,
				nativeScriptEntries: nativeLayoutScriptEntries,
				normalizeEntry,
				jsonPath,
				platform: configService.platform
			});
			for (const layout of layoutPlan.layouts) {
				if (layout.kind === "native") continue;
				if (!layout.file.endsWith(".vue")) continue;
				if (!await shouldEmitScriptlessVueLayoutJs$1(layout.file)) continue;
				const relativeLayoutBase = configService.relativeOutputPath(removeExtensionDeep(layout.file));
				if (!relativeLayoutBase || emittedScriptlessVueLayoutJs.has(relativeLayoutBase)) continue;
				emittedScriptlessVueLayoutJs.add(relativeLayoutBase);
				const { scriptExtension } = resolveCompilerOutputExtensions(configService.outputExtensions);
				emitScriptlessComponentAsset(this, resolveScriptlessComponentFileName(relativeLayoutBase, scriptExtension), SLOT_HOST_SCRIPTLESS_COMPONENT_STUB);
			}
		};
		if (type === "app") {
			if (configService.isDev && vueEntryPath) {
				const vueSource = await readVueSource();
				if (vueSource) {
					const signatureStartedAt = performance$1.now();
					const signatures = resolveVueSfcHmrSignatures(vueSource, vueEntryPath);
					recordEntryDuration("entryVueSignatureMs", signatureStartedAt);
					appVueNonJsonSignature = signatures.nonJsonSignature;
					storeVueSfcHmrSignatures(ctx.runtimeState.build.hmr, normalizedVueEntryPath, signatures);
				}
			}
			if (vueEntryPath && ctx.autoRoutesService?.isEnabled?.() && !ctx.runtimeState.autoRoutes.loadingAppConfig) {
				await ctx.autoRoutesService.ensureFresh();
				const refreshedConfigFromVue = await extractConfigFromVue(vueEntryPath, {
					source: await readVueSource(),
					force: true
				});
				if (isObject(refreshedConfigFromVue)) {
					json = refreshedConfigFromVue;
					hasJsonEntry = true;
				}
			}
			appResult = await collectAppEntries({
				pluginCtx: this,
				id,
				json,
				ctx,
				isPluginBuild,
				registerJsonAsset,
				existsCache,
				pathExistsTtlMs,
				normalizeEntry,
				resolveEntryWithCache: entryResolver.resolveEntryWithCache,
				extendedLibManager,
				cache: appEntriesCache
			});
			if (appResult.appJson) json = appResult.appJson;
			autoRoutesSignature = configService.isDev ? ctx.autoRoutesService?.getSignature?.() : void 0;
			entries.push(...appResult.entries);
			const registerAppComponentEntry = (entry) => {
				entries.push(entry);
				explicitEntryTypes.set(normalizeEntry(entry, jsonPath), "component");
				explicitEntryTypes.set(normalizeEntry(`/${entry}`, jsonPath), "component");
			};
			if (get(json, "tabBar.custom")) registerAppComponentEntry("custom-tab-bar/index");
			if (get(json, "appBar")) registerAppComponentEntry("app-bar/index");
			pluginResolvedRecords = appResult.pluginResolvedRecords;
			if (appResult.pluginEntryTypes?.length) for (const entryType of appResult.pluginEntryTypes) entriesMap.set(entryType.entry, {
				type: entryType.type,
				path: entryType.entry
			});
			pluginJsonPathForRegistration = appResult.pluginJsonPathForRegistration;
			pluginJsonForRegistration = appResult.pluginJsonForRegistration;
			shouldSkipAppEntries = Boolean(configService.isDev && !isPluginBuild && !dirtyEntrySet.has(normalizedId) && !dirtyEntrySet.has(normalizedVueEntryPath ?? "") && appResult.cacheHit && appEntryOutputCache.current && appEntryOutputCache.current.appSignature === appResult.appSignature && appEntryOutputCache.current.appVueNonJsonSignature === appVueNonJsonSignature && appEntryOutputCache.current.pluginSignature === appResult.pluginSignature && appEntryOutputCache.current.pluginJsonPath === appResult.pluginJsonPath && appEntryOutputCache.current.autoRoutesSignature === autoRoutesSignature && appEntryOutputCache.current.resolveCacheVersion === resolveCacheVersion);
		} else {
			const templateScanStartedAt = performance$1.now();
			try {
				templatePath = (isJsonStableHmr ? templateEntryPathCache.get(normalizedId) : void 0) ?? await scanTemplateEntry(this, id, scanTemplateEntryFn, existsCache, pathExistsTtlMs, configService.platform);
				templateEntryPathCache.set(normalizedId, templatePath);
			} finally {
				recordEntryDuration("entryTemplateScanMs", templateScanStartedAt);
			}
			if (libEntry && libConfig) {
				const componentJson = libConfig.componentJson ?? "auto";
				const hasTemplate = Boolean(templatePath) || id.endsWith(".vue");
				const styleEntry = await findCssEntry(baseName, configService.platform);
				const hasStyle = Boolean(styleEntry.path);
				const shouldTreatAsComponent = hasTemplate || hasStyle || Boolean(json?.component);
				if (!hasJsonEntry && shouldTreatAsComponent) {
					if (componentJson === true || componentJson === "auto" || typeof componentJson === "function") {
						const extra = typeof componentJson === "function" ? componentJson({
							name: libEntry.name,
							input: libEntry.input
						}) : void 0;
						if (typeof componentJson === "function" && !isObject(extra)) throw new Error("`weapp.lib.componentJson` 必须返回对象。");
						json = {
							component: true,
							...isObject(extra) ? extra : {}
						};
						hasJsonEntry = true;
					}
				}
				if (shouldTreatAsComponent) entryTypeOverride = "component";
			}
			if (vueEntryPath) {
				const vueSourceForEntry = type === "page" || configService.isDev && hasJsonEntry ? await readVueSource() : void 0;
				const scriptSetupStartedAt = performance$1.now();
				try {
					await applyScriptSetupUsingComponents({
						pluginCtx: this,
						vueEntryPath,
						source: vueSourceForEntry,
						templatePath,
						json,
						configService,
						wxmlService,
						reExportResolutionCache,
						externalComponentEntryMap: ctx.runtimeState.build.hmr.externalComponentEntryMap
					});
				} finally {
					recordEntryDuration("entryScriptSetupMs", scriptSetupStartedAt);
				}
				if (type === "page") {
					const vueSource = await readVueSource();
					if (vueSource) {
						const layoutStartedAt = performance$1.now();
						try {
							const hasLayoutHint = hasPageLayoutSourceHint(vueSource);
							const cachedLayoutPlan = isStableHmr && !hasLayoutHint ? staticPageLayoutPlanCache.get(normalizedId) : void 0;
							const layoutPlan = cachedLayoutPlan === void 0 ? await resolvePageLayoutPlan(vueSource, vueEntryPath, configService) : cachedLayoutPlan ?? void 0;
							resolvedPageLayoutPlan = layoutPlan ?? null;
							replaceLayoutDependencies(normalizedId, []);
							if (hasLayoutHint) staticPageLayoutPlanCache.delete(normalizedId);
							else if (cachedLayoutPlan === void 0) staticPageLayoutPlanCache.set(normalizedId, layoutPlan ?? null);
							if (layoutPlan) await registerPageLayoutComponentEntries(layoutPlan, { trackLayoutDependencies: hasLayoutHint });
						} finally {
							recordEntryDuration("entryLayoutMs", layoutStartedAt);
						}
					}
				}
			} else if (type === "page" && templatePath && !VUE_LIKE_PAGE_ENTRY_RE.test(id)) {
				const layoutStartedAt = performance$1.now();
				try {
					replaceLayoutDependencies(normalizedId, []);
					const source = await fs$1.readFile(id, "utf-8");
					entryCodeSource = source;
					const hasLayoutHint = hasPageLayoutSourceHint(source);
					const cachedLayoutPlan = isStableHmr && !hasLayoutHint ? staticPageLayoutPlanCache.get(normalizedId) : void 0;
					const layoutPlan = cachedLayoutPlan === void 0 ? await resolvePageLayoutPlan(source, id, configService) : cachedLayoutPlan ?? void 0;
					if (hasLayoutHint) staticPageLayoutPlanCache.delete(normalizedId);
					else if (cachedLayoutPlan === void 0) staticPageLayoutPlanCache.set(normalizedId, layoutPlan ?? null);
					resolvedPageLayoutPlan = layoutPlan ?? null;
					if (layoutPlan) await registerPageLayoutComponentEntries(layoutPlan, { trackLayoutDependencies: true });
				} finally {
					recordEntryDuration("entryLayoutMs", layoutStartedAt);
				}
			}
			if (configService.isDev && hasJsonEntry && vueEntryPath) {
				const vueSource = await readVueSource();
				if (vueSource) {
					const signatureStartedAt = performance$1.now();
					const signatures = resolveVueSfcHmrSignatures(vueSource, vueEntryPath);
					recordEntryDuration("entryVueSignatureMs", signatureStartedAt);
					storeVueSfcHmrSignatures(ctx.runtimeState.build.hmr, normalizedId, signatures);
				}
			}
			const autoImportStartedAt = performance$1.now();
			try {
				if (ctx.autoImportService?.hasPendingRegistrations?.() !== false) await ctx.autoImportService?.awaitPendingRegistrations?.();
				const rawInjectedAutoImportEntries = await applyAutoImports(baseName, json) ?? [];
				const injectedAutoImportEntries = await materializeVueAutoImportEntries(this, vueEntryPath ?? id, json, rawInjectedAutoImportEntries);
				const componentEntries = analyzeCommonJson(json);
				const pendingAutoImportMap = ctx.runtimeState?.autoImport?.pendingEntriesByImporter;
				const vueBaseName = vueEntryPath ? removeExtensionDeep(vueEntryPath) : void 0;
				const pendingAutoImportEntries = Array.from(/* @__PURE__ */ new Set([...Array.from(pendingAutoImportMap?.get(baseName) ?? []), ...Array.from(vueBaseName ? pendingAutoImportMap?.get(vueBaseName) ?? [] : [])]));
				if (pendingAutoImportEntries.length) {
					pendingAutoImportMap?.delete(baseName);
					if (vueBaseName) pendingAutoImportMap?.delete(vueBaseName);
				}
				const mergedComponentEntries = Array.from(/* @__PURE__ */ new Set([...componentEntries, ...pendingAutoImportEntries]));
				entries.push(...mergedComponentEntries);
				for (const componentEntry of mergedComponentEntries) {
					const normalizedComponentEntry = normalizeEntry(componentEntry, jsonPath);
					explicitEntryTypes.set(normalizedComponentEntry, "component");
					const isPendingAutoImportEntry = pendingAutoImportEntries.includes(componentEntry);
					if (isPendingAutoImportEntry || injectedAutoImportEntries.includes(componentEntry)) forceEmitEntrySet.add(normalizedComponentEntry);
					if (isPendingAutoImportEntry) forceReloadEntrySet.add(normalizedComponentEntry);
				}
			} finally {
				recordEntryDuration("entryAutoImportMs", autoImportStartedAt);
			}
		}
		const prepareStartedAt = performance$1.now();
		const ownerEntryKey = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(id));
		const ownerEntry = type === "app" ? { ...entriesMap.get(ownerEntryKey) } : {};
		entriesMap.set(ownerEntryKey, {
			...ownerEntry,
			type,
			path: id,
			json,
			...jsonPath ? { jsonPath } : {},
			...templatePath ? { templatePath } : {}
		});
		const normalizedEntries = shouldSkipAppEntries ? [] : prepareNormalizedEntries({
			entries,
			json,
			jsonPath,
			templatePath,
			id,
			skipOwnEntries: isPluginBuild && type === "app",
			entriesMap,
			normalizeEntry,
			extendedLibManager,
			entryType: entryTypeOverride,
			explicitEntryTypes
		});
		markComponentEntries(entriesMap, nativeLayoutScriptEntries);
		recordEntryDuration("entryPrepareMs", prepareStartedAt);
		const entryResolveRoot = isPluginBuild && configService.absolutePluginRoot && isPathInside(configService.absolutePluginRoot, id) ? configService.absolutePluginRoot : configService.absoluteSrcRoot;
		const emitOutputStartedAt = performance$1.now();
		const result = await (async () => {
			try {
				return await emitEntryOutput({
					pluginCtx: this,
					id,
					type,
					json,
					jsonPath,
					templatePath,
					isPluginBuild,
					normalizedEntries,
					entriesMap,
					pluginResolvedRecords,
					pluginJsonPathForRegistration,
					pluginJsonForRegistration,
					resolveEntriesWithCache: entryResolver.resolveEntriesWithCache,
					resolveMappedEntry: (entry) => ctx.runtimeState.build.hmr.externalComponentEntryMap.get(entry),
					entryResolveRoot,
					configService,
					runtimeState: ctx.runtimeState,
					wxmlService,
					resolvedEntryMap,
					loadedEntrySet,
					dirtyEntrySet,
					forceEmitEntrySet,
					forceReloadEntrySet,
					replaceLayoutDependencies,
					replaceEntryDependencies: (entryId, kind, dependencies) => {
						ctx.moduleGraphService.replaceEntryDependencies(entryId, kind, dependencies);
					},
					emitEntriesChunks,
					registerJsonAsset,
					existsCache,
					pathExistsTtlMs,
					debug,
					relativeCwdId,
					getTime,
					emittedWxmlCodeCache: ctx.runtimeState?.wxml?.emittedCode,
					styleImportsCache,
					resolvedPageLayoutPlan,
					entryCodeSource,
					skipEntries: shouldSkipAppEntries,
					metadataOnly: loadOptions?.metadataOnly
				});
			} finally {
				recordEntryDuration("entryEmitOutputMs", emitOutputStartedAt);
			}
		})();
		if (type === "app" && !shouldSkipAppEntries && appResult) {
			ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature = autoRoutesSignature;
			appEntryOutputCache.current = {
				appSignature: appResult.appSignature,
				appVueNonJsonSignature,
				pluginSignature: appResult.pluginSignature,
				pluginJsonPath: appResult.pluginJsonPath,
				autoRoutesSignature,
				resolveCacheVersion
			};
		}
		return result;
	}, { invalidateResolveCache() {
		entryResolver.invalidate();
		scriptlessVueLayoutDecisionCache.clear();
		entrySidecarResolutionCache.clear();
		entryJsonCache.clear();
		vueConfigCache.clear();
		staticPageLayoutPlanCache.clear();
		templateEntryPathCache.clear();
		styleImportsCache.clear();
		resolveCacheVersion += 1;
		appEntryOutputCache.current = void 0;
	} });
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/normalizer.ts
const PLUGIN_PROTOCOL_RE = /plugin:\/\//;
const WINDOWS_PATH_SEPARATOR_RE = /\\/g;
function resolveImportee(importee, jsonPath, configService) {
	let updated = importee;
	if (jsonPath && Array.isArray(configService.aliasEntries)) {
		const matchedEntry = configService.aliasEntries.find((entry) => matches(entry.find, importee));
		if (matchedEntry) updated = importee.replace(matchedEntry.find, matchedEntry.replacement);
	}
	const baseDir = jsonPath ? path.dirname(jsonPath) : configService.absoluteSrcRoot;
	return path.resolve(baseDir, updated);
}
function createEntryNormalizer(configService) {
	return function normalizeEntry(entry, jsonPath) {
		if (PLUGIN_PROTOCOL_RE.test(entry)) return entry;
		const normalizedEntry = normalizeNpmImportLookupPath(entry);
		if (normalizedEntry && isObject(configService.packageJson.dependencies) && hasNpmDependencyPrefix(configService.packageJson.dependencies, normalizedEntry)) return `npm:${normalizedEntry}`;
		if (entry.replace(WINDOWS_PATH_SEPARATOR_RE, "/").startsWith("/")) return normalizedEntry;
		const normalized = resolveImportee(normalizedEntry, jsonPath, configService);
		return configService.relativeAbsoluteSrcRoot(normalized);
	};
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/template.ts
function createTemplateScanner(wxmlService, debug) {
	return async function scanTemplateEntry(templateEntry) {
		const start = performance$1.now();
		const wxmlToken = await wxmlService.scan(templateEntry);
		if (wxmlToken) {
			const { components } = wxmlToken;
			wxmlService.setWxmlComponentsMap(templateEntry, components);
		}
		debug?.(`scanTemplateEntry ${templateEntry} 耗时 ${(performance$1.now() - start).toFixed(2)}ms`);
	};
}
//#endregion
//#region src/plugins/hooks/useLoadEntry/index.ts
function shouldExpandStableSharedChunk(chunkId, importers) {
	if ((importers?.size ?? 0) <= 1) return false;
	return chunkId.startsWith("weapp-vendors/") || !chunkId.includes("/") && chunkId !== "app.js";
}
function resolveUpstreamPendingReasonSummary(dirtyReasonSummary) {
	if (!dirtyReasonSummary?.length) return [];
	const pendingReasonSummary = [];
	const hasLayoutFallback = dirtyReasonSummary.some((item) => item.startsWith("layout-fallback-full:"));
	const hasLayoutPropagation = dirtyReasonSummary.some((item) => item.startsWith("layout-self:") || item.startsWith("layout-dependent:"));
	const hasAutoRoutesTopology = dirtyReasonSummary.some((item) => item.startsWith("auto-routes-topology:"));
	if (dirtyReasonSummary.some((item) => item.startsWith("config-restart:"))) pendingReasonSummary.push("config-restart");
	if (hasLayoutFallback) pendingReasonSummary.push("layout-fallback-full");
	else if (hasLayoutPropagation) pendingReasonSummary.push("layout-propagation");
	if (hasAutoRoutesTopology) pendingReasonSummary.push("auto-routes-topology");
	return pendingReasonSummary;
}
function isEntryAutoRoutesRefresh(dirtyReasonSummary) {
	return dirtyReasonSummary?.some((item) => item.startsWith("entry-auto-routes:")) === true;
}
function isSharedChunkSourceRepresentativeRefresh(dirtyReasonSummary) {
	return Boolean(dirtyReasonSummary?.length && dirtyReasonSummary.some((item) => item.startsWith("shared-chunk-source:")) && dirtyReasonSummary.every((item) => item.startsWith("shared-chunk-source:") || item.startsWith("tailwind-content:")));
}
function isCssImporterOnlyRefresh(dirtyReasonSummary) {
	return Boolean(dirtyReasonSummary?.length && dirtyReasonSummary.every((item) => item.startsWith("css-importer:") || item.startsWith("css-importer-fallback:")));
}
function isWxmlImportOnlyRefresh(dirtyReasonSummary) {
	return Boolean(dirtyReasonSummary?.length && dirtyReasonSummary.every((item) => item.startsWith("wxml-importer-import:")));
}
function isVueEntryId(entryId) {
	return vueExtensions.some((ext) => entryId.endsWith(`.${ext}`));
}
function resolveCssImporterRepresentative(pending, resolvedEntryMap, rootInputIds) {
	let fallback;
	let nonRootFallback;
	for (const entryId of pending) {
		if (!resolvedEntryMap.has(entryId)) continue;
		const isRootInput = rootInputIds?.has(entryId) === true;
		if (!fallback) fallback = entryId;
		if (!isRootInput && !nonRootFallback) nonRootFallback = entryId;
		if (!isRootInput && !isVueEntryId(entryId)) return entryId;
	}
	return nonRootFallback ?? fallback;
}
function resolveSharedChunkRepresentative(importers, pending, resolvedEntryMap) {
	let resolvedRepresentative;
	for (const entryId of importers) {
		if (pending.has(entryId)) return entryId;
		if (!resolvedRepresentative && resolvedEntryMap.has(entryId)) resolvedRepresentative = entryId;
	}
	return resolvedRepresentative;
}
function previewChunkIds(chunkIds) {
	const preview = [];
	for (const chunkId of chunkIds) {
		if (preview.length >= 2) break;
		const segments = chunkId.split("/");
		preview.push(segments[segments.length - 1]);
	}
	return {
		label: preview.join(","),
		overflow: chunkIds.size > 2 ? "+" : ""
	};
}
function resolvePendingEntryIds(options) {
	const pending = new Set(options.dirtyEntrySet);
	const pendingReasonSummary = resolveUpstreamPendingReasonSummary(options.dirtyReasonSummary);
	if (options.mode === "full") return {
		pending: new Set(options.resolvedEntryMap.keys()),
		pendingReasonSummary: ["full-rebuild", ...pendingReasonSummary]
	};
	if (!options.isDev || options.mode === "off") return {
		pending,
		pendingReasonSummary
	};
	if ((isCssImporterOnlyRefresh(options.dirtyReasonSummary) || isWxmlImportOnlyRefresh(options.dirtyReasonSummary)) && pending.size > 1) {
		const representative = resolveCssImporterRepresentative(pending, options.resolvedEntryMap, options.rootInputIds);
		if (representative) {
			const reason = isWxmlImportOnlyRefresh(options.dirtyReasonSummary) ? "wxml-importer-import-representative" : "css-importer-representative";
			pendingReasonSummary.push(`${reason}:1/${pending.size}`);
			return {
				pending: /* @__PURE__ */ new Set([representative]),
				hmrEntries: pending,
				pendingReasonSummary
			};
		}
	}
	if (!options.sharedChunkImporters?.size || !options.sharedChunksByEntry?.size) return {
		pending,
		pendingReasonSummary
	};
	const startedAt = performance.now();
	const relatedChunkIds = /* @__PURE__ */ new Set();
	const shouldExpandLayoutSharedChunks = pendingReasonSummary.includes("layout-propagation") || pendingReasonSummary.includes("layout-fallback-full");
	if (shouldExpandLayoutSharedChunks) for (const chunkId of options.sharedChunkImporters.keys()) relatedChunkIds.add(chunkId);
	for (const entryId of options.dirtyEntrySet) {
		const dirtyReason = options.dirtyEntryReasons.get(entryId);
		if (dirtyReason !== "dependency" && dirtyReason !== "direct" && dirtyReason !== "metadata") continue;
		const chunkIds = options.sharedChunksByEntry.get(entryId);
		if (!chunkIds?.size) continue;
		for (const chunkId of chunkIds) {
			const isSourceSharedChunk = options.sourceSharedChunks?.has(chunkId) === true;
			const isStableSharedChunk = shouldExpandStableSharedChunk(chunkId, options.sharedChunkImporters?.get(chunkId));
			if (dirtyReason === "metadata") continue;
			if (dirtyReason === "dependency" || !isSourceSharedChunk && !isStableSharedChunk) relatedChunkIds.add(chunkId);
		}
	}
	if (!relatedChunkIds.size) return {
		pending,
		sharedChunkResolveMs: performance.now() - startedAt,
		pendingReasonSummary
	};
	const expandedImporters = /* @__PURE__ */ new Set();
	let expansionMode = null;
	let hasStableSharedChunkExpansion = false;
	const representativeImporters = /* @__PURE__ */ new Set();
	for (const chunkId of relatedChunkIds) {
		const importers = options.sharedChunkImporters.get(chunkId);
		if (!importers) continue;
		if (importers.size <= 1 && !shouldExpandLayoutSharedChunks) continue;
		let hasDependencyDrivenImporter = false;
		let hasDirectDirtyImporter = false;
		for (const importer of importers) {
			if (options.dirtyEntrySet.has(importer) && options.dirtyEntryReasons.get(importer) === "dependency") {
				hasDependencyDrivenImporter = true;
				continue;
			}
			if (options.dirtyEntrySet.has(importer) && options.dirtyEntryReasons.get(importer) === "direct") hasDirectDirtyImporter = true;
		}
		if (!hasDependencyDrivenImporter && !hasDirectDirtyImporter && !shouldExpandLayoutSharedChunks) continue;
		if (shouldExpandStableSharedChunk(chunkId, importers)) hasStableSharedChunkExpansion = true;
		if (isSharedChunkSourceRepresentativeRefresh(options.dirtyReasonSummary)) {
			const representative = resolveSharedChunkRepresentative(importers, pending, options.resolvedEntryMap);
			if (representative) representativeImporters.add(representative);
		}
		if (shouldExpandLayoutSharedChunks && !hasDependencyDrivenImporter && !hasDirectDirtyImporter) expansionMode = expansionMode && expansionMode !== "dependency" ? "mixed" : "dependency";
		else if ([hasDependencyDrivenImporter, hasDirectDirtyImporter].filter(Boolean).length > 1) expansionMode = "mixed";
		else if (hasDirectDirtyImporter) expansionMode = expansionMode && expansionMode !== "direct" ? "mixed" : "direct";
		else expansionMode = expansionMode && expansionMode !== "dependency" ? "mixed" : "dependency";
		for (const importer of importers) {
			if (!pending.has(importer)) expandedImporters.add(importer);
			pending.add(importer);
		}
	}
	if (expandedImporters.size > 0) {
		const { label: chunkPreview, overflow } = previewChunkIds(relatedChunkIds);
		const mode = expansionMode ? `:${expansionMode}` : "";
		pendingReasonSummary.push(`shared-chunk(${chunkPreview}${overflow})+${expandedImporters.size}${mode}`);
	}
	if (representativeImporters.size && representativeImporters.size < pending.size) {
		const hmrEntries = new Set(pending);
		const representativePending = /* @__PURE__ */ new Set();
		for (const entryId of representativeImporters) if (pending.has(entryId)) representativePending.add(entryId);
		if (representativePending.size) {
			pendingReasonSummary.push(`shared-chunk-representative:${representativePending.size}/${hmrEntries.size}`);
			return {
				pending: representativePending,
				hmrEntries,
				sharedChunkResolveMs: performance.now() - startedAt,
				pendingReasonSummary
			};
		}
	}
	return {
		pending,
		sharedChunkResolveMs: performance.now() - startedAt,
		pendingReasonSummary,
		shouldEmitAllEntries: hasStableSharedChunkExpansion && pending.size === options.resolvedEntryMap.size,
		forceFullSharedChunkRefresh: hasStableSharedChunkExpansion && pending.size === options.resolvedEntryMap.size
	};
}
function shouldPreloadEntryAssetOnly(dirtyReasonSummary) {
	return dirtyReasonSummary?.some((item) => item.startsWith("json-sidecar:") || item.startsWith("entry-json-only:") || item.startsWith("style-sidecar:") || item.startsWith("entry-style-only:") || item.startsWith("entry-local-asset:") || item.startsWith("wxml-importer-import:")) === true;
}
function resolveCurrentStyleOutputFileName(ctx) {
	const currentFile = ctx.runtimeState.build.hmr.profile.file;
	if (typeof currentFile !== "string") return;
	const normalizedFile = normalizeFsResolvedId(currentFile);
	if (!supportedCssLangs.some((ext) => normalizedFile.endsWith(`.${ext}`))) return;
	return ctx.configService.relativeOutputPath(changeFileExtension(normalizedFile, ctx.configService.outputExtensions.wxss));
}
function createChunkEmitStatsSummary() {
	return {
		chunkEmitCount: 0,
		emitFileMs: 0,
		loadCount: 0,
		loadMs: 0,
		skippedLoadedCount: 0
	};
}
function addChunkEmitStatsSummary(target, source) {
	target.chunkEmitCount += source.chunkEmitCount;
	target.emitFileMs += source.emitFileMs;
	target.loadCount += source.loadCount;
	target.loadMs += source.loadMs;
	target.skippedLoadedCount += source.skippedLoadedCount;
}
function useLoadEntry(ctx, options) {
	const debug = createDebugger("weapp-vite:load-entry");
	const buildTarget = options?.buildTarget ?? "app";
	const entriesMap = ctx.runtimeState.build.hmr.entriesMap;
	const loadedEntrySet = ctx.runtimeState.build.hmr.loadedEntrySet;
	const dirtyEntrySet = ctx.runtimeState.build.hmr.dirtyEntrySet;
	const dirtyEntryReasons = ctx.runtimeState.build.hmr.dirtyEntryReasons;
	const dirtyEntryEventIds = /* @__PURE__ */ new Map();
	const resolvedEntryMap = ctx.runtimeState.build.hmr.resolvedEntryMap;
	const lastActualEmittedEntryIds = /* @__PURE__ */ new Set();
	const lastChunkEmittedEntryIds = /* @__PURE__ */ new Set();
	const lastEmittedChunkFileNames = ctx.runtimeState.build.hmr.lastEmittedChunkFileNames ??= /* @__PURE__ */ new Set();
	const metadataEntryIds = /* @__PURE__ */ new Set();
	const rootInputIds = options?.hmr?.rootInputIds;
	const chunkEmitStats = createChunkEmitStatsSummary();
	const addLastEmittedChunkFileName = (entryId) => {
		lastEmittedChunkFileNames.add(changeFileExtension(ctx.configService.relativeOutputPath(entryId), ".js"));
		if (rootInputIds?.has(entryId)) lastEmittedChunkFileNames.add(changeFileExtension(ctx.configService.relativeAbsoluteSrcRoot(entryId), ".js"));
	};
	const jsonEmitManager = createJsonEmitManager(ctx.configService);
	const registerJsonAsset = jsonEmitManager.register.bind(jsonEmitManager);
	const normalizeEntry = createEntryNormalizer(ctx.configService);
	const scanTemplateEntry = createTemplateScanner(ctx.wxmlService, debug);
	let loadEntry;
	const emitEntriesChunks = createChunkEmitter(ctx.configService, loadedEntrySet, debug, (entryId) => {
		if (rootInputIds?.has(entryId)) {
			addLastEmittedChunkFileName(entryId);
			if (!metadataEntryIds.has(entryId)) lastChunkEmittedEntryIds.add(entryId);
		}
		lastActualEmittedEntryIds.add(entryId);
	}, (entryId) => {
		lastChunkEmittedEntryIds.add(entryId);
	}, (entryId) => !rootInputIds?.has(entryId) && !metadataEntryIds.has(entryId) && !lastChunkEmittedEntryIds.has(entryId), async function preloadAssetOnlyEntry(resolvedId, entryId) {
		if (rootInputIds?.has(entryId)) {
			const relativeBase = removeExtensionDeep(ctx.configService.relativeAbsoluteSrcRoot(entryId));
			const declaredType = entriesMap.get(relativeBase)?.type;
			await loadEntry.call(this, resolvedId.id, declaredType === "page" ? "page" : declaredType === "component" ? "component" : "app");
			return;
		}
		if (!shouldPreloadEntryAssetOnly(ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) {
			await this.load(resolvedId);
			return;
		}
		const entryType = entriesMap.get(entryId)?.type === "page" ? "page" : "component";
		await loadEntry.call(this, resolvedId.id, entryType);
	}, (fileName) => {
		lastEmittedChunkFileNames.add(fileName);
	}, (stats) => addChunkEmitStatsSummary(chunkEmitStats, stats), (entryId) => {
		const relativeBase = removeExtensionDeep(ctx.configService.relativeAbsoluteSrcRoot(entryId));
		return createLogicalEntryId(entryId, ctx.moduleGraphService?.isLogicalLayoutEntry?.(entryId) ? "layout" : rootInputIds?.has(entryId) ? "app" : entriesMap.get(relativeBase)?.type === "page" ? "page" : "component");
	});
	loadEntry = createEntryLoader({
		ctx,
		entriesMap,
		loadedEntrySet,
		dirtyEntrySet,
		resolvedEntryMap,
		replaceLayoutDependencies(entryId, dependencies) {
			ctx.moduleGraphService.replaceEntryDependencies(entryId, "layout", dependencies);
		},
		normalizeEntry,
		registerJsonAsset,
		scanTemplateEntry,
		emitEntriesChunks,
		applyAutoImports: createAutoImportAugmenter(ctx.autoImportService, ctx.wxmlService, ctx.runtimeState.build.hmr.externalComponentEntryMap, ctx.configService),
		extendedLibManager: createExtendedLibManager(),
		buildTarget,
		debug
	});
	const hmrSharedChunksMode = options?.hmr?.sharedChunks ?? "auto";
	const hmrSharedChunkImporters = options?.hmr?.sharedChunkImporters;
	const hmrSharedChunksByEntry = options?.hmr?.sharedChunksByEntry;
	const clearDirtyEntry = (entryId) => {
		dirtyEntrySet.delete(entryId);
		dirtyEntryReasons.delete(entryId);
		dirtyEntryEventIds.delete(entryId);
	};
	return {
		loadEntry,
		entriesMap,
		loadedEntrySet,
		dirtyEntrySet,
		resolvedEntryMap,
		jsonEmitFilesMap: jsonEmitManager.map,
		normalizeEntry,
		markEntryDirty(entryId, reason = "direct") {
			dirtyEntrySet.add(entryId);
			dirtyEntryEventIds.set(entryId, ctx.runtimeState.build.hmr.profile.eventId);
			const previous = dirtyEntryReasons.get(entryId);
			const nextReason = previous === "dependency" || reason === "dependency" ? "dependency" : previous === "direct" || reason === "direct" ? "direct" : reason;
			dirtyEntryReasons.set(entryId, nextReason);
			loadedEntrySet.delete(entryId);
		},
		async emitDirtyEntries() {
			if (!dirtyEntrySet.size) {
				options?.hmr?.setDidEmitAllEntries?.(false);
				options?.hmr?.setLastEmittedEntries?.(/* @__PURE__ */ new Set());
				options?.hmr?.setLastHmrEntries?.(/* @__PURE__ */ new Set());
				options?.hmr?.setSkipSharedChunkRefresh?.(true);
				return;
			}
			const emitStartedAt = performance.now();
			const currentEventId = ctx.runtimeState.build.hmr.profile.eventId;
			const activeDirtyEntrySet = currentEventId ? new Set([...dirtyEntrySet].filter((entryId) => {
				const eventId = dirtyEntryEventIds.get(entryId);
				return eventId === void 0 || eventId === currentEventId;
			})) : dirtyEntrySet;
			if (!activeDirtyEntrySet.size) {
				options?.hmr?.setDidEmitAllEntries?.(false);
				options?.hmr?.setLastEmittedEntries?.(/* @__PURE__ */ new Set());
				options?.hmr?.setLastHmrEntries?.(/* @__PURE__ */ new Set());
				options?.hmr?.setSkipSharedChunkRefresh?.(true);
				return;
			}
			const dirtyCount = activeDirtyEntrySet.size;
			const pendingResolution = resolvePendingEntryIds({
				isDev: Boolean(ctx.configService?.isDev),
				mode: hmrSharedChunksMode,
				resolvedEntryMap,
				dirtyEntrySet: activeDirtyEntrySet,
				dirtyEntryReasons,
				dirtyReasonSummary: ctx.runtimeState.build.hmr.profile.dirtyReasonSummary,
				sharedChunkImporters: hmrSharedChunkImporters,
				sharedChunksByEntry: hmrSharedChunksByEntry,
				sourceSharedChunks: options?.hmr?.sourceSharedChunks,
				rootInputIds
			});
			const pendingEntryIds = pendingResolution.pending;
			const pending = [];
			chunkEmitStats.chunkEmitCount = 0;
			chunkEmitStats.emitFileMs = 0;
			chunkEmitStats.loadCount = 0;
			chunkEmitStats.loadMs = 0;
			chunkEmitStats.skippedLoadedCount = 0;
			lastActualEmittedEntryIds.clear();
			lastChunkEmittedEntryIds.clear();
			lastEmittedChunkFileNames.clear();
			metadataEntryIds.clear();
			const pendingMetadataEntryIds = /* @__PURE__ */ new Set();
			const deferredDirtyEntryIds = /* @__PURE__ */ new Set();
			const autoImportReloadedEntryIds = /* @__PURE__ */ new Set();
			const reloadPendingAutoImportEntry = async (resolvedId) => {
				const entryId = normalizeFsResolvedId(resolvedId.id);
				if (autoImportReloadedEntryIds.has(entryId)) return;
				if (!await fs$1.pathExists(resolvedId.id)) return;
				autoImportReloadedEntryIds.add(entryId);
				const entryType = entriesMap.get(ctx.configService.relativeAbsoluteSrcRoot(removeExtensionDeep(resolvedId.id)))?.type === "component" ? "component" : "page";
				await loadEntry.call(this, resolvedId.id, entryType);
			};
			for (const entryId of pendingEntryIds) {
				if (dirtyEntryReasons.get(entryId) === "metadata") {
					metadataEntryIds.add(entryId);
					pendingMetadataEntryIds.add(entryId);
				}
				if (rootInputIds?.has(entryId)) deferredDirtyEntryIds.add(entryId);
				else clearDirtyEntry(entryId);
				const resolvedId = resolvedEntryMap.get(entryId);
				if (!resolvedId) {
					debug?.(`hmr unresolved entry ${entryId}`);
					continue;
				}
				pending.push(resolvedId);
			}
			for (const resolvedId of pending) {
				const baseName = removeExtensionDeep(resolvedId.id);
				if (!ctx.runtimeState.autoImport?.pendingEntriesByImporter.has(baseName)) continue;
				await reloadPendingAutoImportEntry(resolvedId);
			}
			if (pending.length) {
				const entryChunkEmitStartedAt = performance.now();
				try {
					await Promise.all(emitEntriesChunks.call(this, pending));
				} finally {
					recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "entryChunkEmitMs", performance.now() - entryChunkEmitStartedAt);
				}
			}
			for (const resolvedId of pending) {
				const baseName = removeExtensionDeep(resolvedId.id);
				const autoImportComponents = ctx.wxmlService.getAggregatedAutoImportComponents?.(baseName);
				if (!autoImportComponents || Object.keys(autoImportComponents).length === 0) continue;
				await reloadPendingAutoImportEntry(resolvedId);
			}
			for (const entryId of deferredDirtyEntryIds) clearDirtyEntry(entryId);
			for (const entryId of activeDirtyEntrySet) clearDirtyEntry(entryId);
			const actualEmittedEntryIds = new Set(lastActualEmittedEntryIds);
			const actualChunkEmittedEntryIds = new Set(lastChunkEmittedEntryIds);
			for (const entryId of actualEmittedEntryIds) {
				if (!rootInputIds?.has(entryId)) continue;
				addLastEmittedChunkFileName(entryId);
			}
			if (isEntryAutoRoutesRefresh(ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) for (const entryId of actualChunkEmittedEntryIds) addLastEmittedChunkFileName(entryId);
			let hmrEntryIds = new Set(Array.from(actualEmittedEntryIds).filter((entryId) => pendingEntryIds.has(entryId)));
			if (pendingResolution.hmrEntries) hmrEntryIds = pendingResolution.hmrEntries;
			if (shouldPreloadEntryAssetOnly(ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) {
				if (!isWxmlImportOnlyRefresh(ctx.runtimeState.build.hmr.profile.dirtyReasonSummary) || !pendingResolution.hmrEntries) {
					hmrEntryIds = new Set(pendingMetadataEntryIds);
					for (const entryId of actualChunkEmittedEntryIds) if (pendingEntryIds.has(entryId) && !metadataEntryIds.has(entryId)) hmrEntryIds.add(entryId);
				}
				const currentStyleOutputFileName = resolveCurrentStyleOutputFileName(ctx);
				if (currentStyleOutputFileName) lastEmittedChunkFileNames.add(currentStyleOutputFileName);
			}
			const skipSharedChunkRefresh = actualChunkEmittedEntryIds.size === 0;
			const shouldEmitAllEntries = actualChunkEmittedEntryIds.size > 0 && (actualEmittedEntryIds.size === resolvedEntryMap.size || pendingResolution.shouldEmitAllEntries === true);
			options?.hmr?.setDidEmitAllEntries?.(shouldEmitAllEntries);
			options?.hmr?.setLastEmittedEntries?.(pendingResolution.forceFullSharedChunkRefresh === true ? new Set(resolvedEntryMap.keys()) : actualChunkEmittedEntryIds);
			options?.hmr?.setLastHmrEntries?.(hmrEntryIds);
			options?.hmr?.setSkipSharedChunkRefresh?.(skipSharedChunkRefresh);
			ctx.runtimeState.build.hmr.profile = {
				...ctx.runtimeState.build.hmr.profile,
				emitMs: performance.now() - emitStartedAt,
				sharedChunkResolveMs: pendingResolution.sharedChunkResolveMs,
				entryChunkLoadMs: chunkEmitStats.loadMs,
				entryChunkEmitFileMs: chunkEmitStats.emitFileMs,
				chunkEmitCount: chunkEmitStats.chunkEmitCount,
				loadCount: chunkEmitStats.loadCount,
				skippedLoadedCount: chunkEmitStats.skippedLoadedCount,
				dirtyCount,
				pendingCount: pending.length,
				emittedCount: hmrEntryIds.size,
				pendingReasonSummary: pendingResolution.pendingReasonSummary
			};
			if (debug) debug(`hmr emit dirty=${dirtyCount} resolved=${resolvedEntryMap.size} emitAll=${shouldEmitAllEntries} pending=${pending.length}`);
		}
	};
}
//#endregion
//#region src/plugins/core/helpers/bundle.ts
const IMPLICIT_REQUIRE_RE = /\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*require\((`[^`]+`|'[^']+'|"[^"]+")\);?/g;
const REQUIRE_CALL_RE = /\brequire\((`[^`]+`|'[^']+'|"[^"]+")\)/g;
const WEVU_SRC_CHUNK_RE = /(?:^|\/)wevu-src\.js$/;
const WEVU_VENDOR_RUNTIME_CHUNK_RE = /(?:^|\/)weapp-vendors\/wevu-[^/]+\.js$/;
const WEVU_EXPORT_ALIASES = [["defineComponent", "__wevuDefineComponent"], ["createWevuComponent", "__wevuCreateWevuComponent"]];
const WEVU_SYNTHETIC_SINGLE_PAGE_HOOK_EXPORTS = [
	"onAddToFavorites",
	"onSaveExitState",
	"onShareAppMessage",
	"onShareTimeline"
];
const WEVU_INTERNAL_REACTIVITY_EXPORTS = [
	"addMutationRecorder",
	"batch",
	"computed",
	"customRef",
	"effect",
	"effectScope",
	"endBatch",
	"getCurrentScope",
	"getDeepWatchStrategy",
	"getReactiveVersion",
	"isProxy",
	"isRaw",
	"isReactive",
	"isReadonly",
	"isRef",
	"isShallowReactive",
	"isShallowRef",
	"markRaw",
	"nextTick",
	"onScopeDispose",
	"prelinkReactiveTree",
	"reactive",
	"readonly",
	"ref",
	"removeMutationRecorder",
	"setDeepWatchStrategy",
	"shallowReactive",
	"shallowReadonly",
	"shallowRef",
	"startBatch",
	"stop",
	"toRaw",
	"toRef",
	"toRefs",
	"toValue",
	"touchReactive",
	"traverse",
	"triggerRef",
	"unref",
	"watch",
	"watchEffect",
	"watchPostEffect",
	"watchSyncEffect"
];
const WEVU_INTERNAL_TEMPLATE_EXPORTS = [
	"normalizeClass",
	"normalizeStyle",
	"resolvePropValue"
];
const WEVU_INTERNAL_RUNTIME_EXPORTS = [
	"callHookList",
	"callHookReturn",
	"createApp",
	"createWevuComponent",
	"createWevuScopedSlotComponent",
	"defineAppSetup",
	"defineComponent",
	"getCurrentInstance",
	"getCurrentPageStackSnapshot",
	"getCurrentSetupContext",
	"getNavigationBarMetrics",
	"hasInjectionContext",
	"inject",
	"injectGlobal",
	"isNoSetData",
	"markNoSetData",
	"mergeModels",
	"mountRuntimeInstance",
	"onActivated",
	"onAddToFavorites",
	"onAttached",
	"onBeforeMount",
	"onBeforeUnmount",
	"onBeforeUpdate",
	"onDeactivated",
	"onDetached",
	"onError",
	"onErrorCaptured",
	"onHide",
	"onLaunch",
	"onLoad",
	"onMemoryWarning",
	"onMounted",
	"onMoved",
	"onPageNotFound",
	"onPageScroll",
	"onPullDownRefresh",
	"onReachBottom",
	"onReady",
	"onResize",
	"onRouteDone",
	"onSaveExitState",
	"onServerPrefetch",
	"onShareAppMessage",
	"onShareTimeline",
	"onShow",
	"onTabItemTap",
	"onThemeChange",
	"onUnhandledRejection",
	"onUnload",
	"onUnmounted",
	"onUpdated",
	"provide",
	"provideGlobal",
	"registerApp",
	"registerComponent",
	"resetWevuDefaults",
	"resolveLayoutBridge",
	"resolveLayoutHost",
	"resolveRuntimePageLayoutName",
	"runSetupFunction",
	"setCurrentInstance",
	"setCurrentSetupContext",
	"setGlobalProvidedValue",
	"setPageLayout",
	"setRuntimeSetDataVisibility",
	"setWevuDefaults",
	"syncRuntimePageLayoutState",
	"syncRuntimePageLayoutStateFromRuntime",
	"teardownRuntimeInstance",
	"use",
	"useAsyncPullDownRefresh",
	"useAttrs",
	"useBindModel",
	"useBoundingClientRect",
	"useChangeModel",
	"useDisposables",
	"useElementIntersectionObserver",
	"useIntersectionObserver",
	"useLayoutBridge",
	"useLayoutHosts",
	"useModel",
	"useNativeInstance",
	"useNativePageRouter",
	"useNativeRouter",
	"useNavigationBarMetrics",
	"usePageLayout",
	"usePageScrollThrottle",
	"usePageStack",
	"useScrollOffset",
	"useSelectorFields",
	"useSelectorQuery",
	"useSlots",
	"useTemplateRef",
	"useUpdatePerformanceListener",
	"version",
	"waitForLayoutHost"
];
const WEVU_RUNTIME_MODULE_ID_PATTERN = ["wevu(?:\\/(?:router|store|api|fetch|web-apis|internal-(?:runtime|reactivity|template)))?", ...Object.values(WEAPP_VITE_RUNTIME_VIRTUAL_IDS).map((id) => id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))].join("|");
const WEVU_RUNTIME_NAMED_IMPORT_RE = new RegExp(`\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*["'](${WEVU_RUNTIME_MODULE_ID_PATTERN})["'];?`, "g");
const WEVU_RUNTIME_REQUIRE_RE = new RegExp(`\\brequire\\(\\s*(\`(?:${WEVU_RUNTIME_MODULE_ID_PATTERN})\`|'(?:${WEVU_RUNTIME_MODULE_ID_PATTERN})'|"(?:${WEVU_RUNTIME_MODULE_ID_PATTERN})")\\s*\\)`, "g");
function isWevuRuntimeSharedChunkCandidate(fileName) {
	return fileName.startsWith("weapp-vendors/") || !fileName.includes("/") && fileName !== "app.js" && fileName.endsWith(".js");
}
const WEVU_RUNTIME_MODULE_EXPORT_MARKERS = {
	"wevu": WEVU_INTERNAL_RUNTIME_EXPORTS,
	"wevu/router": [
		"createRouter",
		"useRouter",
		"useRoute",
		"NavigationFailureType"
	],
	"wevu/store": [
		"defineStore",
		"createPinia",
		"storeToRefs"
	],
	"wevu/api": ["createApi", "defineApi"],
	"wevu/fetch": ["createFetch", "useFetch"],
	"wevu/web-apis": ["installWebApis", "createWebApis"],
	"wevu/internal-runtime": WEVU_INTERNAL_RUNTIME_EXPORTS,
	"wevu/internal-reactivity": WEVU_INTERNAL_REACTIVITY_EXPORTS,
	"wevu/internal-template": WEVU_INTERNAL_TEMPLATE_EXPORTS
};
const WEVU_INTERNAL_REACTIVITY_EXPORT_SET = new Set(WEVU_INTERNAL_REACTIVITY_EXPORTS);
const WEVU_INTERNAL_TEMPLATE_EXPORT_SET = new Set(WEVU_INTERNAL_TEMPLATE_EXPORTS);
const WEVU_INTERNAL_RUNTIME_EXPORT_SET = new Set(WEVU_INTERNAL_RUNTIME_EXPORTS);
const JS_IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
function isRegexWordCharCode(code) {
	return code === 95 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
}
function containsIdentifierReference(code, identifier) {
	let index = code.indexOf(identifier);
	while (index >= 0) {
		const before = index > 0 ? code.charCodeAt(index - 1) : 0;
		const afterIndex = index + identifier.length;
		const after = afterIndex < code.length ? code.charCodeAt(afterIndex) : 0;
		if (!isRegexWordCharCode(before) && !isRegexWordCharCode(after)) return true;
		index = code.indexOf(identifier, afterIndex);
	}
	return false;
}
function containsWevuInternalRuntimeExportReference(code) {
	for (const exportName of WEVU_INTERNAL_RUNTIME_EXPORTS) if (containsIdentifierReference(code, exportName)) return true;
	return false;
}
function filterPluginBundleOutputs(bundle, configService) {
	if (configService.pluginOnly) return;
	const pluginOutputRoot = configService.absolutePluginOutputRoot;
	const pluginRoot = configService.absolutePluginRoot;
	const pluginBase = pluginRoot ? path.basename(pluginRoot) : "plugin";
	const relativeToOutDir = pluginOutputRoot ? path.relative(configService.outDir, pluginOutputRoot) : "";
	const isPluginOutputInsideOutDir = pluginOutputRoot ? relativeToOutDir === "" || !relativeToOutDir.startsWith("..") && !path.isAbsolute(relativeToOutDir) : false;
	const pluginBundleBase = pluginOutputRoot && isPluginOutputInsideOutDir ? normalizeRelativePath$1(relativeToOutDir) || pluginBase : pluginBase;
	for (const [fileName, output] of Object.entries(bundle)) {
		const matchesPluginFileName = fileName === pluginBundleBase || fileName.startsWith(`${pluginBundleBase}/`);
		const matchesPluginSource = output.type === "chunk" ? isPathInside(pluginRoot, output.facadeModuleId ?? "") : (output.originalFileNames ?? []).some((originalFile) => isPathInside(pluginRoot, originalFile));
		if (!(matchesPluginFileName || matchesPluginSource)) delete bundle[fileName];
	}
}
function emitJsonAssets(state) {
	const { ctx } = state;
	const { jsonService, configService } = ctx;
	const emittedSourceCache = ctx.runtimeState.json.emittedSource;
	for (const jsonEmitFile of state.jsonEmitFilesMap.values()) if (jsonEmitFile.entry.json && isObject(jsonEmitFile.entry.json) && !isEmptyObject(jsonEmitFile.entry.json)) {
		const source = jsonService.resolve(jsonEmitFile.entry);
		if (source && jsonEmitFile.fileName) {
			const normalizedFileName = changeFileExtension(jsonEmitFile.fileName, resolveCompilerOutputExtensions(configService?.outputExtensions).jsonExtension);
			if (emittedSourceCache.get(normalizedFileName) === source) continue;
			const { jsonExtension } = resolveCompilerOutputExtensions(configService?.outputExtensions);
			emitJsonAsset({ emitFile: (asset) => {
				this.emitFile(asset);
			} }, jsonEmitFile.fileName, source, jsonExtension);
			emittedSourceCache.set(normalizedFileName, source);
		}
	}
}
function stripQuotes(value) {
	if (!value) return value;
	const first = value[0];
	const last = value[value.length - 1];
	if (first === last && (first === "\"" || first === "'") || first === "`" && last === "`") return value.slice(1, -1);
	return value;
}
function resolveRelativeImport(fromFile, specifier) {
	if (!specifier) return "";
	const dir = path.posix.dirname(fromFile);
	const absolute = path.posix.resolve("/", dir, specifier);
	return absolute.startsWith("/") ? absolute.slice(1) : absolute;
}
function normalizeRelativeRequireSpecifier(fromFile, targetFile) {
	const relative = path.posix.relative(path.posix.dirname(fromFile), targetFile);
	return relative.startsWith(".") ? relative : `./${relative}`;
}
function isBundleChunkSnapshot(value) {
	const snapshot = value;
	return Array.isArray(snapshot.chunks) && Array.isArray(snapshot.vendorChunks) && snapshot.chunkFileNames instanceof Set;
}
function createBundleChunkSnapshot(bundle) {
	const allOutputs = [];
	const chunks = [];
	const chunkFileNames = /* @__PURE__ */ new Set();
	const vendorChunks = [];
	const wevuChunks = [];
	const wevuChunkFileNames = /* @__PURE__ */ new Set();
	for (const output of Object.values(bundle)) {
		if (!output || output.type !== "chunk" && output.type !== "asset") continue;
		allOutputs.push(output);
		if (output.type !== "chunk") continue;
		const chunk = output;
		chunks.push(chunk);
		chunkFileNames.add(chunk.fileName);
		if (isWevuRuntimeSharedChunkCandidate(chunk.fileName)) vendorChunks.push(chunk);
		if (WEVU_SRC_CHUNK_RE.test(chunk.fileName) || WEVU_VENDOR_RUNTIME_CHUNK_RE.test(chunk.fileName)) {
			wevuChunks.push(chunk);
			wevuChunkFileNames.add(chunk.fileName);
		}
	}
	return {
		allOutputs,
		chunks,
		chunkFileNames,
		vendorChunks,
		wevuChunks,
		wevuChunkFileNames
	};
}
function findImplicitRequireRemovalRanges(chunk, targetFileNames) {
	const code = chunk.code;
	const ranges = [];
	for (const match of code.matchAll(IMPLICIT_REQUIRE_RE)) {
		const specifier = stripQuotes(match[1]);
		const resolved = resolveRelativeImport(chunk.fileName, specifier);
		if (!resolved || !targetFileNames.has(resolved)) continue;
		const start = match.index;
		const end = start + match[0].length;
		ranges.push({
			start,
			end
		});
	}
	return ranges;
}
function removeImplicitPagePreloads(bundle, options, snapshot = createBundleChunkSnapshot(bundle)) {
	const { configService, entriesMap } = options;
	if (!entriesMap || entriesMap.size === 0) return;
	const requireChunks = [];
	for (const chunk of snapshot.chunks) if (typeof chunk.code === "string" && chunk.code.includes("require(")) requireChunks.push(chunk);
	if (!requireChunks.length) return;
	const pageChunkFileNames = /* @__PURE__ */ new Set();
	for (const entry of entriesMap.values()) {
		if (!entry || entry.type !== "page") continue;
		const relative = configService.relativeAbsoluteSrcRoot(entry.path);
		const outputFile = changeFileExtension(relative, ".js");
		pageChunkFileNames.add(outputFile);
	}
	if (pageChunkFileNames.size === 0) return;
	for (const chunk of requireChunks) {
		let targetSet;
		const addTargetFileName = (fileName) => {
			if (!pageChunkFileNames.has(fileName)) return;
			targetSet ??= /* @__PURE__ */ new Set();
			targetSet.add(fileName);
		};
		if (Array.isArray(chunk.imports)) for (const imported of chunk.imports) addTargetFileName(imported);
		const rawImplicit = chunk.implicitlyLoadedBefore;
		const implicitlyLoaded = Array.isArray(rawImplicit) ? rawImplicit : void 0;
		if (implicitlyLoaded) for (const eager of implicitlyLoaded) addTargetFileName(eager);
		if (!targetSet?.size) continue;
		const targets = targetSet;
		const ranges = findImplicitRequireRemovalRanges(chunk, targets);
		if (!ranges.length) continue;
		editOutputChunkCode(chunk, (magicString) => {
			for (const { start, end } of ranges) magicString.remove(start, end);
		});
		if (Array.isArray(chunk.imports) && chunk.imports.length) chunk.imports = chunk.imports.filter((name) => !targets.has(name));
		if (implicitlyLoaded && implicitlyLoaded.length) chunk.implicitlyLoadedBefore = implicitlyLoaded.filter((name) => !targets.has(name));
	}
}
function syncChunkImportsFromRequireCalls(bundle, snapshot = createBundleChunkSnapshot(bundle)) {
	const requireChunks = [];
	for (const chunk of snapshot.chunks) if (typeof chunk.code === "string" && chunk.code.includes("require(")) requireChunks.push(chunk);
	if (!requireChunks.length) return;
	for (const chunk of requireChunks) {
		const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
		let importsChanged = false;
		for (const match of chunk.code.matchAll(REQUIRE_CALL_RE)) {
			const specifier = stripQuotes(match[1]);
			if (!specifier.startsWith(".")) continue;
			const resolved = resolveRelativeImport(chunk.fileName, specifier);
			if (!resolved || resolved === chunk.fileName || !snapshot.chunkFileNames.has(resolved)) continue;
			if (!nextImports.has(resolved)) importsChanged = true;
			nextImports.add(resolved);
		}
		if (importsChanged) chunk.imports = [...nextImports];
	}
}
function parseNamedImportBindings(importClause) {
	return importClause.split(",").map((segment) => {
		const trimmed = segment.trim();
		if (!trimmed) return;
		const [imported, local] = trimmed.split(/\s+as\s+/);
		const importedName = imported?.trim();
		const localName = local?.trim() || importedName;
		if (!importedName || !localName) return;
		return {
			importedName,
			localName
		};
	}).filter((item) => Boolean(item));
}
function collectExistingExportNames(code) {
	return new Set(Array.from(code.matchAll(/Object\.defineProperty\(exports,\s*["']([^"']+)["']/g), (match) => match[1]));
}
function collectChunkExportNames(chunk) {
	return collectExistingExportNames(chunk.code);
}
function normalizeWevuRuntimeModuleId(value) {
	if (value === WEAPP_VITE_RUNTIME_VIRTUAL_ID) return "wevu/internal-runtime";
	if (value === WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID) return "wevu/internal-reactivity";
	if (value === WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID) return "wevu/internal-template";
	return resolveWevuRuntimeModuleId(value);
}
function resolveWevuInternalChunk(bundleOrSnapshot, importNames) {
	const requiredNames = new Set(importNames);
	if (!requiredNames.size) return;
	return (isBundleChunkSnapshot(bundleOrSnapshot) ? bundleOrSnapshot : createBundleChunkSnapshot(bundleOrSnapshot)).vendorChunks.find((chunk) => {
		if (typeof chunk.code !== "string") return false;
		const exports = collectChunkExportNames(chunk);
		return [...requiredNames].every((name) => exports.has(name));
	});
}
function createWevuRuntimeChunkIndex(bundle, snapshot = createBundleChunkSnapshot(bundle)) {
	const vendorChunks = [];
	const chunksByModuleId = /* @__PURE__ */ new Map();
	const exportNamesByFileName = /* @__PURE__ */ new Map();
	for (const chunk of snapshot.vendorChunks) {
		if (typeof chunk.code !== "string") continue;
		vendorChunks.push(chunk);
		const normalizedFileName = chunk.fileName.replace(/\\/g, "/");
		const resolvedModuleIds = [chunk.facadeModuleId, ...chunk.moduleIds ?? []].filter((id) => typeof id === "string").map((id) => resolveWevuRuntimeModuleId(id)).filter((id) => Boolean(id));
		for (const moduleId of resolvedModuleIds) if (!chunksByModuleId.has(moduleId)) chunksByModuleId.set(moduleId, chunk);
		const stableModuleId = resolveWevuRuntimeModuleIdFromStableVendorFileName(normalizedFileName);
		if (stableModuleId && !chunksByModuleId.has(stableModuleId)) chunksByModuleId.set(stableModuleId, chunk);
		for (const moduleId of WEVU_RUNTIME_MODULE_IDS) {
			const chunkFileName = moduleId.replace(/\//g, "-");
			if ((moduleId === "wevu" ? normalizedFileName.endsWith(`${chunkFileName}.js`) : normalizedFileName.endsWith(`${chunkFileName}.js`) || normalizedFileName.includes(`/${chunkFileName}-`)) && !chunksByModuleId.has(moduleId)) chunksByModuleId.set(moduleId, chunk);
		}
	}
	return {
		vendorChunks,
		chunksByModuleId,
		exportNamesByFileName
	};
}
function getWevuRuntimeChunkExportNames(index, chunk) {
	let exports = index.exportNamesByFileName.get(chunk.fileName);
	if (!exports) {
		exports = collectChunkExportNames(chunk);
		index.exportNamesByFileName.set(chunk.fileName, exports);
	}
	return exports;
}
function resolveIndexedWevuInternalChunk(index, importNames) {
	const requiredNames = new Set(importNames);
	if (!requiredNames.size) return;
	return index.vendorChunks.find((chunk) => {
		const exports = getWevuRuntimeChunkExportNames(index, chunk);
		return [...requiredNames].every((name) => exports.has(name));
	});
}
function resolveIndexedWevuInternalChunkByExportMarkers(index, markers, excludedFileNames) {
	const markerSet = new Set(markers);
	if (!markerSet.size) return;
	return index.vendorChunks.find((chunk) => {
		if (excludedFileNames.has(chunk.fileName)) return false;
		const exports = getWevuRuntimeChunkExportNames(index, chunk);
		return [...markerSet].some((name) => exports.has(name));
	});
}
function rememberWevuRuntimeChunk(moduleId, chunk, options) {
	if (!chunk?.fileName) return;
	if (moduleId === "wevu/internal-runtime") options.onRuntimeFileName?.(chunk.fileName);
	options.onRuntimeModuleFileName?.(moduleId, chunk.fileName);
}
function rememberCurrentWevuRuntimeChunks(index, options) {
	const rememberedFileNames = /* @__PURE__ */ new Set();
	for (const moduleId of WEVU_RUNTIME_MODULE_IDS) {
		if (moduleId === "wevu") continue;
		const chunk = index.chunksByModuleId.get(moduleId) ?? resolveIndexedWevuInternalChunkByExportMarkers(index, WEVU_RUNTIME_MODULE_EXPORT_MARKERS[moduleId], rememberedFileNames);
		rememberWevuRuntimeChunk(moduleId, chunk, options);
		if (chunk?.fileName) rememberedFileNames.add(chunk.fileName);
	}
}
function resolveOutputCode(output) {
	if (output.type === "chunk") return output.code;
	if (typeof output.source === "string") return output.source;
	if (output.source == null) return;
	return Buffer.from(output.source).toString();
}
function replaceOutputCode(output, pattern, replace) {
	if (output.type === "chunk") return replaceOutputChunkCode(output, pattern, replace);
	const code = resolveOutputCode(output);
	if (typeof code !== "string") return false;
	const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
	const matcher = new RegExp(pattern.source, flags);
	const magicString = new MagicString(code);
	let changed = false;
	for (const match of code.matchAll(matcher)) {
		if (typeof match.index !== "number") continue;
		const content = replace(match);
		if (content == null || content === match[0]) continue;
		magicString.overwrite(match.index, match.index + match[0].length, content);
		changed = true;
	}
	if (changed) output.source = magicString.toString();
	return changed;
}
function formatNamedRequireBindings(bindings) {
	return bindings.map(({ importedName, localName }) => {
		return importedName === localName ? importedName : `${importedName}: ${localName}`;
	}).join(", ");
}
function resolveRootWevuInternalModuleId(importedName) {
	if (WEVU_INTERNAL_REACTIVITY_EXPORT_SET.has(importedName)) return "wevu/internal-reactivity";
	if (WEVU_INTERNAL_TEMPLATE_EXPORT_SET.has(importedName)) return "wevu/internal-template";
	if (WEVU_INTERNAL_RUNTIME_EXPORT_SET.has(importedName)) return "wevu/internal-runtime";
}
function resolveWevuRuntimeChunkForModuleId(index, moduleId, importedNames) {
	const names = [...importedNames];
	const exactChunk = index.chunksByModuleId.get(moduleId);
	if (exactChunk) {
		const exports = getWevuRuntimeChunkExportNames(index, exactChunk);
		if (names.every((name) => exports.has(name))) return exactChunk;
	}
	return resolveIndexedWevuInternalChunk(index, names);
}
function resolveRememberedWevuRuntimeFileName(moduleId, importedNames, options) {
	const names = [...importedNames];
	const canUseLegacyRuntimeFileName = moduleId === "wevu/internal-runtime" && names.every((importedName) => WEVU_INTERNAL_RUNTIME_EXPORT_SET.has(importedName));
	const rememberedFileName = options.runtimeFileNames?.get(moduleId) ?? (canUseLegacyRuntimeFileName ? options.runtimeFileName : void 0);
	if (rememberedFileName && options.isRuntimeFileNameAvailable && !options.isRuntimeFileNameAvailable(rememberedFileName)) return;
	return rememberedFileName;
}
function formatWevuRuntimeRequire(fileName, runtimeFileName, bindings) {
	const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
	return `const { ${formatNamedRequireBindings(bindings)} } = require(${JSON.stringify(specifier)});`;
}
function rewriteRootWevuImport(index, fileName, full, bindings, options, requiredRuntimeFileNames) {
	const groupedBindings = /* @__PURE__ */ new Map();
	const remainingBindings = [];
	for (const binding of bindings) {
		const moduleId = resolveRootWevuInternalModuleId(binding.importedName);
		if (!moduleId) {
			remainingBindings.push(binding);
			continue;
		}
		const group = groupedBindings.get(moduleId) ?? [];
		group.push(binding);
		groupedBindings.set(moduleId, group);
	}
	if (!groupedBindings.size) return {
		code: full,
		changed: false
	};
	const statements = [];
	for (const [moduleId, moduleBindings] of groupedBindings) {
		const importedNames = moduleBindings.map((binding) => binding.importedName);
		const runtimeChunk = resolveWevuRuntimeChunkForModuleId(index, moduleId, importedNames);
		const runtimeFileName = runtimeChunk?.fileName ?? resolveRememberedWevuRuntimeFileName(moduleId, importedNames, options);
		if (!runtimeFileName) return {
			code: full,
			changed: false
		};
		rememberWevuRuntimeChunk(moduleId, runtimeChunk, options);
		requiredRuntimeFileNames.add(runtimeFileName);
		statements.push(formatWevuRuntimeRequire(fileName, runtimeFileName, moduleBindings));
	}
	if (remainingBindings.length) statements.push(`import { ${remainingBindings.map(({ importedName, localName }) => {
		return importedName === localName ? importedName : `${importedName} as ${localName}`;
	}).join(", ")} } from "wevu";`);
	return {
		code: statements.join("\n"),
		changed: true
	};
}
function mayContainWevuRuntimeImport(code) {
	return code.includes("wevu") || Object.values(WEAPP_VITE_RUNTIME_VIRTUAL_IDS).some((id) => code.includes(id));
}
function rewriteWevuInternalRuntimeImports(bundle, options = {}, snapshot = createBundleChunkSnapshot(bundle)) {
	const runtimeChunkIndex = createWevuRuntimeChunkIndex(bundle, snapshot);
	const currentRuntimeChunk = resolveIndexedWevuInternalChunk(runtimeChunkIndex, WEVU_INTERNAL_RUNTIME_EXPORTS);
	if (currentRuntimeChunk) rememberWevuRuntimeChunk("wevu/internal-runtime", currentRuntimeChunk, options);
	rememberCurrentWevuRuntimeChunks(runtimeChunkIndex, options);
	for (const output of snapshot.allOutputs) {
		const code = resolveOutputCode(output);
		if (typeof code !== "string") continue;
		const fileName = output.fileName;
		if (!fileName.endsWith(".js")) continue;
		if (!mayContainWevuRuntimeImport(code)) continue;
		const requiredRuntimeFileNames = /* @__PURE__ */ new Set();
		let containsRootWevuRuntimeExport;
		const changedNamedImports = replaceOutputCode(output, WEVU_RUNTIME_NAMED_IMPORT_RE, (match) => {
			const [full, importClause, source] = match;
			const bindings = parseNamedImportBindings(importClause);
			const importedNames = bindings.map((binding) => binding.importedName);
			if (source === "wevu") {
				const result = rewriteRootWevuImport(runtimeChunkIndex, fileName, full, bindings, options, requiredRuntimeFileNames);
				return result.changed ? result.code : void 0;
			}
			const resolvedInternalModuleId = normalizeWevuRuntimeModuleId(source);
			if (!resolvedInternalModuleId) return;
			const runtimeChunk = resolveWevuRuntimeChunkForModuleId(runtimeChunkIndex, resolvedInternalModuleId, importedNames);
			const rememberedRuntimeFileName = resolveRememberedWevuRuntimeFileName(resolvedInternalModuleId, importedNames, options);
			const runtimeFileName = runtimeChunk?.fileName ?? rememberedRuntimeFileName;
			if (!runtimeFileName) return;
			rememberWevuRuntimeChunk(resolvedInternalModuleId, runtimeChunk, options);
			requiredRuntimeFileNames.add(runtimeFileName);
			const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
			return `const { ${formatNamedRequireBindings(bindings)} } = require(${JSON.stringify(specifier)});`;
		});
		const changedRequires = replaceOutputCode(output, WEVU_RUNTIME_REQUIRE_RE, (match) => {
			const rawSpecifier = match[1];
			const specifierValue = stripQuotes(rawSpecifier);
			if (specifierValue === "wevu" && containsRootWevuRuntimeExport === void 0) containsRootWevuRuntimeExport = containsWevuInternalRuntimeExportReference(code);
			const normalizedModuleId = normalizeWevuRuntimeModuleId(specifierValue);
			const canUseRememberedRuntime = normalizedModuleId === "wevu/internal-runtime" || specifierValue === "wevu" && containsRootWevuRuntimeExport === true;
			const rememberedRuntimeFileName = normalizedModuleId ? options.runtimeFileNames?.get(normalizedModuleId) : void 0;
			const runtimeFileName = canUseRememberedRuntime ? currentRuntimeChunk?.fileName ?? rememberedRuntimeFileName ?? options.runtimeFileName : rememberedRuntimeFileName;
			if (!runtimeFileName) return;
			requiredRuntimeFileNames.add(runtimeFileName);
			const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
			return `require(${JSON.stringify(specifier)})`;
		});
		if (!changedNamedImports && !changedRequires) continue;
		if (output.type !== "chunk") continue;
		const chunk = output;
		const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
		for (const runtimeFileName of requiredRuntimeFileNames) nextImports.add(runtimeFileName);
		for (const match of chunk.code.matchAll(REQUIRE_CALL_RE)) {
			const specifier = stripQuotes(match[1]);
			const resolved = resolveRelativeImport(chunk.fileName, specifier);
			if (resolved && resolved !== chunk.fileName && bundle[resolved]?.type === "chunk") nextImports.add(resolved);
		}
		chunk.imports = [...nextImports];
	}
}
function rewriteWevuInternalRuntimeImportCode(fileName, code, runtimeFileNameOrOptions) {
	const options = typeof runtimeFileNameOrOptions === "string" ? { runtimeFileName: runtimeFileNameOrOptions } : runtimeFileNameOrOptions ?? {};
	if (!options.runtimeFileName && !options.runtimeFileNames?.size || !mayContainWevuRuntimeImport(code)) return code;
	const output = {
		type: "asset",
		fileName,
		source: code
	};
	rewriteWevuInternalRuntimeImports({ [fileName]: output }, options);
	return typeof output.source === "string" ? output.source : Buffer.from(output.source).toString();
}
function resolveRequireTarget(fromFile, specifier) {
	if (!specifier.startsWith(".")) return "";
	return resolveRelativeImport(fromFile, specifier);
}
function escapeRegExp(value) {
	return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function collectLocalRuntimeIdentifiers(code) {
	const identifiers = /* @__PURE__ */ new Set();
	for (const match of code.matchAll(/\b(?:function|class)\s+([A-Za-z_$][\w$]*)\b/g)) identifiers.add(match[1]);
	for (const match of code.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g)) identifiers.add(match[1]);
	return identifiers;
}
function resolveWevuExportAliasMap(wevuChunk) {
	const aliases = /* @__PURE__ */ new Map();
	const code = wevuChunk.code;
	const localIdentifiers = collectLocalRuntimeIdentifiers(code);
	for (const [exportName] of WEVU_EXPORT_ALIASES) {
		const exportMatch = new RegExp(`\\b([A-Za-z_$][\\w$]*)\\s+as\\s+${exportName}\\b`).exec(code);
		if (exportMatch?.[1]) aliases.set(exportName, exportMatch[1]);
	}
	const propertyExports = Array.from(code.matchAll(/Object\.defineProperty\(exports,\s*(["'`])([^"'`]+)\1,\s*\{[^{}]*\bget\s*:\s*function\s*\(\)\s*\{([^{}]*)\}\s*\}\s*\)/g)).flatMap((match) => {
		const getterReturn = /^return\s+([A-Za-z_$][\w$]*);?$/.exec((match[3] ?? "").trim());
		return getterReturn?.[1] ? [[match[2], getterReturn[1]]] : [];
	});
	for (const [exportName] of WEVU_EXPORT_ALIASES) {
		if (aliases.has(exportName)) continue;
		const semanticExport = propertyExports.find((match) => match[0] === exportName);
		if (semanticExport?.[1]) {
			aliases.set(exportName, semanticExport[1]);
			continue;
		}
		const stableExport = propertyExports.find((match) => match[0] === `__wevu${exportName[0].toUpperCase()}${exportName.slice(1)}`);
		if (stableExport?.[1]) {
			aliases.set(exportName, stableExport[1]);
			continue;
		}
	}
	if (WEVU_SRC_CHUNK_RE.test(wevuChunk.fileName) && !aliases.has("defineComponent") && localIdentifiers.has("eo")) aliases.set("defineComponent", "eo");
	if (WEVU_SRC_CHUNK_RE.test(wevuChunk.fileName) && !aliases.has("createWevuComponent") && localIdentifiers.has("to")) aliases.set("createWevuComponent", "to");
	if (!aliases.has("defineComponent")) {
		const createWevuComponentLocal = (propertyExports.find((match) => match[0] === "createWevuComponent") ?? propertyExports.find((match) => match[0] === "__wevuCreateWevuComponent"))?.[1];
		if (createWevuComponentLocal) {
			const functionMatch = new RegExp(`function\\s+${createWevuComponentLocal}\\s*\\([^)]*\\)\\s*\\{[\\s\\S]{0,500}?\\b([A-Za-z_$][\\w$]*)\\s*\\(`).exec(code);
			if (functionMatch?.[1]) aliases.set("defineComponent", functionMatch[1]);
		}
	}
	return aliases;
}
function getWevuRuntimeChunkUsage(usageByRuntimeChunk, runtimeChunkFileName, chunk) {
	let usageByChunk = usageByRuntimeChunk.get(runtimeChunkFileName);
	if (!usageByChunk) {
		usageByChunk = /* @__PURE__ */ new Map();
		usageByRuntimeChunk.set(runtimeChunkFileName, usageByChunk);
	}
	let usage = usageByChunk.get(chunk.fileName);
	if (!usage) {
		usage = {
			chunk,
			runtimeRefs: /* @__PURE__ */ new Set(),
			inlineMembers: /* @__PURE__ */ new Set(),
			members: /* @__PURE__ */ new Set()
		};
		usageByChunk.set(chunk.fileName, usage);
	}
	return usage;
}
function collectWevuRuntimeChunkUsage(bundle, wevuChunkFileNames, snapshot = createBundleChunkSnapshot(bundle)) {
	const usageByRuntimeChunk = /* @__PURE__ */ new Map();
	if (!wevuChunkFileNames.size) return usageByRuntimeChunk;
	for (const chunk of snapshot.chunks) {
		if (typeof chunk.code !== "string" || !chunk.code.includes("weapp-vendors/")) continue;
		for (const match of chunk.code.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\((`[^`]+`|'[^']+'|"[^"]+")\);?/g)) {
			const resolved = resolveRequireTarget(chunk.fileName, stripQuotes(match[2]));
			if (!resolved || resolved === chunk.fileName || !wevuChunkFileNames.has(resolved)) continue;
			getWevuRuntimeChunkUsage(usageByRuntimeChunk, resolved, chunk).runtimeRefs.add(match[1]);
		}
		for (const match of chunk.code.matchAll(/require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\b/g)) {
			const resolved = resolveRequireTarget(chunk.fileName, stripQuotes(match[1]));
			if (!resolved || resolved === chunk.fileName || !wevuChunkFileNames.has(resolved)) continue;
			const usage = getWevuRuntimeChunkUsage(usageByRuntimeChunk, resolved, chunk);
			usage.inlineMembers.add(match[2]);
			usage.members.add(match[2]);
		}
	}
	for (const usageByChunk of usageByRuntimeChunk.values()) for (const usage of usageByChunk.values()) for (const ref of usage.runtimeRefs) {
		const memberRe = new RegExp(`\\b${escapeRegExp(ref)}\\.([A-Za-z_$][\\w$]*)\\b`, "g");
		for (const match of usage.chunk.code.matchAll(memberRe)) usage.members.add(match[1]);
	}
	return usageByRuntimeChunk;
}
function collectImportedWevuRuntimeMembers(usageByChunk) {
	const members = /* @__PURE__ */ new Set();
	for (const usage of usageByChunk?.values() ?? []) for (const member of usage.members) members.add(member);
	return members;
}
function appendWevuRuntimeExports(chunk, aliases, importedMembers) {
	const lines = [];
	const existingExports = collectExistingExportNames(chunk.code);
	const localIdentifiers = collectLocalRuntimeIdentifiers(chunk.code);
	for (const [exportName, stableName] of WEVU_EXPORT_ALIASES) {
		const localName = aliases.get(exportName);
		if (!localName || !localIdentifiers.has(localName) || existingExports.has(stableName)) continue;
		lines.push(`Object.defineProperty(exports, ${JSON.stringify(stableName)}, { enumerable: false, get: function() { return ${localName}; } });`);
		existingExports.add(stableName);
	}
	for (const member of importedMembers) {
		if (!JS_IDENTIFIER_RE.test(member) || existingExports.has(member) || !localIdentifiers.has(member)) continue;
		lines.push(`Object.defineProperty(exports, ${JSON.stringify(member)}, { enumerable: true, get: function() { return ${member}; } });`);
		existingExports.add(member);
	}
	if (lines.length) appendOutputChunkCode(chunk, `\n${lines.join("\n")}`);
}
function formatSyntheticSinglePageHookExport(exportName) {
	return [
		`function ${exportName}(handler) {`,
		`\tconst instance = require_weapp_vendors_wevu_base.assertInSetup(${JSON.stringify(exportName)});`,
		`\trequire_weapp_vendors_wevu_base.pushHook(instance, ${JSON.stringify(exportName)}, handler, { single: true });`,
		`}`,
		`Object.defineProperty(exports, ${JSON.stringify(exportName)}, { enumerable: true, get: function() { return ${exportName}; } });`
	].join("\n");
}
function appendSyntheticWevuHookExports(chunk, importedMembers) {
	if (!chunk.code.includes("require_weapp_vendors_wevu_base")) return;
	const existingExports = collectExistingExportNames(chunk.code);
	const lines = [];
	for (const exportName of WEVU_SYNTHETIC_SINGLE_PAGE_HOOK_EXPORTS) {
		if (!importedMembers.has(exportName) || existingExports.has(exportName)) continue;
		lines.push(formatSyntheticSinglePageHookExport(exportName));
		existingExports.add(exportName);
	}
	if (lines.length) appendOutputChunkCode(chunk, `\n${lines.join("\n")}`);
}
function resolveWevuBaseChunk(bundleOrSnapshot) {
	return resolveWevuInternalChunk(bundleOrSnapshot, ["assertInSetup", "pushHook"]);
}
function formatSyntheticSinglePageHookFallback(hookName, receiverAccess, baseRequireSpecifier) {
	const baseRequire = `require(${JSON.stringify(baseRequireSpecifier)})`;
	return `(${receiverAccess} || function(handler) { const instance = ${baseRequire}.assertInSetup(${JSON.stringify(hookName)}); ${baseRequire}.pushHook(instance, ${JSON.stringify(hookName)}, handler, { single: true }); })(`;
}
function rewriteSyntheticWevuHookAccess(chunk, wevuChunkFileName, baseChunkFileName, importedMembers, usage) {
	const hookNames = WEVU_SYNTHETIC_SINGLE_PAGE_HOOK_EXPORTS.filter((name) => {
		return importedMembers.has(name) && usage.members.has(name);
	});
	if (!hookNames.length) return;
	const baseRequireSpecifier = normalizeRelativeRequireSpecifier(chunk.fileName, baseChunkFileName);
	for (const hookName of hookNames) {
		for (const ref of usage.runtimeRefs) replaceOutputChunkCode(chunk, new RegExp(`\\b${escapeRegExp(ref)}\\.${hookName}\\s*\\(`, "g"), () => {
			return formatSyntheticSinglePageHookFallback(hookName, `${ref}.${hookName}`, baseRequireSpecifier);
		});
		if (!usage.inlineMembers.has(hookName)) continue;
		replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
			const rawSpecifier = match[1];
			if (match[2] !== hookName) return;
			if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return;
			return formatSyntheticSinglePageHookFallback(hookName, `require(${rawSpecifier}).${hookName}`, baseRequireSpecifier);
		});
	}
}
function rewriteStableWevuRuntimeAccess(chunk, wevuChunkFileName, aliases, usage) {
	if (!aliases.size) return;
	for (const [exportName, stableName] of WEVU_EXPORT_ALIASES) {
		const localName = aliases.get(exportName);
		if (!localName) continue;
		if (usage.inlineMembers.has(localName) || usage.inlineMembers.has(stableName)) replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
			const rawSpecifier = match[1];
			const property = match[2];
			if (property !== localName && property !== stableName) return;
			if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return;
			return `(require(${rawSpecifier}).${stableName} || require(${rawSpecifier}).${property})(`;
		});
		if (!usage.members.has(localName) && !usage.members.has(stableName)) continue;
		for (const ref of usage.runtimeRefs) replaceOutputChunkCode(chunk, new RegExp(`\\b${escapeRegExp(ref)}\\.(?:${stableName}|${localName})\\s*\\(`, "g"), (match) => {
			const property = match[0].includes(`.${stableName}`) ? stableName : localName;
			return `(${ref}.${stableName} || ${ref}.${property})(`;
		});
	}
}
function stabilizeWevuRuntimeChunkAccess(bundle, snapshot = createBundleChunkSnapshot(bundle)) {
	const wevuChunks = snapshot.wevuChunks;
	const wevuChunkFileNames = snapshot.wevuChunkFileNames;
	if (!wevuChunks.length) return;
	const baseChunk = resolveWevuBaseChunk(snapshot);
	const usageByRuntimeChunk = collectWevuRuntimeChunkUsage(bundle, wevuChunkFileNames, snapshot);
	for (const wevuChunk of wevuChunks) {
		const aliases = resolveWevuExportAliasMap(wevuChunk);
		const usageByChunk = usageByRuntimeChunk.get(wevuChunk.fileName);
		const importedMembers = collectImportedWevuRuntimeMembers(usageByChunk);
		appendWevuRuntimeExports(wevuChunk, aliases, importedMembers);
		appendSyntheticWevuHookExports(wevuChunk, importedMembers);
		for (const usage of usageByChunk?.values() ?? []) {
			const chunk = usage.chunk;
			rewriteStableWevuRuntimeAccess(chunk, wevuChunk.fileName, aliases, usage);
			if (baseChunk?.fileName) {
				rewriteSyntheticWevuHookAccess(chunk, wevuChunk.fileName, baseChunk.fileName, importedMembers, usage);
				if (chunk.code.includes(normalizeRelativeRequireSpecifier(chunk.fileName, baseChunk.fileName))) {
					const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
					nextImports.add(baseChunk.fileName);
					chunk.imports = [...nextImports];
				}
			}
		}
	}
}
//#endregion
//#region src/plugins/core/helpers/bytes.ts
function formatBytes(bytes) {
	if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
	const units = [
		"B",
		"KB",
		"MB",
		"GB"
	];
	let value = bytes;
	let index = 0;
	while (value >= 1024 && index < units.length - 1) {
		value /= 1024;
		index++;
	}
	const precision = value >= 100 ? 0 : value >= 10 ? 1 : 2;
	return `${value.toFixed(precision).replace(/\.0+$/, "")} ${units[index]}`;
}
//#endregion
//#region src/plugins/core/helpers/graph.ts
function resolveSourceEntryId(rawId) {
	return normalizeFsResolvedId(parseLogicalEntryId(rawId)?.sourceId ?? rawId);
}
function collectAffectedSharedChunkEntriesAndChunks(state, startId) {
	const affectedEntries = /* @__PURE__ */ new Set();
	const affectedChunks = /* @__PURE__ */ new Set();
	const chunkIds = state.outputChunksByModule.get(normalizeFsResolvedId(startId));
	if (!chunkIds?.size) return {
		affectedChunks,
		affectedEntries
	};
	for (const chunkId of chunkIds) {
		affectedChunks.add(chunkId);
		const importers = state.hmrSharedChunkImporters.get(chunkId);
		if (!importers?.size) continue;
		for (const importer of importers) if (state.resolvedEntryMap.has(importer)) affectedEntries.add(importer);
	}
	return {
		affectedChunks,
		affectedEntries
	};
}
function createSharedModulesByChunk(sharedChunksByModule) {
	const modulesByChunk = /* @__PURE__ */ new Map();
	for (const [moduleId, chunkIds] of sharedChunksByModule) for (const chunkId of chunkIds) {
		let moduleIds = modulesByChunk.get(chunkId);
		if (!moduleIds) {
			moduleIds = /* @__PURE__ */ new Set();
			modulesByChunk.set(chunkId, moduleIds);
		}
		moduleIds.add(moduleId);
	}
	return modulesByChunk;
}
function appendSharedChunkImporters(bundle, state, onlyEntryIds, previousImporters, previousDependencies) {
	const bundleChunks = /* @__PURE__ */ new Map();
	const resolveImportedChunkId = (importerFileName, imported) => {
		if (bundleChunks.has(imported)) return imported;
		if (imported.startsWith(".")) return path.normalize(path.join(path.dirname(importerFileName), imported));
		return imported;
	};
	const collectChunkImports = (chunk) => {
		const imports = /* @__PURE__ */ new Set();
		if (Array.isArray(chunk.imports)) for (const imported of chunk.imports) imports.add(resolveImportedChunkId(chunk.fileName, imported));
		if (Array.isArray(chunk.dynamicImports)) for (const imported of chunk.dynamicImports) imports.add(resolveImportedChunkId(chunk.fileName, imported));
		return imports;
	};
	const getTrackedImporterIds = (chunk) => {
		const trackedImporterIds = /* @__PURE__ */ new Set();
		if (chunk.facadeModuleId) {
			const entryId = resolveSourceEntryId(chunk.facadeModuleId);
			if (chunk.isEntry || state.resolvedEntryMap.has(entryId)) trackedImporterIds.add(entryId);
		}
		if (Array.isArray(chunk.moduleIds)) for (const moduleId of chunk.moduleIds) {
			const normalizedModuleId = resolveSourceEntryId(moduleId);
			if (state.resolvedEntryMap.has(normalizedModuleId)) trackedImporterIds.add(normalizedModuleId);
		}
		return trackedImporterIds;
	};
	const isProjectSourceModule = (rawId) => {
		if (!rawId) return false;
		const absoluteSrcRoot = state.ctx?.configService?.absoluteSrcRoot;
		if (!absoluteSrcRoot) return false;
		const normalizedRoot = normalizeFsResolvedId(absoluteSrcRoot);
		const normalizedId = normalizeFsResolvedId(rawId);
		if (isSkippableResolvedId(normalizedId)) return false;
		return normalizedId === normalizedRoot || normalizedId.startsWith(`${normalizedRoot}/`);
	};
	const collectProjectSourceModules = (chunk) => {
		const moduleIds = /* @__PURE__ */ new Set();
		if (isProjectSourceModule(chunk.facadeModuleId)) moduleIds.add(normalizeFsResolvedId(chunk.facadeModuleId));
		if (Array.isArray(chunk.moduleIds)) {
			for (const moduleId of chunk.moduleIds) if (isProjectSourceModule(moduleId)) moduleIds.add(normalizeFsResolvedId(moduleId));
		}
		for (const moduleId of Object.keys(chunk.modules ?? {})) if (isProjectSourceModule(moduleId)) moduleIds.add(normalizeFsResolvedId(moduleId));
		return moduleIds;
	};
	const addSharedChunkModule = (moduleId, chunkId) => {
		state.ctx.runtimeState?.build?.hmr?.sharedChunkSourceModuleIds?.add(moduleId);
		const current = state.outputChunksByModule.get(moduleId);
		if (current) current.add(chunkId);
		else state.outputChunksByModule.set(moduleId, /* @__PURE__ */ new Set([chunkId]));
	};
	const previousSharedModulesByChunk = createSharedModulesByChunk(state.outputChunksByModule);
	const pruneSharedChunkModules = (chunkId, nextModuleIds) => {
		if (!nextModuleIds.size) return;
		const previousModuleIds = previousSharedModulesByChunk.get(chunkId);
		if (!previousModuleIds?.size) return;
		for (const moduleId of previousModuleIds) {
			if (nextModuleIds.has(moduleId)) continue;
			const chunkIds = state.outputChunksByModule.get(moduleId);
			if (!chunkIds) continue;
			chunkIds.delete(chunkId);
			if (chunkIds.size === 0) state.outputChunksByModule.delete(moduleId);
		}
	};
	for (const [bundleKey, output] of Object.entries(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (!chunk.fileName) chunk.fileName = bundleKey;
		const projectSourceModules = collectProjectSourceModules(chunk);
		bundleChunks.set(chunk.fileName, chunk);
		pruneSharedChunkModules(chunk.fileName, projectSourceModules);
		if (projectSourceModules.size > 0) state.hmrSourceSharedChunks.add(chunk.fileName);
		for (const moduleId of projectSourceModules) addSharedChunkModule(moduleId, chunk.fileName);
	}
	const trackedImporterIdsByChunk = /* @__PURE__ */ new Map();
	for (const [fileName, chunk] of bundleChunks) {
		trackedImporterIdsByChunk.set(fileName, getTrackedImporterIds(chunk));
		const imports = collectChunkImports(chunk);
		if (imports.size) state.hmrSharedChunkDependencies.set(fileName, imports);
		else state.hmrSharedChunkDependencies.delete(fileName);
	}
	const addSharedChunkImporter = (chunkId, entryId) => {
		const current = state.hmrSharedChunkImporters.get(chunkId);
		if (current) current.add(entryId);
		else state.hmrSharedChunkImporters.set(chunkId, /* @__PURE__ */ new Set([entryId]));
		const currentChunkIds = state.hmrSharedChunksByEntry.get(entryId);
		if (currentChunkIds) currentChunkIds.add(chunkId);
		else state.hmrSharedChunksByEntry.set(entryId, /* @__PURE__ */ new Set([chunkId]));
	};
	const restoreMissingChunkImporters = (entryId, chunkId, visited) => {
		if (visited.has(chunkId)) return;
		visited.add(chunkId);
		if (!previousImporters?.get(chunkId)?.has(entryId)) return;
		addSharedChunkImporter(chunkId, entryId);
		const nestedImports = previousDependencies?.get(chunkId);
		if (!nestedImports?.size) return;
		for (const nestedImport of nestedImports) restoreMissingChunkImporters(entryId, nestedImport, visited);
	};
	const propagateSharedChunkImporter = (entryId, importedChunkId, visited) => {
		if (visited.has(importedChunkId)) return;
		visited.add(importedChunkId);
		if (!bundleChunks.get(importedChunkId)) {
			visited.delete(importedChunkId);
			restoreMissingChunkImporters(entryId, importedChunkId, visited);
			return;
		}
		if ((trackedImporterIdsByChunk.get(importedChunkId)?.size ?? 0) > 0) return;
		addSharedChunkImporter(importedChunkId, entryId);
		const nestedImports = state.hmrSharedChunkDependencies.get(importedChunkId) ?? /* @__PURE__ */ new Set();
		for (const nestedImport of nestedImports) propagateSharedChunkImporter(entryId, nestedImport, visited);
	};
	for (const [fileName] of bundleChunks) {
		const trackedImporterIds = trackedImporterIdsByChunk.get(fileName) ?? /* @__PURE__ */ new Set();
		if (!trackedImporterIds.size) continue;
		for (const trackedImporterId of trackedImporterIds) {
			if (onlyEntryIds && !onlyEntryIds.has(trackedImporterId)) continue;
			const imports = state.hmrSharedChunkDependencies.get(fileName) ?? /* @__PURE__ */ new Set();
			if (!imports.size) continue;
			for (const imported of imports) propagateSharedChunkImporter(trackedImporterId, imported, /* @__PURE__ */ new Set());
		}
	}
}
function collectPreviousSharedChunkSnapshot(state, entryIds) {
	const previousImporters = /* @__PURE__ */ new Map();
	const previousDependencies = /* @__PURE__ */ new Map();
	const visited = /* @__PURE__ */ new Set();
	const addChunk = (chunkId) => {
		if (visited.has(chunkId)) return;
		visited.add(chunkId);
		const importers = state.hmrSharedChunkImporters.get(chunkId);
		if (importers) previousImporters.set(chunkId, new Set(importers));
		const dependencies = state.hmrSharedChunkDependencies.get(chunkId);
		if (!dependencies?.size) return;
		previousDependencies.set(chunkId, new Set(dependencies));
		for (const dependency of dependencies) addChunk(dependency);
	};
	for (const entryId of entryIds) {
		const chunkIds = state.hmrSharedChunksByEntry.get(entryId);
		if (!chunkIds?.size) {
			for (const [chunkId, importers] of state.hmrSharedChunkImporters) if (importers.has(entryId)) addChunk(chunkId);
			continue;
		}
		for (const chunkId of chunkIds) addChunk(chunkId);
	}
	return {
		previousImporters,
		previousDependencies
	};
}
function refreshSharedChunkImporters(bundle, state) {
	state.hmrSharedChunkImporters.clear();
	state.hmrSharedChunksByEntry.clear();
	state.hmrSharedChunkDependencies.clear();
	state.outputChunksByModule.clear();
	state.hmrSourceSharedChunks.clear();
	appendSharedChunkImporters(bundle, state);
}
function refreshPartialSharedChunkImporters(bundle, state, entryIds) {
	if (!entryIds.size) return;
	const refreshedEntryIds = /* @__PURE__ */ new Set();
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (chunk.facadeModuleId) {
			const entryId = resolveSourceEntryId(chunk.facadeModuleId);
			if ((chunk.isEntry || state.resolvedEntryMap.has(entryId)) && entryIds.has(entryId)) refreshedEntryIds.add(entryId);
		}
		if (Array.isArray(chunk.moduleIds)) for (const moduleId of chunk.moduleIds) {
			const normalizedModuleId = resolveSourceEntryId(moduleId);
			if (state.resolvedEntryMap.has(normalizedModuleId) && entryIds.has(normalizedModuleId)) refreshedEntryIds.add(normalizedModuleId);
		}
	}
	if (!refreshedEntryIds.size) return;
	const { previousImporters, previousDependencies } = collectPreviousSharedChunkSnapshot(state, refreshedEntryIds);
	for (const entryId of refreshedEntryIds) {
		const chunkIds = state.hmrSharedChunksByEntry.get(entryId);
		if (!chunkIds?.size) {
			const emptyChunkIds = [];
			for (const [chunkId, importers] of state.hmrSharedChunkImporters) {
				importers.delete(entryId);
				if (importers.size === 0) emptyChunkIds.push(chunkId);
			}
			for (const chunkId of emptyChunkIds) {
				state.hmrSharedChunkImporters.delete(chunkId);
				state.hmrSharedChunkDependencies.delete(chunkId);
			}
			continue;
		}
		for (const chunkId of chunkIds) {
			const importers = state.hmrSharedChunkImporters.get(chunkId);
			if (!importers) continue;
			importers.delete(entryId);
			if (importers.size === 0) {
				state.hmrSharedChunkImporters.delete(chunkId);
				state.hmrSharedChunkDependencies.delete(chunkId);
			}
		}
		state.hmrSharedChunksByEntry.delete(entryId);
	}
	appendSharedChunkImporters(bundle, state, refreshedEntryIds, previousImporters, previousDependencies);
}
//#endregion
//#region src/runtime/config/internal/injectRequestGlobals.ts
const FULL_REQUEST_GLOBAL_TARGETS = [
	"fetch",
	"Headers",
	"Request",
	"Response",
	"TextEncoder",
	"TextDecoder",
	"AbortController",
	"AbortSignal",
	"XMLHttpRequest",
	"WebSocket",
	"atob",
	"btoa",
	"queueMicrotask",
	"performance",
	"crypto",
	"Event",
	"CustomEvent"
];
const ABORT_REQUEST_GLOBAL_TARGETS = ["AbortController", "AbortSignal"];
const REQUEST_RUNTIME_REQUEST_TARGETS = [
	"fetch",
	"Headers",
	"Request",
	"Response",
	"TextEncoder",
	"TextDecoder",
	"AbortController",
	"AbortSignal",
	"XMLHttpRequest"
];
const REQUEST_RUNTIME_CORE_USAGE_TARGETS = /* @__PURE__ */ new Set([
	"fetch",
	"Headers",
	"Request",
	"Response",
	"XMLHttpRequest"
]);
const DEFAULT_REQUEST_GLOBAL_DEPENDENCIES = [
	"axios",
	"graphql-request",
	"socket.io-client",
	"engine.io-client"
];
const DEFAULT_ABORT_GLOBAL_DEPENDENCIES = ["@tanstack/query-core", "@tanstack/vue-query"];
const WEBSOCKET_USAGE_HINT_RE = /\bwebsocket\b/iu;
const REQUEST_GLOBAL_FREE_BINDING_TARGETS = /* @__PURE__ */ new Set([
	...FULL_REQUEST_GLOBAL_TARGETS,
	"URL",
	"URLSearchParams",
	"Blob",
	"File",
	"FormData"
]);
const CODE_USAGE_AUTO_RULES = [
	{
		dependencyPatterns: ["axios", "graphql-request"],
		targets: [...REQUEST_RUNTIME_REQUEST_TARGETS]
	},
	{
		dependencyPatterns: ["socket.io-client", "engine.io-client"],
		targets: [...FULL_REQUEST_GLOBAL_TARGETS]
	},
	{
		dependencyPatterns: [...DEFAULT_ABORT_GLOBAL_DEPENDENCIES],
		targets: [...ABORT_REQUEST_GLOBAL_TARGETS]
	}
];
function resolveAppPreludeWebRuntimeConfig(appPrelude, warn) {
	if (!appPrelude || typeof appPrelude !== "object") return;
	const webRuntime = appPrelude.webRuntime;
	const requestRuntime = appPrelude.requestRuntime;
	if (webRuntime !== void 0) {
		if (requestRuntime !== void 0) warn?.("`weapp.appPrelude.requestRuntime` 已废弃,且当前会被 `weapp.appPrelude.webRuntime` 覆盖。请迁移到 `weapp.appPrelude.webRuntime`。");
		if (typeof webRuntime === "boolean") return webRuntime ? {
			enabled: true,
			prelude: true
		} : false;
		return {
			...webRuntime,
			prelude: true
		};
	}
	if (requestRuntime === void 0) return;
	warn?.("`weapp.appPrelude.requestRuntime` 已废弃,请迁移到 `weapp.appPrelude.webRuntime`。");
	if (typeof requestRuntime === "boolean") return requestRuntime ? {
		enabled: true,
		prelude: true
	} : false;
	return {
		...requestRuntime,
		prelude: true
	};
}
function hasMatchedDependency(packageJson, patterns) {
	return [.../* @__PURE__ */ new Set([
		...Object.keys(packageJson?.dependencies ?? {}),
		...Object.keys(packageJson?.devDependencies ?? {}),
		...Object.keys(packageJson?.peerDependencies ?? {})
	])].some((dependency) => {
		return patterns.some((pattern) => {
			if (typeof pattern === "string") return pattern === dependency;
			pattern.lastIndex = 0;
			return pattern.test(dependency);
		});
	});
}
function resolveTargets(config) {
	if (config && typeof config === "object" && Array.isArray(config.targets) && config.targets.length > 0) return [...new Set(config.targets)];
	return [...FULL_REQUEST_GLOBAL_TARGETS];
}
function resolveDependencyPatterns(config) {
	if (config && typeof config === "object" && Array.isArray(config.dependencies) && config.dependencies.length > 0) return config.dependencies;
	return DEFAULT_REQUEST_GLOBAL_DEPENDENCIES;
}
function hasCustomAutoRuleConfig(config) {
	if (!config || typeof config !== "object") return false;
	return Boolean(Array.isArray(config.dependencies) && config.dependencies.length > 0 || Array.isArray(config.targets) && config.targets.length > 0);
}
function hasConfiguredNetworkDefaults(config) {
	return Boolean(config && typeof config === "object" && hasOwn$5(config, "networkDefaults"));
}
function resolveAutoPrelude(config) {
	if (!config || typeof config !== "object" || !hasOwn$5(config, "prelude")) return true;
	return config.prelude === true;
}
function resolveAutoRules(config) {
	if (hasCustomAutoRuleConfig(config)) return [{
		dependencyPatterns: resolveDependencyPatterns(config),
		targets: resolveTargets(config)
	}];
	return [{
		dependencyPatterns: DEFAULT_REQUEST_GLOBAL_DEPENDENCIES,
		targets: [...FULL_REQUEST_GLOBAL_TARGETS]
	}, {
		dependencyPatterns: DEFAULT_ABORT_GLOBAL_DEPENDENCIES,
		targets: [...ABORT_REQUEST_GLOBAL_TARGETS]
	}];
}
/**
* @description 解析按需注入请求相关全局对象的最终配置。
*/
function resolveInjectRequestGlobalsOptions(config, packageJson) {
	if (config === false) return null;
	if (config && typeof config === "object" && config.enabled === false) return null;
	const enabled = config && typeof config === "object" ? config.enabled : config;
	const networkDefaults = config && typeof config === "object" ? config.networkDefaults : void 0;
	if (enabled === true || hasConfiguredNetworkDefaults(config)) return {
		mode: "explicit",
		targets: resolveTargets(config),
		dependencyPatterns: resolveDependencyPatterns(config),
		...networkDefaults !== void 0 ? { networkDefaults } : {},
		prelude: config && typeof config === "object" ? config.prelude === true : false
	};
	const autoRules = resolveAutoRules(config);
	const matchedTargets = /* @__PURE__ */ new Set();
	for (const rule of autoRules) {
		if (!hasMatchedDependency(packageJson, rule.dependencyPatterns)) continue;
		for (const target of rule.targets) matchedTargets.add(target);
	}
	if (matchedTargets.size === 0) return null;
	return {
		mode: "auto",
		targets: [...matchedTargets],
		prelude: resolveAutoPrelude(config)
	};
}
function resolveRequestRuntimeOptions(input, packageJson, warn) {
	const nestedConfig = resolveAppPreludeWebRuntimeConfig(input.appPrelude, warn);
	const preferredTopLevelConfig = input.webRuntime;
	const legacyConfig = input.injectRequestGlobals;
	if (nestedConfig !== void 0) {
		if (preferredTopLevelConfig !== void 0) warn?.("`weapp.injectWebRuntimeGlobals` 当前会被 `weapp.appPrelude.webRuntime` 覆盖。请优先使用 `weapp.appPrelude.webRuntime`。");
		if (legacyConfig !== void 0) warn?.("`weapp.injectRequestGlobals` 已废弃,且当前会被 `weapp.appPrelude.webRuntime` 覆盖。请迁移到 `weapp.appPrelude.webRuntime`。");
		return resolveInjectRequestGlobalsOptions(nestedConfig, packageJson);
	}
	if (preferredTopLevelConfig !== void 0) {
		if (legacyConfig !== void 0) warn?.("`weapp.injectRequestGlobals` 已废弃,且当前会被 `weapp.injectWebRuntimeGlobals` 覆盖。请迁移到 `weapp.injectWebRuntimeGlobals`。");
		return resolveInjectRequestGlobalsOptions(preferredTopLevelConfig, packageJson);
	}
	if (legacyConfig !== void 0) warn?.("`weapp.injectRequestGlobals` 已废弃,请迁移到 `weapp.appPrelude.webRuntime`。");
	return resolveInjectRequestGlobalsOptions(legacyConfig, packageJson);
}
function resolveRequestGlobalsRuntimeModuleId() {
	return "weapp-vite/web-apis";
}
function resolveRequestGlobalsBindingTargets(targets) {
	const bindingTargets = [...targets];
	if (targets.some((target) => target === "fetch" || target === "Request" || target === "Response" || target === "XMLHttpRequest" || target === "WebSocket")) {
		bindingTargets.push("TextEncoder", "TextDecoder");
		bindingTargets.push("URL", "URLSearchParams", "Blob", "File", "FormData");
	}
	if (targets.includes("CustomEvent")) bindingTargets.push("Event");
	return [...new Set(bindingTargets)].filter((target) => REQUEST_GLOBAL_FREE_BINDING_TARGETS.has(target));
}
/**
* @description 生成运行时 installer 的选项代码。
*/
function createRequestGlobalsInstallerOptionsCode(targets, networkDefaults) {
	const options = [`targets: ${JSON.stringify(targets)}`];
	if (networkDefaults !== void 0) options.push(`networkDefaults: ${JSON.stringify(networkDefaults)}`);
	return `{ ${options.join(", ")} }`;
}
/**
* @description 生成“被动局部绑定”代码。
* @description 这层能力不能退化成只在 app.js 顶部安装全局对象。
* @description 原因是 axios / graphql-request / socket.io-client 一类依赖经常会:
* @description 1. 在模块初始化阶段直接读取自由变量;
* @description 2. 在各自 chunk 作用域里执行 `typeof XMLHttpRequest` / `typeof fetch` / `new URL()`;
* @description 3. 在全局对象完成安装前就完成环境探测并缓存结果。
* @description 因此这里必须把 fetch / XMLHttpRequest / WebSocket / URL 等名字绑定到实际使用它们的产物作用域内。
*/
function createRequestGlobalsPassiveBindingsCode(targets, explicitBindingTargets) {
	const bindingTargets = explicitBindingTargets?.length ? explicitBindingTargets : resolveRequestGlobalsBindingTargets(targets);
	if (bindingTargets.length === 0) return "";
	return `${[
		`const ${REQUEST_GLOBAL_ACTUALS_KEY} = globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] || (globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] = Object.create(null))`,
		`function ${REQUEST_GLOBAL_MARK_PLACEHOLDER_HELPER}(value){try{Object.defineProperty(value,${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)},{value:true,configurable:true})}catch{value[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]=true}return value}`,
		`function ${REQUEST_GLOBAL_LAZY_FUNCTION_HELPER}(name){const placeholder=function(...args){const actual=${REQUEST_GLOBAL_ACTUALS_KEY}[name];if(typeof actual!=="function"){throw new Error(name+" is not initialized")}return actual.apply(this,args)};return ${REQUEST_GLOBAL_MARK_PLACEHOLDER_HELPER}(placeholder)}`,
		`function ${REQUEST_GLOBAL_LAZY_CONSTRUCTOR_HELPER}(name){const placeholder=function(...args){const actual=${REQUEST_GLOBAL_ACTUALS_KEY}[name];if(typeof actual!=="function"){throw new Error(name+" is not initialized")}return Reflect.construct(actual,args)};return ${REQUEST_GLOBAL_MARK_PLACEHOLDER_HELPER}(placeholder)}`,
		`function __weappViteRequestGlobalsLazyObject(name,keys){const placeholder=Object.create(null);for(const key of keys){placeholder[key]=function(...args){const actual=${REQUEST_GLOBAL_ACTUALS_KEY}[name];const actualValue=actual?.[key];if(typeof actualValue!=="function"){throw new Error(name+"."+key+" is not initialized")}return actualValue.apply(actual,args)}}return ${REQUEST_GLOBAL_MARK_PLACEHOLDER_HELPER}(placeholder)}`,
		`function ${REQUEST_GLOBAL_USABLE_CONSTRUCTOR_HELPER}(value,args,expectedHref){if(typeof value!=="function"||value?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]===true){return false}try{const instance=Reflect.construct(value,args);return expectedHref===undefined||instance?.href===expectedHref}catch{return false}}`,
		`function ${REQUEST_GLOBAL_EXPOSE_HELPER}(name,value){if(value==null){return value}const current=globalThis[name];if(current===value){return value}if((typeof current!=="function"&&typeof current!=="object")||current?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]===true){try{globalThis[name]=value}catch{}}return value}`
	].join(";")};${bindingTargets.map((target) => {
		if (target === "fetch") return `var fetch = ${REQUEST_GLOBAL_EXPOSE_HELPER}("fetch",typeof ${REQUEST_GLOBAL_ACTUALS_KEY}["fetch"]==="function"&&${REQUEST_GLOBAL_ACTUALS_KEY}["fetch"]?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${REQUEST_GLOBAL_ACTUALS_KEY}["fetch"]:typeof globalThis.fetch==="function"&&globalThis.fetch?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.fetch:${REQUEST_GLOBAL_LAZY_FUNCTION_HELPER}("fetch"))`;
		if (target === "atob") return `var atob = ${REQUEST_GLOBAL_EXPOSE_HELPER}("atob",typeof ${REQUEST_GLOBAL_ACTUALS_KEY}["atob"]==="function"&&${REQUEST_GLOBAL_ACTUALS_KEY}["atob"]?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${REQUEST_GLOBAL_ACTUALS_KEY}["atob"]:typeof globalThis.atob==="function"&&globalThis.atob?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.atob:${REQUEST_GLOBAL_LAZY_FUNCTION_HELPER}("atob"))`;
		if (target === "btoa") return `var btoa = ${REQUEST_GLOBAL_EXPOSE_HELPER}("btoa",typeof ${REQUEST_GLOBAL_ACTUALS_KEY}["btoa"]==="function"&&${REQUEST_GLOBAL_ACTUALS_KEY}["btoa"]?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${REQUEST_GLOBAL_ACTUALS_KEY}["btoa"]:typeof globalThis.btoa==="function"&&globalThis.btoa?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.btoa:${REQUEST_GLOBAL_LAZY_FUNCTION_HELPER}("btoa"))`;
		if (target === "queueMicrotask") return `var queueMicrotask = ${REQUEST_GLOBAL_EXPOSE_HELPER}("queueMicrotask",typeof ${REQUEST_GLOBAL_ACTUALS_KEY}["queueMicrotask"]==="function"&&${REQUEST_GLOBAL_ACTUALS_KEY}["queueMicrotask"]?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${REQUEST_GLOBAL_ACTUALS_KEY}["queueMicrotask"]:typeof globalThis.queueMicrotask==="function"&&globalThis.queueMicrotask?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.queueMicrotask:${REQUEST_GLOBAL_LAZY_FUNCTION_HELPER}("queueMicrotask"))`;
		const placeholderFactory = `${REQUEST_GLOBAL_LAZY_CONSTRUCTOR_HELPER}(${JSON.stringify(target)})`;
		const actualRef = `${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}]`;
		if (target === "performance") return `var performance = ${REQUEST_GLOBAL_EXPOSE_HELPER}("performance",${actualRef}&&typeof ${actualRef}.now==="function"&&${actualRef}?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${actualRef}:globalThis.performance&&typeof globalThis.performance.now==="function"&&globalThis.performance?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.performance:__weappViteRequestGlobalsLazyObject("performance",["now"]))`;
		if (target === "crypto") return `var crypto = ${REQUEST_GLOBAL_EXPOSE_HELPER}("crypto",${actualRef}&&typeof ${actualRef}.getRandomValues==="function"&&${actualRef}?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${actualRef}:globalThis.crypto&&typeof globalThis.crypto.getRandomValues==="function"&&globalThis.crypto?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.crypto:__weappViteRequestGlobalsLazyObject("crypto",["getRandomValues"]))`;
		if (target === "URL") return `var URL = ${REQUEST_GLOBAL_EXPOSE_HELPER}("URL",${REQUEST_GLOBAL_USABLE_CONSTRUCTOR_HELPER}(${actualRef},["123","fake://abc"],"fake://abc/123")?${actualRef}:${REQUEST_GLOBAL_USABLE_CONSTRUCTOR_HELPER}(globalThis.URL,["123","fake://abc"],"fake://abc/123")?globalThis.URL:${placeholderFactory})`;
		return `var ${target} = ${REQUEST_GLOBAL_EXPOSE_HELPER}(${JSON.stringify(target)},typeof ${actualRef}==="function"&&${actualRef}?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?${actualRef}:typeof globalThis.${target}==="function"&&globalThis.${target}?.[${JSON.stringify(REQUEST_GLOBAL_PLACEHOLDER_KEY)}]!==true?globalThis.${target}:${placeholderFactory})`;
	}).join(";")};`;
}
const MANUAL_REQUEST_GLOBALS_IMPORT_RE = /from\s*['"](?:@wevu\/web-apis|weapp-vite\/web-apis)['"]/;
const MANUAL_INSTALL_REQUEST_GLOBALS_CALL_RE = /\binstallRequestGlobals\s*\(/;
const MANUAL_INSTALL_ABORT_GLOBALS_CALL_RE = /\binstallAbortGlobals\s*\(/;
const REQUEST_GLOBAL_KNOWN_DEPENDENCY_LITERALS = [
	"axios",
	"graphql-request",
	"socket.io-client",
	"engine.io-client",
	"@tanstack/query-core",
	"@tanstack/vue-query"
];
function isIdentifierBoundary(char) {
	if (char === void 0) return true;
	const code = char.charCodeAt(0);
	return !(code === 36 || code === 95 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122);
}
function containsIdentifierByText(code, identifier) {
	let cursor = code.indexOf(identifier);
	while (cursor !== -1) {
		if (isIdentifierBoundary(code[cursor - 1]) && isIdentifierBoundary(code[cursor + identifier.length])) return true;
		cursor = code.indexOf(identifier, cursor + identifier.length);
	}
	return false;
}
function normalizeResolvedRequestGlobalTargets(targets, allowedTargets) {
	const resolvedSet = new Set(targets);
	return allowedTargets.filter((target) => resolvedSet.has(target));
}
function mayContainRequestGlobalsUsageByText(code, allowedTargets) {
	return allowedTargets.some((target) => containsIdentifierByText(code, target)) || REQUEST_GLOBAL_KNOWN_DEPENDENCY_LITERALS.some((specifier) => code.includes(specifier)) || allowedTargets.includes("WebSocket") && WEBSOCKET_USAGE_HINT_RE.test(code);
}
function extractRequestGlobalsUsageSource(code) {
	if (!code.includes("<script")) return code;
	const { descriptor, errors } = parse$1(code, {
		filename: "request-globals-usage.vue",
		ignoreEmpty: false
	});
	if (errors.length > 0) return code;
	return [descriptor.script?.content, descriptor.scriptSetup?.content].filter((content) => typeof content === "string" && content.trim().length > 0).join("\n");
}
function resolveFallbackReferencedRequestGlobalsTargets(usageSource, allowedTargets) {
	return allowedTargets.filter((target) => new RegExp(`\\b${target}\\b`, "u").test(usageSource));
}
function matchesRequestGlobalDependencyPattern(specifier, pattern) {
	if (typeof pattern === "string") return specifier === pattern;
	pattern.lastIndex = 0;
	return pattern.test(specifier);
}
function resolveImportedRequestGlobalsTargetsFromSpecifiers(specifiers, allowedTargets) {
	const resolvedTargets = /* @__PURE__ */ new Set();
	for (const specifier of specifiers) for (const rule of CODE_USAGE_AUTO_RULES) {
		if (!rule.dependencyPatterns.some((pattern) => matchesRequestGlobalDependencyPattern(specifier, pattern))) continue;
		for (const target of rule.targets) if (allowedTargets.includes(target)) resolvedTargets.add(target);
	}
	return normalizeResolvedRequestGlobalTargets(resolvedTargets, allowedTargets);
}
function resolveFallbackImportedRequestGlobalsSpecifiers(code) {
	const matchedSpecifiers = /* @__PURE__ */ new Set();
	for (const specifier of REQUEST_GLOBAL_KNOWN_DEPENDENCY_LITERALS) if (code.includes(specifier)) matchedSpecifiers.add(specifier);
	return matchedSpecifiers;
}
function analyzeRequestGlobalsUsage(code, allowedTargets) {
	const emptyAnalysis = {
		hasWebSocketUsageHint: false,
		importedTargets: [],
		referencedTargets: []
	};
	if (allowedTargets.length === 0) return emptyAnalysis;
	const usageSource = extractRequestGlobalsUsageSource(code);
	const hasWebSocketUsageHint = allowedTargets.includes("WebSocket") && WEBSOCKET_USAGE_HINT_RE.test(code);
	if (!usageSource.trim()) return {
		...emptyAnalysis,
		hasWebSocketUsageHint
	};
	const allowedTargetSet = new Set(allowedTargets);
	const mayHaveReferencedTargets = allowedTargets.some((target) => new RegExp(`\\b${target}\\b`, "u").test(usageSource));
	const mayHaveImportedTargets = REQUEST_GLOBAL_KNOWN_DEPENDENCY_LITERALS.some((specifier) => code.includes(specifier));
	if (!mayHaveReferencedTargets && !mayHaveImportedTargets) return {
		...emptyAnalysis,
		hasWebSocketUsageHint
	};
	const referencedTargets = /* @__PURE__ */ new Set();
	const matchedSpecifiers = /* @__PURE__ */ new Set();
	const addSpecifier = (specifier) => {
		if (typeof specifier === "string" && specifier.length > 0) matchedSpecifiers.add(specifier);
	};
	try {
		const ast = parseJsLike(usageSource);
		traverse(ast, {
			ImportDeclaration(path) {
				addSpecifier(path.node?.source?.value);
			},
			ExportNamedDeclaration(path) {
				addSpecifier(path.node?.source?.value);
			},
			ExportAllDeclaration(path) {
				addSpecifier(path.node?.source?.value);
			},
			CallExpression(path) {
				if (path.node?.callee?.type === "Import") {
					addSpecifier(path.node.arguments?.[0]?.value);
					return;
				}
				if (path.node?.callee?.type === "Identifier" && path.node.callee.name === "require") addSpecifier(path.node.arguments?.[0]?.value);
			},
			Identifier(path) {
				const identifierName = path.node?.name;
				if (!identifierName || !allowedTargetSet.has(identifierName)) return;
				if (typeof path.isReferencedIdentifier === "function" && !path.isReferencedIdentifier()) return;
				if (path.scope?.hasBinding?.(identifierName)) return;
				referencedTargets.add(identifierName);
			}
		});
		return {
			hasWebSocketUsageHint,
			importedTargets: resolveImportedRequestGlobalsTargetsFromSpecifiers(matchedSpecifiers, allowedTargets),
			referencedTargets: [...referencedTargets]
		};
	} catch {
		return {
			hasWebSocketUsageHint,
			importedTargets: resolveImportedRequestGlobalsTargetsFromSpecifiers(resolveFallbackImportedRequestGlobalsSpecifiers(code), allowedTargets),
			referencedTargets: resolveFallbackReferencedRequestGlobalsTargets(usageSource, allowedTargets)
		};
	}
}
function resolveManualRequestGlobalsTargets(code) {
	if (!MANUAL_REQUEST_GLOBALS_IMPORT_RE.test(code)) return [];
	const targets = /* @__PURE__ */ new Set();
	if (MANUAL_INSTALL_REQUEST_GLOBALS_CALL_RE.test(code)) for (const target of FULL_REQUEST_GLOBAL_TARGETS) targets.add(target);
	if (MANUAL_INSTALL_ABORT_GLOBALS_CALL_RE.test(code)) for (const target of ABORT_REQUEST_GLOBAL_TARGETS) targets.add(target);
	return [...targets];
}
/**
* @description 根据源码里的实际引用情况,推导 auto 模式需要安装的最小请求全局集合。
*/
function resolveAutoRequestGlobalsTargets(code, allowedTargets) {
	if (!mayContainRequestGlobalsUsageByText(code, allowedTargets)) return [];
	const { hasWebSocketUsageHint, importedTargets, referencedTargets } = analyzeRequestGlobalsUsage(code, allowedTargets);
	if (referencedTargets.length === 0 && importedTargets.length === 0 && !hasWebSocketUsageHint) return [];
	const resolvedTargets = /* @__PURE__ */ new Set();
	for (const target of importedTargets) resolvedTargets.add(target);
	const referencedTargetSet = new Set(referencedTargets);
	for (const target of referencedTargets) resolvedTargets.add(target);
	if (referencedTargets.some((target) => REQUEST_RUNTIME_CORE_USAGE_TARGETS.has(target))) {
		for (const target of REQUEST_RUNTIME_REQUEST_TARGETS) if (allowedTargets.includes(target)) resolvedTargets.add(target);
	} else if (referencedTargetSet.has("AbortController") || referencedTargetSet.has("AbortSignal")) {
		for (const target of ABORT_REQUEST_GLOBAL_TARGETS) if (allowedTargets.includes(target)) resolvedTargets.add(target);
	}
	if (allowedTargets.includes("WebSocket") && (referencedTargetSet.has("WebSocket") || importedTargets.includes("WebSocket") || hasWebSocketUsageHint)) resolvedTargets.add("WebSocket");
	return normalizeResolvedRequestGlobalTargets(resolvedTargets, allowedTargets);
}
/**
* @description 生成入口文件用的请求全局对象注入代码。
*/
function createInjectRequestGlobalsCode(targets, options) {
	if (options?.passiveLocalBindings) {
		const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(targets);
		return passiveBindingsCode ? `/* ${REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER} */ ${passiveBindingsCode}\n` : "";
	}
	const runtimeModuleId = resolveRequestGlobalsRuntimeModuleId();
	const installerOptionsCode = createRequestGlobalsInstallerOptionsCode(targets, options?.networkDefaults);
	const lines = [`import { installWebRuntimeGlobals as __weappViteInstallRequestGlobals } from ${JSON.stringify(runtimeModuleId)}`];
	if (options?.localBindings) {
		const bindingTargets = resolveRequestGlobalsBindingTargets(targets);
		lines.push(`const ${REQUEST_GLOBAL_INSTALLER_HOST_REF} = __weappViteInstallRequestGlobals(${installerOptionsCode}) || globalThis`, ...bindingTargets.map((target) => `var ${target} = ${REQUEST_GLOBAL_INSTALLER_HOST_REF}.${target}`));
	} else lines.push(`__weappViteInstallRequestGlobals(${installerOptionsCode})`);
	lines.push("");
	return lines.join("\n");
}
/**
* @description 为 Vue SFC 入口生成合法的请求全局注入脚本块。
*/
function createInjectRequestGlobalsSfcCode(targets, options) {
	return `<script${options?.setup ? " setup lang=\"ts\"" : " lang=\"ts\""}>\n${createInjectRequestGlobalsCode(targets, options)}<\/script>\n`;
}
function resolveRequestGlobalsSfcInjection(source, targets, options) {
	if (targets.length === 0) return null;
	const { descriptor, errors } = parse$1(source, {
		filename: "request-globals.vue",
		ignoreEmpty: false
	});
	const injectionOptions = descriptor?.scriptSetup ? {
		...options,
		localBindings: false
	} : options;
	const injection = createInjectRequestGlobalsCode(targets, injectionOptions);
	if (errors.length > 0) return {
		code: createInjectRequestGlobalsSfcCode(targets, source.includes("<script setup") ? {
			...options,
			localBindings: false
		} : options),
		index: 0
	};
	const inlineScript = descriptor.script && !descriptor.script.src ? descriptor.script : void 0;
	if (inlineScript) return {
		code: injection,
		index: inlineScript.loc.start.offset
	};
	if (descriptor.scriptSetup && !descriptor.scriptSetup.src ? descriptor.scriptSetup : void 0) return {
		code: createInjectRequestGlobalsSfcCode(targets, injectionOptions),
		index: 0
	};
	if (!descriptor.script) return {
		code: createInjectRequestGlobalsSfcCode(targets, injectionOptions),
		index: 0
	};
	if (!descriptor.scriptSetup) return {
		code: createInjectRequestGlobalsSfcCode(targets, {
			...options,
			setup: true
		}),
		index: 0
	};
	return null;
}
/**
* @description 将请求全局对象注入到现有 SFC 脚本块,避免生成额外的重复 `<script>`。
*/
function injectRequestGlobalsIntoSfc(source, targets, options) {
	const injection = resolveRequestGlobalsSfcInjection(source, targets, options);
	if (!injection) return source;
	return `${source.slice(0, injection.index)}${injection.code}${source.slice(injection.index)}`;
}
//#endregion
//#region src/postcss/constants.ts
const IFDEF = "#ifdef";
const IFNDEF = "#ifndef";
//#endregion
//#region src/postcss/post.ts
const UNI_APP_PLATFORM_DEFINES = {
	weapp: [
		"mp",
		"mp-weixin",
		"vue3"
	],
	alipay: [
		"mp",
		"mp-alipay",
		"vue3"
	],
	tt: [
		"mp",
		"mp-toutiao",
		"vue3"
	],
	swan: [
		"mp",
		"mp-baidu",
		"vue3"
	],
	jd: [
		"mp",
		"mp-jd",
		"vue3"
	],
	xhs: [
		"mp",
		"mp-xhs",
		"vue3"
	]
};
function normalizeTargets(values) {
	return values.map((value) => value.trim().toLowerCase()).filter(Boolean);
}
function parseDirective(text) {
	const normalized = text.replace(/\*/g, "").trim();
	if (!normalized) return;
	const [keyword, ...rest] = normalized.split(/\s+/);
	if (!keyword) return;
	if (keyword === "#ifdef") return {
		type: "ifdef",
		targets: normalizeTargets(rest)
	};
	if (keyword === "#ifndef") return {
		type: "ifndef",
		targets: normalizeTargets(rest)
	};
	if (keyword === "#endif") return {
		type: "endif",
		targets: []
	};
}
function removeConditionalBlock(start) {
	let depth = 1;
	let node = start.next();
	while (node && depth > 0) {
		if (node.type === "comment") {
			const directive = parseDirective(node.text);
			if (directive) {
				if (directive.type === "endif") {
					depth -= 1;
					const comment = node;
					node = comment.next();
					comment.remove();
					continue;
				} else {
					depth += 1;
					const comment = node;
					node = comment.next();
					comment.remove();
					continue;
				}
			}
		}
		const next = node.next();
		node.remove();
		node = next;
	}
}
const postCreator = (options = { platform: "weapp" }) => {
	const atRulePrefixRegExp = new RegExp(`^wv-`);
	const platform = options.platform.toLowerCase();
	const activeTargets = /* @__PURE__ */ new Set([platform, ...UNI_APP_PLATFORM_DEFINES[options.platform]]);
	return {
		postcssPlugin: "postcss-weapp-vite-plugin-post",
		prepare() {
			return {
				AtRule(atRule) {
					if (!atRulePrefixRegExp.test(atRule.name)) return;
					if (atRule.name === `wv-keep-import`) {
						atRule.name = "import";
						return;
					}
					if (atRule.name === `wv-if`) {
						if (![...atRule.params.matchAll(/\(([^)]+)\)/g)].some((match) => {
							return match[1].trim() === platform;
						})) atRule.remove();
						else atRule.replaceWith(atRule.nodes);
					}
				},
				Comment(comment) {
					const directive = parseDirective(comment.text);
					if (!directive) {
						comment.remove();
						return;
					}
					if (directive.type === "endif") {
						comment.remove();
						return;
					}
					const hasPlatform = directive.targets.some((target) => activeTargets.has(target));
					if (!(directive.type === "ifdef" ? hasPlatform : !hasPlatform)) {
						removeConditionalBlock(comment);
						comment.remove();
						return;
					}
					comment.remove();
				}
			};
		}
	};
};
postCreator.postcss = true;
//#endregion
//#region src/postcss/index.ts
const NEEDS_CONDITIONAL_PROCESS_RE = new RegExp(`@wv-|${IFDEF}|${IFNDEF}`);
async function cssPostProcess(code, options) {
	let processed = code;
	if (NEEDS_CONDITIONAL_PROCESS_RE.test(processed)) processed = (await postcss([postCreator(options)]).process(processed, { from: void 0 })).css;
	return options.platform === "weapp" ? transformNestedWxssVars(transformVueDeepSelectors(processed)) : processed;
}
//#endregion
//#region src/plugins/css/shared/preprocessor.ts
const cssCodeCache = new LRUCache({ max: 512 });
const sharedStyleCache = /* @__PURE__ */ new Map();
const nodeRequire = (() => {
	try {
		return createRequire(import.meta.url);
	} catch {
		return null;
	}
})();
async function processCssWithCache(code, configService) {
	const cacheKey = createHash("sha1").update(configService.platform).update("\0").update(code).digest("base64url");
	let processed = cssCodeCache.get(cacheKey);
	if (!processed) {
		processed = await cssPostProcess(code, { platform: configService.platform });
		cssCodeCache.set(cacheKey, processed);
	}
	return processed;
}
function dedupeAndNormalizeDependencies(base, dependencies) {
	const seen = /* @__PURE__ */ new Set();
	const baseDir = path.dirname(base);
	for (const dep of dependencies) {
		if (!dep) continue;
		const normalized = path.isAbsolute(dep) ? dep : path.resolve(baseDir, dep);
		seen.add(normalized);
	}
	return Array.from(seen);
}
async function renderSharedStyleEntry(entry, _configService, resolvedConfig) {
	const absolutePath = entry.absolutePath;
	const cacheKey = `${absolutePath}:${resolvedConfig ? "resolved" : "raw"}`;
	let stats;
	try {
		stats = await fs$1.stat(absolutePath);
	} catch (error) {
		const reason = error instanceof Error ? error.message : String(error);
		throw new Error(`[分包] 编译共享样式 \`${entry.source}\` 失败:${reason}`);
	}
	const cached = sharedStyleCache.get(cacheKey);
	if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) return {
		css: cached.result.css,
		dependencies: [...cached.result.dependencies],
		source: cached.result.source
	};
	try {
		const css = await fs$1.readFile(absolutePath, "utf8");
		if (!resolvedConfig) {
			const result = {
				css,
				dependencies: [],
				source: css
			};
			sharedStyleCache.set(cacheKey, {
				mtimeMs: stats.mtimeMs,
				size: stats.size,
				result
			});
			return {
				css: result.css,
				dependencies: [...result.dependencies],
				source: result.source
			};
		}
		const processed = await preprocessCSS(css, absolutePath, resolvedConfig);
		const dependencies = processed?.deps ? dedupeAndNormalizeDependencies(absolutePath, processed.deps) : [];
		const result = {
			css: processed.code,
			dependencies,
			source: css
		};
		sharedStyleCache.set(cacheKey, {
			mtimeMs: stats.mtimeMs,
			size: stats.size,
			result
		});
		return {
			css: result.css,
			dependencies: [...result.dependencies],
			source: result.source
		};
	} catch (error) {
		const reason = error instanceof Error ? error.message : String(error);
		throw new Error(`[分包] 编译共享样式 \`${entry.source}\` 失败:${reason}`);
	}
}
function invalidateSharedStyleCache() {
	sharedStyleCache.clear();
	cssCodeCache.clear();
	try {
		const candidates = [
			"tailwindcss/lib/lib/sharedState.js",
			"tailwindcss/dist/sharedState.js",
			"tailwindcss/src/lib/sharedState.js",
			"tailwindcss/sharedState.js"
		];
		if (!nodeRequire) return;
		for (const request of candidates) try {
			const sharedState = nodeRequire(request);
			if (sharedState) {
				sharedState.contextMap?.clear?.();
				sharedState.configContextMap?.clear?.();
				sharedState.contextSourcesMap?.clear?.();
				sharedState.sourceHashMap?.clear?.();
				break;
			}
		} catch {}
	} catch {}
}
//#endregion
//#region src/plugins/css/shared/sharedStyles.ts
const styleMatcherCache = /* @__PURE__ */ new WeakMap();
function collectSharedStyleEntries(ctx, configService) {
	const map = /* @__PURE__ */ new Map();
	const mainPackageEntries = ctx.scanService?.mainPackageStyleEntries;
	const currentRoot = configService.currentSubPackageRoot;
	if (!currentRoot && mainPackageEntries?.length) map.set("", mainPackageEntries);
	const registry = ctx.scanService?.subPackageMap;
	if (!registry?.size) return map;
	for (const [root, meta] of registry.entries()) {
		if (!meta.styleEntries?.length) continue;
		if (currentRoot && root !== currentRoot) continue;
		map.set(root, meta.styleEntries);
	}
	return map;
}
function sanitizeRelativePath(value) {
	const normalized = toPosixPath(value);
	if (normalized.startsWith("./")) return normalized.slice(2);
	return normalized;
}
function isWithinRoot(pathname, root) {
	if (!root) return true;
	return pathname === root || pathname.startsWith(`${root}/`);
}
function relativeToRoot(pathname, root) {
	if (!pathname) return pathname;
	if (!root) return pathname;
	if (pathname === root) return "";
	if (pathname.startsWith(`${root}/`)) return pathname.slice(root.length + 1);
}
function getStyleMatcher(entry) {
	const cached = styleMatcherCache.get(entry);
	if (cached) return cached;
	const includePatterns = entry.include?.length ? entry.include : ["**/*"];
	const excludePatterns = entry.exclude?.length ? entry.exclude : void 0;
	const matcher = { include: picomatch(includePatterns, { dot: true }) };
	if (excludePatterns?.length) matcher.exclude = picomatch(excludePatterns, { dot: true });
	styleMatcherCache.set(entry, matcher);
	return matcher;
}
function matchesStyleEntry(entry, relativeModule, relativeFile) {
	const matcher = getStyleMatcher(entry);
	const candidates = [];
	if (typeof relativeFile === "string" && relativeFile.length > 0) candidates.push(relativeFile);
	if (typeof relativeModule === "string" && relativeModule.length > 0) candidates.push(relativeModule);
	if (!candidates.length) return false;
	if (!candidates.some((candidate) => matcher.include(candidate))) return false;
	if (matcher.exclude && candidates.some((candidate) => matcher.exclude(candidate))) return false;
	return true;
}
function findSharedStylesForModule(modulePath, fileName, sharedStyles) {
	const sanitizedModule = sanitizeRelativePath(modulePath);
	const sanitizedFile = sanitizeRelativePath(fileName);
	const matched = [];
	for (const [root, entries] of sharedStyles.entries()) {
		const normalizedRoot = normalizeRoot(root);
		if (root && !normalizedRoot) continue;
		if (!isWithinRoot(sanitizedFile, normalizedRoot)) continue;
		const relativeModule = relativeToRoot(sanitizedModule, normalizedRoot);
		const relativeFile = relativeToRoot(sanitizedFile, normalizedRoot);
		for (const entry of entries) {
			if (entry.inject === false) continue;
			if (matchesStyleEntry(entry, relativeModule, relativeFile)) matched.push(entry);
		}
	}
	return matched;
}
function resolveImportSpecifiers(fileName, entries) {
	const posixFileName = toPosixPath(fileName);
	const dir = path.posix.dirname(posixFileName);
	const seen = /* @__PURE__ */ new Set();
	const specifiers = [];
	for (const entry of entries) {
		const target = toPosixPath(entry.outputRelativePath);
		if (target === posixFileName) continue;
		let specifier = path.posix.relative(dir, target) || path.posix.basename(target);
		if (!specifier || specifier === ".") continue;
		if (!specifier.startsWith(".")) specifier = `./${specifier}`;
		specifier = specifier.replace(/\/+/g, "/");
		if (specifier === "./") continue;
		if (seen.has(specifier)) continue;
		seen.add(specifier);
		specifiers.push(specifier);
	}
	return specifiers;
}
function prependSharedStyleImports(css, statements) {
	if (!statements.length) return css;
	const importBlock = statements.join("\n");
	const charsetMatch = css.match(/^(@charset\s+['"][^'"]+';\s*)+/);
	if (charsetMatch) {
		const prefix = charsetMatch[0];
		return `${prefix}${importBlock}\n${css.slice(prefix.length)}`;
	}
	return `${importBlock}\n${css}`;
}
function resolveSharedStyleImportStatements(modulePath, fileName, sharedStyles, configService) {
	const relativeModulePath = configService.relativeAbsoluteSrcRoot(modulePath);
	if (!relativeModulePath) return [];
	const normalizedModule = toPosixPath(relativeModulePath);
	if (normalizedModule.startsWith("..")) return [];
	const entries = findSharedStylesForModule(normalizedModule, toPosixPath(fileName), sharedStyles);
	if (!entries?.length) return [];
	const specifiers = resolveImportSpecifiers(fileName, entries);
	if (!specifiers.length) return [];
	const statements = [];
	const emitted = /* @__PURE__ */ new Set();
	for (const specifier of specifiers) {
		const statement = `@import '${specifier}';`;
		if (emitted.has(statement)) continue;
		emitted.add(statement);
		statements.push(statement);
	}
	return statements;
}
function injectSharedStyleImports(css, modulePath, fileName, sharedStyles, configService) {
	const statements = resolveSharedStyleImportStatements(modulePath, fileName, sharedStyles, configService).filter((statement) => {
		if (css.includes(statement)) return false;
		return true;
	});
	if (!statements.length) return css;
	return prependSharedStyleImports(css, statements);
}
//#endregion
//#region src/plugins/tailwindcssMarker.ts
const MANAGED_TAILWINDCSS_ENTRY_MARKER_PREFIX = ".__weapp_vite_managed_tailwindcss_entry_";
const MANAGED_TAILWINDCSS_ENTRY_MARKER_SUFFIX = "__{--weapp-vite-managed-tailwindcss-entry:1}";
const MANAGED_TAILWINDCSS_OUTPUT_MARKER_PREFIX = "/*! weapp-vite managed-tailwindcss-output:";
const MANAGED_TAILWINDCSS_OUTPUT_MARKER_RE = /\/\*! weapp-vite managed-tailwindcss-output:\d+ \*\/\s*/g;
const managedTailwindcssEntries = /* @__PURE__ */ new WeakMap();
function normalizeManagedTailwindcssEntryPath(id) {
	const normalized = normalizeFsResolvedId(id);
	try {
		return normalizeFsResolvedId(fs.realpathSync.native(normalized));
	} catch {
		return normalized;
	}
}
function registerManagedTailwindcssEntries(ctx, entries) {
	managedTailwindcssEntries.set(ctx, new Set(entries.map(normalizeManagedTailwindcssEntryPath)));
}
function isManagedTailwindcssEntry(ctx, id) {
	return managedTailwindcssEntries.get(ctx)?.has(normalizeManagedTailwindcssEntryPath(id)) === true;
}
function createManagedTailwindcssEntryMarker(index) {
	return `${MANAGED_TAILWINDCSS_ENTRY_MARKER_PREFIX}${index}${MANAGED_TAILWINDCSS_ENTRY_MARKER_SUFFIX}`;
}
function findManagedTailwindcssEntryMarker(css) {
	return css.indexOf(MANAGED_TAILWINDCSS_ENTRY_MARKER_PREFIX);
}
function createManagedTailwindcssOutputMarker(index) {
	return `${MANAGED_TAILWINDCSS_OUTPUT_MARKER_PREFIX}${index} */`;
}
function hasManagedTailwindcssOutputMarker(css) {
	return css.includes(MANAGED_TAILWINDCSS_OUTPUT_MARKER_PREFIX);
}
function stripManagedTailwindcssOutputMarkers(css) {
	return css.replace(MANAGED_TAILWINDCSS_OUTPUT_MARKER_RE, "");
}
//#endregion
//#region src/plugins/css.ts
const LEADING_BLANK_LINES_RE = /^(?:[ \t]*\r?\n)+/;
const TAILWIND_CONTENT_HMR_NONCE_RE = /\n\/\* weapp-vite tailwind-content [^*\n]+ \*\/$/;
const VITE_PREPROCESS_STYLE_RE = /\.(?:acss|css|less|sass|scss|styl|stylus|pcss|postcss|sss)$/;
const TAILWIND_GENERATOR_PLACEHOLDER = "/*! weapp-tailwindcss generator-placeholder */";
const pendingOwnerStyleSources = /* @__PURE__ */ new WeakMap();
function consumePendingOwnerStyleSources(ctx) {
	const sources = pendingOwnerStyleSources.get(ctx);
	pendingOwnerStyleSources.delete(ctx);
	return sources;
}
function findGeneratorBoundary(css) {
	const externalIndex = css.indexOf(TAILWIND_GENERATOR_PLACEHOLDER);
	const managedIndex = findManagedTailwindcssEntryMarker(css);
	if (externalIndex < 0) return managedIndex;
	if (managedIndex < 0) return externalIndex;
	return Math.min(externalIndex, managedIndex);
}
function extractPendingOwnerStyleSource(css) {
	const boundary = findGeneratorBoundary(css);
	return (boundary < 0 ? css : css.slice(0, boundary)).trim();
}
function recordPendingOwnerStyleSource(ctx, fileName, css) {
	const authorCss = extractPendingOwnerStyleSource(css);
	if (!authorCss) return;
	const sources = pendingOwnerStyleSources.get(ctx) ?? /* @__PURE__ */ new Map();
	const fragments = sources.get(fileName) ?? [];
	if (!fragments.includes(authorCss)) fragments.push(authorCss);
	sources.set(fileName, fragments);
	pendingOwnerStyleSources.set(ctx, sources);
}
function stripLeadingBlankLines(code) {
	return code.replace(LEADING_BLANK_LINES_RE, "");
}
function isSourceStyleAsset(fileName) {
	const extension = path.extname(fileName);
	return isSourceStyleExtension(extension) || /\.(?:stylus|pcss|postcss|sss)$/.test(fileName);
}
function hasStyleDirtyReason(dirtyReasonSummary) {
	return dirtyReasonSummary.some((reason) => reason.startsWith("style-sidecar:") || reason.startsWith("css-importer:") || reason.startsWith("css-importer-fallback:") || reason.startsWith("entry-style-only:") || reason.startsWith("tailwind-content:"));
}
function hasTailwindContentDirtyReason(ctx) {
	return ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary?.some((reason) => reason.startsWith("tailwind-content:")) === true;
}
function appendTailwindContentHmrNonce(ctx, source) {
	if (!hasTailwindContentDirtyReason(ctx)) return source;
	return `${source}\n/* weapp-vite tailwind-content ${ctx.runtimeState?.build?.hmr?.profile?.eventId ?? "unknown"} */`;
}
function stripTailwindContentHmrNonce(source) {
	return source.replace(TAILWIND_CONTENT_HMR_NONCE_RE, "");
}
function isStyleBundleAsset(output, bundleKey) {
	if (output.type !== "asset") return false;
	return isSourceStyleAsset(output.fileName || bundleKey);
}
function hasStyleBundleAsset(bundle) {
	for (const [bundleKey, output] of Object.entries(bundle)) if (isStyleBundleAsset(output, bundleKey)) return true;
	return false;
}
function shouldSkipUnchangedStyleHmrBundle(ctx, bundle) {
	if (!ctx.configService?.isDev) return false;
	const dirtyReasonSummary = ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary;
	if (!dirtyReasonSummary?.length) return false;
	return !hasStyleDirtyReason(dirtyReasonSummary) && !hasStyleBundleAsset(bundle);
}
function shouldPreprocessWithVite(fileName) {
	return VITE_PREPROCESS_STYLE_RE.test(fileName);
}
function hasViteStyleAssetPlaceholder(source) {
	return source.includes("__VITE_ASSET__") || source.includes("__VITE_PUBLIC_ASSET__");
}
async function preprocessStyleSource(code, fileName, resolvedConfig, options) {
	const normalizedCss = stripLeadingBlankLines(code);
	if (!resolvedConfig || options?.enabled === false || !shouldPreprocessWithVite(fileName)) return {
		css: normalizedCss,
		dependencies: []
	};
	const processed = await preprocessCSS(normalizedCss, fileName, resolvedConfig);
	return {
		css: stripLeadingBlankLines(processed.code),
		dependencies: processed.deps ? Array.from(processed.deps) : []
	};
}
async function readStyleGraphSource(stylePath, fallback) {
	try {
		return await fs$1.readFile(stylePath, "utf8");
	} catch {
		return fallback;
	}
}
async function resolveMemoryStyleSource(ctx, stylePath) {
	const sourceId = normalizeFsResolvedId(stylePath, { stripLeadingNullByte: true });
	const cache = ctx.runtimeState?.css?.transformedSidecarSource;
	const cached = cache?.get(sourceId);
	if (!cached) return;
	try {
		if (await fs$1.readFile(stylePath, "utf8") === cached.diskSource) return cached.code;
	} catch {}
	cache?.delete(sourceId);
}
function resolveOutputStyleFileName(configService, stylePath) {
	return configService.relativeOutputPath(changeFileExtension(stylePath, configService.outputExtensions.wxss));
}
function isUnchangedDevHmrStyleAsset(ctx, normalizedFileName, current, source) {
	const hmrState = ctx.runtimeState?.build?.hmr;
	const currentHmrFile = hmrState?.profile.file;
	if (typeof currentHmrFile === "string") {
		const currentOutputFile = resolveOutputStyleFileName(ctx.configService, currentHmrFile);
		if (currentOutputFile && toPosixPath(currentOutputFile) === normalizedFileName) return false;
	}
	const isDevHmr = ctx.configService?.isDev === true && (hmrState?.didEmitAllEntries === true || (hmrState?.lastHmrEntryIds?.size ?? 0) > 0 || (hmrState?.lastEmittedEntryIds?.size ?? 0) > 0 || hmrState?.profile.event !== void 0);
	const canonicalCurrent = hasTailwindContentDirtyReason(ctx) ? current : stripTailwindContentHmrNonce(current);
	return isDevHmr && canonicalCurrent === source && ctx.runtimeState?.css?.emittedSource.get(normalizedFileName) === source;
}
function resolveCurrentHmrStyleSourcePath(ctx, normalizedFileName) {
	const currentHmrFile = (ctx.runtimeState?.build?.hmr)?.profile.file;
	if (typeof currentHmrFile !== "string") return;
	const currentOutputFile = resolveOutputStyleFileName(ctx.configService, currentHmrFile);
	if (currentOutputFile === void 0 || toPosixPath(currentOutputFile) !== normalizedFileName) return;
	return currentHmrFile;
}
function resolveFreshHmrStyleSourcePath(ctx, normalizedFileName) {
	const currentHmrFile = resolveCurrentHmrStyleSourcePath(ctx, normalizedFileName);
	if (!currentHmrFile || currentHmrFile.endsWith(".css") || !shouldPreprocessWithVite(currentHmrFile)) return;
	return currentHmrFile;
}
function emitCssAssetIfChanged(ctx, pluginCtx, bundle, fileName, source, options) {
	const normalizedFileName = toPosixPath(fileName);
	const cache = ctx.runtimeState?.css?.emittedSource;
	const existing = bundle[fileName];
	const forceEmit = hasTailwindContentDirtyReason(ctx);
	const emittedSource = appendTailwindContentHmrNonce(ctx, source);
	if (existing?.type === "asset") {
		const current = existing.source?.toString?.() ?? "";
		if (!forceEmit && isUnchangedDevHmrStyleAsset(ctx, normalizedFileName, current, emittedSource)) {
			delete bundle[fileName];
			return false;
		}
		if (current !== emittedSource) existing.source = emittedSource;
		cache?.set(normalizedFileName, source);
		return true;
	}
	if (!forceEmit && cache?.get(normalizedFileName) === source) return false;
	pluginCtx.emitFile({
		type: "asset",
		fileName,
		...options?.originalFileName ? { originalFileName: options.originalFileName } : {},
		source: emittedSource
	});
	cache?.set(normalizedFileName, source);
	return true;
}
function injectSharedStyleImportsCached(css, modulePath, fileName, sharedStyles, configService, cache) {
	const cacheKey = `${modulePath}\0${fileName}`;
	let statements = cache.get(cacheKey);
	if (!statements) {
		statements = resolveSharedStyleImportStatements(modulePath, fileName, sharedStyles, configService);
		cache.set(cacheKey, statements);
	}
	let missingStatements;
	for (const statement of statements) {
		if (css.includes(statement)) continue;
		missingStatements ??= [];
		missingStatements.push(statement);
	}
	if (!missingStatements?.length) return css;
	return prependSharedStyleImports(css, missingStatements);
}
function resolveStyleOwnerId(id) {
	return parseLogicalEntryId(id)?.sourceId ?? id;
}
function analyzeBundleStyles(bundle) {
	const facadeChunks = [];
	const ownersByCssAsset = /* @__PURE__ */ new Map();
	const styleAssets = [];
	for (const [bundleKey, output] of Object.entries(bundle)) {
		if (isStyleBundleAsset(output, bundleKey)) {
			styleAssets.push({
				bundleKey,
				asset: output
			});
			continue;
		}
		if (output.type !== "chunk" || !output.facadeModuleId) continue;
		facadeChunks.push(output);
		const importedCss = output.viteMetadata?.importedCss;
		if (!importedCss?.size) continue;
		for (const cssAsset of importedCss) {
			const owners = ownersByCssAsset.get(cssAsset) ?? /* @__PURE__ */ new Set();
			owners.add(resolveStyleOwnerId(output.facadeModuleId));
			ownersByCssAsset.set(cssAsset, owners);
		}
	}
	return {
		facadeChunks,
		ownersByCssAsset,
		styleAssets
	};
}
async function emitStyleSidecarAsset(ctx, pluginCtx, bundle, stylePath, resolvedConfig) {
	const { configService } = ctx;
	const fileName = resolveOutputStyleFileName(configService, stylePath);
	if (!fileName) return false;
	if (isManagedTailwindcssEntry(ctx, stylePath)) return false;
	const rawCss = await resolveMemoryStyleSource(ctx, stylePath) ?? await fs$1.readFile(stylePath, "utf8");
	const { css, dependencies } = await preprocessStyleSource(rawCss, stylePath, resolvedConfig);
	syncCssImportDependencies(ctx, stylePath, rawCss, dependencies);
	if (typeof pluginCtx.addWatchFile === "function") for (const dependency of dependencies) pluginCtx.addWatchFile(normalizeWatchPath(dependency));
	return emitCssAssetIfChanged(ctx, pluginCtx, bundle, fileName, injectSharedStyleImports(await processCssWithCache(css, configService), stylePath, fileName, collectSharedStyleEntries(ctx, configService), configService), { originalFileName: stylePath });
}
async function handleBundleEntry(ctx, bundle, bundleKey, asset, configService, sharedStyles, cssAssetOwners, emitted, sharedStyleImportCache, resolvedConfig) {
	if (asset.type !== "asset") return;
	const toAbsolute = (id) => {
		return toAbsoluteId(id, configService, void 0, { base: "cwd" }) || id;
	};
	const normalizeOwnerId = (id) => {
		return normalizeFsResolvedId(resolveStyleOwnerId(id), { stripLeadingNullByte: true });
	};
	const preparedStyleAssets = /* @__PURE__ */ new Map();
	const resolveOriginalStylePath = () => {
		const [rawOriginal] = asset.originalFileNames ?? [];
		return rawOriginal ? toAbsolute(rawOriginal) : path.resolve(configService.absoluteSrcRoot, bundleKey);
	};
	const prepareStyleAssetForOwner = async (rawCss, preprocessId, shouldPreprocess) => {
		const cacheKey = `${shouldPreprocess ? 1 : 0}\0${preprocessId}\0${rawCss}`;
		let cached = preparedStyleAssets.get(cacheKey);
		if (!cached) {
			cached = (async () => {
				const graphSource = await readStyleGraphSource(preprocessId, rawCss);
				const { css, dependencies } = await preprocessStyleSource(shouldPreprocess && hasViteStyleAssetPlaceholder(rawCss) ? graphSource : rawCss, preprocessId, resolvedConfig, { enabled: shouldPreprocess });
				syncCssImportDependencies(ctx, preprocessId, graphSource, dependencies);
				if (typeof this.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(normalizeWatchPath(dependency));
				return { processedCss: stripManagedTailwindcssOutputMarkers(await processCssWithCache(css, configService)) };
			})();
			preparedStyleAssets.set(cacheKey, cached);
		}
		return cached;
	};
	const prepareOwnedStyleAsset = async (owner, preprocessId, shouldPreprocess) => {
		const fileName = resolveOutputStyleFileName(configService, owner);
		if (!fileName) return;
		const rawCss = asset.source.toString();
		const { processedCss } = await prepareStyleAssetForOwner(rawCss, preprocessId, shouldPreprocess);
		return {
			fileName,
			modulePath: owner,
			normalizedFileName: toPosixPath(fileName),
			processedCss
		};
	};
	const emitStyleAssetForOwner = async (owner, preprocessId, shouldPreprocess) => {
		const prepared = await prepareOwnedStyleAsset(owner, preprocessId, shouldPreprocess);
		if (!prepared) return;
		const cssWithImports = injectSharedStyleImportsCached(prepared.processedCss, prepared.modulePath, prepared.fileName, sharedStyles, configService, sharedStyleImportCache);
		emitCssAssetIfChanged(ctx, this, bundle, prepared.fileName, cssWithImports);
		emitted.add(prepared.normalizedFileName);
		return prepared.normalizedFileName;
	};
	const isCssAsset = bundleKey.endsWith(".css");
	const isFinalStyleAsset = bundleKey.endsWith(`.${configService.outputExtensions.wxss}`) && (!isCssAsset || path.posix.basename(bundleKey, ".css") === "app");
	const isSourceStyleAssetKey = isSourceStyleAsset(bundleKey);
	const originalStylePath = resolveOriginalStylePath();
	if (isManagedTailwindcssEntry(ctx, originalStylePath) && !hasManagedTailwindcssOutputMarker(asset.source.toString())) {
		delete bundle[bundleKey];
		return;
	}
	if (isFinalStyleAsset) {
		const absOriginal = originalStylePath;
		const fileName = resolveOutputStyleFileName(configService, absOriginal);
		if (fileName) emitted.add(toPosixPath(fileName));
		if (fileName) {
			const source = asset.source.toString();
			const canonicalSource = hasTailwindContentDirtyReason(ctx) ? source : stripTailwindContentHmrNonce(source);
			const normalizedFileName = toPosixPath(fileName);
			const freshHmrStyleSourcePath = resolveFreshHmrStyleSourcePath(ctx, normalizedFileName);
			const preprocessId = freshHmrStyleSourcePath ?? absOriginal;
			const shouldPreprocess = shouldPreprocessWithVite(preprocessId);
			const graphSource = await readStyleGraphSource(preprocessId, canonicalSource);
			const preprocessInput = freshHmrStyleSourcePath ? await resolveMemoryStyleSource(ctx, freshHmrStyleSourcePath) ?? graphSource : shouldPreprocess && hasViteStyleAssetPlaceholder(canonicalSource) ? graphSource : canonicalSource;
			const { css, dependencies } = await preprocessStyleSource(preprocessInput, preprocessId, resolvedConfig, { enabled: shouldPreprocess });
			syncCssImportDependencies(ctx, preprocessId, freshHmrStyleSourcePath ? preprocessInput : graphSource, dependencies);
			if (typeof this.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(normalizeWatchPath(dependency));
			const processedCss = stripManagedTailwindcssOutputMarkers(await processCssWithCache(css, configService));
			if (fileName !== bundleKey) {
				delete bundle[bundleKey];
				emitCssAssetIfChanged(ctx, this, bundle, fileName, processedCss);
			} else if (isUnchangedDevHmrStyleAsset(ctx, normalizedFileName, source, processedCss)) delete bundle[bundleKey];
			else if (processedCss !== source) asset.source = processedCss;
			ctx.runtimeState?.css?.emittedSource.set(normalizedFileName, processedCss);
		}
		return;
	}
	if (!isCssAsset && !isSourceStyleAssetKey) return;
	const ownersFromChunks = cssAssetOwners.get(bundleKey);
	const owners = ownersFromChunks?.size ? ownersFromChunks : new Set((asset.originalFileNames ?? []).map(normalizeOwnerId).filter((originalFileName) => {
		return isJsOrTs(originalFileName) || originalFileName.endsWith(".vue");
	}).map(toAbsolute));
	if (!owners.size) {
		if (isSourceStyleAssetKey && !isCssAsset) {
			await emitStyleAssetForOwner(resolveOriginalStylePath(), resolveOriginalStylePath(), !isCssAsset);
			delete bundle[bundleKey];
			return;
		}
		delete bundle[bundleKey];
		return;
	}
	const preparedOwners = (await Promise.all(Array.from(owners).map(async (owner) => {
		return await prepareOwnedStyleAsset(owner, resolveOriginalStylePath(), !isCssAsset);
	}))).filter((prepared) => prepared !== void 0);
	const normalizedBundleKey = toPosixPath(bundleKey);
	if (!isCssAsset || !preparedOwners.some((prepared) => prepared.normalizedFileName === normalizedBundleKey)) delete bundle[bundleKey];
	return preparedOwners;
}
async function emitSharedStyleEntries(ctx, sharedStyles, emitted, configService, bundle, resolvedConfig) {
	if (!sharedStyles.size) return;
	const tasks = [];
	for (const entries of sharedStyles.values()) for (const entry of entries) {
		const fileName = toPosixPath(entry.outputRelativePath);
		if (emitted.has(fileName)) continue;
		const absolutePath = entry.absolutePath;
		if (typeof this.addWatchFile === "function") this.addWatchFile(normalizeWatchPath(absolutePath));
		tasks.push({
			entry,
			fileName,
			absolutePath
		});
	}
	const renderedEntries = await Promise.all(tasks.map(async (task) => {
		const { entry, absolutePath } = task;
		if (!await pathExists(absolutePath, { ttlMs: getPathExistsTtlMs(configService) })) return;
		const { css: renderedCss, dependencies, source } = await renderSharedStyleEntry(entry, configService, resolvedConfig);
		syncCssImportDependencies(ctx, absolutePath, source ?? await readStyleGraphSource(absolutePath, renderedCss), dependencies);
		if (typeof this.addWatchFile === "function" && dependencies.length) {
			for (const dependency of dependencies) if (dependency && dependency !== absolutePath) this.addWatchFile(normalizeWatchPath(dependency));
		}
		const css = await processCssWithCache(renderedCss, configService);
		return {
			...task,
			css
		};
	}));
	for (const result of renderedEntries) {
		if (!result) continue;
		if (emitted.has(result.fileName)) continue;
		if (bundle[result.fileName]) delete bundle[result.fileName];
		emitted.add(result.fileName);
		emitCssAssetIfChanged(ctx, this, bundle, result.fileName, result.css);
	}
}
async function prepareSharedStyleImportForModule(sharedStyles, configService, sharedStyleImportCache, moduleId) {
	const { outputExtensions } = configService;
	if (!configService.relativeAbsoluteSrcRoot(moduleId)) return;
	const converted = changeFileExtension(moduleId, outputExtensions.wxss);
	const fileName = configService.relativeOutputPath(converted);
	if (!fileName) return;
	const normalizedFileName = toPosixPath(fileName);
	const cssWithImports = injectSharedStyleImportsCached("", moduleId, fileName, sharedStyles, configService, sharedStyleImportCache);
	if (!cssWithImports.trim()) return;
	return {
		fileName,
		normalizedFileName,
		css: await processCssWithCache(cssWithImports, configService)
	};
}
async function emitSharedStyleImportsForChunks(ctx, sharedStyles, emitted, configService, bundle, facadeChunks, sharedStyleImportCache) {
	if (!sharedStyles.size) return;
	const handledModuleIds = /* @__PURE__ */ new Set();
	const chunkImportAssets = await Promise.all(facadeChunks.map(async (output) => {
		const moduleId = output.facadeModuleId;
		if (!moduleId) return;
		const ownerId = resolveStyleOwnerId(moduleId);
		handledModuleIds.add(normalizeFsResolvedId(ownerId));
		return prepareSharedStyleImportForModule(sharedStyles, configService, sharedStyleImportCache, ownerId);
	}));
	for (const asset of chunkImportAssets) {
		if (!asset || emitted.has(asset.normalizedFileName)) continue;
		emitCssAssetIfChanged(ctx, this, bundle, asset.fileName, asset.css);
		emitted.add(asset.normalizedFileName);
	}
	if (!ctx.configService?.isDev) return;
	if (!((ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary)?.some((reason) => reason.startsWith("css-importer:") || reason.startsWith("css-importer-fallback:")) === true)) return;
	const hmrImportAssets = await Promise.all(Array.from(ctx.runtimeState?.build?.hmr?.lastHmrEntryIds ?? []).map(async (moduleId) => {
		if (handledModuleIds.has(normalizeFsResolvedId(moduleId))) return;
		return prepareSharedStyleImportForModule(sharedStyles, configService, sharedStyleImportCache, moduleId);
	}));
	for (const asset of hmrImportAssets) {
		if (!asset || emitted.has(asset.normalizedFileName)) continue;
		emitCssAssetIfChanged(ctx, this, bundle, asset.fileName, asset.css);
		emitted.add(asset.normalizedFileName);
	}
}
async function generateBundleSharedCss(ctx, configService, bundle, analysis, resolvedConfig) {
	pendingOwnerStyleSources.delete(ctx);
	const sharedStyles = collectSharedStyleEntries(ctx, configService);
	const { facadeChunks, ownersByCssAsset, styleAssets } = analysis;
	if (!sharedStyles.size && !styleAssets.length) return;
	const emitted = /* @__PURE__ */ new Set();
	const sharedStyleImportCache = /* @__PURE__ */ new Map();
	const tasks = styleAssets.map(({ bundleKey, asset }) => {
		return handleBundleEntry.call(this, ctx, bundle, bundleKey, asset, configService, sharedStyles, ownersByCssAsset, emitted, sharedStyleImportCache, resolvedConfig);
	});
	const preparedOwnerStyles = (await Promise.all(tasks)).flatMap((result) => result ?? []);
	const ownerStyleGroups = /* @__PURE__ */ new Map();
	for (const prepared of preparedOwnerStyles) {
		let group = ownerStyleGroups.get(prepared.normalizedFileName);
		if (!group) {
			group = {
				fileName: prepared.fileName,
				fragments: [],
				modulePath: prepared.modulePath
			};
			ownerStyleGroups.set(prepared.normalizedFileName, group);
		}
		group.fragments.push(prepared.processedCss);
	}
	for (const [normalizedFileName, group] of ownerStyleGroups) {
		const cssWithImports = injectSharedStyleImportsCached(group.fragments.join("\n"), group.modulePath, group.fileName, sharedStyles, configService, sharedStyleImportCache);
		if (group.fragments.some((fragment) => findGeneratorBoundary(fragment) >= 0)) {
			const ownerCssWithImports = injectSharedStyleImportsCached(group.fragments.map(extractPendingOwnerStyleSource).filter(Boolean).join("\n"), group.modulePath, group.fileName, sharedStyles, configService, sharedStyleImportCache);
			recordPendingOwnerStyleSource(ctx, group.fileName, ownerCssWithImports);
		}
		emitCssAssetIfChanged(ctx, this, bundle, group.fileName, cssWithImports);
		emitted.add(normalizedFileName);
	}
	await emitSharedStyleEntries.call(this, ctx, sharedStyles, emitted, configService, bundle, resolvedConfig);
	await emitSharedStyleImportsForChunks.call(this, ctx, sharedStyles, emitted, configService, bundle, facadeChunks, sharedStyleImportCache);
}
async function emitCollectedStyleSidecars(ctx, bundle, resolvedConfig) {
	const sidecarImports = ctx.runtimeState?.css?.sidecarImports;
	if (!sidecarImports?.size) return;
	await Promise.all(Array.from(sidecarImports).map(async (stylePath) => {
		await emitStyleSidecarAsset(ctx, this, bundle, stylePath, resolvedConfig);
	}));
}
function css(ctx) {
	const { configService } = ctx;
	let resolvedConfig;
	return [{
		name: "weapp-vite:css",
		enforce: "pre",
		configResolved(config) {
			resolvedConfig = config;
		},
		generateBundle: { async handler(_opts, bundle) {
			const rolldownBundle = bundle;
			if (shouldSkipUnchangedStyleHmrBundle(ctx, rolldownBundle)) return;
			const styleAnalysis = analyzeBundleStyles(rolldownBundle);
			await generateBundleSharedCss.call(this, ctx, configService, bundle, styleAnalysis, resolvedConfig);
			await emitCollectedStyleSidecars.call(this, ctx, rolldownBundle, resolvedConfig);
		} }
	}, {
		name: "weapp-vite:css-sidecar-source",
		async transform(code, id) {
			const sidecar = parseSidecarSourceRequest(id);
			if (!sidecar || sidecar.kind !== "style") return null;
			const sourceId = normalizeFsResolvedId(sidecar.sourceId, { stripLeadingNullByte: true });
			try {
				const diskSource = await fs$1.readFile(sourceId, "utf8");
				ctx.runtimeState?.css?.transformedSidecarSource.set(sourceId, {
					code,
					diskSource
				});
			} catch {
				ctx.runtimeState?.css?.transformedSidecarSource.delete(sourceId);
			}
			return null;
		}
	}];
}
//#endregion
//#region src/analyze/glassEasel/index.ts
const MIGRATION_GUIDE = "https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/glass-easel/migration.html";
const TEMPLATE_FILE_RE = /\.(?:wxml|axml|swan|ttml|jxml|qml|ksml|xhsml)$/i;
function isRecord(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getOutputSource(output) {
	if (output.type === "chunk") return output.code;
	if (typeof output.source === "string") return output.source;
	return Buffer.from(output.source).toString("utf8");
}
function offsetToLocation(source, offset) {
	const lines = source.slice(0, offset).split(/\r?\n/);
	return {
		line: lines.length,
		column: (lines[lines.length - 1]?.length ?? 0) + 1
	};
}
function diagnosticKey(diagnostic) {
	return [
		diagnostic.code,
		diagnostic.file,
		diagnostic.line ?? 0,
		diagnostic.column ?? 0,
		diagnostic.message
	].join(":");
}
function registerDiagnostic(ctx, diagnostic) {
	const key = diagnosticKey(diagnostic);
	ctx.runtimeState.glassEasel.diagnostics.set(key, diagnostic);
	if (ctx.runtimeState.glassEasel.silent || ctx.runtimeState.glassEasel.warnedDiagnostics.has(key)) return;
	ctx.runtimeState.glassEasel.warnedDiagnostics.add(key);
	logger_default.warn(`[${diagnostic.code}] ${diagnostic.file}${diagnostic.line ? `:${diagnostic.line}:${diagnostic.column}` : ""} ${diagnostic.message}`);
}
function analyzeJsonConfig(file, source) {
	let config;
	try {
		config = JSON.parse(source);
	} catch {
		return {
			detected: false,
			diagnostics: []
		};
	}
	if (!isRecord(config)) return {
		detected: false,
		diagnostics: []
	};
	if (!(file === "app.json" || file.endsWith("/app.json") || file === "plugin.json" || file.endsWith("/plugin.json") || config.component !== true) || config.glassEaselWebview !== true) return {
		detected: false,
		diagnostics: []
	};
	if (config.componentFramework === "glass-easel") return {
		detected: true,
		diagnostics: []
	};
	return {
		detected: true,
		diagnostics: [{
			code: "GE001",
			severity: "error",
			file,
			message: "WebView glass-easel 需成对配置 componentFramework: \"glass-easel\" 与 glassEaselWebview: true。"
		}]
	};
}
function getMemberPropertyName(node) {
	if (!node || node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") return;
	if (!node.computed && node.property?.type === "Identifier") return node.property.name;
	if (node.property?.type === "StringLiteral") return node.property.value;
}
function isWxCreateSelectorQueryCall(node) {
	if (!node || node.type !== "CallExpression") return false;
	const callee = node.callee;
	return getMemberPropertyName(callee) === "createSelectorQuery" && callee.object?.type === "Identifier" && callee.object.name === "wx";
}
function analyzeScript(file, source) {
	const diagnostics = [];
	try {
		const ast = parseJsLike(source);
		traverse(ast, { CallExpression(callPath) {
			const node = callPath.node;
			const method = getMemberPropertyName(node.callee);
			if (method === "select" || method === "selectAll") {
				const selector = node.arguments?.[0];
				if (selector?.type === "StringLiteral" && /(?:^|[\s>+~,])[.#]\d/.test(selector.value)) diagnostics.push({
					code: "GE005",
					severity: "error",
					file,
					line: selector.loc?.start.line,
					column: selector.loc ? selector.loc.start.column + 1 : void 0,
					message: `SelectorQuery 选择器 ${JSON.stringify(selector.value)} 含数字开头的 id 或 class。`
				});
			}
			if (method === "in" && isWxCreateSelectorQueryCall(node.callee.object) && node.arguments?.[0]?.type === "ThisExpression") diagnostics.push({
				code: "GE006",
				severity: "warning",
				file,
				line: node.loc?.start.line,
				column: node.loc ? node.loc.start.column + 1 : void 0,
				message: "可将 wx.createSelectorQuery().in(this) 改为 this.createSelectorQuery(),减少兼容层开销。"
			});
		} });
	} catch {}
	return diagnostics;
}
function analyzeGlassEaselBundle(ctx, bundle) {
	const entries = Object.entries(bundle);
	const localDiagnostics = [];
	let detected = ctx.runtimeState.glassEasel.detected;
	for (const [bundleFileName, output] of entries) {
		const file = output.fileName || bundleFileName;
		if (!file.endsWith(".json")) continue;
		const result = analyzeJsonConfig(file, getOutputSource(output));
		detected ||= result.detected;
		localDiagnostics.push(...result.diagnostics);
	}
	ctx.runtimeState.glassEasel.detected = detected;
	if (!detected) return;
	for (const [sourceFile, token] of ctx.runtimeState.wxml.tokenMap) for (const finding of token.glassEaselFindings ?? []) {
		if (finding.code !== "GE002") continue;
		localDiagnostics.push({
			code: finding.code,
			severity: finding.severity,
			message: finding.message,
			file: ctx.configService.relativeAbsoluteSrcRoot(sourceFile),
			...offsetToLocation(token.code, finding.start),
			normalized: finding.normalized
		});
	}
	for (const [bundleFileName, output] of entries) {
		const file = output.fileName || bundleFileName;
		const source = getOutputSource(output);
		if (TEMPLATE_FILE_RE.test(file)) {
			const token = scanWxml(source, { platform: ctx.configService.platform });
			for (const finding of token.glassEaselFindings ?? []) localDiagnostics.push({
				code: finding.code,
				severity: finding.severity,
				message: finding.message,
				file,
				...offsetToLocation(source, finding.start),
				normalized: finding.normalized
			});
		} else if (output.type === "chunk") localDiagnostics.push(...analyzeScript(file, source));
	}
	for (const diagnostic of localDiagnostics) registerDiagnostic(ctx, diagnostic);
}
function createGlassEaselAnalyzeResult(ctx) {
	const diagnostics = Array.from(ctx.runtimeState.glassEasel.diagnostics.values()).sort((left, right) => left.file.localeCompare(right.file) || (left.line ?? 0) - (right.line ?? 0) || left.code.localeCompare(right.code));
	return {
		detected: ctx.runtimeState.glassEasel.detected,
		minimumBaseLibrary: "3.8.12",
		migrationGuide: MIGRATION_GUIDE,
		diagnostics,
		summary: {
			errors: diagnostics.filter((item) => item.severity === "error").length,
			warnings: diagnostics.filter((item) => item.severity === "warning").length
		}
	};
}
//#endregion
//#region src/i18n/config.ts
const IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
function normalizeName(value, fallback, field) {
	const resolved = value?.trim() || fallback;
	if (!IDENTIFIER_RE.test(resolved)) throw new Error(`weapp.i18n.${field} 必须是合法标识符,当前值为 \`${resolved}\`。`);
	return resolved;
}
function resolveWeappI18nConfig(config) {
	if (!config || typeof config !== "object") throw new Error("weapp.i18n 必须是配置对象。");
	const defaultLocale = config.defaultLocale?.trim();
	if (!defaultLocale) throw new Error("weapp.i18n.defaultLocale 为必填项。");
	const include = (Array.isArray(config.include) ? config.include : [config.include ?? "**/i18n/*.json"]).map((item) => item.trim()).filter(Boolean);
	if (!include.length) throw new Error("weapp.i18n.include 至少需要一个有效 glob。");
	return {
		defaultLocale,
		fallbackLocale: config.fallbackLocale?.trim() || defaultLocale,
		include,
		functionName: normalizeName(config.functionName, "t", "functionName"),
		moduleName: normalizeName(config.moduleName, "i18n", "moduleName")
	};
}
//#endregion
//#region src/i18n/template.ts
function resolveAssetSource(fileName, assetFileName) {
	const relative = path.posix.relative(path.posix.dirname(fileName), assetFileName);
	return relative.startsWith(".") ? relative : `./${relative}`;
}
function collectCallReplacements(expression, expressionOffset, options) {
	let ast;
	try {
		ast = parse$3(`(${expression})`, { sourceType: "module" });
	} catch {
		return [];
	}
	const calls = [];
	traverse(ast, { CallExpression(callPath) {
		const node = callPath.node;
		if (node.callee.type !== "Identifier" || node.callee.name !== options.functionName) return;
		const start = (node.start ?? 1) - 1;
		const end = (node.end ?? 1) - 1;
		calls.push({
			end,
			start
		});
	} });
	if (!calls.length) return [];
	const renderSegment = (start, end) => {
		const nestedCalls = calls.filter((call) => call.start >= start && call.end <= end).filter((call) => {
			return !calls.some((parent) => parent !== call && parent.start >= start && parent.end <= end && parent.start <= call.start && parent.end >= call.end);
		}).sort((left, right) => left.start - right.start);
		let cursor = start;
		let rendered = "";
		for (const call of nestedCalls) {
			rendered += expression.slice(cursor, call.start);
			const openParen = expression.slice(call.start, call.end).indexOf("(");
			const argsStart = call.start + openParen + 1;
			const args = openParen >= 0 ? renderSegment(argsStart, call.end - 1).trim() : "";
			rendered += `${options.moduleName}.t(${options.localeDataKey}${args ? `, ${args}` : ""})`;
			cursor = call.end;
		}
		return rendered + expression.slice(cursor, end);
	};
	return [{
		start: expressionOffset,
		end: expressionOffset + expression.length,
		value: renderSegment(0, expression.length)
	}];
}
function collectMustacheRanges(source, start, end) {
	const ranges = [];
	for (let cursor = start; cursor < end - 1;) {
		if (source[cursor] !== "{" || source[cursor + 1] !== "{") {
			cursor++;
			continue;
		}
		const expressionStart = cursor + 2;
		let expressionEnd = expressionStart;
		let braceDepth = 0;
		let escaped = false;
		let quote = "";
		for (; expressionEnd < end - 1; expressionEnd++) {
			const char = source[expressionEnd];
			if (quote) {
				if (escaped) escaped = false;
				else if (char === "\\") escaped = true;
				else if (char === quote) quote = "";
				continue;
			}
			if (char === "'" || char === "\"" || char === "`") quote = char;
			else if (char === "{") braceDepth++;
			else if (char === "}" && braceDepth > 0) braceDepth--;
			else if (char === "}" && source[expressionEnd + 1] === "}") {
				ranges.push({
					expressionEnd,
					expressionStart
				});
				cursor = expressionEnd + 2;
				break;
			}
		}
		if (expressionEnd >= end - 1) break;
	}
	return ranges;
}
function transformI18nTemplate(source, options) {
	const token = scanWxml(source, { platform: "weapp" });
	const replacements = [];
	for (const templateToken of token.templateTokens ?? []) for (const range of collectMustacheRanges(source, templateToken.start, templateToken.end)) {
		const expression = source.slice(range.expressionStart, range.expressionEnd);
		replacements.push(...collectCallReplacements(expression, range.expressionStart, options));
	}
	if (!replacements.length) return source;
	if (token.scriptModules?.some((scriptModule) => {
		return scriptModule.attrs.module === options.moduleName;
	})) throw new Error(`${options.fileName} 已存在 module=\"${options.moduleName}\" 的 WXS 模块,无法注入 i18n。`);
	const ms = new MagicString(source);
	for (const replacement of replacements.sort((left, right) => right.start - left.start)) ms.update(replacement.start, replacement.end, replacement.value);
	const src = resolveAssetSource(options.fileName, options.assetFileName);
	return `<wxs module="${options.moduleName}" src="${src}"/>\n${ms.toString()}`;
}
//#endregion
//#region src/plugins/i18n.ts
const TEMPLATE_MODULE_RE = /\.(?:vue|wxml)(?:\?|$)/;
function withPackageRoot(root, fileName) {
	const normalizedRoot = root.replace(/^\/+|\/+$/g, "");
	return normalizedRoot ? `${normalizedRoot}/${fileName}` : fileName;
}
function resolveCurrentPackageRoot(subPackageMeta) {
	return subPackageMeta?.subPackage.root?.replace(/^\/+|\/+$/g, "") ?? "";
}
function resolveOutputPackageRoot(ctx, fileName, subPackageMeta) {
	const currentRoot = resolveCurrentPackageRoot(subPackageMeta);
	if (currentRoot) return currentRoot;
	const normalized = toPosixPath(fileName).replace(/^\/+/, "");
	return [...ctx.scanService.subPackageMap.keys()].map((root) => root.replace(/^\/+|\/+$/g, "")).filter((root) => normalized === root || normalized.startsWith(`${root}/`)).sort((left, right) => right.length - left.length)[0] ?? "";
}
function resolveEmittedPackageRoots(ctx, subPackageMeta) {
	const currentRoot = resolveCurrentPackageRoot(subPackageMeta);
	if (currentRoot) return [currentRoot];
	return ["", ...[...ctx.scanService.subPackageMap.keys()].filter((root) => !ctx.scanService.independentSubPackageMap.has(root))];
}
async function loadI18nCatalog(ctx, config) {
	const root = ctx.configService.absoluteSrcRoot;
	const matcher = picomatch(config.include, { dot: false });
	const files = (await new fdir({
		includeDirs: false,
		pathSeparator: "/"
	}).withFullPaths().crawl(root).withPromise()).filter((file) => matcher(toPosixPath(path.relative(root, file)))).sort();
	if (!files.length) throw new Error(`weapp.i18n 未找到 locale 文件,include: ${config.include.join(", ")}。`);
	const inputs = [];
	for (const filePath of files) {
		let messages;
		try {
			messages = JSON.parse(await fs$1.readFile(filePath, "utf8"));
		} catch (error) {
			throw new Error(`无法解析 i18n 文件 \`${ctx.configService.relativeCwd(filePath)}\`:${String(error)}`);
		}
		inputs.push({
			filePath: ctx.configService.relativeCwd(filePath),
			locale: path.basename(filePath, path.extname(filePath)),
			messages
		});
	}
	return {
		catalog: compileI18nCatalog(inputs, config),
		files
	};
}
function matchesI18nLocaleFile(ctx, config, filePath) {
	const relativePath = toPosixPath(path.relative(ctx.configService.absoluteSrcRoot, filePath));
	return !relativePath.startsWith("../") && picomatch(config.include, { dot: false })(relativePath);
}
function transformI18nOutputTemplate(ctx, fileName, source, subPackageMeta) {
	const rawConfig = ctx.configService.weappViteConfig?.i18n;
	if (!rawConfig || ctx.configService.platform !== "weapp") return source;
	const config = resolveWeappI18nConfig(rawConfig);
	return transformI18nTemplate(source, {
		assetFileName: withPackageRoot(resolveOutputPackageRoot(ctx, fileName, subPackageMeta), WEAPP_I18N_WXS_FILE),
		fileName,
		functionName: config.functionName,
		localeDataKey: WEAPP_I18N_LOCALE_DATA_KEY,
		moduleName: config.moduleName
	});
}
function i18n(ctx, subPackageMeta) {
	const state = { files: [] };
	const resolvedId = `\0${WEAPP_I18N_VIRTUAL_MODULE_ID}:${resolveCurrentPackageRoot(subPackageMeta) || "main"}`;
	async function refreshCatalog(pluginContext) {
		if (!state.config) return;
		const loaded = await loadI18nCatalog(ctx, state.config);
		state.catalog = loaded.catalog;
		state.files = loaded.files;
		for (const file of state.files) pluginContext?.addWatchFile?.(file);
	}
	return [{
		name: "weapp-vite:i18n",
		enforce: "pre",
		async buildStart() {
			const rawConfig = ctx.configService.weappViteConfig?.i18n;
			if (!rawConfig) return;
			if (ctx.configService.platform !== "weapp") throw new Error("weapp.i18n v1 仅支持 platform = \"weapp\"。");
			state.config = resolveWeappI18nConfig(rawConfig);
			await refreshCatalog(this);
			this.emitFile({
				type: "chunk",
				id: WEAPP_I18N_PUBLIC_MODULE_ID,
				fileName: withPackageRoot(resolveCurrentPackageRoot(subPackageMeta), WEAPP_I18N_JS_FILE),
				preserveSignature: "exports-only"
			});
		},
		watchChange(id) {
			if (state.config && matchesI18nLocaleFile(ctx, state.config, id)) state.catalog = void 0;
		},
		async handleHotUpdate(hotContext) {
			if (!state.config || !matchesI18nLocaleFile(ctx, state.config, hotContext.file)) return;
			await refreshCatalog();
			const affectedModules = [];
			const runtimeModule = hotContext.server.moduleGraph.getModuleById(resolvedId);
			if (runtimeModule) {
				hotContext.server.moduleGraph.invalidateModule(runtimeModule);
				affectedModules.push(runtimeModule);
			}
			for (const module of hotContext.server.moduleGraph.idToModuleMap.values()) if (module.id && TEMPLATE_MODULE_RE.test(module.id)) {
				hotContext.server.moduleGraph.invalidateModule(module);
				affectedModules.push(module);
			}
			return affectedModules;
		},
		resolveId(id) {
			if (id === WEAPP_I18N_PUBLIC_MODULE_ID && ctx.configService.weappViteConfig?.i18n) return resolvedId;
		},
		load(id) {
			if (id !== resolvedId) return;
			if (!state.catalog) throw new Error("i18n runtime 在 locale catalog 初始化前被加载。");
			return generateI18nRuntimeSource(state.catalog);
		},
		generateBundle() {
			if (!state.catalog) return;
			const wxsSource = generateI18nWxsSource(state.catalog);
			const catalogSource = generateI18nCatalogModuleSource(state.catalog);
			const currentRoot = resolveCurrentPackageRoot(subPackageMeta);
			for (const root of resolveEmittedPackageRoots(ctx, subPackageMeta)) {
				this.emitFile({
					type: "asset",
					fileName: withPackageRoot(root, WEAPP_I18N_WXS_FILE),
					source: wxsSource
				});
				if (root !== currentRoot) this.emitFile({
					type: "asset",
					fileName: withPackageRoot(root, WEAPP_I18N_JS_FILE),
					source: `${catalogSource}// ${WEAPP_I18N_RUNTIME_MARKER}\n`
				});
			}
		}
	}];
}
//#endregion
//#region src/plugins/outputFinalizer/independent.ts
function toEmittedAsset(output) {
	if (output.type === "chunk") return {
		type: "asset",
		fileName: output.fileName,
		name: output.name,
		source: output.code
	};
	const name = output.names[0] ?? output.name;
	const originalFileName = output.originalFileNames[0] ?? output.originalFileName;
	return {
		type: "asset",
		fileName: output.fileName,
		source: output.source,
		...name ? { name } : {},
		...originalFileName ? { originalFileName } : {}
	};
}
function getBundleOutputs(output) {
	return Array.isArray(output.output) ? output.output : [];
}
async function flushIndependentOutputs(ctx, subPackageMeta, emitAsset) {
	if (subPackageMeta) return;
	const independentState = ctx.runtimeState?.build?.independent;
	if (!independentState) return;
	const pendingOutputs = independentState.pendingOutputs;
	if (pendingOutputs.length === 0) return;
	independentState.pendingOutputs = [];
	const outputs = await Promise.all(pendingOutputs);
	for (const output of outputs) for (const bundleOutput of getBundleOutputs(output)) emitAsset(toEmittedAsset(bundleOutput));
}
//#endregion
//#region src/plugins/outputFinalizer.ts
const PREPROCESSOR_STYLE_ASSET_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss|sss)$/i;
const TEMPLATE_ASSET_RE = /\.(?:wxml|axml|swan|ttml|jxml|qml|ksml|xhsml)$/i;
const TEMPLATE_STATIC_REWRITE_MARKERS = [
	"@",
	"<!--",
	"<wxs",
	"</wxs",
	"<sjs",
	"</sjs",
	".html",
	".wxs",
	".sjs",
	".wxml",
	".axml",
	".swan",
	".ttml",
	".jxml",
	".qml",
	".ksml",
	".xhsml",
	"import.meta.",
	"wx-if",
	"wx-for"
];
const TEMPLATE_DIRECTIVE_PREFIXES = getSupportedMiniProgramDirectivePrefixes();
const GRAPH_ONLY_OUTPUT_MARKERS = [WEAPP_VITE_LOGICAL_ENTRY_RESOLVED_PREFIX, WEAPP_VITE_SIDECAR_RESOLVED_PREFIX];
function parseGraphOnlyAssetModuleId(fileName) {
	for (const marker of GRAPH_ONLY_OUTPUT_MARKERS) {
		const markerIndex = fileName.indexOf(marker);
		if (markerIndex < 0) continue;
		const request = fileName.slice(markerIndex);
		const extension = path.extname(request);
		return `${extension ? request.slice(0, -extension.length) : request}.js`;
	}
}
function parseGraphOnlyAssetOwner(fileName) {
	const moduleId = parseGraphOnlyAssetModuleId(fileName);
	return moduleId ? parseLogicalEntryId(moduleId)?.sourceId ?? parseSidecarModuleId(moduleId)?.ownerId : void 0;
}
function normalizeGraphOnlyAssets(ctx, bundle, emitAsset) {
	for (const [bundleFileName, output] of Object.entries(bundle)) {
		if (output?.type !== "asset") continue;
		const fileName = output.fileName || bundleFileName;
		const moduleId = parseGraphOnlyAssetModuleId(fileName);
		const sidecar = moduleId ? parseSidecarModuleId(moduleId) : void 0;
		if (sidecar?.kind === "style" && isManagedTailwindcssEntry(ctx, sidecar.sourceId) && !hasManagedTailwindcssOutputMarker(output.source.toString())) {
			delete bundle[bundleFileName];
			continue;
		}
		const ownerId = parseGraphOnlyAssetOwner(fileName);
		if (!ownerId) continue;
		delete bundle[bundleFileName];
		const outputFileName = ctx.configService.relativeOutputPath(changeFileExtension(ownerId, ctx.configService.outputExtensions.wxss));
		if (!outputFileName) continue;
		const existingOutput = bundle[outputFileName];
		if (existingOutput?.type === "asset") {
			existingOutput.source = output.source;
			existingOutput.fileName = outputFileName;
			continue;
		}
		if (!existingOutput) emitAsset({
			type: "asset",
			fileName: outputFileName,
			source: output.source
		});
	}
}
function collectOutputFinalizerAssetEntries(bundle) {
	const preprocessorStyleAssets = [];
	const templateAssets = [];
	for (const [bundleFileName, output] of Object.entries(bundle)) {
		if (output?.type !== "asset") continue;
		const fileName = output.fileName || bundleFileName;
		if (PREPROCESSOR_STYLE_ASSET_RE.test(fileName)) preprocessorStyleAssets.push({
			bundleFileName,
			output
		});
		if (TEMPLATE_ASSET_RE.test(fileName)) templateAssets.push({
			bundleFileName,
			output
		});
	}
	return {
		preprocessorStyleAssets,
		templateAssets
	};
}
function outputSourceToString(output) {
	if (output.type === "chunk") return output.code;
	const source = output.source;
	return typeof source === "string" ? source : Buffer.from(source).toString("base64");
}
function mergePendingOwnerStyleSources(ctx, bundle) {
	const pending = consumePendingOwnerStyleSources(ctx);
	if (!pending) return;
	for (const [fileName, fragments] of pending) {
		const output = bundle[fileName] ?? Object.values(bundle).find((candidate) => candidate.type === "asset" && candidate.fileName === fileName);
		if (output?.type !== "asset") continue;
		const source = output.source.toString();
		const missing = fragments.filter((fragment) => !source.includes(fragment));
		if (!missing.length) continue;
		output.source = `${source.trimEnd()}\n${missing.join("\n")}\n`;
	}
}
function mayNeedTemplateNormalization(code, platform) {
	let lowerCode;
	const readLowerCode = () => {
		lowerCode ??= code.toLowerCase();
		return lowerCode;
	};
	const hasUppercase = /[A-Z]/.test(code);
	const { directivePrefix, eventBindingStyle, normalizeComponentTagName } = getWxmlPlatformTransformOptions(platform);
	if (normalizeComponentTagName && hasUppercase) return true;
	for (const prefix of TEMPLATE_DIRECTIVE_PREFIXES) if (prefix !== directivePrefix) {
		const marker = prefix === "s" ? "s-" : `${prefix}:`;
		if (code.includes(marker)) return true;
	}
	if (eventBindingStyle === "alipay" && (readLowerCode().includes("bind") || readLowerCode().includes("catch") || readLowerCode().includes("capture-") || readLowerCode().includes("mut-bind"))) return true;
	const normalizedCode = hasUppercase ? readLowerCode() : code;
	return TEMPLATE_STATIC_REWRITE_MARKERS.some((marker) => normalizedCode.includes(marker));
}
function normalizePreprocessorStyleAssetEntries(bundle, entries, styleExtension, emitAsset) {
	if (!styleExtension) return;
	for (const { bundleFileName, output } of entries) {
		const fileName = output.fileName || bundleFileName;
		const outputFileName = changeFileExtension(fileName, styleExtension);
		if (!outputFileName || outputFileName === fileName) continue;
		const existingOutput = bundle[outputFileName];
		delete bundle[bundleFileName];
		if (existingOutput?.type === "asset") {
			existingOutput.source = output.source;
			existingOutput.fileName = outputFileName;
			continue;
		}
		if (existingOutput) continue;
		output.fileName = outputFileName;
		const [name] = output.names ?? [];
		const [originalFileName] = output.originalFileNames ?? [];
		emitAsset({
			type: "asset",
			fileName: outputFileName,
			...name ? { name } : {},
			...originalFileName ? { originalFileName } : {},
			source: output.source
		});
	}
}
function normalizePreprocessorStyleAssets(bundle, styleExtension, emitAsset) {
	if (!styleExtension) return;
	normalizePreprocessorStyleAssetEntries(bundle, collectOutputFinalizerAssetEntries(bundle).preprocessorStyleAssets, styleExtension, emitAsset);
}
function normalizeTemplateAssetEntries(ctx, entries, subPackageMeta) {
	const { configService } = ctx;
	for (const { bundleFileName, output } of entries) {
		const source = output.source;
		const code = typeof source === "string" ? source : source instanceof Uint8Array ? Buffer.from(source).toString("utf8") : void 0;
		if (code === void 0) continue;
		let normalized = code;
		if (mayNeedTemplateNormalization(code, configService?.platform)) normalized = handleWxml(scanWxml(code, { platform: configService?.platform }), {
			scriptModuleExtension: configService?.outputExtensions?.wxs,
			scriptModuleTag: resolveScriptModuleTagName({
				platform: configService?.platform,
				scriptModuleExtension: configService?.outputExtensions?.wxs
			}),
			templateExtension: configService?.outputExtensions?.wxml
		}).code;
		const transformed = transformI18nOutputTemplate(ctx, output.fileName || bundleFileName, normalized, subPackageMeta);
		if (transformed !== code) output.source = transformed;
	}
}
function pruneUneventedDevHmrChunks(ctx, bundle) {
	const emittedChunkFileNames = ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
	if (!ctx.configService?.isDev || ctx.runtimeState?.build?.hmr?.profile?.event === void 0 || !emittedChunkFileNames?.size) return;
	for (const [fileName, output] of Object.entries(bundle)) if (output?.type === "chunk" && !emittedChunkFileNames.has(fileName) && !emittedChunkFileNames.has(output.fileName)) delete bundle[fileName];
}
function pruneUnchangedDevHmrOutputs(ctx, bundle, rewriteOptions, options) {
	const cache = ctx.runtimeState?.build?.output?.emittedSource;
	if (!ctx.configService?.isDev || !cache) return;
	const isHmrBuild = ctx.runtimeState?.build?.hmr?.profile?.event !== void 0;
	const emittedChunkFileNames = ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
	if (!options?.runtimeRewriteDone) {
		rewriteWevuInternalRuntimeImports(bundle, rewriteOptions);
		stabilizeWevuRuntimeChunkAccess(bundle);
	}
	for (const [fileName, output] of Object.entries(bundle)) {
		const shouldForceEmitCurrentHmrChunk = isHmrBuild && output.type === "chunk" && (emittedChunkFileNames?.has(fileName) === true || emittedChunkFileNames?.has(output.fileName) === true);
		if (isHmrBuild && output.type === "chunk" && emittedChunkFileNames?.size && !shouldForceEmitCurrentHmrChunk) {
			delete bundle[fileName];
			continue;
		}
		const source = outputSourceToString(output);
		if (isHmrBuild && !shouldForceEmitCurrentHmrChunk && cache.get(fileName) === source) {
			delete bundle[fileName];
			continue;
		}
		cache.set(fileName, source);
	}
}
function createOutputFinalizerPlugin(ctx, subPackageMeta) {
	const wevuRuntimeRewriteOptions = {
		get runtimeFileName() {
			return ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileName;
		},
		get runtimeFileNames() {
			return ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileNames;
		},
		isRuntimeFileNameAvailable(fileName) {
			return ctx.runtimeState?.build?.output?.emittedSource.has(fileName) === true;
		},
		onRuntimeFileName(fileName) {
			const outputState = ctx.runtimeState?.build?.output;
			if (outputState) outputState.wevuInternalRuntimeFileName = fileName;
		},
		onRuntimeModuleFileName(moduleId, fileName) {
			const outputState = ctx.runtimeState?.build?.output;
			if (outputState) {
				outputState.wevuInternalRuntimeFileNames ??= /* @__PURE__ */ new Map();
				outputState.wevuInternalRuntimeFileNames.set(moduleId, fileName);
			}
		}
	};
	return {
		name: "weapp-vite:output-finalizer",
		enforce: "post",
		generateBundle: {
			order: "post",
			async handler(_options, bundle) {
				const outputBundle = bundle;
				mergePendingOwnerStyleSources(ctx, outputBundle);
				rewriteWevuInternalRuntimeImports(bundle, wevuRuntimeRewriteOptions);
				stabilizeWevuRuntimeChunkAccess(bundle);
				restoreNativePageLayoutOutputs(ctx, outputBundle);
				normalizeGraphOnlyAssets(ctx, outputBundle, (asset) => this.emitFile(asset));
				const assetEntries = collectOutputFinalizerAssetEntries(outputBundle);
				if (ctx.configService.platform === "weapp") analyzeGlassEaselBundle(ctx, outputBundle);
				normalizePreprocessorStyleAssetEntries(outputBundle, assetEntries.preprocessorStyleAssets, ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
				normalizeTemplateAssetEntries(ctx, assetEntries.templateAssets, subPackageMeta);
				pruneUnchangedDevHmrOutputs(ctx, outputBundle, wevuRuntimeRewriteOptions, { runtimeRewriteDone: true });
				syncOutputChunkSourceMapAssets(outputBundle);
				await flushIndependentOutputs(ctx, subPackageMeta, (asset) => this.emitFile(asset));
			}
		}
	};
}
//#endregion
//#region src/plugins/core/lifecycle/transform/importMeta.ts
function hasOwn$2(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
function isImportMetaNode(node) {
	return node?.type === "MetaProperty" && node.meta?.type === "Identifier" && node.meta.name === "import" && node.property?.type === "Identifier" && node.property.name === "meta";
}
function isImportMetaMemberAccess(node, propertyName) {
	if (!node || node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") return false;
	if (!isImportMetaNode(node.object)) return false;
	if (!node.computed) return node.property?.type === "Identifier" && node.property.name === propertyName;
	return node.property?.type === "StringLiteral" && node.property.value === propertyName;
}
function getImportMetaEnvPropertyName(node) {
	if (!node || node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") return;
	if (!isImportMetaMemberAccess(node.object, "env")) return;
	if (!node.computed && node.property?.type === "Identifier") return node.property.name;
	if (node.property?.type === "StringLiteral") return node.property.value;
}
function wrapInlineExpression(expression) {
	const trimmed = expression.trim();
	return trimmed.startsWith("{") ? `(${trimmed})` : trimmed;
}
function createSerializedEnvExpression(envObject) {
	return `JSON.parse(${JSON.stringify(JSON.stringify(envObject))})`;
}
function createCachedImportMetaEnvExpression(rawExpression, envObject) {
	const trimmed = rawExpression.trim();
	const runtimeExpression = trimmed.startsWith("{") || trimmed.startsWith("JSON.parse(") ? createSerializedEnvExpression(envObject) : wrapInlineExpression(trimmed);
	const globalRef = `globalThis[${JSON.stringify(WEAPP_VITE_IMPORT_META_ENV_KEY)}]`;
	return `(${globalRef}||(${globalRef}=${runtimeExpression}))`;
}
function toInlineLiteral(value) {
	if (value === void 0) return "undefined";
	if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value) || typeof value === "object") return JSON.stringify(value);
	return "undefined";
}
function createImportMetaObjectExpression(values, envExpression) {
	return `({"filename":${JSON.stringify(values.filename)},"url":${JSON.stringify(values.url)},"dirname":${JSON.stringify(values.dirname)},"env":${wrapInlineExpression(envExpression)}})`;
}
function resolveNodeRange(node) {
	return typeof node?.start === "number" && typeof node?.end === "number" ? {
		start: node.start,
		end: node.end
	} : void 0;
}
function intersectsReplacement(replacements, start, end) {
	return replacements.some((replacement) => !(end <= replacement.start || start >= replacement.end));
}
function replaceImportMetaAccess(code, options) {
	if (!code.includes("import.meta")) return code;
	const values = createStaticImportMetaValues(options);
	const envExpression = createCachedImportMetaEnvExpression(resolveImportMetaEnvExpression(options.importMetaDefineRegistry?.defineEntries, values.env), values.env);
	const importMetaObjectExpression = createImportMetaObjectExpression(values, envExpression);
	const ast = parseJsLike(code);
	const replacements = [];
	function addReplacement(node, value) {
		const range = resolveNodeRange(node);
		if (!range || intersectsReplacement(replacements, range.start, range.end)) return;
		replacements.push({
			start: range.start,
			end: range.end,
			value
		});
	}
	traverse(ast, {
		MemberExpression(path) {
			const envPropertyName = getImportMetaEnvPropertyName(path.node);
			if (envPropertyName) {
				const envValue = hasOwn$2(values.envAccess, envPropertyName) ? values.envAccess[envPropertyName] : void 0;
				addReplacement(path.node, toInlineLiteral(envValue));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "env")) {
				addReplacement(path.node, wrapInlineExpression(envExpression));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "url")) {
				addReplacement(path.node, JSON.stringify(values.url));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "filename")) {
				addReplacement(path.node, JSON.stringify(values.filename));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "dirname")) addReplacement(path.node, JSON.stringify(values.dirname));
		},
		OptionalMemberExpression(path) {
			const envPropertyName = getImportMetaEnvPropertyName(path.node);
			if (envPropertyName) {
				const envValue = hasOwn$2(values.envAccess, envPropertyName) ? values.envAccess[envPropertyName] : void 0;
				addReplacement(path.node, toInlineLiteral(envValue));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "env")) {
				addReplacement(path.node, wrapInlineExpression(envExpression));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "url")) {
				addReplacement(path.node, JSON.stringify(values.url));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "filename")) {
				addReplacement(path.node, JSON.stringify(values.filename));
				return;
			}
			if (isImportMetaMemberAccess(path.node, "dirname")) addReplacement(path.node, JSON.stringify(values.dirname));
		},
		MetaProperty(path) {
			const parent = path.parent;
			if ((parent?.type === "MemberExpression" || parent?.type === "OptionalMemberExpression") && parent.object === path.node) return;
			if (!isImportMetaNode(path.node)) return;
			addReplacement(path.node, importMetaObjectExpression);
		}
	});
	if (replacements.length === 0) return code;
	const ms = new MagicString(code);
	for (const replacement of replacements.sort((left, right) => left.start - right.start)) ms.update(replacement.start, replacement.end, replacement.value);
	return ms.toString();
}
function replaceImportMetaAccessInSfc(source, options) {
	if (!source.includes("import.meta")) return source;
	const { descriptor, errors } = parse$1(source, {
		filename: "import-meta.vue",
		ignoreEmpty: false
	});
	if (errors.length > 0) return source;
	const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => {
		return Boolean(block && !block.src);
	});
	if (blocks.length === 0) return source;
	const ms = new MagicString(source);
	let mutated = false;
	for (const block of blocks) {
		const nextContent = replaceImportMetaAccess(block.content, options);
		if (nextContent === block.content) continue;
		ms.update(block.loc.start.offset, block.loc.end.offset, nextContent);
		mutated = true;
	}
	return mutated ? ms.toString() : source;
}
//#endregion
//#region src/plugins/core/lifecycle/emit/rewrite/literals.ts
const SCRIPT_ENTRY_CANDIDATES = [
	"index.js",
	"index.mjs",
	"index.cjs"
];
const SCRIPT_FILE_EXTENSIONS = [
	".js",
	".mjs",
	".cjs"
];
const SCRIPT_FILE_RE = /\.[cm]?js$/i;
const resolvePackageJson = createRequire(import.meta.url);
function resolveInstalledPackageEntryRoot(importee, basedir) {
	const parsed = parseNpmPackageSpecifier(importee);
	if (!parsed) return;
	try {
		const packageJsonPath = resolvePackageJson.resolve(`${parsed.packageName}/package.json`, { paths: basedir ? [basedir] : void 0 });
		const packageRoot = path.dirname(packageJsonPath);
		const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
		const miniprogramRoot = typeof packageJson.miniprogram === "string" && packageJson.miniprogram ? packageJson.miniprogram : void 0;
		return {
			...parsed,
			entryRoot: miniprogramRoot ? path.resolve(packageRoot, miniprogramRoot) : packageRoot
		};
	} catch {
		return;
	}
}
function normalizeWeappLocalNpmImport(importee, basedir) {
	const normalized = normalizeNpmImportLookupPath(importee);
	const segments = normalized.split("/").filter(Boolean);
	if (segments.length === 1 || segments.length === 2 && normalized.startsWith("@")) return `${normalized}/index`;
	if (SCRIPT_FILE_RE.test(normalized)) return normalized;
	const resolved = resolveInstalledPackageEntryRoot(normalized, basedir);
	if (!resolved?.subPath) return normalized;
	const targetPath = path.resolve(resolved.entryRoot, resolved.subPath);
	if (SCRIPT_FILE_EXTENSIONS.some((ext) => existsSync(`${targetPath}${ext}`))) return normalized;
	if (SCRIPT_ENTRY_CANDIDATES.some((candidate) => existsSync(path.resolve(targetPath, candidate)))) return `${normalized}/index`;
	return normalized;
}
function getRequireImportLiteral(node) {
	if (!node) return null;
	if (node.type === "StringLiteral" || node.type === "Literal") return typeof node.value === "string" ? node.value : null;
	if (node.type === "TemplateLiteral" && node.expressions?.length === 0 && node.quasis?.length === 1) return node.quasis[0]?.value?.cooked ?? null;
	return null;
}
function getStaticStringLiteral(node) {
	return getRequireImportLiteral(node);
}
function normalizeRelativeChunkImport(fileName, importee) {
	return toPosixPath(path.normalize(path.join(path.dirname(fileName), importee)));
}
//#endregion
//#region src/utils/weapi.ts
function getWeapiGlobalRootCandidateItems() {
	return [
		`(typeof globalThis !== 'undefined' && globalThis)`,
		`(typeof self !== 'undefined' && self)`,
		`(typeof window !== 'undefined' && window)`,
		`(typeof global !== 'undefined' && global)`
	];
}
function getWeapiGlobalHostCandidateItems() {
	return [...getWeapiGlobalRootCandidateItems(), ...getMiniProgramGlobalKeys().map((key) => `(typeof ${key} !== 'undefined' && ${key})`)];
}
function createUniqueCandidatesExpression(items) {
	return `([${items.join(",")}].filter(Boolean).filter((item,index,list)=>list.indexOf(item)===index))`;
}
function createGlobalRootCandidatesExpression() {
	return createUniqueCandidatesExpression(getWeapiGlobalRootCandidateItems());
}
function createGlobalHostCandidatesExpression() {
	return createUniqueCandidatesExpression(getWeapiGlobalHostCandidateItems());
}
function createNativeApiFallbackExpression() {
	return createMiniProgramTopLevelResolveExpression({ globalKeys: getMiniProgramGlobalKeys() });
}
function createWeapiHostCandidatesExpression() {
	return createGlobalRootCandidatesExpression();
}
function createWeapiAccessExpression(globalName) {
	const globalKey = JSON.stringify(globalName);
	return `((${createGlobalHostCandidatesExpression()}.map(item=>item&&item[${globalKey}]).find(Boolean)) || ${createNativeApiFallbackExpression()})`;
}
//#endregion
//#region src/plugins/core/lifecycle/platformApiRewrite.ts
function createMiniProgramPlatformApiRewrite(code, globalName, _options) {
	const injectedApiIdentifier = WEAPP_VITE_INJECTED_API_IDENTIFIER;
	try {
		const ast = parseJsLike(code);
		const magicString = new MagicString(code);
		let mutated = false;
		const rewritePath = (path) => {
			const object = path.node?.object;
			if (!object || object.type !== "Identifier") return;
			const identifierName = object.name;
			if (!platformApiIdentifiers.has(identifierName)) return;
			if (path.scope?.hasBinding?.(identifierName)) return;
			if (typeof object.start !== "number" || typeof object.end !== "number" || object.start < 0 || object.end < object.start) return;
			magicString.update(object.start, object.end, injectedApiIdentifier);
			mutated = true;
		};
		traverse(ast, {
			MemberExpression: rewritePath,
			OptionalMemberExpression: rewritePath
		});
		if (mutated) {
			const aliasCode = `var ${injectedApiIdentifier} = ${createWeapiAccessExpression(globalName)};`;
			magicString.prepend(`${aliasCode}\n`);
			return magicString;
		}
	} catch {}
}
function rewriteMiniProgramPlatformApiAccess(code, globalName, options) {
	return createMiniProgramPlatformApiRewrite(code, globalName, options)?.toString() ?? code;
}
//#endregion
//#region src/plugins/core/lifecycle/emit/rewrite/platform.ts
function mayNeedChunkScriptAnalysis(code) {
	if (code.includes("require")) return true;
	for (const identifier of platformApiIdentifiers) if (code.includes(identifier)) return true;
	return false;
}
function rememberChunkScriptAnalysis(chunk, analysis, options) {
	options?.cache?.set(chunk, {
		analysis,
		code: chunk.code
	});
}
function getChunkScriptAnalysis(chunk, options) {
	const cached = options?.cache?.get(chunk);
	if (cached?.code === chunk.code) return cached.analysis;
	const analysis = mayNeedChunkScriptAnalysis(chunk.code) ? analyzeScript$1(chunk.code, { engine: options?.astEngine }) : {
		hasPlatformApiAccess: false,
		hasStaticRequireLiteral: false
	};
	rememberChunkScriptAnalysis(chunk, analysis, options);
	return analysis;
}
function warmupBundleScriptAnalysis(bundle, options) {
	const cache = options?.cache;
	if (!cache) return;
	const chunks = [];
	const inputs = [];
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (cache.get(chunk)?.code === chunk.code) continue;
		if (!mayNeedChunkScriptAnalysis(chunk.code)) {
			rememberChunkScriptAnalysis(chunk, {
				hasPlatformApiAccess: false,
				hasStaticRequireLiteral: false
			}, options);
			continue;
		}
		chunks.push(chunk);
		inputs.push({
			code: chunk.code,
			filename: chunk.fileName
		});
	}
	if (inputs.length === 0) return;
	const analyses = analyzeScripts(inputs, { engine: options.astEngine });
	for (const [index, analysis] of analyses.entries()) {
		const chunk = chunks[index];
		if (!chunk) continue;
		rememberChunkScriptAnalysis(chunk, analysis, options);
	}
}
function normalizeNpmImportByPlatform(platform, importee, dependencies, mode) {
	return normalizeNpmImportPathByPlatform(importee, {
		platform,
		dependencies,
		alipayNpmMode: mode
	});
}
function createPlatformNpmImportRewrite(platform, code, dependencies, mode, options) {
	if (!(options?.analysis?.hasStaticRequireLiteral ?? mayContainStaticRequireLiteral(code, { engine: options?.astEngine }))) return;
	try {
		const ast = parseJsLike(code);
		const magicString = new MagicString(code);
		let mutated = false;
		traverse(ast, { CallExpression(path) {
			const callee = path.node?.callee;
			if (!callee || callee.type !== "Identifier" || callee.name !== "require") return;
			if (path.scope?.hasBinding?.("require")) return;
			const args = path.node.arguments;
			if (!Array.isArray(args) || args.length === 0) return;
			const firstArg = args[0];
			const currentValue = getRequireImportLiteral(firstArg);
			if (typeof currentValue !== "string") return;
			const nextValue = normalizeNpmImportByPlatform(platform, currentValue, dependencies, mode);
			if (nextValue === currentValue) return;
			if (typeof firstArg.start !== "number" || typeof firstArg.end !== "number" || firstArg.start < 0 || firstArg.end < firstArg.start) return;
			magicString.update(firstArg.start, firstArg.end, JSON.stringify(nextValue));
			mutated = true;
		} });
		if (mutated) return magicString;
	} catch {}
}
function rewriteBundleNpmImportsByPlatform(platform, bundle, dependencies, mode, options) {
	warmupBundleScriptAnalysis(bundle, {
		astEngine: options?.astEngine,
		cache: options?.analysisCache
	});
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		const analysis = getChunkScriptAnalysis(chunk, {
			astEngine: options?.astEngine,
			cache: options?.analysisCache
		});
		const magicString = createPlatformNpmImportRewrite(platform, chunk.code, dependencies, mode, {
			...options,
			analysis
		});
		if (!magicString) continue;
		applyMagicStringChunkRewrite(chunk, magicString);
		rememberChunkScriptAnalysis(chunk, analysis, { cache: options?.analysisCache });
	}
}
function rewriteBundlePlatformApi(bundle, globalName, options) {
	warmupBundleScriptAnalysis(bundle, {
		astEngine: options?.astEngine,
		cache: options?.analysisCache
	});
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		const analysis = getChunkScriptAnalysis(chunk, {
			astEngine: options?.astEngine,
			cache: options?.analysisCache
		});
		if (analysis && !analysis.hasPlatformApiAccess) continue;
		const magicString = createMiniProgramPlatformApiRewrite(chunk.code, globalName);
		if (!magicString) continue;
		applyMagicStringChunkRewrite(chunk, magicString);
	}
}
function rewriteBundleDynamicGlobalResolution(bundle) {
	const applyPatternRewrite = (chunk, expression) => {
		expression.lastIndex = 0;
		const magicString = new MagicString(chunk.code);
		for (const match of chunk.code.matchAll(expression)) if (typeof match.index === "number") magicString.update(match.index, match.index + match[0].length, "globalThis");
		applyMagicStringChunkRewrite(chunk, magicString);
	};
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (!(chunk.code.includes("Function(") && chunk.code.includes("return this")) && !chunk.code.includes("typeof self<")) continue;
		const hasDynamicGlobalResolution = DYNAMIC_GLOBAL_RESOLUTION_RE.test(chunk.code);
		DYNAMIC_GLOBAL_RESOLUTION_RE.lastIndex = 0;
		if (hasDynamicGlobalResolution) applyPatternRewrite(chunk, DYNAMIC_GLOBAL_RESOLUTION_RE);
		const hasBrowserGlobalHostTernary = BROWSER_GLOBAL_HOST_TERNARY_RE.test(chunk.code);
		BROWSER_GLOBAL_HOST_TERNARY_RE.lastIndex = 0;
		if (hasBrowserGlobalHostTernary) applyPatternRewrite(chunk, BROWSER_GLOBAL_HOST_TERNARY_RE);
	}
}
function matchesSubPackageDependency(dependencies, importee, fallbackDependencies) {
	const normalized = normalizeNpmImportLookupPath(importee);
	if (Array.isArray(dependencies) && dependencies.length > 0) {
		const dependencyId = resolveNpmDependencyId(normalized);
		return dependencies.some((pattern) => {
			if (typeof pattern === "string") return dependencyId === pattern || normalized === pattern || normalized.startsWith(`${pattern}/`);
			pattern.lastIndex = 0;
			if (pattern.test(dependencyId)) return true;
			pattern.lastIndex = 0;
			return pattern.test(normalized);
		});
	}
	return hasNpmDependencyPrefix(fallbackDependencies, normalized);
}
//#endregion
//#region src/plugins/core/lifecycle/emit/rewrite/localRoot.ts
function isRelativeMiniprogramNpmImport(importee) {
	return importee === "miniprogram_npm" || importee.startsWith("./miniprogram_npm/") || importee.startsWith("../miniprogram_npm/") || importee.includes("/miniprogram_npm/");
}
function isToEsmCall(node) {
	const callee = node?.callee;
	if (!callee) return false;
	if (callee.type === "Identifier") return callee.name === "__toESM";
	return callee.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier" && callee.property.name === "__toESM";
}
function isNumericOneLiteral(node) {
	return (node?.type === "NumericLiteral" || node?.type === "Literal") && node.value === 1;
}
function hasNodeRange(node) {
	return Number.isInteger(node?.start) && Number.isInteger(node?.end) && node.start >= 0 && node.end >= node.start;
}
function findPreviousCommaIndex(code, start) {
	for (let index = start - 1; index >= 0; index--) {
		const char = code[index];
		if (char === ",") return index;
		if (!/\s/.test(char)) return start;
	}
	return start;
}
function getLocalizedBindingNameFromExpression(node, localizedRequireBindings) {
	if (!node) return;
	if (node.type === "Identifier" && localizedRequireBindings.has(node.name)) return node.name;
	if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require") {
		const importee = getRequireImportLiteral(node.arguments?.[0]);
		if (typeof importee === "string" && isRelativeMiniprogramNpmImport(importee)) return importee;
	}
}
function toRelativeRuntimeNpmImport(fileName, root, importee, basedir) {
	const normalized = normalizeWeappLocalNpmImport(importee, basedir);
	const target = root ? `${root}/miniprogram_npm/${normalized}` : `miniprogram_npm/${normalized}`;
	const relative = toPosixPath(path.relative(path.dirname(fileName), target));
	return relative.startsWith(".") ? relative : `./${relative}`;
}
function rewriteChunkNpmImportsToLocalRoot(chunk, root, dependencyPatterns, dependencies, options) {
	const analysis = getChunkScriptAnalysis(chunk, {
		astEngine: options?.astEngine,
		cache: options?.analysisCache
	});
	if (!analysis.hasStaticRequireLiteral) return;
	try {
		const ast = parseJsLike(chunk.code);
		const magicString = new MagicString(chunk.code);
		let mutated = false;
		const localizedRequireBindings = /* @__PURE__ */ new Set();
		traverse(ast, {
			VariableDeclarator(path) {
				const id = path.node?.id;
				const init = path.node?.init;
				if (!id || id.type !== "Identifier") return;
				if (!init || init.type !== "CallExpression" && init.type !== "Identifier") return;
				if (path.scope?.hasBinding?.("require")) return;
				if (getLocalizedBindingNameFromExpression(init, localizedRequireBindings)) localizedRequireBindings.add(id.name);
			},
			AssignmentExpression(path) {
				const left = path.node?.left;
				const right = path.node?.right;
				if (!left || left.type !== "Identifier") return;
				if (!right || right.type !== "CallExpression" && right.type !== "Identifier") return;
				if (path.scope?.hasBinding?.("require")) return;
				if (getLocalizedBindingNameFromExpression(right, localizedRequireBindings)) localizedRequireBindings.add(left.name);
			},
			CallExpression(path) {
				const callee = path.node?.callee;
				if (callee?.type === "Identifier" && callee.name === "require") {
					if (path.scope?.hasBinding?.("require")) return;
					const args = path.node.arguments;
					if (!Array.isArray(args) || args.length === 0) return;
					const firstArg = args[0];
					const currentValue = getRequireImportLiteral(firstArg);
					if (typeof currentValue !== "string" || !matchesSubPackageDependency(dependencyPatterns, currentValue, dependencies)) return;
					const nextValue = toRelativeRuntimeNpmImport(chunk.fileName, root, currentValue, options?.basedir);
					if (nextValue === currentValue) return;
					if (!hasNodeRange(firstArg)) return;
					magicString.update(firstArg.start, firstArg.end, JSON.stringify(nextValue));
					if (isRelativeMiniprogramNpmImport(nextValue) && path.parentPath?.node?.type === "VariableDeclarator" && path.parentPath.node.id?.type === "Identifier") localizedRequireBindings.add(path.parentPath.node.id.name);
					if (isRelativeMiniprogramNpmImport(nextValue) && path.parentPath?.node?.type === "AssignmentExpression" && path.parentPath.node.left?.type === "Identifier") localizedRequireBindings.add(path.parentPath.node.left.name);
					mutated = true;
					return;
				}
				if (!isToEsmCall(path.node)) return;
				const args = path.node.arguments;
				if (!Array.isArray(args) || args.length < 2 || !isNumericOneLiteral(args[1])) return;
				const firstArg = args[0];
				if (!Boolean(getLocalizedBindingNameFromExpression(firstArg, localizedRequireBindings))) return;
				const secondArg = args[1];
				if (!hasNodeRange(firstArg) || !hasNodeRange(secondArg)) return;
				magicString.remove(findPreviousCommaIndex(chunk.code, secondArg.start), secondArg.end);
				mutated = true;
			}
		});
		if (mutated) {
			applyMagicStringChunkRewrite(chunk, magicString);
			rememberChunkScriptAnalysis(chunk, analysis, { cache: options?.analysisCache });
		}
	} catch {}
}
function rewriteJsonNpmImportsToLocalRoot(bundle, root, dependencyPatterns, dependencies, basedir, options) {
	for (const output of Object.values(bundle)) {
		if (output?.type !== "asset" || typeof output.fileName !== "string" || !output.fileName.endsWith(".json")) continue;
		if (options?.excludeRoots?.some((excludeRoot) => output.fileName === excludeRoot || output.fileName.startsWith(`${excludeRoot}/`))) continue;
		if (root && (output.fileName === `${root}.json` || !output.fileName.startsWith(`${root}/`))) continue;
		const source = typeof output.source === "string" ? output.source : output.source?.toString();
		if (!source) continue;
		try {
			const parsed = JSON.parse(source);
			if (!parsed || typeof parsed !== "object" || !parsed.usingComponents || typeof parsed.usingComponents !== "object" || Array.isArray(parsed.usingComponents)) continue;
			let mutated = false;
			for (const [componentName, importee] of Object.entries(parsed.usingComponents)) {
				if (typeof importee !== "string" || !matchesSubPackageDependency(dependencyPatterns, importee, dependencies)) continue;
				parsed.usingComponents[componentName] = toRelativeRuntimeNpmImport(output.fileName, root, importee, basedir);
				mutated = true;
			}
			if (mutated) output.source = `${JSON.stringify(parsed, null, 2)}\n`;
		} catch {}
	}
}
function rewriteJsonAssetNpmImportsToLocalRoot(output, root, dependencyPatterns, dependencies, basedir) {
	if (output?.type !== "asset" || typeof output.fileName !== "string" || !output.fileName.endsWith(".json")) return;
	const source = typeof output.source === "string" ? output.source : output.source?.toString();
	if (!source) return;
	try {
		const parsed = JSON.parse(source);
		if (!parsed || typeof parsed !== "object" || !parsed.usingComponents || typeof parsed.usingComponents !== "object" || Array.isArray(parsed.usingComponents)) return;
		let mutated = false;
		for (const [componentName, importee] of Object.entries(parsed.usingComponents)) {
			if (typeof importee !== "string" || !matchesSubPackageDependency(dependencyPatterns, importee, dependencies)) continue;
			parsed.usingComponents[componentName] = toRelativeRuntimeNpmImport(output.fileName, root, importee, basedir);
			mutated = true;
		}
		if (mutated) output.source = `${JSON.stringify(parsed, null, 2)}\n`;
	} catch {}
}
function matchesRootFile(fileName, root) {
	return fileName.startsWith(`${root}/`);
}
function createLocalRootRewriteTargetResolver(localSubPackages) {
	const orderedLocalSubPackages = localSubPackages.length > 1 ? [...localSubPackages].sort((a, b) => b.root.length - a.root.length) : localSubPackages;
	const cache = /* @__PURE__ */ new Map();
	return (fileName) => {
		if (cache.has(fileName)) return cache.get(fileName);
		const matched = orderedLocalSubPackages.find((meta) => meta.root && matchesRootFile(fileName, meta.root));
		cache.set(fileName, matched);
		return matched;
	};
}
function rewriteJsonNpmImportsToLocalRoots(bundle, dependencies, resolveLocalRootRewriteTarget, basedir) {
	for (const output of Object.values(bundle)) {
		if (output?.type !== "asset" || typeof output.fileName !== "string" || !output.fileName.endsWith(".json")) continue;
		const subPackageTarget = resolveLocalRootRewriteTarget(output.fileName);
		if (subPackageTarget) {
			rewriteJsonAssetNpmImportsToLocalRoot(output, subPackageTarget.root, subPackageTarget.dependencies, dependencies, basedir);
			continue;
		}
		rewriteJsonAssetNpmImportsToLocalRoot(output, "", void 0, dependencies, basedir);
	}
}
function rewriteBundleNpmImportsToLocalRoots(bundle, dependencies, localSubPackages, options) {
	const resolveLocalRootRewriteTarget = createLocalRootRewriteTargetResolver(localSubPackages);
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		const subPackageTarget = resolveLocalRootRewriteTarget(chunk.fileName);
		if (subPackageTarget) {
			rewriteChunkNpmImportsToLocalRoot(chunk, subPackageTarget.root, subPackageTarget.dependencies, dependencies, options);
			continue;
		}
		rewriteChunkNpmImportsToLocalRoot(chunk, "", void 0, dependencies, options);
	}
	rewriteJsonNpmImportsToLocalRoots(bundle, dependencies, resolveLocalRootRewriteTarget, options?.basedir);
}
//#endregion
//#region src/plugins/core/lifecycle/emit/requestGlobals.ts
const REQUEST_GLOBAL_REQUIRE_CALL_RE = /require\((`([^`]+)`|'([^']+)'|"([^"]+)")\)/g;
const REQUEST_GLOBAL_APP_MODULE_KEY_PREFIX = "__weappViteRequestGlobalsModule:";
function resolveChunkRequestGlobalsTargets(code, targets, mode) {
	return mode === "auto" ? resolveAutoRequestGlobalsTargets(code, targets) : targets;
}
function resolvePreludeRequestGlobalsTargets(code, targets, mode) {
	return mode === "auto" ? targets : resolveChunkRequestGlobalsTargets(code, targets, mode);
}
function collectTopLevelDeclaredIdentifiers(code) {
	const identifiers = /* @__PURE__ */ new Set();
	try {
		const body = parseJsLike(code)?.program?.body;
		if (!Array.isArray(body)) return identifiers;
		for (const statement of body) {
			if ((statement?.type === "FunctionDeclaration" || statement?.type === "ClassDeclaration") && statement.id?.type === "Identifier") identifiers.add(statement.id.name);
			if (statement?.type !== "VariableDeclaration") continue;
			for (const declaration of statement.declarations ?? []) if (declaration?.id?.type === "Identifier") identifiers.add(declaration.id.name);
		}
	} catch {
		return identifiers;
	}
	return identifiers;
}
function resolveRequestGlobalsInstallerName(code) {
	const installerMatch = code.match(REQUEST_GLOBAL_INSTALLER_RE);
	if (installerMatch?.[1]) return installerMatch[1];
	try {
		const ast = parseJsLike(code);
		let installerName = null;
		const isInstallerFunctionNode = (node) => {
			if (!node) return false;
			if (Array.isArray(node.params) && node.params.length > 1) return false;
			const functionCode = generate$1(node).code;
			return FULL_REQUEST_GLOBAL_TARGETS.every((target) => functionCode.includes(target));
		};
		traverse(ast, {
			FunctionDeclaration(path) {
				if (installerName || !path.node?.id?.name) return;
				if (isInstallerFunctionNode(path.node)) installerName = path.node.id.name;
			},
			VariableDeclarator(path) {
				if (installerName || path.node?.id?.type !== "Identifier") return;
				const init = path.node.init;
				if (!init || init.type !== "FunctionExpression" && init.type !== "ArrowFunctionExpression") return;
				if (isInstallerFunctionNode(init)) installerName = path.node.id.name;
			}
		});
		return installerName;
	} catch {
		return null;
	}
}
function resolveRequestGlobalsExportName(code) {
	const installerName = resolveRequestGlobalsInstallerName(code);
	if (!installerName) return null;
	for (const match of code.matchAll(REQUEST_GLOBAL_EXPORT_RE)) {
		const candidateExportName = match[1] ?? match[2] ?? match[3];
		const returnedIdentifier = match[4];
		if (candidateExportName && returnedIdentifier === installerName) return candidateExportName;
	}
	try {
		const ast = parseJsLike(code);
		let exportName = null;
		traverse(ast, { CallExpression(path) {
			if (exportName) return;
			const callee = path.node?.callee;
			if (!callee || callee.type !== "MemberExpression" || callee.object?.type !== "Identifier" || callee.object.name !== "Object" || callee.property?.type !== "Identifier" || callee.property.name !== "defineProperty") return;
			const args = path.node.arguments;
			if (!Array.isArray(args) || args.length < 3) return;
			if (args[0]?.type !== "Identifier" || args[0].name !== "exports") return;
			const candidateExportName = getStaticStringLiteral(args[1]);
			if (!candidateExportName || args[2]?.type !== "ObjectExpression") return;
			const getterProperty = args[2].properties.find((property) => {
				return property?.type === "ObjectProperty" && property.key?.type === "Identifier" && property.key.name === "get" || property?.type === "ObjectMethod" && property.key?.type === "Identifier" && property.key.name === "get";
			});
			const getterValue = getterProperty?.type === "ObjectMethod" ? getterProperty : getterProperty?.value;
			if (!getterValue) return;
			const getterBody = getterValue.body;
			const returnIdentifier = getterBody?.type === "BlockStatement" ? getterBody.body.find((statement) => statement?.type === "ReturnStatement")?.argument : getterBody;
			if (returnIdentifier?.type === "Identifier" && returnIdentifier.name === installerName) exportName = candidateExportName;
		} });
		return exportName;
	} catch {
		return null;
	}
}
function injectRequestGlobalsBundleRuntime(bundle, targets, mode, networkDefaults) {
	const installerChunks = /* @__PURE__ */ new Map();
	if (targets.length === 0) return installerChunks;
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (chunk.code.includes(REQUEST_GLOBAL_BUNDLE_MARKER)) continue;
		const installerName = resolveRequestGlobalsInstallerName(chunk.code);
		const exportName = resolveRequestGlobalsExportName(chunk.code);
		if (!installerName) continue;
		const resolvedExportName = exportName ?? REQUEST_GLOBAL_SYNTHETIC_EXPORT_NAME;
		installerChunks.set(toPosixPath(chunk.fileName), resolvedExportName);
		const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
		if (chunkTargets.length === 0) continue;
		const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
		if (bindingTargets.length === 0) continue;
		const topLevelDeclaredIdentifiers = collectTopLevelDeclaredIdentifiers(chunk.code);
		const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets, bindingTargets.filter((target) => !topLevelDeclaredIdentifiers.has(target)));
		const syntheticExportCode = exportName ? "" : `Object.defineProperty(exports,${JSON.stringify(REQUEST_GLOBAL_SYNTHETIC_EXPORT_NAME)},{enumerable:false,get:function(){return ${installerName}}});`;
		const installerOptionsCode = createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults);
		const runtimeBindingCode = [
			`const ${REQUEST_GLOBAL_BUNDLE_HOST_REF} = ${installerName}(${installerOptionsCode}) || globalThis`,
			...bindingTargets.map((target) => `${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}`),
			...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}}catch{}`)
		].join(";");
		const bundlePrelude = `/* ${REQUEST_GLOBAL_BUNDLE_MARKER} */ ${passiveBindingsCode ? `${passiveBindingsCode}\n` : ""}`;
		editOutputChunkCode(chunk, (magicString) => {
			magicString.prepend(`${bundlePrelude}${syntheticExportCode}`);
			magicString.append(`\n;${runtimeBindingCode};\n`);
		});
	}
	return installerChunks;
}
function injectRequestGlobalsPassiveBindings(bundle, installerChunks, targets, mode, entriesMap) {
	if (targets.length === 0) return;
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (installerChunks.has(toPosixPath(chunk.fileName))) continue;
		if (chunk.code.includes(REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER) || chunk.code.includes(REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER) || chunk.code.includes(REQUEST_GLOBAL_BUNDLE_MARKER)) continue;
		const entryName = chunk.fileName.replace(REQUEST_GLOBAL_ENTRY_NAME_RE, "");
		const entryType = entriesMap?.get(entryName)?.type;
		if (entryType === "page" || entryType === "component" || entryType === "app") continue;
		const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
		if (chunkTargets.length === 0) continue;
		const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets, resolveRequestGlobalsBindingTargets(chunkTargets));
		if (!passiveBindingsCode) continue;
		prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER} */ ${passiveBindingsCode}\n`);
	}
}
function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mode, entriesMap, networkDefaults) {
	if (targets.length === 0) return;
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		const entryName = chunk.fileName.replace(REQUEST_GLOBAL_ENTRY_NAME_RE, "");
		const entryType = entriesMap?.get(entryName)?.type;
		if (entryType !== "page" && entryType !== "component" && entryType !== "app") continue;
		if (chunk.code.includes(REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER)) continue;
		const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
		if (chunkTargets.length === 0) continue;
		const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
		if (bindingTargets.length === 0) continue;
		const inlineInstallerName = resolveRequestGlobalsInstallerName(chunk.code);
		const firstRequireMatch = chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE).next().value;
		let requireImportLiteral = null;
		let exportName;
		for (const requireMatch of chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
			const importee = requireMatch[3] ?? requireMatch[4] ?? requireMatch[5];
			if (!importee) continue;
			const installerChunkFileName = normalizeRelativeChunkImport(chunk.fileName, importee);
			exportName = installerChunks.get(installerChunkFileName);
			if (!exportName) continue;
			requireImportLiteral = requireMatch[2] ?? null;
			break;
		}
		const installerOptionsCode = createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults);
		const installerHostExpression = inlineInstallerName ? `${inlineInstallerName}(${installerOptionsCode}) || globalThis` : requireImportLiteral && exportName ? `${REQUEST_GLOBAL_CHUNK_MODULE_REF}[${JSON.stringify(exportName)}](${installerOptionsCode}) || globalThis` : null;
		if (!installerHostExpression) {
			const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets);
			if (!passiveBindingsCode) continue;
			prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${passiveBindingsCode}\n`);
			continue;
		}
		const injectionCode = [
			...!inlineInstallerName && requireImportLiteral ? [`const ${REQUEST_GLOBAL_CHUNK_MODULE_REF} = require(${requireImportLiteral})`] : [],
			`const ${REQUEST_GLOBAL_CHUNK_HOST_REF} = ${installerHostExpression}`,
			`const ${REQUEST_GLOBAL_ACTUALS_KEY} = globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] || (globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] = Object.create(null))`,
			...bindingTargets.map((target) => `${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}`),
			...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}}catch{}`),
			...bindingTargets.map((target) => `var ${target} = ${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}`)
		].join(";");
		if (inlineInstallerName && firstRequireMatch?.[0] && typeof firstRequireMatch.index === "number") {
			const firstRequireIndex = firstRequireMatch.index;
			editOutputChunkCode(chunk, (magicString) => {
				magicString.prepend(`/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ `);
				magicString.overwrite(firstRequireIndex, firstRequireIndex + firstRequireMatch[0].length, `${firstRequireMatch[0]};${injectionCode}`);
				magicString.append("\n");
			});
			continue;
		}
		prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${injectionCode};\n`);
	}
}
function resolveRequestGlobalsInstallerImport(chunk, installerChunks) {
	for (const requireMatch of chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
		const importee = requireMatch[3] ?? requireMatch[4] ?? requireMatch[5];
		if (!importee) continue;
		const installerChunkFileName = normalizeRelativeChunkImport(chunk.fileName, importee);
		const exportName = installerChunks.get(installerChunkFileName);
		if (!exportName) continue;
		return {
			exportName,
			installerChunkFileName
		};
	}
	try {
		const ast = parseJsLike(chunk.code);
		let resolvedImport = null;
		traverse(ast, { ImportDeclaration(path) {
			if (resolvedImport) return;
			const importee = getStaticStringLiteral(path.node?.source);
			if (!importee) return;
			const installerChunkFileName = normalizeRelativeChunkImport(chunk.fileName, importee);
			const exportName = installerChunks.get(installerChunkFileName);
			if (!exportName) return;
			resolvedImport = {
				exportName,
				installerChunkFileName
			};
		} });
		if (resolvedImport) return resolvedImport;
	} catch {}
	return null;
}
function toRequireRequestPath(fromFileName, toFileName) {
	const relativePath = toPosixPath(path.relative(path.dirname(fromFileName), toFileName));
	return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
}
function isRequestGlobalsSupportChunkFileName(fileName) {
	const baseName = path.basename(toPosixPath(fileName));
	return baseName.startsWith("request-globals-") || baseName === "web-apis-shared.js";
}
function rewriteChunkRequireLiteral(chunk, fromFileName, toFileName) {
	replaceOutputChunkCode(chunk, REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE, (match) => {
		const requireLiteral = match[2];
		const importee = match[3] ?? match[4] ?? match[5];
		if (!requireLiteral || !importee) return;
		if (normalizeRelativeChunkImport(chunk.fileName, importee) !== fromFileName) return;
		return match[0].replace(requireLiteral, JSON.stringify(toRequireRequestPath(chunk.fileName, toFileName)));
	});
}
function hasBareRequireRegistration(code, requirePath) {
	const escapedRequireLiteral = JSON.stringify(requirePath).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
	return new RegExp(`(?:^|[;\\n])\\s*require\\(${escapedRequireLiteral}\\);`).test(code);
}
function getRequireCallImportee(args) {
	return args[2] ?? args[3] ?? args[4];
}
function rewriteRequireCallLiterals(code, rewrite) {
	return code.replaceAll(REQUEST_GLOBAL_REQUIRE_CALL_RE, (...args) => {
		const match = args[0];
		const requireLiteral = args[1];
		const importee = getRequireCallImportee(args);
		if (typeof importee !== "string") return match;
		return rewrite(requireLiteral, importee) ?? match;
	});
}
function rewriteEmbeddedRequirePaths(code, fromFileName, toFileName) {
	return rewriteRequireCallLiterals(code, (_requireLiteral, importee) => {
		const resolvedImport = normalizeRelativeChunkImport(fromFileName, importee);
		return `require(${JSON.stringify(toRequireRequestPath(toFileName, resolvedImport))})`;
	});
}
function rewriteChunkRequireCallsToExpression(chunk, targetFileName, expression) {
	return replaceOutputChunkCode(chunk, REQUEST_GLOBAL_REQUIRE_CALL_RE, (match) => {
		const importee = match[2] ?? match[3] ?? match[4];
		if (!importee) return;
		if (normalizeRelativeChunkImport(chunk.fileName, importee) !== targetFileName) return;
		return expression;
	});
}
function createRequestGlobalsStaticImportReplacement(node, expression) {
	const declarations = [];
	const namedSpecifiers = [];
	for (const specifier of node.specifiers ?? []) {
		if (specifier?.type === "ImportNamespaceSpecifier" && specifier.local?.type === "Identifier") {
			declarations.push(`const ${specifier.local.name} = ${expression};`);
			continue;
		}
		if (specifier?.type === "ImportDefaultSpecifier" && specifier.local?.type === "Identifier") {
			declarations.push(`const ${specifier.local.name} = ${expression}.default;`);
			continue;
		}
		if (specifier?.type !== "ImportSpecifier" || specifier.local?.type !== "Identifier") continue;
		const importedName = specifier.imported?.type === "Identifier" ? specifier.imported.name : getStaticStringLiteral(specifier.imported);
		if (!importedName) continue;
		const propertyName = /^[_a-z]\w*$/i.test(importedName) ? importedName : JSON.stringify(importedName);
		namedSpecifiers.push(specifier.local.name === importedName && propertyName === importedName ? importedName : `${propertyName}: ${specifier.local.name}`);
	}
	if (namedSpecifiers.length > 0) declarations.unshift(`const { ${namedSpecifiers.join(", ")} } = ${expression};`);
	return declarations.length > 0 ? declarations.join("\n") : `${expression};`;
}
function rewriteChunkStaticImportsToExpression(chunk, targetFileName, expression) {
	try {
		const ast = parseJsLike(chunk.code);
		const replacements = [];
		traverse(ast, { ImportDeclaration(path) {
			const importee = getStaticStringLiteral(path.node?.source);
			if (!importee) return;
			if (normalizeRelativeChunkImport(chunk.fileName, importee) !== targetFileName) return;
			if (typeof path.node.start !== "number" || typeof path.node.end !== "number") return;
			replacements.push({
				end: path.node.end,
				start: path.node.start,
				value: createRequestGlobalsStaticImportReplacement(path.node, expression)
			});
		} });
		if (replacements.length === 0) return false;
		return replaceOutputChunkCodeRanges(chunk, replacements.map((replacement) => ({
			content: replacement.value,
			end: replacement.end,
			start: replacement.start
		})));
	} catch {
		return false;
	}
}
function hasAssetRequireCallToFile(source, fileName, targetFileName) {
	let hasRequireCall = false;
	rewriteRequireCallLiterals(source, (_requireLiteral, importee) => {
		if (normalizeRelativeChunkImport(fileName, importee) === targetFileName) hasRequireCall = true;
	});
	return hasRequireCall;
}
function shouldInlineRequestGlobalsAppRegisteredInstallerChunk(fileName) {
	return fileName !== "weapp-vendors/request-globals-runtime.js" && fileName.startsWith("weapp-vendors/request-globals-");
}
function toRequestGlobalsAppRegisteredModuleExpression(fileName) {
	return `globalThis[${JSON.stringify(`${REQUEST_GLOBAL_APP_MODULE_KEY_PREFIX}${fileName}`)}]`;
}
function toRequestGlobalsRequireModuleExpression(fromFileName, installerChunkFileName) {
	return `require(${JSON.stringify(toRequireRequestPath(fromFileName, installerChunkFileName))})`;
}
function toRequestGlobalsInstallerModuleExpression(fromFileName, installerChunkFileName, options = {}) {
	return options.appRegisteredModule !== false && shouldInlineRequestGlobalsAppRegisteredInstallerChunk(installerChunkFileName) ? toRequestGlobalsAppRegisteredModuleExpression(installerChunkFileName) : toRequestGlobalsRequireModuleExpression(fromFileName, installerChunkFileName);
}
function collapseRequestGlobalsRuntimeSupportChunk(bundle) {
	const runtimeChunk = bundle[REQUEST_GLOBAL_RUNTIME_CHUNK_FILE_BASENAME];
	if (!runtimeChunk || runtimeChunk.type !== "chunk") return;
	const runtimeOutput = runtimeChunk;
	let supportChunkFileName = null;
	let runtimeRequireMatch = null;
	for (const requireMatch of runtimeOutput.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
		const importee = requireMatch[3] ?? requireMatch[4] ?? requireMatch[5];
		if (!importee) continue;
		const resolvedImport = normalizeRelativeChunkImport(runtimeOutput.fileName, importee);
		const supportChunk = bundle[resolvedImport];
		if (!supportChunk || supportChunk.type !== "chunk") continue;
		if (resolvedImport === "weapp-vendors/request-globals-runtime.js" || !isRequestGlobalsSupportChunkFileName(resolvedImport)) continue;
		supportChunkFileName = resolvedImport;
		runtimeRequireMatch = requireMatch;
		break;
	}
	if (!supportChunkFileName || !runtimeRequireMatch) return;
	const supportChunk = bundle[supportChunkFileName];
	if (!supportChunk || supportChunk.type !== "chunk") return;
	const supportModuleRef = "__wvRGS__";
	const supportRequireIdentifier = runtimeRequireMatch[1];
	editOutputChunkCode(runtimeOutput, (magicString) => {
		const runtimeRequireIndex = runtimeRequireMatch.index;
		if (typeof runtimeRequireIndex !== "number") return;
		magicString.overwrite(runtimeRequireIndex, runtimeRequireIndex + runtimeRequireMatch[0].length, `${supportRequireIdentifier} = ${supportModuleRef}`);
		magicString.prepend([
			`const ${supportModuleRef} = (() => {`,
			"  const module = { exports: {} }",
			"  const exports = module.exports",
			String(supportChunk.code),
			"  return module.exports",
			"})();",
			""
		].join("\n"));
		magicString.append([
			"",
			`for (const __wvRGK__ in ${supportModuleRef}) {`,
			"  if (__wvRGK__ in exports) {",
			"    continue",
			"  }",
			`  Object.defineProperty(exports, __wvRGK__, { enumerable: true, get: () => ${supportModuleRef}[__wvRGK__] })`,
			"}"
		].join("\n"));
	});
	delete bundle[supportChunkFileName];
	for (const output of Object.values(bundle)) {
		if (!output || output.type !== "chunk") continue;
		const chunk = output;
		if (chunk.fileName === runtimeOutput.fileName) continue;
		rewriteChunkRequireLiteral(chunk, supportChunkFileName, runtimeOutput.fileName);
	}
}
function injectRequestGlobalsAppRegistration(bundle, installerChunks) {
	if (installerChunks.size === 0) return;
	const appOutput = bundle["app.js"];
	if (!appOutput || appOutput.type !== "chunk") return;
	const appChunk = appOutput;
	const requireStatements = [];
	for (const installerChunkFileName of installerChunks.keys()) {
		const installerOutput = bundle[installerChunkFileName];
		if (!installerOutput || installerOutput.type !== "chunk") continue;
		const requirePath = toRequireRequestPath(appChunk.fileName, installerChunkFileName);
		if (hasBareRequireRegistration(appChunk.code, requirePath)) continue;
		requireStatements.push(`require(${JSON.stringify(requirePath)});`);
	}
	if (requireStatements.length === 0) return;
	prependOutputChunkCode(appChunk, `${requireStatements.join("\n")}\n`);
}
function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunks, preservedInstallerChunks = /* @__PURE__ */ new Set()) {
	if (installerChunks.size === 0) return;
	const appOutput = bundle["app.js"];
	if (!appOutput || appOutput.type !== "chunk") return;
	const appChunk = appOutput;
	const inlinedModules = [];
	let inlinedIndex = 0;
	for (const installerChunkFileName of installerChunks.keys()) {
		if (!shouldInlineRequestGlobalsAppRegisteredInstallerChunk(installerChunkFileName)) continue;
		const installerOutput = bundle[installerChunkFileName];
		if (!installerOutput || installerOutput.type !== "chunk") continue;
		const moduleRef = `__wvRGA${inlinedIndex++}__`;
		const globalModuleExpression = toRequestGlobalsAppRegisteredModuleExpression(installerChunkFileName);
		const installerChunk = installerOutput;
		const embeddedCode = rewriteEmbeddedRequirePaths(installerChunk.code, installerChunk.fileName, appChunk.fileName);
		let hasPreservedAssetRequire = preservedInstallerChunks.has(installerChunkFileName);
		inlinedModules.push([
			`const ${moduleRef} = (() => {`,
			"  const module = { exports: {} }",
			"  const exports = module.exports",
			embeddedCode,
			"  return module.exports",
			"})();",
			`try{${globalModuleExpression}=${moduleRef}}catch{}`
		].join("\n"));
		for (const output of Object.values(bundle)) {
			if (!output || output.type !== "chunk") continue;
			const chunk = output;
			const didRewriteRequire = rewriteChunkRequireCallsToExpression(chunk, installerChunkFileName, globalModuleExpression);
			const didRewriteImport = rewriteChunkStaticImportsToExpression(chunk, installerChunkFileName, globalModuleExpression);
			if ((didRewriteRequire || didRewriteImport) && Array.isArray(chunk.imports)) chunk.imports = chunk.imports.filter((importee) => importee !== installerChunkFileName);
		}
		for (const output of Object.values(bundle)) {
			if (!output || output.type !== "asset" || typeof output.fileName !== "string") continue;
			const source = typeof output.source === "string" ? output.source : output.source?.toString();
			if (!source) continue;
			if (hasAssetRequireCallToFile(source, output.fileName, installerChunkFileName)) hasPreservedAssetRequire = true;
		}
		if (!hasPreservedAssetRequire) delete bundle[installerChunkFileName];
	}
	if (inlinedModules.length === 0) return;
	prependOutputChunkCode(appChunk, `${inlinedModules.join("\n")}\n`);
}
function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode, networkDefaults) {
	const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
	if (chunkTargets.length === 0 || chunk.code.includes(REQUEST_GLOBAL_PRELUDE_MARKER)) return;
	const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
	if (bindingTargets.length === 0) return;
	const installerName = resolveRequestGlobalsInstallerName(chunk.code);
	const exportName = resolveRequestGlobalsExportName(chunk.code);
	let installerHostCode;
	if (installerName && exportName) installerHostCode = `${installerName}(${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`;
	else {
		const installerImport = resolveRequestGlobalsInstallerImport(chunk, installerChunks);
		if (!installerImport?.exportName || !installerImport.installerChunkFileName) return;
		installerHostCode = `${toRequestGlobalsInstallerModuleExpression(chunk.fileName, installerImport.installerChunkFileName)}[${JSON.stringify(installerImport.exportName)}](${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`;
	}
	return [
		`/* ${REQUEST_GLOBAL_PRELUDE_MARKER} */`,
		`(() => {`,
		`  if (globalThis[${JSON.stringify(REQUEST_GLOBAL_PRELUDE_GUARD_KEY)}]) {`,
		`    return`,
		`  }`,
		`  globalThis[${JSON.stringify(REQUEST_GLOBAL_PRELUDE_GUARD_KEY)}] = true`,
		`  const ${REQUEST_GLOBAL_INSTALLER_HOST_REF} = ${installerHostCode}`,
		`  const ${REQUEST_GLOBAL_ACTUALS_KEY} = globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] || (globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] = Object.create(null))`,
		...bindingTargets.map((target) => `  ${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_INSTALLER_HOST_REF}.${target}`),
		...bindingTargets.map((target) => `  try { globalThis[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_INSTALLER_HOST_REF}.${target} } catch {}`),
		`})();`
	].join("\n");
}
function createRequestGlobalsPreludeAssetCode(preludeFileName, chunk, installerChunks, targets, mode, networkDefaults) {
	const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
	if (chunkTargets.length === 0) return;
	const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
	if (bindingTargets.length === 0) return;
	const installerImport = resolveRequestGlobalsInstallerImport(chunk, installerChunks);
	let installerChunkFileName = installerImport?.installerChunkFileName;
	let exportName = installerImport?.exportName;
	if (!installerChunkFileName || !exportName) {
		const ownExportName = installerChunks.get(toPosixPath(chunk.fileName));
		if (ownExportName) {
			installerChunkFileName = chunk.fileName;
			exportName = ownExportName;
		}
	}
	if (!installerChunkFileName || !exportName) return;
	const installerHostCode = `${toRequestGlobalsInstallerModuleExpression(preludeFileName, installerChunkFileName, { appRegisteredModule: false })}[${JSON.stringify(exportName)}](${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`;
	return [
		`/* ${REQUEST_GLOBAL_PRELUDE_MARKER} */`,
		`(() => {`,
		`  if (globalThis[${JSON.stringify(REQUEST_GLOBAL_PRELUDE_GUARD_KEY)}]) {`,
		`    return`,
		`  }`,
		`  globalThis[${JSON.stringify(REQUEST_GLOBAL_PRELUDE_GUARD_KEY)}] = true`,
		`  const ${REQUEST_GLOBAL_INSTALLER_HOST_REF} = ${installerHostCode}`,
		`  const ${REQUEST_GLOBAL_ACTUALS_KEY} = globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] || (globalThis[${JSON.stringify(REQUEST_GLOBAL_ACTUALS_KEY)}] = Object.create(null))`,
		...bindingTargets.map((target) => `  ${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_INSTALLER_HOST_REF}.${target}`),
		...bindingTargets.map((target) => `  try { globalThis[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_INSTALLER_HOST_REF}.${target} } catch {}`),
		`})();`
	].join("\n");
}
function injectAxiosFetchAdapterEnv(bundle) {
	const axiosEnvPatchCode = [
		"/* __wvAXFE__ */",
		"let __wvAX__ = null",
		"for (const __wvAXK__ in exports) {",
		"  const __wvAXC__ = exports[__wvAXK__]",
		"  if (__wvAXC__ && typeof __wvAXC__ === \"function\" && __wvAXC__.Axios && __wvAXC__.defaults) {",
		"    __wvAX__ = __wvAXC__",
		"    break",
		"  }",
		"}",
		"if (__wvAX__) {",
		"  __wvAX__.defaults.env = {",
		"    ...(__wvAX__.defaults.env ?? {}),",
		"    Request,",
		"    Response,",
		"    fetch,",
		"  }",
		"}",
		""
	].join("\n");
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (chunk.code.includes("__wvAXFE__")) continue;
		const moduleIds = Array.isArray(chunk.moduleIds) ? chunk.moduleIds : [];
		const normalizedFileName = toPosixPath(chunk.fileName);
		if (!(moduleIds.some((id) => AXIOS_MODULE_ID_RE.test(id)) || normalizedFileName === "axios.js" || normalizedFileName.endsWith("/axios.js"))) continue;
		appendOutputChunkCode(chunk, `\n${axiosEnvPatchCode}`);
	}
}
//#endregion
//#region src/plugins/core/lifecycle/emit/appPrelude.ts
function resolveAppPreludeOptions(state) {
	const option = state.ctx.configService.weappViteConfig?.appPrelude;
	if (option === false) return {
		enabled: false,
		mode: "require"
	};
	if (option === true || option == null) return {
		enabled: true,
		mode: "require"
	};
	return {
		enabled: option.enabled !== false,
		mode: option.mode ?? "require"
	};
}
function collectAppPreludeEntryChunkFileNames(state) {
	const entryChunkFileNames = /* @__PURE__ */ new Set();
	for (const entry of state.entriesMap.values()) {
		if (!entry || entry.type !== "app" && entry.type !== "page" && entry.type !== "component") continue;
		const relative = state.ctx.configService.relativeAbsoluteSrcRoot(entry.path);
		entryChunkFileNames.add(changeFileExtension(relative, ".js"));
	}
	return entryChunkFileNames;
}
async function resolveAppPreludeCode(preludePath, options) {
	if (!preludePath) return;
	const source = await readFile(preludePath, "utf8");
	if (!source.trim()) return;
	const ast = parseJsLike(source);
	let hasModuleSyntax = false;
	traverse(ast, {
		ImportDeclaration() {
			hasModuleSyntax = true;
		},
		ExportAllDeclaration() {
			hasModuleSyntax = true;
		},
		ExportDefaultDeclaration() {
			hasModuleSyntax = true;
		},
		ExportNamedDeclaration() {
			hasModuleSyntax = true;
		}
	});
	if (hasModuleSyntax) throw new Error("[app.prelude] 当前仅支持无 import/export 的自包含脚本。");
	const transformed = await transformWithOxc(source, preludePath);
	const normalizedCode = (options?.relativePath ? replaceImportMetaAccess(transformed.code, {
		importMetaDefineRegistry: options.importMetaDefineRegistry,
		extension: path.extname(preludePath),
		relativePath: options.relativePath
	}) : transformed.code).replace(USE_STRICT_PREFIX_RE, "").trim();
	if (!normalizedCode) return;
	return [
		`/* ${APP_PRELUDE_CHUNK_MARKER} */`,
		`(() => {`,
		`  if (globalThis[${JSON.stringify(APP_PRELUDE_GUARD_KEY)}]) {`,
		`    return`,
		`  }`,
		`  globalThis[${JSON.stringify(APP_PRELUDE_GUARD_KEY)}] = true`,
		normalizedCode,
		`})();`
	].join("\n");
}
function resolveAppPreludeRequireFileName(fileName, state) {
	const matchedIndependentRoot = state.subPackageMeta?.subPackage.root;
	if (matchedIndependentRoot) return `${matchedIndependentRoot}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`;
	const matchedRoot = [...state.ctx.scanService.subPackageMap?.keys() ?? []].filter(Boolean).sort((l, r) => r.length - l.length).find((root) => fileName === root || fileName.startsWith(`${root}/`));
	if (!matchedRoot) return APP_PRELUDE_REQUIRE_FILE_BASENAME;
	return `${matchedRoot}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`;
}
function createAppPreludeRequireStatement(chunkFileName, preludeFileName) {
	const relativePath = toPosixPath(path.relative(path.dirname(chunkFileName), preludeFileName));
	const requestPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
	return `/* ${APP_PRELUDE_REQUIRE_MARKER} */require(${JSON.stringify(requestPath)})`;
}
function prependChunkCodeWithSourcemap(chunk, injectedCode) {
	const directiveMatch = chunk.code.match(DIRECTIVE_PROLOGUE_RE);
	const insertIndex = directiveMatch?.[0] ? directiveMatch[0].length : 0;
	const magicString = new MagicString(chunk.code);
	magicString.prependLeft(insertIndex, `${injectedCode}\n`);
	applyMagicStringChunkRewrite(chunk, magicString, { hires: true });
}
function hasRequestGlobalsPreludeDependency(chunk, requestGlobalsPreludeOptions) {
	if (!requestGlobalsPreludeOptions.enabled) return false;
	return requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName)) || Boolean(resolveRequestGlobalsInstallerImport(chunk, requestGlobalsPreludeOptions.installerChunks)) || chunk.code.includes(REQUEST_GLOBAL_BUNDLE_MARKER$1) || chunk.code.includes(REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER$1) || chunk.code.includes(REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER$1);
}
function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile) {
	const preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
	if (!appPreludeCode && !requestGlobalsPreludeOptions.enabled) return preservedRequestGlobalsInstallerChunks;
	const preludeFileNames = /* @__PURE__ */ new Set();
	if (state.subPackageMeta?.subPackage.root) preludeFileNames.add(`${state.subPackageMeta.subPackage.root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
	else {
		preludeFileNames.add(APP_PRELUDE_REQUIRE_FILE_BASENAME);
		for (const root of state.ctx.scanService.subPackageMap.keys()) if (root) preludeFileNames.add(`${root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
	}
	for (const fileName of preludeFileNames) {
		if (bundle[fileName]) continue;
		const scopeChunks = Object.values(bundle).filter((output) => {
			return output?.type === "chunk" && resolveAppPreludeRequireFileName(output.fileName, state) === fileName;
		});
		const sortedScopeChunks = [...scopeChunks.filter((chunk) => !requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName))), ...scopeChunks.filter((chunk) => requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName)))];
		let requestGlobalsPreludeCode;
		if (requestGlobalsPreludeOptions.enabled) for (const chunk of sortedScopeChunks) {
			const code = createRequestGlobalsPreludeAssetCode(fileName, chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults);
			if (!code) continue;
			requestGlobalsPreludeCode = code;
			const installerChunkFileName = resolveRequestGlobalsInstallerImport(chunk, requestGlobalsPreludeOptions.installerChunks)?.installerChunkFileName ?? (requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName)) ? toPosixPath(chunk.fileName) : void 0);
			if (installerChunkFileName) preservedRequestGlobalsInstallerChunks.add(installerChunkFileName);
			break;
		}
		const source = [requestGlobalsPreludeCode, appPreludeCode].filter(Boolean).join("\n");
		emitFile?.({
			type: "asset",
			fileName,
			source: `${source}\n`
		});
	}
	return preservedRequestGlobalsInstallerChunks;
}
function injectAppPreludeCode(bundle, appPreludeCode, options, state, requestGlobalsPreludeOptions, emitFile) {
	let preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
	if (!options.enabled) return preservedRequestGlobalsInstallerChunks;
	const entryChunkFileNames = options.mode === "entry" ? collectAppPreludeEntryChunkFileNames(state) : void 0;
	if (options.mode === "require" && (appPreludeCode || requestGlobalsPreludeOptions.enabled)) preservedRequestGlobalsInstallerChunks = emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile);
	for (const output of Object.values(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (chunk.code.includes(APP_PRELUDE_CHUNK_MARKER) || chunk.code.includes(APP_PRELUDE_REQUIRE_MARKER)) continue;
		const isTargetEntryChunk = chunk.isEntry === true || entryChunkFileNames?.has(chunk.fileName) === true;
		if (entryChunkFileNames && !isTargetEntryChunk) continue;
		const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled && options.mode !== "require" ? createRequestGlobalsPreludeCode(chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults) : void 0;
		const shouldInjectRequirePrelude = appPreludeCode || hasRequestGlobalsPreludeDependency(chunk, requestGlobalsPreludeOptions);
		const injectedCode = [requestGlobalsPreludeCode, options.mode === "require" ? shouldInjectRequirePrelude ? createAppPreludeRequireStatement(chunk.fileName, resolveAppPreludeRequireFileName(chunk.fileName, state)) : void 0 : appPreludeCode].filter(Boolean).join("\n");
		if (!injectedCode) continue;
		prependChunkCodeWithSourcemap(chunk, injectedCode);
	}
	return preservedRequestGlobalsInstallerChunks;
}
//#endregion
//#region src/plugins/core/lifecycle/emit/generate.ts
function resolveInjectWeapiGlobalName(state) {
	const injectWeapi = state.ctx.configService.weappViteConfig?.injectWeapi;
	if (!injectWeapi) return null;
	if (!(typeof injectWeapi === "object" ? injectWeapi.enabled === true : injectWeapi === true) || typeof injectWeapi !== "object" || injectWeapi.replaceWx !== true) return null;
	return injectWeapi.globalName?.trim() || "wpi";
}
function hasChunkOutputs(bundle) {
	return Object.values(bundle).some((output) => output?.type === "chunk");
}
function pruneHmrMetadataOnlyChunks(bundle, state) {
	if (!state.ctx.configService.isDev || !state.hmrState.hasBuiltOnce || !state.hmrState.skipSharedChunkRefresh) return hasChunkOutputs(bundle);
	for (const [fileName, output] of Object.entries(bundle)) if (output?.type === "chunk") delete bundle[fileName];
	return false;
}
function isAssetOnlyDevHmrBundle(hasChunkOutput, state) {
	return state.ctx.configService.isDev && state.hmrState.hasBuiltOnce && state.hmrState.skipSharedChunkRefresh && !hasChunkOutput;
}
function isStableHmrSharedChunk(fileName) {
	return fileName.startsWith("weapp-vendors/") || !fileName.includes("/") && fileName !== "app.js";
}
function isRuntimeVendorSharedChunk(fileName) {
	return !isWevuStableVendorFileName(fileName) && fileName.startsWith("weapp-vendors/") && /(?:^|[-/])[\w-]*runtime[\w-]*(?:[-.]|$)/.test(fileName);
}
function addEmittedChunkFileName(emittedChunkFileNames, fileName, chunk) {
	if (!emittedChunkFileNames) return;
	emittedChunkFileNames.add(fileName);
	if (chunk.fileName) emittedChunkFileNames.add(chunk.fileName);
}
function isCurrentStyleSidecarUpdate(state) {
	return state.ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary?.some((item) => item.startsWith("style-sidecar:")) === true;
}
function createSubPackageMatcher(subPackageRoots) {
	const candidates = subPackageRoots.map((root) => ({
		prefix: `${root}/`,
		root
	}));
	const cache = /* @__PURE__ */ new Map();
	return function matchSubPackage(filePath) {
		const cached = cache.get(filePath);
		if (cached !== void 0 || cache.has(filePath)) return cached;
		let matched;
		for (const { prefix, root } of candidates) if (filePath === root || filePath.startsWith(prefix)) {
			matched = root;
			break;
		}
		cache.set(filePath, matched);
		return matched;
	};
}
function createBundleChunkResolver(bundle) {
	const chunksByFileName = /* @__PURE__ */ new Map();
	for (const [fileName, output] of Object.entries(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		chunksByFileName.set(fileName, chunk);
		if (chunk.fileName) chunksByFileName.set(chunk.fileName, chunk);
	}
	return (fileName) => chunksByFileName.get(fileName);
}
async function emitCurrentStyleSidecarAsset(state, bundle) {
	if (!isCurrentStyleSidecarUpdate(state)) return;
	const currentFile = state.ctx.runtimeState.build.hmr.profile.file;
	if (typeof currentFile !== "string") return;
	await emitStyleSidecarAsset(state.ctx, this, bundle, currentFile, state.resolvedConfig);
}
function resolveImportedChunkId(importerFileName, imported) {
	if (!imported.startsWith(".")) return imported;
	const importerSegments = importerFileName.split("/");
	importerSegments.pop();
	for (const segment of imported.split("/")) {
		if (!segment || segment === ".") continue;
		if (segment === "..") {
			importerSegments.pop();
			continue;
		}
		importerSegments.push(segment);
	}
	return importerSegments.join("/");
}
function collectResolvedImportedChunkIds(importedChunkIds, importerFileName, imports) {
	if (!Array.isArray(imports)) return;
	for (const imported of imports) {
		if (typeof imported !== "string") continue;
		importedChunkIds.add(resolveImportedChunkId(importerFileName, imported));
	}
}
function isActiveHmrEntryFacade(facadeModuleId, activeEntryIds) {
	if (!facadeModuleId || !activeEntryIds?.size) return false;
	if (activeEntryIds.has(facadeModuleId)) return true;
	const sourceId = parseLogicalEntryId(facadeModuleId)?.sourceId;
	return sourceId ? activeEntryIds.has(normalizeFsResolvedId(sourceId)) : false;
}
function collectActiveHmrImportedChunkIds(bundle, activeEntryIds) {
	if (!activeEntryIds?.size) return /* @__PURE__ */ new Set();
	const importedChunkIds = /* @__PURE__ */ new Set();
	for (const [bundleFileName, output] of Object.entries(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (!isActiveHmrEntryFacade(chunk.facadeModuleId, activeEntryIds)) continue;
		const importerFileName = chunk.fileName || bundleFileName;
		collectResolvedImportedChunkIds(importedChunkIds, importerFileName, chunk.imports);
		collectResolvedImportedChunkIds(importedChunkIds, importerFileName, chunk.dynamicImports);
	}
	return importedChunkIds;
}
function mergeActiveHmrEntryIds(lastHmrEntryIds, lastEmittedEntryIds) {
	if (!lastHmrEntryIds?.size) return lastEmittedEntryIds;
	if (!lastEmittedEntryIds?.size) return lastHmrEntryIds;
	return /* @__PURE__ */ new Set([...lastHmrEntryIds, ...lastEmittedEntryIds]);
}
function resolveActiveHmrEntryIds(state) {
	return mergeActiveHmrEntryIds(state.hmrState.lastHmrEntryIds, state.hmrState.lastEmittedEntryIds);
}
function shouldRewriteDevHmrChunk(fileName, output, state, activeEntryIds, activeImportedChunkIds) {
	if (output?.type !== "chunk") return true;
	if (!activeEntryIds?.size) return true;
	const chunk = output;
	if (isActiveHmrEntryFacade(chunk.facadeModuleId, activeEntryIds)) return true;
	if (state.hmrState.affectedSharedChunkIds?.has(fileName) || state.hmrState.affectedSharedChunkIds?.has(chunk.fileName)) return true;
	return activeImportedChunkIds.has(fileName);
}
function resolveDevHmrRewriteBundle(bundle, state, precomputedActiveImportedChunkIds) {
	if (!state.ctx.configService.isDev || !state.hmrState.hasBuiltOnce || state.hmrState.didEmitAllEntries) return bundle;
	const rewriteBundle = {};
	const activeEntryIds = resolveActiveHmrEntryIds(state);
	const activeImportedChunkIds = precomputedActiveImportedChunkIds ?? collectActiveHmrImportedChunkIds(bundle, activeEntryIds);
	for (const [fileName, output] of Object.entries(bundle)) if (shouldRewriteDevHmrChunk(fileName, output, state, activeEntryIds, activeImportedChunkIds)) rewriteBundle[fileName] = output;
	return rewriteBundle;
}
function createDevHmrRuntimeRewriteSnapshot(bundle, rewriteBundle) {
	if (bundle === rewriteBundle) return createBundleChunkSnapshot(bundle);
	const fullSnapshot = createBundleChunkSnapshot(bundle);
	return {
		...createBundleChunkSnapshot(rewriteBundle),
		chunkFileNames: fullSnapshot.chunkFileNames,
		vendorChunks: fullSnapshot.vendorChunks,
		wevuChunks: fullSnapshot.wevuChunks,
		wevuChunkFileNames: fullSnapshot.wevuChunkFileNames
	};
}
function shouldWarmupBundleScriptAnalysis(options) {
	return !options.rewritesBundleNpmImports && (options.hasNpmBuildCandidateDependencies || options.hasLocalRootNpmRewriteTargets || options.hasPlatformApiRewrite);
}
function prunePartialHmrStableSharedChunks(bundle, state) {
	if (!state.ctx.configService.isDev || !state.hmrState.hasBuiltOnce || state.hmrState.didEmitAllEntries || state.hmrState.skipSharedChunkRefresh || !state.hmrState.lastEmittedEntryIds?.size) return;
	const activeEntryIds = resolveActiveHmrEntryIds(state);
	const activeImportedChunkIds = /* @__PURE__ */ new Set();
	const pendingRuntimeVendorChunks = [];
	const emittedChunkFileNames = state.ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
	for (const [fileName, output] of Object.entries(bundle)) {
		if (output?.type !== "chunk") continue;
		const chunk = output;
		if (isActiveHmrEntryFacade(chunk.facadeModuleId, activeEntryIds)) {
			const importerFileName = chunk.fileName || fileName;
			addEmittedChunkFileName(emittedChunkFileNames, fileName, chunk);
			collectResolvedImportedChunkIds(activeImportedChunkIds, importerFileName, chunk.imports);
			collectResolvedImportedChunkIds(activeImportedChunkIds, importerFileName, chunk.dynamicImports);
		}
		if (!isStableHmrSharedChunk(fileName)) continue;
		const knownImporters = state.hmrSharedChunkImporters.get(fileName);
		if (!knownImporters?.size) {
			delete bundle[fileName];
			continue;
		}
		if (state.hmrState.affectedSharedChunkIds?.has(fileName) === true || (output.fileName ? state.hmrState.affectedSharedChunkIds?.has(output.fileName) === true : false)) {
			addEmittedChunkFileName(emittedChunkFileNames, fileName, chunk);
			continue;
		}
		if (isRuntimeVendorSharedChunk(fileName)) {
			pendingRuntimeVendorChunks.push({
				fileName,
				chunk
			});
			continue;
		}
		let isCompleteSharedChunkRefresh = true;
		for (const entryId of knownImporters) if (!activeEntryIds?.has(entryId)) {
			isCompleteSharedChunkRefresh = false;
			break;
		}
		if (!isCompleteSharedChunkRefresh) {
			delete bundle[fileName];
			continue;
		}
		addEmittedChunkFileName(emittedChunkFileNames, fileName, chunk);
	}
	for (const { fileName, chunk } of pendingRuntimeVendorChunks) {
		if (activeImportedChunkIds.has(fileName) || (chunk.fileName ? activeImportedChunkIds.has(chunk.fileName) : false)) {
			addEmittedChunkFileName(emittedChunkFileNames, fileName, chunk);
			continue;
		}
		const knownImporters = state.hmrSharedChunkImporters.get(fileName);
		let isCompleteSharedChunkRefresh = true;
		for (const entryId of knownImporters ?? []) if (!activeEntryIds?.has(entryId)) {
			isCompleteSharedChunkRefresh = false;
			break;
		}
		if (!isCompleteSharedChunkRefresh) {
			delete bundle[fileName];
			continue;
		}
		addEmittedChunkFileName(emittedChunkFileNames, fileName, chunk);
	}
	return activeImportedChunkIds;
}
function retainFullEntryHmrChunks(bundle, state) {
	if (!state.ctx.configService.isDev || !state.hmrState.hasBuiltOnce || !state.hmrState.didEmitAllEntries) return;
	const emittedChunkFileNames = state.ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
	if (!emittedChunkFileNames?.size) return;
	for (const [fileName, output] of Object.entries(bundle)) {
		if (output?.type !== "chunk") continue;
		addEmittedChunkFileName(emittedChunkFileNames, fileName, output);
	}
}
function createGenerateBundleHook(state, isPluginBuild) {
	const { ctx, subPackageMeta } = state;
	const { scanService, configService } = ctx;
	const astEngine = resolveAstEngine(configService.weappViteConfig);
	const injectRequestGlobalsOptions = resolveRequestRuntimeOptions({
		appPrelude: configService.weappViteConfig?.appPrelude,
		webRuntime: configService.weappViteConfig?.injectWebRuntimeGlobals,
		injectRequestGlobals: configService.weappViteConfig?.injectRequestGlobals
	}, configService.packageJson, (message) => logger_default.warn(message));
	const npmBuildCandidateDependencies = resolveNpmBuildCandidateDependencyRecordSync(ctx, configService.packageJson);
	return async function generateBundle(_options, bundle) {
		const startedAt = performance.now();
		try {
			ctx.moduleGraphService?.bindBuildContext(state, this);
			ctx.moduleGraphService?.bindPluginContext(this);
			const rolldownBundle = bundle;
			const scriptAnalysisCache = /* @__PURE__ */ new WeakMap();
			const hasChunkOutput = pruneHmrMetadataOnlyChunks(rolldownBundle, state);
			await emitCurrentStyleSidecarAsset.call(this, state, rolldownBundle);
			const assetOnlyDevHmrBundle = isAssetOnlyDevHmrBundle(hasChunkOutput, state);
			if (isPluginBuild) {
				filterPluginBundleOutputs(rolldownBundle, configService);
				if (!shouldRewriteBundleNpmImports(configService.platform)) {
					warmupBundleScriptAnalysis(rolldownBundle, {
						astEngine,
						cache: scriptAnalysisCache
					});
					for (const output of Object.values(rolldownBundle)) if (output?.type === "chunk") rewriteChunkNpmImportsToLocalRoot(output, "", void 0, npmBuildCandidateDependencies, {
						analysisCache: scriptAnalysisCache,
						astEngine,
						basedir: configService.cwd
					});
					rewriteJsonNpmImportsToLocalRoot(rolldownBundle, "", void 0, npmBuildCandidateDependencies, configService.cwd);
				}
				normalizePreprocessorStyleAssets(rolldownBundle, state.ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
				return;
			}
			const sharedStartedAt = performance.now();
			let activeImportedChunkIds;
			if (!subPackageMeta) {
				const sharedStrategy = configService.weappViteConfig?.chunks?.sharedStrategy ?? "hoist";
				const shouldLogChunks = configService.weappViteConfig?.chunks?.logOptimization ?? true;
				const subPackageRoots = [...scanService.subPackageMap.keys()].filter(Boolean);
				const duplicateWarningBytes = Number(configService.weappViteConfig?.chunks?.duplicateWarningBytes ?? 0);
				const shouldWarnOnDuplicate = Number.isFinite(duplicateWarningBytes) && duplicateWarningBytes > 0;
				let redundantBytesTotal = 0;
				if (configService.isDev && (state.hmrSharedChunksMode === "auto" || state.hmrSharedChunksMode === "full")) {
					const forceFullSharedChunkRefresh = process.env.WEAPP_VITE_FORCE_FULL_HMR_SHARED_CHUNKS === "1";
					if (assetOnlyDevHmrBundle && !forceFullSharedChunkRefresh) {} else if (state.hmrSharedChunksMode === "full" || state.hmrState.didEmitAllEntries || !state.hmrState.hasBuiltOnce) refreshSharedChunkImporters(rolldownBundle, state);
					else if (forceFullSharedChunkRefresh) refreshSharedChunkImporters(rolldownBundle, state);
					else if (state.hmrState.lastHmrEntryIds?.size) refreshPartialSharedChunkImporters(rolldownBundle, state, state.hmrState.lastHmrEntryIds);
					else if (state.hmrState.lastEmittedEntryIds?.size) refreshPartialSharedChunkImporters(rolldownBundle, state, state.hmrState.lastEmittedEntryIds);
					state.hmrState.hasBuiltOnce = true;
				}
				activeImportedChunkIds = prunePartialHmrStableSharedChunks(rolldownBundle, state);
				retainFullEntryHmrChunks(rolldownBundle, state);
				pruneUneventedDevHmrChunks(ctx, rolldownBundle);
				if (assetOnlyDevHmrBundle) {
					state.hmrState.affectedSharedChunkIds?.clear();
					normalizePreprocessorStyleAssets(rolldownBundle, state.ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
					return;
				}
				const matchSubPackage = createSubPackageMatcher(subPackageRoots);
				const resolveBundleChunk = createBundleChunkResolver(rolldownBundle);
				const resolveSharedChunkLabel = (sharedFileName, finalFileName) => {
					const prettifyModuleLabel = (label) => {
						return toPosixPath(label).match(PRETTY_NODE_MODULES_RE)?.[1] || label;
					};
					const chunk = resolveBundleChunk(sharedFileName) ?? resolveBundleChunk(finalFileName);
					if (!chunk) return finalFileName;
					const seenModuleLabels = /* @__PURE__ */ new Set();
					const preview = [];
					let moduleLabelCount = 0;
					for (const id in chunk.modules ?? {}) {
						if (!id || id.startsWith("\0")) continue;
						const label = configService.relativeAbsoluteSrcRoot(id);
						if (!label || seenModuleLabels.has(label)) continue;
						seenModuleLabels.add(label);
						moduleLabelCount += 1;
						if (preview.length < 3) preview.push(prettifyModuleLabel(label));
					}
					if (moduleLabelCount === 0) return chunk.fileName || finalFileName;
					const suffix = moduleLabelCount > preview.length ? ` 等 ${moduleLabelCount} 个模块` : "";
					return `${preview.join("、")}${suffix}`;
				};
				const runtimeLocalizationRoots = /* @__PURE__ */ new Set();
				const handleDuplicate = ({ duplicates, ignoredMainImporters, chunkBytes, redundantBytes, retainedInMain, sharedFileName, requiresRuntimeLocalization }) => {
					if (shouldWarnOnDuplicate) {
						const duplicateCount = duplicates.length;
						const computedRedundant = typeof redundantBytes === "number" ? redundantBytes : typeof chunkBytes === "number" ? chunkBytes * Math.max(duplicateCount - 1, 0) : 0;
						redundantBytesTotal += computedRedundant;
					}
					if (requiresRuntimeLocalization) for (const { fileName } of duplicates) {
						const match = matchSubPackage(fileName);
						if (match) runtimeLocalizationRoots.add(match);
					}
					if (!shouldLogChunks) return;
					const subPackageSet = /* @__PURE__ */ new Set();
					let totalReferences = 0;
					for (const { fileName, importers } of duplicates) {
						totalReferences += importers.length;
						const match = matchSubPackage(fileName);
						if (match) subPackageSet.add(match);
					}
					const subPackageList = [...subPackageSet].join("、") || "相关分包";
					const ignoredHint = ignoredMainImporters?.length ? `,忽略主包引用:${ignoredMainImporters.join("、")}` : "";
					logger_default.info(`[分包] 分包 ${subPackageList} 共享模块已复制到各自 weapp-shared/common.js(${totalReferences} 处引用${ignoredHint})`);
					if (retainedInMain) logger_default.warn(`[分包] 模块 ${sharedFileName} 同时被主包引用,因此仍保留在主包 common.js,并复制到 ${subPackageList},请确认是否需要将源代码移动到主包或公共目录。`);
				};
				applySharedChunkStrategy.call(this, rolldownBundle, {
					strategy: sharedStrategy,
					subPackageRoots,
					onDuplicate: handleDuplicate,
					onFallback: shouldLogChunks ? ({ reason, importers, sharedFileName, finalFileName }) => {
						const involvedSubs = /* @__PURE__ */ new Set();
						let hasMainReference = false;
						for (const importer of importers) {
							const match = matchSubPackage(importer);
							if (match) involvedSubs.add(match);
							else hasMainReference = true;
						}
						const segments = [];
						if (involvedSubs.size) segments.push(`分包 ${[...involvedSubs].join("、")}`);
						if (hasMainReference) segments.push("主包");
						const scope = segments.join("、") || "主包";
						const sharedChunkLabel = resolveSharedChunkLabel(sharedFileName, finalFileName);
						if (reason === "main-package") logger_default.info(`[分包] ${scope} 共享模块 ${sharedChunkLabel}(${importers.length} 处引用)已提升到主包 common.js`);
						else logger_default.info(`[分包] 仅主包使用共享模块 ${sharedChunkLabel}(${importers.length} 处引用),保留在主包 common.js`);
					} : void 0
				});
				applyRuntimeChunkLocalization.call(this, rolldownBundle, {
					subPackageRoots,
					forceRoots: runtimeLocalizationRoots,
					onDuplicate: shouldLogChunks ? ({ duplicates, runtimeFileName }) => {
						const subPackageSet = /* @__PURE__ */ new Set();
						for (const { fileName } of duplicates) {
							const match = matchSubPackage(fileName);
							if (match) subPackageSet.add(match);
						}
						const subPackageList = [...subPackageSet].join("、") || "相关分包";
						logger_default.info(`[分包] 分包 ${subPackageList} 已本地化 ${runtimeFileName} 依赖,避免跨包 runtime 引用。`);
					} : void 0
				});
				if (shouldWarnOnDuplicate && redundantBytesTotal > duplicateWarningBytes) logger_default.warn(`[分包] 分包复制共享模块产生冗余体积 ${formatBytes(redundantBytesTotal)},已超过阈值 ${formatBytes(duplicateWarningBytes)},建议调整分包划分或运行 weapp-vite analyze 定位问题。`);
			}
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "generateSharedMs", performance.now() - sharedStartedAt);
			const preloadBundleSnapshot = createBundleChunkSnapshot(rolldownBundle);
			removeImplicitPagePreloads(rolldownBundle, {
				configService,
				entriesMap: state.entriesMap
			}, preloadBundleSnapshot);
			const rewriteStartedAt = performance.now();
			const rewriteBundle = resolveDevHmrRewriteBundle(rolldownBundle, state, activeImportedChunkIds);
			const localSubPackageMetas = [...(scanService.subPackageMap ?? /* @__PURE__ */ new Map()).values()].filter((meta) => Array.isArray(meta?.subPackage?.dependencies) && meta.subPackage.dependencies.length > 0);
			const hasNpmBuildCandidateDependencies = npmBuildCandidateDependencies ? Object.keys(npmBuildCandidateDependencies).some(() => true) : false;
			const hasLocalRootNpmRewriteTargets = localSubPackageMetas.length > 0;
			const rewritesBundleNpmImports = shouldRewriteBundleNpmImports(configService.platform);
			const injectWeapiGlobalName = resolveInjectWeapiGlobalName(state);
			if (shouldWarmupBundleScriptAnalysis({
				rewritesBundleNpmImports,
				hasNpmBuildCandidateDependencies,
				hasLocalRootNpmRewriteTargets,
				hasPlatformApiRewrite: Boolean(injectWeapiGlobalName)
			})) warmupBundleScriptAnalysis(rewriteBundle, {
				astEngine,
				cache: scriptAnalysisCache
			});
			if (rewritesBundleNpmImports) rewriteBundleNpmImportsByPlatform(configService.platform, rewriteBundle, npmBuildCandidateDependencies, configService.weappViteConfig?.npm?.alipayNpmMode, {
				astEngine,
				analysisCache: scriptAnalysisCache
			});
			else if (hasNpmBuildCandidateDependencies || hasLocalRootNpmRewriteTargets) rewriteBundleNpmImportsToLocalRoots(rewriteBundle, npmBuildCandidateDependencies, localSubPackageMetas.map((meta) => ({
				root: meta.subPackage.root,
				dependencies: meta.subPackage.dependencies
			})), {
				analysisCache: scriptAnalysisCache,
				astEngine,
				basedir: configService.cwd
			});
			if (injectWeapiGlobalName) rewriteBundlePlatformApi(rewriteBundle, injectWeapiGlobalName, {
				analysisCache: scriptAnalysisCache,
				astEngine
			});
			rewriteBundleDynamicGlobalResolution(rewriteBundle);
			const installerChunks = injectRequestGlobalsOptions?.targets?.length ? injectRequestGlobalsBundleRuntime(rolldownBundle, injectRequestGlobalsOptions.targets, injectRequestGlobalsOptions.mode, injectRequestGlobalsOptions.networkDefaults) : /* @__PURE__ */ new Map();
			if (injectRequestGlobalsOptions?.targets?.length) {
				injectRequestGlobalsPassiveBindings(rolldownBundle, installerChunks, injectRequestGlobalsOptions.targets, injectRequestGlobalsOptions.mode, state.entriesMap);
				injectRequestGlobalsLocalBindings(rolldownBundle, installerChunks, injectRequestGlobalsOptions.targets, injectRequestGlobalsOptions.mode, state.entriesMap, injectRequestGlobalsOptions.networkDefaults);
				injectAxiosFetchAdapterEnv(rolldownBundle);
				injectRequestGlobalsAppRegistration(rolldownBundle, installerChunks);
				collapseRequestGlobalsRuntimeSupportChunk(rolldownBundle);
			}
			const appPreludePath = scanService.appEntry?.preludePath;
			const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true && Boolean(scanService.appEntry || subPackageMeta);
			const appPreludeOptions = resolveAppPreludeOptions(state);
			const preservedRequestGlobalsInstallerChunks = appPreludeOptions.enabled && Boolean(appPreludePath) || shouldInjectRequestGlobalsPrelude ? injectAppPreludeCode(rolldownBundle, await resolveAppPreludeCode(appPreludePath, {
				importMetaDefineRegistry: configService.importMetaDefineRegistry,
				relativePath: appPreludePath ? configService.relativeAbsoluteSrcRoot(appPreludePath) : void 0
			}), {
				...appPreludeOptions,
				enabled: appPreludeOptions.enabled || shouldInjectRequestGlobalsPrelude
			}, state, {
				enabled: shouldInjectRequestGlobalsPrelude,
				installerChunks,
				mode: injectRequestGlobalsOptions?.mode ?? "explicit",
				networkDefaults: injectRequestGlobalsOptions?.networkDefaults,
				targets: injectRequestGlobalsOptions?.targets ?? []
			}, (asset) => this.emitFile(asset)) : /* @__PURE__ */ new Set();
			if (injectRequestGlobalsOptions?.targets?.length) inlineRequestGlobalsAppRegisteredInstallerChunks(rolldownBundle, installerChunks, preservedRequestGlobalsInstallerChunks);
			const runtimeRewriteBundle = resolveDevHmrRewriteBundle(rolldownBundle, state, activeImportedChunkIds);
			const finalBundleSnapshot = createDevHmrRuntimeRewriteSnapshot(rolldownBundle, runtimeRewriteBundle);
			rewriteWevuInternalRuntimeImports(runtimeRewriteBundle, {
				runtimeFileName: state.ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileName,
				runtimeFileNames: state.ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileNames,
				isRuntimeFileNameAvailable(fileName) {
					return state.ctx.runtimeState?.build?.output?.emittedSource.has(fileName) === true;
				},
				onRuntimeFileName(fileName) {
					const outputState = state.ctx.runtimeState?.build?.output;
					if (outputState) outputState.wevuInternalRuntimeFileName = fileName;
				},
				onRuntimeModuleFileName(moduleId, fileName) {
					const outputState = state.ctx.runtimeState?.build?.output;
					if (outputState) {
						outputState.wevuInternalRuntimeFileNames ??= /* @__PURE__ */ new Map();
						outputState.wevuInternalRuntimeFileNames.set(moduleId, fileName);
					}
				}
			}, finalBundleSnapshot);
			stabilizeWevuRuntimeChunkAccess(runtimeRewriteBundle, finalBundleSnapshot);
			syncChunkImportsFromRequireCalls(runtimeRewriteBundle, finalBundleSnapshot);
			normalizePreprocessorStyleAssets(rolldownBundle, state.ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "generateRewriteMs", performance.now() - rewriteStartedAt);
			state.hmrState.affectedSharedChunkIds?.clear();
			if (configService.weappViteConfig?.debug?.watchFiles) {
				const watcherService = ctx.watcherService;
				const watcherRoot = subPackageMeta?.subPackage.root ?? "/";
				const watcher = watcherService?.getRollupWatcher(watcherRoot);
				let watchFiles;
				if (watcher && typeof watcher.getWatchFiles === "function") watchFiles = await watcher.getWatchFiles();
				else if (state.watchFilesSnapshot.length) watchFiles = state.watchFilesSnapshot;
				if (watchFiles && watchFiles.length) configService.weappViteConfig.debug.watchFiles(watchFiles, subPackageMeta);
				state.watchFilesSnapshot = [];
			}
		} finally {
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "generateBundleMs", performance.now() - startedAt);
			if (!subPackageMeta) ctx.moduleGraphService?.clearPendingChanges();
		}
	};
}
//#endregion
//#region src/plugins/core/lifecycle/emit.ts
function shouldEmitJsonDuringRenderStart(state) {
	const { ctx, hmrState } = state;
	if (!ctx.configService.isDev || !hmrState.hasBuiltOnce || hmrState.didEmitAllEntries) return true;
	const dirtyReasons = ctx.runtimeState.build.hmr.profile.dirtyReasonSummary;
	if (!dirtyReasons?.length) return true;
	return dirtyReasons.some((reason) => reason.startsWith("json-sidecar:") || reason.startsWith("entry-json-only:") || reason.startsWith("config-restart:") || reason.startsWith("auto-routes-topology:") || reason.startsWith("app-shell-dependent:") || reason.startsWith("layout-self:") || reason.startsWith("layout-dependent:") || reason.startsWith("layout-fallback-full:"));
}
function resolveIncrementalHmrWxmlTargetIds(state) {
	const { ctx, hmrState, entriesMap } = state;
	if (!ctx.configService.isDev || !hmrState.hasBuiltOnce || hmrState.didEmitAllEntries) return;
	const targets = /* @__PURE__ */ new Set();
	const currentFile = ctx.runtimeState.build.hmr.profile.file;
	if (typeof currentFile === "string" && isTemplate(currentFile)) targets.add(normalizeWatchPath(currentFile));
	const entryIds = hmrState.lastHmrEntryIds?.size ? hmrState.lastHmrEntryIds : hmrState.lastEmittedEntryIds;
	for (const entryId of entryIds ?? []) {
		const candidates = [
			entryId,
			ctx.configService.relativeAbsoluteSrcRoot(entryId),
			removeExtensionDeep(entryId),
			removeExtensionDeep(ctx.configService.relativeAbsoluteSrcRoot(entryId))
		];
		for (const candidate of candidates) {
			const entry = entriesMap.get(candidate);
			if (entry && "templatePath" in entry && entry.templatePath) targets.add(normalizeWatchPath(entry.templatePath));
		}
	}
	return targets.size ? targets : void 0;
}
function createRenderStartHook(state) {
	const { ctx, subPackageMeta, buildTarget } = state;
	return async function renderStart() {
		const startedAt = performance.now();
		try {
			const runtime = { emitFile: (asset) => {
				this.emitFile(asset);
			} };
			if (shouldEmitJsonDuringRenderStart(state)) emitJsonAssets.call(this, state);
			state.watchFilesSnapshot = emitWxmlAssetsWithCache({
				runtime,
				compiler: ctx,
				subPackageMeta,
				emittedCodeCache: ctx.runtimeState.wxml.emittedCode,
				buildTarget,
				targetIds: resolveIncrementalHmrWxmlTargetIds(state)
			});
		} finally {
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "renderStartMs", performance.now() - startedAt);
		}
	};
}
//#endregion
//#region src/plugins/core/lifecycle/end.ts
const debug$1 = createDebugger("weapp-vite:core");
function resolveEntryType(state, entryId) {
	const relativeBase = removeExtensionDeep(state.ctx.configService.relativeAbsoluteSrcRoot(entryId));
	const declaredType = state.entriesMap.get(relativeBase)?.type;
	if (declaredType === "page" || declaredType === "component") return declaredType;
	return state.hmrRootInputIds.has(normalizeSourceId(entryId)) ? "app" : "component";
}
function resolveChangeCause(state, file, affectedEntries) {
	const normalized = normalizeFsResolvedId(file);
	if (configSuffixes.some((suffix) => normalized.endsWith(suffix))) return "json-sidecar";
	const extension = path.extname(normalized);
	if (watchedCssExts.has(extension)) {
		const styleBase = removeExtensionDeep(normalized);
		return Array.from(affectedEntries).some((entryId) => {
			return removeExtensionDeep(normalizeFsResolvedId(entryId)) === styleBase;
		}) ? "style-sidecar" : "css-importer";
	}
	if (watchedTemplateExts.has(extension)) return isLayoutSourcePath(state.ctx.configService.relativeAbsoluteSrcRoot(normalized)) ? "layout-dependent" : "sidecar-direct";
	if (state.ctx.moduleGraphService.isLogicalLayoutEntry(normalized)) return "layout-script";
	if (isLayoutSourcePath(state.ctx.configService.relativeAbsoluteSrcRoot(normalized))) return "layout-dependent";
	if (state.resolvedEntryMap.has(normalized)) return "entry-direct";
	return "importer-graph";
}
function createBuildEndHook(state) {
	const { subPackageMeta } = state;
	return async function buildEnd() {
		state.ctx.moduleGraphService.bindBuildContext(state, this);
		const pendingChanges = state.ctx.moduleGraphService.getPendingChanges();
		const affectedEntries = /* @__PURE__ */ new Set();
		const causes = /* @__PURE__ */ new Map();
		let metadataOnly = pendingChanges.length > 0;
		for (const change of pendingChanges) {
			const affected = state.ctx.moduleGraphService.collectAffectedEntries(change.file);
			const cause = resolveChangeCause(state, change.file, affected);
			causes.set(cause, (causes.get(cause) ?? 0) + affected.size);
			if (cause === "entry-direct" || cause === "importer-graph" || cause === "layout-script") metadataOnly = false;
			for (const entryId of affected) {
				if (!state.resolvedEntryMap.has(entryId)) continue;
				affectedEntries.add(entryId);
			}
		}
		if (affectedEntries.size) {
			const hmr = state.ctx.runtimeState.build.hmr;
			state.hmrState.lastHmrEntryIds = new Set(affectedEntries);
			hmr.lastHmrEntryIds = new Set(affectedEntries);
			state.hmrState.didEmitAllEntries = false;
			state.hmrState.skipSharedChunkRefresh = metadataOnly;
			const summary = [...causes.entries()].map(([cause, count]) => `${cause}:${count}`);
			hmr.profile = {
				...hmr.profile,
				dirtyCount: affectedEntries.size,
				emittedCount: metadataOnly ? affectedEntries.size : hmr.profile.emittedCount,
				pendingCount: metadataOnly ? affectedEntries.size : hmr.profile.pendingCount,
				dirtyReasonSummary: summary
			};
			if (metadataOnly) for (const entryId of affectedEntries) {
				state.loadedEntrySet.delete(entryId);
				await state.loadEntry.call(this, entryId, resolveEntryType(state, entryId), { metadataOnly: true });
			}
		}
		await state.ctx.moduleGraphService.syncDevGraph(this);
		debug$1?.(`${subPackageMeta ? `独立分包 ${subPackageMeta.subPackage.root}` : "主包"} ${Array.from(this.getModuleIds()).length} 个模块被编译`);
	};
}
//#endregion
//#region src/plugins/utils/parse.ts
function hasOwn$1(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
/**
* 参考:https://github.com/tailwindlabs/tailwindcss/blob/main/packages/%40tailwindcss-vite/src/index.ts
* 解析请求ID,返回包含文件名和查询参数的对象。
* 如果查询参数中包含'wxss',则将其值设置为true。
* @param id - 请求ID,格式为'filename?query'
* @returns 解析后的请求响应对象
*/
function parseRequest(id) {
	const [filename, rawQuery] = id.split(`?`, 2);
	const query = {};
	if (rawQuery) {
		const params = new URLSearchParams(rawQuery);
		for (const [key, value] of params.entries()) query[key] = value;
		if (hasOwn$1(query, "wxss")) query.wxss = true;
	}
	return {
		filename,
		query
	};
}
/**
* 根据请求响应获取 CSS 文件的真实路径。
* 如果请求中包含 wxss 查询参数,则将文件扩展名更改为 'wxss'。
* @param res - 解析请求的响应对象,包含文件名和查询参数。
* @returns 返回文件的真实路径。
*/
function getCssRealPath(res) {
	if (typeof res.query.nativeStyle === "string" && res.query.nativeStyle) return changeFileExtension(res.filename, res.query.nativeStyle);
	if (res.query.wxss) return changeFileExtension(res.filename, "wxss");
	return res.filename;
}
//#endregion
//#region src/utils/codeTransform.ts
/**
* 对 load/transform 结果执行可追踪编辑,并按需组合已有映射。
*/
function editCodeTransformResult(result, sourceId, edit, options) {
	const magicString = new MagicString(result.code);
	edit(magicString, result.code);
	const code = magicString.toString();
	if (code === result.code) return result;
	const previousMap = normalizeEncodedSourceMapLike(result.map);
	if (!options?.sourceMap && !previousMap) return {
		...result,
		code
	};
	const rewriteMap = magicString.generateMap({
		hires: true,
		includeContent: true,
		source: sourceId
	});
	return {
		...result,
		code,
		map: previousMap ? composeSourceMaps(rewriteMap, previousMap) : rewriteMap
	};
}
//#endregion
//#region src/plugins/core/lifecycle/load/requestGlobals.ts
const NORMAL_SFC_SCRIPT_RE = /<script(?![^>]*setup)[^>]*>/u;
function resolvePassiveRequestGlobalsTargets(code, requestGlobalsTargets) {
	if (requestGlobalsTargets.length > 0) return [];
	return resolveManualRequestGlobalsTargets(code);
}
function resolveRequestGlobalsTargetsForCode(code, sourceId, options) {
	const requestGlobalsTargets = options?.targets ?? [];
	if (requestGlobalsTargets.length === 0) return [];
	if (options?.mode === "auto") {
		if (sourceId.endsWith(".vue") && code.includes("<script setup") && !NORMAL_SFC_SCRIPT_RE.test(code)) return [];
		return resolveAutoRequestGlobalsTargets(code, requestGlobalsTargets);
	}
	return requestGlobalsTargets;
}
function injectRequestGlobalsIntoLoadResult(result, sourceId, targets, options) {
	if (!result || typeof result !== "object" || !("code" in result) || typeof result.code !== "string" || targets.length === 0) return result;
	if (sourceId.endsWith(".vue")) {
		const injection = resolveRequestGlobalsSfcInjection(result.code, targets, options);
		if (!injection) return result;
		return editCodeTransformResult(result, sourceId, (magicString) => magicString.appendLeft(injection.index, injection.code), { sourceMap: options?.sourceMap });
	}
	const injection = createInjectRequestGlobalsCode(targets, options);
	return editCodeTransformResult(result, sourceId, (magicString) => magicString.prepend(injection), { sourceMap: options?.sourceMap });
}
//#endregion
//#region src/plugins/core/lifecycle/load/weapi.ts
function resolveInjectWeapiOptions$1(configService) {
	const injectWeapi = configService.weappViteConfig?.injectWeapi;
	if (!injectWeapi) return null;
	if (!(typeof injectWeapi === "object" ? injectWeapi.enabled === true : injectWeapi === true)) return null;
	return {
		globalName: typeof injectWeapi === "object" && injectWeapi.globalName ? injectWeapi.globalName : "wpi",
		replaceWx: typeof injectWeapi === "object" ? injectWeapi.replaceWx === true : false
	};
}
function createWeapiInjectionCode(options) {
	const globalKey = JSON.stringify(options.globalName);
	const platform = JSON.stringify(options.platform);
	const hostCandidatesExpression = createWeapiHostCandidatesExpression();
	const nativeApiResolveExpression = [`(${getMiniProgramGlobalKeys().map((globalKey) => `__weappResolveRootGlobal(${JSON.stringify(globalKey)})`).join(" ?? ")}`, ` ?? ${createMiniProgramTopLevelResolveExpression()})`].join("");
	const nativeApiFallbackExpression = [`(${getMiniProgramGlobalKeys().map((globalKey) => `__weappResolveGlobal(${JSON.stringify(globalKey)})`).join(" ?? ")}`, ` ?? ${createMiniProgramTopLevelResolveExpression()})`].join("");
	const replaceLines = options.replaceWx ? [
		`    for (const __weappGlobal of __weappGlobals) {`,
		...getMiniProgramRuntimeGlobalKeys().map((globalKey) => `      __weappGlobal.${globalKey} = __weappInstance`),
		`      if (__weappPlatformKey) {`,
		`        __weappGlobal[__weappPlatformKey] = __weappInstance`,
		`      }`,
		`    }`
	] : [];
	return [
		`import { wpi as __weappWpi } from '@wevu/api'`,
		`const __weappRootGlobals = ${hostCandidatesExpression}`,
		`const __weappResolveRootGlobal = key => __weappRootGlobals.map(item => item && item[key]).find(Boolean)`,
		`const __weappNativeApi = ${nativeApiResolveExpression}`,
		`const __weappGlobals = __weappRootGlobals.length ? __weappRootGlobals : [__weappNativeApi].filter(Boolean)`,
		`const __weappGlobal = __weappGlobals[0] || {}`,
		`const __weappResolveGlobal = key => __weappGlobals.map(item => item && item[key]).find(Boolean)`,
		`const __weappPlatformKey = ${platform}`,
		`if (__weappGlobal) {`,
		`  const __weappExistingWpi = __weappResolveGlobal(${globalKey})`,
		`  const __weappInstance = __weappExistingWpi || __weappWpi`,
		`  if (!__weappExistingWpi) {`,
		`    const __weappRawApi = (__weappPlatformKey ? __weappResolveGlobal(__weappPlatformKey) : undefined) ?? ${nativeApiFallbackExpression}`,
		`    if (__weappRawApi && __weappRawApi !== __weappWpi) {`,
		`      __weappWpi.setAdapter(__weappRawApi, __weappPlatformKey)`,
		`    }`,
		`    __weappGlobal[${globalKey}] = __weappWpi`,
		`  }`,
		...replaceLines,
		`}`,
		""
	].join("\n");
}
function replacePlatformApiAccess$1(code, globalName, options) {
	return rewriteMiniProgramPlatformApiAccess(code, globalName, options);
}
function replacePlatformApiInLoadResult(result, options, astEngine, parserLike) {
	if (!options.replaceWx) return result;
	if (!result || typeof result !== "object" || !("code" in result) || typeof result.code !== "string") return result;
	const replacedCode = replacePlatformApiAccess$1(result.code, options.globalName, {
		engine: astEngine,
		parserLike
	});
	if (replacedCode === result.code) return result;
	return {
		...result,
		code: replacedCode
	};
}
function resolveRootEntryBasename(state) {
	if (!state.ctx.configService.pluginOnly) return "app";
	const pluginMain = typeof state.ctx.scanService?.pluginJson?.main === "string" ? state.ctx.scanService.pluginJson.main.trim() : "";
	return pluginMain ? removeExtensionDeep(pluginMain) : "app";
}
//#endregion
//#region src/plugins/core/lifecycle/load/options.ts
const LOCAL_IMPORT_RE = /\bimport\s+(?:[\s\S]*?\s+from\s+)?(['"])([^'"\n]+)\1/g;
async function collectImportedVueComponents(state, candidates) {
	const { absoluteSrcRoot } = state.ctx.configService;
	const importedComponents = /* @__PURE__ */ new Set();
	for (const candidate of candidates) {
		if (candidate.type !== "page" || candidate.entry.includes(":")) continue;
		const pageBase = path.resolve(absoluteSrcRoot, candidate.entry);
		const pageSource = (await findJsEntry(pageBase)).path ?? await findVueEntry(pageBase);
		if (!pageSource || !await fs$1.pathExists(pageSource)) continue;
		let source;
		try {
			source = await fs$1.readFile(pageSource, "utf8");
		} catch {
			continue;
		}
		for (const match of source.matchAll(LOCAL_IMPORT_RE)) {
			const importSource = match[2];
			if (!importSource.startsWith(".") && !importSource.startsWith("/")) continue;
			const importedBase = path.resolve(path.dirname(pageSource), importSource);
			const importedVue = importedBase.endsWith(".vue") ? importedBase : await findVueEntry(importedBase);
			if (!importedVue || !await fs$1.pathExists(importedVue)) continue;
			const relativeEntry = path.relative(absoluteSrcRoot, removeExtensionDeep(importedVue)).replaceAll("\\", "/");
			if (relativeEntry && !relativeEntry.startsWith("../")) importedComponents.add(relativeEntry);
		}
	}
	return [...importedComponents];
}
async function collectMainLogicalInputs(state, appEntry) {
	const { absoluteSrcRoot } = state.ctx.configService;
	const appJson = normalizeAppJson(appEntry.json ?? {});
	const inputs = { app: {
		input: appEntry.path,
		type: "app"
	} };
	const candidates = [];
	for (const entry of appJson.pages ?? []) candidates.push({
		entry,
		type: "page"
	});
	for (const subPackage of [...appJson.subPackages ?? [], ...appJson.subpackages ?? []]) {
		if (subPackage.independent || typeof subPackage.root !== "string") continue;
		for (const entry of subPackage.pages ?? []) candidates.push({
			entry: path.join(subPackage.root, entry),
			type: "page"
		});
	}
	for (const entry of Object.values(appJson.usingComponents ?? {})) if (typeof entry === "string") candidates.push({
		entry,
		type: "component"
	});
	if (appJson.tabBar?.custom) candidates.push({
		entry: "custom-tab-bar/index",
		type: "component"
	});
	if (appJson.appBar) candidates.push({
		entry: "app-bar/index",
		type: "component"
	});
	for (const entry of await collectImportedVueComponents(state, candidates)) candidates.push({
		entry,
		type: "component"
	});
	for (const { entry: rawEntry, type } of candidates) {
		if (!rawEntry || rawEntry.includes(":")) continue;
		const name = removeExtensionDeep(rawEntry).replace(/^[/\\]+/, "");
		if (!name || inputs[name]) continue;
		inputs[name] = {
			input: path.resolve(absoluteSrcRoot, name),
			source: rawEntry,
			type
		};
	}
	return inputs;
}
async function resolveLogicalInput(pluginContext, source, importer) {
	const resolveSource = async (id, sourceImporter) => {
		if (typeof pluginContext?.resolve !== "function") return;
		const resolved = await pluginContext.resolve(id, sourceImporter);
		return resolved?.external ? void 0 : resolved?.id;
	};
	const resolvePhysicalEntry = async (id) => {
		const normalized = normalizeFsResolvedId(id);
		if (path.extname(normalized)) return id;
		const localEntry = (await findJsEntry(normalized)).path ?? await findVueEntry(normalized);
		if (!localEntry) return;
		return await resolveSource(localEntry, importer) ?? localEntry;
	};
	const primaryEntry = await resolvePhysicalEntry(await resolveSource(source.input, importer) ?? source.input);
	if (primaryEntry) return primaryEntry;
	if (!source.source || typeof pluginContext?.resolve !== "function") return;
	const fallbackId = await resolveSource(source.source, importer);
	return fallbackId ? await resolvePhysicalEntry(fallbackId) : void 0;
}
async function resolvePluginOnlyInput(state) {
	const { scanService } = state.ctx;
	const pluginJson = scanService.pluginJson;
	const pluginJsonPath = scanService.pluginJsonPath;
	const pluginMain = typeof pluginJson?.main === "string" ? pluginJson.main.trim() : "";
	if (!pluginJsonPath || !pluginMain) throw new Error("插件独立构建需要在 plugin.json 中声明有效的 main 入口。");
	const pluginEntryBase = path.resolve(path.dirname(pluginJsonPath), removeExtensionDeep(pluginMain));
	const { path: pluginEntryPath } = await findJsEntry(pluginEntryBase);
	const pluginVueEntryPath = pluginEntryPath ? void 0 : await findVueEntry(pluginEntryBase);
	const resolvedPath = pluginEntryPath ?? pluginVueEntryPath;
	if (!resolvedPath) throw new Error(`未找到插件主入口 ${pluginMain} 对应的脚本文件。`);
	return { [removeExtensionDeep(pluginMain)]: resolvedPath };
}
function createOptionsHook(state) {
	const { ctx, subPackageMeta } = state;
	const { scanService, configService, buildService } = ctx;
	return async function options(options) {
		if (this) ctx.moduleGraphService?.bindPluginContext(this);
		state.hmrRootInputIds ??= /* @__PURE__ */ new Set();
		state.hmrRootInputIds.clear();
		let scannedInput;
		if (subPackageMeta) scannedInput = subPackageMeta.entries.reduce((acc, entry) => {
			acc[entry] = {
				input: path.resolve(configService.absoluteSrcRoot, entry),
				type: "page"
			};
			return acc;
		}, {});
		else if (configService.weappLibConfig?.enabled) {
			const libState = ctx.runtimeState.lib;
			const entries = await resolveWeappLibEntries(configService, configService.weappLibConfig);
			const outputMap = /* @__PURE__ */ new Map();
			libState.entries.clear();
			scannedInput = entries.reduce((acc, entry) => {
				acc[entry.name] = {
					input: entry.input,
					type: "component"
				};
				outputMap.set(entry.relativeBase, entry.outputBase);
				const normalized = normalizeFsResolvedId(entry.input);
				if (normalized) libState.entries.set(normalized, entry);
				return acc;
			}, {});
			libState.enabled = true;
			configService.options = {
				...configService.options,
				weappLibOutputMap: outputMap
			};
		} else {
			const libState = ctx.runtimeState.lib;
			libState.enabled = false;
			libState.entries.clear();
			if (configService.options.weappLibOutputMap) configService.options = {
				...configService.options,
				weappLibOutputMap: void 0
			};
			const appEntry = await scanService.loadAppEntry();
			if (configService.pluginOnly) scannedInput = Object.fromEntries(Object.entries(await resolvePluginOnlyInput(state)).map(([name, input]) => [name, {
				input,
				type: "app"
			}]));
			else {
				const independentState = ctx.runtimeState.build.independent;
				independentState.pendingOutputs = [];
				scanService.loadSubPackages();
				const dirtyIndependentRoots = scanService.drainIndependentDirtyRoots();
				const previousSubPackageRoot = configService.currentSubPackageRoot;
				for (const root of dirtyIndependentRoots) {
					const meta = scanService.independentSubPackageMap.get(root);
					if (!meta) continue;
					const buildTask = buildService.buildIndependentBundle(root, meta);
					buildTask.catch(() => {});
					independentState.pendingOutputs.push(buildTask);
					try {
						await buildTask;
					} catch {}
				}
				if (configService.currentSubPackageRoot !== previousSubPackageRoot) configService.options = {
					...configService.options,
					currentSubPackageRoot: previousSubPackageRoot
				};
				scannedInput = await collectMainLogicalInputs(state, appEntry);
			}
		}
		const logicalInput = {};
		for (const [name, source] of Object.entries(scannedInput)) {
			const sourceId = await resolveLogicalInput(this, source, state.ctx.scanService.appEntry?.path);
			if (!sourceId) continue;
			logicalInput[name] = createLogicalEntryId(sourceId, source.type);
			const normalized = normalizeFsResolvedId(sourceId);
			if (normalized) {
				state.hmrRootInputIds.add(normalizeSourceId(normalized));
				if (source.type !== "app" && state.entriesMap) {
					const relativeBase = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(normalized));
					state.entriesMap.set(relativeBase, {
						path: normalized,
						type: source.type === "page" ? "page" : "component"
					});
				}
			}
		}
		options.input = logicalInput;
	};
}
//#endregion
//#region src/plugins/core/lifecycle/load/index.ts
function createLoadHook(state) {
	const { ctx, subPackageMeta, loadEntry, loadedEntrySet, resolvedEntryMap } = state;
	const { configService } = ctx;
	const astEngine = resolveAstEngine(configService.weappViteConfig);
	const pathExistsTtlMs = getPathExistsTtlMs(configService);
	const weapiResolution = {
		checked: false,
		available: false
	};
	const injectRequestGlobalsOptions = resolveRequestRuntimeOptions({
		appPrelude: configService.weappViteConfig?.appPrelude,
		webRuntime: configService.weappViteConfig?.injectWebRuntimeGlobals,
		injectRequestGlobals: configService.weappViteConfig?.injectRequestGlobals
	}, configService.packageJson, (message) => logger_default.warn(message));
	function recordLoadDuration(key, startedAt) {
		recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, key, performance.now() - startedAt);
	}
	async function loadProfiledEntry(pluginCtx, sourceId, type) {
		const startedAt = performance.now();
		try {
			return await loadEntry.call(pluginCtx, sourceId, type);
		} finally {
			recordLoadDuration("entryLoadMs", startedAt);
		}
	}
	function resolveRequestGlobalsTargets(result, sourceId) {
		const startedAt = performance.now();
		try {
			return result && typeof result === "object" && "code" in result ? resolveRequestGlobalsTargetsForCode(result.code, sourceId, injectRequestGlobalsOptions) : injectRequestGlobalsOptions?.targets ?? [];
		} finally {
			recordLoadDuration("requestGlobalsMs", startedAt);
		}
	}
	function resolvePassiveTargets(result, requestGlobalsTargets) {
		const startedAt = performance.now();
		try {
			return result && typeof result === "object" && "code" in result ? resolvePassiveRequestGlobalsTargets(result.code, requestGlobalsTargets) : [];
		} finally {
			recordLoadDuration("requestGlobalsMs", startedAt);
		}
	}
	function injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, options) {
		const startedAt = performance.now();
		try {
			return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, {
				...options,
				sourceMap: Boolean(configService.inlineConfig?.build?.sourcemap)
			});
		} finally {
			recordLoadDuration("requestGlobalsMs", startedAt);
		}
	}
	async function ensureWeapiAvailable(pluginCtx, importer) {
		if (weapiResolution.checked) return weapiResolution.available;
		weapiResolution.checked = true;
		if (typeof pluginCtx?.resolve !== "function") {
			weapiResolution.available = true;
			return true;
		}
		const startedAt = performance.now();
		const resolved = await pluginCtx.resolve("@wevu/api", importer);
		recordLoadDuration("weapiResolveMs", startedAt);
		if (!resolved) {
			logger_default.warn("[weapp-vite] 未找到 @wevu/api,已跳过 wpi 全局注入。");
			weapiResolution.available = false;
			return false;
		}
		weapiResolution.available = true;
		return true;
	}
	return async function load(id) {
		const loadStartedAt = performance.now();
		try {
			configService.weappViteConfig?.debug?.load?.(id, subPackageMeta);
			if (isCSSRequest(id)) {
				const parsed = parseRequest(id);
				if (parsed.query.wxss || parsed.query.nativeStyle) {
					const realPath = getCssRealPath(parsed);
					try {
						return { code: await readFile$1(realPath, { checkMtime: configService.isDev }) };
					} catch {}
				}
				return null;
			}
			const sourceId = normalizeFsResolvedId(id);
			const injectOptions = resolveInjectWeapiOptions$1(configService);
			if (configService.weappLibConfig?.enabled ? ctx.runtimeState.lib.entries.get(sourceId) : void 0) {
				const result = await loadProfiledEntry(this, sourceId, "component");
				const requestGlobalsTargets = resolveRequestGlobalsTargets(result, sourceId);
				if (requestGlobalsTargets.length === 0) return result;
				return injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, {
					localBindings: true,
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults
				});
			}
			const relativeBasename = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(sourceId));
			const declaredEntryType = state.entriesMap?.get(relativeBasename)?.type;
			const isDeclaredEntry = Boolean(declaredEntryType);
			if (configService.isDev && ctx.runtimeState?.build?.hmr?.profile?.event === "delete" && isDeclaredEntry && sourceId && !sourceId.startsWith("\0") && await pathExists(sourceId, { ttlMs: pathExistsTtlMs }) === false) return {
				code: sourceId.endsWith(".vue") ? "<template />" : "",
				map: { mappings: "" }
			};
			if (relativeBasename === resolveRootEntryBasename(state)) {
				const result = await loadProfiledEntry(this, sourceId, "app");
				if (configService.isDev && sourceId && !sourceId.startsWith("\0")) resolvedEntryMap.set(sourceId, { id: sourceId });
				const requestGlobalsTargets = resolveRequestGlobalsTargets(result, sourceId);
				const passiveRequestGlobalsTargets = resolvePassiveTargets(result, requestGlobalsTargets);
				if (requestGlobalsTargets.length === 0 && passiveRequestGlobalsTargets.length > 0) return injectRequestGlobalsProfiled(result, sourceId, passiveRequestGlobalsTargets, {
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults,
					passiveLocalBindings: true
				});
				if (!injectOptions || configService.weappLibConfig?.enabled) return injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, {
					localBindings: true,
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults
				});
				if (!await ensureWeapiAvailable(this, sourceId)) return injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, {
					localBindings: true,
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults
				});
				if (result && typeof result === "object" && "code" in result) {
					const requestGlobalsInjectedResult = injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, {
						localBindings: true,
						networkDefaults: injectRequestGlobalsOptions?.networkDefaults
					});
					const platform = getMiniProgramPlatformGlobalKey(configService.platform) ?? "";
					const injectedCode = createWeapiInjectionCode({
						globalName: injectOptions.globalName,
						replaceWx: injectOptions.replaceWx,
						platform
					});
					return replacePlatformApiInLoadResult({
						...requestGlobalsInjectedResult,
						code: `${injectedCode}${requestGlobalsInjectedResult.code}`
					}, injectOptions, astEngine, this);
				}
				return result;
			}
			if (loadedEntrySet.has(sourceId) || isDeclaredEntry || subPackageMeta?.entries.includes(relativeBasename)) {
				const loadType = declaredEntryType === "page" ? "page" : "component";
				const result = await loadProfiledEntry(this, sourceId, loadType);
				const requestGlobalsTargets = resolveRequestGlobalsTargets(result, sourceId);
				const passiveRequestGlobalsTargets = resolvePassiveTargets(result, requestGlobalsTargets);
				if (requestGlobalsTargets.length === 0 && passiveRequestGlobalsTargets.length > 0) return injectRequestGlobalsProfiled(result, sourceId, passiveRequestGlobalsTargets, {
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults,
					passiveLocalBindings: true
				});
				if (!injectOptions || !injectOptions.replaceWx || configService.weappLibConfig?.enabled) return injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, {
					localBindings: true,
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults
				});
				if (!await ensureWeapiAvailable(this, sourceId)) return injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, {
					localBindings: true,
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults
				});
				return injectRequestGlobalsProfiled(replacePlatformApiInLoadResult(result, injectOptions, astEngine, this), sourceId, requestGlobalsTargets, {
					localBindings: true,
					networkDefaults: injectRequestGlobalsOptions?.networkDefaults
				});
			}
		} finally {
			recordLoadDuration("coreLoadMs", loadStartedAt);
		}
	};
}
//#endregion
//#region src/plugins/core/lifecycle/logicalEntry.ts
function resolveEntryRecord(state, sourceId) {
	const relativeBase = removeExtensionDeep(state.ctx.configService.relativeAbsoluteSrcRoot(sourceId));
	return state.entriesMap.get(relativeBase) ?? state.entriesMap.get(removeExtensionDeep(sourceId));
}
async function resolveLocalModule(pluginContext, source, importer) {
	const localBase = path.isAbsolute(source) ? source : source.startsWith("/") ? source : path.resolve(path.dirname(importer), source);
	const resolved = await pluginContext.resolve(localBase, importer);
	if (resolved?.id) return normalizeFsResolvedId(resolved.id);
	if (path.isAbsolute(localBase) && !path.extname(localBase)) {
		const localEntry = (await findJsEntry(localBase)).path ?? await findVueEntry(localBase);
		if (localEntry) return normalizeFsResolvedId((await pluginContext.resolve(localEntry, importer))?.id ?? localEntry);
	}
}
async function collectUsingComponentDependencies(state, pluginContext, ownerId, json) {
	if (!json || typeof json !== "object" || !("usingComponents" in json)) return [];
	const usingComponents = json.usingComponents;
	if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return [];
	const dependencies = [];
	for (const value of Object.values(usingComponents)) {
		if (typeof value !== "string" || !value || value.includes("://")) continue;
		const outputKey = removeExtensionDeep(value).replace(/^\/+/, "");
		const resolved = await resolveLocalModule(pluginContext, state.ctx.runtimeState.build.hmr.externalComponentEntryMap.get(outputKey) ?? (value.startsWith("/") ? path.resolve(state.ctx.configService.absoluteSrcRoot, value.slice(1)) : value), ownerId);
		if (resolved) dependencies.push({
			kind: "using-component",
			sourceId: resolved
		});
	}
	return dependencies;
}
function collectTemplateDependencies(state, templatePath) {
	if (!templatePath) return [];
	const dependencies = [];
	for (const sourceId of state.ctx.wxmlService?.depsMap?.get(templatePath) ?? []) dependencies.push({
		kind: isTemplate(sourceId) ? "template" : "wxs",
		sourceId: normalizeFsResolvedId(sourceId)
	});
	return dependencies;
}
async function collectLogicalEntryDependencies(state, pluginContext, ownerId) {
	const pendingDependencies = state.ctx.moduleGraphService.getEntryDependencies(ownerId);
	const dependencies = [];
	const addExistingDependency = async (kind, sourceId) => {
		if (sourceId && await pathExists(sourceId)) dependencies.push({
			kind,
			sourceId: normalizeFsResolvedId(sourceId)
		});
	};
	for (const dependency of pendingDependencies) await addExistingDependency(dependency.kind, dependency.sourceId);
	await addExistingDependency("script", ownerId);
	const entry = resolveEntryRecord(state, ownerId);
	const [jsonEntry, templateEntry, styleEntry] = await Promise.all([
		findJsonEntry(ownerId),
		findTemplateEntry(ownerId, state.ctx.configService.platform),
		findCssEntry(ownerId, state.ctx.configService.platform)
	]);
	await addExistingDependency("json", entry?.jsonPath ?? jsonEntry.path);
	await addExistingDependency("json", entry && "sitemapJsonPath" in entry ? entry.sitemapJsonPath : void 0);
	await addExistingDependency("json", entry && "themeJsonPath" in entry ? entry.themeJsonPath : void 0);
	const templatePath = entry && "templatePath" in entry ? entry.templatePath : templateEntry.path;
	await addExistingDependency("template", templatePath);
	await addExistingDependency("style", styleEntry.path);
	if (templatePath) await state.ctx.wxmlService?.scan(templatePath);
	dependencies.push(...collectTemplateDependencies(state, templatePath));
	dependencies.push(...await collectUsingComponentDependencies(state, pluginContext, ownerId, entry?.json));
	for (const kind of [
		"json",
		"jsx",
		"layout",
		"script",
		"style",
		"template",
		"using-component",
		"wxs"
	]) state.ctx.moduleGraphService.replaceEntryDependencies(ownerId, kind, dependencies.filter((dependency) => dependency.kind === kind).map((dependency) => dependency.sourceId));
	return dependencies;
}
function createLogicalEntryResolveHook(state) {
	return async function resolveId(id, importer) {
		const resolvedId = resolveVirtualModuleId(id);
		if (resolvedId) return {
			id: resolvedId,
			moduleSideEffects: "no-treeshake"
		};
		const sidecarSource = parseSidecarSourceRequest(id);
		if (!sidecarSource) return null;
		state.ctx.moduleGraphService.bindPluginContext(this);
		return {
			id: (await this.resolve(id, importer, { skipSelf: true }))?.id ?? createSidecarSourceSpecifier(sidecarSource.ownerId, sidecarSource.sourceId, sidecarSource.kind),
			moduleSideEffects: "no-treeshake"
		};
	};
}
function createLogicalEntryLoadHook(state) {
	return async function load(id) {
		const logicalEntry = parseLogicalEntryId(id);
		if (logicalEntry) {
			state.ctx.moduleGraphService.bindPluginContext(this);
			if (state.ctx.configService.isDev) await state.loadEntry.call(this, logicalEntry.sourceId, logicalEntry.type === "app" ? "app" : logicalEntry.type === "page" ? "page" : "component");
			return {
				code: createLogicalEntryModuleCode(logicalEntry, await collectLogicalEntryDependencies(state, this, logicalEntry.sourceId)),
				moduleSideEffects: "no-treeshake"
			};
		}
		const sidecar = parseSidecarModuleId(id);
		if (sidecar) return {
			code: createSidecarModuleCode(sidecar.ownerId, sidecar.sourceId, sidecar.kind),
			meta: { weappViteSidecar: sidecar },
			moduleSideEffects: "no-treeshake"
		};
		return null;
	};
}
//#endregion
//#region src/plugins/core/lifecycle/transform/platform.ts
function replacePlatformApiAccess(code, globalName, options) {
	return rewriteMiniProgramPlatformApiAccess(code, globalName, options);
}
//#endregion
//#region src/plugins/core/lifecycle/transform/shared.ts
function resolveInjectWeapiOptions(configService) {
	const injectWeapi = configService.weappViteConfig?.injectWeapi;
	if (!injectWeapi) return null;
	if (!(typeof injectWeapi === "object" ? injectWeapi.enabled === true : injectWeapi === true) || typeof injectWeapi !== "object" || injectWeapi.replaceWx !== true) return null;
	return { globalName: injectWeapi.globalName?.trim() || "wpi" };
}
function shouldTransformId(id, options) {
	if (isCSSRequest(id)) return false;
	if (parseRequest(id).query.type === "style") return false;
	const sourceId = normalizeFsResolvedId(id);
	if (!sourceId) return false;
	if (sourceId === options.absoluteSrcRoot) return true;
	if (sourceId.startsWith(`${options.absoluteSrcRoot}/`)) return true;
	return options.isEntry?.(sourceId) === true;
}
//#endregion
//#region src/plugins/core/lifecycle/transform/index.ts
function mayContainManualRequestGlobalsInstall(code) {
	return code.includes("installRequestGlobals") && (code.includes("@wevu/web-apis") || code.includes("weapp-vite/web-apis"));
}
function createTransformHook(state) {
	const { configService } = state.ctx;
	const astEngine = resolveAstEngine(configService.weappViteConfig);
	const injectOptions = resolveInjectWeapiOptions(configService);
	const injectRequestGlobalsOptions = resolveRequestRuntimeOptions({
		appPrelude: configService.weappViteConfig?.appPrelude,
		webRuntime: configService.weappViteConfig?.injectWebRuntimeGlobals,
		injectRequestGlobals: configService.weappViteConfig?.injectRequestGlobals
	}, configService.packageJson, (message) => logger_default.warn(message));
	function resolveRequestGlobalsTransformCode(id, code) {
		const requestGlobalsTargets = injectRequestGlobalsOptions?.targets?.length ? injectRequestGlobalsOptions.mode === "auto" ? resolveAutoRequestGlobalsTargets(code, injectRequestGlobalsOptions.targets) : injectRequestGlobalsOptions.targets : resolveManualRequestGlobalsTargets(code);
		if (requestGlobalsTargets.length === 0) return null;
		const passiveLocalBindings = !injectRequestGlobalsOptions?.targets?.length;
		if (code.includes("__weappViteInstallRequestGlobals") || code.includes(REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER$1)) return null;
		const sourceId = normalizeFsResolvedId(id);
		if (!sourceId) return null;
		const relativeBasename = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(sourceId));
		const declaredEntryType = state.entriesMap?.get(relativeBasename)?.type;
		const isLoadedEntry = state.loadedEntrySet?.has(sourceId) === true;
		const isRootEntry = relativeBasename === "app";
		if (!isLoadedEntry && declaredEntryType !== "page" && declaredEntryType !== "component") return null;
		if (isLoadedEntry && isRootEntry) return null;
		if (sourceId.endsWith(".vue") && code.includes("<")) return injectRequestGlobalsIntoSfc(code, requestGlobalsTargets, {
			localBindings: !passiveLocalBindings,
			networkDefaults: injectRequestGlobalsOptions?.networkDefaults,
			passiveLocalBindings
		});
		return `${createInjectRequestGlobalsCode(requestGlobalsTargets, {
			localBindings: !passiveLocalBindings,
			networkDefaults: injectRequestGlobalsOptions?.networkDefaults,
			passiveLocalBindings
		})}${code}`;
	}
	function mayNeedTransformWork(code) {
		const mayNeedRequestGlobals = injectRequestGlobalsOptions ? injectRequestGlobalsOptions.mode === "auto" ? mayContainRequestGlobalsUsageByText(code, injectRequestGlobalsOptions.targets) : true : false;
		return code.includes("import.meta") || mayNeedRequestGlobals || mayContainManualRequestGlobalsInstall(code) || Boolean(injectOptions && mayContainPlatformApiIdentifierByText(code));
	}
	return async function transform(code, id) {
		if (parseSidecarSourceRequest(id)) return null;
		if (!shouldTransformId(id, {
			absoluteSrcRoot: configService.absoluteSrcRoot,
			isEntry: (sourceId) => state.loadedEntrySet?.has(sourceId) === true || state.resolvedEntryMap?.has(sourceId) === true
		})) return null;
		if (!mayNeedTransformWork(code)) return null;
		const startedAt = performance.now();
		try {
			const sourceId = normalizeFsResolvedId(id);
			const relativeOutputPath = sourceId ? configService.relativeOutputPath?.(sourceId) ?? configService.relativeAbsoluteSrcRoot?.(sourceId) : void 0;
			const importMetaTransformOptions = relativeOutputPath ? {
				importMetaDefineRegistry: configService.importMetaDefineRegistry,
				extension: "js",
				relativePath: relativeOutputPath
			} : void 0;
			const importMetaCode = importMetaTransformOptions ? sourceId?.endsWith(".vue") ? replaceImportMetaAccessInSfc(code, importMetaTransformOptions) : replaceImportMetaAccess(code, importMetaTransformOptions) : code;
			const nextCode = resolveRequestGlobalsTransformCode(id, importMetaCode) ?? importMetaCode;
			if (!injectOptions) return nextCode === code ? null : {
				code: nextCode,
				map: null
			};
			const replaced = replacePlatformApiAccess(nextCode, injectOptions.globalName, {
				engine: astEngine,
				parserLike: this
			});
			if (replaced === code) return null;
			return {
				code: replaced,
				map: null
			};
		} finally {
			const durationMs = performance.now() - startedAt;
			recordHmrProfileDuration(state.ctx.runtimeState?.build?.hmr?.profile, "transformMs", durationMs);
			recordHmrProfileDuration(state.ctx.runtimeState?.build?.hmr?.profile, "coreTransformMs", durationMs);
		}
	};
}
//#endregion
//#region src/plugins/vue/transform/appShell.ts
const APP_VUE_FILE_RE = /[\\/]app\.vue$/;
function isAppVueFile(filename) {
	return APP_VUE_FILE_RE.test(filename);
}
function hasAppShellTemplate(result) {
	return Boolean(result?.template?.trim());
}
function resolveAppShellBase(configService) {
	return path.join(configService.absoluteSrcRoot, WEVU_APP_SHELL_COMPONENT_BASE);
}
function resolveAppShellRelativeBase(configService) {
	return configService.relativeOutputPath(resolveAppShellBase(configService));
}
function resolveAppShellImportPath(configService) {
	const relativeBase = resolveAppShellRelativeBase(configService);
	return relativeBase ? `/${toPosixPath(relativeBase)}` : void 0;
}
function resolveAppShellLayout(configService) {
	const importPath = resolveAppShellImportPath(configService);
	if (!importPath) return;
	return {
		file: normalizeWatchPath(resolveAppShellBase(configService)),
		importPath,
		kind: "vue",
		layoutName: "app-shell",
		tagName: WEVU_APP_SHELL_TAG_NAME
	};
}
function applyAppShell(result, filename, appShell) {
	if (!appShell || !result.template) return result;
	return applyPageLayout(result, filename, {
		file: appShell.file,
		importPath: appShell.importPath,
		kind: "vue",
		layoutName: "app-shell",
		tagName: appShell.tagName
	});
}
//#endregion
//#region src/plugins/core/lifecycle/vueEntryUpdate.ts
function createVueEntryUpdateInspector(state, normalizedId, options = {}) {
	const readFile = options.readFile ?? fs$1.readFile;
	let sourcePromise;
	let signatures;
	let changedBlocks;
	async function loadSource() {
		sourcePromise ??= readFile(normalizedId, "utf-8").catch(() => void 0);
		return await sourcePromise;
	}
	async function resolveSignatures() {
		const source = await loadSource();
		if (source === void 0) return;
		signatures ??= resolveVueSfcHmrSignatures(source, normalizedId);
		return signatures;
	}
	async function resolveChangedBlocks() {
		if (changedBlocks) return changedBlocks;
		const previous = state.ctx.runtimeState.build.hmr.vueEntrySfcSignatures.get(normalizedId);
		const current = (await resolveSignatures())?.blockSignatures;
		if (!previous || !current) return;
		changedBlocks = classifyVueSfcBlockChanges(previous, current);
		return changedBlocks;
	}
	return {
		async getChangedBlocks() {
			return await resolveChangedBlocks();
		},
		async isAppShellTopologyUpdate() {
			if (!isAppVueFile(normalizedId)) return false;
			const previous = state.ctx.runtimeState.build.hmr.vueEntryHasTemplate.get(normalizedId);
			if (previous === void 0) return false;
			const current = (await resolveSignatures())?.hasTemplate;
			return current !== void 0 && current !== previous;
		},
		async isJsonOnlyUpdate() {
			const blocks = await resolveChangedBlocks();
			return blocks?.length === 1 && blocks[0] === "config";
		},
		async isLocalAssetOnlyUpdate() {
			const blocks = await resolveChangedBlocks();
			return Boolean(blocks && !blocks.includes("script"));
		},
		async isStyleOnlyUpdate() {
			const blocks = await resolveChangedBlocks();
			return blocks?.length === 1 && blocks[0] === "style";
		},
		async isTailwindContentUpdate() {
			const previousTemplate = state.ctx.runtimeState.build.hmr.vueEntryTailwindTemplateContentSignatures?.get(normalizedId);
			const previousScript = state.ctx.runtimeState.build.hmr.vueEntryTailwindScriptContentSignatures?.get(normalizedId);
			if (!previousTemplate || !previousScript) return true;
			const signatures = await resolveSignatures();
			const currentTemplate = signatures?.tailwindTemplateContentSignature;
			if (!currentTemplate || currentTemplate !== previousTemplate) return true;
			const currentScript = signatures.tailwindScriptContentSignature;
			return !currentScript || currentScript !== previousScript;
		}
	};
}
//#endregion
//#region src/plugins/core/lifecycle/watch.ts
const ATOMIC_SAVE_RECHECK_DELAYS_MS = [20, 60];
const tailwindContentExtensions = /* @__PURE__ */ new Set([
	".vue",
	".wxml",
	".axml",
	".js",
	".jsx",
	".ts",
	".tsx",
	".mts",
	".cts",
	".mjs",
	".cjs"
]);
const TAILWIND_APP_STYLE_RE = /@import\s+['"]tailwindcss['"]|weapp-tailwindcss|tailwindcss\/vite/;
function resolveWatchPathKind(normalizedId) {
	const extension = path.extname(normalizedId);
	let configSuffix;
	let isScriptModuleSidecar = false;
	for (const suffix of configSuffixes) if (normalizedId.endsWith(suffix)) {
		configSuffix = suffix;
		break;
	}
	for (const suffix of watchedScriptModuleSuffixes) if (normalizedId.endsWith(suffix)) {
		isScriptModuleSidecar = true;
		break;
	}
	return {
		configSuffix,
		extension,
		isHtmlTemplate: normalizedId.endsWith(".html"),
		isScriptModuleSidecar,
		isStyle: watchedCssExts.has(extension),
		isTemplate: watchedTemplateExts.has(extension)
	};
}
function isOutputFileChange(state, normalizedId) {
	const outDir = state.ctx.configService?.outDir;
	if (!outDir) return false;
	const normalizedOutDir = normalizeFsResolvedId(outDir);
	return normalizedId === normalizedOutDir || normalizedId.startsWith(`${normalizedOutDir}/`);
}
function isAutoRoutesGeneratedFileChange(state, normalizedId) {
	const configService = state.ctx.configService;
	if (!configService) return false;
	return isAutoRoutesGeneratedPath(normalizedId, {
		cwd: configService.cwd,
		absoluteSrcRoot: configService.absoluteSrcRoot,
		managedOutputPaths: resolveAutoRoutesManagedOutputPaths(state.ctx)
	});
}
function isAutoRoutesPagesRelatedChange(state, normalizedId) {
	const configService = state.ctx.configService;
	if (!configService) return false;
	const { autoRoutesConfig, subPackageRoots } = resolveAutoRoutesMatcherContext(state.ctx);
	return isAutoRoutesPagesRelatedPath(normalizedId, {
		cwd: configService.cwd,
		absoluteSrcRoot: configService.absoluteSrcRoot,
		include: autoRoutesConfig.include,
		managedOutputPaths: resolveAutoRoutesManagedOutputPaths(state.ctx),
		subPackageRoots
	});
}
function isConfigFileDependencyChange(state, normalizedId) {
	return state.ctx.configService.configFileDependencies.some((dependency) => normalizeFsResolvedId(dependency) === normalizedId);
}
function shouldRefreshAppStyleForTailwindContent(state) {
	const configService = state.ctx.configService;
	return resolveTouchAppWxssEnabled({
		option: configService.weappViteConfig?.hmr?.touchAppWxss,
		platform: configService.platform,
		packageJson: configService.packageJson ?? {},
		cwd: configService.cwd
	});
}
async function isTailwindAppStyleSource(stylePath) {
	try {
		const source = await fs$1.readFile(stylePath, "utf8");
		return TAILWIND_APP_STYLE_RE.test(source);
	} catch {
		return false;
	}
}
function collectEmittedJsonPaths(state) {
	const emittedJsonPaths = /* @__PURE__ */ new Set();
	for (const record of state.jsonEmitFilesMap.values()) {
		const jsonPath = record.entry.jsonPath;
		if (jsonPath) emittedJsonPaths.add(normalizeFsResolvedId(jsonPath));
	}
	return emittedJsonPaths;
}
function isCurrentSubPackageFile(relativeSrc, subPackageMeta) {
	const root = subPackageMeta?.subPackage.root;
	return !root || relativeSrc === root || relativeSrc.startsWith(`${root}/`);
}
async function normalizeWatchEvent(id, event, options) {
	if (event === "create" && (options.loadedEntrySet.has(id) || options.resolvedEntryMap.has(id)) && await fs$1.pathExists(id)) return "update";
	if (event === "create" && (options.hasModule?.(id) || options.sharedChunkSourceModuleIds?.has(id)) && await fs$1.pathExists(id)) return "update";
	if (event === "create" && await fs$1.pathExists(id)) {
		const ext = path.extname(id);
		if (ext) {
			const basePath = id.slice(0, -ext.length);
			const primaryScript = await findJsEntry(basePath);
			const primaryScriptId = primaryScript.path ? normalizeFsResolvedId(primaryScript.path) : "";
			if (primaryScriptId && options.resolvedEntryMap.has(primaryScriptId)) return "update";
		}
		if (options.emittedJsonPaths?.has(id)) return "update";
	}
	if (event !== "delete") return event;
	for (const delayMs of ATOMIC_SAVE_RECHECK_DELAYS_MS) {
		if (await fs$1.pathExists(id)) return "update";
		await new Promise((resolve) => setTimeout(resolve, delayMs));
	}
	return await fs$1.pathExists(id) ? "update" : event;
}
function createBuildStartHook(state) {
	const { ctx, subPackageMeta, emitDirtyEntries, buildTarget } = state;
	const { configService } = ctx;
	const isPluginBuild = buildTarget === "plugin";
	return async function buildStart() {
		const startedAt = performance.now();
		try {
			ctx.moduleGraphService?.bindBuildContext(state, this);
			ctx.moduleGraphService?.bindPluginContext(this);
			resetTakeImportRegistry({ preserveSharedChunkNameCache: configService.isDev });
			if (configService.isDev) {
				let sharedChunkAffectedEntryCount = 0;
				for (const change of ctx.moduleGraphService?.getPendingChanges?.() ?? []) {
					const sharedChunkAffected = collectAffectedSharedChunkEntriesAndChunks(state, change.file);
					state.hmrState.affectedSharedChunkIds ??= /* @__PURE__ */ new Set();
					for (const chunkId of sharedChunkAffected.affectedChunks) state.hmrState.affectedSharedChunkIds.add(chunkId);
					for (const entryId of sharedChunkAffected.affectedEntries) {
						state.markEntryDirty(entryId, "dependency");
						sharedChunkAffectedEntryCount += 1;
					}
				}
				if (sharedChunkAffectedEntryCount) {
					const profile = ctx.runtimeState.build.hmr.profile;
					profile.dirtyReasonSummary = [...(profile.dirtyReasonSummary ?? []).filter((reason) => !reason.startsWith("shared-chunk-source:")), `shared-chunk-source:${sharedChunkAffectedEntryCount}`];
				}
				addNormalizedWatchFiles(this, configService.configFileDependencies);
				if (isPluginBuild) {
					if (configService.absolutePluginRoot) ensureSidecarWatcher(ctx, configService.absolutePluginRoot);
				} else {
					const rootDir = subPackageMeta ? path.resolve(configService.absoluteSrcRoot, subPackageMeta.subPackage.root) : configService.absoluteSrcRoot;
					ensureSidecarWatcher(ctx, rootDir);
					if (!subPackageMeta && configService.absolutePluginRoot) ensureSidecarWatcher(ctx, configService.absolutePluginRoot);
				}
			}
			await emitDirtyEntries.call(this);
		} finally {
			recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "buildStartMs", performance.now() - startedAt);
		}
	};
}
function isAppEntryAutoRoutesSignatureStale(state, normalizedId) {
	if (!isAppVueFile(normalizedId)) return false;
	const currentSignature = state.ctx.autoRoutesService?.getSignature?.();
	const previousSignature = state.ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature;
	if (typeof currentSignature !== "string") return false;
	return previousSignature !== currentSignature;
}
async function processChangedFile(state, id, event) {
	const { ctx, subPackageMeta, loadEntry, loadedEntrySet, resolvedEntryMap } = state;
	const { scanService, configService, buildService } = ctx;
	const normalizedId = normalizeFsResolvedId(id);
	if (isSkippableResolvedId(normalizedId)) return;
	const sidecarDirtyFiles = ctx.runtimeState.watcher?.sidecarDirtyFiles;
	const sidecarDirtyCause = sidecarDirtyFiles?.get(normalizedId);
	sidecarDirtyFiles?.delete(normalizedId);
	const importerGraphAffectedEntryIds = ctx.moduleGraphService.invalidate(normalizedId);
	const relativeSrc = configService.relativeAbsoluteSrcRoot(normalizedId);
	const affectedLayoutEntryIds = /* @__PURE__ */ new Set();
	const dirtyReasonStats = /* @__PURE__ */ new Map();
	const markEntryDirtyWithCause = (entryId, reason, cause) => {
		state.markEntryDirty(entryId, reason);
		const isJsxTemplateDependency = reason === "dependency" && /\.(?:jsx|tsx)$/.test(normalizedId);
		if (/\.(?:vue|jsx|tsx)$/.test(entryId) && (reason !== "dependency" || isJsxTemplateDependency)) {
			const hmr = ctx.runtimeState.build.hmr;
			hmr.dirtyVueEntryIds ??= /* @__PURE__ */ new Set();
			hmr.dirtyVueEntryIds.add(entryId);
		}
		dirtyReasonStats.set(cause, (dirtyReasonStats.get(cause) ?? 0) + 1);
	};
	const declaredEntryType = state.entriesMap.get(removeExtensionDeep(relativeSrc))?.type;
	const isDeletedMissingSelf = event === "delete" && !await fs$1.pathExists(normalizedId);
	const isAutoRouteFile = Boolean(ctx.autoRoutesService?.isRouteFile(normalizedId));
	const pathKind = resolveWatchPathKind(normalizedId);
	const isReactStaticTemplateUpdate = event === "update" && isReactStaticTemplateSource(configService.weappViteConfig?.react, normalizedId);
	const isScriptModuleSidecar = pathKind.isScriptModuleSidecar;
	const concreteChangedEntryId = isAppVueFile(normalizedId) && scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : normalizedId;
	const vueEntryUpdateInspector = normalizedId.endsWith(".vue") ? createVueEntryUpdateInspector(state, normalizedId) : void 0;
	let isAppShellTopologyChanged = false;
	let handledSidecarMetadataUpdate = false;
	const markScriptDirty = (scriptId, cause) => {
		const normalizedScriptId = normalizeFsResolvedId(scriptId);
		const reason = isLayoutSourcePath(configService.relativeAbsoluteSrcRoot(normalizedScriptId)) ? "dependency" : "direct";
		if (reason === "dependency") affectedLayoutEntryIds.add(normalizedScriptId);
		else markEntryDirtyWithCause(normalizedScriptId, cause === "sidecar-direct" || cause === "json-sidecar" || cause === "style-sidecar" ? "metadata" : reason, cause);
	};
	const markChangedEntryDirty = (reason, cause) => {
		if (isAppVueFile(normalizedId)) {
			if (concreteChangedEntryId !== normalizedId) {
				markEntryDirtyWithCause(concreteChangedEntryId, reason, cause);
				return;
			}
		}
		markEntryDirtyWithCause(normalizedId, reason, cause);
	};
	const markAppEntryForJsonEmit = () => {
		const appEntryId = scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : void 0;
		if (!appEntryId || !resolvedEntryMap.has(appEntryId)) return false;
		for (const jsonEmitRecord of state.jsonEmitFilesMap.values()) if (jsonEmitRecord.entry.jsonPath && normalizeFsResolvedId(jsonEmitRecord.entry.jsonPath) === normalizedId) {
			markEntryDirtyWithCause(appEntryId, "metadata", "json-sidecar");
			return true;
		}
		return false;
	};
	const markAppEntryForAutoRoutesTopology$1 = () => {
		return markAppEntryForAutoRoutesTopology(ctx, {
			loadEntry,
			resolvedEntryMap,
			markEntryDirty: (entryId) => markEntryDirtyWithCause(entryId, "direct", "auto-routes-topology")
		});
	};
	const markAppEntryForTailwindContent = async () => {
		if (event !== "update" || pathKind.isStyle || pathKind.configSuffix || !tailwindContentExtensions.has(pathKind.extension)) return false;
		if (vueEntryUpdateInspector && !await vueEntryUpdateInspector.isTailwindContentUpdate()) return false;
		if (!shouldRefreshAppStyleForTailwindContent(state)) return false;
		const appEntryId = scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : void 0;
		if (!appEntryId || appEntryId === normalizedId || !resolvedEntryMap.has(appEntryId)) return false;
		const styleEntry = await findCssEntry(appEntryId, ctx.configService.platform);
		if (!styleEntry.path) return false;
		if (!await isTailwindAppStyleSource(styleEntry.path)) return false;
		if (concreteChangedEntryId !== appEntryId && (loadedEntrySet.has(concreteChangedEntryId) || resolvedEntryMap.has(concreteChangedEntryId))) markEntryDirtyWithCause(concreteChangedEntryId, "direct", "tailwind-content");
		markEntryDirtyWithCause(appEntryId, "metadata", "tailwind-content");
		invalidateSharedStyleCache();
		return true;
	};
	if (isDeletedMissingSelf) {
		ctx.runtimeState.build.hmr.vueEntryHasTemplate.delete(normalizedId);
		ctx.runtimeState.build.hmr.vueEntrySfcSignatures.delete(normalizedId);
		ctx.runtimeState.build.hmr.vueEntryTailwindContentSignatures?.delete(normalizedId);
		ctx.runtimeState.build.hmr.vueEntryTailwindTemplateContentSignatures?.delete(normalizedId);
		ctx.runtimeState.build.hmr.vueEntryTailwindScriptContentSignatures?.delete(normalizedId);
	}
	if ((event === "create" || isDeletedMissingSelf) && isAutoRouteFile) {
		if (await ctx.autoRoutesService?.handleFileChange(normalizedId, event)) markAppEntryForAutoRoutesTopology$1();
	} else if ((event === "create" || isDeletedMissingSelf) && isAutoRoutesPagesRelatedChange(state, normalizedId)) {
		const didChangeRoutes = await ctx.autoRoutesService?.handleFileChange(normalizedId, event === "create" ? "create" : "delete");
		const currentSignature = ctx.autoRoutesService?.getSignature?.();
		const appEntrySignature = ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature;
		if (didChangeRoutes || typeof currentSignature === "string" && typeof appEntrySignature === "string" && currentSignature !== appEntrySignature) markAppEntryForAutoRoutesTopology$1();
	}
	if (event === "update" && isAppVueFile(normalizedId) && resolvedEntryMap.size) {
		const isJsonOnlyVueEntryUpdate = await vueEntryUpdateInspector.isJsonOnlyUpdate();
		const isAutoRoutesStaleAppEntry = isJsonOnlyVueEntryUpdate && isAppEntryAutoRoutesSignatureStale(state, normalizedId);
		isAppShellTopologyChanged = !isJsonOnlyVueEntryUpdate && await vueEntryUpdateInspector.isAppShellTopologyUpdate();
		const isLocalAssetOnlyVueEntryUpdate = !isJsonOnlyVueEntryUpdate && !isAppShellTopologyChanged && await vueEntryUpdateInspector.isLocalAssetOnlyUpdate();
		if (isAutoRoutesStaleAppEntry) loadEntry?.invalidateResolveCache?.();
		else if (!isJsonOnlyVueEntryUpdate && !isLocalAssetOnlyVueEntryUpdate) {
			loadEntry?.invalidateResolveCache?.();
			for (const entryId of resolvedEntryMap.keys()) {
				if (entryId === normalizedId || entryId === concreteChangedEntryId) continue;
				markEntryDirtyWithCause(entryId, "dependency", "app-shell-dependent");
			}
		}
	}
	invalidateFileCache(normalizedId);
	const isSidecarPath = Boolean(pathKind.isStyle || pathKind.isTemplate || pathKind.isHtmlTemplate || pathKind.configSuffix || isScriptModuleSidecar);
	if (event === "update" || event === "create" && isSidecarPath || isDeletedMissingSelf && isSidecarPath) {
		if (pathKind.isStyle && !isDeletedMissingSelf) await extractCssImportDependencies(ctx, normalizedId);
		if (pathKind.isTemplate && !isDeletedMissingSelf) {
			const wxmlService = ctx.wxmlService;
			if (wxmlService) await wxmlService.scan(normalizedId);
		}
		if (isSidecarPath && importerGraphAffectedEntryIds.size) {
			const cause = pathKind.configSuffix ? "json-sidecar" : pathKind.isStyle ? "style-sidecar" : "sidecar-direct";
			const isLayoutChange = isLayoutSourcePath(relativeSrc) || Array.from(importerGraphAffectedEntryIds).some((entryId) => isLayoutSourcePath(configService.relativeAbsoluteSrcRoot(entryId)));
			for (const entryId of importerGraphAffectedEntryIds) markEntryDirtyWithCause(entryId, isLayoutChange ? "dependency" : "metadata", isLayoutChange ? isLayoutSourcePath(configService.relativeAbsoluteSrcRoot(entryId)) ? "layout-self" : "layout-dependent" : cause);
			handledSidecarMetadataUpdate = true;
		} else if (isSidecarPath && event === "update") handledSidecarMetadataUpdate = true;
		else if (isSidecarPath && (event === "create" || isDeletedMissingSelf)) {
			const basePath = pathKind.configSuffix ? normalizedId.slice(0, -pathKind.configSuffix.length) : pathKind.extension ? normalizedId.slice(0, -pathKind.extension.length) : normalizedId;
			const primaryEntry = (await findJsEntry(basePath)).path ?? (pathKind.isStyle ? await findVueEntry(basePath) : void 0);
			if (primaryEntry) {
				markScriptDirty(primaryEntry, pathKind.configSuffix ? "json-sidecar" : pathKind.isStyle ? "style-sidecar" : "sidecar-direct");
				handledSidecarMetadataUpdate = true;
			} else if (pathKind.configSuffix && markAppEntryForJsonEmit()) handledSidecarMetadataUpdate = true;
			else {
				ctx.moduleGraphService.requestTopologyRescan(event === "create" ? "sidecar-create" : "sidecar-delete", normalizedId);
				if (ctx.moduleGraphService.consumeTopologyRescan()) {
					scanService.markDirty();
					loadEntry?.invalidateResolveCache?.();
					for (const entryId of resolvedEntryMap.keys()) if (isCurrentSubPackageFile(configService.relativeAbsoluteSrcRoot(entryId), subPackageMeta)) markEntryDirtyWithCause(entryId, "dependency", "topology-full-rescan");
					handledSidecarMetadataUpdate = true;
				}
			}
		}
	}
	if (event === "update" && isLayoutSourcePath(relativeSrc) && (loadedEntrySet.has(normalizedId) || resolvedEntryMap.has(normalizedId))) affectedLayoutEntryIds.add(normalizedId);
	if (event === "update" && affectedLayoutEntryIds.size) {
		if (!resolvedEntryMap.size) {
			for (const entryId of affectedLayoutEntryIds) markEntryDirtyWithCause(entryId, "dependency", "layout-self");
			return [...dirtyReasonStats.entries()].map(([cause, count]) => `${cause}:${count}`);
		}
		for (const entryId of importerGraphAffectedEntryIds) markEntryDirtyWithCause(entryId, "dependency", affectedLayoutEntryIds.has(entryId) ? "layout-self" : "layout-dependent");
		return [...dirtyReasonStats.entries()].map(([cause, count]) => `${cause}:${count}`);
	}
	if (!isDeletedMissingSelf && isCurrentSubPackageFile(relativeSrc, subPackageMeta) && !handledSidecarMetadataUpdate && (loadedEntrySet.has(normalizedId) || loadedEntrySet.has(concreteChangedEntryId) || resolvedEntryMap.has(normalizedId) || resolvedEntryMap.has(concreteChangedEntryId) || declaredEntryType === "page" || declaredEntryType === "component")) {
		const isJsonOnlyVueEntryUpdate = event === "update" && vueEntryUpdateInspector ? await vueEntryUpdateInspector.isJsonOnlyUpdate() : false;
		const isAutoRoutesStaleAppEntry = isJsonOnlyVueEntryUpdate && isAppEntryAutoRoutesSignatureStale(state, normalizedId);
		const isLocalAssetOnlyVueEntryUpdate = !isJsonOnlyVueEntryUpdate && !isAppShellTopologyChanged && event === "update" && (vueEntryUpdateInspector ? await vueEntryUpdateInspector.isLocalAssetOnlyUpdate() : false);
		const isStyleOnlyVueEntryUpdate = isLocalAssetOnlyVueEntryUpdate && (vueEntryUpdateInspector ? await vueEntryUpdateInspector.isStyleOnlyUpdate() : false);
		markChangedEntryDirty(sidecarDirtyCause ? "metadata" : isJsonOnlyVueEntryUpdate && !isAutoRoutesStaleAppEntry || isLocalAssetOnlyVueEntryUpdate ? "metadata" : "direct", sidecarDirtyCause ?? (isReactStaticTemplateUpdate ? "react-template" : isJsonOnlyVueEntryUpdate ? isAutoRoutesStaleAppEntry ? "entry-auto-routes" : "entry-json-only" : isAppShellTopologyChanged ? "entry-direct" : isLocalAssetOnlyVueEntryUpdate ? isStyleOnlyVueEntryUpdate ? "entry-style-only" : "entry-local-asset" : "entry-direct"));
	} else if (!handledSidecarMetadataUpdate && importerGraphAffectedEntryIds.size) for (const entryId of importerGraphAffectedEntryIds) markEntryDirtyWithCause(entryId, "dependency", isReactStaticTemplateUpdate ? "react-template" : "importer-graph");
	else if (!handledSidecarMetadataUpdate && event === "update" && /\.(?:vue|jsx|tsx)$/.test(normalizedId) && resolvedEntryMap.has(normalizedId)) markChangedEntryDirty("direct", "entry-direct");
	await markAppEntryForTailwindContent();
	const relativeCwd = configService.relativeCwd(normalizedId);
	let handledByIndependentWatcher = false;
	let independentMeta;
	const isConfigDependency = isConfigFileDependencyChange(state, normalizedId);
	if (isConfigDependency) {
		loadEntry?.invalidateResolveCache?.();
		scanService.markDirty();
		buildService.requestConfigRestart?.(state.buildTarget);
		for (const entryId of resolvedEntryMap.keys()) markEntryDirtyWithCause(entryId, "direct", "config-restart");
	}
	if (event === "create" || event === "delete") {
		loadEntry?.invalidateResolveCache?.();
		await invalidateEntryForSidecar(ctx, normalizedId, event);
	}
	if (!subPackageMeta && !configService.weappLibConfig?.enabled) {
		const isMultiPlatformEnabled = configService.multiPlatform.enabled;
		const platform = configService.platform ?? DEFAULT_MP_PLATFORM;
		const projectConfigFileName = getProjectConfigFileName(platform);
		const projectPrivateConfigFileName = getProjectPrivateConfigFileName(platform);
		let shouldMarkProjectConfigDirty = relativeCwd === projectConfigFileName || relativeCwd === projectPrivateConfigFileName;
		if (isMultiPlatformEnabled) {
			const platformConfigPrefix = `${resolveMultiPlatformProjectConfigDir(configService.multiPlatform, platform)}/`;
			shouldMarkProjectConfigDirty = relativeCwd.startsWith(platformConfigPrefix);
		}
		if (!isConfigDependency && (relativeSrc === "app.json" || shouldMarkProjectConfigDirty)) scanService.markDirty();
		let independentRoot;
		for (const root of scanService.independentSubPackageMap.keys()) if (relativeSrc.startsWith(`${root}/`)) {
			independentRoot = root;
			break;
		}
		if (independentRoot) {
			independentMeta = scanService.independentSubPackageMap.get(independentRoot);
			buildService.invalidateIndependentOutput(independentRoot);
			scanService.markIndependentDirty(independentRoot);
			handledByIndependentWatcher = true;
			if (independentMeta?.watchSharedStyles !== false) invalidateSharedStyleCache();
		}
	}
	if (subPackageMeta && dirtyReasonStats.size > 0) {
		if (subPackageMeta.watchSharedStyles !== false) invalidateSharedStyleCache();
		logger_default.success(`[${event}] ${configService.relativeCwd(normalizedId)} --[独立分包 ${subPackageMeta.subPackage.root}]`);
	} else if (!subPackageMeta && !handledByIndependentWatcher) logger_default.success(`[${event}] ${configService.relativeCwd(normalizedId)}`);
	return [...dirtyReasonStats.entries()].map(([cause, count]) => `${cause}:${count}`);
}
function createWatchChangeHook(state) {
	return async function watchChange(id, change) {
		const startedAt = performance.now();
		const eventId = createHmrProfileEventId();
		const normalizedId = normalizeFsResolvedId(id);
		state.ctx.moduleGraphService?.bindPluginContext(this);
		state.ctx.moduleGraphService?.recordChangedFile?.(normalizedId, change.event);
		if (isSkippableResolvedId(normalizedId)) return;
		if (isOutputFileChange(state, normalizedId)) return;
		if (isAutoRoutesGeneratedFileChange(state, normalizedId)) return;
		const emittedJsonPaths = change.event === "create" ? collectEmittedJsonPaths(state) : void 0;
		const event = await normalizeWatchEvent(normalizedId, change.event, {
			emittedJsonPaths,
			loadedEntrySet: state.loadedEntrySet,
			hasModule: (changedId) => state.ctx.moduleGraphService.hasModule(changedId),
			resolvedEntryMap: state.resolvedEntryMap,
			sharedChunkSourceModuleIds: state.ctx.runtimeState.build.hmr.sharedChunkSourceModuleIds
		});
		state.ctx.runtimeState.build.hmr.profile = {
			...state.ctx.runtimeState.build.hmr.profile,
			eventId,
			event,
			file: normalizedId
		};
		const dirtyReasonSummary = await processChangedFile(state, normalizedId, event);
		state.ctx.runtimeState.build.hmr.profile = {
			...state.ctx.runtimeState.build.hmr.profile,
			eventId,
			event,
			file: normalizedId,
			watchToDirtyMs: performance.now() - startedAt,
			dirtyReasonSummary
		};
		state.ctx.onStatefulHmrSourceChange?.(normalizedId, dirtyReasonSummary ?? []);
	};
}
//#endregion
//#region src/plugins/core/lifecycle/index.ts
const CORE_TRANSFORM_FILTER_RE = /\.(?:[cm]?[jt]sx?|vue)(?:\?.*)?$/;
function createCoreLifecyclePlugin(state) {
	const isPluginBuild = state.buildTarget === "plugin";
	const loadLogicalEntry = createLogicalEntryLoadHook(state);
	const loadSource = createLoadHook(state);
	return {
		name: "weapp-vite:pre",
		enforce: "pre",
		configResolved(config) {
			state.resolvedConfig = config;
		},
		configureServer(server) {
			state.ctx.moduleGraphService.bindDevServer(server);
		},
		buildStart: createBuildStartHook(state),
		watchChange: createWatchChangeHook(state),
		options: createOptionsHook(state),
		resolveId: createLogicalEntryResolveHook(state),
		async load(id) {
			state.ctx.moduleGraphService.bindPluginContext(this);
			const logicalResult = await loadLogicalEntry.call(this, id);
			if (logicalResult || parseSidecarSourceRequest(id)) return logicalResult;
			return await loadSource.call(this, id);
		},
		transform: {
			filter: { id: CORE_TRANSFORM_FILTER_RE },
			handler: createTransformHook(state)
		},
		renderStart: createRenderStartHook(state),
		generateBundle: createGenerateBundleHook(state, isPluginBuild),
		buildEnd: createBuildEndHook(state)
	};
}
//#endregion
//#region src/plugins/core/requireAnalysis.ts
const REQUIRE_ANALYSIS_FILTER_RE = /\.[jt]s$/;
const URL_SUFFIX_RE = /[?#].*$/;
const REQUIRE_ASYNC_TARGET_MARKER_PREFIX = "__weapp_vite_require_async_target__";
const REQUIRE_ASYNC_TARGET_MARKER_RE = new RegExp(`\\brequire\\.async\\(\\s*(['"])${REQUIRE_ASYNC_TARGET_MARKER_PREFIX}([\\w-]+)\\1\\s*\\)`, "g");
function cleanModuleId(id) {
	return id.replace(URL_SUFFIX_RE, "");
}
function createRelativeModuleSpecifier(importerFileName, targetFileName) {
	const relativePath = path.relative(path.dirname(importerFileName), targetFileName);
	return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
}
function createRequireAsyncTargetMarker(fileName) {
	return `${REQUIRE_ASYNC_TARGET_MARKER_PREFIX}${Buffer.from(fileName).toString("base64url")}`;
}
function decodeRequireAsyncTargetMarker(value) {
	if (!value.startsWith(REQUIRE_ASYNC_TARGET_MARKER_PREFIX)) return null;
	try {
		return Buffer.from(value.slice(35), "base64url").toString("utf8");
	} catch {
		return null;
	}
}
/**
* 按最终 chunk 文件名修正异步分包加载路径。
*/
function rewriteRequireAsyncChunkPaths(code, importerFileName) {
	const source = new MagicString(code);
	let changed = false;
	for (const match of code.matchAll(REQUIRE_ASYNC_TARGET_MARKER_RE)) {
		if (typeof match.index !== "number") continue;
		const targetFileName = decodeRequireAsyncTargetMarker(`${REQUIRE_ASYNC_TARGET_MARKER_PREFIX}${match[2]}`);
		if (!targetFileName) continue;
		const literalStart = match.index + match[0].indexOf(match[1]);
		const literalEnd = literalStart + 35 + match[2].length + 2;
		source.overwrite(literalStart, literalEnd, JSON.stringify(createRelativeModuleSpecifier(importerFileName, targetFileName)));
		changed = true;
	}
	if (!changed) return null;
	return {
		code: source.toString(),
		map: source.generateMap({ hires: "boundary" })
	};
}
function resolveModulePackageRoot(id, relativeAbsoluteSrcRoot, subPackageRoots) {
	return resolveSubPackagePrefix(relativeAbsoluteSrcRoot(cleanModuleId(id)), subPackageRoots);
}
/**
* 判断静态导入是否能安全交给微信普通分包的原生异步加载器。
*/
function isNativeSubPackageImport(options) {
	return options.dynamicImports === "native" && options.platform === "weapp" && options.request.startsWith(".") && Boolean(options.targetPackageRoot) && options.targetPackageRoot !== options.importerPackageRoot && !options.independentTarget;
}
function rewriteAsyncDependencies(code, options) {
	const { dependencyRewrites = [], nativeImportTokens = [], requireCallbackTokens = [] } = options;
	if (dependencyRewrites.length === 0 && nativeImportTokens.length === 0 && requireCallbackTokens.length === 0) return null;
	const source = new MagicString(code);
	for (const token of requireCallbackTokens) {
		source.overwrite(token.callStart, token.start, "void require.async(");
		source.overwrite(token.end, token.successCallbackStart, ").then(");
	}
	for (const token of nativeImportTokens) source.overwrite(token.callStart, token.start, "require.async(");
	for (const rewrite of dependencyRewrites) source.overwrite(rewrite.start, rewrite.end, JSON.stringify(rewrite.value));
	return {
		code: source.toString(),
		map: source.generateMap({ hires: "boundary" })
	};
}
function createRequireAnalysisPlugin(state) {
	const { ctx, requireAsyncEmittedChunks } = state;
	const { configService, scanService } = ctx;
	const resolveDynamicImports = () => configService.weappViteConfig?.chunks?.dynamicImports ?? "preserve";
	let warnedInlineFallback = false;
	return {
		name: "weapp-vite:post",
		enforce: "post",
		buildStart() {
			if (resolveDynamicImports() === "inline" && state.buildTarget === "app" && !warnedInlineFallback) {
				warnedInlineFallback = true;
				logger_default.warn("`weapp.chunks.dynamicImports: \"inline\"` 已废弃,当前会回退为 `preserve`;请改用 `preserve`,或在微信分包场景使用 `native`。");
			}
		},
		transform: {
			filter: { id: REQUIRE_ANALYSIS_FILTER_RE },
			async handler(code, id) {
				try {
					const dynamicImports = resolveDynamicImports();
					const ast = this.parse(code);
					const { dynamicImportTokens, requireCallbackTokens, requireTokens } = collectRequireTokens(ast);
					const dependencyRewrites = [];
					const nativeImportTokens = [];
					const resolvedDependencies = [];
					const subPackageRoots = [...scanService.subPackageMap.keys()].filter(Boolean).sort((left, right) => right.length - left.length);
					const importerPackageRoot = resolveModulePackageRoot(id, configService.relativeAbsoluteSrcRoot, subPackageRoots);
					const resolveDependency = async (token) => {
						if (!token.value.startsWith(".")) return null;
						const absoluteRequest = path.resolve(path.dirname(cleanModuleId(id)), token.value);
						const resolved = await this.resolve(absoluteRequest, id);
						if (!resolved || resolved.external) return null;
						const resolvedId = cleanModuleId(resolved.id);
						const fileName = resolveRelativeOutputFileNameWithExtension(configService, resolvedId, ".js");
						return {
							dependency: {
								fileName,
								id: resolvedId
							},
							specifier: createRequireAsyncTargetMarker(fileName)
						};
					};
					for (const token of requireTokens) {
						const resolved = await resolveDependency(token);
						if (!resolved) continue;
						dependencyRewrites.push({
							end: token.end,
							start: token.start,
							value: resolved.specifier
						});
						resolvedDependencies.push(resolved.dependency);
					}
					if (dynamicImports === "native" && configService.platform === "weapp") for (const token of dynamicImportTokens) {
						const resolved = await resolveDependency(token);
						if (!resolved) continue;
						const targetPackageRoot = resolveModulePackageRoot(resolved.dependency.id, configService.relativeAbsoluteSrcRoot, subPackageRoots);
						if (!isNativeSubPackageImport({
							dynamicImports,
							importerPackageRoot,
							independentTarget: scanService.independentSubPackageMap.has(targetPackageRoot),
							platform: configService.platform,
							request: token.value,
							targetPackageRoot
						})) continue;
						dependencyRewrites.push({
							end: token.end,
							start: token.start,
							value: resolved.specifier
						});
						nativeImportTokens.push(token);
						resolvedDependencies.push(resolved.dependency);
					}
					const rewritten = rewriteAsyncDependencies(code, {
						dependencyRewrites,
						nativeImportTokens,
						requireCallbackTokens
					});
					return {
						code: rewritten?.code ?? code,
						...rewritten ? {} : { ast },
						map: rewritten?.map ?? null,
						meta: { requireAsyncDependencies: resolvedDependencies }
					};
				} catch (error) {
					logger_default.error(error);
				}
			}
		},
		generateBundle(_options, bundle) {
			for (const output of Object.values(bundle)) {
				if (output?.type !== "chunk") continue;
				const chunk = output;
				const rewritten = rewriteRequireAsyncChunkPaths(chunk.code, chunk.fileName);
				if (!rewritten) continue;
				applyOutputChunkTransform(chunk, rewritten.code, rewritten.map);
			}
		},
		async moduleParsed(moduleInfo) {
			const dependencies = moduleInfo.meta.requireAsyncDependencies;
			if (!Array.isArray(dependencies)) return;
			for (const dependency of dependencies) {
				await this.load({ id: dependency.id });
				if (requireAsyncEmittedChunks.has(dependency.id)) continue;
				requireAsyncEmittedChunks.add(dependency.id);
				this.emitFile({
					type: "chunk",
					id: dependency.id,
					fileName: dependency.fileName,
					preserveSignature: "exports-only"
				});
			}
		}
	};
}
//#endregion
//#region src/plugins/core/wxss.ts
const nativeStyleExtensionRe = new RegExp(`\\.(${ALL_NATIVE_STYLE_RESOLVER_EXTENSIONS.join("|")})$`);
function createWxssResolverPlugin(state) {
	return {
		name: "weapp-vite:pre:native-style",
		enforce: "pre",
		resolveId: {
			filter: { id: nativeStyleExtensionRe },
			handler(id) {
				const startedAt = performance.now();
				try {
					return id.replace(nativeStyleExtensionRe, (_match, extension) => `.css?nativeStyle=${extension}`);
				} finally {
					const profile = state.ctx.runtimeState?.build?.hmr?.profile;
					recordHmrProfileDuration(profile, "pluginResolveMs", performance.now() - startedAt);
					recordHmrProfileOperation(profile, "resolveCount");
				}
			}
		}
	};
}
//#endregion
//#region src/plugins/core/index.ts
function weappVite(ctx, subPackageMeta) {
	const buildTarget = ctx.currentBuildTarget ?? "app";
	const hmrSharedChunksMode = ctx.configService?.weappViteConfig?.hmr?.sharedChunks ?? "auto";
	const hmrSharedChunkImporters = /* @__PURE__ */ new Map();
	const hmrSharedChunksByEntry = /* @__PURE__ */ new Map();
	const hmrSharedChunkDependencies = /* @__PURE__ */ new Map();
	const outputChunksByModule = /* @__PURE__ */ new Map();
	const hmrSourceSharedChunks = /* @__PURE__ */ new Set();
	const hmrRootInputIds = /* @__PURE__ */ new Set();
	const hmrState = {
		didEmitAllEntries: false,
		hasBuiltOnce: false,
		affectedSharedChunkIds: /* @__PURE__ */ new Set(),
		lastHmrEntryIds: /* @__PURE__ */ new Set(),
		lastEmittedEntryIds: /* @__PURE__ */ new Set(),
		skipSharedChunkRefresh: false
	};
	const { loadEntry, loadedEntrySet, jsonEmitFilesMap, entriesMap, resolvedEntryMap, markEntryDirty, emitDirtyEntries } = useLoadEntry(ctx, {
		buildTarget,
		hmr: {
			sharedChunks: hmrSharedChunksMode,
			sharedChunkImporters: hmrSharedChunkImporters,
			sharedChunksByEntry: hmrSharedChunksByEntry,
			sourceSharedChunks: hmrSourceSharedChunks,
			rootInputIds: hmrRootInputIds,
			setDidEmitAllEntries: (value) => {
				hmrState.didEmitAllEntries = value;
				if (ctx.runtimeState?.build?.hmr) ctx.runtimeState.build.hmr.didEmitAllEntries = value;
			},
			setLastEmittedEntries: (entryIds) => {
				hmrState.lastEmittedEntryIds = new Set(entryIds);
				if (ctx.runtimeState?.build?.hmr) ctx.runtimeState.build.hmr.lastEmittedEntryIds = new Set(entryIds);
			},
			setLastHmrEntries: (entryIds) => {
				hmrState.lastHmrEntryIds = new Set(entryIds);
				if (ctx.runtimeState?.build?.hmr) ctx.runtimeState.build.hmr.lastHmrEntryIds = new Set(entryIds);
			},
			setSkipSharedChunkRefresh: (value) => {
				hmrState.skipSharedChunkRefresh = value;
			}
		}
	});
	const state = {
		ctx,
		subPackageMeta,
		loadEntry,
		loadedEntrySet,
		markEntryDirty,
		emitDirtyEntries,
		entriesMap,
		jsonEmitFilesMap,
		resolvedEntryMap,
		requireAsyncEmittedChunks: /* @__PURE__ */ new Set(),
		watchFilesSnapshot: [],
		buildTarget,
		hmrState,
		hmrSharedChunksMode,
		hmrSharedChunkImporters,
		hmrSharedChunksByEntry,
		hmrSharedChunkDependencies,
		outputChunksByModule,
		hmrSourceSharedChunks,
		hmrRootInputIds
	};
	return [
		createWxssResolverPlugin(state),
		createCoreLifecyclePlugin(state),
		createRequireAnalysisPlugin(state)
	];
}
//#endregion
//#region src/plugins/preflight.ts
const debug = createDebugger("weapp-vite:preflight");
const removePlugins = ["vite:build-import-analysis", "native:import-analysis-build"];
const EXTERNAL_TAILWINDCSS_PLUGIN_PREFIX = "weapp-tailwindcss:";
const BUILTIN_TAILWINDCSS_VERSION = "6.24.0";
function createPluginPruner() {
	let warnedExternalTailwindcss = false;
	return {
		name: "weapp-vite:preflight",
		enforce: "pre",
		configResolved(config) {
			if (!config.plugins?.length) return;
			for (const removePlugin of removePlugins) {
				const plugins = config.plugins;
				const idx = plugins.findIndex((plugin) => plugin.name === removePlugin);
				if (idx > -1) {
					const [plugin] = plugins.splice(idx, 1);
					plugin && debug?.("remove plugin", plugin.name);
				}
			}
			if (config.plugins.filter((plugin) => plugin.name.startsWith(EXTERNAL_TAILWINDCSS_PLUGIN_PREFIX)).length === 0) return;
			const plugins = config.plugins;
			for (let index = plugins.length - 1; index >= 0; index--) {
				const plugin = plugins[index];
				if (plugin?.name.startsWith(EXTERNAL_TAILWINDCSS_PLUGIN_PREFIX)) {
					plugins.splice(index, 1);
					debug?.("remove plugin", plugin.name);
				}
			}
			if (!warnedExternalTailwindcss) {
				warnedExternalTailwindcss = true;
				logger_default.warn(`[weapp-vite] 检测到已注册 \`weapp-tailwindcss/vite\` 插件,已由内置集成接管并禁用外部插件。自 weapp-vite@${BUILTIN_TAILWINDCSS_VERSION} 起无需单独安装或注册 weapp-tailwindcss,请删除对应 import 和 plugins 配置。`);
			}
		}
	};
}
function createEnvSynchronizer({ configService }) {
	return {
		name: "weapp-vite:set-env",
		enforce: "pre",
		configResolved(config) {
			if (!isObject(config.env)) return;
			for (const [key, value] of Object.entries(config.env)) configService.setDefineEnv(key, value);
		}
	};
}
function preflight(ctx) {
	return [createPluginPruner(), createEnvSynchronizer(ctx)];
}
//#endregion
//#region src/plugins/tailwindcss.ts
const CORE_NODE_RANGE = "^22.18.0 || >=24.11.0";
const MANAGED_PLUGIN_NAME = "weapp-vite:tailwindcss";
const VIRTUAL_ENTRY_PREFIX = "\0weapp-vite:managed-tailwindcss-entry:";
const TAILWIND_IMPORT_RE = /@import\s+(?:url\(\s*)?['"]tailwindcss['"]\s*\)?(?:\s|;|$)/;
const TAILWIND_SOURCE_DIRECTIVE_RE = /@(?:config|custom-variant|layer|plugin|reference|source|tailwind|theme|utility|variant)\b/;
function unique(values) {
	return [...new Set(values)];
}
function resolveCssEntries(ctx, options, basedir) {
	const nestedTailwindcss = options.tailwindcss?.tailwindcss;
	const entries = unique([
		...options.cssEntries ?? [],
		...options.tailwindcss?.v4?.cssEntries ?? [],
		...nestedTailwindcss?.v4?.cssEntries ?? [],
		...options.tailwindcssRuntimeOptions?.tailwindcss?.v4?.cssEntries ?? []
	]).map((entry) => path.isAbsolute(entry) ? path.normalize(entry) : path.resolve(basedir, entry));
	return entries.length > 0 ? entries : [path.resolve(ctx.configService.absoluteSrcRoot, "app.css")];
}
function resolveManagedTailwindcssOptions(ctx) {
	const input = ctx.configService.weappViteConfig?.tailwindcss;
	if (input === void 0) {
		const version = safeGetPackageInfoSync("tailwindcss", { paths: [ctx.configService.cwd] })?.version;
		if (!version || Number.parseInt(version.split(".")[0] ?? "", 10) !== 4) return;
		return {
			basedir: ctx.configService.cwd,
			cssEntries: [],
			generatorTarget: "weapp",
			autoDetected: true,
			options: {
				appType: "weapp-vite",
				platform: ctx.configService.platform,
				tailwindcssBasedir: ctx.configService.cwd
			}
		};
	}
	if (input === false) return;
	const userOptions = input === true ? {} : input;
	if (userOptions.disabled === true || typeof userOptions.disabled === "object" && userOptions.disabled.plugin === true) return;
	const cwd = ctx.configService.cwd;
	const basedir = userOptions.tailwindcssBasedir ? path.resolve(cwd, userOptions.tailwindcssBasedir) : cwd;
	const cssEntries = resolveCssEntries(ctx, userOptions, basedir);
	return {
		basedir,
		cssEntries,
		generatorTarget: typeof userOptions.generator === "object" && userOptions.generator.target ? userOptions.generator.target : "weapp",
		autoDetected: false,
		options: {
			...userOptions,
			appType: "weapp-vite",
			cssEntries,
			platform: userOptions.platform ?? ctx.configService.platform,
			tailwindcssBasedir: basedir
		}
	};
}
function outputAssetSource(asset) {
	return typeof asset.source === "string" ? asset.source : Buffer.from(asset.source).toString("utf8");
}
function createVirtualEntryId(index, source) {
	const queryIndex = source.indexOf("?");
	const query = queryIndex >= 0 ? source.slice(queryIndex) : "";
	return `${VIRTUAL_ENTRY_PREFIX}${index}.css${query}`;
}
function parseVirtualEntryIndex(id) {
	if (!id.startsWith(VIRTUAL_ENTRY_PREFIX)) return;
	const value = Number.parseInt(id.slice(38), 10);
	return Number.isInteger(value) ? value : void 0;
}
function parseManagedEntryIndex(id, entries) {
	const sourceId = normalizeFsResolvedId(id.split("?")[0], { stripLeadingNullByte: true });
	return entries.get(normalizeManagedTailwindcssEntryPath(sourceId));
}
function isVueStyleModuleId(id) {
	return id.includes("?weapp-vite-vue&type=style&");
}
function resolveManagedEntryIndex(id, code, entries) {
	const directIndex = parseManagedEntryIndex(id, entries);
	if (directIndex !== void 0 || !isVueStyleModuleId(id)) return directIndex;
	for (const [entry, index] of entries) try {
		if (fs.readFileSync(entry, "utf8") === code) return index;
	} catch {}
}
function createTailwindV4SourceOptions(resolved, entry) {
	const configuredTailwindcss = resolved.options.tailwindcss;
	const tailwindcss = configuredTailwindcss?.tailwindcss ?? configuredTailwindcss;
	const v4 = tailwindcss?.v4;
	const runtimeV4 = resolved.options.tailwindcssRuntimeOptions?.tailwindcss?.v4;
	return {
		projectRoot: resolved.basedir,
		cwd: tailwindcss?.cwd,
		base: v4?.base,
		cssSources: v4?.cssSources,
		cssEntries: [entry],
		sources: v4?.sources ?? runtimeV4?.sources,
		packageName: tailwindcss?.packageName ?? "tailwindcss"
	};
}
function createCompilerRootId(index, entry) {
	return `weapp-vite:tailwindcss:${index}:${normalizeManagedTailwindcssEntryPath(entry)}`;
}
function assertRuntimeRequirements(resolved) {
	const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
	if (!(major === 22 && minor >= 18 || major >= 24 && (major > 24 || minor >= 11))) throw new Error(`weapp.tailwindcss requires Node ${CORE_NODE_RANGE}; current version is ${process.versions.node}.`);
	for (const entry of resolved.cssEntries) if (!fs.existsSync(entry)) throw new Error(`weapp.tailwindcss CSS entry does not exist: ${entry}`);
}
function hasTailwindImport(code) {
	return TAILWIND_IMPORT_RE.test(code);
}
function createTailwindcssPlugin(ctx) {
	const managedOptions = resolveManagedTailwindcssOptions(ctx);
	if (!managedOptions) return [];
	const resolved = managedOptions;
	registerManagedTailwindcssEntries(ctx, resolved.cssEntries);
	const entryIndex = new Map(resolved.cssEntries.map((entry, index) => [normalizeManagedTailwindcssEntryPath(entry), index]));
	const previousEntrySources = /* @__PURE__ */ new Map();
	const resolvedEntryIndexes = /* @__PURE__ */ new Set();
	const loadedEntryIndexes = /* @__PURE__ */ new Set();
	const previousGeneratedCss = /* @__PURE__ */ new Map();
	const generatedOutputEntries = /* @__PURE__ */ new Map();
	const compilerRootIds = /* @__PURE__ */ new Map();
	const compilerSourceOptions = /* @__PURE__ */ new Map();
	const compilerSnapshots = /* @__PURE__ */ new Map();
	const processedStyleOutputs = /* @__PURE__ */ new WeakSet();
	let generatedEntriesPromise;
	let coreModulePromise;
	let compilerPromise;
	let resolvedConfig;
	let loaded = false;
	let compilerDisposed = false;
	function resolveAutoEntryIndex(id, code) {
		if (!resolved.autoDetected || !hasTailwindImport(code)) return;
		const sourceId = normalizeFsResolvedId(id.split("?")[0], { stripLeadingNullByte: true });
		if (!sourceId || !/\.(?:css|pcss|postcss|sss|scss|sass|less|styl|stylus)$/.test(sourceId)) return;
		const normalizedEntry = normalizeManagedTailwindcssEntryPath(sourceId);
		const existingIndex = entryIndex.get(normalizedEntry);
		if (existingIndex !== void 0) return existingIndex;
		const index = resolved.cssEntries.length;
		resolved.cssEntries.push(sourceId);
		entryIndex.set(normalizedEntry, index);
		registerManagedTailwindcssEntries(ctx, resolved.cssEntries);
		return index;
	}
	function getCoreModule() {
		coreModulePromise ??= import("weapp-tailwindcss/core");
		return coreModulePromise;
	}
	async function getCompiler() {
		compilerPromise ??= getCoreModule().then(({ createCompiler }) => createCompiler(resolved.options));
		const compiler = await compilerPromise;
		if (!loaded) {
			loaded = true;
			resolved.options.onLoad?.();
		}
		return compiler;
	}
	async function stripResidualTailwindSourceDirectives(css) {
		if (!TAILWIND_SOURCE_DIRECTIVE_RE.test(css)) return css;
		const { postcss, removeTailwindSourceDirectivesRoot } = await getCoreModule();
		const root = postcss.parse(css);
		removeTailwindSourceDirectivesRoot(root);
		return root.toString();
	}
	async function generateEntryCss(compiler, index, entry) {
		const sourceOptions = compilerSourceOptions.get(index) ?? createTailwindV4SourceOptions(resolved, entry);
		compilerSourceOptions.set(index, sourceOptions);
		const id = compilerRootIds.get(index) ?? createCompilerRootId(index, entry);
		compilerRootIds.set(index, id);
		const generated = await compiler.generate({
			id,
			sourceOptions,
			target: resolved.generatorTarget,
			scanSources: true,
			bareArbitraryValues: resolved.options.arbitraryValues?.bareArbitraryValues,
			styleOptions: typeof resolved.options.generator === "object" ? resolved.options.generator.styleOptions : void 0
		});
		compilerSnapshots.set(index, generated.snapshot);
		return generated;
	}
	async function disposeCompiler() {
		if (compilerDisposed) return;
		compilerDisposed = true;
		await compilerPromise?.then((compiler) => compiler.dispose());
	}
	async function invalidateCompilerForFile(id, event) {
		const compiler = await getCompiler();
		const normalizedId = normalizeFsResolvedId(id.split("?")[0], { stripLeadingNullByte: true });
		const index = entryIndex.get(normalizeManagedTailwindcssEntryPath(normalizedId));
		generatedEntriesPromise = void 0;
		if (event === "delete" && index !== void 0) {
			const rootId = compilerRootIds.get(index);
			if (rootId) await compiler.remove(rootId);
			compilerSourceOptions.delete(index);
			return;
		}
		compiler.invalidate([normalizedId]);
	}
	async function transformBundle(bundle, options = {}) {
		if (resolved.autoDetected && resolved.cssEntries.length === 0) return;
		const transformStyles = options.styles !== false;
		const transformTemplates = options.templates !== false;
		const compiler = await getCompiler();
		const generatedEntries = resolved.options.generator === false ? [] : await (generatedEntriesPromise ??= Promise.all(resolved.cssEntries.map((entry, index) => generateEntryCss(compiler, index, entry))));
		const snapshots = generatedEntries.length > 0 ? generatedEntries.map((generated, index) => compilerSnapshots.get(index) ?? generated.snapshot) : [compiler.createSnapshot({
			id: `${MANAGED_PLUGIN_NAME}:disabled`,
			classSet: [],
			target: resolved.generatorTarget
		})];
		const snapshot = compiler.mergeSnapshots(snapshots);
		const seenEntries = /* @__PURE__ */ new Set();
		const styleExtension = ctx.configService.outputExtensions.wxss;
		const templateExtension = ctx.configService.outputExtensions.wxml;
		const scriptSourceMap = Boolean(resolvedConfig?.build.sourcemap);
		for (const output of Object.values(bundle)) {
			if (!transformStyles) break;
			if (output.type !== "asset") continue;
			if (processedStyleOutputs.has(output)) {
				generatedOutputEntries.get(output.fileName)?.forEach((index) => seenEntries.add(index));
				continue;
			}
			let source = outputAssetSource(output);
			let hasManagedEntry = false;
			let isMainChunk = output.fileName === `app.${styleExtension}`;
			for (let index = 0; index < generatedEntries.length; index++) {
				const marker = createManagedTailwindcssEntryMarker(index);
				const outputMarker = createManagedTailwindcssOutputMarker(index);
				const hasEntryMarker = source.includes(marker);
				const hasOutputMarker = source.includes(outputMarker);
				const previousCss = previousGeneratedCss.get(index);
				const isTrackedOutput = generatedOutputEntries.get(output.fileName)?.has(index) === true;
				const expectedOutputFile = typeof ctx.configService.relativeOutputPath === "function" ? ctx.configService.relativeOutputPath(changeFileExtension(resolved.cssEntries[index], styleExtension)) : void 0;
				const isCanonicalOutput = expectedOutputFile !== void 0 && normalizeManagedTailwindcssEntryPath(expectedOutputFile) === normalizeManagedTailwindcssEntryPath(output.fileName);
				if (!hasEntryMarker && !hasOutputMarker && !isTrackedOutput && !isCanonicalOutput) continue;
				const generated = generatedEntries[index];
				hasManagedEntry = true;
				isMainChunk ||= normalizeManagedTailwindcssEntryPath(resolved.cssEntries[index]) === normalizeManagedTailwindcssEntryPath(path.resolve(ctx.configService.absoluteSrcRoot, "app.css"));
				seenEntries.add(index);
				const replacement = `${outputMarker}\n${generated.css}`;
				if (hasEntryMarker) {
					const markerIndex = source.indexOf(marker);
					source = source.slice(0, markerIndex) + replacement + source.slice(markerIndex + marker.length).replaceAll(marker, "");
				} else if (previousCss !== void 0) source = source.includes(outputMarker) ? source.replace(`${outputMarker}\n${previousCss}`, replacement) : `${replacement}\n${source}`;
				else if (isCanonicalOutput) source = `${replacement}\n${source}`;
				else source = source.replace(outputMarker, replacement);
				previousGeneratedCss.set(index, generated.css);
				const trackedEntries = generatedOutputEntries.get(output.fileName) ?? /* @__PURE__ */ new Set();
				trackedEntries.add(index);
				generatedOutputEntries.set(output.fileName, trackedEntries);
				for (const dependency of generated.dependencies) this.addWatchFile(dependency);
			}
			if (!hasManagedEntry && !output.fileName.endsWith(`.${styleExtension}`)) continue;
			output.source = stripManagedTailwindcssOutputMarkers(await stripResidualTailwindSourceDirectives((await compiler.transformCss(source, snapshot, { isMainChunk })).css));
			processedStyleOutputs.add(output);
		}
		if (transformStyles && !ctx.configService.isDev && resolved.options.generator !== false) {
			const stages = resolved.cssEntries.filter((_entry, index) => resolvedEntryIndexes.has(index) || loadedEntryIndexes.has(index)).filter((entry) => !seenEntries.has(resolved.cssEntries.indexOf(entry))).map((entry) => {
				const index = resolved.cssEntries.indexOf(entry);
				return `${entry} (resolved: ${resolvedEntryIndexes.has(index)}, loaded: ${loadedEntryIndexes.has(index)})`;
			});
			if (stages.length > 0) throw new Error(`weapp.tailwindcss CSS entries must be imported by the build graph: ${stages.join(", ")}`);
		}
		if (!transformTemplates) return;
		for (const output of Object.values(bundle)) {
			if (output.type === "asset" && output.fileName.endsWith(`.${templateExtension}`)) {
				output.source = await compiler.transformTemplate(outputAssetSource(output), snapshot, { filename: output.fileName });
				continue;
			}
			if (output.type !== "chunk" || !output.fileName.endsWith(".js")) continue;
			const transformed = await compiler.transformJavaScript(output.code, snapshot, {
				filename: output.fileName,
				generateMap: scriptSourceMap
			});
			if (transformed.error) throw transformed.error;
			applyOutputChunkTransform(output, transformed.code, transformed.map);
		}
	}
	return [{
		name: MANAGED_PLUGIN_NAME,
		enforce: "pre",
		generateBundle: {
			order: "pre",
			async handler(_options, bundle) {
				generatedEntriesPromise = void 0;
				resolved.options.onStart?.();
				try {
					await transformBundle.call(this, bundle, { templates: false });
				} finally {
					resolved.options.onEnd?.();
				}
			}
		},
		async buildStart() {
			generatedEntriesPromise = void 0;
			assertRuntimeRequirements(resolved);
			if (ctx.configService.isDev) {
				const pendingChanges = ctx.moduleGraphService?.getPendingChanges?.() ?? [];
				if (pendingChanges.length > 0) await Promise.all(pendingChanges.map((change) => invalidateCompilerForFile(change.file, change.event)));
			}
			resolvedEntryIndexes.clear();
			loadedEntryIndexes.clear();
			for (const entry of resolved.cssEntries) this.addWatchFile(entry);
		},
		configResolved(config) {
			resolvedConfig = config;
		},
		resolveId(source) {
			if (resolved.options.generator === false) return null;
			const sidecar = parseSidecarSourceRequest(source);
			if (!sidecar || sidecar.kind !== "style") return null;
			let index = entryIndex.get(normalizeManagedTailwindcssEntryPath(sidecar.sourceId));
			if (index === void 0 && resolved.autoDetected) try {
				index = resolveAutoEntryIndex(sidecar.sourceId, fs.readFileSync(sidecar.sourceId, "utf8"));
			} catch {}
			if (index === void 0) return null;
			resolvedEntryIndexes.add(index);
			return createVirtualEntryId(index, source);
		},
		load(id) {
			if (resolved.options.generator === false) return null;
			const virtualIndex = parseVirtualEntryIndex(id);
			const normalizedId = virtualIndex === void 0 ? normalizeFsResolvedId(id.split("?")[0]) : normalizeFsResolvedId(resolved.cssEntries[virtualIndex] ?? "");
			const index = virtualIndex ?? entryIndex.get(normalizedId);
			if (index === void 0) return null;
			loadedEntryIndexes.add(index);
			const code = fs.readFileSync(normalizedId, "utf8");
			const previous = previousEntrySources.get(normalizedId);
			if (previous !== void 0 && previous !== code) resolved.options.onUpdate?.(normalizedId, previous, code);
			previousEntrySources.set(normalizedId, code);
			return createManagedTailwindcssEntryMarker(index);
		},
		transform(code, id) {
			if (resolved.options.generator === false) return null;
			const index = resolveManagedEntryIndex(id, code, entryIndex) ?? resolveAutoEntryIndex(id, code);
			if (index === void 0) return null;
			loadedEntryIndexes.add(index);
			return {
				code: createManagedTailwindcssEntryMarker(index),
				map: null
			};
		},
		async watchChange(id, change) {
			await invalidateCompilerForFile(id, change.event);
		},
		async handleHotUpdate({ file }) {
			await invalidateCompilerForFile(file, "update");
		},
		async closeWatcher() {
			await disposeCompiler();
		}
	}, {
		name: `${MANAGED_PLUGIN_NAME}:output`,
		enforce: "post",
		generateBundle: {
			order: "post",
			async handler(_options, bundle) {
				resolved.options.onStart?.();
				try {
					await transformBundle.call(this, bundle);
				} finally {
					resolved.options.onEnd?.();
				}
			}
		},
		async closeBundle() {
			if (!ctx.configService.isDev) await disposeCompiler();
		}
	}];
}
//#endregion
//#region src/plugins/uniApp.ts
const SUPPORTED_SOURCE_RE = /(?:\.vue|\.[cm]?[jt]sx?|\.(?:css|less|sass|scss|styl|stylus))(?:\?.*)?$/i;
function resolveVirtualBlockType(id) {
	const queryIndex = id.indexOf("?");
	if (queryIndex < 0) return;
	const query = new URLSearchParams(id.slice(queryIndex + 1));
	const block = query.get("weapp-vite-sidecar") ?? (query.has("weapp-vite-vue") ? query.get("type") : void 0);
	return block === "script" || block === "template" || block === "style" ? block : block ? null : void 0;
}
function resolveIncludedPackage(id, include) {
	const normalized = id.replace(/\\/g, "/");
	return include.find((packageName) => normalized.includes(`/node_modules/${packageName}/`));
}
function uniAppCompatibility(ctx) {
	const configService = ctx.configService;
	const config = configService.weappViteConfig?.uniApp;
	if (!config || configService.platform !== "weapp") return [];
	return [{
		name: "weapp-vite:uni-app-compatibility",
		enforce: "pre",
		transform(code, id) {
			const blockType = resolveVirtualBlockType(id);
			if (id.startsWith("\0") || parseSidecarSourceRequest(id) || !SUPPORTED_SOURCE_RE.test(id) || blockType === null || !isUniAppCompatibilityFile(id, configService.absoluteSrcRoot, config.include)) return null;
			try {
				const result = transformUniAppSource(code, {
					blockType: blockType ?? void 0,
					filename: id,
					target: "mp-weixin"
				});
				return result.changed ? {
					code: result.code,
					map: null
				} : null;
			} catch (error) {
				const packageName = resolveIncludedPackage(id, config.include) ?? "<project-source>";
				const filename = id.split("?", 1)[0];
				const section = blockType ?? (filename.endsWith(".vue") ? "sfc" : "source");
				throw new Error(`[uni-app] package=${packageName} file=${filename} block=${section}: ${error instanceof Error ? error.message : String(error)}`);
			}
		}
	}];
}
//#endregion
//#region src/plugins/vue/transform/styleRequest.ts
const WEAPP_VUE_STYLE_VIRTUAL_PREFIX = "\0weapp-vite:vue-style:";
const WEAPP_VUE_STYLE_VIRTUAL_PREFIX_PLAIN = "weapp-vite:vue-style:";
function appendHmrToken(query, token) {
	if (typeof token === "number") return Number.isFinite(token) && token > 0 ? `${query}&hmr=${token}` : query;
	if (typeof token === "string" && token.trim()) return `${query}&hmr=${encodeURIComponent(token)}`;
	return query;
}
function resolveEncodedStyleRequestFilename(filename) {
	const normalizedFilename = normalizeFsResolvedId(filename);
	return {
		normalizedFilename,
		encodedFilename: encodeURIComponent(normalizedFilename)
	};
}
function parseWeappVueStyleRequest(id) {
	const queryIndex = id.indexOf("?");
	if (queryIndex === -1) return;
	const rawQuery = id.slice(queryIndex + 1);
	const params = new URLSearchParams(rawQuery);
	if (!params.has("weapp-vite-vue")) return;
	if (params.get("type") !== "style") return;
	const indexRaw = params.get("index");
	const index = indexRaw ? Number(indexRaw) : 0;
	if (!Number.isFinite(index) || index < 0) return;
	let filename = id.slice(0, queryIndex);
	if (filename.startsWith("\0weapp-vite:vue-style:") || filename.startsWith(WEAPP_VUE_STYLE_VIRTUAL_PREFIX_PLAIN)) {
		const prefix = filename.startsWith("\0weapp-vite:vue-style:") ? WEAPP_VUE_STYLE_VIRTUAL_PREFIX : WEAPP_VUE_STYLE_VIRTUAL_PREFIX_PLAIN;
		const encoded = filename.slice(prefix.length);
		if (!encoded) return;
		try {
			filename = decodeURIComponent(encoded);
		} catch {
			return;
		}
	}
	const normalizedFilename = normalizeFsResolvedId(filename);
	if (!normalizedFilename) return;
	return {
		filename: normalizedFilename,
		index
	};
}
function buildWeappVueStyleRequests(filename, styleBlocks, options = {}) {
	const { encodedFilename } = resolveEncodedStyleRequestFilename(filename);
	return styleBlocks.map((styleBlock, index) => {
		const lang = styleBlock.lang || "css";
		let query = `weapp-vite-vue&type=style&index=${index}`;
		if (styleBlock.scoped) query += "&scoped=true";
		if (styleBlock.module) query += typeof styleBlock.module === "string" ? `&module=${encodeURIComponent(styleBlock.module)}` : "&module=true";
		query = appendHmrToken(query, options.hmrToken);
		query += `&lang.${lang}`;
		return `${WEAPP_VUE_STYLE_VIRTUAL_PREFIX}${encodedFilename}?${query}`;
	});
}
//#endregion
//#region src/plugins/vue/resolver.ts
const VUE_VIRTUAL_MODULE_PREFIX = "\0vue:";
const LEGACY_WEAPP_VUE_STYLE_VIRTUAL_PREFIX = "weapp-vite:vue-style:";
const WINDOWS_ABSOLUTE_PATH_RE$1 = /^[A-Z]:[\\/]/i;
let warnedMissingWevu = false;
let wevuInstallState = "unknown";
function isExplicitFileRequest$1(id) {
	return id.startsWith(".") || id.startsWith("/") || WINDOWS_ABSOLUTE_PATH_RE$1.test(id);
}
function hasWevuDependency$1(ctx) {
	const packageJson = ctx.configService?.packageJson;
	if (!packageJson) return false;
	return Boolean(packageJson.dependencies?.wevu || packageJson.devDependencies?.wevu);
}
function ensureWevuInstalled(ctx) {
	if (wevuInstallState === "present") return;
	if (wevuInstallState === "missing") return;
	if (warnedMissingWevu) return;
	if (hasWevuDependency$1(ctx)) {
		wevuInstallState = "present";
		return;
	}
	const cwd = ctx.configService?.cwd ?? process.cwd();
	const require = createRequire(path.resolve(cwd, "package.json"));
	try {
		require.resolve("wevu");
		wevuInstallState = "present";
	} catch {
		warnedMissingWevu = true;
		wevuInstallState = "missing";
		logger_default.warn("[vue] 检测到项目中有 .vue 文件,但未安装 wevu,请安装 wevu 后重试。");
	}
}
function createVueResolverPlugin(ctx, options = {}) {
	const isWeappVueStyleVirtualId = (id) => {
		return id.startsWith("\0weapp-vite:vue-style:") || id.startsWith(LEGACY_WEAPP_VUE_STYLE_VIRTUAL_PREFIX);
	};
	return {
		name: `${VUE_PLUGIN_NAME}:resolver`,
		async resolveId(id, importer) {
			const configService = ctx.configService;
			if (!configService) return null;
			const styleRequest = parseWeappVueStyleRequest(id);
			if (styleRequest) {
				ensureWevuInstalled(ctx);
				const queryIndex = id.indexOf("?");
				const query = queryIndex === -1 ? "" : id.slice(queryIndex + 1);
				const absoluteId = toAbsoluteId(styleRequest.filename, configService, importer, { base: "srcRoot" });
				if (!absoluteId) return isWeappVueStyleVirtualId(id) ? id : null;
				return query ? `${absoluteId}?${query}` : absoluteId;
			}
			if (isVueLikeFile(id)) {
				if (options.react && /\.(?:jsx|tsx)(?:\?.*)?$/.test(id)) return null;
				ensureWevuInstalled(ctx);
				if (!isExplicitFileRequest$1(id)) return null;
				const absoluteId = toAbsoluteId(id, configService, importer, { base: "srcRoot" });
				if (!absoluteId) return null;
				return absoluteId;
			}
			if (id.startsWith(VUE_VIRTUAL_MODULE_PREFIX)) return id;
			if (!isExplicitFileRequest$1(id)) return null;
			const absoluteId = toAbsoluteId(id, configService, importer, { base: "srcRoot" });
			if (!absoluteId) return null;
			for (const ext of VUE_LIKE_EXTENSIONS$1) {
				const vueLikePath = `${absoluteId}${ext}`;
				if (await pathExists(vueLikePath, { ttlMs: getPathExistsTtlMs(configService) })) {
					ensureWevuInstalled(ctx);
					return vueLikePath;
				}
			}
			return null;
		},
		async load(id) {
			if (id.startsWith(VUE_VIRTUAL_MODULE_PREFIX)) {
				const absoluteId = toAbsoluteId(id.slice(5), ctx.configService, void 0, { base: "cwd" });
				if (!absoluteId) return null;
				return {
					code: await readFile$1(absoluteId, {
						checkMtime: ctx.configService?.isDev ?? false,
						encoding: "utf-8"
					}),
					moduleSideEffects: false
				};
			}
			return null;
		}
	};
}
function getSourceFromVirtualId(id) {
	if (id.startsWith(VUE_VIRTUAL_MODULE_PREFIX)) return id.slice(5);
	return id;
}
//#endregion
//#region src/plugins/vue/transform/classStyle.ts
function resolveClassStylePackageRoot(ctx, relativeBase, configService) {
	const currentRoot = normalizeRoot(configService.currentSubPackageRoot ?? "");
	if (currentRoot) return currentRoot;
	const scanService = ctx.scanService;
	if (!scanService?.independentSubPackageMap?.size) return "";
	const normalizedBase = toPosixPath(relativeBase);
	for (const root of scanService.independentSubPackageMap.keys()) {
		const normalizedRoot = normalizeRoot(root);
		if (!normalizedRoot) continue;
		if (normalizedBase === normalizedRoot || normalizedBase.startsWith(`${normalizedRoot}/`)) return normalizedRoot;
	}
	return "";
}
function resolveClassStyleWxsLocationForBase(ctx, relativeBase, extension, configService) {
	const packageRoot = configService.weappViteConfig?.vue?.template?.classStyleWxsShared ?? true ? resolveClassStylePackageRoot(ctx, relativeBase, configService) : (() => {
		const dir = path.posix.dirname(toPosixPath(relativeBase));
		return dir === "." ? "" : dir;
	})();
	return resolveClassStyleWxsLocation({
		relativeBase,
		extension,
		packageRoot
	});
}
//#endregion
//#region src/plugins/vue/transform/bundle/outputExtensions.ts
function resolveBundleOutputExtensions(outputExtensions) {
	return resolveOutputExtensions(outputExtensions);
}
//#endregion
//#region src/plugins/vue/transform/scopedSlot/assets.ts
function hasOwn(source, key) {
	return Object.prototype.hasOwnProperty.call(source, key);
}
function parseJsonSafely$1(source) {
	if (!source) return;
	try {
		return JSON.parse(source);
	} catch {
		return;
	}
}
function resolveScopedSlotOwnerStyleImport(relativeBase, styleExtension) {
	const normalizedBase = toPosixPath(relativeBase);
	return `@import './${normalizedBase.slice(normalizedBase.lastIndexOf("/") + 1)}.${styleExtension}';\n`;
}
function normalizeJsonConfigForPlatform$1(json, compilerCtx) {
	const jsonPlatformOptions = resolveVueTransformJsonPlatformOptions(compilerCtx?.configService);
	if (!jsonPlatformOptions.normalizeUsingComponents) return json;
	try {
		const source = resolveJson({ json }, void 0, jsonPlatformOptions.platform, {
			dependencies: jsonPlatformOptions.dependencies,
			alipayNpmMode: jsonPlatformOptions.alipayNpmMode
		});
		if (!source) return json;
		return JSON.parse(source);
	} catch {
		return json;
	}
}
function resolveScopedSlotAutoImports(compilerCtx, baseUsingComponents, componentBase, template) {
	const autoImportService = compilerCtx?.autoImportService;
	const wxmlService = compilerCtx?.wxmlService;
	if (!autoImportService || !wxmlService) return { ...baseUsingComponents };
	const usingComponents = {};
	try {
		const token = wxmlService.analyze(template);
		const depComponentNames = Object.keys(token.components ?? {});
		for (const depComponentName of depComponentNames) {
			if (hasOwn(baseUsingComponents, depComponentName)) {
				usingComponents[depComponentName] = baseUsingComponents[depComponentName];
				continue;
			}
			const match = autoImportService.resolve(depComponentName, componentBase);
			if (!match) continue;
			const { value } = match;
			if (hasOwn(usingComponents, value.name)) continue;
			usingComponents[value.name] = value.from;
		}
	} catch {
		return { ...baseUsingComponents };
	}
	return usingComponents;
}
function resolveNestedScopedSlotUsingComponents(scopedSlots, currentComponentName, relativeBase, template) {
	const usingComponents = {};
	for (const scopedSlot of scopedSlots) {
		if (scopedSlot.componentName === currentComponentName) continue;
		if (!template.includes(scopedSlot.componentName)) continue;
		usingComponents[scopedSlot.componentName] = `/${toPosixPath(`${relativeBase}.__scoped-slot-${scopedSlot.id}`)}`;
	}
	return usingComponents;
}
function collectScopedSlotHostGenerics(scopedSlots, baseUsingComponents) {
	const result = /* @__PURE__ */ new Map();
	for (const scopedSlot of scopedSlots) {
		const hostComponentName = scopedSlot.hostComponentName;
		if (!hostComponentName) continue;
		const componentPath = baseUsingComponents[hostComponentName];
		if (!componentPath || !componentPath.startsWith("/")) continue;
		const key = `scoped-slots-${scopedSlot.slotKey}`;
		const keys = result.get(componentPath) ?? /* @__PURE__ */ new Set();
		keys.add(key);
		result.set(componentPath, keys);
	}
	return result;
}
function registerScopedSlotHostGenerics(ctx, scopedSlots, baseUsingComponents) {
	if (!ctx || !scopedSlots?.length) return;
	const hostGenerics = collectScopedSlotHostGenerics(scopedSlots, baseUsingComponents);
	for (const [componentPath, keys] of hostGenerics) {
		const registered = ctx.runtimeState.asset.scopedSlotGenerics.get(componentPath) ?? /* @__PURE__ */ new Set();
		for (const key of keys) registered.add(key);
		ctx.runtimeState.asset.scopedSlotGenerics.set(componentPath, registered);
	}
}
function emitScopedSlotAssets(ctx, bundle, relativeBase, result, compilerCtx, classStyleWxs, outputExtensions, jsonOptions) {
	const scopedSlots = result.scopedSlotComponents;
	if (!scopedSlots?.length) return;
	const { templateExtension, styleExtension, jsonExtension } = resolveBundleOutputExtensions(outputExtensions);
	const hasOwnerStyle = typeof result.style === "string" && result.style.trim().length > 0;
	if (hasOwnerStyle) emitSfcStyleIfMissing(ctx, bundle, relativeBase, "", styleExtension, { updateExisting: false });
	const configObj = parseJsonSafely$1(result.config) ?? {};
	const baseUsingComponents = configObj.usingComponents && typeof configObj.usingComponents === "object" && !Array.isArray(configObj.usingComponents) ? { ...configObj.usingComponents } : {};
	const usingComponents = { ...baseUsingComponents };
	registerScopedSlotHostGenerics(compilerCtx, scopedSlots, baseUsingComponents);
	for (const scopedSlot of scopedSlots) {
		const componentBase = `${relativeBase}.__scoped-slot-${scopedSlot.id}`;
		const componentPath = `/${toPosixPath(componentBase)}`;
		usingComponents[scopedSlot.componentName] = componentPath;
		const wxmlFile = `${componentBase}.${templateExtension}`;
		const styleFile = `${componentBase}.${styleExtension}`;
		const jsonFile = `${componentBase}.${jsonExtension}`;
		const scopedUsingComponents = resolveScopedSlotAutoImports(compilerCtx, baseUsingComponents, componentBase, scopedSlot.template);
		Object.assign(scopedUsingComponents, resolveNestedScopedSlotUsingComponents(scopedSlots, scopedSlot.componentName, relativeBase, scopedSlot.template));
		if (!bundle[wxmlFile]) ctx.emitFile({
			type: "asset",
			fileName: wxmlFile,
			source: scopedSlot.template
		});
		if (hasOwnerStyle && !bundle[styleFile]) ctx.emitFile({
			type: "asset",
			fileName: styleFile,
			source: resolveScopedSlotOwnerStyleImport(relativeBase, styleExtension)
		});
		if (!bundle[jsonFile]) {
			const mergeJson = createJsonMerger(jsonOptions?.mergeStrategy, {
				filename: jsonFile,
				kind: "component"
			});
			let json = mergeJson({}, { usingComponents: scopedUsingComponents }, "auto-using-components");
			if (scopedSlot.componentGenerics && Object.keys(scopedSlot.componentGenerics).length > 0) json = mergeJson(json, { componentGenerics: scopedSlot.componentGenerics }, "component-generics");
			if (jsonOptions?.defaults && Object.keys(jsonOptions.defaults).length > 0) json = mergeJson(json, jsonOptions.defaults, "defaults");
			const defaultConfig = {
				component: true,
				styleIsolation: "apply-shared"
			};
			json = mergeJson(defaultConfig, json, "emit");
			if (hasOwn(defaultConfig, "component")) json.component = true;
			const normalizedJson = normalizeJsonConfigForPlatform$1(json, compilerCtx);
			ctx.emitFile({
				type: "asset",
				fileName: jsonFile,
				source: JSON.stringify(normalizedJson, null, 2)
			});
		}
		if (scopedSlot.classStyleWxs && classStyleWxs) emitClassStyleWxsAssetIfMissing(ctx, bundle, classStyleWxs.fileName, classStyleWxs.source);
	}
	configObj.usingComponents = usingComponents;
	result.config = JSON.stringify(normalizeJsonConfigForPlatform$1(configObj, compilerCtx), null, 2);
}
//#endregion
//#region src/plugins/vue/transform/scopedSlot/module.ts
const SCOPED_SLOT_VIRTUAL_PREFIX = "\0weapp-vite:scoped-slot:";
function buildInlineExpressionMapCode(inlineExpressions) {
	if (!inlineExpressions?.length) return null;
	return `{${inlineExpressions.map((entry) => {
		const keys = JSON.stringify(entry.scopeKeys);
		return `${JSON.stringify(entry.id)}:{keys:${keys},fn:(ctx,scope,$event)=>${entry.expression}}`;
	}).join(",")}}`;
}
function buildTemplateRefsCode(templateRefs) {
	if (!templateRefs?.length) return null;
	return `[${templateRefs.map((binding) => {
		const fields = [`selector:${JSON.stringify(binding.selector)}`, `inFor:${binding.inFor}`];
		if (binding.name) fields.push(`name:${JSON.stringify(binding.name)}`);
		if (binding.expAst) fields.push(`get:function(){return ${generate(binding.expAst, { compact: true }).code}}`);
		if (binding.kind) fields.push(`kind:${JSON.stringify(binding.kind)}`);
		return `{${fields.join(",")}}`;
	}).join(",")}]`;
}
function buildScopedSlotComponentModule(options) {
	const computedCode = options?.computedCode;
	const inlineMapCode = options?.inlineMapCode;
	const templateRefsCode = options?.templateRefsCode;
	const lines = [`import { ${WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent} as _createWevuScopedSlotComponent } from '${WE_VU_COMPILER_RUNTIME_MODULE_ID}';`];
	if (computedCode) lines.push(`import { normalizeClass as __wevuNormalizeClass, normalizeStyle as __wevuNormalizeStyle } from '${WE_VU_COMPILER_TEMPLATE_MODULE_ID}';`);
	if (computedCode || templateRefsCode) lines.push(`import { unref as __wevuUnref } from '${WE_VU_COMPILER_REACTIVITY_MODULE_ID}';`);
	lines.push("const globalObject = typeof globalThis !== 'undefined' ? globalThis : undefined;", `const createWevuScopedSlotComponent = globalObject?.${WEVU_SCOPED_SLOT_CREATOR_KEY}`, "  ?? _createWevuScopedSlotComponent;");
	if (computedCode) lines.push(`const __wevuComputed = ${computedCode};`);
	if (inlineMapCode) lines.push(`const __wevuInlineMap = ${inlineMapCode};`);
	if (templateRefsCode) lines.push(`const __wevuTemplateRefs = ${templateRefsCode};`);
	const overrideParts = [];
	if (computedCode) overrideParts.push("computed: __wevuComputed");
	if (inlineMapCode) overrideParts.push("inlineMap: __wevuInlineMap");
	if (templateRefsCode) overrideParts.push("templateRefs: __wevuTemplateRefs");
	const overrideArg = overrideParts.length ? `{ ${overrideParts.join(", ")} }` : "";
	lines.push("if (typeof createWevuScopedSlotComponent === 'function') {");
	if (overrideArg) lines.push(`  createWevuScopedSlotComponent(${overrideArg});`);
	else lines.push("  createWevuScopedSlotComponent();");
	lines.push("}");
	lines.push("");
	return lines.join("\n");
}
function getScopedSlotVirtualId(componentBase) {
	return `${SCOPED_SLOT_VIRTUAL_PREFIX}${componentBase}`;
}
function emitScopedSlotChunks(ctx, relativeBase, result, scopedSlotModules, emittedScopedSlotChunks, outputExtensions) {
	const scopedSlots = result.scopedSlotComponents;
	if (!scopedSlots?.length) return;
	const { scriptExtension } = resolveCompilerOutputExtensions(outputExtensions);
	for (const scopedSlot of scopedSlots) {
		const componentBase = `${relativeBase}.__scoped-slot-${scopedSlot.id}`;
		const jsFile = `${componentBase}.${scriptExtension}`;
		if (emittedScopedSlotChunks.has(jsFile)) continue;
		const virtualId = getScopedSlotVirtualId(componentBase);
		if (!scopedSlotModules.has(virtualId)) {
			const computedCode = scopedSlot.classStyleBindings?.length ? buildClassStyleComputedCode(scopedSlot.classStyleBindings, {
				normalizeClassName: "__wevuNormalizeClass",
				normalizeStyleName: "__wevuNormalizeStyle",
				unrefName: "__wevuUnref"
			}) : null;
			const inlineMapCode = buildInlineExpressionMapCode(scopedSlot.inlineExpressions);
			const templateRefsCode = buildTemplateRefsCode(scopedSlot.templateRefs);
			scopedSlotModules.set(virtualId, buildScopedSlotComponentModule(computedCode || inlineMapCode || templateRefsCode ? {
				computedCode: computedCode ?? void 0,
				inlineMapCode: inlineMapCode ?? void 0,
				templateRefsCode: templateRefsCode ?? void 0
			} : void 0));
		}
		ctx.emitFile({
			type: "chunk",
			id: virtualId,
			fileName: jsFile,
			preserveSignature: "exports-only"
		});
		emittedScopedSlotChunks.add(jsFile);
	}
}
function resolveScopedSlotVirtualId(id) {
	if (!id.startsWith(SCOPED_SLOT_VIRTUAL_PREFIX)) return null;
	return id;
}
function loadScopedSlotModule(id, scopedSlotModules) {
	if (!id.startsWith(SCOPED_SLOT_VIRTUAL_PREFIX)) return null;
	const code = scopedSlotModules.get(id);
	if (!code) return null;
	return {
		code,
		map: null
	};
}
//#endregion
//#region src/plugins/vue/transform/slotFallbackWrapper.ts
const slotFallbackWrapperScriptByBundle = /* @__PURE__ */ new WeakMap();
function parseJsonSafely(source) {
	if (!source) return {};
	try {
		const parsed = JSON.parse(source);
		return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
	} catch {
		return {};
	}
}
function stringifyJson(json) {
	return JSON.stringify(json, null, 2);
}
function upsertSlotFallbackWrapperUsingComponent(json) {
	const usingComponents = json.usingComponents && typeof json.usingComponents === "object" && !Array.isArray(json.usingComponents) ? { ...json.usingComponents } : {};
	usingComponents[WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME] = WEVU_SLOT_FALLBACK_VIRTUAL_HOST_GLOBAL_PATH;
	json.usingComponents = usingComponents;
	return json;
}
function normalizeJsonConfigForPlatform(json, compilerCtx) {
	const jsonPlatformOptions = resolveVueTransformJsonPlatformOptions(compilerCtx?.configService);
	if (!jsonPlatformOptions.normalizeUsingComponents) return json;
	try {
		const source = resolveJson({ json }, void 0, jsonPlatformOptions.platform, {
			dependencies: jsonPlatformOptions.dependencies,
			alipayNpmMode: jsonPlatformOptions.alipayNpmMode
		});
		return source ? JSON.parse(source) : json;
	} catch {
		return json;
	}
}
function getSlotFallbackWrapperScriptCache(bundle) {
	let cache = slotFallbackWrapperScriptByBundle.get(bundle);
	if (!cache) {
		cache = /* @__PURE__ */ new Map();
		slotFallbackWrapperScriptByBundle.set(bundle, cache);
	}
	return cache;
}
function injectLocalSlotFallbackWrapperUsingComponentIfNeeded(options) {
	if (!options.result.slotFallbackWrapperComponent) return false;
	const config = upsertSlotFallbackWrapperUsingComponent(parseJsonSafely(options.result.config));
	options.result.config = stringifyJson(normalizeJsonConfigForPlatform(config, options.compilerCtx));
	return true;
}
function emitSlotFallbackWrapperScriptIfMissing(ctx, bundle, fileName, script) {
	const existing = bundle[fileName];
	if (existing && existing.type === "asset") {
		if ((existing.source?.toString?.() ?? "") !== script) existing.source = script;
		return;
	}
	const cache = getSlotFallbackWrapperScriptCache(bundle);
	if (cache.get(fileName) === script) return;
	if (!existing) {
		ctx.emitFile({
			type: "asset",
			fileName,
			source: script
		});
		cache.set(fileName, script);
	}
}
function emitSlotFallbackWrapperComponentAsset(options) {
	const component = options.result.slotFallbackWrapperComponent;
	if (!component) return;
	const { templateExtension, jsonExtension, scriptExtension } = resolveBundleOutputExtensions(options.outputExtensions);
	const componentBase = WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE;
	emitSfcTemplateIfMissing(options.ctx, options.bundle, componentBase, component.template, templateExtension);
	const jsonFileName = `${componentBase}.${jsonExtension}`;
	const mergeJson = createJsonMerger(options.jsonOptions?.mergeStrategy, {
		filename: jsonFileName,
		kind: "component"
	});
	let config = component.config;
	if (options.jsonOptions?.defaults && Object.keys(options.jsonOptions.defaults).length > 0) config = mergeJson(config, options.jsonOptions.defaults, "defaults");
	emitSfcJsonAsset(options.ctx, options.bundle, componentBase, { config: JSON.stringify(normalizeJsonConfigForPlatform(config, options.compilerCtx), null, 2) }, {
		kind: "component",
		extension: jsonExtension
	});
	emitSlotFallbackWrapperScriptIfMissing(options.ctx, options.bundle, `${componentBase}.${scriptExtension}`, component.script);
}
//#endregion
//#region src/plugins/vue/transform/bundle/shared/assets.ts
const APP_VUE_LIKE_FILE_RE$1 = /[\\/]app\.(?:vue|jsx|tsx)$/;
async function processVueResultStyle(style, configService) {
	if (!configService.platform) return style;
	return await processCssWithCache(style, configService);
}
function resolveVueBundleAssetContext(configService) {
	const outputExtensions = configService.outputExtensions;
	const bundleOutputExtensions = resolveBundleOutputExtensions(outputExtensions);
	return {
		outputExtensions,
		...bundleOutputExtensions,
		platformAssetOptions: resolveVueBundlePlatformAssetOptions({
			configService,
			templateExtension: bundleOutputExtensions.templateExtension,
			scriptModuleExtension: bundleOutputExtensions.scriptModuleExtension
		})
	};
}
function emitSharedVueEntryJsonAsset(options) {
	const normalizedConfig = preparePlatformConfigAsset(options.bundle, {
		pluginCtx: options.pluginCtx,
		relativeBase: options.relativeBase,
		config: options.config,
		kind: options.jsonOptions.kind,
		outputExtensions: options.outputExtensions,
		...options.platformAssetOptions
	});
	emitSfcJsonAsset(options.pluginCtx, options.bundle, options.relativeBase, { config: normalizedConfig }, options.jsonOptions);
}
async function emitSharedFallbackPageAssets(options) {
	const { bundle, pluginCtx, configService, relativeBase, result, outputExtensions, platformAssetOptions, styleExtension, jsonExtension, jsonDefaults, jsonMergeStrategy } = options;
	if (result.style) emitSfcStyleIfMissing(pluginCtx, bundle, relativeBase, await processVueResultStyle(result.style, configService), styleExtension);
	emitSharedVueEntryJsonAsset({
		bundle,
		pluginCtx,
		relativeBase,
		config: result.config,
		outputExtensions,
		platformAssetOptions,
		jsonOptions: {
			mergeExistingAsset: true,
			mergeStrategy: jsonMergeStrategy,
			defaults: jsonDefaults,
			kind: "page",
			extension: jsonExtension
		}
	});
}
function resolveClassStyleWxsAsset(ctx, relativeBase, wxsExtension, configService, result) {
	if (!(Boolean(result.classStyleWxs) || Boolean(result.scopedSlotComponents?.some((slot) => slot.classStyleWxs))) || typeof wxsExtension !== "string" || wxsExtension.length === 0) return;
	return {
		fileName: resolveClassStyleWxsLocationForBase(ctx, relativeBase, wxsExtension, configService).fileName,
		source: getClassStyleWxsSource({ extension: wxsExtension })
	};
}
function emitSharedVueEntryAssets(options) {
	const { bundle, pluginCtx, ctx, filename, relativeBase, result, configService, scriptModuleExtension, outputExtensions, platformAssetOptions, scopedSlotDefaults, scopedSlotMergeStrategy } = options;
	const isAppVue = APP_VUE_LIKE_FILE_RE$1.test(filename);
	if (result.template && !isAppVue) emitPlatformTemplateAsset(bundle, {
		ctx,
		pluginCtx,
		filename,
		relativeBase,
		template: result.template,
		...platformAssetOptions
	});
	const classStyleWxs = resolveClassStyleWxsAsset(ctx, relativeBase, scriptModuleExtension, configService, result);
	if (result.classStyleWxs && classStyleWxs) emitClassStyleWxsAssetIfMissing(pluginCtx, bundle, classStyleWxs.fileName, classStyleWxs.source);
	emitScopedSlotAssets(pluginCtx, bundle, relativeBase, result, ctx, classStyleWxs, outputExtensions, {
		defaults: scopedSlotDefaults,
		mergeStrategy: scopedSlotMergeStrategy
	});
	injectLocalSlotFallbackWrapperUsingComponentIfNeeded({
		bundle,
		result,
		compilerCtx: ctx,
		outputExtensions
	});
	emitSlotFallbackWrapperComponentAsset({
		ctx: pluginCtx,
		bundle,
		relativeBase,
		result,
		compilerCtx: ctx,
		outputExtensions,
		jsonOptions: {
			defaults: scopedSlotDefaults,
			mergeStrategy: scopedSlotMergeStrategy
		}
	});
	return { classStyleWxs };
}
function emitBundleVueEntryAssets(options) {
	const jsonConfig = options.configService.weappViteConfig?.json;
	emitSharedVueEntryAssets({
		...options,
		scopedSlotDefaults: jsonConfig?.defaults?.component,
		scopedSlotMergeStrategy: jsonConfig?.mergeStrategy
	});
	return { jsonConfig };
}
async function emitFallbackPageBundleAssets(options) {
	const { jsonConfig } = emitBundleVueEntryAssets({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		ctx: options.ctx,
		filename: options.filename,
		relativeBase: options.relativeBase,
		result: options.result,
		configService: options.configService,
		templateExtension: options.templateExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions
	});
	await emitSharedFallbackPageAssets({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		configService: options.configService,
		relativeBase: options.relativeBase,
		result: options.result,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions,
		styleExtension: options.styleExtension,
		jsonExtension: options.jsonExtension,
		jsonDefaults: jsonConfig?.defaults?.page,
		jsonMergeStrategy: jsonConfig?.mergeStrategy
	});
}
async function emitCompiledEntryBundleAssets(options) {
	const isAppVue = APP_VUE_LIKE_FILE_RE$1.test(options.filename);
	const hmrState = options.ctx.runtimeState?.build?.hmr;
	const shouldEmitComponentJson = !isAppVue && !options.isPage;
	const shouldMergeJsonAsset = isAppVue;
	const jsonKind = isAppVue ? "app" : options.isPage ? "page" : "component";
	const isStyleAssetHmr = (hmrState?.profile?.dirtyReasonSummary)?.some((item) => item.startsWith("entry-style-only:") || item.startsWith("style-sidecar:")) === true;
	const isAppVueHmrUpdate = Boolean(isAppVue && options.configService.isDev && typeof hmrState?.profile?.file === "string" && normalizeFsResolvedId(hmrState.profile.file) === normalizeFsResolvedId(options.filename));
	const sfcStyle = options.result.style;
	const shouldEmitSfcStyleAsset = typeof sfcStyle === "string" && sfcStyle.length > 0 && (isAppVue && (!options.configService.isDev || isAppVueHmrUpdate) || options.configService.isDev && isStyleAssetHmr && hmrState?.lastHmrEntryIds?.has(options.filename));
	const { jsonConfig } = emitBundleVueEntryAssets({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		ctx: options.ctx,
		filename: options.filename,
		relativeBase: options.relativeBase,
		result: options.result,
		configService: options.configService,
		templateExtension: options.templateExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions
	});
	if (shouldEmitSfcStyleAsset) {
		const style = await processVueResultStyle(sfcStyle, options.configService);
		emitSfcStyleIfMissing(options.pluginCtx, options.bundle, options.relativeBase, style, options.outputExtensions.wxss, isAppVue ? { updateExisting: false } : void 0);
	}
	const finalizeJsonConfig = isAppVue ? (config) => finalizeAppConfigForBuild(config, {
		buildScope: options.configService.weappViteConfig?.buildScope,
		platform: options.configService.platform,
		routeRules: options.configService.weappViteConfig?.routeRules
	}) : void 0;
	if (options.result.config || shouldEmitComponentJson) emitSharedVueEntryJsonAsset({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		relativeBase: options.relativeBase,
		config: options.result.config,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions,
		jsonOptions: {
			defaultConfig: shouldEmitComponentJson ? { component: true } : void 0,
			mergeExistingAsset: shouldMergeJsonAsset,
			mergeStrategy: jsonConfig?.mergeStrategy,
			defaults: jsonConfig?.defaults?.[jsonKind],
			...finalizeJsonConfig ? { finalizeConfig: finalizeJsonConfig } : {},
			kind: jsonKind,
			extension: options.jsonExtension
		}
	});
	return {
		isAppVue,
		shouldEmitComponentJson
	};
}
//#endregion
//#region src/plugins/vue/transform/compileOptions.ts
function hasVueExtension(id) {
	return Boolean(id?.endsWith(".vue"));
}
function getCompileVueFileOptionsCacheKey(vuePath, isPage, isApp, delegatesComponentRegistration = false, emitResolvedComponentEntries = true) {
	return `${vuePath}::${isPage ? "page" : "component"}::${isApp ? "app" : "entry"}::${delegatesComponentRegistration ? "logical-registration" : "module-registration"}::${emitResolvedComponentEntries ? "emit-entries" : "resolve-only"}`;
}
function shouldDelegateComponentRegistration(ctx, vuePath, isPage, isApp, configService) {
	return !isPage && !isApp && !configService.weappLibConfig?.enabled && !ctx.moduleGraphService?.isLogicalLayoutEntry?.(vuePath);
}
function isVueTransformSourceMapEnabled(configService) {
	return Boolean(configService.inlineConfig?.build?.sourcemap);
}
function resolveSfcStylePreprocessOptions(configService) {
	const options = configService.inlineConfig?.css?.preprocessorOptions;
	if (!options) return;
	const root = path.resolve(configService.cwd, configService.inlineConfig?.root ?? ".");
	const nodeModules = path.resolve(root, "node_modules");
	return Object.fromEntries(Object.entries(options).map(([language, languageOptions]) => {
		if (!["sass", "scss"].includes(language)) return [language, languageOptions];
		const loadPaths = Array.isArray(languageOptions.loadPaths) ? languageOptions.loadPaths.filter((value) => typeof value === "string") : [];
		return [language, {
			...languageOptions,
			loadPaths: Array.from(/* @__PURE__ */ new Set([...loadPaths, nodeModules]))
		}];
	}));
}
function resolveVueTemplatePlatformOptions(options) {
	const supportsWxs = options.wxsEnabled && typeof options.wxsExtension === "string" && options.wxsExtension.length > 0;
	const resolvedWxsExtension = supportsWxs ? options.wxsExtension : void 0;
	let classStyleRuntime = options.classStyleRuntime;
	if (options.classStyleRuntime === "auto") classStyleRuntime = supportsWxs ? "wxs" : "js";
	else if (options.classStyleRuntime === "wxs" && !supportsWxs) {
		classStyleRuntime = "js";
		if (!options.classStyleRuntimeWarned.value) {
			logger_default.warn("已配置 vue.template.classStyleRuntime = \"wxs\",但当前平台不支持 WXS 或已禁用 weapp.wxs,将回退到 JS 运行时。");
			options.classStyleRuntimeWarned.value = true;
		}
	}
	return {
		templatePlatform: getMiniProgramTemplatePlatform(options.platform),
		supportsWxs,
		wxsExtension: resolvedWxsExtension,
		classStyleRuntime
	};
}
function buildCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, configService, state, delegatesComponentRegistration) {
	const importerBaseName = removeExtensionDeep(vuePath);
	const autoImportResolveCache = /* @__PURE__ */ new Map();
	const resolveUsingComponentPath = createUsingComponentPathResolver(pluginCtx, configService, state.reExportResolutionCache);
	const externalComponentEntryMap = ctx.runtimeState?.build?.hmr?.externalComponentEntryMap;
	const registerResolvedComponentEntry = externalComponentEntryMap ? async (...args) => {
		const [importSource, importerFilename, info] = args;
		const resolved = await resolveUsingComponentPath(importSource, importerFilename, info);
		if (typeof resolved !== "string" && resolved?.from && resolved.resolvedId) {
			const outputKey = removeExtensionDeep(resolved.from).replace(/^\/+/, "");
			const isNewEntry = externalComponentEntryMap.get(outputKey) !== resolved.resolvedId;
			externalComponentEntryMap.set(outputKey, resolved.resolvedId);
			if (isNewEntry && state.emitResolvedComponentEntries !== false && typeof pluginCtx.emitFile === "function") pluginCtx.emitFile({
				type: "chunk",
				id: createLogicalEntryId(resolved.resolvedId, "component"),
				fileName: resolveRelativeOutputFileNameWithExtension(configService, resolved.resolvedId, ".js"),
				preserveSignature: "exports-only"
			});
		}
		return resolved;
	} : resolveUsingComponentPath;
	const scopedSlotsCompiler = configService.weappViteConfig?.vue?.template?.scopedSlotsCompiler ?? "auto";
	const scopedSlotsRequireProps = configService.weappViteConfig?.vue?.template?.scopedSlotsRequireProps ?? false;
	const slotSingleRootNoWrapper = configService.weappViteConfig?.vue?.template?.slotSingleRootNoWrapper ?? false;
	const slotFallbackWrapper = configService.weappViteConfig?.vue?.template?.slotFallbackWrapper;
	const slotFallbackWrapperStrategy = configService.weappViteConfig?.vue?.template?.slotFallbackWrapperStrategy ?? (configService.platform === "weapp" && slotFallbackWrapper === void 0 ? "virtual-host" : "view");
	const slotMultipleInstance = configService.weappViteConfig?.vue?.template?.slotMultipleInstance ?? true;
	const htmlTagToWxml = configService.weappViteConfig?.vue?.template?.htmlTagToWxml;
	const htmlTagToWxmlTagClass = configService.weappViteConfig?.vue?.template?.htmlTagToWxmlTagClass ?? true;
	const classStyleRuntimeConfig = configService.weappViteConfig?.vue?.template?.classStyleRuntime ?? "js";
	const objectLiteralBindMode = configService.weappViteConfig?.vue?.template?.objectLiteralBindMode ?? "runtime";
	const mustacheInterpolation = configService.weappViteConfig?.vue?.template?.mustacheInterpolation ?? "compact";
	const functionPropNames = configService.weappViteConfig?.vue?.template?.functionPropNames;
	const i18nConfig = configService.platform === "weapp" ? configService.weappViteConfig?.i18n : void 0;
	const templateSafeCallNames = i18nConfig ? [i18nConfig.functionName ?? "t"] : void 0;
	const formatWxmlConfig = configService.weappViteConfig?.vue?.template?.formatWxml ?? "auto";
	const formatWxml = formatWxmlConfig === "auto" ? configService.isDev : formatWxmlConfig;
	const wxsEnabled = configService.weappViteConfig?.wxs !== false;
	const wxsExtension = configService.outputExtensions?.wxs;
	const templatePlatformOptions = resolveVueTemplatePlatformOptions({
		platform: configService.platform,
		wxsEnabled,
		wxsExtension,
		classStyleRuntime: classStyleRuntimeConfig,
		classStyleRuntimeWarned: state.classStyleRuntimeWarned
	});
	const relativeBase = configService.relativeOutputPath(vuePath.slice(0, -4));
	const resolvedWxsExtension = templatePlatformOptions.wxsExtension;
	let classStyleWxsSrc;
	if (resolvedWxsExtension && relativeBase) classStyleWxsSrc = resolveClassStyleWxsLocationForBase(ctx, relativeBase, resolvedWxsExtension, configService).src;
	const jsonConfig = configService.weappViteConfig?.json;
	const wevuDefaults = resolveWevuDefaultsWithPreset(configService.weappViteConfig);
	const wevuMinify = isWevuMinifyEnabled(configService.weappViteConfig, configService.isDev);
	const jsonKind = isApp ? "app" : isPage ? "page" : "component";
	const sourceMap = isVueTransformSourceMapEnabled(configService);
	async function resolvePotentialVueSfcEntryId(candidate) {
		const trimmed = candidate?.trim();
		if (!trimmed) return;
		const entryResolveOptions = createCachedEntryResolveOptions(configService, { kind: "default" });
		const localCandidate = path.isAbsolute(trimmed) ? trimmed : trimmed.startsWith(".") ? path.resolve(path.dirname(vuePath), trimmed) : !trimmed.includes(":") && !trimmed.startsWith("@") ? path.resolve(configService.absoluteSrcRoot, trimmed) : void 0;
		if (localCandidate) {
			const normalized = normalizeFsResolvedId(localCandidate);
			if (hasVueExtension(normalized)) return normalized;
			const resolvedEntry = !normalized || isSkippableResolvedId(normalized) ? void 0 : await resolveEntryPath(normalized, entryResolveOptions);
			if (hasVueExtension(resolvedEntry)) return resolvedEntry;
		}
		const resolveCandidates = path.extname(trimmed) ? [trimmed] : [
			trimmed,
			`${trimmed}.vue`,
			`${trimmed}/index.vue`
		];
		for (const resolveCandidate of resolveCandidates) {
			const resolved = await pluginCtx.resolve?.(resolveCandidate, vuePath);
			const normalized = resolved?.id ? normalizeFsResolvedId(resolved.id) : void 0;
			if (!normalized || isSkippableResolvedId(normalized)) continue;
			if (hasVueExtension(normalized)) return normalized;
			if (path.isAbsolute(normalized)) {
				const resolvedEntry = await resolveEntryPath(normalized, entryResolveOptions);
				if (hasVueExtension(resolvedEntry)) return resolvedEntry;
			}
		}
	}
	async function resolveAutoImportComponentSourceType(match) {
		if (match.kind === "local") {
			const resolvedId = match.entry.templatePath;
			return {
				resolvedId,
				sourceType: hasVueExtension(resolvedId) ? "wevu-sfc" : "native"
			};
		}
		const explicitSourceType = match.value.sourceType;
		const explicitResolvedId = match.value.resolvedId;
		const resolvedExplicitVueId = await resolvePotentialVueSfcEntryId(explicitResolvedId);
		if (explicitSourceType || resolvedExplicitVueId || hasVueExtension(explicitResolvedId) || hasVueExtension(match.value.from)) return {
			resolvedId: resolvedExplicitVueId ?? explicitResolvedId,
			sourceType: explicitSourceType ?? (resolvedExplicitVueId || hasVueExtension(explicitResolvedId) || hasVueExtension(match.value.from) ? "wevu-sfc" : "native")
		};
		let localSourceBase;
		if (match.value.from.startsWith("/")) localSourceBase = path.join(configService.absoluteSrcRoot, match.value.from.slice(1));
		else if (match.value.from.startsWith(".")) localSourceBase = path.resolve(path.dirname(importerBaseName), match.value.from);
		if (!localSourceBase) return {
			resolvedId: explicitResolvedId,
			sourceType: "native"
		};
		const resolvedId = await resolveEntryPath(localSourceBase, createCachedEntryResolveOptions(configService, { kind: "default" }));
		return {
			resolvedId,
			sourceType: hasVueExtension(resolvedId) ? "wevu-sfc" : "native"
		};
	}
	return {
		isPage,
		isApp,
		skipComponentTransform: delegatesComponentRegistration,
		warn: (message) => logger_default.warn(message),
		autoUsingComponents: {
			enabled: true,
			warn: (message) => logger_default.warn(message),
			resolveUsingComponentPath: registerResolvedComponentEntry
		},
		autoImportTags: {
			enabled: true,
			warn: (message) => logger_default.warn(message),
			resolveUsingComponent: async (tag) => {
				const autoImportService = ctx.autoImportService;
				if (!autoImportService) return;
				const version = typeof autoImportService.getVersion === "function" ? autoImportService.getVersion() : 0;
				const cached = autoImportResolveCache.get(tag);
				const match = cached && cached.version === version ? cached.match : autoImportService.resolve(tag, importerBaseName);
				if (!cached || cached.version !== version) autoImportResolveCache.set(tag, {
					match,
					version
				});
				if (!match?.value) return;
				const sourceInfo = await resolveAutoImportComponentSourceType(match);
				const stableFrom = sourceInfo.sourceType === "wevu-sfc" ? usingComponentFromResolvedFile(sourceInfo.resolvedId, configService) : void 0;
				if (stableFrom && sourceInfo.resolvedId) ctx.runtimeState?.build?.hmr?.externalComponentEntryMap?.set(removeExtensionDeep(stableFrom).replace(/^\/+/, ""), sourceInfo.resolvedId);
				return {
					...match.value,
					...sourceInfo,
					...stableFrom ? { from: stableFrom } : {}
				};
			}
		},
		template: {
			platform: templatePlatformOptions.templatePlatform,
			htmlTagToWxml,
			htmlTagToWxmlTagClass,
			scopedSlotsCompiler,
			scopedSlotsRequireProps,
			slotSingleRootNoWrapper,
			slotFallbackWrapper,
			slotFallbackWrapperStrategy,
			slotMultipleInstance,
			classStyleRuntime: templatePlatformOptions.classStyleRuntime,
			objectLiteralBindMode,
			mustacheInterpolation,
			functionPropNames,
			templateSafeCallNames,
			formatWxml,
			wxsExtension: templatePlatformOptions.wxsExtension,
			classStyleWxsSrc
		},
		style: { preprocessOptions: resolveSfcStylePreprocessOptions(configService) },
		json: {
			kind: jsonKind,
			defaults: jsonConfig?.defaults,
			mergeStrategy: jsonConfig?.mergeStrategy
		},
		sfcSrc: createSfcResolveSrcOptions(pluginCtx, configService),
		wevuDefaults,
		minify: wevuMinify,
		sourceMap,
		componentMetaCache: state.componentMetaCache
	};
}
function createCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, configService, state) {
	const delegatesComponentRegistration = shouldDelegateComponentRegistration(ctx, vuePath, isPage, isApp, configService);
	const cacheKey = getCompileVueFileOptionsCacheKey(vuePath, isPage, isApp, delegatesComponentRegistration, state.emitResolvedComponentEntries !== false);
	const cached = state.compileOptionsCache?.get(cacheKey);
	if (cached) return cached;
	const created = buildCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, configService, state, delegatesComponentRegistration);
	state.compileOptionsCache?.set(cacheKey, created);
	return created;
}
//#endregion
//#region src/plugins/utils/viteResolverAdapter.ts
const WINDOWS_ABSOLUTE_PATH_RE = /^[A-Z]:[\\/]/i;
function isExplicitFileRequest(id) {
	return id.startsWith(".") || id.startsWith("/") || WINDOWS_ABSOLUTE_PATH_RE.test(id);
}
function isFilePathLike(id) {
	return Boolean(path.extname(id));
}
function resolveLocalFile(source, importer, normalizeOptions) {
	const cleanSource = normalizeFsResolvedId(source, normalizeOptions);
	if (!isExplicitFileRequest(cleanSource) || !isFilePathLike(cleanSource)) return;
	const candidate = path.isAbsolute(cleanSource) || WINDOWS_ABSOLUTE_PATH_RE.test(cleanSource) ? cleanSource : importer ? path.resolve(path.dirname(normalizeFsResolvedId(importer, normalizeOptions)), cleanSource) : void 0;
	if (!candidate) return;
	try {
		return fs.statSync(candidate).isFile() ? candidate : void 0;
	} catch {
		return;
	}
}
function createViteResolverAdapter(resolver, reader, options) {
	const checkMtime = options?.checkMtime;
	const normalizeOptions = options?.normalize;
	return {
		resolveId: async (source, importer) => {
			const localFile = resolveLocalFile(source, importer, normalizeOptions);
			if (localFile) return localFile;
			const resolved = await resolver.resolve(source, importer);
			return resolved ? resolved.id : void 0;
		},
		loadCode: async (resolvedId) => {
			const clean = normalizeFsResolvedId(resolvedId, normalizeOptions);
			if (isSkippableResolvedId(clean)) return;
			try {
				return await reader.readFile(clean, { checkMtime });
			} catch {
				return;
			}
		}
	};
}
//#endregion
//#region src/plugins/vue/transform/injectPageFeatures.ts
async function injectWevuPageFeaturesInJsWithViteResolver(ctx, source, id, options) {
	const checkMtime = options?.checkMtime ?? true;
	const injected = await injectWevuPageFeaturesInJsWithResolver(source, {
		id,
		resolver: createViteResolverAdapter({ resolve: (source, importer) => ctx.resolve(source, importer) }, { readFile: readFile$1 }, { checkMtime }),
		minify: options?.minify,
		sourceMap: options?.sourceMap
	});
	return {
		...injected,
		map: normalizeEncodedSourceMapLike(injected.map)
	};
}
//#endregion
//#region src/plugins/vue/transform/plugin/shared/autoRoutes.ts
const AUTO_ROUTES_DYNAMIC_IMPORT_RE = /import\(\s*['"](?:weapp-vite\/auto-routes|virtual:weapp-vite-auto-routes)['"]\s*\)/g;
const AUTO_ROUTES_ID = "weapp-vite/auto-routes";
const AUTO_ROUTES_VIRTUAL_ID = "virtual:weapp-vite-auto-routes";
const AUTO_ROUTES_NAMED_IMPORT_ALIAS_RE = /\s+as\s+/g;
const AUTO_ROUTES_DEFAULT_AND_NAMED_IMPORT_RE = /^([A-Z_$][\w$]*)\s*,\s*(\{[^}]+\})$/i;
function mayNeedInlineAutoRoutes(source) {
	return source.includes(AUTO_ROUTES_ID) || source.includes(AUTO_ROUTES_VIRTUAL_ID);
}
function toObjectDestructureClause(namedImportClause) {
	return namedImportClause.replace(AUTO_ROUTES_NAMED_IMPORT_ALIAS_RE, ": ");
}
function resolveInlineAutoRoutesImport(line, inlineRoutes, replacementIndex) {
	const trimmedLine = line.trim();
	if (!trimmedLine.startsWith("import ") || !trimmedLine.includes(" from ") || !trimmedLine.includes(`'${AUTO_ROUTES_ID}'`) && !trimmedLine.includes(`"${AUTO_ROUTES_ID}"`) && !trimmedLine.includes(`'${AUTO_ROUTES_VIRTUAL_ID}'`) && !trimmedLine.includes(`"${AUTO_ROUTES_VIRTUAL_ID}"`)) return;
	const clause = trimmedLine.slice(7, trimmedLine.lastIndexOf(" from ")).trim();
	const inlineLiteral = JSON.stringify(inlineRoutes);
	if (clause.startsWith("{")) return `const ${toObjectDestructureClause(clause)} = ${inlineLiteral};`;
	if (clause.startsWith("* as ")) return `const ${clause.slice(5).trim()} = ${inlineLiteral};`;
	const defaultAndNamedMatch = clause.match(AUTO_ROUTES_DEFAULT_AND_NAMED_IMPORT_RE);
	if (defaultAndNamedMatch) {
		const [, defaultName, namedClause] = defaultAndNamedMatch;
		const localRef = `__weappViteAutoRoutesInline${replacementIndex}`;
		return `const ${localRef} = ${inlineLiteral};\nconst ${defaultName} = ${localRef};\nconst ${toObjectDestructureClause(namedClause)} = ${localRef};`;
	}
	return `const ${clause} = ${inlineLiteral};`;
}
function createTransformStageMeasurer(vueTransformTiming) {
	const stageTimings = {};
	const totalStart = vueTransformTiming ? performance$1.now() : 0;
	const measureStage = async (label, task) => {
		if (!vueTransformTiming) return await task();
		const start = performance$1.now();
		const result = await task();
		stageTimings[label] = Number((performance$1.now() - start).toFixed(2));
		return result;
	};
	const reportTiming = (id, isPage) => {
		if (!vueTransformTiming) return;
		vueTransformTiming({
			id,
			isPage,
			totalMs: Number((performance$1.now() - totalStart).toFixed(2)),
			stages: stageTimings
		});
	};
	return {
		measureStage,
		reportTiming
	};
}
async function resolveTransformAutoRoutesSource(options) {
	const { source, autoRoutesService } = options;
	if (!mayNeedInlineAutoRoutes(source)) return {
		source,
		signature: void 0
	};
	AUTO_ROUTES_DYNAMIC_IMPORT_RE.lastIndex = 0;
	await autoRoutesService?.ensureFresh?.();
	const routesRef = autoRoutesService?.getReference?.();
	const inlineRoutes = {
		pages: routesRef?.pages ?? [],
		entries: routesRef?.entries ?? [],
		subPackages: routesRef?.subPackages ?? []
	};
	const signature = autoRoutesService?.getSignature?.();
	let importReplacementIndex = 0;
	return {
		source: source.split("\n").map((line) => {
			const replaced = resolveInlineAutoRoutesImport(line, inlineRoutes, importReplacementIndex);
			if (replaced) {
				importReplacementIndex += 1;
				return replaced;
			}
			return line;
		}).join("\n").replace(AUTO_ROUTES_DYNAMIC_IMPORT_RE, `Promise.resolve(${JSON.stringify(inlineRoutes)})`),
		signature
	};
}
//#endregion
//#region src/plugins/wevuPageFeatureHints.ts
const WEVU_RUNTIME_MODULE_HINTS = [
	"'wevu'",
	"\"wevu\"",
	"'wevu/internal-runtime'",
	"\"wevu/internal-runtime\"",
	...Object.values(WEAPP_VITE_RUNTIME_VIRTUAL_IDS).flatMap((moduleId) => [`'${moduleId}'`, `"${moduleId}"`])
];
const PAGE_FEATURE_HOOK_HINTS = [
	"onPageScroll",
	"onPullDownRefresh",
	"onReachBottom",
	"onRouteDone",
	"onTabItemTap",
	"onResize",
	"onShareAppMessage",
	"onShareTimeline",
	"onAddToFavorites",
	"onSaveExitState"
];
function mayNeedWevuPageFeatureAnalysis(code) {
	return WEVU_RUNTIME_MODULE_HINTS.some((hint) => code.includes(hint)) || PAGE_FEATURE_HOOK_HINTS.some((hint) => code.includes(hint));
}
//#endregion
//#region src/plugins/vue/transform/plugin/shared/state.ts
const APP_ENTRY_RE = /[\\/]app\.(?:vue|jsx|tsx)$/;
const TEMPLATE_MUSTACHE_HINT = "{{";
const TEMPLATE_EVENT_HINT_RE = /\b(?:bind|catch)[A-Za-z:_-]+=/;
const PAGE_SCROLL_HOOK_HINT = "onPageScroll";
function resolveScriptlessVueEntryStub(isPage) {
	return isPage ? "Page({})" : "Component({})";
}
function isAppEntry(filename) {
	return APP_ENTRY_RE.test(filename);
}
function isVueLikeId(id) {
	return isVueLikeFile(id);
}
function resolveDirtyVueEntryId(dirtyVueEntryIds, filename) {
	if (!dirtyVueEntryIds?.size) return;
	const normalizedFilename = normalizeFsResolvedId(filename);
	if (dirtyVueEntryIds.has(filename)) return filename;
	if (dirtyVueEntryIds.has(normalizedFilename)) return normalizedFilename;
	for (const entryId of dirtyVueEntryIds) if (normalizeFsResolvedId(entryId) === normalizedFilename) return entryId;
}
function isVueStyleOnlyDirtyReasonSummary(dirtyReasonSummary) {
	return dirtyReasonSummary?.some((item) => item.startsWith("entry-style-only:") || item.startsWith("css-importer") || item.startsWith("style-sidecar:")) === true;
}
function isVueCssImporterDirtyReasonSummary(dirtyReasonSummary) {
	return dirtyReasonSummary?.some((item) => item.startsWith("css-importer")) === true;
}
function mayNeedTransformSetDataPick(template, options) {
	if (template.includes(TEMPLATE_MUSTACHE_HINT)) return true;
	const directivePrefix = getWxmlDirectivePrefix(options?.platform);
	if (new RegExp(`${escapeStringRegexp(directivePrefix)}:`).test(template)) return true;
	return TEMPLATE_EVENT_HINT_RE.test(template);
}
function mayNeedTransformPageFeatureInjection(script) {
	return mayNeedWevuPageFeatureAnalysis(script);
}
function mayNeedTransformPageScrollDiagnostics(script) {
	return script.includes(PAGE_SCROLL_HOOK_HINT);
}
function resolveTransformFilename(options) {
	const { id, configService, getSourceFromVirtualId } = options;
	const filename = toAbsoluteId(getSourceFromVirtualId(id), configService, void 0, { base: "cwd" });
	if (!filename || !path.isAbsolute(filename)) return null;
	return filename;
}
async function loadTransformPageEntries(scanService) {
	if (!scanService) return {
		pages: [],
		subPackages: [],
		pluginPages: []
	};
	const appEntry = await scanService.loadAppEntry();
	const subPackages = scanService.loadSubPackages().map((meta) => ({
		root: meta.subPackage.root,
		pages: meta.subPackage.pages
	}));
	const pluginPages = scanService.pluginJson ? Object.values(scanService.pluginJson.pages ?? {}).map((page) => String(page)) : [];
	return {
		pages: appEntry.json?.pages ?? [],
		subPackages,
		pluginPages
	};
}
function invalidatePageLayoutCaches(configService, compilationCache, styleBlocksCache, styleRefreshTokens) {
	if (!configService) return;
	for (const [cachedId, cached] of compilationCache.entries()) {
		if (cached.isPage) {
			cached.source = void 0;
			cached.styleIndependentSignature = void 0;
		}
		styleBlocksCache.delete(cachedId);
		styleRefreshTokens?.delete(cachedId);
	}
}
function invalidateVueFileCaches(file, compilationCache, styleBlocksCache, options, styleRefreshTokens) {
	if (!options.existsSync(file)) {
		compilationCache.delete(file);
		styleRefreshTokens?.delete(file);
	} else {
		const cached = compilationCache.get(file);
		if (cached) cached.refreshToken = (cached.refreshToken ?? 0) + 1;
	}
	styleBlocksCache.delete(file);
}
function handleTransformLayoutInvalidation(file, options) {
	const { configService, compilationCache, styleBlocksCache, styleRefreshTokens, isLayoutFile, invalidateResolvedPageLayoutsCache } = options;
	if (!configService || !isLayoutFile(file, configService)) return false;
	invalidateResolvedPageLayoutsCache(configService.absoluteSrcRoot);
	invalidatePageLayoutCaches(configService, compilationCache, styleBlocksCache, styleRefreshTokens);
	return true;
}
function handleTransformVueFileInvalidation(file, options) {
	if (!isVueLikeId(file)) return false;
	invalidateVueFileCaches(file, options.compilationCache, options.styleBlocksCache, { existsSync: options.existsSync }, options.styleRefreshTokens);
	return true;
}
async function ensureSfcStyleBlocks(filename, styleBlocksCache, options) {
	const cached = styleBlocksCache.get(filename);
	if (cached) return cached;
	const styles = await options.load(filename);
	styleBlocksCache.set(filename, styles);
	return styles;
}
async function loadTransformSource(options) {
	const { code, filename, isDev, readFileCached } = options;
	if (typeof code === "string") return code;
	return isDev ? await readFileCached(filename, {
		checkMtime: true,
		encoding: "utf8"
	}) : await fs$1.readFile(filename, "utf-8");
}
async function preloadTransformSfcStyleBlocks(options) {
	const { filename, source, styleBlocksCache, load } = options;
	if (!filename.endsWith(".vue") || !source.includes("<style")) return;
	try {
		return await ensureSfcStyleBlocks(filename, styleBlocksCache, { load: async (target) => await load(target, source) });
	} catch {
		return;
	}
}
//#endregion
//#region src/plugins/vue/transform/plugin/shared/layout.ts
async function handleTransformEntryPageLayoutFlow(options) {
	const configService = options.ctx.configService;
	if (!configService) return;
	const resolvedLayoutPlan = await resolvePageLayoutPlan(options.source, options.filename, configService);
	if (!resolvedLayoutPlan) return;
	if (options.result) applyPageLayoutPlan(options.result, options.filename, resolvedLayoutPlan, { platform: configService.platform });
	await registerResolvedPageLayoutDependencies(options.ctx, options.filename, resolvedLayoutPlan.layouts);
	return resolvedLayoutPlan;
}
async function resolveTransformEntryFlags(options) {
	const { pageMatcher, setPageMatcher, createPageMatcher, configService, scanService, scanDirty, scanDirtySynced, setScanDirtySynced, filename } = options;
	if (configService.weappLibConfig?.enabled) return {
		isPage: false,
		isApp: false,
		pageMatcher: pageMatcher ?? null
	};
	const pageSourceRoot = configService.pluginOnly ? configService.absolutePluginRoot ?? configService.absoluteSrcRoot : configService.absoluteSrcRoot;
	const currentPageMatcher = pageMatcher ?? createPageMatcher({
		srcRoot: pageSourceRoot,
		loadEntries: async () => await loadTransformPageEntries(scanService),
		warn: () => {}
	});
	setPageMatcher(currentPageMatcher);
	if (scanDirty && !scanDirtySynced) {
		currentPageMatcher.markDirty();
		setScanDirtySynced(true);
	} else if (!scanDirty && scanDirtySynced) setScanDirtySynced(false);
	return {
		isPage: await currentPageMatcher.isPageFile(filename),
		isApp: isAppEntry(filename),
		pageMatcher: currentPageMatcher
	};
}
async function registerNativeLayoutChunksForEntry(pluginCtx, ctx, filename, source) {
	await handleTransformEntryPageLayoutFlow({
		pluginCtx,
		ctx,
		filename,
		source
	});
}
async function preloadNativeLayoutEntries(options) {
	const { pluginCtx, ctx, configService, scanService, collectFallbackPageEntryIds, findFirstResolvedVueLikeEntry, pathExists, readFile } = options;
	if (!configService || !scanService) return;
	const entryIds = await collectFallbackPageEntryIds(configService, scanService);
	await Promise.all(entryIds.map(async (entryId) => {
		const entryFilePath = await findFirstResolvedVueLikeEntry(entryId, { resolve: async (candidate) => await pathExists(candidate) ? candidate : void 0 });
		if (!entryFilePath) return;
		try {
			const source = await readFile(entryFilePath, "utf8");
			await registerNativeLayoutChunksForEntry(pluginCtx, ctx, entryFilePath, source);
		} catch {}
	}));
}
async function loadTransformStyleBlock(options) {
	const { id, pluginCtx, ctx, configService, styleBlocksCache, loadScopedSlotModule, scopedSlotModules, parseWeappVueStyleRequest, readAndParseSfc, createReadAndParseSfcOptions } = options;
	const scopedSlot = loadScopedSlotModule(id, scopedSlotModules);
	if (scopedSlot) return scopedSlot;
	const parsed = parseWeappVueStyleRequest(id);
	if (!parsed) return null;
	const { filename, index } = parsed;
	const loadStyleBlocks = async (target) => (await readAndParseSfc(target, { ...createReadAndParseSfcOptions(pluginCtx, configService) })).descriptor.styles;
	let styles;
	try {
		const cachedStyles = styleBlocksCache.get(filename);
		styles = await ensureSfcStyleBlocks(filename, styleBlocksCache, { load: loadStyleBlocks });
		const cachedBlock = cachedStyles?.[index];
		if (typeof cachedBlock?.src === "string" && cachedBlock.src.trim()) {
			styles = await loadStyleBlocks(filename);
			styleBlocksCache.set(filename, styles);
		}
	} catch {
		return null;
	}
	const block = styles[index];
	if (!block) return null;
	const dependencies = syncVueSfcStyleDependencies(ctx, filename, styles);
	ctx.moduleGraphService.replaceEntryDependencies(filename, "style", dependencies);
	const compiled = await compileVueStyleToWxss(block, {
		id: generateScopedId(filename),
		filename,
		scoped: block.scoped,
		modules: block.module,
		preprocessOptions: resolveSfcStylePreprocessOptions(configService)?.[block.lang || "css"]
	});
	for (const dependency of compiled.dependencies ?? []) pluginCtx.addWatchFile?.(dependency);
	return {
		code: compiled.code,
		map: compiled.map ? JSON.parse(compiled.map) : null
	};
}
//#endregion
//#region src/plugins/vue/transform/plugin/shared/compile.ts
function normalizeVueTransformResult(result) {
	return {
		...result,
		scriptMap: normalizeEncodedSourceMapLike(result.scriptMap)
	};
}
async function finalizeTransformEntryScript(options) {
	const { result, filename, pluginCtx, configService, isPage, isApp, forcePageFeatureInjection = false, sourceMap = true } = options;
	if (isPage && result.script) {
		if (mayNeedTransformPageScrollDiagnostics(result.script)) for (const warning of collectOnPageScrollPerformanceWarnings(result.script, filename, { engine: resolveAstEngine(configService.weappViteConfig) })) logger_default.warn(warning);
		if (forcePageFeatureInjection || mayNeedTransformPageFeatureInjection(result.script)) {
			const injected = await injectWevuPageFeaturesInJsWithViteResolver(pluginCtx, result.script, filename, {
				checkMtime: configService.isDev,
				minify: isWevuMinifyEnabled(configService.weappViteConfig, configService.isDev),
				sourceMap
			});
			if (injected.transformed) {
				result.script = injected.code;
				result.scriptMap = composeSourceMaps(injected.map, result.scriptMap);
			}
		}
	}
	const shouldAutoSetDataPick = !isApp && result.script && result.template && isAutoSetDataPickEnabled(configService.weappViteConfig) && mayNeedTransformSetDataPick(result.template, { platform: configService.platform }) && mayNeedInjectSetDataPickInJs(result.script);
	const shouldInjectScopedSlotOwnerPick = !isApp && result.script && result.template?.includes(WEVU_SLOT_OWNER_ID_ATTR) && mayNeedInjectSetDataPickInJs(result.script);
	if (shouldAutoSetDataPick) {
		const keys = collectSetDataPickKeysFromTemplate(result.template, { astEngine: resolveAstEngine(configService.weappViteConfig) });
		const scopedSlotPickKeys = shouldUseScopedSlotOwnerOnlySetDataPick(keys) ? pruneScopedSlotOwnerAutoSetDataPickKeys(keys) : keys;
		const injectedPick = shouldInjectScopedSlotOwnerPick ? injectScopedSlotOwnerSetDataPickInJs(result.script, scopedSlotPickKeys, { sourceMap }) : injectSetDataPickInJs(result.script, keys, { sourceMap });
		if (injectedPick.transformed) {
			result.script = injectedPick.code;
			result.scriptMap = composeSourceMaps(injectedPick.map, result.scriptMap);
		}
	} else if (shouldInjectScopedSlotOwnerPick) {
		const keys = collectSetDataPickKeysFromTemplate(result.template, { astEngine: resolveAstEngine(configService.weappViteConfig) });
		const injectedPick = injectScopedSlotOwnerSetDataPickInJs(result.script, pruneScopedSlotOwnerAutoSetDataPickKeys(keys), { sourceMap });
		if (injectedPick.transformed) {
			result.script = injectedPick.code;
			result.scriptMap = composeSourceMaps(injectedPick.map, result.scriptMap);
		}
	}
	const hasScopedSlotHostGenerics = Boolean(result.componentGenerics && Object.keys(result.componentGenerics).length > 0);
	const needsSetupSlotHostProperties = result.script && mayNeedScopedSlotHostPropertiesForSetupSlotsInJs(result.script);
	if (!isPage && !isApp && result.script && (hasScopedSlotHostGenerics || result.template?.includes(WEVU_SLOT_OWNER_ID_PROP) || result.template?.includes("<slot") || result.template?.includes("vueSlots") || needsSetupSlotHostProperties)) {
		const injectedProps = injectScopedSlotHostPropertiesInJs(result.script, { sourceMap });
		if (injectedProps.transformed) {
			result.script = injectedProps.code;
			result.scriptMap = composeSourceMaps(injectedProps.map, result.scriptMap);
		}
	}
	return result;
}
function finalizeTransformEntryCode(options) {
	const { result, filename, styleBlocks, isPage, isApp, isDev, sourceMap = true, hmrStyleToken } = options;
	const script = result.script ?? "";
	const returned = new MagicString(script);
	let hasMutation = false;
	if (styleBlocks?.length) {
		const styleImports = buildWeappVueStyleRequests(filename, styleBlocks, { hmrToken: hmrStyleToken }).map((request) => `import ${JSON.stringify(request)};\n`).join("");
		returned.prepend(styleImports);
		hasMutation = true;
	}
	if (!isApp && !result.script?.trim()) {
		returned.append(resolveScriptlessVueEntryStub(isPage));
		hasMutation = true;
	}
	const macroHash = result.meta?.jsonMacroHash;
	if (macroHash && isDev) {
		returned.append(`\n;Object.defineProperty({}, '__weappViteJsonMacroHash', { value: ${JSON.stringify(macroHash)} })\n`);
		hasMutation = true;
	}
	const defineOptionsHash = result.meta?.defineOptionsHash;
	if (defineOptionsHash && isDev) {
		returned.append(`\n;Object.defineProperty({}, '__weappViteDefineOptionsHash', { value: ${JSON.stringify(defineOptionsHash)} })\n`);
		hasMutation = true;
	}
	const generatedMap = hasMutation && sourceMap ? returned.generateMap({
		hires: true,
		includeContent: true,
		source: filename,
		file: filename
	}) : null;
	return {
		code: returned.toString(),
		map: sourceMap ? composeSourceMaps(generatedMap, result.scriptMap) : null
	};
}
async function compileTransformEntryResult(options) {
	const { transformedSource, filename, compileOptions, compileVueFile, compileJsxFile } = options;
	return filename.endsWith(".vue") ? await compileVueFile(transformedSource, filename, compileOptions) : await compileJsxFile(transformedSource, filename, compileOptions);
}
async function finalizeTransformCompiledResult(options) {
	const { ctx, pluginCtx, filename, source, autoRoutesSignature, result, compilationCache, styleIndependentSignature, setAppShell, configService, isPage, isApp, sourceMap, scopedSlotModules, emittedScopedSlotChunks, emitScopedSlotChunks } = options;
	const transformResult = result;
	if (isPage && result.template) await handleTransformEntryPageLayoutFlow({
		pluginCtx,
		ctx,
		filename,
		source,
		result
	});
	if (isApp) setAppShell?.(hasAppShellTemplate(result) ? resolveAppShellLayout(configService) : void 0);
	if (!isApp) registerVueTemplateToken(ctx, filename, result.template);
	if (Array.isArray(result.meta?.sfcSrcDeps)) ctx.moduleGraphService.replaceEntryDependencies(filename, "style", result.meta.sfcSrcDeps);
	const jsxDependencies = result.meta?.jsxDependencies ?? [];
	addNormalizedWatchFiles(pluginCtx, jsxDependencies);
	ctx.moduleGraphService.replaceEntryDependencies(filename, "jsx", jsxDependencies);
	await finalizeTransformEntryScript({
		result: transformResult,
		filename,
		pluginCtx,
		configService,
		isPage,
		isApp,
		sourceMap
	});
	compilationCache.set(filename, {
		result,
		source,
		isPage,
		autoRoutesSignature,
		refreshToken: 0,
		styleIndependentSignature
	});
	if (configService.isDev && filename.endsWith(".vue")) {
		const normalizedFilename = normalizeFsResolvedId(filename);
		const hmr = ctx.runtimeState?.build?.hmr;
		const signatures = resolveVueSfcHmrSignatures(source, filename);
		if (hmr) storeVueSfcHmrSignatures(hmr, normalizedFilename, signatures);
	}
	const relativeBase = resolveVueOutputBase(configService, filename);
	if (relativeBase) emitScopedSlotChunks(pluginCtx, relativeBase, result, scopedSlotModules, emittedScopedSlotChunks, configService.outputExtensions);
	return transformResult;
}
function logTransformFileError(filename, error) {
	const message = error instanceof Error ? error.message : String(error);
	logger_default.error(`[Vue 编译] 编译 ${filename} 失败:${message}`);
}
//#endregion
//#region src/plugins/vue/transform/styleOnly.ts
function hasCssModules(styleBlocks) {
	return styleBlocks?.some((styleBlock) => Boolean(styleBlock.module)) === true;
}
async function refreshStyleOnlyVueTransformResult(result, filename, styleBlocks, stylePreprocessOptions) {
	if (!styleBlocks || hasCssModules(styleBlocks)) return false;
	if (!styleBlocks.length) {
		result.style = void 0;
		return true;
	}
	const scopedId = generateScopedId(filename);
	result.style = (await Promise.all(styleBlocks.map(async (styleBlock) => await compileVueStyleToWxss(styleBlock, {
		id: scopedId,
		filename,
		scoped: styleBlock.scoped,
		modules: styleBlock.module,
		preprocessOptions: stylePreprocessOptions?.[styleBlock.lang || "css"]
	})))).map((result) => result.code.trim()).filter(Boolean).join("\n\n") || void 0;
	return true;
}
//#endregion
//#region src/plugins/vue/transform/bundle/shared/types.ts
function getVueBundlePageLayoutPlan(result) {
	return result.meta?.pageLayoutPlan;
}
function setVueBundlePageLayoutPlan(result, plan) {
	const current = result;
	current.meta = {
		...current.meta,
		pageLayoutPlan: plan
	};
}
//#endregion
//#region src/plugins/vue/transform/bundle/shared/layout.ts
const APP_VUE_LIKE_FILE_RE = /[\\/]app\.(?:vue|jsx|tsx)$/;
function getEntryBaseName(filename) {
	const extIndex = filename.lastIndexOf(".");
	if (extIndex < 0) return filename;
	return filename.slice(0, extIndex);
}
function isAppVueLikeFile(filename) {
	return APP_VUE_LIKE_FILE_RE.test(filename);
}
async function resolveFallbackPageEntryFile(options) {
	return await findFirstResolvedVueLikeEntry(options.entryId, { resolve: async (candidate) => {
		if (options.compilationCache.has(candidate)) return null;
		return await options.pathExists(candidate);
	} });
}
async function resolveFallbackPageEmitState(options) {
	const relativeBase = options.configService.relativeOutputPath(options.entryId);
	if (!relativeBase) return;
	const entryFilePath = await resolveFallbackPageEntryFile({
		entryId: options.entryId,
		compilationCache: options.compilationCache,
		pathExists: options.pathExists
	});
	if (!entryFilePath) return;
	return {
		relativeBase,
		entryFilePath
	};
}
async function handleFallbackPageLayouts(options) {
	const resolvedLayoutPlan = await resolvePageLayoutPlan(options.source, options.entryFilePath, options.configService);
	await options.emitLayouts(resolvedLayoutPlan?.layouts);
}
async function handleCompiledEntryPageLayouts(options) {
	const resolvedLayoutPlan = getVueBundlePageLayoutPlan(options.result) ?? await resolvePageLayoutPlan(options.source, options.filename, options.configService);
	if (resolvedLayoutPlan) applyPageLayoutPlan(options.result, options.filename, resolvedLayoutPlan, { platform: options.configService.platform });
	await options.emitLayouts(resolvedLayoutPlan?.layouts);
}
//#endregion
//#region src/plugins/vue/transform/bundle/shared/compile.ts
async function compileVueLikeFile(options) {
	const { source, filename, ctx, pluginCtx, isPage, isApp, configService, compileOptionsState } = options;
	const compileOptions = createCompileVueFileOptions(ctx, pluginCtx, filename, isPage, isApp, configService, compileOptionsState);
	if (filename.endsWith(".vue")) {
		const result = await compileVueFile(source, filename, compileOptions);
		if (isPage && result.template) {
			const resolvedLayoutPlan = await resolvePageLayoutPlan(source, filename, configService);
			if (resolvedLayoutPlan) {
				setVueBundlePageLayoutPlan(result, resolvedLayoutPlan);
				applyPageLayoutPlan(result, filename, resolvedLayoutPlan, { platform: configService.platform });
				await registerResolvedPageLayoutDependencies(ctx, filename, resolvedLayoutPlan.layouts);
			}
		}
		const hmr = ctx.runtimeState?.build?.hmr;
		if (configService.isDev && hmr) storeVueSfcHmrSignatures(hmr, normalizeFsResolvedId(filename), resolveVueSfcHmrSignatures(source, filename));
		return result;
	}
	const result = await compileJsxFile(source, filename, compileOptions);
	if (isPage && result.template) {
		const resolvedLayoutPlan = await resolvePageLayoutPlan(source, filename, configService);
		if (resolvedLayoutPlan) {
			setVueBundlePageLayoutPlan(result, resolvedLayoutPlan);
			applyPageLayoutPlan(result, filename, resolvedLayoutPlan, { platform: configService.platform });
			await registerResolvedPageLayoutDependencies(ctx, filename, resolvedLayoutPlan.layouts);
		}
	}
	return result;
}
async function finalizeCompiledVueLikeResult(options) {
	const { result, filename, pluginCtx, configService, isPage, isApp } = options;
	if (isPage && result.script) {
		const injected = await injectWevuPageFeaturesInJsWithViteResolver(pluginCtx, result.script, filename, {
			checkMtime: configService.isDev,
			minify: isWevuMinifyEnabled(configService.weappViteConfig, configService.isDev),
			sourceMap: false
		});
		if (injected.transformed) result.script = injected.code;
	}
	const shouldAutoSetDataPick = !isApp && result.script && result.template && isAutoSetDataPickEnabled(configService.weappViteConfig) && mayNeedInjectSetDataPickInJs(result.script);
	const shouldInjectScopedSlotOwnerPick = !isApp && result.script && result.template?.includes(WEVU_SLOT_OWNER_ID_ATTR) && mayNeedInjectSetDataPickInJs(result.script);
	if (shouldAutoSetDataPick) {
		const keys = collectSetDataPickKeysFromTemplate(result.template);
		const scopedSlotPickKeys = shouldUseScopedSlotOwnerOnlySetDataPick(keys) ? pruneScopedSlotOwnerAutoSetDataPickKeys(keys) : keys;
		const injectedPick = shouldInjectScopedSlotOwnerPick ? injectScopedSlotOwnerSetDataPickInJs(result.script, scopedSlotPickKeys, { sourceMap: false }) : injectSetDataPickInJs(result.script, keys, { sourceMap: false });
		if (injectedPick.transformed) result.script = injectedPick.code;
	} else if (shouldInjectScopedSlotOwnerPick) {
		const keys = collectSetDataPickKeysFromTemplate(result.template);
		const injectedPick = injectScopedSlotOwnerSetDataPickInJs(result.script, pruneScopedSlotOwnerAutoSetDataPickKeys(keys), { sourceMap: false });
		if (injectedPick.transformed) result.script = injectedPick.code;
	}
	const hasScopedSlotHostGenerics = Boolean(result.componentGenerics && Object.keys(result.componentGenerics).length > 0);
	const needsSetupSlotHostProperties = result.script && mayNeedScopedSlotHostPropertiesForSetupSlotsInJs(result.script);
	if (!isPage && !isApp && result.script && (hasScopedSlotHostGenerics || result.template?.includes(WEVU_SLOT_OWNER_ID_PROP) || result.template?.includes("<slot") || result.template?.includes("vueSlots") || needsSetupSlotHostProperties)) {
		const injectedProps = injectScopedSlotHostPropertiesInJs(result.script, { sourceMap: false });
		if (injectedProps.transformed) result.script = injectedProps.code;
	}
	return result;
}
async function compileAndFinalizeVueLikeFile(options) {
	return await finalizeCompiledVueLikeResult({
		result: await compileVueLikeFile(options),
		filename: options.filename,
		pluginCtx: options.pluginCtx,
		configService: options.configService,
		isPage: options.isPage,
		isApp: options.isApp
	});
}
async function refreshCompiledVueEntryCacheInDev(options) {
	const { filename, cached, ctx, pluginCtx, configService, compileOptionsState } = options;
	if (!configService.isDev) return cached.result;
	try {
		const rawSource = await fs$1.readFile(filename, "utf-8");
		const isApp = isAppVueLikeFile(filename);
		const transformed = isApp ? await resolveTransformAutoRoutesSource({
			source: rawSource,
			autoRoutesService: ctx.autoRoutesService
		}) : {
			source: rawSource,
			signature: void 0
		};
		const source = transformed.source;
		const dirtyVueEntryIds = ctx.runtimeState?.build?.hmr?.dirtyVueEntryIds;
		const dirtyEntryId = resolveDirtyVueEntryId(dirtyVueEntryIds, filename);
		if (source === cached.source && transformed.signature === cached.autoRoutesSignature) {
			cached.refreshToken = 0;
			if (dirtyEntryId) dirtyVueEntryIds?.delete(dirtyEntryId);
			return cached.result;
		}
		const currentStyleIndependentSignature = dirtyEntryId && filename.endsWith(".vue") && isVueStyleOnlyDirtyReasonSummary(ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary) ? resolveVueSfcStyleIndependentSignature(source, filename) : void 0;
		if (dirtyEntryId && filename.endsWith(".vue") && cached.styleIndependentSignature && currentStyleIndependentSignature && cached.styleIndependentSignature === currentStyleIndependentSignature && transformed.signature === cached.autoRoutesSignature && cached.source !== source) {
			const { descriptor } = await readAndParseSfc(filename, {
				source,
				checkMtime: configService.isDev
			});
			if (!await refreshStyleOnlyVueTransformResult(cached.result, filename, descriptor.styles, resolveSfcStylePreprocessOptions(configService))) cached.styleIndependentSignature = void 0;
			else {
				cached.source = source;
				cached.styleIndependentSignature = currentStyleIndependentSignature;
				cached.refreshToken = 0;
				storeVueSfcHmrSignatures(ctx.runtimeState.build.hmr, filename, resolveVueSfcHmrSignatures(source, filename));
				dirtyVueEntryIds?.delete(dirtyEntryId);
				return cached.result;
			}
		}
		const compiled = await compileAndFinalizeVueLikeFile({
			source,
			filename,
			ctx,
			pluginCtx,
			isPage: cached.isPage,
			isApp,
			configService,
			compileOptionsState
		});
		const nextStyleIndependentSignature = filename.endsWith(".vue") ? currentStyleIndependentSignature ?? resolveVueSfcStyleIndependentSignature(source, filename) : void 0;
		cached.source = source;
		cached.autoRoutesSignature = transformed.signature;
		cached.styleIndependentSignature = nextStyleIndependentSignature;
		cached.refreshToken = 0;
		if (dirtyEntryId) dirtyVueEntryIds?.delete(dirtyEntryId);
		cached.result = compiled;
		return compiled;
	} catch {
		return cached.result;
	}
}
async function resolveCompiledEntryEmitState(options) {
	const result = await refreshCompiledVueEntryCacheInDev({
		filename: options.filename,
		cached: options.cached,
		ctx: options.ctx,
		pluginCtx: options.pluginCtx,
		configService: options.configService,
		compileOptionsState: options.compileOptionsState
	});
	const baseName = getEntryBaseName(options.filename);
	const relativeBase = options.configService.relativeOutputPath(baseName);
	if (!relativeBase) return;
	return {
		result,
		relativeBase
	};
}
async function loadFallbackPageEntryCompilation(options) {
	const source = await fs$1.readFile(options.entryFilePath, "utf-8");
	return {
		source,
		result: await compileAndFinalizeVueLikeFile({
			source,
			filename: options.entryFilePath,
			ctx: options.ctx,
			pluginCtx: options.pluginCtx,
			isPage: true,
			isApp: false,
			configService: options.configService,
			compileOptionsState: options.compileOptionsState
		})
	};
}
//#endregion
//#region src/plugins/vue/transform/bundle/layoutAssets.ts
function resolveVueLayoutAssetOptions(options) {
	return resolveNativeLayoutOutputOptions(options);
}
async function emitResolvedBundleLayouts(options) {
	for (const layout of options.layouts) {
		if (layout.kind === "native") {
			await options.emitNativeLayout(layout.file);
			continue;
		}
		await options.emitVueLayout(layout.file);
	}
}
async function resolveNativeLayoutAssetState(options) {
	const resolvedOptions = resolveVueLayoutAssetOptions({
		configService: options.configService,
		layoutBasePath: options.layoutBasePath,
		outputExtensions: options.outputExtensions
	});
	if (!resolvedOptions) return;
	return {
		resolvedOptions,
		assets: await collectNativeLayoutAssets(options.layoutBasePath, options.configService.platform)
	};
}
async function emitResolvedNativeLayoutStaticAssets(options) {
	const staticAssetEntries = await resolveNativeLayoutStaticAssetEntries({
		assets: options.assets,
		resolvedOptions: options.resolvedOptions,
		readFile: fs$1.readFile
	});
	for (const asset of staticAssetEntries) {
		if (asset.kind === "template") {
			assertTemplateHasDefaultSlot({
				filename: options.assets.template,
				kind: "page-layout",
				template: asset.source
			});
			emitSfcTemplateIfMissing(options.pluginCtx, options.bundle, options.resolvedOptions.relativeBase, asset.source, options.resolvedOptions.templateExtension);
			continue;
		}
		emitSfcStyleIfMissing(options.pluginCtx, options.bundle, options.resolvedOptions.relativeBase, asset.source, options.resolvedOptions.styleExtension);
	}
}
async function emitNativeLayoutAssetsIfNeeded(options) {
	const { pluginCtx, bundle } = options;
	const nativeLayoutState = await resolveNativeLayoutAssetState(options);
	if (!nativeLayoutState) return;
	const { resolvedOptions, assets } = nativeLayoutState;
	if (assets.json) {
		const source = await fs$1.readFile(assets.json, "utf8");
		emitSfcJsonAsset(pluginCtx, bundle, resolvedOptions.relativeBase, { config: source }, {
			emitIfMissingOnly: true,
			extension: resolvedOptions.jsonExtension,
			kind: "component"
		});
	}
	await emitResolvedNativeLayoutStaticAssets({
		pluginCtx,
		bundle,
		assets,
		resolvedOptions
	});
}
function emitScriptlessComponentJsFallbackIfMissing(options) {
	const { pluginCtx, bundle, relativeBase, scriptExtension, source } = options;
	ensureScriptlessComponentAsset(pluginCtx, bundle, relativeBase, scriptExtension, source);
}
function resolveVueLayoutScriptFallbackState(options) {
	const resolvedOptions = resolveVueLayoutAssetOptions({
		configService: options.configService,
		layoutBasePath: getEntryBaseName(options.layoutFilePath),
		outputExtensions: options.outputExtensions
	});
	if (!resolvedOptions) return;
	const scriptFileName = resolveScriptlessComponentFileName(resolvedOptions.relativeBase, resolvedOptions.scriptExtension);
	if (options.bundle[scriptFileName]) return;
	return {
		resolvedOptions,
		scriptFileName
	};
}
async function emitVueLayoutScriptFallbackIfNeeded(options) {
	const { pluginCtx, bundle, layoutFilePath, ctx, configService, compileOptionsState, outputExtensions } = options;
	const fallbackState = resolveVueLayoutScriptFallbackState({
		bundle,
		layoutFilePath,
		configService,
		outputExtensions
	});
	if (!fallbackState) return;
	const { resolvedOptions } = fallbackState;
	const result = await compileVueLikeFile({
		source: await fs$1.readFile(layoutFilePath, "utf-8"),
		filename: layoutFilePath,
		ctx,
		pluginCtx,
		isPage: false,
		isApp: false,
		configService,
		compileOptionsState
	});
	assertTemplateHasDefaultSlot({
		filename: layoutFilePath,
		kind: "page-layout",
		template: result.template
	});
	if (result.script?.trim()) return;
	emitScriptlessComponentJsFallbackIfMissing({
		pluginCtx,
		bundle,
		relativeBase: resolvedOptions.relativeBase,
		scriptExtension: resolvedOptions.scriptExtension,
		source: SLOT_HOST_SCRIPTLESS_COMPONENT_STUB
	});
}
function createBundleLayoutEmitters(options) {
	return {
		emitNativeLayout: async (layoutFilePath) => {
			await emitNativeLayoutAssetsIfNeeded({
				pluginCtx: options.pluginCtx,
				bundle: options.bundle,
				layoutBasePath: layoutFilePath,
				configService: options.configService,
				outputExtensions: options.outputExtensions
			});
		},
		emitVueLayout: async (layoutFilePath) => {
			await emitVueLayoutScriptFallbackIfNeeded({
				pluginCtx: options.pluginCtx,
				bundle: options.bundle,
				layoutFilePath,
				ctx: options.ctx,
				configService: options.configService,
				compileOptionsState: options.compileOptionsState,
				outputExtensions: options.outputExtensions
			});
		}
	};
}
async function emitBundlePageLayoutsIfNeeded(options) {
	if (!options.layouts?.length) return;
	const layoutEmitters = createBundleLayoutEmitters(options);
	await emitResolvedBundleLayouts({
		layouts: options.layouts,
		emitNativeLayout: layoutEmitters.emitNativeLayout,
		emitVueLayout: layoutEmitters.emitVueLayout
	});
}
function resolveAppShellUsingComponents(template, usingComponents) {
	const templateComponents = scanWxml(template, { excludeComponent: () => false }).autoImportComponents ?? {};
	return Object.fromEntries(Object.entries(usingComponents).filter(([name]) => Reflect.has(templateComponents, name)));
}
function resolveAppShellComponentConfig(config, template) {
	const shellConfig = { styleIsolation: "apply-shared" };
	if (!config) return JSON.stringify(shellConfig, null, 2);
	try {
		const parsed = JSON.parse(config);
		if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return JSON.stringify(shellConfig, null, 2);
		for (const key of ["usingComponents", "componentGenerics"]) {
			const value = parsed[key];
			if (value && typeof value === "object" && !Array.isArray(value)) {
				const normalizedValue = key === "usingComponents" ? resolveAppShellUsingComponents(template, value) : value;
				if (Object.keys(normalizedValue).length > 0) shellConfig[key] = normalizedValue;
			}
		}
		return Object.keys(shellConfig).length ? JSON.stringify(shellConfig, null, 2) : void 0;
	} catch {
		return;
	}
}
function emitAppShellAssetsIfNeeded(options) {
	const { relativeBase, result } = options;
	if (!relativeBase || !result.template?.trim()) return;
	assertTemplateHasDefaultSlot({
		filename: options.filename,
		kind: "app-shell",
		template: result.template
	});
	emitBundleVueEntryAssets({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		ctx: options.ctx,
		filename: relativeBase,
		relativeBase,
		result,
		configService: options.configService,
		templateExtension: options.templateExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions
	});
	emitSharedVueEntryJsonAsset({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		relativeBase,
		config: resolveAppShellComponentConfig(result.config, result.template),
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions,
		jsonOptions: {
			defaultConfig: { component: true },
			kind: "component",
			extension: options.jsonExtension
		}
	});
	emitScriptlessComponentJsFallbackIfMissing({
		pluginCtx: options.pluginCtx,
		bundle: options.bundle,
		relativeBase,
		scriptExtension: options.scriptExtension,
		source: SLOT_HOST_SCRIPTLESS_COMPONENT_STUB
	});
}
//#endregion
//#region src/plugins/vue/transform/bundle/emitCompiledEntry.ts
function shouldReplaceAppScriptBundleEntry(options) {
	if (!isAppVueFile(options.filename) || !options.isDev || !options.hasDevHmrEvent) return false;
	return true;
}
function hasUnresolvedModuleImportDeclaration(script) {
	if (!script?.includes("import")) return false;
	try {
		let hasUnresolvedImport = false;
		const ast = parseJsLike(script);
		traverse(ast, { ImportDeclaration(path) {
			const source = path.node.source.value;
			if (typeof source === "string" && !(source === "wevu" || source === "wevu/router" || source === "wevu/store" || source === "wevu/api" || source === "wevu/fetch" || source === "wevu/web-apis" || source === "wevu/internal-runtime" || source === "wevu/internal-reactivity" || source === "wevu/internal-template" || Object.values(WEAPP_VITE_RUNTIME_VIRTUAL_IDS).includes(source))) {
				hasUnresolvedImport = true;
				path.stop();
			}
		} });
		return hasUnresolvedImport;
	} catch {
		return true;
	}
}
function retainReplacedDevHmrScriptChunk(state, fileName) {
	const hmrState = state.ctx.runtimeState?.build?.hmr;
	if (!state.ctx.configService?.isDev || hmrState?.profile?.event === void 0) return;
	hmrState.lastEmittedChunkFileNames ??= /* @__PURE__ */ new Set();
	hmrState.lastEmittedChunkFileNames.add(fileName);
}
async function emitResolvedCompiledVueEntryAssets(options) {
	const { bundle, state, filename, cached, result, relativeBase, compileOptionsState } = options;
	const { ctx, pluginCtx } = state;
	const { configService } = ctx;
	if (!configService) return;
	const hmrState = ctx.runtimeState?.build?.hmr;
	const shouldReplaceAppScript = shouldReplaceAppScriptBundleEntry({
		filename,
		isDev: configService.isDev,
		hasDevHmrEvent: hmrState?.profile?.event !== void 0
	});
	if (isAppVueFile(filename) && hasAppShellTemplate(result)) emitAppShellAssetsIfNeeded({
		bundle,
		pluginCtx,
		ctx,
		filename,
		relativeBase: resolveAppShellRelativeBase(configService),
		result,
		configService,
		templateExtension: options.templateExtension,
		jsonExtension: options.jsonExtension,
		scriptExtension: options.scriptExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions
	});
	if (cached.isPage && cached.source) {
		await handleCompiledEntryPageLayouts({
			source: cached.source,
			filename,
			result,
			configService,
			emitLayouts: async (layouts) => {
				await emitBundlePageLayoutsIfNeeded({
					layouts,
					pluginCtx,
					bundle,
					ctx,
					configService,
					compileOptionsState,
					outputExtensions: options.outputExtensions
				});
			}
		});
		applyAppShell(result, filename, state.appShell);
	}
	if (isLayoutFile(filename, configService)) assertTemplateHasDefaultSlot({
		filename,
		kind: "page-layout",
		template: result.template
	});
	const { shouldEmitComponentJson } = await emitCompiledEntryBundleAssets({
		bundle,
		pluginCtx,
		ctx,
		filename,
		relativeBase,
		result,
		isPage: cached.isPage,
		configService,
		templateExtension: options.templateExtension,
		jsonExtension: options.jsonExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions
	});
	if (shouldReplaceAppScript && result.script?.trim()) {
		const scriptFileName = `${relativeBase}.${options.scriptExtension}`;
		const script = rewriteWevuInternalRuntimeImportCode(scriptFileName, result.script, {
			runtimeFileName: ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileName,
			runtimeFileNames: ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileNames
		});
		if (hasUnresolvedModuleImportDeclaration(script)) return;
		emitSfcScriptAssetReplacingBundleEntry(pluginCtx, bundle, relativeBase, script, options.scriptExtension);
		retainReplacedDevHmrScriptChunk(state, scriptFileName);
	}
	if (shouldEmitComponentJson && !result.script?.trim()) emitScriptlessComponentJsFallbackIfMissing({
		pluginCtx,
		bundle,
		relativeBase,
		scriptExtension: options.scriptExtension
	});
}
async function emitCompiledVueEntryAssets(bundle, state, filename, cached) {
	const { ctx, pluginCtx, reExportResolutionCache, classStyleRuntimeWarned, compileOptionsCache, componentMetaCache } = state;
	const { configService } = ctx;
	if (!configService) return;
	const compileOptionsState = {
		reExportResolutionCache,
		classStyleRuntimeWarned,
		compileOptionsCache,
		componentMetaCache,
		emitResolvedComponentEntries: false
	};
	const { outputExtensions, templateExtension, jsonExtension, scriptExtension, scriptModuleExtension, platformAssetOptions } = resolveVueBundleAssetContext(configService);
	const emitState = await resolveCompiledEntryEmitState({
		filename,
		cached,
		ctx,
		pluginCtx,
		configService,
		compileOptionsState
	});
	if (!emitState) return;
	await emitResolvedCompiledVueEntryAssets({
		bundle,
		state,
		filename,
		cached,
		result: emitState.result,
		relativeBase: emitState.relativeBase,
		compileOptionsState,
		outputExtensions,
		templateExtension,
		jsonExtension,
		scriptExtension,
		scriptModuleExtension,
		platformAssetOptions
	});
}
//#endregion
//#region src/plugins/vue/transform/collectVuePages.ts
async function collectVuePages(root) {
	const results = [];
	try {
		const entries = await fs$1.readdir(root);
		for (const entry of entries) {
			const full = path.join(root, entry);
			if ((await fs$1.stat(full)).isDirectory()) {
				const nested = await collectVuePages(full);
				results.push(...nested);
			} else if (isVueLikeFile(full)) results.push(stripVueLikeExtension(full));
		}
	} catch {}
	return results;
}
//#endregion
//#region src/plugins/vue/transform/fallbackEntries.ts
async function collectFallbackPageEntryIds(configService, scanService) {
	let pageList = [];
	if (scanService?.appEntry?.json?.pages?.length) pageList = scanService.appEntry.json.pages;
	else {
		const appJsonPath = path.join(configService.cwd, "dist", "app.json");
		try {
			const appJsonContent = await fs$1.readFile(appJsonPath, "utf-8");
			pageList = JSON.parse(appJsonContent).pages || [];
		} catch {}
	}
	const collectedEntries = /* @__PURE__ */ new Set();
	pageList.forEach((p) => collectedEntries.add(path.join(configService.absoluteSrcRoot, p)));
	(await collectVuePages(path.join(configService.absoluteSrcRoot, "pages"))).forEach((f) => collectedEntries.add(f.slice(0, -4)));
	return collectedEntries;
}
//#endregion
//#region src/plugins/vue/transform/bundle/emitFallbackPage.ts
function isFallbackEntryPending(entryId, emittedEntryIds, configService) {
	const normalizedEntryId = removeExtensionDeep(configService.relativeOutputPath(entryId));
	for (const emittedEntryId of emittedEntryIds) {
		const normalizedEmitted = normalizeFsResolvedId(emittedEntryId);
		if (!normalizedEmitted) continue;
		if (removeExtensionDeep(configService.relativeOutputPath(normalizedEmitted)) === normalizedEntryId) return true;
	}
	return false;
}
async function emitResolvedFallbackPageEntryAssets(options) {
	const { source, result } = await loadFallbackPageEntryCompilation({
		entryFilePath: options.entryFilePath,
		ctx: options.ctx,
		pluginCtx: options.pluginCtx,
		configService: options.configService,
		compileOptionsState: options.compileOptionsState
	});
	await handleFallbackPageLayouts({
		source,
		entryFilePath: options.entryFilePath,
		configService: options.configService,
		emitLayouts: async (layouts) => {
			await emitBundlePageLayoutsIfNeeded({
				layouts,
				pluginCtx: options.pluginCtx,
				bundle: options.bundle,
				ctx: options.ctx,
				configService: options.configService,
				compileOptionsState: options.compileOptionsState,
				outputExtensions: options.outputExtensions
			});
		}
	});
	applyAppShell(result, options.entryFilePath, options.appShell);
	await emitFallbackPageBundleAssets({
		bundle: options.bundle,
		pluginCtx: options.pluginCtx,
		ctx: options.ctx,
		filename: options.entryFilePath,
		relativeBase: options.relativeBase,
		result,
		configService: options.configService,
		templateExtension: options.templateExtension,
		styleExtension: options.styleExtension,
		jsonExtension: options.jsonExtension,
		scriptModuleExtension: options.scriptModuleExtension,
		outputExtensions: options.outputExtensions,
		platformAssetOptions: options.platformAssetOptions
	});
}
async function emitFallbackPageAssets(bundle, state, options) {
	const { ctx, pluginCtx, compilationCache, reExportResolutionCache, classStyleRuntimeWarned, compileOptionsCache, componentMetaCache } = state;
	const { configService, scanService } = ctx;
	if (!configService || !scanService) return;
	const compileOptionsState = {
		reExportResolutionCache,
		classStyleRuntimeWarned,
		compileOptionsCache,
		componentMetaCache,
		emitResolvedComponentEntries: false
	};
	const { outputExtensions, templateExtension, styleExtension, jsonExtension, scriptModuleExtension, platformAssetOptions } = resolveVueBundleAssetContext(configService);
	const collectedEntries = await collectFallbackPageEntryIds(configService, scanService);
	for (const entryId of collectedEntries) {
		if (options?.emittedEntryIds && !isFallbackEntryPending(entryId, options.emittedEntryIds, configService)) continue;
		const emitState = await resolveFallbackPageEmitState({
			entryId,
			configService,
			compilationCache,
			pathExists: async (candidate) => {
				return await pathExists(candidate, { ttlMs: getPathExistsTtlMs(configService) }) ? candidate : void 0;
			}
		});
		if (!emitState) continue;
		const { relativeBase, entryFilePath } = emitState;
		try {
			await emitResolvedFallbackPageEntryAssets({
				bundle,
				pluginCtx,
				entryFilePath,
				ctx,
				relativeBase,
				configService,
				compileOptionsState,
				templateExtension,
				styleExtension,
				jsonExtension,
				scriptModuleExtension,
				outputExtensions,
				platformAssetOptions,
				appShell: state.appShell
			});
		} catch (error) {
			const message = error instanceof Error ? error.message : String(error);
			logger_default.error(`[Vue 编译] 编译 ${entryFilePath} 失败:${message}`);
		}
	}
}
//#endregion
//#region src/plugins/vue/transform/bundle/index.ts
function isAutoRoutesAppRefreshHmrUpdate(hmrState) {
	return hmrState?.profile?.dirtyReasonSummary?.some((item) => item.startsWith("entry-auto-routes:") || item.startsWith("auto-routes-topology:")) === true;
}
function resolveVueBundleEmitState(state) {
	const { ctx, compilationCache } = state;
	const { configService, scanService } = ctx;
	if (!configService || !scanService) return;
	state.appShell = Array.from(compilationCache.entries()).find(([filename, cached]) => {
		return isAppVueFile(filename) && hasAppShellTemplate(cached.result);
	}) ? resolveAppShellLayout(configService) : void 0;
	const hmrState = ctx.runtimeState?.build?.hmr;
	const currentHmrFile = hmrState?.profile?.file;
	const isAppVueHmrUpdate = Boolean(configService.isDev && typeof currentHmrFile === "string" && isAppVueFile(normalizeFsResolvedId(currentHmrFile)));
	const isAutoRoutesAppRefreshUpdate = configService.isDev && isAutoRoutesAppRefreshHmrUpdate(hmrState);
	const emittedEntryIds = Boolean(configService.isDev && hmrState && !isAppVueHmrUpdate && !hmrState.didEmitAllEntries && (hmrState.lastHmrEntryIds?.size ?? hmrState.lastEmittedEntryIds?.size ?? 0) > 0) && hmrState ? hmrState.lastHmrEntryIds?.size ? hmrState.lastHmrEntryIds : hmrState.lastEmittedEntryIds : void 0;
	const dirtyVueEntryIds = hmrState?.dirtyVueEntryIds;
	const currentAutoRoutesSignature = ctx.autoRoutesService?.getSignature?.();
	return {
		compilationEntries: Array.from(compilationCache.entries()).filter(([id]) => {
			const normalizedId = normalizeFsResolvedId(id);
			const cached = compilationCache.get(id);
			const isStaleAutoRoutesAppEntry = Boolean(cached && isAppVueFile(normalizedId) && typeof currentAutoRoutesSignature === "string" && cached.autoRoutesSignature !== currentAutoRoutesSignature);
			const isAutoRoutesAppRefreshAppEntry = isAutoRoutesAppRefreshUpdate && isAppVueFile(normalizedId);
			return !emittedEntryIds || emittedEntryIds.has(normalizedId) || dirtyVueEntryIds?.has(normalizedId) || isStaleAutoRoutesAppEntry || isAutoRoutesAppRefreshAppEntry;
		}),
		emittedEntryIds
	};
}
async function emitCompiledBundleEntries(bundle, state, compilationEntries) {
	for (const [filename, cached] of compilationEntries) await emitCompiledVueEntryAssets(bundle, state, filename, cached);
}
async function emitVueBundleAssets(bundle, state) {
	const emitState = resolveVueBundleEmitState(state);
	if (!emitState) return;
	await emitCompiledBundleEntries(bundle, state, emitState.compilationEntries);
	await emitFallbackPageAssets(bundle, state, { emittedEntryIds: emitState.emittedEntryIds });
}
//#endregion
//#region src/plugins/wevu.ts
const JS_LIKE_SOURCE_RE = /\.[cm]?[jt]sx?$/;
const JS_LIKE_SOURCE_FILTER_RE = /\.[cm]?[jt]sx?(?:\?.*)?$/;
function createWevuAutoPageFeaturesPlugin(ctx) {
	let matcher = null;
	let scanDirtySynced = false;
	const pageFileCache = /* @__PURE__ */ new Map();
	return {
		name: "weapp-vite:wevu:page-features",
		enforce: "pre",
		transform: {
			filter: { id: JS_LIKE_SOURCE_FILTER_RE },
			async handler(code, id) {
				const configService = ctx.configService;
				const scanService = ctx.scanService;
				if (!configService || !scanService) return null;
				const pageMatcher = matcher ?? (matcher = createPageEntryMatcher({
					srcRoot: configService.absoluteSrcRoot,
					loadEntries: async () => {
						const appEntry = await scanService.loadAppEntry();
						const subPackages = scanService.loadSubPackages().map((meta) => ({
							root: meta.subPackage.root,
							pages: meta.subPackage.pages
						}));
						const pluginPages = scanService.pluginJson ? Object.values(scanService.pluginJson.pages ?? {}).map((page) => String(page)) : [];
						return {
							pages: appEntry.json?.pages ?? [],
							subPackages,
							pluginPages
						};
					},
					warn: (message) => logger_default.warn(message)
				}));
				if (ctx.runtimeState.scan.isDirty && !scanDirtySynced) {
					pageMatcher.markDirty();
					pageFileCache.clear();
					scanDirtySynced = true;
				} else if (!ctx.runtimeState.scan.isDirty && scanDirtySynced) scanDirtySynced = false;
				const sourceId = normalizeFsResolvedId(id);
				if (!sourceId) return null;
				if (sourceId.endsWith(".vue")) return null;
				if (!JS_LIKE_SOURCE_RE.test(sourceId)) return null;
				const filename = toAbsoluteId(sourceId, configService, void 0, { base: "cwd" });
				if (!filename || !path.isAbsolute(filename)) return null;
				const startedAt = performance.now();
				try {
					let isPageFile = pageFileCache.get(filename);
					if (isPageFile === void 0) {
						isPageFile = await pageMatcher.isPageFile(filename);
						pageFileCache.set(filename, isPageFile);
					}
					if (!isPageFile) return null;
					if (!mayNeedWevuPageFeatureAnalysis(code)) return null;
					const astEngine = resolveAstEngine(configService.weappViteConfig);
					if (code.includes("onPageScroll")) for (const warning of collectOnPageScrollPerformanceWarnings(code, filename, { engine: astEngine })) logger_default.warn(warning);
					const result = await injectWevuPageFeaturesInJsWithResolver(code, {
						id: filename,
						astEngine,
						resolver: createViteResolverAdapter({ resolve: async (source, importer) => {
							return await this.resolve(source, importer);
						} }, { readFile: readFile$1 }, { checkMtime: getReadFileCheckMtime(configService) }),
						sourceMap: false
					});
					if (!result.transformed) return null;
					return {
						code: result.code,
						map: null
					};
				} finally {
					const durationMs = performance.now() - startedAt;
					recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "transformMs", durationMs);
					recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "wevuTransformMs", durationMs);
				}
			}
		}
	};
}
function wevuPlugin(ctx) {
	return [createWevuAutoPageFeaturesPlugin(ctx)];
}
const wevu = wevuPlugin;
//#endregion
//#region src/plugins/vue/transform/plugin/styleOnlyRefresh.ts
function createSfcStyleBlocksSignature(styleBlocks) {
	if (!styleBlocks?.length) return "";
	return JSON.stringify(styleBlocks.map((styleBlock) => ({
		attrs: styleBlock.attrs,
		content: styleBlock.content,
		lang: styleBlock.lang,
		module: styleBlock.module,
		scoped: styleBlock.scoped
	})));
}
async function loadStyleBlocksForStyleOnlyRefresh(options) {
	const { filename, source, styleBlocksCache, force, readAndParseSfc, createReadAndParseSfcOptions, pluginCtx, configService } = options;
	if (force) styleBlocksCache.delete(filename);
	await preloadTransformSfcStyleBlocks({
		filename,
		source,
		styleBlocksCache,
		load: async (target, source) => {
			return (await readAndParseSfc(target, createReadAndParseSfcOptions(pluginCtx, configService, {
				source,
				checkMtime: configService.isDev
			}))).descriptor.styles;
		}
	});
	return styleBlocksCache.get(filename);
}
//#endregion
//#region src/plugins/vue/transform/plugin/usingComponents.ts
function parseUsingComponents(config) {
	if (!config) return {};
	try {
		const usingComponents = JSON.parse(config)?.usingComponents;
		return usingComponents && typeof usingComponents === "object" && !Array.isArray(usingComponents) ? usingComponents : {};
	} catch {
		return {};
	}
}
//#endregion
//#region src/plugins/vue/transform/plugin/transformFile/finalize.ts
async function finalizeVueTransform(options) {
	const { ctx, pluginCtx, filename, source, autoRoutesSignature, result, compilationCache, currentStyleIndependentSignature, previousStyleSignature, dirtyEntryId, dirtyVueEntryIds, isCssImporterDirty, isPage, isApp, sourceMap, styleBlocksCache, styleRefreshTokens, scopedSlotModules, emittedScopedSlotChunks, setAppShell, readAndParseSfc, createReadAndParseSfcOptions, measureStage, measureVueHmrStage, reportTiming } = options;
	const configService = ctx.configService;
	let currentStyleBlocks = Array.isArray(result.meta?.styleBlocks) ? result.meta.styleBlocks : styleBlocksCache.get(filename);
	if (!currentStyleBlocks) currentStyleBlocks = await measureStage("preloadSfcStyles", async () => await loadStyleBlocksForStyleOnlyRefresh({
		filename,
		source,
		styleBlocksCache,
		readAndParseSfc,
		createReadAndParseSfcOptions,
		pluginCtx,
		configService
	}));
	if (currentStyleBlocks) styleBlocksCache.set(filename, currentStyleBlocks);
	if (configService.isDev && dirtyEntryId) {
		const currentStyleSignature = createSfcStyleBlocksSignature(currentStyleBlocks);
		const hmrEventId = ctx.runtimeState.build?.hmr?.profile?.eventId;
		if (hmrEventId != null && (isCssImporterDirty || currentStyleSignature && currentStyleSignature !== previousStyleSignature)) styleRefreshTokens.set(filename, hmrEventId);
		else styleRefreshTokens.delete(filename);
		dirtyVueEntryIds?.delete(dirtyEntryId);
	}
	const sfcStyleDependencies = syncVueSfcStyleDependencies(ctx, filename, currentStyleBlocks);
	ctx.moduleGraphService.replaceEntryDependencies(filename, "style", sfcStyleDependencies);
	const jsxDependencies = result.meta?.jsxDependencies ?? [];
	addNormalizedWatchFiles(pluginCtx, jsxDependencies);
	ctx.moduleGraphService.replaceEntryDependencies(filename, "jsx", jsxDependencies);
	registerScopedSlotHostGenerics(ctx, result.scopedSlotComponents, parseUsingComponents(result.config));
	await measureVueHmrStage("finalizeCompiledResult", "vueFinalizeCompiledMs", async () => {
		await finalizeTransformCompiledResult({
			ctx,
			pluginCtx,
			filename,
			source,
			autoRoutesSignature,
			result,
			compilationCache,
			styleIndependentSignature: filename.endsWith(".vue") ? currentStyleIndependentSignature ?? resolveVueSfcStyleIndependentSignature(source, filename) : void 0,
			setAppShell,
			configService,
			isPage,
			isApp,
			sourceMap,
			scopedSlotModules,
			emittedScopedSlotChunks,
			emitScopedSlotChunks
		});
	});
	const returnedCode = await measureVueHmrStage("finalizeCode", "vueFinalizeCodeMs", async () => finalizeTransformEntryCode({
		result,
		filename,
		styleBlocks: result.meta?.styleBlocks ?? styleBlocksCache.get(filename),
		isPage,
		isApp,
		isDev: configService.isDev,
		sourceMap,
		hmrStyleToken: configService.isDev ? styleRefreshTokens.get(filename) : void 0
	}));
	reportTiming(filename, isPage);
	return returnedCode;
}
//#endregion
//#region src/plugins/vue/transform/plugin/transformFile/jsonOnly.ts
function isVueJsonOnlyDirtyReasonSummary(dirtyReasonSummary) {
	return Boolean(dirtyReasonSummary?.length && dirtyReasonSummary.every((item) => item.startsWith("entry-json-only:")));
}
async function tryRefreshJsonOnlyVueCompilation(options) {
	const { cachedResult, compileOptions, dirtyEntryId, dirtyReasonSummary, filename, isDev, scanDirty, source, autoRoutesSignature, cachedAutoRoutesSignature } = options;
	if (!isDev || scanDirty || !dirtyEntryId || !cachedResult || !filename.endsWith(".vue") || cachedAutoRoutesSignature !== autoRoutesSignature || !isVueJsonOnlyDirtyReasonSummary(dirtyReasonSummary)) return;
	const refreshed = await refreshVueFileJsonConfig(source, filename, cachedResult, compileOptions);
	return refreshed ? normalizeVueTransformResult(refreshed) : void 0;
}
//#endregion
//#region src/plugins/vue/transform/plugin/transformFile/reuse.ts
async function tryReuseVueCompilation(options) {
	const { ctx, pluginCtx, filename, source, cachedCompilation, previousStyleSignature, autoRoutesSignature, dirtyEntryId, dirtyVueEntryIds, isCssImporterDirty, canAttemptStyleOnlyReuse, isJsxTemplateDependencyDirty, sourceMap, isApp, styleBlocksCache, styleRefreshTokens, readAndParseSfc, createReadAndParseSfcOptions, measureStage, measureVueHmrStage, reportTiming } = options;
	const configService = ctx.configService;
	if (configService.isDev && cachedCompilation && !isJsxTemplateDependencyDirty && (filename.endsWith(".vue") || (cachedCompilation.refreshToken ?? 0) === 0) && !ctx.runtimeState.scan.isDirty && cachedCompilation.source === source && cachedCompilation.autoRoutesSignature === autoRoutesSignature) {
		cachedCompilation.refreshToken = 0;
		const cachedResult = normalizeVueTransformResult(cachedCompilation.result);
		let cachedStyleBlocks = cachedResult.meta?.styleBlocks ?? styleBlocksCache.get(filename);
		let canReturnCachedCompilation = true;
		if (dirtyEntryId && canAttemptStyleOnlyReuse && filename.endsWith(".vue")) {
			const refreshedStyleBlocks = await measureStage("loadStyleOnlySfcStyles", async () => await loadStyleBlocksForStyleOnlyRefresh({
				filename,
				source,
				styleBlocksCache,
				force: true,
				readAndParseSfc,
				createReadAndParseSfcOptions,
				pluginCtx,
				configService
			}));
			if (!await refreshStyleOnlyVueTransformResult(cachedResult, filename, refreshedStyleBlocks, resolveSfcStylePreprocessOptions(configService))) {
				cachedCompilation.styleIndependentSignature = void 0;
				canReturnCachedCompilation = false;
			} else {
				cachedStyleBlocks = refreshedStyleBlocks;
				cachedCompilation.result = cachedResult;
				const currentStyleSignature = createSfcStyleBlocksSignature(cachedStyleBlocks);
				const hmrEventId = ctx.runtimeState.build?.hmr?.profile?.eventId;
				if (hmrEventId != null && (isCssImporterDirty || currentStyleSignature && currentStyleSignature !== previousStyleSignature)) styleRefreshTokens.set(filename, hmrEventId);
				else styleRefreshTokens.delete(filename);
			}
		}
		if (!canReturnCachedCompilation) cachedCompilation.refreshToken = 1;
		else {
			const returnedCode = await measureVueHmrStage("finalizeCode", "vueFinalizeCodeMs", async () => finalizeTransformEntryCode({
				result: cachedResult,
				filename,
				styleBlocks: cachedStyleBlocks,
				isPage: cachedCompilation.isPage,
				isApp,
				isDev: configService.isDev,
				sourceMap,
				hmrStyleToken: styleRefreshTokens.get(filename)
			}));
			if (dirtyEntryId) dirtyVueEntryIds?.delete(dirtyEntryId);
			reportTiming(filename, cachedCompilation.isPage);
			return { returnedCode };
		}
	}
	const currentStyleIndependentSignature = configService.isDev && dirtyEntryId && canAttemptStyleOnlyReuse && filename.endsWith(".vue") ? resolveVueSfcStyleIndependentSignature(source, filename) : void 0;
	if (Boolean(configService.isDev && cachedCompilation && dirtyEntryId && canAttemptStyleOnlyReuse && filename.endsWith(".vue") && !ctx.runtimeState.scan.isDirty && cachedCompilation.autoRoutesSignature === autoRoutesSignature && cachedCompilation.styleIndependentSignature && currentStyleIndependentSignature && cachedCompilation.styleIndependentSignature === currentStyleIndependentSignature && cachedCompilation.source !== source) && cachedCompilation) {
		const cachedResult = normalizeVueTransformResult(cachedCompilation.result);
		const styleBlocks = await measureStage("loadStyleOnlySfcStyles", async () => await loadStyleBlocksForStyleOnlyRefresh({
			filename,
			source,
			styleBlocksCache,
			force: true,
			readAndParseSfc,
			createReadAndParseSfcOptions,
			pluginCtx,
			configService
		}));
		if (!await refreshStyleOnlyVueTransformResult(cachedResult, filename, styleBlocks, resolveSfcStylePreprocessOptions(configService))) cachedCompilation.styleIndependentSignature = void 0;
		else {
			cachedCompilation.source = source;
			cachedCompilation.result = cachedResult;
			cachedCompilation.styleIndependentSignature = currentStyleIndependentSignature;
			cachedCompilation.refreshToken = 0;
			const hmrEventId = ctx.runtimeState.build?.hmr?.profile?.eventId;
			if (hmrEventId != null && (isCssImporterDirty || styleBlocks?.length)) styleRefreshTokens.set(filename, hmrEventId);
			const returnedCode = await measureVueHmrStage("finalizeCode", "vueFinalizeCodeMs", async () => finalizeTransformEntryCode({
				result: cachedResult,
				filename,
				styleBlocks,
				isPage: cachedCompilation.isPage,
				isApp,
				isDev: configService.isDev,
				sourceMap,
				hmrStyleToken: styleRefreshTokens.get(filename)
			}));
			if (dirtyEntryId) dirtyVueEntryIds?.delete(dirtyEntryId);
			reportTiming(filename, cachedCompilation.isPage);
			return {
				currentStyleIndependentSignature,
				returnedCode
			};
		}
	}
	return { currentStyleIndependentSignature };
}
//#endregion
//#region src/plugins/vue/transform/plugin/transformFile.ts
async function transformVueLikeFile(options) {
	const { ctx, pluginCtx, code, id, compilationCache, setAppShell, pageMatcher, setPageMatcher, scanDirtySynced, setScanDirtySynced, reExportResolutionCache, compileOptionsCache, componentMetaCache, styleBlocksCache, styleRefreshTokens, scopedSlotModules, emittedScopedSlotChunks, classStyleRuntimeWarned, readAndParseSfc, createReadAndParseSfcOptions } = options;
	const vueTransformTiming = ctx.configService?.weappViteConfig?.debug?.vueTransformTiming;
	const { measureStage, reportTiming } = createTransformStageMeasurer(vueTransformTiming);
	const configService = ctx.configService;
	if (!configService) return null;
	const filename = resolveTransformFilename({
		id,
		configService,
		pluginCtx,
		getSourceFromVirtualId
	});
	if (!filename) return null;
	const sourceMap = isVueTransformSourceMapEnabled(configService);
	const measureVueHmrStage = async (stage, profileKey, action) => {
		const startedAt = performance$1.now();
		try {
			return await measureStage(stage, action);
		} finally {
			recordHmrProfileDuration(ctx.runtimeState.build?.hmr?.profile, profileKey, performance$1.now() - startedAt);
		}
	};
	try {
		const cachedCompilation = compilationCache.get(filename);
		const previousStyleSignature = createSfcStyleBlocksSignature(cachedCompilation?.result.meta?.styleBlocks ?? styleBlocksCache.get(filename));
		const source = await measureVueHmrStage("readSource", "vueReadSourceMs", async () => await loadTransformSource({
			code,
			filename,
			isDev: configService.isDev,
			readFileCached: readFile$1
		}));
		const { isPage, isApp } = await measureStage("matchPageEntry", async () => await resolveTransformEntryFlags({
			pageMatcher,
			setPageMatcher,
			createPageMatcher: createPageEntryMatcher$1,
			configService,
			scanService: ctx.scanService,
			scanDirty: ctx.runtimeState.scan.isDirty,
			scanDirtySynced,
			setScanDirtySynced,
			filename
		}));
		let transformedSource = source;
		let autoRoutesSignature;
		if (isApp) {
			const transformed = await measureStage("ensureAutoRoutes", async () => await resolveTransformAutoRoutesSource({
				source: transformedSource,
				autoRoutesService: ctx.autoRoutesService
			}));
			transformedSource = transformed.source;
			autoRoutesSignature = transformed.signature;
		}
		const dirtyVueEntryIds = ctx.runtimeState?.build?.hmr?.dirtyVueEntryIds;
		const dirtyEntryId = resolveDirtyVueEntryId(dirtyVueEntryIds, filename);
		const isJsxTemplateDependencyDirty = Boolean(dirtyEntryId && /\.(?:jsx|tsx)$/.test(ctx.runtimeState?.build?.hmr?.profile?.file ?? ""));
		const isCssImporterDirty = isVueCssImporterDirtyReasonSummary(ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary);
		const canAttemptStyleOnlyReuse = isVueStyleOnlyDirtyReasonSummary(ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary);
		const reuseResult = await tryReuseVueCompilation({
			ctx,
			pluginCtx,
			filename,
			source: transformedSource,
			cachedCompilation,
			previousStyleSignature,
			autoRoutesSignature,
			dirtyEntryId,
			dirtyVueEntryIds,
			isCssImporterDirty,
			canAttemptStyleOnlyReuse,
			isJsxTemplateDependencyDirty,
			sourceMap,
			isApp,
			styleBlocksCache,
			styleRefreshTokens,
			readAndParseSfc,
			createReadAndParseSfcOptions,
			measureStage,
			measureVueHmrStage,
			reportTiming
		});
		if (reuseResult.returnedCode) return {
			code: reuseResult.returnedCode.code,
			map: reuseResult.returnedCode.map
		};
		const { currentStyleIndependentSignature } = reuseResult;
		const compileOptions = createCompileVueFileOptions(ctx, pluginCtx, filename, isPage, isApp, configService, {
			reExportResolutionCache,
			classStyleRuntimeWarned,
			compileOptionsCache,
			componentMetaCache
		});
		const jsonOnlyResult = await measureVueHmrStage("refreshJsonConfig", "vueCompileMs", async () => {
			return await tryRefreshJsonOnlyVueCompilation({
				cachedResult: cachedCompilation?.result,
				compileOptions,
				dirtyEntryId,
				dirtyReasonSummary: ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary,
				filename,
				isDev: configService.isDev,
				scanDirty: ctx.runtimeState.scan.isDirty,
				source: transformedSource,
				autoRoutesSignature,
				cachedAutoRoutesSignature: cachedCompilation?.autoRoutesSignature
			});
		});
		if (jsonOnlyResult) {
			const returnedCode = await finalizeVueTransform({
				ctx,
				pluginCtx,
				filename,
				source: transformedSource,
				autoRoutesSignature,
				result: jsonOnlyResult,
				compilationCache,
				currentStyleIndependentSignature: cachedCompilation?.styleIndependentSignature,
				previousStyleSignature,
				dirtyEntryId,
				dirtyVueEntryIds,
				isCssImporterDirty,
				isPage,
				isApp,
				sourceMap,
				styleBlocksCache,
				styleRefreshTokens,
				scopedSlotModules,
				emittedScopedSlotChunks,
				setAppShell,
				readAndParseSfc,
				createReadAndParseSfcOptions,
				measureStage,
				measureVueHmrStage,
				reportTiming
			});
			return {
				code: returnedCode.code,
				map: returnedCode.map
			};
		}
		const result = normalizeVueTransformResult(await measureVueHmrStage("compile", "vueCompileMs", async () => await compileTransformEntryResult({
			transformedSource,
			filename,
			compileOptions,
			compileVueFile,
			compileJsxFile
		})));
		const returnedCode = await finalizeVueTransform({
			ctx,
			pluginCtx,
			filename,
			source: transformedSource,
			autoRoutesSignature,
			result,
			compilationCache,
			currentStyleIndependentSignature,
			previousStyleSignature,
			dirtyEntryId,
			dirtyVueEntryIds,
			isCssImporterDirty,
			isPage,
			isApp,
			sourceMap,
			styleBlocksCache,
			styleRefreshTokens,
			scopedSlotModules,
			emittedScopedSlotChunks,
			setAppShell,
			readAndParseSfc,
			createReadAndParseSfcOptions,
			measureStage,
			measureVueHmrStage,
			reportTiming
		});
		return {
			code: returnedCode.code,
			map: returnedCode.map
		};
	} catch (error) {
		logTransformFileError(filename, error);
		throw error;
	}
}
//#endregion
//#region src/plugins/vue/transform/plugin/index.ts
const VUE_TRANSFORM_FILTER_RE = /\.(?:vue|tsx|jsx)(?:\?.*)?$/;
const VUE_LOAD_FILTER_RE = /^(?:\0weapp-vite:scoped-slot:|.*[?&]weapp-vite-vue(?:[=&]|$))/;
const SCOPED_SLOT_VIRTUAL_ID_RE = /^\0weapp-vite:scoped-slot:/;
function invalidateDirtyVueEntryCaches(dirtyVueEntryIds, compilationCache) {
	if (!dirtyVueEntryIds?.size) return;
	const cachedEntriesByNormalizedId = /* @__PURE__ */ new Map();
	for (const [cachedId, cached] of compilationCache.entries()) cachedEntriesByNormalizedId.set(normalizeFsResolvedId(cachedId), cached);
	for (const entryId of dirtyVueEntryIds) {
		const cached = compilationCache.get(entryId) ?? cachedEntriesByNormalizedId.get(normalizeFsResolvedId(entryId));
		if (!cached) continue;
		cached.refreshToken = (cached.refreshToken ?? 0) + 1;
	}
}
function invalidateComponentMetaCache(componentMetaCache, id) {
	componentMetaCache.delete(id);
	componentMetaCache.delete(normalizeFsResolvedId(id));
}
function createVueTransformPlugin(ctx, options = {}) {
	const compilationCache = /* @__PURE__ */ new Map();
	let appShell;
	let pageMatcher = null;
	let scanDirtySynced = false;
	const reExportResolutionCache = /* @__PURE__ */ new Map();
	const compileOptionsCache = /* @__PURE__ */ new Map();
	const componentMetaCache = /* @__PURE__ */ new Map();
	const styleBlocksCache = /* @__PURE__ */ new Map();
	const styleRefreshTokens = /* @__PURE__ */ new Map();
	const scopedSlotModules = /* @__PURE__ */ new Map();
	const emittedScopedSlotChunks = /* @__PURE__ */ new Set();
	const classStyleRuntimeWarned = { value: false };
	return {
		name: `${VUE_PLUGIN_NAME}:transform`,
		async buildStart() {
			scopedSlotModules.clear();
			emittedScopedSlotChunks.clear();
			compileOptionsCache.clear();
			componentMetaCache.clear();
			await preloadNativeLayoutEntries({
				pluginCtx: this,
				ctx,
				configService: ctx.configService,
				scanService: ctx.scanService,
				collectFallbackPageEntryIds: async (configService, scanService) => {
					return Array.from(await collectFallbackPageEntryIds(configService, scanService));
				},
				findFirstResolvedVueLikeEntry,
				pathExists: fs$1.pathExists,
				readFile: fs$1.readFile
			});
		},
		resolveId(id) {
			if (!SCOPED_SLOT_VIRTUAL_ID_RE.test(id)) return null;
			const startedAt = performance.now();
			try {
				return resolveScopedSlotVirtualId(id);
			} finally {
				const profile = ctx.runtimeState?.build?.hmr?.profile;
				recordHmrProfileDuration(profile, "pluginResolveMs", performance.now() - startedAt);
				recordHmrProfileOperation(profile, "resolveCount");
			}
		},
		async load(id) {
			if (!VUE_LOAD_FILTER_RE.test(id)) return null;
			return await loadTransformStyleBlock({
				id,
				pluginCtx: this,
				ctx,
				configService: ctx.configService,
				styleBlocksCache,
				loadScopedSlotModule: (id) => {
					return loadScopedSlotModule(id, scopedSlotModules)?.code ?? null;
				},
				scopedSlotModules,
				parseWeappVueStyleRequest: (id) => parseWeappVueStyleRequest(id) ?? null,
				readAndParseSfc,
				createReadAndParseSfcOptions
			});
		},
		async transform(code, id) {
			if (options.react && /\.(?:jsx|tsx)(?:\?.*)?$/.test(id)) return null;
			if (parseSidecarSourceRequest(id) || !VUE_TRANSFORM_FILTER_RE.test(id) || !isVueLikeId(id)) return null;
			const startedAt = performance.now();
			try {
				return await transformVueLikeFile({
					ctx,
					pluginCtx: this,
					code,
					id,
					compilationCache,
					setAppShell: (shell) => appShell = shell,
					pageMatcher,
					setPageMatcher: (matcher) => pageMatcher = matcher,
					scanDirtySynced,
					setScanDirtySynced: (synced) => scanDirtySynced = synced,
					reExportResolutionCache,
					compileOptionsCache,
					componentMetaCache,
					styleBlocksCache,
					styleRefreshTokens,
					scopedSlotModules,
					emittedScopedSlotChunks,
					classStyleRuntimeWarned,
					readAndParseSfc,
					createReadAndParseSfcOptions
				});
			} finally {
				const durationMs = performance.now() - startedAt;
				recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "transformMs", durationMs);
				recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "vueTransformMs", durationMs);
			}
		},
		async generateBundle(_options, bundle) {
			await emitVueBundleAssets(bundle, {
				ctx,
				pluginCtx: this,
				compilationCache,
				appShell,
				reExportResolutionCache,
				compileOptionsCache,
				componentMetaCache,
				classStyleRuntimeWarned
			});
		},
		watchChange(id, change) {
			const startedAt = performance.now();
			const normalizedId = normalizeFsResolvedId(id);
			invalidateComponentMetaCache(componentMetaCache, normalizedId);
			handleTransformLayoutInvalidation(normalizedId, {
				configService: ctx.configService,
				compilationCache,
				styleBlocksCache,
				styleRefreshTokens,
				isLayoutFile,
				invalidateResolvedPageLayoutsCache
			});
			handleTransformVueFileInvalidation(normalizedId, {
				compilationCache,
				styleBlocksCache,
				styleRefreshTokens,
				existsSync: fs$1.existsSync
			});
			invalidateDirtyVueEntryCaches(ctx.runtimeState?.build?.hmr?.dirtyVueEntryIds, compilationCache);
			const profile = ctx.runtimeState?.build?.hmr?.profile;
			if (profile && !profile.file) {
				profile.eventId = createHmrProfileEventId();
				profile.event = change?.event ?? "update";
				profile.file = normalizedId;
				profile.watchToDirtyMs = performance.now() - startedAt;
			}
		},
		async handleHotUpdate({ file }) {
			invalidateComponentMetaCache(componentMetaCache, file);
			if (handleTransformLayoutInvalidation(file, {
				configService: ctx.configService,
				compilationCache,
				styleBlocksCache,
				styleRefreshTokens,
				isLayoutFile,
				invalidateResolvedPageLayoutsCache
			})) return [];
			if (!handleTransformVueFileInvalidation(file, {
				compilationCache,
				styleBlocksCache,
				styleRefreshTokens,
				existsSync: fs$1.existsSync
			})) return;
			return [];
		}
	};
}
//#endregion
//#region src/plugins/vue/watch.ts
function createVueWatchPlugin(_ctx) {
	return {
		name: `${VUE_PLUGIN_NAME}:watch`,
		configureServer(server) {
			server.watcher.on("change", (id) => {
				if (isVueLikeFile(id)) {
					if (server.moduleGraph.getModuleById(id)) server.ws.send({
						type: "full-reload",
						path: id
					});
				}
			});
		},
		async handleHotUpdate({ file }) {
			if (!isVueLikeFile(file)) return;
			return [];
		}
	};
}
//#endregion
//#region src/plugins/vue/index.ts
const VUE_PLUGIN_NAME = "weapp-vite:vue";
function vuePlugin(ctx, options) {
	if (options?.enable === false) return [];
	return [
		createVueResolverPlugin(ctx, options),
		createVueTransformPlugin(ctx, options),
		createVueWatchPlugin(ctx)
	];
}
const vue = vuePlugin;
//#endregion
//#region src/plugins/workers.ts
async function resolveWorkerEntry(ctx, entry) {
	const { configService, scanService } = ctx;
	const relativeEntryPath = path.join(scanService.workersDir, entry);
	const key = removeExtension(relativeEntryPath);
	const absoluteEntry = path.resolve(configService.absoluteSrcRoot, relativeEntryPath);
	if (isJsOrTs(entry)) {
		if (!await fs$1.pathExists(absoluteEntry)) {
			logger_default.warn(`引用 worker: \`${configService.relativeCwd(relativeEntryPath)}\` 不存在!`);
			return { key };
		}
		return {
			key,
			value: absoluteEntry
		};
	}
	const { path: discovered } = await findJsEntry(absoluteEntry);
	if (!discovered) {
		logger_default.warn(`引用 worker: \`${configService.relativeCwd(relativeEntryPath)}\` 不存在!`);
		return { key };
	}
	return {
		key,
		value: discovered
	};
}
function createWorkerBuildPlugin(ctx) {
	const { configService, scanService } = ctx;
	return {
		name: "weapp-vite:workers",
		enforce: "pre",
		async options(options) {
			const workerConfig = configService.weappViteConfig?.worker;
			const entries = Array.isArray(workerConfig?.entry) ? workerConfig.entry : [workerConfig?.entry];
			options.input = (await Promise.all(entries.filter(Boolean).map((entry) => resolveWorkerEntry(ctx, entry)))).filter((result) => Boolean(result.value)).reduce((acc, cur) => {
				acc[cur.key] = cur.value;
				return acc;
			}, {});
		},
		watchChange(id, change) {
			logger_default.success(`[workers:${change.event}] ${configService.relativeCwd(id)}`);
		},
		outputOptions(options) {
			options.chunkFileNames = (chunkInfo) => {
				const workersDir = scanService.workersDir ?? "";
				if (chunkInfo.isDynamicEntry) return path.join(workersDir, "[name].js");
				const sourceId = chunkInfo.facadeModuleId ?? chunkInfo.moduleIds[0];
				const hashBase = typeof sourceId === "string" ? configService.relativeCwd(sourceId) : chunkInfo.name;
				const stableHash = createHash("sha256").update(hashBase).digest("base64url").slice(0, 8);
				return path.join(workersDir, `${chunkInfo.name}-${stableHash}.js`);
			};
		}
	};
}
function workers(ctx) {
	if (!ctx.scanService.workersDir) return [];
	return [createWorkerBuildPlugin(ctx)];
}
//#endregion
//#region src/plugins/wxs.ts
const wxsCodeCache = new LRUCache({ max: 512 });
const WXS_FILE_SUFFIX_RE = /\.(?:wxs|sjs)(\.[jt]s)?$/;
const WXS_SCAN_RELEVANT_HMR_RE = /\.(?:vue|wxml|axml|swan|ttml|jxml|qml|ksml|xhsml|html|wxs|sjs)(?:\.[jt]s)?$/i;
function createWxsCodeCacheKey(rawCode, scriptModuleExtension) {
	return `${scriptModuleExtension ?? "wxs"}::${rawCode}`;
}
function resolveWxsOutputFileName(ctx, wxsPath, scriptModuleExtension) {
	const suffixMatch = wxsPath.match(WXS_FILE_SUFFIX_RE);
	const isRaw = suffixMatch ? !suffixMatch[1] : true;
	return resolveRelativeOutputFileNameWithExtension(ctx.configService, isRaw ? wxsPath : removeExtension(wxsPath), scriptModuleExtension ?? "wxs");
}
async function transformWxsFile(state, wxsPath) {
	const { ctx } = state;
	const { configService } = ctx;
	const { scriptModuleExtension } = resolveCompilerOutputExtensions(configService.outputExtensions);
	let rawCode;
	try {
		rawCode = await fs$1.readFile(wxsPath, "utf8");
	} catch {
		return;
	}
	const { result, importees } = transformWxsCode(rawCode, {
		filename: wxsPath,
		extension: scriptModuleExtension
	});
	const cacheKey = createWxsCodeCacheKey(rawCode, scriptModuleExtension);
	const code = wxsCodeCache.get(cacheKey) ?? result?.code;
	const dirname = path.dirname(wxsPath);
	const importeePaths = importees.map(({ source }) => path.resolve(dirname, source));
	await Promise.all(importeePaths.map((importeePath) => transformWxsFile.call(this, state, importeePath)));
	if (code == null) return;
	const emittedFile = {
		type: "asset",
		fileName: resolveWxsOutputFileName(ctx, wxsPath, scriptModuleExtension),
		source: code
	};
	state.wxsMap.set(wxsPath, { emittedFile });
	wxsCodeCache.set(cacheKey, code);
}
async function handleWxsDeps(state, deps, absPath) {
	await Promise.all(deps.filter((dep) => isScriptModuleTagName(dep.tagName)).map(async (dep) => {
		const arr = dep.value.match(WXS_FILE_SUFFIX_RE);
		if (!jsExtensions.includes(dep.attrs.lang) && !arr) return;
		const wxsPath = path.resolve(path.dirname(absPath), dep.value);
		await transformWxsFile.call(this, state, wxsPath);
	}));
}
async function handleWxsDepsFromBundle(state, bundle) {
	const { templateExtension } = resolveCompilerOutputExtensions(state.ctx.configService.outputExtensions);
	const platform = state.ctx.configService.platform;
	await Promise.all(Object.entries(bundle).filter(([fileName, output]) => {
		return fileName.endsWith(`.${templateExtension}`) && output?.type === "asset";
	}).map(async ([fileName, output]) => {
		const source = output.source?.toString?.();
		if (!source) return;
		let deps = [];
		try {
			deps = scanWxml(source, { platform }).deps;
		} catch {
			return;
		}
		const absPath = path.resolve(state.ctx.configService.absoluteSrcRoot, fileName);
		await handleWxsDeps.call(this, state, deps, absPath);
	}));
}
function shouldScanWxsTokenMap(state) {
	const hmrProfile = state.ctx.runtimeState?.build?.hmr?.profile;
	if (!state.ctx.configService.isDev || hmrProfile?.event === void 0) return true;
	if (!hmrProfile.file) return true;
	return WXS_SCAN_RELEVANT_HMR_RE.test(hmrProfile.file) || hmrProfile.dirtyReasonSummary?.some((reason) => reason.startsWith("importer-graph:")) === true;
}
function shouldScanFullWxsTokenMap(state) {
	const hmrProfile = state.ctx.runtimeState?.build?.hmr?.profile;
	if (!state.ctx.configService.isDev || hmrProfile?.event === void 0) return true;
	if (!hmrProfile.file) return true;
	return WXS_FILE_SUFFIX_RE.test(hmrProfile.file) || hmrProfile.dirtyReasonSummary?.some((reason) => reason.startsWith("importer-graph:")) === true;
}
function resolveWxsTokenScanEntries(state) {
	const tokenMap = state.ctx.wxmlService.tokenMap;
	if (!shouldScanWxsTokenMap(state)) return [];
	if (shouldScanFullWxsTokenMap(state)) return Array.from(tokenMap.entries());
	const hmrFile = state.ctx.runtimeState?.build?.hmr?.profile?.file;
	if (!hmrFile) return [];
	const token = tokenMap.get(hmrFile);
	return token ? [[hmrFile, token]] : [];
}
function createWxsPlugin(state) {
	return {
		name: "weapp-vite:wxs",
		enforce: "post",
		buildStart() {
			state.wxsMap.clear();
		},
		async generateBundle(_options, bundle) {
			state.wxsMap.clear();
			const tokenEntries = resolveWxsTokenScanEntries(state);
			if (tokenEntries.length) await Promise.all(tokenEntries.map(([id, token]) => {
				return handleWxsDeps.call(this, state, token.deps, id);
			}));
			await handleWxsDepsFromBundle.call(this, state, bundle);
			for (const { emittedFile } of state.wxsMap.values()) this.emitFile(emittedFile);
		}
	};
}
function wxs(ctx) {
	return [createWxsPlugin({
		ctx,
		wxsMap: /* @__PURE__ */ new Map()
	})];
}
//#endregion
//#region src/plugins/index.ts
const RUNTIME_PLUGINS_SYMBOL = Symbol.for("weapp-runtime:plugins");
const WEAPP_VITE_CONTEXT_PLUGIN_NAME = "weapp-vite:context";
function createContextPlugin(ctx) {
	return {
		name: WEAPP_VITE_CONTEXT_PLUGIN_NAME,
		enforce: "pre",
		api: { ctx }
	};
}
function attachRuntimePlugins(ctx, plugins) {
	const runtimePlugins = ctx[RUNTIME_PLUGINS_SYMBOL];
	if (!runtimePlugins?.length) return plugins;
	return [...runtimePlugins, ...plugins];
}
function applyInspect(ctx, plugins) {
	const inspectOptions = ctx.configService.weappViteConfig?.debug?.inspect;
	if (!inspectOptions) return plugins;
	return wrapPlugin(plugins, inspectOptions);
}
function flatten(groups) {
	return groups.reduce((acc, cur) => {
		acc.push(...cur);
		return acc;
	}, []);
}
function hasWevuDependency(ctx) {
	const packageJson = ctx.configService?.packageJson;
	return Boolean(packageJson?.dependencies?.wevu || packageJson?.devDependencies?.wevu);
}
function vitePluginWeapp(ctx, subPackageMeta) {
	const libModeEnabled = ctx.configService?.weappLibConfig?.enabled;
	const vueEnabled = ctx.configService?.weappViteConfig?.vue?.enable !== false;
	const reactEnabled = isReactEnabled(ctx);
	const runtimeProvider = resolveRuntimeProvider("miniprogram", vueEnabled && (!reactEnabled || hasWevuDependency(ctx)) ? "vue" : "native");
	const groups = [
		[createContextPlugin(ctx), createSelectedRuntimeProviderPlugin(runtimeProvider, ctx.configService.isDev)],
		preflight(ctx),
		uniAppCompatibility(ctx),
		createReactPlugin(ctx),
		vue(ctx, {
			enable: vueEnabled,
			react: reactEnabled
		})
	];
	if (vueEnabled && !libModeEnabled && !reactEnabled) groups.push(wevu(ctx));
	const autoRoutesEnabled = resolveWeappAutoRoutesConfig(ctx.configService?.weappViteConfig?.autoRoutes).enabled;
	if (!subPackageMeta) {
		groups.push(asset(ctx));
		if (autoRoutesEnabled && !libModeEnabled) groups.push(autoRoutes(ctx));
		groups.push(autoImport(ctx));
	}
	const tailwindcssPlugins = createTailwindcssPlugin(ctx);
	groups.push(i18n(ctx, subPackageMeta), weappVite(ctx, subPackageMeta), wxs(ctx));
	if (tailwindcssPlugins.length > 0) groups.push([tailwindcssPlugins[0]]);
	groups.push(css(ctx));
	groups.push([createOutputFinalizerPlugin(ctx, subPackageMeta)]);
	if (tailwindcssPlugins.length > 1) groups.push([tailwindcssPlugins[1]]);
	const assembled = attachRuntimePlugins(ctx, flatten(groups));
	if (subPackageMeta) return assembled;
	return applyInspect(ctx, assembled);
}
function vitePluginWeappWorkers(ctx) {
	return applyInspect(ctx, attachRuntimePlugins(ctx, flatten([
		[createContextPlugin(ctx)],
		preflight(ctx),
		workers(ctx)
	])));
}
//#endregion
//#region src/runtime/config/internal/merge/plugins.ts
const WEAPP_VITE_OUTPUT_FINALIZER_PLUGIN_NAME = "weapp-vite:output-finalizer";
function normalizePluginOptions(option) {
	const normalized = [];
	if (!option) return normalized;
	if (Array.isArray(option)) {
		for (const entry of option) normalized.push(...normalizePluginOptions(entry));
		return normalized;
	}
	normalized.push(option);
	return normalized;
}
function isNamedPlugin(option, name) {
	return typeof option === "object" && option !== null && "name" in option && option.name === name;
}
function arrangePlugins(config, ctx, subPackageMeta) {
	const existing = normalizePluginOptions(config.plugins);
	const internal = normalizePluginOptions(vitePluginWeapp(ctx, subPackageMeta));
	const tsconfigPlugins = [];
	const others = [];
	const finalizers = [];
	for (const entry of internal) {
		if (!entry) continue;
		if (isNamedPlugin(entry, WEAPP_VITE_OUTPUT_FINALIZER_PLUGIN_NAME)) {
			finalizers.push(entry);
			continue;
		}
		others.push(entry);
	}
	for (const entry of existing) {
		if (!entry) continue;
		if (isNamedPlugin(entry, "vite-tsconfig-paths")) {
			tsconfigPlugins.push(entry);
			continue;
		}
		if (isNamedPlugin(entry, "weapp-vite:context") || isNamedPlugin(entry, WEAPP_VITE_OUTPUT_FINALIZER_PLUGIN_NAME)) continue;
		others.push(entry);
	}
	config.plugins = [
		...others,
		...tsconfigPlugins,
		...finalizers
	];
}
//#endregion
//#region src/runtime/config/internal/merge/miniprogram.ts
const PACKAGE_NAME_REGEX = /[-/\\^$*+?.()|[\]{}]/g;
const PATH_SEPARATOR_SPLIT_REGEX = /[/\\]+/;
function escapeRegex(value) {
	return value.replace(PACKAGE_NAME_REGEX, "\\$&");
}
function createAbsolutePathPattern(value) {
	return value.split(PATH_SEPARATOR_SPLIT_REGEX).map((segment) => escapeRegex(segment)).join("[/\\\\]+");
}
function hasTsconfigReference(tsconfig, target) {
	if (!existsSync(tsconfig)) return false;
	try {
		const parsed = parse(readFileSync(tsconfig, "utf8"), void 0, true);
		const references = Array.isArray(parsed.references) ? parsed.references : [];
		const tsconfigDir = path.dirname(tsconfig);
		return references.some((reference) => {
			if (!reference || typeof reference !== "object" || typeof reference.path !== "string") return false;
			return path.resolve(tsconfigDir, reference.path) === target;
		});
	} catch {
		return false;
	}
}
function resolveDefaultRolldownTsconfig(cwd, configFilePath) {
	const configRoot = configFilePath ? path.dirname(configFilePath) : void 0;
	const projectRoot = configRoot && existsSync(path.resolve(configRoot, ".weapp-vite/tsconfig.app.json")) ? configRoot : cwd;
	const appTsconfig = path.resolve(projectRoot, ".weapp-vite/tsconfig.app.json");
	const rootTsconfig = path.resolve(projectRoot, "tsconfig.json");
	if (existsSync(appTsconfig)) return appTsconfig;
	if (hasTsconfigReference(rootTsconfig, appTsconfig)) return appTsconfig;
	if (existsSync(rootTsconfig)) return rootTsconfig;
}
function normalizeInlineConfigAfterDefu(inline, options) {
	const { cwd, configFilePath, ctx, platform, rolldownOptions, subPackageMeta } = options;
	const build = inline.build ?? (inline.build = {});
	const userRolldownOptions = build.rolldownOptions;
	const mergedRolldownOptions = {
		...userRolldownOptions ?? {},
		...rolldownOptions,
		output: {
			...rolldownOptions.output,
			...userRolldownOptions?.output ?? {}
		}
	};
	if (ctx.configService) normalizePreserveModulesRolldownOptions(ctx.configService, mergedRolldownOptions);
	const defaultTsconfig = resolveDefaultRolldownTsconfig(cwd, configFilePath);
	const resolveOptions = mergedRolldownOptions.resolve;
	if (defaultTsconfig) {
		if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig")) mergedRolldownOptions.tsconfig = configFilePath && !resolveOptions?.tsconfigFilename ? false : defaultTsconfig;
	} else if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig") && !resolveOptions?.tsconfigFilename) mergedRolldownOptions.tsconfig = false;
	build.rolldownOptions = mergedRolldownOptions;
	inline.define = {
		...inline.define ?? {},
		__VITE_IS_MODERN__: "false"
	};
	applyWeappViteHostMeta(inline, "miniprogram", platform);
	stripRollupOptions(inline);
	arrangePlugins(inline, ctx, subPackageMeta);
}
function resolveMiniprogramWatchInclude(options) {
	const srcRoot = path.join(options.cwd, options.srcRoot);
	const watchInclude = ["**", ...options.buildScope?.enabled ? [...options.buildScope.includeMainPackage ? [path.join(srcRoot, "pages", "**")] : [], ...options.buildScope.subPackageRoots.map((root) => path.join(srcRoot, root, "**"))] : [path.join(srcRoot, "**")]];
	if (options.pluginRoot) {
		const absolutePluginRoot = path.resolve(options.cwd, options.pluginRoot);
		const relativeToSrc = path.relative(path.resolve(options.cwd, options.srcRoot), absolutePluginRoot);
		const pluginPatternBase = relativeToSrc.startsWith("..") ? absolutePluginRoot : path.join(options.cwd, options.srcRoot, relativeToSrc);
		watchInclude.push(path.join(pluginPatternBase, "**"));
	}
	for (const dependency of options.configFileDependencies ?? []) watchInclude.push(dependency);
	const include = [...Array.isArray(options.userInclude) ? options.userInclude : options.userInclude ? [options.userInclude] : [], ...watchInclude];
	const seen = /* @__PURE__ */ new Set();
	return include.filter((item) => {
		if (typeof item !== "string") return true;
		if (seen.has(item)) return false;
		seen.add(item);
		return true;
	});
}
function mergeMiniprogram(options, ...configs) {
	const { ctx, subPackageMeta, config, cwd, srcRoot, mpDistRoot, configFileDependencies = [], configFilePath, packageJson, isDev, applyRuntimePlatform, injectBuiltinAliases, getDefineImportMetaEnv, setOptions, oxcRolldownPlugin } = options;
	const platform = ctx.configService?.platform;
	applyRuntimePlatform("miniprogram");
	const createMiniprogramCustomLogger = () => {
		return createLogger("warn");
	};
	const external = [];
	const npmBuildCandidates = packageJson ? resolveNpmBuildCandidateDependenciesSync(ctx, packageJson) : [];
	if (npmBuildCandidates.length > 0) {
		const builtinAliases = resolveBuiltinPackageAliases({
			cwd,
			isDev,
			wevuRuntime: config.weapp?.wevu?.runtime
		});
		external.push(...npmBuildCandidates.map((pkg) => {
			return new RegExp(`^${escapeRegex(pkg)}(\\/|$)`);
		}), ...builtinAliases.filter(({ find }) => {
			return npmBuildCandidates.some((dep) => find === dep || find.startsWith(`${dep}/`));
		}).map(({ replacement }) => {
			return new RegExp(`^${createAbsolutePathPattern(replacement)}(?:\\?.*)?$`);
		}));
	}
	const rolldownOptions = {
		external,
		plugins: oxcRolldownPlugin ? [oxcRolldownPlugin] : void 0
	};
	const miniprogramDefines = {
		...getDefineImportMetaEnv(),
		__VITE_IS_MODERN__: "false"
	};
	if (isDev) {
		const hmrWatchBuildDelay = 10;
		const userBuildWatch = config.build?.watch;
		const watchInclude = resolveMiniprogramWatchInclude({
			cwd,
			srcRoot,
			pluginRoot: config.weapp?.pluginRoot,
			buildScope: resolveBuildScope(config.weapp?.buildScope),
			configFileDependencies
		});
		const inline = defu(config, ...configs, {
			root: cwd,
			mode: "development",
			customLogger: createMiniprogramCustomLogger(),
			define: miniprogramDefines,
			build: {
				modulePreload: false,
				watch: {
					buildDelay: hmrWatchBuildDelay,
					...typeof userBuildWatch === "object" && userBuildWatch ? userBuildWatch : {},
					exclude: [...defaultExcluded, mpDistRoot ? path.join(cwd, mpDistRoot, "**") : path.join(cwd, "dist", "**")],
					include: watchInclude
				},
				minify: false,
				emptyOutDir: false,
				rolldownOptions: { ...rolldownOptions },
				sourcemap: false
			}
		});
		inline.build.watch.include = resolveMiniprogramWatchInclude({
			cwd,
			srcRoot,
			pluginRoot: config.weapp?.pluginRoot,
			buildScope: resolveBuildScope(config.weapp?.buildScope),
			userInclude: inline.build?.watch?.include,
			configFileDependencies
		});
		normalizeInlineConfigAfterDefu(inline, {
			cwd,
			configFilePath,
			ctx,
			platform,
			rolldownOptions,
			subPackageMeta
		});
		injectBuiltinAliases(inline);
		return inline;
	}
	const inlineConfig = defu(config, ...configs, {
		root: cwd,
		mode: "production",
		define: miniprogramDefines,
		build: {
			modulePreload: false,
			minify: false,
			emptyOutDir: false,
			rolldownOptions: { ...rolldownOptions }
		}
	});
	if (inlineConfig.build) delete inlineConfig.build.watch;
	normalizeInlineConfigAfterDefu(inlineConfig, {
		cwd,
		configFilePath,
		ctx,
		platform,
		rolldownOptions,
		subPackageMeta
	});
	inlineConfig.logLevel = "warn";
	injectBuiltinAliases(inlineConfig);
	const currentRoot = subPackageMeta?.subPackage.root;
	setOptions({ currentSubPackageRoot: currentRoot });
	return inlineConfig;
}
//#endregion
//#region src/runtime/config/internal/merge/web.ts
function mergeWebPlugins(rawPlugins, webPlugin, runtimeProviderPlugin) {
	const remaining = [];
	const ownedPluginNames = new Set([webPlugin, runtimeProviderPlugin].map((option) => option && typeof option === "object" && "name" in option ? option.name : void 0).filter((name) => typeof name === "string"));
	const collect = (option) => {
		if (!option) return;
		if (Array.isArray(option)) {
			option.forEach((item) => collect(item));
			return;
		}
		if (typeof option === "object" && option !== null && "name" in option && typeof option.name === "string" && ownedPluginNames.has(option.name)) return;
		remaining.push(option);
	};
	if (Array.isArray(rawPlugins)) rawPlugins.forEach((entry) => collect(entry));
	else if (rawPlugins) collect(rawPlugins);
	return [
		runtimeProviderPlugin,
		webPlugin,
		...remaining
	].filter(Boolean);
}
function mergeWeb(options, ...configs) {
	const { config, mode, isDev, applyRuntimePlatform, injectBuiltinAliases, getDefineImportMetaEnv } = options;
	const web = options.web;
	if (!web?.enabled) return;
	applyRuntimePlatform("web");
	const inline = defu(config, web.userConfig, ...configs, {
		root: web.root,
		mode,
		configFile: false,
		define: getDefineImportMetaEnv(),
		build: {
			outDir: web.outDir,
			emptyOutDir: !isDev
		}
	});
	stripRollupOptions(inline);
	if (options.configService) normalizePreserveModulesRolldownOptions(options.configService, inline.build?.rolldownOptions ?? (inline.build.rolldownOptions = {}));
	inline.root = web.root;
	inline.configFile = false;
	const runtimeProvider = resolveRuntimeProvider("web", "web");
	const runtimeProviderPlugin = createSelectedRuntimeProviderPlugin(runtimeProvider, isDev);
	const webPlugin = weappWebPlugin({
		...web.pluginOptions,
		__uniApp: options.uniApp || void 0,
		__autoImportResolvers: options.autoImportResolvers,
		__resolveAppConfig: options.resolveAppConfig,
		__runtimeProvider: {
			moduleId: WEAPP_VITE_RUNTIME_VIRTUAL_ID,
			hmrAcceptCode: resolveRuntimeProviderHmrFooter(runtimeProvider)
		}
	});
	inline.plugins = mergeWebPlugins(inline.plugins, webPlugin, runtimeProviderPlugin);
	inline.build ??= {};
	inline.build.outDir = web.outDir;
	inline.build.emptyOutDir ??= !isDev;
	applyWeappViteHostMeta(inline, "web", "web");
	inline.define = defu(inline.define, getDefineImportMetaEnv());
	injectBuiltinAliases(inline, "build");
	const runtimeAlias = {
		find: "weapp-vite/runtime",
		replacement: WEAPP_VITE_RUNTIME_VIRTUAL_ID
	};
	inline.resolve ??= {};
	const aliases = inline.resolve.alias;
	if (Array.isArray(aliases)) inline.resolve.alias = [runtimeAlias, ...aliases.filter((alias) => !(typeof alias === "object" && alias !== null && "find" in alias && alias.find === runtimeAlias.find))];
	else inline.resolve.alias = [runtimeAlias, ...Object.entries(aliases ?? {}).filter(([find]) => find !== runtimeAlias.find).map(([find, replacement]) => ({
		find,
		replacement
	}))];
	return inline;
}
//#endregion
//#region src/runtime/config/internal/merge/workers.ts
function resolveWorkersBuildDefaults(isDev) {
	return isDev ? {
		watch: {},
		minify: false,
		emptyOutDir: false
	} : { emptyOutDir: false };
}
function mergeWorkers(options, ...configs) {
	const { ctx, isDev, config, cwd, injectBuiltinAliases, getDefineImportMetaEnv, applyRuntimePlatform } = options;
	const platform = ctx.configService?.platform;
	applyRuntimePlatform("miniprogram");
	if (isDev) {
		const inline = defu(config, ...configs, {
			root: cwd,
			mode: "development",
			plugins: [vitePluginWeappWorkers(ctx)],
			define: getDefineImportMetaEnv(),
			build: resolveWorkersBuildDefaults(true)
		});
		applyWeappViteHostMeta(inline, "miniprogram", platform);
		stripRollupOptions(inline);
		normalizePreserveModulesRolldownOptions(ctx.configService, inline.build?.rolldownOptions ?? (inline.build.rolldownOptions = {}));
		injectBuiltinAliases(inline);
		return inline;
	}
	const inlineConfig = defu(config, ...configs, {
		root: cwd,
		mode: "production",
		plugins: [vitePluginWeappWorkers(ctx)],
		define: getDefineImportMetaEnv(),
		build: resolveWorkersBuildDefaults(false)
	});
	applyWeappViteHostMeta(inlineConfig, "miniprogram", platform);
	stripRollupOptions(inlineConfig);
	inlineConfig.logLevel = "info";
	normalizePreserveModulesRolldownOptions(ctx.configService, inlineConfig.build?.rolldownOptions ?? (inlineConfig.build.rolldownOptions = {}));
	injectBuiltinAliases(inlineConfig);
	return inlineConfig;
}
//#endregion
//#region src/runtime/config/internal/merge/index.ts
function createMergeFactories(options) {
	const { ctx, getOptions, setOptions, injectBuiltinAliases, getDefineImportMetaEnv, applyRuntimePlatform, oxcRolldownPlugin } = options;
	function mergeWorkersFactory(...configs) {
		ensureConfigService(ctx);
		const currentOptions = getOptions();
		const configService = ctx.configService;
		const subPackageRoots = Object.keys(configService.weappViteConfig.subPackages ?? {});
		const sharedOutput = configService.options.chunksConfigured ? createSharedBuildOutput(configService, () => subPackageRoots) : void 0;
		return mergeWorkers({
			ctx,
			isDev: currentOptions.isDev,
			config: currentOptions.config,
			cwd: currentOptions.cwd,
			injectBuiltinAliases,
			getDefineImportMetaEnv,
			applyRuntimePlatform
		}, sharedOutput ? { build: { rolldownOptions: { output: sharedOutput } } } : {}, ...configs);
	}
	function mergeFactory(subPackageMeta, ...configs) {
		ensureConfigService(ctx);
		const backend = platformBackendRegistry.get("miniprogram");
		if (!backend) throw new Error("小程序平台后端未注册。");
		const currentOptions = getOptions();
		return backend.driver.mergeConfig({ merge: (...backendConfigs) => mergeMiniprogram({
			ctx,
			subPackageMeta,
			config: currentOptions.config,
			cwd: currentOptions.cwd,
			srcRoot: currentOptions.srcRoot,
			mpDistRoot: currentOptions.mpDistRoot,
			configFileDependencies: currentOptions.configFileDependencies,
			configFilePath: currentOptions.configFilePath,
			packageJson: currentOptions.packageJson,
			isDev: currentOptions.isDev,
			applyRuntimePlatform,
			injectBuiltinAliases,
			getDefineImportMetaEnv,
			setOptions: (next) => setOptions({
				...currentOptions,
				...next
			}),
			oxcRolldownPlugin
		}, ...backendConfigs) }, ...configs);
	}
	function mergeWebFactory(...configs) {
		ensureConfigService(ctx);
		const backend = platformBackendRegistry.get("web");
		if (!backend) throw new Error("Web 平台后端未注册。");
		const currentOptions = getOptions();
		const configService = ctx.configService;
		const subPackageRoots = Object.keys(configService.weappViteConfig?.subPackages ?? {});
		const sharedOutput = configService.options.chunksConfigured ? createSharedBuildOutput(configService, () => subPackageRoots, { runtime: "web" }) : void 0;
		return backend.driver.mergeConfig({ merge: (...backendConfigs) => mergeWeb({
			configService,
			config: currentOptions.config,
			web: currentOptions.weappWeb,
			mode: currentOptions.mode,
			isDev: currentOptions.isDev,
			applyRuntimePlatform,
			injectBuiltinAliases,
			getDefineImportMetaEnv,
			uniApp: configService.weappViteConfig.uniApp,
			autoImportResolvers: typeof configService.weappViteConfig.autoImportComponents === "object" ? configService.weappViteConfig.autoImportComponents.resolvers : void 0,
			resolveAppConfig: async () => (await ctx.scanService.loadAppEntry()).json
		}, sharedOutput ? { build: { rolldownOptions: { output: sharedOutput } } } : {}, ...backendConfigs) }, ...configs);
	}
	function mergeInlineFactory(...configs) {
		return mergeInlineConfig(getOptions().config, injectBuiltinAliases, ...configs);
	}
	return {
		mergeWorkers: mergeWorkersFactory,
		merge: mergeFactory,
		mergeWeb: mergeWebFactory,
		mergeInlineConfig: mergeInlineFactory
	};
}
//#endregion
//#region src/runtime/config/createConfigService.ts
function createConfigService(ctx) {
	const configState = ctx.runtimeState.config;
	configState.packageInfo = safeGetPackageInfoSync("weapp-vite") ?? configState.packageInfo;
	const defineEnv = configState.defineEnv;
	let packageManager = configState.packageManager;
	let options = configState.options;
	let loadingOptions;
	const oxcRuntimeSupport = createOxcRuntimeSupport();
	const aliasManager = createAliasManager(oxcRuntimeSupport.alias, resolveBuiltinPackageAliases({ cwd: options.cwd }));
	function injectBuiltinAliases(config, wevuRuntime) {
		aliasManager.injectBuiltinAliases(config, resolveBuiltinPackageAliases({
			cwd: loadingOptions?.cwd ?? options.cwd,
			isDev: loadingOptions?.isDev ?? options.isDev,
			wevuRuntime: wevuRuntime ?? config.weapp?.wevu?.runtime
		}));
	}
	const normalizeComparablePath = (input) => {
		const resolved = path.resolve(input);
		try {
			return normalizeRelativePath$1(fs.realpathSync.native(resolved));
		} catch {
			const suffixParts = [];
			let cursor = resolved;
			let parent = path.dirname(cursor);
			while (parent !== cursor && !fs.existsSync(cursor)) {
				suffixParts.unshift(path.basename(cursor));
				cursor = parent;
				parent = path.dirname(cursor);
			}
			try {
				const normalizedBase = normalizeRelativePath$1(fs.realpathSync.native(cursor));
				return suffixParts.length > 0 ? normalizeRelativePath$1(path.join(normalizedBase, ...suffixParts)) : normalizedBase;
			} catch {
				return normalizeRelativePath$1(resolved);
			}
		}
	};
	const resolveAbsolutePluginRoot = () => {
		const pluginRootConfig = options.config.weapp?.pluginRoot;
		if (!pluginRootConfig) return;
		return path.resolve(options.cwd, pluginRootConfig);
	};
	const resolvePluginSourceBase = () => {
		const absolutePluginRoot = resolveAbsolutePluginRoot();
		if (!absolutePluginRoot) return;
		return toPosixPath(path.basename(absolutePluginRoot));
	};
	const resolveAbsolutePluginOutputRoot = () => {
		const absolutePluginRoot = resolveAbsolutePluginRoot();
		if (!absolutePluginRoot) return;
		if (options.pluginOnly) return path.resolve(options.cwd, options.mpDistRoot ?? options.config.build?.outDir ?? "");
		const configured = options.projectConfig?.pluginRoot;
		if (configured) return path.resolve(options.cwd, configured);
		const outDir = path.resolve(options.cwd, options.mpDistRoot ?? "");
		const pluginBase = path.basename(absolutePluginRoot);
		return path.resolve(outDir, pluginBase);
	};
	const resolvePluginOutputBasePosix = () => {
		if (options.pluginOnly) return "";
		const absoluteOutputRoot = resolveAbsolutePluginOutputRoot();
		if (!absoluteOutputRoot) return;
		const outDir = path.resolve(options.cwd, options.mpDistRoot ?? "");
		const relativeToOutDir = path.relative(outDir, absoluteOutputRoot);
		if (!(relativeToOutDir === "" || !relativeToOutDir.startsWith("..") && !path.isAbsolute(relativeToOutDir))) return resolvePluginSourceBase();
		const normalized = normalizeRelativePath$1(relativeToOutDir);
		if (!normalized || normalized === ".") return resolvePluginSourceBase();
		return normalized;
	};
	const remapPluginRelativePath = (relativePath) => {
		const pluginBase = resolvePluginSourceBase();
		if (!pluginBase) return normalizeRelativePath$1(relativePath);
		const normalizedRelative = normalizeRelativePath$1(relativePath);
		if (normalizedRelative === pluginBase || normalizedRelative.startsWith(`${pluginBase}/`)) {
			const pluginRelative = normalizedRelative === pluginBase ? "" : normalizedRelative.slice(pluginBase.length + 1);
			const outputBase = resolvePluginOutputBasePosix() ?? pluginBase;
			return pluginRelative ? `${outputBase}/${pluginRelative}` : outputBase;
		}
		return normalizedRelative;
	};
	const resolveExternalOutputPath = (filePath) => {
		const normalizedPath = normalizeComparablePath(filePath);
		const nodeModulesIndex = normalizedPath.lastIndexOf("/node_modules/");
		if (nodeModulesIndex >= 0) {
			const packageRelative = normalizedPath.slice(nodeModulesIndex + 14);
			return normalizeRelativePath$1(path.join(WEAPP_VITE_EXTERNAL_OUTPUT_DIRECTORY, packageRelative));
		}
		const normalizedDir = path.dirname(normalizedPath);
		const dirHash = createHash("sha256").update(normalizedDir).digest("hex").slice(0, 10);
		return normalizeRelativePath$1(path.join(WEAPP_VITE_EXTERNAL_OUTPUT_DIRECTORY, dirHash, path.basename(normalizedPath)));
	};
	function setOptions(value) {
		options = value;
		configState.options = value;
	}
	const getOptions = () => options;
	function setDefineEnv(key, value) {
		defineEnv[key] = value;
	}
	function setImportMetaEnvDefineOverride(define) {
		configState.importMetaEnvDefineOverride = define ? pickImportMetaEnvDefineEntries(define) : void 0;
	}
	function getUserDefinedImportMetaEnv() {
		const userDefine = options?.config?.define;
		return pickImportMetaEnvDefineEntries(userDefine);
	}
	function getCurrentImportMetaExplicitDefine() {
		return configState.importMetaEnvDefineOverride ?? getUserDefinedImportMetaEnv();
	}
	function getImportMetaBaseEnv() {
		const miniPlatform = options?.platform ?? DEFAULT_MP_PLATFORM;
		const resolvedPlatform = defineEnv.PLATFORM ?? miniPlatform;
		return {
			PLATFORM: resolvedPlatform,
			MP_PLATFORM: resolvedPlatform,
			...defineEnv
		};
	}
	function getImportMetaDefineRegistry() {
		return createImportMetaDefineRegistry({
			baseEnv: getImportMetaBaseEnv(),
			defineEntries: getCurrentImportMetaExplicitDefine()
		});
	}
	function getDefineImportMetaEnv() {
		return getImportMetaDefineRegistry().defineEntries;
	}
	function applyRuntimePlatform(runtime) {
		const isWeb = runtime === "web";
		const miniPlatform = options?.platform ?? DEFAULT_MP_PLATFORM;
		setDefineEnv("PLATFORM", isWeb ? "web" : miniPlatform);
		setDefineEnv("IS_WEB", isWeb);
		setDefineEnv("IS_MINIPROGRAM", !isWeb);
	}
	applyRuntimePlatform("miniprogram");
	const loadConfigImpl = createLoadConfig({
		injectBuiltinAliases,
		oxcRolldownPlugin: oxcRuntimeSupport.rolldownPlugin,
		oxcVitePlugin: oxcRuntimeSupport.vitePlugin
	});
	function formatConfigDisplayPath(filePath) {
		if (!filePath) return;
		const relative = normalizeRelativePath$1(path.relative(options.cwd, filePath));
		return relative && relative !== "" ? relative : path.basename(filePath);
	}
	async function load(optionsInput) {
		const defaultCwd = process.cwd();
		const input = defu(optionsInput, {
			cwd: defaultCwd,
			isDev: false,
			mode: "development",
			emitDefaultAutoImportOutputs: true
		});
		loadingOptions = input;
		let rawConfig;
		try {
			rawConfig = await loadConfigImpl(input);
		} finally {
			loadingOptions = void 0;
		}
		const resolvedConfig = defu(rawConfig, {
			cwd: input.cwd ?? defaultCwd,
			isDev: false,
			emitDefaultAutoImportOutputs: true,
			projectConfig: {},
			projectPrivateConfig: {},
			config: {},
			loadOptions: input,
			packageJson: {},
			platform: "weapp",
			multiPlatform: resolveMultiPlatformConfig(false),
			configFilePath: void 0,
			currentSubPackageRoot: void 0,
			weappWeb: void 0,
			configFileDependencies: []
		});
		setOptions(resolvedConfig);
		configureLogger(resolvedConfig.config.weapp?.logger);
		if (resolvedConfig.configMergeInfo?.merged) {
			const weappConfigDisplay = formatConfigDisplayPath(resolvedConfig.configMergeInfo.weappConfigPath) ?? "weapp-vite.config.ts";
			const viteConfigDisplay = formatConfigDisplayPath(resolvedConfig.configMergeInfo.viteConfigPath) ?? "vite.config.ts";
			logger_default.info(`[config] 检测到同时存在 ${weappConfigDisplay} 与 ${viteConfigDisplay},已合并两份 Vite 配置,优先级:${weappConfigDisplay} > ${viteConfigDisplay}`);
		}
		packageManager = await detect() ?? {
			agent: "npm",
			name: "npm"
		};
		configState.packageManager = packageManager;
		return resolvedConfig;
	}
	const { mergeWorkers, merge, mergeWeb, mergeInlineConfig } = createMergeFactories({
		ctx,
		getOptions,
		setOptions,
		injectBuiltinAliases,
		getDefineImportMetaEnv,
		applyRuntimePlatform,
		oxcRolldownPlugin: oxcRuntimeSupport.rolldownPlugin
	});
	return {
		get options() {
			return options;
		},
		set options(value) {
			setOptions(value);
		},
		get outputExtensions() {
			return options.outputExtensions;
		},
		set outputExtensions(value) {
			setOptions({
				...options,
				outputExtensions: value
			});
		},
		defineEnv,
		get packageManager() {
			return packageManager;
		},
		get packageInfo() {
			return configState.packageInfo;
		},
		setDefineEnv,
		setImportMetaEnvDefineOverride,
		load,
		mergeWorkers,
		merge,
		mergeWeb,
		mergeInlineConfig,
		get importMetaDefineEntries() {
			return getDefineImportMetaEnv();
		},
		get defineImportMetaEnv() {
			return getDefineImportMetaEnv();
		},
		get importMetaEnvDefineOverride() {
			return configState.importMetaEnvDefineOverride;
		},
		get importMetaDefineRegistry() {
			return getImportMetaDefineRegistry();
		},
		get cwd() {
			return options.cwd;
		},
		get isDev() {
			return options.isDev;
		},
		get emitDefaultAutoImportOutputs() {
			return options.emitDefaultAutoImportOutputs;
		},
		get mpDistRoot() {
			return options.mpDistRoot;
		},
		get outDir() {
			return path.resolve(options.cwd, options.mpDistRoot ?? "");
		},
		get multiPlatform() {
			return options.multiPlatform;
		},
		get currentSubPackageRoot() {
			return options.currentSubPackageRoot;
		},
		get inlineConfig() {
			return options.config;
		},
		get loadOptions() {
			return options.loadOptions;
		},
		get weappViteConfig() {
			return options.config.weapp;
		},
		get packageJson() {
			return options.packageJson;
		},
		get projectConfig() {
			return options.projectConfig;
		},
		get projectPrivateConfig() {
			return options.projectPrivateConfig;
		},
		get projectConfigPath() {
			return options.projectConfigPath;
		},
		get projectPrivateConfigPath() {
			return options.projectPrivateConfigPath;
		},
		get srcRoot() {
			return options.srcRoot;
		},
		get pluginOnly() {
			return options.pluginOnly === true;
		},
		get pluginRoot() {
			return options.config.weapp?.pluginRoot;
		},
		get absolutePluginRoot() {
			return resolveAbsolutePluginRoot();
		},
		get absolutePluginOutputRoot() {
			return resolveAbsolutePluginOutputRoot();
		},
		get absoluteSrcRoot() {
			return path.resolve(options.cwd, options.srcRoot);
		},
		get mode() {
			return options.mode;
		},
		get aliasEntries() {
			return options.aliasEntries;
		},
		get platform() {
			return options.platform;
		},
		get configFilePath() {
			return options.configFilePath;
		},
		get configFileDependencies() {
			return options.configFileDependencies;
		},
		get weappWebConfig() {
			return options.weappWeb;
		},
		get weappLibConfig() {
			return options.weappLib;
		},
		get weappLibOutputMap() {
			return options.weappLibOutputMap;
		},
		relativeCwd(p) {
			return normalizeRelativePath$1(path.relative(options.cwd, p));
		},
		relativeSrcRoot(p) {
			return options.relativeSrcRoot(p);
		},
		relativeAbsoluteSrcRoot(p) {
			const absoluteSrcRoot = path.resolve(options.cwd, options.srcRoot);
			const comparableTarget = normalizeComparablePath(p);
			const comparableSrcRoot = normalizeComparablePath(absoluteSrcRoot);
			const absolutePluginRoot = resolveAbsolutePluginRoot();
			if (absolutePluginRoot) {
				const relativeToPlugin = normalizeRelativePath$1(path.relative(normalizeComparablePath(absolutePluginRoot), comparableTarget));
				if (!relativeToPlugin.startsWith("..")) {
					if (options.pluginOnly) return relativeToPlugin;
					const posixBase = toPosixPath(path.basename(absolutePluginRoot));
					return relativeToPlugin ? `${posixBase}/${relativeToPlugin}` : posixBase;
				}
			}
			const relativeFromSrc = normalizeRelativePath$1(path.relative(comparableSrcRoot, comparableTarget));
			if (!relativeFromSrc.startsWith("..")) return relativeFromSrc;
			return normalizeRelativePath$1(path.relative(normalizeComparablePath(options.cwd), comparableTarget));
		},
		relativeOutputPath(p) {
			const relative = this.relativeAbsoluteSrcRoot(p);
			if (!relative) return relative;
			if (relative.startsWith("..") || relative === "node_modules" || relative.startsWith("node_modules/")) return resolveExternalOutputPath(p);
			const libOutputMap = options.weappLibOutputMap;
			if (libOutputMap && libOutputMap.size > 0) {
				const base = normalizeRelativePath$1(removeExtensionDeep(relative));
				const mapped = libOutputMap.get(base);
				if (mapped) {
					const ext = path.extname(relative);
					const fileName = ext ? `${mapped}${ext}` : mapped;
					return remapPluginRelativePath(fileName);
				}
			}
			return remapPluginRelativePath(relative);
		}
	};
}
//#endregion
//#region src/runtime/configPlugin.ts
function createConfigServicePlugin(ctx) {
	ctx.configService = createConfigService(ctx);
	return { name: "weapp-runtime:config-service" };
}
//#endregion
//#region src/runtime/jsonPlugin.ts
const APP_CONFIG_RE = /(?:^|[/\\])app\.json(?:\.[jt]s)?$/;
const SCRIPT_JSON_CONFIG_RE = /\.json\.[jt]s$/;
function createJsonService(ctx) {
	const cache = ctx.runtimeState.json.cache;
	async function read(filepath) {
		const configService = requireConfigService(ctx, "读取 JSON 前必须初始化 configService。");
		try {
			const isAppConfig = APP_CONFIG_RE.test(filepath);
			let autoRoutesSignature;
			if (isAppConfig && !ctx.runtimeState.autoRoutes.loadingAppConfig) {
				await ctx.autoRoutesService?.ensureFresh();
				autoRoutesSignature = ctx.autoRoutesService?.getSignature?.();
			}
			if (!await cache.isInvalidate(filepath, typeof autoRoutesSignature === "string" ? { signature: autoRoutesSignature } : void 0)) {
				const cached = cache.get(filepath);
				if (cached !== void 0) return cached;
			}
			let resultJson;
			if (SCRIPT_JSON_CONFIG_RE.test(filepath)) {
				const fallbackRoutes = ctx.autoRoutesService?.getReference() ?? {
					pages: [],
					entries: [],
					subPackages: []
				};
				const scriptContent = await fs$1.readFile(filepath, "utf8");
				const inlinedContent = isAppConfig ? inlineAutoRoutesImports(scriptContent, fallbackRoutes) : scriptContent;
				const { mod } = await bundleRequire({
					filepath,
					cwd: configService.options.cwd,
					preserveTemporaryFile: true,
					...inlinedContent === scriptContent ? {} : { source: inlinedContent },
					rolldownOptions: {
						input: { define: configService.importMetaDefineEntries },
						output: { exports: "named" }
					}
				});
				const exportedConfig = hasOwn$5(mod, "default") ? mod.default : mod;
				resultJson = typeof exportedConfig === "function" ? await exportedConfig(ctx) : exportedConfig;
			} else resultJson = parseCommentJson(await fs$1.readFile(filepath, "utf8"));
			if (isAppConfig) resultJson = normalizeAppJson(resultJson);
			cache.set(filepath, resultJson);
			return resultJson;
		} catch (error) {
			logger_default.error(`残破的 JSON 文件:${filepath}`);
			debug$2?.(error);
		}
	}
	function resolve(entry) {
		const configService = requireConfigService(ctx, "解析 JSON 前必须初始化 configService。");
		return resolveJson(entry, configService.aliasEntries, configService.platform, {
			dependencies: configService.packageJson.dependencies,
			alipayNpmMode: configService.weappViteConfig?.npm?.alipayNpmMode
		});
	}
	return {
		cache,
		read,
		resolve
	};
}
function createJsonServicePlugin(ctx) {
	ctx.jsonService = createJsonService(ctx);
	return { name: "weapp-runtime:json-service" };
}
//#endregion
//#region src/runtime/npmPlugin/index.ts
function createNpmServicePlugin(ctx) {
	ctx.npmService = createNpmService(ctx);
	return { name: "weapp-runtime:npm-service" };
}
//#endregion
//#region src/runtime/scanPlugin/service/shared.ts
function createWarnOnce(warnedMessages) {
	return function warnOnce(message) {
		if (warnedMessages.has(message)) return;
		warnedMessages.add(message);
		logger_default.warn(message);
	};
}
function mergeAutoRoutePages(pages, routePages) {
	if (routePages.length === 0) return pages;
	const existingPages = Array.isArray(pages) ? pages.filter((page) => typeof page === "string" && page.length > 0) : [];
	const existingSet = new Set(existingPages);
	if (routePages.every((page) => existingSet.has(page))) return existingPages;
	return [...routePages, ...existingPages.filter((page) => !routePages.includes(page))];
}
function isMainPackageFileName(fileName, independentSubPackageMap) {
	const normalizedFileName = toPosixPath(fileName);
	return [...independentSubPackageMap.keys()].every((root) => {
		return !normalizedFileName.startsWith(root);
	});
}
function markIndependentDirty(root, independentSubPackageMap, independentDirtyRoots) {
	if (!root) return;
	const normalizedRoot = normalizeRoot(root);
	if (independentSubPackageMap.has(normalizedRoot)) independentDirtyRoots.add(normalizedRoot);
}
function drainIndependentDirtyRoots(independentDirtyRoots) {
	const roots = [...independentDirtyRoots];
	independentDirtyRoots.clear();
	return roots;
}
//#endregion
//#region src/runtime/scanPlugin/service/app.ts
function resolveScanAppBasename(absoluteSrcRoot) {
	return path.resolve(absoluteSrcRoot, "app");
}
function resolveScanAppPreludeBasename(absoluteSrcRoot) {
	return path.resolve(absoluteSrcRoot, "app.prelude");
}
async function resolveScanAppPreludePath(absoluteSrcRoot) {
	const basename = resolveScanAppPreludeBasename(absoluteSrcRoot);
	return (await findJsEntry(basename)).path;
}
function resolveScanPluginBasename(absolutePluginRoot) {
	return absolutePluginRoot ? path.resolve(absolutePluginRoot, "plugin") : void 0;
}
function resolveScanJsonEntryBasename(appDirname, location, fallbackName) {
	const value = typeof location === "string" ? location : void 0;
	if (value === "") return;
	return path.resolve(appDirname, value || fallbackName);
}
async function resolveOptionalAppSideJson(ctx, basename) {
	if (!basename) return {};
	const { path: jsonPath } = await findJsonEntry(basename);
	if (!jsonPath) return {};
	return {
		jsonPath,
		json: await ctx.jsonService.read(jsonPath)
	};
}
function mergeAutoRouteSubPackages(subPackages, routeSubPackages) {
	if (routeSubPackages.length === 0) return subPackages;
	const merged = /* @__PURE__ */ new Map();
	const anonymousEntries = [];
	const existingEntries = Array.isArray(subPackages) ? subPackages : [];
	for (const entry of existingEntries) {
		if (!entry?.root) {
			anonymousEntries.push(entry);
			continue;
		}
		merged.set(entry.root, {
			...entry,
			pages: Array.isArray(entry.pages) ? [...entry.pages] : []
		});
	}
	let changed = false;
	for (const routeSubPackage of routeSubPackages) {
		const existingEntry = merged.get(routeSubPackage.root);
		if (!existingEntry) {
			merged.set(routeSubPackage.root, {
				root: routeSubPackage.root,
				pages: [...routeSubPackage.pages]
			});
			changed = true;
			continue;
		}
		const existingPages = Array.isArray(existingEntry.pages) ? existingEntry.pages : [];
		const existingPageSet = new Set(existingPages);
		if (routeSubPackage.pages.every((page) => existingPageSet.has(page))) continue;
		existingEntry.pages = [...routeSubPackage.pages, ...existingPages.filter((page) => !routeSubPackage.pages.includes(page))];
		changed = true;
	}
	if (!changed && anonymousEntries.length === 0) return existingEntries;
	return [...merged.values(), ...anonymousEntries];
}
function normalizeAppConfigSubPackages(config) {
	const normalized = normalizeAppJson(config);
	if (!isObject(normalized)) return config;
	for (const key of Object.keys(config)) delete config[key];
	Object.assign(config, normalized);
	return config;
}
async function applyAutoRoutesToAppConfigIfNeeded(ctx, config) {
	const autoRoutesService = ctx.autoRoutesService;
	if (!autoRoutesService?.isEnabled()) return config;
	if (ctx.runtimeState.autoRoutes.loadingAppConfig) return config;
	ctx.runtimeState.autoRoutes.loadingAppConfig = true;
	try {
		await autoRoutesService.ensureFresh();
	} finally {
		ctx.runtimeState.autoRoutes.loadingAppConfig = false;
	}
	const routes = autoRoutesService.getReference();
	config.pages = mergeAutoRoutePages(config.pages, routes.pages) ?? [];
	const mergedSubPackages = mergeAutoRouteSubPackages(config.subPackages ?? config.subpackages, routes.subPackages.map((subPackage) => ({
		root: subPackage.root,
		pages: [...subPackage.pages]
	})));
	if (mergedSubPackages) config.subPackages = mergedSubPackages.map((subPackage) => ({
		...subPackage,
		pages: Array.isArray(subPackage.pages) ? subPackage.pages : []
	}));
	return normalizeAppConfigSubPackages(config);
}
async function loadAppEntry(ctx, scanState) {
	if (!ctx.configService || !ctx.jsonService) throw new Error("扫描入口前必须初始化 configService/jsonService。");
	if (scanState.appEntry && !scanState.isDirty) return scanState.appEntry;
	const warnOnce = createWarnOnce(scanState.warnedMessages);
	const appDirname = ctx.configService.absoluteSrcRoot;
	const appBasename = resolveScanAppBasename(appDirname);
	const [appConfigEntry, appEntry, appPreludePath, vueAppPath] = await Promise.all([
		findJsonEntry(appBasename),
		findJsEntry(appBasename),
		resolveScanAppPreludePath(appDirname),
		findVueEntry(appBasename)
	]);
	let { path: appConfigFile } = appConfigEntry;
	const discoveredAppConfigFile = appConfigFile;
	const { path: appEntryPath } = appEntry;
	let configFromVue;
	if (!appConfigFile && vueAppPath) {
		const { extractConfigFromVue } = await import("./file-pxD6pTOO.mjs");
		configFromVue = await extractConfigFromVue(vueAppPath);
		if (configFromVue) appConfigFile = vueAppPath;
	}
	if (appEntryPath && vueAppPath) warnOnce(`[app] 检测到 ${path.basename(appEntryPath)} 与 ${path.basename(vueAppPath)} 同时存在,当前将优先使用 ${path.basename(appEntryPath)} 作为应用入口,${path.basename(vueAppPath)} 将被忽略。`);
	if (discoveredAppConfigFile && vueAppPath) warnOnce(`[app] 检测到 ${path.basename(discoveredAppConfigFile)} 与 ${path.basename(vueAppPath)} 同时存在,当前将优先使用 ${path.basename(discoveredAppConfigFile)} 作为应用配置来源,${path.basename(vueAppPath)} 中的 app 配置不会生效。`);
	if (ctx.configService.absolutePluginRoot) {
		const pluginBasename = resolveScanPluginBasename(ctx.configService.absolutePluginRoot);
		const { path: pluginConfigFile } = await findJsonEntry(pluginBasename);
		if (pluginConfigFile) {
			scanState.pluginJson = await ctx.jsonService.read(pluginConfigFile);
			scanState.pluginJsonPath = pluginConfigFile;
		} else {
			scanState.pluginJson = void 0;
			scanState.pluginJsonPath = void 0;
		}
	}
	if ((appEntryPath || vueAppPath) && appConfigFile) {
		let config;
		if (configFromVue) config = configFromVue;
		else config = await ctx.jsonService.read(appConfigFile);
		await applyAutoRoutesToAppConfigIfNeeded(ctx, config);
		config = finalizeAppConfigForBuild(config, {
			buildScope: ctx.configService.weappViteConfig.buildScope,
			platform: ctx.configService.platform,
			routeRules: ctx.configService.weappViteConfig.routeRules
		});
		if (isObject(config)) {
			const resolvedAppEntry = {
				path: appEntryPath || vueAppPath,
				preludePath: appPreludePath,
				json: config,
				jsonPath: appConfigFile,
				type: "app"
			};
			scanState.appEntry = resolvedAppEntry;
			const sitemapBasename = resolveScanJsonEntryBasename(appDirname, config.sitemapLocation, "sitemap.json");
			const themeBasename = resolveScanJsonEntryBasename(appDirname, config.themeLocation, "theme.json");
			const [sitemapEntry, themeEntry] = await Promise.all([resolveOptionalAppSideJson(ctx, sitemapBasename), resolveOptionalAppSideJson(ctx, themeBasename)]);
			if (sitemapEntry.jsonPath) {
				resolvedAppEntry.sitemapJsonPath = sitemapEntry.jsonPath;
				resolvedAppEntry.sitemapJson = sitemapEntry.json;
			}
			if (themeEntry.jsonPath) {
				resolvedAppEntry.themeJsonPath = themeEntry.jsonPath;
				resolvedAppEntry.themeJson = themeEntry.json;
			}
			scanState.appEntry = resolvedAppEntry;
			return resolvedAppEntry;
		}
		throw new Error("`app.json` 解析失败,请确保 `app.json` 文件格式正确");
	}
	throw new Error(`在 ${appDirname} 目录下没有找到 \`app.json\`、\`app.json.ts\` 或 \`app.vue\`,请确保你初始化了小程序项目,或者在 \`vite.config.ts\` / \`weapp-vite.config.ts\` 中设置正确的 \`weapp.srcRoot\` 配置路径`);
}
//#endregion
//#region src/runtime/scanPlugin/styleEntries/config.ts
const SUPPORTED_SHARED_STYLE_EXTENSIONS = [
	".wxss",
	".css",
	".scss",
	".sass",
	".less",
	".styl",
	".stylus",
	".pcss",
	".postcss",
	".sss"
];
const SUPPORTED_SHARED_STYLE_EXTS = new Set(SUPPORTED_SHARED_STYLE_EXTENSIONS);
const DEFAULT_SCOPE_INCLUDES = {
	all: ["**/*"],
	pages: ["pages/**"],
	components: ["components/**"]
};
const DEFAULT_SCOPED_FILES = [
	{
		base: "index",
		scope: "all"
	},
	{
		base: "pages",
		scope: "pages"
	},
	{
		base: "components",
		scope: "components"
	}
];
const DEFAULT_SCOPED_EXTENSIONS = Array.from(SUPPORTED_SHARED_STYLE_EXTS);
function coerceScope(scope) {
	const value = typeof scope === "string" ? scope.trim() : "";
	if (value === "pages" || value === "components") return value;
	if (value && value !== "all") logger_default.warn(`[分包] 未识别的样式作用域 \`${value}\`,已按 \`all\` 处理。`);
	return "all";
}
function coerceStyleConfig(entry) {
	if (typeof entry === "string") {
		const source = entry.trim();
		if (!source) return;
		return {
			source,
			scope: "all",
			inject: true,
			explicitScope: false
		};
	}
	if (!entry || typeof entry !== "object") return;
	const source = entry.source?.toString().trim();
	if (!source) return;
	const hasExplicitScope = hasOwn$5(entry, "scope") && entry.scope != null;
	return {
		source,
		scope: hasExplicitScope ? coerceScope(entry.scope) : "all",
		include: entry.include,
		exclude: entry.exclude,
		inject: entry.inject !== false,
		explicitScope: hasExplicitScope
	};
}
//#endregion
//#region src/runtime/scanPlugin/styleEntries/patterns.ts
const LEADING_SLASH_RE = /^\/+/;
function toArray(value) {
	if (value === void 0) return [];
	return Array.isArray(value) ? value : [value];
}
function normalizePattern(pattern, normalizedRoot) {
	const trimmed = pattern.trim();
	if (!trimmed) return;
	let normalized = toPosixPath(trimmed);
	if (normalizedRoot && normalized.startsWith(`${normalizedRoot}/`)) normalized = normalized.slice(normalizedRoot.length + 1);
	if (normalized.startsWith("./")) normalized = normalized.slice(2);
	normalized = normalized.replace(LEADING_SLASH_RE, "");
	if (!normalized) return "**/*";
	if (normalized.endsWith("/")) normalized = `${normalized}**`;
	return normalized;
}
function resolveIncludePatterns(descriptor, normalizedRoot) {
	const normalized = /* @__PURE__ */ new Set();
	for (const pattern of toArray(descriptor.include)) {
		const resolved = normalizePattern(pattern, normalizedRoot);
		if (resolved) normalized.add(resolved);
	}
	if (!normalized.size) {
		const defaults = DEFAULT_SCOPE_INCLUDES[descriptor.scope] ?? DEFAULT_SCOPE_INCLUDES.all;
		for (const pattern of defaults) {
			const resolved = normalizePattern(pattern, normalizedRoot);
			if (resolved) normalized.add(resolved);
		}
	}
	return Array.from(normalized);
}
function resolveExcludePatterns(descriptor, normalizedRoot) {
	const normalized = /* @__PURE__ */ new Set();
	for (const pattern of toArray(descriptor.exclude)) {
		const resolved = normalizePattern(pattern, normalizedRoot);
		if (resolved) normalized.add(resolved);
	}
	return Array.from(normalized);
}
//#endregion
//#region src/runtime/scanPlugin/styleEntries/entries.ts
function createStyleEntryDedupeKey(posixOutput, include, exclude, inject) {
	return JSON.stringify({
		file: posixOutput,
		include,
		exclude,
		inject
	});
}
function resolveDefaultScopedStyleEntryCandidates(absoluteSrcRoot, root) {
	const absoluteSubRoot = path.resolve(absoluteSrcRoot, root);
	return DEFAULT_SCOPED_FILES.flatMap(({ base, scope }) => DEFAULT_SCOPED_EXTENSIONS.map((ext) => ({
		base,
		scope,
		filename: `${base}${ext}`,
		absolutePath: path.resolve(absoluteSubRoot, `${base}${ext}`)
	})));
}
function addStyleEntry(descriptor, absolutePath, posixOutput, normalizedRoot, warningPrefix, dedupe, normalized) {
	const include = resolveIncludePatterns({
		scope: descriptor.scope,
		include: descriptor.include
	}, normalizedRoot);
	const exclude = resolveExcludePatterns({ exclude: descriptor.exclude }, normalizedRoot);
	include.sort();
	exclude.sort();
	if (!include.length) {
		logger_default.warn(`${warningPrefix}样式入口 \`${descriptor.source}\` 缺少有效作用范围,已按 \`**/*\` 处理。`);
		include.push("**/*");
	}
	const key = createStyleEntryDedupeKey(posixOutput, include, exclude, descriptor.inject);
	if (dedupe.has(key)) return;
	dedupe.add(key);
	normalized.push({
		source: descriptor.source,
		absolutePath,
		outputRelativePath: posixOutput,
		inputExtension: path.extname(absolutePath).toLowerCase(),
		scope: descriptor.scope,
		include,
		exclude,
		inject: descriptor.inject
	});
}
function appendDefaultScopedStyleEntries(root, normalizedRoot, service, dedupe, normalized) {
	let previousBase = "";
	let matchedCurrentBase = false;
	for (const candidate of resolveDefaultScopedStyleEntryCandidates(service.absoluteSrcRoot, root)) {
		if (candidate.base !== previousBase) {
			previousBase = candidate.base;
			matchedCurrentBase = false;
		}
		if (matchedCurrentBase || !fs.existsSync(candidate.absolutePath)) continue;
		const descriptor = {
			source: candidate.filename,
			scope: candidate.scope,
			include: void 0,
			exclude: void 0,
			inject: true,
			explicitScope: true
		};
		const outputAbsolutePath = changeFileExtension(candidate.absolutePath, service.outputExtensions.wxss);
		const outputRelativePath = service.relativeOutputPath(outputAbsolutePath);
		if (!outputRelativePath) continue;
		const posixOutput = toPosixPath(outputRelativePath);
		addStyleEntry(descriptor, candidate.absolutePath, posixOutput, normalizedRoot, `[分包] 分包 ${root} `, dedupe, normalized);
		matchedCurrentBase = true;
	}
}
//#endregion
//#region src/runtime/scanPlugin/styleEntries/resolve.ts
const LEADING_DOT_SLASH_RE = /^\.\//;
function isSubPackageRelativeStyleEntry(normalizedEntry, normalizedRoot) {
	return normalizedEntry === normalizedRoot || normalizedEntry.startsWith(`${normalizedRoot}/`);
}
function resolveStyleEntryCandidates(source, subPackageRoot, absoluteSrcRoot) {
	const trimmed = source.trim();
	if (!trimmed) return [];
	const absoluteSubRoot = path.resolve(absoluteSrcRoot, subPackageRoot);
	const normalizedEntry = toPosixPath(trimmed);
	const normalizedRoot = toPosixPath(subPackageRoot);
	if (path.isAbsolute(trimmed)) return [trimmed];
	if (isSubPackageRelativeStyleEntry(normalizedEntry, normalizedRoot)) return [path.resolve(absoluteSrcRoot, trimmed)];
	return [path.resolve(absoluteSubRoot, trimmed), path.resolve(absoluteSrcRoot, trimmed)];
}
function resolveStyleEntryAbsolutePath(source, subPackageRoot, configService) {
	const service = configService;
	if (!service) return;
	const trimmed = source.trim();
	if (!trimmed) return;
	const srcRoot = service.absoluteSrcRoot;
	const candidates = resolveStyleEntryCandidates(trimmed, subPackageRoot, srcRoot);
	for (const candidate of candidates) if (isPathInside(srcRoot, candidate)) return candidate;
}
function getRelativePathWithinSubPackage(pathname, normalizedRoot) {
	if (!normalizedRoot) return pathname;
	if (pathname === normalizedRoot) return "";
	if (pathname.startsWith(`${normalizedRoot}/`)) return pathname.slice(normalizedRoot.length + 1);
	return pathname;
}
function inferScopeFromRelativePath(relativePath) {
	if (!relativePath) return;
	const cleaned = relativePath.replace(LEADING_DOT_SLASH_RE, "");
	if (cleaned.includes("/")) return;
	const base = path.posix.basename(cleaned, path.posix.extname(cleaned));
	if (base === "pages") return "pages";
	if (base === "components") return "components";
	if (base === "index") return "all";
}
//#endregion
//#region src/runtime/scanPlugin/styleEntries/index.ts
function hasExplicitIncludePattern(include, normalizedRoot) {
	return (include === void 0 ? [] : Array.isArray(include) ? include : [include]).some((pattern) => normalizePattern(pattern, normalizedRoot) !== void 0);
}
function appendExcludePattern(exclude, pattern) {
	if (exclude === void 0) return [pattern];
	return Array.isArray(exclude) ? [...exclude, pattern] : [exclude, pattern];
}
function isSupportedSharedStyleExtension(absolutePath) {
	return SUPPORTED_SHARED_STYLE_EXTS.has(path.extname(absolutePath).toLowerCase());
}
function resolveStyleEntryScope(descriptor, posixOutput, normalizedRoot) {
	if (descriptor.explicitScope) return descriptor.scope;
	return inferScopeFromRelativePath(getRelativePathWithinSubPackage(posixOutput, normalizedRoot)) ?? descriptor.scope;
}
function normalizeStyleEntries(styles, root, configService, options) {
	const service = configService;
	if (!service) return;
	const list = styles === void 0 ? [] : Array.isArray(styles) ? styles : [styles];
	const normalizedRoot = normalizeRoot(root);
	const normalized = [];
	const dedupe = /* @__PURE__ */ new Set();
	for (const entry of list) {
		const descriptor = coerceStyleConfig(entry);
		if (!descriptor) {
			logger_default.warn(`${options.warningPrefix}样式入口配置无效,已忽略。`);
			continue;
		}
		const absolutePath = resolveStyleEntryAbsolutePath(descriptor.source, root, service);
		if (!absolutePath) {
			logger_default.warn(`${options.warningPrefix}样式入口 \`${descriptor.source}\` 解析失败,已忽略。`);
			continue;
		}
		if (!fs.existsSync(absolutePath)) {
			logger_default.warn(`${options.warningPrefix}样式入口 \`${descriptor.source}\` 对应文件不存在,已忽略。`);
			continue;
		}
		if (!isSupportedSharedStyleExtension(absolutePath)) {
			logger_default.warn(`${options.warningPrefix}样式入口 \`${descriptor.source}\` 当前仅支持以下格式:${SUPPORTED_SHARED_STYLE_EXTENSIONS.join(", ")},已忽略。`);
			continue;
		}
		const outputAbsolutePath = changeFileExtension(absolutePath, service.outputExtensions.wxss);
		const outputRelativePath = service.relativeOutputPath(outputAbsolutePath);
		if (!outputRelativePath) {
			logger_default.warn(`${options.warningPrefix}样式入口 \`${descriptor.source}\` 不在项目源码目录内,已忽略。`);
			continue;
		}
		const posixOutput = toPosixPath(outputRelativePath);
		addStyleEntry({
			...descriptor,
			exclude: options.excludeRootAppByDefault && !hasExplicitIncludePattern(descriptor.include, normalizedRoot) ? appendExcludePattern(descriptor.exclude, "app.*") : descriptor.exclude,
			scope: resolveStyleEntryScope(descriptor, posixOutput, normalizedRoot)
		}, absolutePath, posixOutput, normalizedRoot, options.warningPrefix, dedupe, normalized);
	}
	if (options.appendDefaultEntries) appendDefaultScopedStyleEntries(root, normalizedRoot, service, dedupe, normalized);
	return normalized.length ? normalized : void 0;
}
function normalizeSubPackageStyleEntries(styles, subPackage, configService) {
	const root = subPackage.root?.trim();
	if (!root) return;
	return normalizeStyleEntries(styles, root, configService, {
		warningPrefix: `[分包] 分包 ${root} `,
		appendDefaultEntries: true,
		excludeRootAppByDefault: false
	});
}
function normalizeMainPackageStyleEntries(styles, configService) {
	if (styles === void 0) return;
	return normalizeStyleEntries(styles, "", configService, {
		warningPrefix: "[样式] 主包 ",
		appendDefaultEntries: false,
		excludeRootAppByDefault: true
	});
}
//#endregion
//#region src/runtime/scanPlugin/subpackages.ts
function resolveSubPackageEntries(subPackage) {
	const entries = /* @__PURE__ */ new Set();
	const root = subPackage.root ?? "";
	if (Array.isArray(subPackage.pages)) for (const page of subPackage.pages) entries.add(`${root}/${page}`);
	if (subPackage.entry) entries.add(`${root}/${removeExtensionDeep(subPackage.entry)}`);
	for (const entry of collectPluginExportEntries(subPackage.plugins, root)) entries.add(entry);
	return [...entries];
}
//#endregion
//#region src/runtime/scanPlugin/service/subPackages.ts
function loadSubPackages(ctx) {
	const scanState = ctx.runtimeState.scan;
	const { subPackageMap, independentSubPackageMap, independentDirtyRoots } = scanState;
	const configService = requireConfigService(ctx, "扫描分包前必须初始化 configService。");
	const json = scanState.appEntry?.json;
	if (scanState.isDirty || subPackageMap.size === 0) {
		subPackageMap.clear();
		independentSubPackageMap.clear();
		scanState.mainPackageStyleEntries = normalizeMainPackageStyleEntries(configService.weappViteConfig?.styles, configService);
		if (scanState.isDirty) independentDirtyRoots.clear();
		if (json) {
			const independentSubPackages = [...json.subPackages ?? [], ...json.subpackages ?? []];
			for (const subPackage of independentSubPackages) {
				const normalizedRoot = subPackage.root ? normalizeRoot(subPackage.root) : void 0;
				const subPackageConfig = normalizedRoot ? configService.weappViteConfig?.subPackages?.[normalizedRoot] : void 0;
				const npmSubPackageConfig = normalizedRoot ? configService.weappViteConfig?.npm?.subPackages?.[normalizedRoot] : void 0;
				const independent = subPackage.independent ?? subPackageConfig?.independent;
				const resolvedSubPackage = {
					...subPackage,
					...normalizedRoot ? { root: normalizedRoot } : {},
					...independent === void 0 ? {} : { independent },
					dependencies: npmSubPackageConfig?.dependencies,
					inlineConfig: subPackageConfig?.inlineConfig
				};
				const meta = {
					subPackage: resolvedSubPackage,
					entries: resolveSubPackageEntries(resolvedSubPackage)
				};
				meta.autoImportComponents = subPackageConfig?.autoImportComponents;
				meta.styleEntries = normalizeSubPackageStyleEntries(subPackageConfig?.styles, resolvedSubPackage, configService);
				meta.watchSharedStyles = subPackageConfig?.watchSharedStyles ?? true;
				if (normalizedRoot) {
					subPackageMap.set(normalizedRoot, meta);
					if (resolvedSubPackage.independent) {
						independentSubPackageMap.set(normalizedRoot, meta);
						if (scanState.isDirty) independentDirtyRoots.add(normalizedRoot);
					}
				}
			}
		}
		scanState.isDirty = false;
	}
	if (scanState.appEntry) return [...subPackageMap.values()];
	throw new Error(`在 ${configService.absoluteSrcRoot} 目录下没有找到 \`app.json\`、\`app.json.ts\` 或 \`app.vue\`,请确保你初始化了小程序项目,或者在 \`vite.config.ts\` / \`weapp-vite.config.ts\` 中设置正确的 \`weapp.srcRoot\` 配置路径`);
}
//#endregion
//#region src/runtime/scanPlugin/service/index.ts
function createScanService(ctx) {
	const scanState = ctx.runtimeState.scan;
	const { subPackageMap, independentSubPackageMap, independentDirtyRoots } = scanState;
	return {
		get appEntry() {
			return scanState.appEntry;
		},
		set appEntry(value) {
			scanState.appEntry = value;
		},
		get pluginJson() {
			return scanState.pluginJson;
		},
		set pluginJson(value) {
			scanState.pluginJson = value;
		},
		get pluginJsonPath() {
			return scanState.pluginJsonPath;
		},
		set pluginJsonPath(value) {
			scanState.pluginJsonPath = value;
		},
		get mainPackageStyleEntries() {
			return scanState.mainPackageStyleEntries;
		},
		subPackageMap,
		independentSubPackageMap,
		async loadAppEntry() {
			return await loadAppEntry(ctx, scanState);
		},
		loadSubPackages() {
			return loadSubPackages(ctx);
		},
		isMainPackageFileName(fileName) {
			return isMainPackageFileName(fileName, independentSubPackageMap);
		},
		get workersOptions() {
			return scanState.appEntry?.json?.workers;
		},
		get workersDir() {
			const workersOptions = scanState.appEntry?.json?.workers;
			return typeof workersOptions === "object" ? workersOptions?.path : workersOptions;
		},
		markDirty() {
			scanState.isDirty = true;
			scanState.appEntry = void 0;
			scanState.mainPackageStyleEntries = void 0;
			scanState.pluginJson = void 0;
			scanState.pluginJsonPath = void 0;
		},
		markIndependentDirty(root) {
			markIndependentDirty(root, independentSubPackageMap, independentDirtyRoots);
		},
		drainIndependentDirtyRoots() {
			return drainIndependentDirtyRoots(independentDirtyRoots);
		}
	};
}
//#endregion
//#region src/runtime/scanPlugin/index.ts
function createScanServicePlugin(ctx) {
	const service = createScanService(ctx);
	ctx.scanService = service;
	return {
		name: "weapp-runtime:scan-service",
		async buildStart() {
			if (ctx.configService?.weappLibConfig?.enabled) return;
			await service.loadAppEntry();
			service.loadSubPackages();
		}
	};
}
//#endregion
//#region src/runtime/watcherPlugin.ts
function createWatcherService(ctx) {
	const { rollupWatcherMap, sidecarWatcherMap } = ctx.runtimeState.watcher;
	return {
		rollupWatcherMap,
		sidecarWatcherMap,
		getRollupWatcher(root = "/") {
			return rollupWatcherMap.get(root);
		},
		setRollupWatcher(watcher, root = "/") {
			rollupWatcherMap.get(root)?.close();
			rollupWatcherMap.set(root, watcher);
		},
		closeAll() {
			rollupWatcherMap.forEach((watcher) => {
				watcher.close();
			});
			rollupWatcherMap.clear();
			sidecarWatcherMap.forEach((watcher) => {
				Promise.resolve(watcher.close()).catch(() => {});
			});
			sidecarWatcherMap.clear();
			ctx.webService?.close().catch(() => {});
		},
		close(root = "/") {
			const watcher = rollupWatcherMap.get(root);
			if (watcher) {
				watcher.close();
				rollupWatcherMap.delete(root);
			}
			const sidecarWatcher = sidecarWatcherMap.get(root);
			if (sidecarWatcher) {
				Promise.resolve(sidecarWatcher.close()).catch(() => {});
				sidecarWatcherMap.delete(root);
			}
			if (rollupWatcherMap.size === 0 && sidecarWatcherMap.size === 0) ctx.webService?.close().catch(() => {});
		}
	};
}
function createWatcherServicePlugin(ctx) {
	const service = createWatcherService(ctx);
	ctx.watcherService = service;
	return {
		name: "weapp-runtime:watcher-service",
		closeBundle() {
			const configService = ctx.configService;
			if (!(configService?.isDev || Boolean(configService?.inlineConfig?.build?.watch))) service.closeAll();
		}
	};
}
//#endregion
//#region src/runtime/webPlugin.ts
function createWebService(ctx) {
	const configService = requireConfigService(ctx, "启动 Web 服务前必须初始化 configService。");
	let devServer;
	function isEnabled() {
		return Boolean(configService.weappWebConfig?.enabled);
	}
	async function startDevServer() {
		if (!configService.isDev) return;
		if (!isEnabled()) return;
		if (devServer) return devServer;
		const inlineConfig = configService.mergeWeb();
		if (!inlineConfig) return;
		const server = await createServer(inlineConfig);
		const requestedPort = typeof inlineConfig.server?.port === "number" ? inlineConfig.server.port : void 0;
		await server.listen(requestedPort);
		devServer = server;
		return devServer;
	}
	async function buildWeb() {
		if (!isEnabled()) return;
		const inlineConfig = configService.mergeWeb();
		if (!inlineConfig) return;
		return await build(inlineConfig);
	}
	async function close() {
		if (!devServer) return;
		const server = devServer;
		devServer = void 0;
		await server.close();
	}
	return {
		get devServer() {
			return devServer;
		},
		isEnabled,
		startDevServer,
		build: buildWeb,
		close
	};
}
function createWebServicePlugin(ctx) {
	const service = createWebService(ctx);
	ctx.webService = service;
	return {
		name: "weapp-runtime:web-service",
		async closeBundle() {
			if (!ctx.configService?.isDev) await service.close();
		}
	};
}
//#endregion
//#region src/runtime/wxmlPlugin/service/clear.ts
function createClearAll(state, unlinkImporter) {
	return function clearAll(options) {
		const clearEmittedCode = options?.clearEmittedCode !== false;
		const currentRoot = state.ctx.configService?.currentSubPackageRoot;
		if (!currentRoot) {
			state.depsMap.clear();
			state.importerMap.clear();
			state.depKindMap.clear();
			state.tokenMap.clear();
			state.componentsMap.clear();
			state.aggregatedComponentsMap.clear();
			state.autoImportComponentsMap.clear();
			state.aggregatedAutoImportComponentsMap.clear();
			state.templatePathMap.clear();
			state.cache.cache.clear();
			state.cache.mtimeMap.clear();
			state.cache.signatureMap.clear();
			if (clearEmittedCode) state.emittedCode.clear();
			return;
		}
		const shouldClear = (absPath) => {
			return state.ctx.configService.relativeAbsoluteSrcRoot(absPath).startsWith(`${currentRoot}/`);
		};
		for (const key of Array.from(state.depsMap.keys())) {
			if (shouldClear(key)) {
				const depSet = state.depsMap.get(key);
				if (depSet) for (const dep of depSet) unlinkImporter(dep, key);
				state.depsMap.delete(key);
				continue;
			}
			const depSet = state.depsMap.get(key);
			if (depSet) {
				for (const dep of Array.from(depSet)) if (shouldClear(dep)) {
					unlinkImporter(dep, key);
					depSet.delete(dep);
				}
			}
		}
		for (const key of Array.from(state.importerMap.keys())) if (shouldClear(key)) state.importerMap.delete(key);
		for (const key of Array.from(state.depKindMap.keys())) {
			if (shouldClear(key)) {
				state.depKindMap.delete(key);
				continue;
			}
			const importerKinds = state.depKindMap.get(key);
			if (!importerKinds) continue;
			for (const importer of Array.from(importerKinds.keys())) if (shouldClear(importer)) importerKinds.delete(importer);
			if (importerKinds.size === 0) state.depKindMap.delete(key);
		}
		for (const key of Array.from(state.tokenMap.keys())) if (shouldClear(key)) state.tokenMap.delete(key);
		for (const key of Array.from(state.componentsMap.keys())) if (shouldClear(key)) state.componentsMap.delete(key);
		for (const key of Array.from(state.aggregatedComponentsMap.keys())) if (shouldClear(key)) state.aggregatedComponentsMap.delete(key);
		for (const key of Array.from(state.autoImportComponentsMap.keys())) if (shouldClear(key)) state.autoImportComponentsMap.delete(key);
		for (const key of Array.from(state.aggregatedAutoImportComponentsMap.keys())) if (shouldClear(key)) state.aggregatedAutoImportComponentsMap.delete(key);
		for (const [key, value] of Array.from(state.templatePathMap.entries())) if (shouldClear(key) || shouldClear(value)) state.templatePathMap.delete(key);
		for (const key of Array.from(state.cache.cache.keys())) if (shouldClear(key)) state.cache.delete(key);
		for (const key of Array.from(state.cache.mtimeMap.keys())) if (shouldClear(key)) state.cache.mtimeMap.delete(key);
		if (clearEmittedCode) for (const key of Array.from(state.emittedCode.keys())) {
			const normalized = toPosixPath(key);
			if (normalized === currentRoot || normalized.startsWith(`${currentRoot}/`)) state.emittedCode.delete(key);
		}
	};
}
//#endregion
//#region src/runtime/wxmlPlugin/service/shared.ts
function createWxmlServiceState(ctx) {
	const { depsMap, importerMap, depKindMap, tokenMap, componentsMap, aggregatedComponentsMap, templatePathMap, cache, emittedCode } = ctx.runtimeState.wxml;
	return {
		ctx,
		depsMap,
		importerMap,
		depKindMap,
		tokenMap,
		componentsMap,
		aggregatedComponentsMap,
		autoImportComponentsMap: /* @__PURE__ */ new Map(),
		aggregatedAutoImportComponentsMap: /* @__PURE__ */ new Map(),
		templatePathMap,
		cache,
		emittedCode
	};
}
function linkImporter(state, dep, importer, kind = "unknown") {
	let importers = state.importerMap.get(dep);
	if (!importers) {
		importers = /* @__PURE__ */ new Set();
		state.importerMap.set(dep, importers);
	}
	importers.add(importer);
	let importerKinds = state.depKindMap.get(dep);
	if (!importerKinds) {
		importerKinds = /* @__PURE__ */ new Map();
		state.depKindMap.set(dep, importerKinds);
	}
	let kinds = importerKinds.get(importer);
	if (!kinds) {
		kinds = /* @__PURE__ */ new Set();
		importerKinds.set(importer, kinds);
	}
	kinds.add(kind);
}
function unlinkImporter(state, dep, importer) {
	const importers = state.importerMap.get(dep);
	if (!importers) return;
	importers.delete(importer);
	if (importers.size === 0) state.importerMap.delete(dep);
	const importerKinds = state.depKindMap.get(dep);
	if (!importerKinds) return;
	importerKinds.delete(importer);
	if (importerKinds.size === 0) state.depKindMap.delete(dep);
}
function getImporterDependencyKind(state, dep, importer) {
	const kinds = state.depKindMap.get(dep)?.get(importer);
	if (!kinds?.size) return;
	if (kinds.size === 1) return Array.from(kinds)[0];
	return "mixed";
}
function invalidateAggregatedComponents(state, filepath, targetMap, visited = /* @__PURE__ */ new Set()) {
	if (visited.has(filepath)) return;
	visited.add(filepath);
	targetMap.delete(removeExtensionDeep(filepath));
	const importers = state.importerMap.get(filepath);
	if (!importers) return;
	for (const importer of importers) invalidateAggregatedComponents(state, importer, targetMap, visited);
}
//#endregion
//#region src/runtime/wxmlPlugin/service/components.ts
function resolveTemplatePath(state, filepathOrBaseName) {
	if (state.depsMap.has(filepathOrBaseName) || state.tokenMap.has(filepathOrBaseName)) return filepathOrBaseName;
	if (state.templatePathMap.has(filepathOrBaseName)) return state.templatePathMap.get(filepathOrBaseName);
}
function getAggregatedComponentMap(state, filepathOrBaseName, targetMap, resolveOwnComponents) {
	const templatePath = resolveTemplatePath(state, filepathOrBaseName);
	if (!templatePath) return;
	const baseName = removeExtensionDeep(templatePath);
	const cached = targetMap.get(baseName);
	if (cached) return cached;
	const visited = /* @__PURE__ */ new Set();
	const aggregate = (filepath) => {
		if (visited.has(filepath)) return {};
		visited.add(filepath);
		const currentBaseName = removeExtensionDeep(filepath);
		const merged = {};
		const own = resolveOwnComponents(currentBaseName);
		if (own) for (const [name, ranges] of Object.entries(own)) merged[name] = ranges;
		const deps = state.depsMap.get(filepath);
		if (deps) for (const dep of deps) {
			if (!isTemplate(dep)) continue;
			const depComponents = aggregate(dep);
			for (const [name, ranges] of Object.entries(depComponents)) if (!merged[name]) merged[name] = ranges;
		}
		targetMap.set(currentBaseName, merged);
		return merged;
	};
	return aggregate(templatePath);
}
function createWxmlComponentService(state) {
	function getAggregatedComponents(filepathOrBaseName) {
		return getAggregatedComponentMap(state, filepathOrBaseName, state.aggregatedComponentsMap, (baseName) => state.componentsMap.get(baseName));
	}
	function getAggregatedAutoImportComponents(filepathOrBaseName) {
		return getAggregatedComponentMap(state, filepathOrBaseName, state.aggregatedAutoImportComponentsMap, (baseName) => state.autoImportComponentsMap.get(baseName) ?? state.componentsMap.get(baseName));
	}
	function setWxmlComponentsMap(absPath, components) {
		const baseName = removeExtensionDeep(absPath);
		state.templatePathMap.set(baseName, absPath);
		if (Object.keys(components).length === 0) state.componentsMap.delete(baseName);
		else state.componentsMap.set(baseName, components);
		invalidateAggregatedComponents(state, absPath, state.aggregatedComponentsMap);
	}
	return {
		getAggregatedComponents,
		getAggregatedAutoImportComponents,
		setWxmlComponentsMap
	};
}
//#endregion
//#region src/runtime/wxmlPlugin/service/deps.ts
function createWxmlDependencyService(state, scanTemplateDep) {
	async function setDepRecords(filepath, deps = []) {
		const nextDeps = new Set(deps.map((dep) => dep.path));
		const previousDeps = state.depsMap.get(filepath) ?? /* @__PURE__ */ new Set();
		const nextDepsKey = Array.from(nextDeps).sort().join("\0");
		const previousDepsKey = Array.from(previousDeps).sort().join("\0");
		for (const previousDep of previousDeps) unlinkImporter(state, previousDep, filepath);
		for (const dep of deps) linkImporter(state, dep.path, filepath, dep.kind);
		state.depsMap.set(filepath, nextDeps);
		if (nextDepsKey !== previousDepsKey) {
			invalidateAggregatedComponents(state, filepath, state.aggregatedComponentsMap);
			invalidateAggregatedComponents(state, filepath, state.aggregatedAutoImportComponentsMap);
		}
		await Promise.all(Array.from(nextDeps).filter((dep) => isTemplate(dep)).map(async (dep) => {
			return await scanTemplateDep(dep);
		}));
	}
	async function setDeps(filepath, deps = []) {
		await setDepRecords(filepath, deps.map((dep) => ({
			path: dep,
			kind: "unknown"
		})));
	}
	async function addDeps(filepath, deps = []) {
		await setDeps(filepath, [...state.depsMap.get(filepath) ?? /* @__PURE__ */ new Set(), ...deps]);
	}
	function resolveDepPath(filepath, value) {
		const configService = requireConfigService(state.ctx, "解析 WXML 依赖前必须初始化 configService。");
		const dirname = path.dirname(filepath);
		if (value.startsWith("/")) return path.resolve(configService.absoluteSrcRoot, value.slice(1));
		return path.resolve(dirname, value);
	}
	function collectDepRecordsFromToken(filepath, deps = []) {
		return deps.reduce((resolvedDeps, dep) => {
			if (!dep.value) return resolvedDeps;
			if (isTemplateImportTag(dep.tagName) && !isTemplate(dep.value)) return resolvedDeps;
			if (!isTemplateImportTag(dep.tagName) && !isScriptModuleTagName(dep.tagName)) return resolvedDeps;
			const kind = dep.tagName === "import" ? "template-import" : dep.tagName === "include" ? "template-include" : "script-module";
			resolvedDeps.push({
				path: resolveDepPath(filepath, dep.value),
				kind
			});
			return resolvedDeps;
		}, []);
	}
	function collectDepsFromToken(filepath, deps = []) {
		return collectDepRecordsFromToken(filepath, deps).map((dep) => dep.path);
	}
	async function setTokenDeps(filepath, deps = []) {
		await setDepRecords(filepath, collectDepRecordsFromToken(filepath, deps));
	}
	function getImporters(filepath) {
		return new Set(state.importerMap.get(filepath) ?? []);
	}
	function getAllDeps() {
		const set = /* @__PURE__ */ new Set();
		for (const [key, value] of state.depsMap) {
			set.add(key);
			for (const item of value) set.add(item);
		}
		return set;
	}
	return {
		addDeps,
		setDeps,
		setTokenDeps,
		collectDepsFromToken,
		getImporters,
		getImporterDependencyKind(dep, importer) {
			return getImporterDependencyKind(state, dep, importer);
		},
		getAllDeps,
		unlinkImporter(dep, importer) {
			unlinkImporter(state, dep, importer);
		}
	};
}
//#endregion
//#region src/runtime/wxmlPlugin/service/scan.ts
function createWxmlScanner(state, options) {
	function analyze(wxml) {
		const configService = requireConfigService(state.ctx, "扫描 WXML 前必须初始化 configService。");
		const wxmlConfig = configService.weappViteConfig?.wxml ?? configService.weappViteConfig?.enhance?.wxml;
		return scanWxml(wxml, {
			platform: configService.platform,
			...wxmlConfig === true ? {} : wxmlConfig ?? {}
		});
	}
	async function scan(filepath) {
		const configService = requireConfigService(state.ctx, "扫描 WXML 前必须初始化 configService。");
		let stat;
		try {
			stat = await fs$1.stat(filepath);
		} catch (error) {
			if (error && error.code === "ENOENT") {
				logger_default.warn(`引用模板 \`${configService.relativeCwd(filepath)}\` 不存在!`);
				return;
			}
			throw error;
		}
		const signature = `${stat.mtimeMs ?? ""}:${stat.ctimeMs ?? ""}:${stat.size ?? ""}`;
		if (!await state.cache.isInvalidate(filepath, {
			signature,
			checkMtime: false
		})) {
			const cached = state.cache.get(filepath);
			if (cached) {
				state.tokenMap.set(filepath, cached);
				return cached;
			}
		}
		const res = analyze(await fs$1.readFile(filepath, "utf8"));
		state.tokenMap.set(filepath, res);
		state.cache.set(filepath, res);
		const baseName = removeExtensionDeep(filepath);
		const autoImportComponentEntries = res.autoImportComponents ?? res.components ?? {};
		if (isEmptyObject$1(autoImportComponentEntries)) state.autoImportComponentsMap.delete(baseName);
		else state.autoImportComponentsMap.set(baseName, autoImportComponentEntries);
		invalidateAggregatedComponents(state, filepath, state.aggregatedAutoImportComponentsMap);
		await options.setTokenDeps(filepath, res.deps);
		return res;
	}
	return {
		analyze,
		scan
	};
}
//#endregion
//#region src/runtime/wxmlPlugin/service/index.ts
function createWxmlService(ctx) {
	const state = createWxmlServiceState(ctx);
	let scan = async () => void 0;
	const deps = createWxmlDependencyService(state, async (filepath) => {
		return await scan(filepath);
	});
	const components = createWxmlComponentService(state);
	const scanner = createWxmlScanner(state, { setTokenDeps: deps.setTokenDeps });
	scan = scanner.scan;
	return {
		depsMap: state.depsMap,
		importerMap: state.importerMap,
		depKindMap: state.depKindMap,
		tokenMap: state.tokenMap,
		wxmlComponentsMap: state.componentsMap,
		aggregatedComponentsMap: state.aggregatedComponentsMap,
		addDeps: deps.addDeps,
		setDeps: deps.setDeps,
		setTokenDeps: deps.setTokenDeps,
		collectDepsFromToken: deps.collectDepsFromToken,
		getImporters: deps.getImporters,
		getImporterDependencyKind: deps.getImporterDependencyKind,
		getAllDeps: deps.getAllDeps,
		getAggregatedComponents: components.getAggregatedComponents,
		getAggregatedAutoImportComponents: components.getAggregatedAutoImportComponents,
		clearAll: createClearAll(state, deps.unlinkImporter),
		analyze: scanner.analyze,
		scan,
		setWxmlComponentsMap: components.setWxmlComponentsMap
	};
}
//#endregion
//#region src/runtime/wxmlPlugin.ts
function createWxmlServicePlugin(ctx) {
	const service = createWxmlService(ctx);
	ctx.wxmlService = service;
	return {
		name: "weapp-runtime:wxml-service",
		buildStart() {
			if (!ctx.configService?.isDev) service.clearAll();
		}
	};
}
//#endregion
//#region src/context/createCompilerContextInstance.ts
function createCompilerContextInstance() {
	const context = {
		moduleGraphService: createModuleGraphService(),
		runtimeState: createRuntimeState()
	};
	const runtimePlugins = [
		createConfigServicePlugin(context),
		createWatcherServicePlugin(context),
		createWxmlServicePlugin(context),
		createJsonServicePlugin(context),
		createScanServicePlugin(context),
		createAutoRoutesServicePlugin(context),
		createAutoImportServicePlugin(context),
		createNpmServicePlugin(context),
		createBuildServicePlugin(context),
		createWebServicePlugin(context)
	];
	Object.defineProperty(context, Symbol.for("weapp-runtime:plugins"), {
		configurable: false,
		enumerable: false,
		writable: false,
		value: runtimePlugins
	});
	return context;
}
//#endregion
//#region src/context/getInstance.ts
const compilerContextMap = /* @__PURE__ */ new Map();
const DEFAULT_KEY = "default";
let activeCompilerContextKey = DEFAULT_KEY;
function setActiveCompilerContextKey(key) {
	activeCompilerContextKey = key;
}
function getCompilerContext(key = activeCompilerContextKey) {
	let ctx = compilerContextMap.get(key);
	if (!ctx) {
		ctx = createCompilerContextInstance();
		compilerContextMap.set(key, ctx);
		setActiveCompilerContextKey(key);
	}
	return ctx;
}
function resetCompilerContext(key) {
	if (key) {
		compilerContextMap.delete(key);
		if (activeCompilerContextKey === key) activeCompilerContextKey = DEFAULT_KEY;
		return;
	}
	compilerContextMap.clear();
	activeCompilerContextKey = DEFAULT_KEY;
}
//#endregion
//#region src/createContext.ts
/**
* @description 创建并初始化编译上下文(加载配置、扫描入口)
*/
async function createCompilerContext(options) {
	const bootstrapManagedTsconfigPromise = options?.cwd && !hasManagedTsconfigBootstrapCompleted(options.cwd) ? Promise.resolve().then(() => syncManagedTsconfigBootstrapFiles(options.cwd)).catch((error) => {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.warn(`[tsconfig] 跳过 .weapp-vite 支持文件预生成:${message}`);
		return false;
	}) : Promise.resolve(false);
	const key = options?.key ?? "default";
	if (!options?.key) resetCompilerContext(key);
	setActiveCompilerContextKey(key);
	const ctx = getCompilerContext(key);
	const { configService, scanService } = ctx;
	await configService.load(options);
	const bootstrapManagedTsconfigChanged = await bootstrapManagedTsconfigPromise;
	if (options?.syncSupportFiles !== false) try {
		const supportFiles = await syncProjectSupportFiles(ctx, { syncAutoImport: options?.syncAutoImportSupportFiles });
		for (const warning of supportFiles.managedTsconfigWarnings) logger_default.warn(warning);
		if (supportFiles.managedTsconfigWarnings.length === 0 && (bootstrapManagedTsconfigChanged || supportFiles.managedTsconfigChanged)) logger_default.warn("[prepare] 检测到 .weapp-vite 支持文件缺失或已过期,已自动重新生成。建议执行 wv prepare 并提交更新。");
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		logger_default.warn(`[prepare] 自动同步 .weapp-vite 支持文件失败:${message}`);
	}
	if (options?.preloadAppEntry !== false) try {
		await scanService.loadAppEntry();
	} catch {}
	return ctx;
}
//#endregion
export { getDefaultIdeProjectRoot as A, collectPreloadPages as C, loadViteConfigFile as D, suggestPreloadRules as E, isPathInside as M, createCjsConfigLoadError as O, getProjectConfigFileName as S, resolvePreloadPackageIdentifier as T, SHARED_CHUNK_VIRTUAL_PREFIX as _, createGlassEaselAnalyzeResult as a, resolveWeappConfigFile as b, getSupportedWeappVitePlatforms as c, resolveWeappViteTarget as d, getBackendForCapability as f, createSharedBuildConfig as g, syncManagedTsconfigBootstrapFiles as h, setActiveCompilerContextKey as i, shouldPassPlatformArgToIdeOpen as j, parseCommentJson as k, getSupportedWeappViteTargetDescriptors as l, syncProjectSupportFiles as m, getCompilerContext as n, formatBytes as o, resolveBackendExecution as p, resetCompilerContext as r, WEB_PLATFORM_ALIASES as s, createCompilerContext as t, isWebPlatform as u, resolveHmrProfileJsonPath as v, findPreloadRuleKey as w, checkRuntime as x, getRouteRuntimeGlobalKeys as y };