weapp-vite 6.11.3 → 6.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -85,6 +85,39 @@ function handleClick() {
85
85
  - Vite 插件识别 weapp-vite 宿主:https://vite.icebreaker.top/guide/vite-plugin-host
86
86
  - MCP 集成使用指南:[docs/mcp.md](./docs/mcp.md)
87
87
 
88
+ ## DevTools 日志桥接
89
+
90
+ `weapp-vite` 现在支持把微信开发者工具里的小程序 `console` 输出桥接到当前终端。
91
+
92
+ 默认行为:
93
+
94
+ - `weapp.forwardConsole` 默认是 `enabled: 'auto'`
95
+ - 当检测到当前运行环境是 AI 终端时,`weapp-vite dev --open` 会自动尝试附加日志桥
96
+ - 也可以手动进入持续监听模式
97
+
98
+ 配置示例:
99
+
100
+ ```ts
101
+ import { defineConfig } from 'weapp-vite/config'
102
+
103
+ export default defineConfig({
104
+ weapp: {
105
+ forwardConsole: {
106
+ enabled: 'auto',
107
+ logLevels: ['log', 'info', 'warn', 'error'],
108
+ unhandledErrors: true,
109
+ },
110
+ },
111
+ })
112
+ ```
113
+
114
+ 手动启动持续监听:
115
+
116
+ ```sh
117
+ weapp-vite ide logs
118
+ weapp-vite ide logs --open
119
+ ```
120
+
88
121
  ## CLI 中调用 weapp-ide-cli
89
122
 
90
123
  `weapp-vite` 内置了对 `weapp-ide-cli` 的透传能力,除了 `dev/build/open/init/generate/analyze/npm` 等原生命令外,其它 IDE 相关命令都可以直接调用:
@@ -101,6 +134,7 @@ weapp-vite navigate pages/index/index --project ./dist/build/mp-weixin
101
134
  ```sh
102
135
  weapp-vite ide preview --project ./dist/build/mp-weixin
103
136
  weapp-vite ide config show
137
+ weapp-vite ide logs --open
104
138
  ```
105
139
 
106
140
  ## CLI 启动 MCP
@@ -1,6 +1,4 @@
1
- import { i as getCompilerContext } from "./createContext-DzgL8nmB.mjs";
2
- import "./logger-gutcwWKE.mjs";
3
- import "./file-D6dnM58g.mjs";
1
+ import { i as getCompilerContext } from "./createContext-BzGZK60x.mjs";
4
2
  //#region src/auto-routes.ts
5
3
  const ROUTE_RUNTIME_OVERRIDE_KEY = Symbol.for("weapp-vite.route-runtime");
6
4
  function createGetter(resolver) {
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { c as normalizeMiniPlatform, d as SHARED_CHUNK_VIRTUAL_PREFIX, f as resolveWeappConfigFile, g as isPathInside, h as createCjsConfigLoadError, l as resolveMiniPlatform, m as getProjectConfigFileName, n as syncProjectSupportFiles, o as formatBytes, p as checkRuntime, r as syncManagedTsconfigBootstrapFiles, s as DEFAULT_MP_PLATFORM, t as createCompilerContext, u as createSharedBuildConfig } from "./createContext-DzgL8nmB.mjs";
1
+ import { c as normalizeMiniPlatform, d as SHARED_CHUNK_VIRTUAL_PREFIX, f as resolveWeappConfigFile, g as isPathInside, h as createCjsConfigLoadError, l as resolveMiniPlatform, m as getProjectConfigFileName, n as syncProjectSupportFiles, o as formatBytes, p as checkRuntime, r as syncManagedTsconfigBootstrapFiles, s as DEFAULT_MP_PLATFORM, t as createCompilerContext, u as createSharedBuildConfig } from "./createContext-BzGZK60x.mjs";
2
2
  import { r as logger_default, t as colors } from "./logger-gutcwWKE.mjs";
3
- import { f as VERSION } from "./file-D6dnM58g.mjs";
3
+ import { f as VERSION } from "./file-CHBdQW3o.mjs";
4
4
  import { resolveWeappMcpConfig, startWeappViteMcpServer } from "./mcp.mjs";
5
5
  import { defu } from "@weapp-core/shared";
6
6
  import path, { posix } from "pathe";
@@ -8,12 +8,15 @@ import fs from "fs-extra";
8
8
  import process from "node:process";
9
9
  import { build, createServer, loadConfigFromFile } from "vite";
10
10
  import { getPackageInfoSync } from "local-pkg";
11
+ import { execFile } from "node:child_process";
11
12
  import { Buffer } from "node:buffer";
12
13
  import fs$1 from "node:fs";
13
14
  import { cac } from "cac";
14
15
  import { resolveCommand } from "package-manager-detector/commands";
15
- import { formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, parse, waitForRetryKeypress } from "weapp-ide-cli";
16
+ import { promisify } from "node:util";
17
+ import { formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, getConfig, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, parse, startForwardConsole, waitForRetryKeypress } from "weapp-ide-cli";
16
18
  import { generateJs, generateJson, generateWxml, generateWxss } from "@weapp-core/schematics";
19
+ import { determineAgent } from "@vercel/detect-agent";
17
20
  import { initConfig } from "@weapp-core/init";
18
21
  //#region src/analyze/subpackages/classifier.ts
19
22
  const VIRTUAL_MODULE_INDICATOR = "\0";
@@ -759,12 +762,71 @@ function logBuildPackageSizeReport(options) {
759
762
  }
760
763
  //#endregion
761
764
  //#region src/cli/openIde.ts
765
+ const execFileAsync = promisify(execFile);
762
766
  async function openIde(platform, projectPath) {
763
767
  const argv = ["open", "-p"];
764
768
  if (projectPath) argv.push(projectPath);
765
769
  if (platform === "alipay") argv.push("--platform", platform);
766
770
  await runWechatIdeOpenWithRetry(argv);
767
771
  }
772
+ async function closeIde() {
773
+ const config = await getConfig();
774
+ const cliPath = config.cliPath?.trim() ? config.cliPath : null;
775
+ try {
776
+ await parse(["close"]);
777
+ return true;
778
+ } catch (error) {
779
+ if (isWechatIdeLoginRequiredError(error)) try {
780
+ await runWechatIdeOpenWithRetry(["close"]);
781
+ return true;
782
+ } catch (retryError) {
783
+ logger_default.error(retryError);
784
+ }
785
+ else {
786
+ logger_default.warn("微信开发者工具 CLI close 执行失败,尝试回退为系统级关闭。");
787
+ logger_default.error(error);
788
+ }
789
+ if (await closeIdeByAppleScript()) {
790
+ logger_default.info("已回退为系统级关闭微信开发者工具。");
791
+ return true;
792
+ }
793
+ if (await closeIdeByProcessKill(cliPath)) {
794
+ logger_default.info("已回退为进程级关闭微信开发者工具。");
795
+ return true;
796
+ }
797
+ return false;
798
+ }
799
+ }
800
+ /**
801
+ * @description 解析 IDE 相关命令所需的平台、项目目录与配置上下文。
802
+ */
803
+ async function resolveIdeCommandContext(options) {
804
+ const cwd = options.cwd ?? process.cwd();
805
+ let platform = options.platform;
806
+ let projectPath = options.projectPath;
807
+ if (!platform || !projectPath) try {
808
+ const ctx = await createCompilerContext({
809
+ cwd,
810
+ mode: options.mode ?? "development",
811
+ configFile: options.configFile,
812
+ inlineConfig: createInlineConfig(platform),
813
+ cliPlatform: options.cliPlatform
814
+ });
815
+ platform ??= ctx.configService.platform;
816
+ if (!projectPath) projectPath = resolveIdeProjectRoot(ctx.configService.mpDistRoot, ctx.configService.cwd);
817
+ return {
818
+ platform,
819
+ projectPath,
820
+ weappViteConfig: ctx.configService.weappViteConfig,
821
+ mpDistRoot: ctx.configService.mpDistRoot
822
+ };
823
+ } catch {}
824
+ if (!projectPath && platform === "alipay") projectPath = resolveIdeProjectRoot("dist/alipay/dist", cwd);
825
+ return {
826
+ platform,
827
+ projectPath
828
+ };
829
+ }
768
830
  /**
769
831
  * @description 执行 IDE 打开流程,并在登录失效时允许按键重试。
770
832
  */
@@ -789,15 +851,41 @@ async function runWechatIdeOpenWithRetry(argv) {
789
851
  logger_default.info(colors.bold(colors.green("正在重试连接微信开发者工具...")));
790
852
  }
791
853
  }
854
+ async function closeIdeByAppleScript() {
855
+ if (process.platform !== "darwin") return false;
856
+ const appName = process.env.WEAPP_DEVTOOLS_APP_NAME || "wechatwebdevtools";
857
+ try {
858
+ await execFileAsync("osascript", ["-e", `tell application "${appName}" to quit`]);
859
+ return true;
860
+ } catch {
861
+ return false;
862
+ }
863
+ }
864
+ async function closeIdeByProcessKill(cliPath) {
865
+ if (!cliPath) return false;
866
+ const appContentsRoot = cliPath.includes(".app/") ? cliPath.slice(0, cliPath.indexOf(".app/") + 4) : path.dirname(path.dirname(cliPath));
867
+ try {
868
+ await execFileAsync("pkill", ["-f", appContentsRoot]);
869
+ return true;
870
+ } catch {
871
+ return false;
872
+ }
873
+ }
792
874
  /**
793
875
  * @description 根据 mpDistRoot 推导 IDE 项目目录(目录内应包含 project/mini 配置)
794
876
  */
795
877
  function resolveIdeProjectPath(mpDistRoot) {
796
878
  if (!mpDistRoot || !mpDistRoot.trim()) return;
797
879
  const parent = path.dirname(mpDistRoot);
798
- if (!parent || parent === ".") return;
880
+ if (!parent || parent === "." || parent === "/") return;
799
881
  return parent;
800
882
  }
883
+ /**
884
+ * @description 结合 mpDistRoot 与配置根目录解析最终 IDE 项目目录。
885
+ */
886
+ function resolveIdeProjectRoot(mpDistRoot, cwd) {
887
+ return resolveIdeProjectPath(mpDistRoot) ?? cwd;
888
+ }
801
889
  //#endregion
802
890
  //#region src/cli/commands/build.ts
803
891
  function registerBuildCommand(cli) {
@@ -858,6 +946,13 @@ function isSassEmbeddedChild(handle) {
858
946
  return Boolean(handle && typeof handle === "object" && "kill" in handle && "spawnfile" in handle && typeof handle.spawnfile === "string" && handle.spawnfile?.includes("sass-embedded"));
859
947
  }
860
948
  //#endregion
949
+ //#region src/cli/commands/close.ts
950
+ function registerCloseCommand(cli) {
951
+ cli.command("close", "close Wechat DevTools").action(async () => {
952
+ if (!await closeIde()) throw new Error("关闭微信开发者工具失败。");
953
+ });
954
+ }
955
+ //#endregion
861
956
  //#region src/schematics.ts
862
957
  function composePath(outDir, filename) {
863
958
  return `${outDir}${outDir ? "/" : ""}${filename}`;
@@ -1026,6 +1121,213 @@ function registerGenerateCommand(cli) {
1026
1121
  });
1027
1122
  }
1028
1123
  //#endregion
1124
+ //#region src/cli/forwardConsole.ts
1125
+ const DEFAULT_FORWARD_CONSOLE_LEVELS = [
1126
+ "log",
1127
+ "info",
1128
+ "warn",
1129
+ "error"
1130
+ ];
1131
+ let activeForwardConsoleSession;
1132
+ const FORWARD_CONSOLE_RETRY_DELAY_MS = 1e3;
1133
+ const FORWARD_CONSOLE_RETRY_TIMES = 5;
1134
+ /**
1135
+ * @description 解析 forwardConsole 配置,并在 auto 模式下检测 AI 终端。
1136
+ */
1137
+ async function resolveForwardConsoleOptions(config) {
1138
+ const rawConfig = config?.forwardConsole;
1139
+ const defaults = {
1140
+ logLevels: DEFAULT_FORWARD_CONSOLE_LEVELS,
1141
+ unhandledErrors: true
1142
+ };
1143
+ if (rawConfig === false) return {
1144
+ enabled: false,
1145
+ ...defaults
1146
+ };
1147
+ if (rawConfig === true) return {
1148
+ enabled: true,
1149
+ ...defaults
1150
+ };
1151
+ const normalizedConfig = rawConfig ?? {};
1152
+ const enabledMode = normalizedConfig.enabled ?? "auto";
1153
+ const logLevels = normalizedConfig.logLevels?.length ? normalizedConfig.logLevels : defaults.logLevels;
1154
+ const unhandledErrors = normalizedConfig.unhandledErrors ?? defaults.unhandledErrors;
1155
+ if (enabledMode === true) return {
1156
+ enabled: true,
1157
+ logLevels,
1158
+ unhandledErrors
1159
+ };
1160
+ if (enabledMode === false) return {
1161
+ enabled: false,
1162
+ logLevels,
1163
+ unhandledErrors
1164
+ };
1165
+ const agentResult = await detectAgent();
1166
+ return {
1167
+ enabled: agentResult.isAgent,
1168
+ agentName: agentResult.agentName,
1169
+ logLevels,
1170
+ unhandledErrors
1171
+ };
1172
+ }
1173
+ /**
1174
+ * @description 在 weapp 开发态按需启动控制台转发。
1175
+ */
1176
+ async function maybeStartForwardConsole(options) {
1177
+ if (options.platform !== "weapp") return false;
1178
+ const projectPath = resolveIdeProjectPath(options.mpDistRoot) ?? options.cwd;
1179
+ if (!projectPath) return false;
1180
+ const resolved = await resolveForwardConsoleOptions(options.weappViteConfig);
1181
+ if (!resolved.enabled) return false;
1182
+ if (activeForwardConsoleSession) return true;
1183
+ try {
1184
+ activeForwardConsoleSession = await startForwardConsoleBridge({
1185
+ agentName: resolved.agentName,
1186
+ projectPath,
1187
+ logLevels: resolved.logLevels,
1188
+ unhandledErrors: resolved.unhandledErrors,
1189
+ onReadyMessage: "[forwardConsole] 已连接微信开发者工具日志"
1190
+ });
1191
+ return true;
1192
+ } catch (error) {
1193
+ activeForwardConsoleSession = void 0;
1194
+ const message = error instanceof Error ? error.message : String(error);
1195
+ logger_default.warn(`[forwardConsole] 启动失败,回退到普通 IDE 打开流程:${message}`);
1196
+ return false;
1197
+ }
1198
+ }
1199
+ /**
1200
+ * @description 统一启动 DevTools 日志桥,并在 IDE 刚启动时做短暂重试。
1201
+ */
1202
+ async function startForwardConsoleBridge(options) {
1203
+ return await withForwardConsoleRetry(async () => {
1204
+ return await startForwardConsole({
1205
+ projectPath: options.projectPath,
1206
+ logLevels: options.logLevels,
1207
+ unhandledErrors: options.unhandledErrors,
1208
+ onReady: () => {
1209
+ const suffix = options.agentName ? `(AI 终端:${options.agentName})` : "";
1210
+ logger_default.info(`${options.onReadyMessage}${suffix}`);
1211
+ },
1212
+ onLog: (event) => {
1213
+ const line = `[mini:${event.level}] ${event.message}`;
1214
+ if (event.level === "error") {
1215
+ logger_default.error(line);
1216
+ return;
1217
+ }
1218
+ if (event.level === "warn") {
1219
+ logger_default.warn(line);
1220
+ return;
1221
+ }
1222
+ if (event.level === "info") {
1223
+ logger_default.info(line);
1224
+ return;
1225
+ }
1226
+ logger_default.log(line);
1227
+ }
1228
+ });
1229
+ });
1230
+ }
1231
+ async function detectAgent() {
1232
+ try {
1233
+ const result = await determineAgent();
1234
+ return {
1235
+ isAgent: result.isAgent,
1236
+ agentName: result.isAgent ? result.agent.name : void 0
1237
+ };
1238
+ } catch {
1239
+ return {
1240
+ isAgent: false,
1241
+ agentName: void 0
1242
+ };
1243
+ }
1244
+ }
1245
+ async function withForwardConsoleRetry(runner) {
1246
+ let lastError;
1247
+ for (let attempt = 0; attempt <= FORWARD_CONSOLE_RETRY_TIMES; attempt++) try {
1248
+ return await runner();
1249
+ } catch (error) {
1250
+ lastError = error;
1251
+ if (!isDevtoolsPortNotReadyError(error) || attempt === FORWARD_CONSOLE_RETRY_TIMES) break;
1252
+ await sleep(FORWARD_CONSOLE_RETRY_DELAY_MS);
1253
+ }
1254
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
1255
+ }
1256
+ function isDevtoolsPortNotReadyError(error) {
1257
+ return error instanceof Error && error.message === "DEVTOOLS_HTTP_PORT_ERROR";
1258
+ }
1259
+ function sleep(ms) {
1260
+ return new Promise((resolve) => setTimeout(resolve, ms));
1261
+ }
1262
+ //#endregion
1263
+ //#region src/cli/commands/ide.ts
1264
+ /**
1265
+ * @description 注册 IDE 相关子命令。
1266
+ */
1267
+ function registerIdeCommand(cli) {
1268
+ cli.command("ide [action] [root]", "forward Wechat DevTools console logs to terminal").option("-o, --open", "[boolean] open ide before attaching log bridge").option("-p, --platform <platform>", "[string] target platform (weapp | h5)").option("--project-config <path>", "[string] project config path (miniprogram only)").action(async (action, root, options) => {
1269
+ await runIdeCommand(action, root, options);
1270
+ });
1271
+ }
1272
+ /**
1273
+ * @description 执行 ide 子命令。
1274
+ */
1275
+ async function runIdeCommand(action, root, options) {
1276
+ if (action !== "logs") throw new Error(`未知 ide 子命令: ${action ?? "(empty)"}`);
1277
+ filterDuplicateOptions(options);
1278
+ const configFile = resolveConfigFile(options);
1279
+ const targets = resolveRuntimeTargets(options);
1280
+ const resolved = await resolveIdeCommandContext({
1281
+ configFile,
1282
+ mode: options.mode ?? "development",
1283
+ platform: targets.mpPlatform,
1284
+ projectPath: root,
1285
+ cliPlatform: targets.rawPlatform
1286
+ });
1287
+ if (resolved.platform !== "weapp") throw new Error("`weapp-vite ide logs` 当前仅支持微信小程序平台。");
1288
+ if (!resolved.projectPath) throw new Error("无法解析微信开发者工具项目目录,请显式传入 root 或检查 project.config.json。");
1289
+ if (options.open) await openIde(resolved.platform, resolved.projectPath);
1290
+ const forwardConsoleOptions = await resolveForwardConsoleOptions({
1291
+ ...resolved.weappViteConfig,
1292
+ forwardConsole: resolved.weappViteConfig?.forwardConsole === false ? { enabled: true } : {
1293
+ ...typeof resolved.weappViteConfig?.forwardConsole === "object" ? resolved.weappViteConfig.forwardConsole : {},
1294
+ enabled: true
1295
+ }
1296
+ });
1297
+ const session = await startForwardConsoleBridge({
1298
+ projectPath: resolved.projectPath,
1299
+ agentName: void 0,
1300
+ logLevels: forwardConsoleOptions.logLevels,
1301
+ unhandledErrors: forwardConsoleOptions.unhandledErrors,
1302
+ onReadyMessage: "[forwardConsole] 已进入持续监听模式,按 Ctrl+C 退出。"
1303
+ });
1304
+ await waitForTermination(async () => {
1305
+ logger_default.info("[forwardConsole] 正在关闭日志桥接...");
1306
+ await session.close();
1307
+ });
1308
+ }
1309
+ async function waitForTermination(cleanup) {
1310
+ await new Promise((resolve) => {
1311
+ const signals = ["SIGINT", "SIGTERM"];
1312
+ let cleaning = false;
1313
+ const teardown = async () => {
1314
+ if (cleaning) return;
1315
+ cleaning = true;
1316
+ for (const signal of signals) process.off(signal, handlers.get(signal));
1317
+ await cleanup();
1318
+ resolve();
1319
+ };
1320
+ const handlers = /* @__PURE__ */ new Map();
1321
+ for (const signal of signals) {
1322
+ const handler = () => {
1323
+ teardown();
1324
+ };
1325
+ handlers.set(signal, handler);
1326
+ process.on(signal, handler);
1327
+ }
1328
+ });
1329
+ }
1330
+ //#endregion
1029
1331
  //#region src/cli/commands/init.ts
1030
1332
  function registerInitCommand(cli) {
1031
1333
  cli.command("init").action(async () => {
@@ -1076,21 +1378,14 @@ function registerOpenCommand(cli) {
1076
1378
  filterDuplicateOptions(options);
1077
1379
  const configFile = resolveConfigFile(options);
1078
1380
  const targets = resolveRuntimeTargets(options);
1079
- let platform = targets.mpPlatform;
1080
- let projectPath = root;
1081
- if (targets.runMini && (!platform || !projectPath)) try {
1082
- const ctx = await createCompilerContext({
1083
- cwd: process.cwd(),
1084
- mode: options.mode ?? "development",
1085
- configFile,
1086
- inlineConfig: createInlineConfig(platform),
1087
- cliPlatform: targets.rawPlatform
1088
- });
1089
- platform ??= ctx.configService.platform;
1090
- if (!projectPath) projectPath = resolveIdeProjectPath(ctx.configService.mpDistRoot);
1091
- } catch {}
1092
- if (!projectPath && platform === "alipay") projectPath = resolveIdeProjectPath("dist/alipay/dist");
1093
- await openIde(platform, projectPath);
1381
+ const { platform, projectPath, mpDistRoot } = await resolveIdeCommandContext({
1382
+ configFile,
1383
+ mode: options.mode ?? "development",
1384
+ platform: targets.mpPlatform,
1385
+ projectPath: root,
1386
+ cliPlatform: targets.rawPlatform
1387
+ });
1388
+ await openIde(platform, projectPath ?? resolveIdeProjectRoot(mpDistRoot, process.cwd()));
1094
1389
  });
1095
1390
  }
1096
1391
  //#endregion
@@ -1186,7 +1481,14 @@ function registerServeCommand(cli) {
1186
1481
  }
1187
1482
  if (targets.runMini) logBuildAppFinish(configService, webServer, { skipWeb: !targets.runWeb });
1188
1483
  else if (targets.runWeb) logBuildAppFinish(configService, webServer, { skipMini: true });
1189
- if (options.open && targets.runMini) await openIde(configService.platform, resolveIdeProjectPath(configService.mpDistRoot));
1484
+ if (options.open && targets.runMini) {
1485
+ if (!await maybeStartForwardConsole({
1486
+ platform: configService.platform,
1487
+ mpDistRoot: configService.mpDistRoot,
1488
+ cwd: configService.cwd,
1489
+ weappViteConfig: configService.weappViteConfig
1490
+ })) await openIde(configService.platform, resolveIdeProjectRoot(configService.mpDistRoot, configService.cwd));
1491
+ }
1190
1492
  if (analyzeHandle) await analyzeHandle.waitForExit();
1191
1493
  });
