vite.config.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import { createRequire } from "node:module";
  2. import { mkdirSync, writeFileSync } from "node:fs";
  3. import { dirname, extname, isAbsolute, resolve } from "node:path";
  4. import { pathToFileURL } from "node:url";
  5. import { defineConfig, loadEnv, type Plugin } from "vite";
  6. import react from "@vitejs/plugin-react";
  7. import tailwindcss from "@tailwindcss/vite";
  8. import { resolveZCodeEndpointOrigin } from "@zcode/shared/zcodeEndpoint";
  9. import { pdfJsCMapsPlugin } from "../ui/vite/pdfJsCMapsPlugin.js";
  10. import { getBuildMetadata } from "./scripts/build-metadata.mjs";
  11. import { resolveDesktopProductFlavor } from "./scripts/desktop-product-identity.mjs";
  12. // 动态加载仓库根的构建工具,避免配置打包后其 import.meta.dirname 被重定位到 desktop。
  13. // 构建期可选能力(ARMS、事件上报、自动更新),见 docs/desktop/build-time-optional-capabilities.md
  14. const { resolveBuildTimeConfig, createBuildTimeConfigDefines } = await import(
  15. pathToFileURL(resolve(__dirname, "../../scripts/build-time-config.mjs")).href
  16. );
  17. const buildTimeConfigDefines = createBuildTimeConfigDefines(
  18. await resolveBuildTimeConfig(process.env),
  19. );
  20. const buildMetadata = getBuildMetadata();
  21. const desktopRequire = createRequire(import.meta.url);
  22. interface IstanbulInstrumenter {
  23. instrumentSync(sourceCode: string, filename: string): string;
  24. lastFileCoverage(): unknown;
  25. lastSourceMap(): object | null;
  26. }
  27. interface IstanbulLibInstrument {
  28. createInstrumenter(options: {
  29. autoWrap: boolean;
  30. compact: boolean;
  31. coverageGlobalScope: string;
  32. coverageGlobalScopeFunc: boolean;
  33. esModules: boolean;
  34. parserPlugins: string[];
  35. preserveComments: boolean;
  36. produceSourceMap: boolean;
  37. }): IstanbulInstrumenter;
  38. }
  39. const { createInstrumenter } = desktopRequire("istanbul-lib-instrument") as IstanbulLibInstrument;
  40. function resolveInstalledPackageRoot(packageName: string): string {
  41. return dirname(desktopRequire.resolve(`${packageName}/package.json`));
  42. }
  43. export const desktopRendererDependencyAliases = {
  44. // pnpm hoisted/package-local 布局会随安装配置变化;硬编码 node_modules 子路径
  45. // 会让 Rolldown 依赖优化把 react/jsx-runtime 等入口解析到不存在的位置。
  46. // 通过 Node 解析真实安装根目录,既保留单 React runtime,又兼容不同 node-linker。
  47. react: resolveInstalledPackageRoot("react"),
  48. "react-dom": resolveInstalledPackageRoot("react-dom"),
  49. "lucide-react": resolveInstalledPackageRoot("lucide-react"),
  50. } as const;
  51. function resolveZCodeEnv(value: string | undefined): "test" | "production" {
  52. return value?.trim().toLowerCase() === "production" ? "production" : "test";
  53. }
  54. function createE2EUIRendererCoveragePlugin(repoRoot: string): Plugin {
  55. const sourceRoots = [
  56. resolve(repoRoot, "packages/ui/src"),
  57. resolve(repoRoot, "packages/desktop/src/renderer"),
  58. ].map(normalizePathForVite);
  59. const instrumenter = createInstrumenter({
  60. autoWrap: true,
  61. compact: false,
  62. coverageGlobalScope: "globalThis",
  63. coverageGlobalScopeFunc: false,
  64. esModules: true,
  65. parserPlugins: ["typescript", "jsx"],
  66. preserveComments: true,
  67. produceSourceMap: true,
  68. });
  69. const baselineCoverage: Record<string, unknown> = {};
  70. const baselinePath = resolve(
  71. repoRoot,
  72. "packages/desktop/out/renderer/e2e-coverage-baseline.json",
  73. );
  74. return {
  75. name: "zcode:e2e-ui-source-coverage",
  76. enforce: "pre",
  77. transform(sourceCode, id, options) {
  78. if (options?.ssr || id.startsWith("\0")) {
  79. return null;
  80. }
  81. const filename = stripViteRequestQuery(id);
  82. const absoluteFilename = isAbsolute(filename) ? filename : resolve(repoRoot, filename);
  83. const normalizedFilename = normalizePathForVite(absoluteFilename);
  84. if (!shouldInstrumentE2EUISource(normalizedFilename, sourceRoots)) {
  85. return null;
  86. }
  87. // post-transform 插桩依赖 Vite/React/esbuild 的合并 sourcemap,
  88. // 会把生成后的 JS 覆盖点反投影到 import、interface 等 TS 源码行上。
  89. // 这里先对原始 TS/TSX AST 插桩,再交给 Vite 编译,保证 coverage map 只包含真实运行时代码。
  90. const code = instrumenter.instrumentSync(sourceCode, normalizedFilename);
  91. baselineCoverage[normalizedFilename] = JSON.parse(
  92. JSON.stringify(instrumenter.lastFileCoverage()),
  93. );
  94. return {
  95. code,
  96. map: instrumenter.lastSourceMap(),
  97. };
  98. },
  99. closeBundle() {
  100. // 只读取页面 __coverage__ 会让从未加载的 lazy chunk 消失,分母被缩小。
  101. // coverage build 将完整 renderer graph 的零命中 map 留给 suite reporter 合并。
  102. mkdirSync(dirname(baselinePath), { recursive: true });
  103. writeFileSync(baselinePath, `${JSON.stringify(baselineCoverage, null, 2)}\n`, "utf-8");
  104. },
  105. };
  106. }
  107. function shouldInstrumentE2EUISource(filename: string, sourceRoots: string[]) {
  108. return (
  109. isCoverageSourceFile(filename) &&
  110. !filename.includes("/node_modules/") &&
  111. !isDeclarationFile(filename) &&
  112. !isTestSourceFile(filename) &&
  113. sourceRoots.some((sourceRoot) => isInsidePath(filename, sourceRoot))
  114. );
  115. }
  116. function isCoverageSourceFile(filename: string) {
  117. return [".cts", ".cjs", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"].includes(extname(filename));
  118. }
  119. function isDeclarationFile(filename: string) {
  120. return /\.d\.[cm]?ts$/u.test(filename);
  121. }
  122. function isTestSourceFile(filename: string) {
  123. return /\.(?:spec|test)\.[cm]?[jt]sx?$/u.test(filename);
  124. }
  125. function isInsidePath(filename: string, directory: string) {
  126. return filename === directory || filename.startsWith(`${directory}/`);
  127. }
  128. function normalizePathForVite(path: string) {
  129. return path.replaceAll("\\", "/");
  130. }
  131. function stripViteRequestQuery(id: string) {
  132. return id.split("?")[0] ?? id;
  133. }
  134. export default defineConfig(({ mode }) => {
  135. // `.env*` 只提供链接常量;当前产品环境由启动脚本或 CI 注入 ZCODE_ENV。
  136. const env = loadEnv(mode, "../..", "");
  137. const repoRoot = resolve(__dirname, "../..");
  138. const zcodeEnv = resolveZCodeEnv(env.ZCODE_ENV);
  139. // 安装包身份与后端环境分轴;renderer 用它决定是否展示更新入口。
  140. const zcodeProductFlavor = resolveDesktopProductFlavor({
  141. ...process.env,
  142. ...env,
  143. ZCODE_ENV: zcodeEnv,
  144. });
  145. const e2eCoverageEnabled =
  146. env.ZCODE_E2E_COVERAGE === "1" || process.env.ZCODE_E2E_COVERAGE === "1";
  147. const e2eStoreBridgeEnabled =
  148. env.VITE_ZCODE_E2E_STORE_BRIDGE === "1" || process.env.VITE_ZCODE_E2E_STORE_BRIDGE === "1";
  149. const zcodeEndpointOrigin = resolveZCodeEndpointOrigin({
  150. env: zcodeEnv,
  151. envBaseOrigin:
  152. env.ZCODE_BASE_URL ??
  153. env.ZCODE_ENDPOINT_ORIGIN ??
  154. (zcodeEnv === "production" ? env.ZCODE_PRODUCTION_BASE_URL : env.ZCODE_TEST_BASE_URL),
  155. });
  156. const codingPlanWebviewOrigin =
  157. env.VITE_CODING_PLAN_WEBVIEW_ORIGIN ?? process.env.VITE_CODING_PLAN_WEBVIEW_ORIGIN ?? "";
  158. const plugins = [
  159. ...(e2eCoverageEnabled ? [createE2EUIRendererCoveragePlugin(repoRoot)] : []),
  160. pdfJsCMapsPlugin(),
  161. react(),
  162. tailwindcss(),
  163. ];
  164. return {
  165. root: "src/renderer",
  166. plugins,
  167. resolve: {
  168. alias: {
  169. // 修复 UI 组件库中的 @ 别名解析失败。
  170. // 问题原因:desktop 会直接打包 packages/ui 的源码,但当前 Vite 配置不知道 @ 应该指向 packages/ui/src,
  171. // 导致 spinner、alert 等组件里的内部导入在构建时全部失效。
  172. // 这里在消费端补齐别名,比逐个改组件导入更稳,也能和 web 端保持一致。
  173. "@": resolve(__dirname, "../ui/src"),
  174. ...desktopRendererDependencyAliases,
  175. // Recharts 通过 d3-shape 读取 d3-path 的 Path 导出;hoisted node_modules
  176. // 里可能残留 d3-shape/node_modules/d3-path@1.x,Vite 预构建会优先命中旧包并报 Missing export。
  177. // 这里把 d3-path 固定到根部 3.x 入口,确保桌面端依赖优化和运行时解析一致。
  178. "d3-path": resolve(__dirname, "../../node_modules/d3-path/src/index.js"),
  179. },
  180. dedupe: ["react", "react-dom", "lucide-react"],
  181. },
  182. server: { port: 5174, strictPort: true },
  183. define: {
  184. __ZCODE_VERSION__: JSON.stringify(buildMetadata.appVersion),
  185. __ZCODE_COMMIT__: JSON.stringify(buildMetadata.buildCommitId),
  186. __ZCODE_BUILD_TIME__: JSON.stringify(buildMetadata.buildTime),
  187. __ZCODE_ENV__: JSON.stringify(zcodeEnv),
  188. __ZCODE_PRODUCT_FLAVOR__: JSON.stringify(zcodeProductFlavor),
  189. ...buildTimeConfigDefines,
  190. __ZCODE_LOCAL_DEVELOPMENT_RUNTIME__: JSON.stringify(mode !== "production"),
  191. "import.meta.env.VITE_ZCODE_BASE_URL": JSON.stringify(zcodeEndpointOrigin),
  192. // 兼容旧 renderer 读取名;新代码统一读 VITE_ZCODE_BASE_URL。
  193. "import.meta.env.VITE_ZCODE_ENDPOINT_ORIGIN": JSON.stringify(zcodeEndpointOrigin),
  194. "import.meta.env.VITE_CODING_PLAN_WEBVIEW_ORIGIN": JSON.stringify(codingPlanWebviewOrigin),
  195. "import.meta.env.VITE_REWARDS_WEBVIEW_ORIGIN": JSON.stringify(env.VITE_REWARDS_WEBVIEW_ORIGIN ?? process.env.VITE_REWARDS_WEBVIEW_ORIGIN ?? ""),
  196. // Bugfix: E2E store bridge 只能由 WDIO 专用变量打开,避免把 ZCODE_ENV=test 产品环境误当成测试运行态。
  197. "import.meta.env.VITE_ZCODE_E2E_STORE_BRIDGE": JSON.stringify(
  198. e2eStoreBridgeEnabled ? "1" : "",
  199. ),
  200. },
  201. // Electron 用 file:// 协议加载页面,资源路径必须是相对路径,否则会 ERR_FILE_NOT_FOUND
  202. base: "./",
  203. worker: {
  204. rollupOptions: {
  205. // @pierre/diffs 的 worker 入口依赖 import 后注册 message 监听。
  206. // 它的 package sideEffects 漏声明会让生产 worker 子构建被摇成 0B;
  207. // 只关闭 worker 构建的摇树,避免影响主包。
  208. treeshake: false,
  209. },
  210. },
  211. build: {
  212. outDir: "../../out/renderer",
  213. emptyOutDir: true,
  214. // 生产包若直接暴露 sourceMappingURL,攻击者可在客户端侧还原业务源码。
  215. // 生产使用 hidden sourcemap:本地/发布流程保留 .map,不在产物里暴露映射入口。
  216. sourcemap: mode === "production" ? "hidden" : true,
  217. rollupOptions: {
  218. // 多入口:主窗口 + 进程监控 + CUA 权限拖拽浮窗
  219. input: {
  220. index: resolve(__dirname, "src/renderer/index.html"),
  221. "resource-manager": resolve(__dirname, "src/renderer/resource-manager.html"),
  222. "cua-permission-panel": resolve(__dirname, "src/renderer/cua-permission-panel.html"),
  223. // 插件 UI 沙箱的受信 shell,经 zcode-sandbox:// 提供
  224. "plugin-sandbox": resolve(__dirname, "src/renderer/plugin-sandbox.html"),
  225. },
  226. },
  227. },
  228. };
  229. });