weapp-vite
Version:
weapp-vite 一个现代化的小程序打包工具
1,118 lines • 1.41 MB
JavaScript
import { n as applyWeappViteHostMeta } from "./pluginHost--CaeyWpA.mjs";
import { n as configureLogger, r as logger_default } from "./logger-mt4mSTqV.mjs";
import { _ as jsExtensions, a as findJsonEntry, b as vueExtensions, c as isJsOrTs, d as touch, g as configExtensions, i as findJsEntry, l as isTemplate, n as changeFileExtension, o as findTemplateEntry, p as inlineAutoRoutesImports, r as findCssEntry, s as findVueEntry, t as extractConfigFromVue, v as supportedCssLangs, y as templateExtensions } from "./file-CFQYYS_3.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_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, MINI_PROGRAM_PLATFORM_DESCRIPTORS as MINI_PROGRAM_PLATFORM_ADAPTERS, addExtension, defu, escapeStringRegexp, get, getDefaultMiniProgramPlatform, getMiniProgramAppTypesPackage, getMiniProgramDefaultBuildTarget, getMiniProgramDirectivePrefix, getMiniProgramRouteRuntimeGlobalKeys, getMiniProgramRuntimeGlobalKey, getMiniProgramRuntimeGlobalKeys, getMiniProgramRuntimeGlobalKeysByResolvePriority, getSupportedMiniProgramDirectivePrefixes, getSupportedMiniProgramPlatforms, isEmptyObject, isObject, normalizeMiniProgramPlatform, removeExtension, removeExtensionDeep, resolveMiniProgramPlatform, set, supportsMiniProgramAutoTouchAppStyle } from "@weapp-core/shared";
import { fs as fs$1 } from "@weapp-core/shared/fs";
import { analyzeScript, analyzeScripts, collectComponentPropsFromCode, collectRequireTokens, collectScriptSetupImportsFromCode, generate, mayContainPlatformApiAccess, mayContainPlatformApiIdentifierByText, mayContainStaticRequireLiteral, parseJsLikeWithEngine, platformApiIdentifiers } from "@weapp-vite/ast";
import { collectOnPageScrollPerformanceWarnings } from "@weapp-vite/ast/operations/onPageScroll";
import { collectSetDataPickKeysFromTemplateCode } from "@weapp-vite/ast/operations/setDataPick";
import { compileScript, parse } from "vue/compiler-sfc";
import { BABEL_TS_MODULE_PARSER_OPTIONS, generate as generate$1, getVisitorKeys, parse as parse$2, parseJsLike, traverse } from "@weapp-vite/ast/babel";
import pm 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, 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, stripJsonMacroCallsFromCode, transformNestedWxssVars, transformUniAppSource, transformVueDeepSelectors } from "wevu/compiler";
import process from "node:process";
import { parse as parse$1, stringify } from "comment-json";
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 babelPresetEnv from "@babel/preset-env";
import babelPresetTypescript from "@babel/preset-typescript";
import * as babel from "@weapp-vite/ast/babelCore";
import * as t from "@weapp-vite/ast/babelTypes";
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 remapping from "@jridgewell/remapping";
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",
"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",
"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 {}
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 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();
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 (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$1(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$1(configService)) addDefaultComponentGlobs(globs, configService, "vue");
return {
...defaults,
globs: [...globs],
output: true,
typedComponents: true,
htmlCustomData: true,
vueComponents: true,
vueComponentsModule: hasWevuDependency$1(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/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.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);
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/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;
l