1192
1494
  }
@@ -1238,6 +1540,7 @@ const WEAPP_VITE_NATIVE_COMMANDS = new Set([
1238
1540
  "dev",
1239
1541
  "serve",
1240
1542
  "build",
1543
+ "close",
1241
1544
  "analyze",
1242
1545
  "init",
1243
1546
  "open",
@@ -1255,6 +1558,7 @@ async function tryRunIdeCommand(argv) {
1255
1558
  const command = argv[0];
1256
1559
  if (!command) return false;
1257
1560
  if (command === "ide") {
1561
+ if (argv[1] === "logs") return false;
1258
1562
  await parse(argv.slice(1));
1259
1563
  return true;
1260
1564
  }
@@ -1349,8 +1653,9 @@ try {
1349
1653
  });
1350
1654
  } catch {}
1351
1655
  cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, { type: [convertBase] }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
1352
- registerServeCommand(cli);
1656
+ registerIdeCommand(cli);
1353
1657
  registerBuildCommand(cli);
1658
+ registerCloseCommand(cli);
1354
1659
  registerAnalyzeCommand(cli);
1355
1660
  registerInitCommand(cli);
1356
1661
  registerOpenCommand(cli);
@@ -1358,11 +1663,13 @@ registerPrepareCommand(cli);
1358
1663
  registerNpmCommand(cli);
1359
1664
  registerGenerateCommand(cli);
1360
1665
  registerMcpCommand(cli);
1666
+ registerServeCommand(cli);
1361
1667
  cli.help();
1362
1668
  cli.version(VERSION);
1363
1669
  const skipManagedTsconfigBootstrapCommands = new Set([
1364
1670
  "g",
1365
1671
  "generate",
1672
+ "ide",
1366
1673
  "init",
1367
1674
  "mcp",
1368
1675
  "npm"
@@ -1371,10 +1678,17 @@ function resolveManagedTsconfigBootstrapRoot(args) {
1371
1678
  const [firstArg, secondArg] = args;
1372
1679
  if (!firstArg || firstArg === "--help" || firstArg === "-h" || firstArg === "--version" || firstArg === "-v") return;
1373
1680
  if (firstArg.startsWith("-")) return process.cwd();
1374
- if (skipManagedTsconfigBootstrapCommands.has(firstArg)) return;
1681
+ if (skipManagedTsconfigBootstrapCommands.has(firstArg)) {
1682
+ if (firstArg === "ide") {
1683
+ const thirdArg = args[2];
1684
+ if (secondArg === "logs" && thirdArg && !thirdArg.startsWith("-")) return path.resolve(thirdArg);
1685
+ }
1686
+ return;
1687
+ }
1375
1688
  if ([
1376
1689
  "analyze",
1377
1690
  "build",
1691
+ "close",
1378
1692
  "dev",
1379
1693
  "open",
1380
1694
  "prepare",
@@ -12,8 +12,8 @@ import { WrapPluginOptions } from "vite-plugin-performance";
12
12
  import PQueue from "p-queue";
13
13
  import { ComputedDefinitions as ComputedDefinitions$1, MethodDefinitions as MethodDefinitions$1, PageLayoutMeta, Ref, WevuDefaults } from "wevu";
14
14
  import { App, App as App$1, Component, Component as Component$1, GenerateType, Page, Page as Page$1, Plugin, Sitemap, Sitemap as Sitemap$1, Theme, Theme as Theme$1 } from "@weapp-core/schematics";
15
- import { CompilerOptions } from "typescript";
16
15
  import { WeappWebPluginOptions } from "@weapp-vite/web/plugin";
16
+ import { CompilerOptions } from "typescript";
17
17
  import { DetectResult } from "package-manager-detector";
18
18
 
19
19
  //#region src/pluginHost.d.ts
@@ -500,12 +500,45 @@ interface WeappDebugConfig {
500
500
  watchFiles?: (watchFiles: string[], subPackageMeta?: SubPackageMetaValue) => void;
501
501
  resolveId?: (id: string, subPackageMeta?: SubPackageMetaValue) => void;
502
502
  load?: (id: string, subPackageMeta?: SubPackageMetaValue) => void;
503
+ vueTransformTiming?: (timing: {
504
+ id: string;
505
+ isPage: boolean;
506
+ totalMs: number;
507
+ stages: Record<string, number>;
508
+ }) => void;
503
509
  inspect?: WrapPluginOptions;
504
510
  }
511
+ type WeappForwardConsoleLogLevel = 'debug' | 'log' | 'info' | 'warn' | 'error';
512
+ /**
513
+ * @description 微信开发者工具日志转发配置。
514
+ */
515
+ interface WeappForwardConsoleConfig {
516
+ /**
517
+ * 是否启用日志转发。
518
+ * - `true`: 始终开启
519
+ * - `false`: 始终关闭
520
+ * - `'auto'`: 仅在检测到 AI 终端时开启
521
+ */
522
+ enabled?: boolean | 'auto';
523
+ /**
524
+ * 允许转发的日志级别。
525
+ */
526
+ logLevels?: WeappForwardConsoleLogLevel[];
527
+ /**
528
+ * 是否同时转发未捕获异常。
529
+ */
530
+ unhandledErrors?: boolean;
531
+ }
505
532
  /**
506
533
  * @description weapp-vite 主配置
507
534
  */
508
535
  interface WeappViteConfig {
536
+ /**
537
+ * 开发态是否在启动构建前清空输出目录。
538
+ * 开发态默认 `true`,设置为 `false` 可跳过每次 dev 启动前的全量输出目录清理。
539
+ * 生产构建始终会清空输出目录。
540
+ */
541
+ cleanOutputsInDev?: boolean;
509
542
  /**
510
543
  * 应用入口目录(`app.json` 所在目录)。
511
544
  */
@@ -563,6 +596,7 @@ interface WeappViteConfig {
563
596
  routeRules?: WeappRouteRules;
564
597
  injectWeapi?: boolean | WeappInjectWeapiConfig;
565
598
  mcp?: boolean | WeappMcpConfig;
599
+ forwardConsole?: boolean | WeappForwardConsoleConfig;
566
600
  chunks?: ChunksConfig;
567
601
  json?: JsonConfig;
568
602
  }
@@ -1416,7 +1450,6 @@ type UserConfigFnObjectPlain<T extends UserConfig$1 = UserConfig$1> = (env: Conf
1416
1450
  type UserConfigFnObject<T extends UserConfig$1 = UserConfig$1> = (env: ConfigEnv) => T;
1417
1451
  type UserConfigFnPromise<T extends UserConfig$1 = UserConfig$1> = (env: ConfigEnv) => Promise<T>;
1418
1452
  type UserConfigFn<T extends UserConfig$1 = UserConfig$1> = (env: ConfigEnv) => T | Promise<T>;
1419
- type UserConfigLoose = UserConfig$1 & Record<string, any>;
1420
1453
  type UserConfigExport<T extends UserConfig$1 = UserConfig$1> = T | Promise<T> | UserConfigFnNoEnv<T> | UserConfigFnObject<T> | UserConfigFnPromise<T> | UserConfigFn<T>;
1421
1454
  declare module 'vite' {
1422
1455
  interface UserConfig {
@@ -1431,11 +1464,8 @@ declare module 'vite' {
1431
1464
  */
1432
1465
  declare function defineConfig(config: UserConfig$1): UserConfig$1;
1433
1466
  declare function defineConfig(config: Promise<UserConfig$1>): Promise<UserConfig$1>;
1434
- declare function defineConfig(config: UserConfigFnNoEnvPlain): UserConfigFnNoEnvPlain;
1435
- declare function defineConfig(config: UserConfigFnNoEnv): UserConfigFnNoEnv;
1436
1467
  declare function defineConfig(config: UserConfigFnObjectPlain): UserConfigFnObjectPlain;
1437
- declare function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise;
1438
1468
  declare function defineConfig(config: UserConfigFn): UserConfigFn;
1439
- declare function defineConfig(config: UserConfigLoose): UserConfigLoose;
1469
+ declare function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise;
1440
1470
  //#endregion
1441
- export { WeappDebugConfig as $, ResolvedAlias as $t, Ref as A, GenerateExtensionsOptions as At, BindingErrorLike as B, GenerateTemplateScope as Bt, LoadConfigOptions as C, WeappViteHostMeta as Cn, AliasOptions as Ct, MethodDefinitions$1 as D, isWeappViteHost as Dn, CopyGlobs as Dt, InlineConfig$1 as E, createWeappViteHostMeta as En, ChunksConfig as Et, RolldownPlugin as F, GenerateTemplateContext as Ft, EntryJsonFragment as G, JsonMergeFunction as Gt, BaseEntry as H, JsFormat as Ht, RolldownPluginOption as I, GenerateTemplateEntry as It, ScanComponentItem as J, MpPlatform as Jt, PageEntry as K, JsonMergeStage as Kt, RolldownWatchOptions as L, GenerateTemplateFactory as Lt, RolldownBuild as M, GenerateFilenamesOptions as Mt, RolldownOptions as N, GenerateOptions as Nt, Plugin$1 as O, resolveWeappViteHostMeta as On, CopyOptions as Ot, RolldownOutput$1 as P, GenerateTemplate as Pt, UserConfig$2 as Q, NpmSubPackageConfig as Qt, RolldownWatcher$1 as R, GenerateTemplateFileSource as Rt, CompilerContext as S, WEAPP_VITE_HOST_NAME as Sn, Alias as St, ConfigEnv$1 as T, applyWeappViteHostMeta as Tn, BuildNpmPackageMeta as Tt, ComponentEntry as U, JsonConfig as Ut, AppEntry as V, GenerateTemplatesConfig as Vt, Entry as W, JsonMergeContext as Wt, ProjectConfig as X, NpmMainPackageConfig as Xt, WxmlDep as Y, NpmBuildOptions as Yt, SubPackageMetaValue as Z, NpmPluginPackageConfig as Zt, definePageJson as _, WeappManagedNodeTsconfigConfig as _n, WeappSubPackageConfig as _t, UserConfigFnNoEnvPlain as a, SubPackageStyleConfigEntry as an, HandleWxmlOptions as at, ChangeEvent as b, WeappManagedTypeScriptConfig as bn, WeappWevuConfig as bt, UserConfigFnPromise as c, SubPackageStyleScope as cn, WeappAutoRoutesConfig as ct, Component$1 as d, WeappLibDtsOptions as dn, WeappHmrConfig as dt, SharedChunkDynamicImports as en, WeappViteConfig as et, Page$1 as f, WeappLibEntryContext as fn, WeappInjectWeapiConfig as ft, defineComponentJson as g, WeappManagedAppTsconfigConfig as gn, WeappRouteRules as gt, defineAppJson as h, WeappLibVueTscOptions as hn, WeappRouteRule as ht, UserConfigFnNoEnv as i, SubPackage as in, EnhanceWxmlOptions as it, ResolvedConfig as j, GenerateFileType as jt, PluginOption as k, GenerateDirsOptions as kt, defineConfig as l, WeappLibComponentJson as ln, WeappAutoRoutesInclude as lt, Theme$1 as m, WeappLibInternalDtsOptions as mn, WeappNpmConfig as mt, UserConfigExport as n, SharedChunkOverride as nn, AutoImportComponentsOption as nt, UserConfigFnObject as o, SubPackageStyleConfigObject as on, MultiPlatformConfig as ot, Sitemap$1 as p, WeappLibFileName as pn, WeappMcpConfig as pt, ComponentsMap as q, JsonMergeStrategy as qt, UserConfigFn as r, SharedChunkStrategy as rn, EnhanceOptions as rt, UserConfigFnObjectPlain as s, SubPackageStyleEntry as sn, ScanWxmlOptions as st, UserConfig$1 as t, SharedChunkMode as tn, AutoImportComponents as tt, App$1 as u, WeappLibConfig as un, WeappAutoRoutesIncludePattern as ut, defineSitemapJson as v, WeappManagedServerTsconfigConfig as vn, WeappVueConfig as vt, ComputedDefinitions$1 as w, WeappViteRuntime as wn, AlipayNpmMode as wt, WeappVitePluginApi as x, WeappWebConfig as xn, WeappWorkerConfig as xt, defineThemeJson as y, WeappManagedSharedTsconfigConfig as yn, WeappVueTemplateConfig as yt, ViteDevServer$1 as z, GenerateTemplateInlineSource as zt };
1471
+ export { WeappDebugConfig as $, NpmPluginPackageConfig as $t, Ref as A, resolveWeappViteHostMeta as An, CopyOptions as At, BindingErrorLike as B, GenerateTemplateFileSource as Bt, LoadConfigOptions as C, WeappWebConfig as Cn, WeappWorkerConfig as Ct, MethodDefinitions$1 as D, applyWeappViteHostMeta as Dn, BuildNpmPackageMeta as Dt, InlineConfig$1 as E, WeappViteRuntime as En, AlipayNpmMode as Et, RolldownPlugin as F, GenerateOptions as Ft, EntryJsonFragment as G, JsonConfig as Gt, BaseEntry as H, GenerateTemplateScope as Ht, RolldownPluginOption as I, GenerateTemplate as It, ScanComponentItem as J, JsonMergeStage as Jt, PageEntry as K, JsonMergeContext as Kt, RolldownWatchOptions as L, GenerateTemplateContext as Lt, RolldownBuild as M, GenerateExtensionsOptions as Mt, RolldownOptions as N, GenerateFileType as Nt, Plugin$1 as O, createWeappViteHostMeta as On, ChunksConfig as Ot, RolldownOutput$1 as P, GenerateFilenamesOptions as Pt, UserConfig$2 as Q, NpmMainPackageConfig as Qt, RolldownWatcher$1 as R, GenerateTemplateEntry as Rt, CompilerContext as S, WeappManagedTypeScriptConfig as Sn, WeappWevuConfig as St, ConfigEnv$1 as T, WeappViteHostMeta as Tn, AliasOptions as Tt, ComponentEntry as U, GenerateTemplatesConfig as Ut, AppEntry as V, GenerateTemplateInlineSource as Vt, Entry as W, JsFormat as Wt, ProjectConfig as X, MpPlatform as Xt, WxmlDep as Y, JsonMergeStrategy as Yt, SubPackageMetaValue as Z, NpmBuildOptions as Zt, definePageJson as _, WeappLibVueTscOptions as _n, WeappRouteRule as _t, UserConfigFnNoEnvPlain as a, SharedChunkStrategy as an, EnhanceOptions as at, ChangeEvent as b, WeappManagedServerTsconfigConfig as bn, WeappVueConfig as bt, UserConfigFnPromise as c, SubPackageStyleConfigObject as cn, MultiPlatformConfig as ct, Component$1 as d, WeappLibComponentJson as dn, WeappAutoRoutesInclude as dt, NpmSubPackageConfig as en, WeappForwardConsoleConfig as et, Page$1 as f, WeappLibConfig as fn, WeappAutoRoutesIncludePattern as ft, defineComponentJson as g, WeappLibInternalDtsOptions as gn, WeappNpmConfig as gt, defineAppJson as h, WeappLibFileName as hn, WeappMcpConfig as ht, UserConfigFnNoEnv as i, SharedChunkOverride as in, AutoImportComponentsOption as it, ResolvedConfig as j, GenerateDirsOptions as jt, PluginOption as k, isWeappViteHost as kn, CopyGlobs as kt, defineConfig as l, SubPackageStyleEntry as ln, ScanWxmlOptions as lt, Theme$1 as m, WeappLibEntryContext as mn, WeappInjectWeapiConfig as mt, UserConfigExport as n, SharedChunkDynamicImports as nn, WeappViteConfig as nt, UserConfigFnObject as o, SubPackage as on, EnhanceWxmlOptions as ot, Sitemap$1 as p, WeappLibDtsOptions as pn, WeappHmrConfig as pt, ComponentsMap as q, JsonMergeFunction as qt, UserConfigFn as r, SharedChunkMode as rn, AutoImportComponents as rt, UserConfigFnObjectPlain as s, SubPackageStyleConfigEntry as sn, HandleWxmlOptions as st, UserConfig$1 as t, ResolvedAlias as tn, WeappForwardConsoleLogLevel as tt, App$1 as u, SubPackageStyleScope as un, WeappAutoRoutesConfig as ut, defineSitemapJson as v, WeappManagedAppTsconfigConfig as vn, WeappRouteRules as vt, ComputedDefinitions$1 as w, WEAPP_VITE_HOST_NAME as wn, Alias as wt, WeappVitePluginApi as x, WeappManagedSharedTsconfigConfig as xn, WeappVueTemplateConfig as xt, defineThemeJson as y, WeappManagedNodeTsconfigConfig as yn, WeappSubPackageConfig as yt, ViteDevServer$1 as z, GenerateTemplateFactory as zt };
package/dist/config.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { Cn as WeappViteHostMeta, Dn as isWeappViteHost, En as createWeappViteHostMeta, On as resolveWeappViteHostMeta, Sn as WEAPP_VITE_HOST_NAME, Tn as applyWeappViteHostMeta, _ as definePageJson, a as UserConfigFnNoEnvPlain, c as UserConfigFnPromise, d as Component, et as WeappViteConfig, f as Page, g as defineComponentJson, h as defineAppJson, i as UserConfigFnNoEnv, l as defineConfig, m as Theme, n as UserConfigExport, o as UserConfigFnObject, p as Sitemap, r as UserConfigFn, s as UserConfigFnObjectPlain, t as UserConfig, u as App, v as defineSitemapJson, wn as WeappViteRuntime, y as defineThemeJson } from "./config-mYISi4CS.mjs";
1
+ import { An as resolveWeappViteHostMeta, Dn as applyWeappViteHostMeta, En as WeappViteRuntime, On as createWeappViteHostMeta, Tn as WeappViteHostMeta, _ as definePageJson, a as UserConfigFnNoEnvPlain, c as UserConfigFnPromise, d as Component, f as Page, g as defineComponentJson, h as defineAppJson, i as UserConfigFnNoEnv, kn as isWeappViteHost, l as defineConfig, m as Theme, n as UserConfigExport, nt as WeappViteConfig, o as UserConfigFnObject, p as Sitemap, r as UserConfigFn, s as UserConfigFnObjectPlain, t as UserConfig, u as App, v as defineSitemapJson, wn as WEAPP_VITE_HOST_NAME, y as defineThemeJson } from "./config-DHz3M7If.mjs";
2
2
  export { App, Component, Page, Sitemap, Theme, UserConfig, UserConfigExport, UserConfigFn, UserConfigFnNoEnv, UserConfigFnNoEnvPlain, UserConfigFnObject, UserConfigFnObjectPlain, UserConfigFnPromise, WEAPP_VITE_HOST_NAME, WeappViteConfig, WeappViteHostMeta, WeappViteRuntime, applyWeappViteHostMeta, createWeappViteHostMeta, defineAppJson, defineComponentJson, defineConfig, definePageJson, defineSitemapJson, defineThemeJson, isWeappViteHost, resolveWeappViteHostMeta };