UNPKG

weapp-vite

Version:

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

1,592 lines (1,576 loc) 63.5 kB
import { createCompilerContext } from "./chunk-LLYDSPS7.mjs"; import { DEFAULT_MP_PLATFORM, SHARED_CHUNK_VIRTUAL_PREFIX, VERSION, checkRuntime, createSharedBuildConfig, logger_default, normalizeMiniPlatform, resolveMiniPlatform, resolveWeappConfigFile } from "./chunk-TS7WK45E.mjs"; import { init_esm_shims } from "./chunk-MDUMD5GP.mjs"; // src/cli.ts init_esm_shims(); // ../../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs init_esm_shims(); import { EventEmitter } from "events"; function toArr(any) { return any == null ? [] : Array.isArray(any) ? any : [any]; } function toVal(out, key, val, opts) { var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val; out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt]; } function mri2(args, opts) { args = args || []; opts = opts || {}; var k, arr, arg, name, val, out = { _: [] }; var i = 0, j = 0, idx = 0, len = args.length; const alibi = opts.alias !== void 0; const strict = opts.unknown !== void 0; const defaults = opts.default !== void 0; opts.alias = opts.alias || {}; opts.string = toArr(opts.string); opts.boolean = toArr(opts.boolean); if (alibi) { for (k in opts.alias) { arr = opts.alias[k] = toArr(opts.alias[k]); for (i = 0; i < arr.length; i++) { (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); } } } for (i = opts.boolean.length; i-- > 0; ) { arr = opts.alias[opts.boolean[i]] || []; for (j = arr.length; j-- > 0; ) opts.boolean.push(arr[j]); } for (i = opts.string.length; i-- > 0; ) { arr = opts.alias[opts.string[i]] || []; for (j = arr.length; j-- > 0; ) opts.string.push(arr[j]); } if (defaults) { for (k in opts.default) { name = typeof opts.default[k]; arr = opts.alias[k] = opts.alias[k] || []; if (opts[name] !== void 0) { opts[name].push(k); for (i = 0; i < arr.length; i++) { opts[name].push(arr[i]); } } } } const keys = strict ? Object.keys(opts.alias) : []; for (i = 0; i < len; i++) { arg = args[i]; if (arg === "--") { out._ = out._.concat(args.slice(++i)); break; } for (j = 0; j < arg.length; j++) { if (arg.charCodeAt(j) !== 45) break; } if (j === 0) { out._.push(arg); } else if (arg.substring(j, j + 3) === "no-") { name = arg.substring(j + 3); if (strict && !~keys.indexOf(name)) { return opts.unknown(arg); } out[name] = false; } else { for (idx = j + 1; idx < arg.length; idx++) { if (arg.charCodeAt(idx) === 61) break; } name = arg.substring(j, idx); val = arg.substring(++idx) || (i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i]); arr = j === 2 ? [name] : name; for (idx = 0; idx < arr.length; idx++) { name = arr[idx]; if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name); toVal(out, name, idx + 1 < arr.length || val, opts); } } } if (defaults) { for (k in opts.default) { if (out[k] === void 0) { out[k] = opts.default[k]; } } } if (alibi) { for (k in out) { arr = opts.alias[k] || []; while (arr.length > 0) { out[arr.shift()] = out[k]; } } } return out; } var removeBrackets = (v) => v.replace(/[<[].+/, "").trim(); var findAllBrackets = (v) => { const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; const res = []; const parse3 = (match) => { let variadic = false; let value = match[1]; if (value.startsWith("...")) { value = value.slice(3); variadic = true; } return { required: match[0].startsWith("<"), value, variadic }; }; let angledMatch; while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) { res.push(parse3(angledMatch)); } let squareMatch; while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) { res.push(parse3(squareMatch)); } return res; }; var getMriOptions = (options) => { const result = { alias: {}, boolean: [] }; for (const [index, option] of options.entries()) { if (option.names.length > 1) { result.alias[option.names[0]] = option.names.slice(1); } if (option.isBoolean) { if (option.negated) { const hasStringTypeOption = options.some((o, i) => { return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean"; }); if (!hasStringTypeOption) { result.boolean.push(option.names[0]); } } else { result.boolean.push(option.names[0]); } } } return result; }; var findLongest = (arr) => { return arr.sort((a, b) => { return a.length > b.length ? -1 : 1; })[0]; }; var padRight = (str, length) => { return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; }; var camelcase = (input) => { return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => { return p1 + p2.toUpperCase(); }); }; var setDotProp = (obj, keys, val) => { let i = 0; let length = keys.length; let t = obj; let x; for (; i < length; ++i) { x = t[keys[i]]; t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : []; } }; var setByType = (obj, transforms) => { for (const key of Object.keys(transforms)) { const transform = transforms[key]; if (transform.shouldTransform) { obj[key] = Array.prototype.concat.call([], obj[key]); if (typeof transform.transformFunction === "function") { obj[key] = obj[key].map(transform.transformFunction); } } } }; var getFileName = (input) => { const m = /([^\\\/]+)$/.exec(input); return m ? m[1] : ""; }; var camelcaseOptionName = (name) => { return name.split(".").map((v, i) => { return i === 0 ? camelcase(v) : v; }).join("."); }; var CACError = class extends Error { constructor(message) { super(message); this.name = this.constructor.name; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error(message).stack; } } }; var Option = class { constructor(rawName, description, config) { this.rawName = rawName; this.description = description; this.config = Object.assign({}, config); rawName = rawName.replace(/\.\*/g, ""); this.negated = false; this.names = removeBrackets(rawName).split(",").map((v) => { let name = v.trim().replace(/^-{1,2}/, ""); if (name.startsWith("no-")) { this.negated = true; name = name.replace(/^no-/, ""); } return camelcaseOptionName(name); }).sort((a, b) => a.length > b.length ? 1 : -1); this.name = this.names[this.names.length - 1]; if (this.negated && this.config.default == null) { this.config.default = true; } if (rawName.includes("<")) { this.required = true; } else if (rawName.includes("[")) { this.required = false; } else { this.isBoolean = true; } } }; var processArgs = process.argv; var platformInfo = `${process.platform}-${process.arch} node-${process.version}`; var Command = class { constructor(rawName, description, config = {}, cli2) { this.rawName = rawName; this.description = description; this.config = config; this.cli = cli2; this.options = []; this.aliasNames = []; this.name = removeBrackets(rawName); this.args = findAllBrackets(rawName); this.examples = []; } usage(text) { this.usageText = text; return this; } allowUnknownOptions() { this.config.allowUnknownOptions = true; return this; } ignoreOptionDefaultValue() { this.config.ignoreOptionDefaultValue = true; return this; } version(version, customFlags = "-v, --version") { this.versionNumber = version; this.option(customFlags, "Display version number"); return this; } example(example) { this.examples.push(example); return this; } option(rawName, description, config) { const option = new Option(rawName, description, config); this.options.push(option); return this; } alias(name) { this.aliasNames.push(name); return this; } action(callback) { this.commandAction = callback; return this; } isMatched(name) { return this.name === name || this.aliasNames.includes(name); } get isDefaultCommand() { return this.name === "" || this.aliasNames.includes("!"); } get isGlobalCommand() { return this instanceof GlobalCommand; } hasOption(name) { name = name.split(".")[0]; return this.options.find((option) => { return option.names.includes(name); }); } outputHelp() { const { name, commands } = this.cli; const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand; let sections = [ { body: `${name}${versionNumber ? `/${versionNumber}` : ""}` } ]; sections.push({ title: "Usage", body: ` $ ${name} ${this.usageText || this.rawName}` }); const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; if (showCommands) { const longestCommandName = findLongest(commands.map((command) => command.rawName)); sections.push({ title: "Commands", body: commands.map((command) => { return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`; }).join("\n") }); sections.push({ title: `For more info, run any command with the \`--help\` flag`, body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n") }); } let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []]; if (!this.isGlobalCommand && !this.isDefaultCommand) { options = options.filter((option) => option.name !== "version"); } if (options.length > 0) { const longestOptionName = findLongest(options.map((option) => option.rawName)); sections.push({ title: "Options", body: options.map((option) => { return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`; }).join("\n") }); } if (this.examples.length > 0) { sections.push({ title: "Examples", body: this.examples.map((example) => { if (typeof example === "function") { return example(name); } return example; }).join("\n") }); } if (helpCallback) { sections = helpCallback(sections) || sections; } console.log(sections.map((section) => { return section.title ? `${section.title}: ${section.body}` : section.body; }).join("\n\n")); } outputVersion() { const { name } = this.cli; const { versionNumber } = this.cli.globalCommand; if (versionNumber) { console.log(`${name}/${versionNumber} ${platformInfo}`); } } checkRequiredArgs() { const minimalArgsCount = this.args.filter((arg) => arg.required).length; if (this.cli.args.length < minimalArgsCount) { throw new CACError(`missing required args for command \`${this.rawName}\``); } } checkUnknownOptions() { const { options, globalCommand } = this.cli; if (!this.config.allowUnknownOptions) { for (const name of Object.keys(options)) { if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) { throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``); } } } } checkOptionValue() { const { options: parsedOptions, globalCommand } = this.cli; const options = [...globalCommand.options, ...this.options]; for (const option of options) { const value = parsedOptions[option.name.split(".")[0]]; if (option.required) { const hasNegated = options.some((o) => o.negated && o.names.includes(option.name)); if (value === true || value === false && !hasNegated) { throw new CACError(`option \`${option.rawName}\` value is missing`); } } } } }; var GlobalCommand = class extends Command { constructor(cli2) { super("@@global@@", "", {}, cli2); } }; var __assign = Object.assign; var CAC = class extends EventEmitter { constructor(name = "") { super(); this.name = name; this.commands = []; this.rawArgs = []; this.args = []; this.options = {}; this.globalCommand = new GlobalCommand(this); this.globalCommand.usage("<command> [options]"); } usage(text) { this.globalCommand.usage(text); return this; } command(rawName, description, config) { const command = new Command(rawName, description || "", config, this); command.globalCommand = this.globalCommand; this.commands.push(command); return command; } option(rawName, description, config) { this.globalCommand.option(rawName, description, config); return this; } help(callback) { this.globalCommand.option("-h, --help", "Display this message"); this.globalCommand.helpCallback = callback; this.showHelpOnExit = true; return this; } version(version, customFlags = "-v, --version") { this.globalCommand.version(version, customFlags); this.showVersionOnExit = true; return this; } example(example) { this.globalCommand.example(example); return this; } outputHelp() { if (this.matchedCommand) { this.matchedCommand.outputHelp(); } else { this.globalCommand.outputHelp(); } } outputVersion() { this.globalCommand.outputVersion(); } setParsedInfo({ args, options }, matchedCommand, matchedCommandName) { this.args = args; this.options = options; if (matchedCommand) { this.matchedCommand = matchedCommand; } if (matchedCommandName) { this.matchedCommandName = matchedCommandName; } return this; } unsetMatchedCommand() { this.matchedCommand = void 0; this.matchedCommandName = void 0; } parse(argv = processArgs, { run = true } = {}) { this.rawArgs = argv; if (!this.name) { this.name = argv[1] ? getFileName(argv[1]) : "cli"; } let shouldParse = true; for (const command of this.commands) { const parsed = this.mri(argv.slice(2), command); const commandName = parsed.args[0]; if (command.isMatched(commandName)) { shouldParse = false; const parsedInfo = __assign(__assign({}, parsed), { args: parsed.args.slice(1) }); this.setParsedInfo(parsedInfo, command, commandName); this.emit(`command:${commandName}`, command); } } if (shouldParse) { for (const command of this.commands) { if (command.name === "") { shouldParse = false; const parsed = this.mri(argv.slice(2), command); this.setParsedInfo(parsed, command); this.emit(`command:!`, command); } } } if (shouldParse) { const parsed = this.mri(argv.slice(2)); this.setParsedInfo(parsed); } if (this.options.help && this.showHelpOnExit) { this.outputHelp(); run = false; this.unsetMatchedCommand(); } if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) { this.outputVersion(); run = false; this.unsetMatchedCommand(); } const parsedArgv = { args: this.args, options: this.options }; if (run) { this.runMatchedCommand(); } if (!this.matchedCommand && this.args[0]) { this.emit("command:*"); } return parsedArgv; } mri(argv, command) { const cliOptions = [ ...this.globalCommand.options, ...command ? command.options : [] ]; const mriOptions = getMriOptions(cliOptions); let argsAfterDoubleDashes = []; const doubleDashesIndex = argv.indexOf("--"); if (doubleDashesIndex > -1) { argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); argv = argv.slice(0, doubleDashesIndex); } let parsed = mri2(argv, mriOptions); parsed = Object.keys(parsed).reduce((res, name) => { return __assign(__assign({}, res), { [camelcaseOptionName(name)]: parsed[name] }); }, { _: [] }); const args = parsed._; const options = { "--": argsAfterDoubleDashes }; const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; let transforms = /* @__PURE__ */ Object.create(null); for (const cliOption of cliOptions) { if (!ignoreDefault && cliOption.config.default !== void 0) { for (const name of cliOption.names) { options[name] = cliOption.config.default; } } if (Array.isArray(cliOption.config.type)) { if (transforms[cliOption.name] === void 0) { transforms[cliOption.name] = /* @__PURE__ */ Object.create(null); transforms[cliOption.name]["shouldTransform"] = true; transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; } } } for (const key of Object.keys(parsed)) { if (key !== "_") { const keys = key.split("."); setDotProp(options, keys, parsed[key]); setByType(options, transforms); } } return { args, options }; } runMatchedCommand() { const { args, options, matchedCommand: command } = this; if (!command || !command.commandAction) return; command.checkUnknownOptions(); command.checkOptionValue(); command.checkRequiredArgs(); const actionArgs = []; command.args.forEach((arg, index) => { if (arg.variadic) { actionArgs.push(args.slice(index)); } else { actionArgs.push(args[index]); } }); actionArgs.push(options); return command.commandAction.apply(this, actionArgs); } }; var cac = (name = "") => new CAC(name); // src/cli/commands/analyze.ts init_esm_shims(); import process3 from "process"; import fs3 from "fs-extra"; import path2 from "pathe"; // src/analyze/subpackages.ts init_esm_shims(); import { Buffer } from "buffer"; import { posix as path } from "pathe"; import { build } from "vite"; var VIRTUAL_MODULE_INDICATOR = "\0"; var VIRTUAL_PREFIX = `${SHARED_CHUNK_VIRTUAL_PREFIX}/`; function isPathInside(parent, candidate) { if (!parent) { return false; } const relative = path.relative(parent, candidate); return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative); } function ensurePackage(packages, classification) { const existing = packages.get(classification.id); if (existing) { return existing; } const created = { ...classification, files: /* @__PURE__ */ new Map() }; packages.set(classification.id, created); return created; } function ensureModule(modules, id, source, sourceType) { const existing = modules.get(id); if (existing) { return existing; } const created = { id, source, sourceType, packages: /* @__PURE__ */ new Map() }; modules.set(id, created); return created; } function registerModuleInPackage(modules, moduleId, source, sourceType, packageId, fileName) { const moduleEntry = ensureModule(modules, moduleId, source, sourceType); const files = moduleEntry.packages.get(packageId) ?? /* @__PURE__ */ new Set(); files.add(fileName); moduleEntry.packages.set(packageId, files); } function classifyPackage(fileName, origin, context) { if (fileName.startsWith(VIRTUAL_PREFIX)) { const combination = fileName.slice(VIRTUAL_PREFIX.length).split("/")[0] || "shared"; return { id: `virtual:${combination}`, label: `\u5171\u4EAB\u865A\u62DF\u5305 ${combination}`, type: "virtual" }; } const segments = fileName.split("/"); const rootCandidate = segments[0] ?? ""; if (rootCandidate && context.subPackageRoots.has(rootCandidate)) { const isIndependent = context.independentRoots.has(rootCandidate); return { id: rootCandidate, label: `${isIndependent ? "\u72EC\u7ACB\u5206\u5305" : "\u5206\u5305"} ${rootCandidate}`, type: isIndependent || origin === "independent" ? "independent" : "subPackage" }; } return { id: "__main__", label: "\u4E3B\u5305", type: "main" }; } function normalizeModuleId(id) { if (!id || id.includes(VIRTUAL_MODULE_INDICATOR)) { return void 0; } if (!path.isAbsolute(id)) { return void 0; } return path.normalize(id); } function resolveModuleSourceType(absoluteId, ctx) { const { configService } = ctx; const isNodeModule = absoluteId.includes("/node_modules/") || absoluteId.includes("\\node_modules\\"); const pluginRoot = configService.absolutePluginRoot; const srcRoot = configService.absoluteSrcRoot; const inSrc = isPathInside(srcRoot, absoluteId); const inPlugin = pluginRoot ? isPathInside(pluginRoot, absoluteId) : false; let sourceType; if (isNodeModule) { sourceType = "node_modules"; } else if (inSrc) { sourceType = "src"; } else if (inPlugin) { sourceType = "plugin"; } else { sourceType = "workspace"; } return { source: configService.relativeAbsoluteSrcRoot(absoluteId), sourceType }; } function resolveAssetSource(fileName, ctx) { const { configService } = ctx; const normalized = path.normalize(fileName); const srcCandidate = path.resolve(configService.absoluteSrcRoot, normalized); if (isPathInside(configService.absoluteSrcRoot, srcCandidate)) { return { absolute: srcCandidate, source: configService.relativeAbsoluteSrcRoot(srcCandidate), sourceType: "src" }; } const pluginRoot = configService.absolutePluginRoot; if (pluginRoot) { const pluginBase = path.basename(pluginRoot); if (normalized === pluginBase || normalized.startsWith(`${pluginBase}/`)) { const relative = normalized === pluginBase ? "" : normalized.slice(pluginBase.length + 1); const absolute = path.resolve(pluginRoot, relative); if (isPathInside(pluginRoot, absolute)) { return { absolute, source: configService.relativeAbsoluteSrcRoot(absolute), sourceType: "plugin" }; } } } } function toArray(value) { return Array.from(value); } function getAssetSize(asset) { if (typeof asset.source === "string") { return Buffer.byteLength(asset.source, "utf8"); } if (asset.source instanceof Uint8Array) { return asset.source.byteLength; } } function processChunk(chunk, origin, ctx, classifierContext, packages, modules) { const classification = classifyPackage(chunk.fileName, origin, classifierContext); const packageEntry = ensurePackage(packages, classification); const chunkEntry = { file: chunk.fileName, type: "chunk", from: origin, size: typeof chunk.code === "string" ? Buffer.byteLength(chunk.code, "utf8") : void 0, isEntry: chunk.isEntry, modules: [] }; const moduleEntries = Object.entries(chunk.modules ?? {}); for (const [rawModuleId, info] of moduleEntries) { const absoluteId = normalizeModuleId(rawModuleId); if (!absoluteId) { continue; } const { source, sourceType } = resolveModuleSourceType(absoluteId, ctx); const moduleEntry = { id: absoluteId, source, sourceType, bytes: info?.renderedLength }; if (typeof info?.code === "string") { moduleEntry.originalBytes = Buffer.byteLength(info.code, "utf8"); } chunkEntry.modules.push(moduleEntry); registerModuleInPackage( modules, absoluteId, source, sourceType, classification.id, chunk.fileName ); } if (chunkEntry.modules) { chunkEntry.modules.sort((a, b) => a.source.localeCompare(b.source)); } packageEntry.files.set(chunk.fileName, chunkEntry); } function processAsset(asset, origin, ctx, classifierContext, packages, modules) { const classification = classifyPackage(asset.fileName, origin, classifierContext); const packageEntry = ensurePackage(packages, classification); const entry = { file: asset.fileName, type: "asset", from: origin, size: getAssetSize(asset) }; const assetSource = resolveAssetSource(asset.fileName, ctx); if (assetSource) { entry.source = assetSource.source; registerModuleInPackage( modules, assetSource.absolute, assetSource.source, assetSource.sourceType, classification.id, asset.fileName ); } packageEntry.files.set(asset.fileName, entry); } function processOutput(output, origin, ctx, classifierContext, packages, modules) { if (!output) { return; } for (const item of output.output ?? []) { if (item.type === "chunk") { processChunk(item, origin, ctx, classifierContext, packages, modules); } else if (item.type === "asset") { processAsset(item, origin, ctx, classifierContext, packages, modules); } } } function summarizePackages(packages) { const order = { main: 0, subPackage: 1, independent: 2, virtual: 3 }; const reports = toArray(packages.values()).map((pkg) => { const files = toArray(pkg.files.values()); files.sort((a, b) => a.file.localeCompare(b.file)); return { id: pkg.id, label: pkg.label, type: pkg.type, files }; }); reports.sort((a, b) => { const delta = order[a.type] - order[b.type]; if (delta !== 0) { return delta; } if (a.id === "__main__") { return -1; } if (b.id === "__main__") { return 1; } return a.id.localeCompare(b.id); }); return reports; } function summarizeModules(modules) { const usage = toArray(modules.values()).map((module) => { const packages = toArray(module.packages.entries()).map(([packageId, files]) => { const sortedFiles = toArray(files).sort((a, b) => a.localeCompare(b)); return { packageId, files: sortedFiles }; }).sort((a, b) => { if (a.packageId === b.packageId) { return 0; } if (a.packageId === "__main__") { return -1; } if (b.packageId === "__main__") { return 1; } return a.packageId.localeCompare(b.packageId); }); return { id: module.id, source: module.source, sourceType: module.sourceType, packages }; }); usage.sort((a, b) => a.source.localeCompare(b.source)); return usage; } function expandVirtualModulePlacements(modules, packages, context) { for (const moduleEntry of modules.values()) { const virtualEntries = Array.from(moduleEntry.packages.entries()).filter(([packageId]) => packageId.startsWith("virtual:")); if (!virtualEntries.length) { continue; } const virtualFileBases = /* @__PURE__ */ new Map(); for (const [virtualPackageId, files] of virtualEntries) { const combination = virtualPackageId.slice("virtual:".length); if (!combination) { continue; } const segments = combination.split(/[_+]/).map((segment) => segment.trim()).filter(Boolean); if (!segments.length) { continue; } let matchingBases = virtualFileBases.get(virtualPackageId); if (!matchingBases) { matchingBases = Array.from(files).map((file) => path.basename(file)); virtualFileBases.set(virtualPackageId, matchingBases); } for (const root of segments) { if (!context.subPackageRoots.has(root)) { continue; } const targetPackage = packages.get(root); if (!targetPackage) { continue; } const moduleFiles = moduleEntry.packages.get(root) ?? /* @__PURE__ */ new Set(); const targetFiles = Array.from(targetPackage.files.values()).filter((fileEntry) => { if (!matchingBases?.length) { return true; } const base = path.basename(fileEntry.file); return matchingBases.includes(base); }).map((fileEntry) => fileEntry.file); if (targetFiles.length === 0) { const fallback = targetPackage.files.values().next().value; if (fallback) { moduleFiles.add(fallback.file); } } else { for (const fileName of targetFiles) { moduleFiles.add(fileName); } } if (moduleFiles.size > 0) { moduleEntry.packages.set(root, moduleFiles); } } } } } function summarizeSubPackages(metas) { const descriptors = metas.map((meta) => { const root = meta.subPackage.root ?? ""; return { root, independent: Boolean(meta.subPackage.independent), name: meta.subPackage.name }; }).filter((descriptor) => descriptor.root); descriptors.sort((a, b) => a.root.localeCompare(b.root)); return descriptors; } async function analyzeSubpackages(ctx) { const { configService, scanService, buildService } = ctx; if (!configService || !scanService || !buildService) { throw new Error("analyzeSubpackages requires configService, scanService and buildService to be initialized"); } await scanService.loadAppEntry(); const subPackageMetas = scanService.loadSubPackages(); const subPackageRoots = /* @__PURE__ */ new Set(); const independentRoots = /* @__PURE__ */ new Set(); for (const meta of subPackageMetas) { const root = meta.subPackage.root; if (root) { subPackageRoots.add(root); if (meta.subPackage.independent) { independentRoots.add(root); } } } const classifierContext = { subPackageRoots, independentRoots }; const analysisConfig = configService.merge( void 0, createSharedBuildConfig(configService, scanService), { build: { write: false, watch: null } } ); const mainResult = await build(analysisConfig); const mainOutputs = Array.isArray(mainResult) ? mainResult : [mainResult]; const packages = /* @__PURE__ */ new Map(); const modules = /* @__PURE__ */ new Map(); for (const output of mainOutputs) { processOutput(output, "main", ctx, classifierContext, packages, modules); } for (const root of independentRoots) { const output = buildService.getIndependentOutput(root); processOutput(output, "independent", ctx, classifierContext, packages, modules); } expandVirtualModulePlacements(modules, packages, classifierContext); return { packages: summarizePackages(packages), modules: summarizeModules(modules), subPackages: summarizeSubPackages(subPackageMetas) }; } // src/cli/analyze/dashboard.ts init_esm_shims(); import process2 from "process"; import fs2 from "fs-extra"; import { createServer } from "vite"; // src/packagePaths.ts init_esm_shims(); import { dirname, join } from "path"; import { fileURLToPath } from "url"; import fs from "fs-extra"; function findPackageRoot(from) { let current = from; while (true) { if (fs.existsSync(join(current, "package.json"))) { return current; } const parent = dirname(current); if (parent === current) { break; } current = parent; } throw new Error("\u65E0\u6CD5\u5B9A\u4F4D weapp-vite \u5305\u6839\u76EE\u5F55\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u8DEF\u5F84\u3002"); } var CURRENT_DIR = dirname(fileURLToPath(import.meta.url)); var PACKAGE_ROOT = findPackageRoot(CURRENT_DIR); var ANALYZE_DASHBOARD_ROOT = join(PACKAGE_ROOT, "modules/analyze-dashboard"); // src/cli/analyze/dashboard.ts var ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_ANALYZE_RESULT__"; function resolveDashboardRoot() { if (fs2.existsSync(ANALYZE_DASHBOARD_ROOT)) { return { root: ANALYZE_DASHBOARD_ROOT }; } throw new Error( "[weapp-vite analyze] \u672A\u627E\u5230\u4EEA\u8868\u76D8\u4EA7\u7269\uFF0C\u8BF7\u5148\u6267\u884C `pnpm --filter weapp-vite run build:dashboard` \u751F\u6210\u3002" ); } function createAnalyzeHtmlPlugin(state, onServerInstance) { return { name: "weapp-vite-analyze-html", transformIndexHtml(html) { return { html, tags: [ { tag: "script", children: `window.${ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.current)}`, injectTo: "head-prepend" } ] }; }, configureServer(server) { onServerInstance(server); } }; } async function waitForServerExit(server) { let resolved = false; const cleanup = async () => { if (resolved) { return; } resolved = true; try { await server.close(); } catch (error) { logger_default.error(error); } }; const signals = ["SIGINT", "SIGTERM"]; await new Promise((resolvePromise) => { const resolveOnce = async () => { await cleanup(); signals.forEach((signal) => { process2.removeListener(signal, resolveOnce); }); resolvePromise(); }; signals.forEach((signal) => { process2.once(signal, resolveOnce); }); server.httpServer?.once("close", resolveOnce); }); } async function startAnalyzeDashboard(result, options) { const { root } = resolveDashboardRoot(); const state = { current: result }; let serverRef; const plugins = [ createAnalyzeHtmlPlugin(state, (server2) => { serverRef = server2; }) ]; const server = await createServer({ root, clearScreen: false, appType: "spa", publicDir: false, plugins, server: { host: "127.0.0.1", port: 0 }, logLevel: "error" }); await server.listen(); serverRef ??= server; server.printUrls(); const urls = (() => { const resolved = server.resolvedUrls; if (!resolved) { return []; } return [ ...resolved.local ?? [], ...resolved.network ?? [] ]; })(); const waitPromise = waitForServerExit(server); if (serverRef?.ws) { serverRef.ws.send({ type: "custom", event: "weapp-analyze:update", data: state.current }); } const handle = { async update(nextResult) { state.current = nextResult; if (serverRef) { serverRef.ws.send({ type: "custom", event: "weapp-analyze:update", data: nextResult }); } }, waitForExit: () => waitPromise, close: async () => { await server.close(); }, urls }; if (options?.watch) { logger_default.info("\u5206\u6790\u4EEA\u8868\u76D8\u5DF2\u542F\u52A8\uFF08\u5B9E\u65F6\u6A21\u5F0F\uFF09\uFF0C\u6309 Ctrl+C \u9000\u51FA\u3002"); for (const url of handle.urls) { logger_default.info(`\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8\uFF1A${url}`); } void waitPromise; return handle; } logger_default.info("\u5206\u6790\u4EEA\u8868\u76D8\u5DF2\u542F\u52A8\uFF08\u9759\u6001\u6A21\u5F0F\uFF09\uFF0C\u6309 Ctrl+C \u9000\u51FA\u3002"); for (const url of handle.urls) { logger_default.info(`\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8\uFF1A${url}`); } await waitPromise; } // src/cli/options.ts init_esm_shims(); function filterDuplicateOptions(options) { for (const [key, value] of Object.entries(options)) { if (Array.isArray(value)) { options[key] = value[value.length - 1]; } } } function resolveConfigFile(options) { if (typeof options.config === "string") { return options.config; } if (typeof options.c === "string") { return options.c; } } function convertBase(value) { if (value === 0) { return ""; } return value; } function coerceBooleanOption(value) { if (value === void 0) { return void 0; } if (typeof value === "boolean") { return value; } if (typeof value === "string") { const normalized = value.trim().toLowerCase(); if (normalized === "") { return true; } if (normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") { return false; } if (normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes") { return true; } return true; } if (typeof value === "number") { return value !== 0; } return Boolean(value); } // src/cli/runtime.ts init_esm_shims(); function logRuntimeTarget(targets) { logger_default.info(`\u76EE\u6807\u5E73\u53F0\uFF1A${targets.label}`); } function resolveRuntimeTargets(options) { const rawPlatform = typeof options.platform === "string" ? options.platform : typeof options.p === "string" ? options.p : void 0; if (!rawPlatform) { return { runMini: true, runWeb: false, mpPlatform: DEFAULT_MP_PLATFORM, label: DEFAULT_MP_PLATFORM }; } const normalized = normalizeMiniPlatform(rawPlatform); if (!normalized) { return { runMini: true, runWeb: false, mpPlatform: DEFAULT_MP_PLATFORM, label: DEFAULT_MP_PLATFORM }; } if (normalized === "h5" || normalized === "web") { return { runMini: false, runWeb: true, mpPlatform: void 0, label: normalized === "h5" ? "h5" : "web" }; } const mpPlatform = resolveMiniPlatform(normalized); if (mpPlatform) { return { runMini: true, runWeb: false, mpPlatform, label: mpPlatform }; } logger_default.warn(`\u672A\u8BC6\u522B\u7684\u5E73\u53F0 "${rawPlatform}"\uFF0C\u5DF2\u56DE\u9000\u5230 ${DEFAULT_MP_PLATFORM}`); return { runMini: true, runWeb: false, mpPlatform: DEFAULT_MP_PLATFORM, label: DEFAULT_MP_PLATFORM }; } function createInlineConfig(mpPlatform) { if (!mpPlatform) { return void 0; } return { weapp: { platform: mpPlatform } }; } // src/cli/commands/analyze.ts function printAnalysisSummary(result) { const packageLabelMap = /* @__PURE__ */ new Map(); const packageModuleSet = /* @__PURE__ */ new Map(); for (const pkg of result.packages) { packageLabelMap.set(pkg.id, pkg.label); } for (const module of result.modules) { for (const pkgRef of module.packages) { const set = packageModuleSet.get(pkgRef.packageId) ?? /* @__PURE__ */ new Set(); set.add(module.id); packageModuleSet.set(pkgRef.packageId, set); } } logger_default.success("\u5206\u5305\u5206\u6790\u5B8C\u6210"); for (const pkg of result.packages) { const chunkCount = pkg.files.filter((file) => file.type === "chunk").length; const assetCount = pkg.files.length - chunkCount; const moduleCount = packageModuleSet.get(pkg.id)?.size ?? 0; logger_default.info(`- ${pkg.label}\uFF1A${chunkCount} \u4E2A\u6A21\u5757\u4EA7\u7269\uFF0C${assetCount} \u4E2A\u8D44\u6E90\uFF0C\u8986\u76D6 ${moduleCount} \u4E2A\u6E90\u7801\u6A21\u5757`); } if (result.subPackages.length > 0) { logger_default.info("\u5206\u5305\u914D\u7F6E\uFF1A"); for (const descriptor of result.subPackages) { const segments = [descriptor.root]; if (descriptor.name) { segments.push(`\u522B\u540D\uFF1A${descriptor.name}`); } if (descriptor.independent) { segments.push("\u72EC\u7ACB\u6784\u5EFA"); } logger_default.info(`- ${segments.join("\uFF0C")}`); } } const duplicates = result.modules.filter((module) => module.packages.length > 1); if (duplicates.length === 0) { logger_default.info("\u672A\u68C0\u6D4B\u5230\u8DE8\u5305\u590D\u7528\u7684\u6E90\u7801\u6A21\u5757\u3002"); return; } logger_default.info(`\u8DE8\u5305\u590D\u7528/\u590D\u5236\u6E90\u7801\u5171 ${duplicates.length} \u9879\uFF1A`); const limit = 10; const entries = duplicates.slice(0, limit); for (const module of entries) { const placements = module.packages.map((pkgRef) => { const label = packageLabelMap.get(pkgRef.packageId) ?? pkgRef.packageId; return `${label} \u2192 ${pkgRef.files.join(", ")}`; }).join("\uFF1B"); logger_default.info(`- ${module.source} (${module.sourceType})\uFF1A${placements}`); } if (duplicates.length > limit) { logger_default.info(`- \u2026\u5176\u4F59 ${duplicates.length - limit} \u9879\u8BF7\u4F7F\u7528 \`weapp-vite analyze --json\` \u67E5\u770B`); } } function registerAnalyzeCommand(cli2) { cli2.command("analyze [root]", "analyze \u4E24\u7AEF\u5305\u4F53\u4E0E\u6E90\u7801\u6620\u5C04").option("--json", `[boolean] \u8F93\u51FA JSON \u7ED3\u679C`).option("--output <file>", `[string] \u5C06\u5206\u6790\u7ED3\u679C\u5199\u5165\u6307\u5B9A\u6587\u4EF6\uFF08JSON\uFF09`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).action(async (root, options) => { filterDuplicateOptions(options); const configFile = resolveConfigFile(options); const targets = resolveRuntimeTargets(options); logRuntimeTarget(targets); if (!targets.runMini) { logger_default.warn("\u5F53\u524D\u547D\u4EE4\u4EC5\u652F\u6301\u5C0F\u7A0B\u5E8F\u5E73\u53F0\uFF0C\u8BF7\u901A\u8FC7 --platform weapp \u6307\u5B9A\u76EE\u6807\u3002"); return; } if (targets.runWeb) { logger_default.warn("\u5206\u6790\u547D\u4EE4\u6682\u4E0D\u652F\u6301 Web \u5E73\u53F0\uFF0C\u5C06\u5FFD\u7565\u76F8\u5173\u914D\u7F6E\u3002"); } const inlineConfig = createInlineConfig(targets.mpPlatform); try { const ctx = await createCompilerContext({ cwd: root, mode: options.mode ?? "production", configFile, inlineConfig }); const result = await analyzeSubpackages(ctx); const outputJson = coerceBooleanOption(options.json); const outputOption = typeof options.output === "string" ? options.output.trim() : ""; let writtenPath; if (outputOption) { const configService = ctx.configService; const baseDir = configService?.cwd ?? process3.cwd(); const resolvedOutputPath = path2.isAbsolute(outputOption) ? outputOption : path2.resolve(baseDir, outputOption); await fs3.ensureDir(path2.dirname(resolvedOutputPath)); await fs3.writeFile(resolvedOutputPath, `${JSON.stringify(result, null, 2)} `, "utf8"); const relativeOutput = configService ? configService.relativeCwd(resolvedOutputPath) : resolvedOutputPath; logger_default.success(`\u5206\u6790\u7ED3\u679C\u5DF2\u5199\u5165 ${relativeOutput}`); writtenPath = resolvedOutputPath; } if (outputJson) { if (!writtenPath) { process3.stdout.write(`${JSON.stringify(result, null, 2)} `); } } else { printAnalysisSummary(result); await startAnalyzeDashboard(result); } } catch (error) { logger_default.error(error); process3.exitCode = 1; } }); } // src/cli/commands/build.ts init_esm_shims(); // src/cli/logBuildAppFinish.ts init_esm_shims(); // ../../node_modules/.pnpm/package-manager-detector@1.6.0/node_modules/package-manager-detector/dist/commands.mjs init_esm_shims(); function dashDashArg(agent, agentCommand) { return (args) => { if (args.length > 1) { return [agent, agentCommand, args[0], "--", ...args.slice(1)]; } else { return [agent, agentCommand, args[0]]; } }; } function denoExecute() { return (args) => { return ["deno", "run", `npm:${args[0]}`, ...args.slice(1)]; }; } var npm = { "agent": ["npm", 0], "run": dashDashArg("npm", "run"), "install": ["npm", "i", 0], "frozen": ["npm", "ci", 0], "global": ["npm", "i", "-g", 0], "add": ["npm", "i", 0], "upgrade": ["npm", "update", 0], "upgrade-interactive": null, "dedupe": ["npm", "dedupe", 0], "execute": ["npx", 0], "execute-local": ["npx", 0], "uninstall": ["npm", "uninstall", 0], "global_uninstall": ["npm", "uninstall", "-g", 0] }; var yarn = { "agent": ["yarn", 0], "run": ["yarn", "run", 0], "install": ["yarn", "install", 0], "frozen": ["yarn", "install", "--frozen-lockfile", 0], "global": ["yarn", "global", "add", 0], "add": ["yarn", "add", 0], "upgrade": ["yarn", "upgrade", 0], "upgrade-interactive": ["yarn", "upgrade-interactive", 0], "dedupe": null, "execute": ["npx", 0], "execute-local": dashDashArg("yarn", "exec"), "uninstall": ["yarn", "remove", 0], "global_uninstall": ["yarn", "global", "remove", 0] }; var yarnBerry = { ...yarn, "frozen": ["yarn", "install", "--immutable", 0], "upgrade": ["yarn", "up", 0], "upgrade-interactive": ["yarn", "up", "-i", 0], "dedupe": ["yarn", "dedupe", 0], "execute": ["yarn", "dlx", 0], "execute-local": ["yarn", "exec", 0], // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821 "global": ["npm", "i", "-g", 0], "global_uninstall": ["npm", "uninstall", "-g", 0] }; var pnpm = { "agent": ["pnpm", 0], "run": ["pnpm", "run", 0], "install": ["pnpm", "i", 0], "frozen": ["pnpm", "i", "--frozen-lockfile", 0], "global": ["pnpm", "add", "-g", 0], "add": ["pnpm", "add", 0], "upgrade": ["pnpm", "update", 0], "upgrade-interactive": ["pnpm", "update", "-i", 0], "dedupe": ["pnpm", "dedupe", 0], "execute": ["pnpm", "dlx", 0], "execute-local": ["pnpm", "exec", 0], "uninstall": ["pnpm", "remove", 0], "global_uninstall": ["pnpm", "remove", "--global", 0] }; var bun = { "agent": ["bun", 0], "run": ["bun", "run", 0], "install": ["bun", "install", 0], "frozen": ["bun", "install", "--frozen-lockfile", 0], "global": ["bun", "add", "-g", 0], "add": ["bun", "add", 0], "upgrade": ["bun", "update", 0], "upgrade-interactive": ["bun", "update", "-i", 0], "dedupe": null, "execute": ["bun", "x", 0], "execute-local": ["bun", "x", 0], "uninstall": ["bun", "remove", 0], "global_uninstall": ["bun", "remove", "-g", 0] }; var deno = { "agent": ["deno", 0], "run": ["deno", "task", 0], "install": ["deno", "install", 0], "frozen": ["deno", "install", "--frozen", 0], "global": ["deno", "install", "-g", 0], "add": ["deno", "add", 0], "upgrade": ["deno", "outdated", "--update", 0], "upgrade-interactive": ["deno", "outdated", "--update", 0], "dedupe": null, "execute": denoExecute(), "execute-local": ["deno", "task", "--eval", 0], "uninstall": ["deno", "remove", 0], "global_uninstall": ["deno", "uninstall", "-g", 0] }; var COMMANDS = { "npm": npm, "yarn": yarn, "yarn@berry": yarnBerry, "pnpm": pnpm, // pnpm v6.x or below "pnpm@6": { ...pnpm, run: dashDashArg("pnpm", "run") }, "bun": bun, "deno": deno }; function resolveCommand(agent, command, args) { const value = COMMANDS[agent][command]; return constructCommand(value, args); } function constructCommand(value, args) { if (value == null) return null; const list = typeof value === "function" ? value(args) : value.flatMap((v) => { if (typeof v === "number") return args; return [v]; }); return { command: list[0], args: list.slice(1) }; } // src/cli/logBuildAppFinish.ts var logBuildAppFinishOnlyShowOnce = false; function logBuildAppFinish(configService, webServer, options = {}) { if (logBuildAppFinishOnlyShowOnce) { return; } const { skipMini = false, skipWeb = false } = options; if (skipMini) { if (webServer) { const urls = webServer.resolvedUrls; const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : []; if (candidates.length > 0) { logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A"); for (const url of candidates) { logger_default.info(` \u279C ${url}`); } } else { logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8"); } } else { logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8"); } logBuildAppFinishOnlyShowOnce = true; return; } const { command, args } = resolveCommand( configService.packageManager.agent, "run", ["open"] ) ?? { command: "npm", args: ["run", "open"] }; const devCommand = `${command} ${args.join(" ")}`; logger_default.success("\u5E94\u7528\u6784\u5EFA\u5B8C\u6210\uFF01\u9884\u89C8\u65B9\u5F0F ( `2` \u79CD\u9009\u5176\u4E00\u5373\u53EF)\uFF1A"); logger_default.info(`\u6267\u884C \`${devCommand}\` \u53EF\u4EE5\u76F4\u63A5\u5728 \`\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\` \u91CC\u6253\u5F00\u5F53\u524D\u5E94\u7528`); logger_default.info("\u6216\u624B\u52A8\u6253\u5F00\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\uFF0C\u5BFC\u5165\u6839\u76EE\u5F55(`project.config.json` \u6587\u4EF6\u6240\u5728\u7684\u76EE\u5F55)\uFF0C\u5373\u53EF\u9884\u89C8\u6548\u679C"); if (!skipWeb && webServer) { const urls = webServer.resolvedUrls; const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : []; if (candidates.length > 0) { logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A"); for (const url of candidates) { logger_default.info(` \u279C ${url}`); } } else { logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8"); } } logBuildAppFinishOnlyShowOnce = true; } // src/cli/openIde.ts init_esm_shims(); import { parse } from "weapp-ide-cli"; async function openIde() { try { await parse(["open", "-p"]); } catch (error) { logger_default.error(error); } } // src/cli/commands/build.ts function registerBuildCommand(cli2) { cli2.command("build [root]", "build fo