electron-builder.config.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /* eslint-disable max-lines -- Electron Builder config keeps related packaging hooks together so build order stays explicit. */
  2. import { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
  3. import { readdir, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join, resolve } from "node:path";
  6. import { createRequire } from "node:module";
  7. import { HELPER_APP_NAME } from "@zcode/zcode-cua/broker/helperConstants";
  8. import { runCommand, runCommandAndReadStdout } from "../../scripts/spawn-command.mjs";
  9. import { loadBuiltinProviderConfig } from "../../scripts/builtin-provider-config.mjs";
  10. import { noticesFileName, stageElectronNotices } from "../../scripts/third-party-notices.mjs";
  11. import { resolveNativeSearchReleasePlan } from "../../scripts/native-search-tools-config.mjs";
  12. import { getBuildMetadata } from "./scripts/build-metadata.mjs";
  13. import { collectRuntimeModuleClosureEntries } from "./scripts/runtime-dependency-closure.mjs";
  14. import {
  15. resolvePackagedNodePtyPrebuildPath,
  16. restoreTargetNodePtyPrebuild,
  17. } from "./scripts/node-pty-package-assets.mjs";
  18. import { cleanupPackagedSourcemaps } from "./scripts/packaged-sourcemap-cleanup.mjs";
  19. import { getTargetPlatform } from "./scripts/target-platform.mjs";
  20. import {
  21. resolveDesktopArtifactSuffix,
  22. resolveDesktopProductIdentity,
  23. } from "./scripts/desktop-product-identity.mjs";
  24. import { createWindowsPowerShellSecurityArgs } from "./scripts/powershell-command.mjs";
  25. import { isSharpRequiredByComputerUse, verifyStagedSharp } from "./scripts/sharp-package-assets.mjs";
  26. import { isRealComputerUseProducerInstalled } from "./scripts/computer-use-producer.mjs";
  27. import { verifyStagedKoffi } from "./scripts/koffi-package-assets.mjs";
  28. import {
  29. finalizePackagedWindowsCuaHelper,
  30. resolveElectronBuilderWindowsTarget,
  31. } from "./scripts/windows-cua-helper-assets.mjs";
  32. import {
  33. findDesktopNativePackageViolations,
  34. createDesktopNativePackagePrunePatterns,
  35. parseAsarListWithPackState,
  36. } from "./scripts/desktop-native-package-policy.mjs";
  37. import {
  38. replaceAppAsarFromStaging,
  39. resolveUnpackPackageDirsFromAsarList,
  40. } from "./scripts/app-asar-repack.mjs";
  41. import {
  42. patchNsisInstallSectionFile,
  43. restoreNsisInstallSectionFileSync,
  44. } from "./scripts/patch-nsis-install-section.mjs";
  45. const buildMetadata = getBuildMetadata();
  46. const targetPlatform = getTargetPlatform();
  47. // 修复原因:Windows Chrome 导入入口已暂时隐藏,默认安装包不应继续携带、签名或校验原生 helper。
  48. // 代码和完整供应链保留在显式 opt-in 后,便于未来恢复而不影响当前发布流程。
  49. const shouldPackageWindowsBrowserImportHelper =
  50. targetPlatform.os === "win32" && process.env.ZCODE_ENABLE_WINDOWS_BROWSER_IMPORT === "1";
  51. const builtinProviderConfig = await loadBuiltinProviderConfig();
  52. const desktopProductIdentity = resolveDesktopProductIdentity({
  53. ...process.env,
  54. ZCODE_ENV: builtinProviderConfig.environment,
  55. });
  56. const nativeSearchReleasePlan = resolveNativeSearchReleasePlan({
  57. platform: targetPlatform.os,
  58. arch: targetPlatform.arch,
  59. });
  60. const workspaceRoot = resolve(import.meta.dirname, "../..");
  61. const desktopPackageRoot = import.meta.dirname;
  62. // Computer Use Helper(macOS .app、Windows runtime)只随真实 producer 打包;开源占位包下跳过随包资源与校验。
  63. const shouldPackageComputerUseHelper = isRealComputerUseProducerInstalled({ desktopPackageRoot });
  64. const HELPER_FILENAME = "zcode-browser-import-helper.exe";
  65. const runtimeModuleLookupRoots = [
  66. desktopPackageRoot,
  67. workspaceRoot,
  68. resolve(desktopPackageRoot, "node_modules", ".pnpm", "node_modules"),
  69. resolve(workspaceRoot, "node_modules", ".pnpm", "node_modules"),
  70. ];
  71. const desktopDistDir = process.env.ZCODE_DESKTOP_DIST_DIR || "dist";
  72. const bundledCuaHelperSource = resolve(
  73. desktopPackageRoot,
  74. "bundled-cua-helper",
  75. targetPlatform.arch,
  76. HELPER_APP_NAME,
  77. );
  78. const DEFAULT_ELECTRON_MIRROR = "https://npmmirror.com/mirrors/electron/";
  79. // `pnpm exec asar` 依赖 `.bin/asar`,但 @electron/asar 仅是 electron-builder 传递依赖时,
  80. // Linux CI(pnpm hoisted)往往解析不到该二进制,`asar list` 未运行即 exit 1。
  81. // 显式依赖 @electron/asar 并用 Node 直接执行 CLI,避免跨平台找不齐 shim。
  82. const requireFromConfig = createRequire(import.meta.url);
  83. let nsisInstallSectionPatched = false;
  84. let nsisInstallSectionOriginalSource = null;
  85. let nsisInstallSectionPath = null;
  86. const desktopElectronVersion = requireFromConfig("./package.json").devDependencies.electron;
  87. const asarCliPath = resolve(
  88. dirname(requireFromConfig.resolve("@electron/asar/package.json")),
  89. "bin",
  90. "asar.js",
  91. );
  92. const REQUIRED_ASAR_RUNTIME_MODULES = [
  93. "module-details-from-path",
  94. "@opentelemetry/api-logs",
  95. // Bugfix: telemetry 的 OTLP exporter 会在启动阶段加载 sdk-metrics。pnpm 开发态可从
  96. // workspace 根目录解析,但 electron-builder 不会稳定复制这条 hoisted 依赖,导致安装包启动即崩溃。
  97. // 将 sdk-metrics 作为闭包根注入,同时递归带齐它的 OpenTelemetry 运行时依赖。
  98. "@opentelemetry/sdk-metrics",
  99. // Bugfix:主进程的本地 TTFT / renderer 动作追踪导出器使用 OTLP proto 导出链。pnpm hoisted 布局下
  100. // electron-builder 会把 otlp-transformer 打进 app.asar,却漏拷其传递依赖 protobufjs,已安装应用启动即报
  101. // Cannot find module protobufjs/minimal(开源侧 3.14.0 arm64 DMG 实测复现)。以两个 proto exporter
  102. // 作为闭包根注入,递归带齐 otlp-transformer、protobufjs 与 @protobufjs/* 全链。
  103. "@opentelemetry/exporter-trace-otlp-proto",
  104. "@opentelemetry/exporter-metrics-otlp-proto",
  105. "pngjs",
  106. // Bugfix: @arms/rum-core 把 @babel/runtime 声明成 peerDependency,pnpm 安装时可由 peer 解析兜住,
  107. // 但 electron-builder 重打 app.asar 时不会因为 @arms/rum-electron 本体进包,就稳定把这个 peer 运行时一起带上。
  108. // 线上已出现安装包启动即报 Cannot find module '@babel/runtime/helpers/interopRequireDefault',
  109. // 这里显式把 @babel/runtime 作为闭包根注入,确保 ARMS 主进程埋点链路在生产包内可解析。
  110. "@babel/runtime",
  111. // Bugfix: @zcode/services 的代理连通性探测会动态 require("undici") 取 ProxyAgent。
  112. // tsup 虽然把 services 代码并进了主/host 产物,但不会把这个运行时 require 的包内联进去,
  113. // electron-builder 产物又可能漏掉 hoisted 的 undici,最终 mac 安装包启动即报 Cannot find module "undici"。
  114. // 这里把 undici 和其他兜底依赖一样强制注入 app.asar,避免用户在已安装应用里主进程直接崩溃。
  115. "undici",
  116. // node-forge 一直只写在 bundle.mjs 的校验名单里,靠 electron-builder 自己打进 app.asar;
  117. // 这与 yauzl 漏 pend 是同一类隐患——校验要求的模块必须有人负责补齐。node-forge 无子依赖,
  118. // 已在产物里时 afterPack 扫描会跳过它,不改变现有打包结果。
  119. "node-forge",
  120. // 2.7.0 起 services 新增反馈日志压缩链路并引入 yazl;2.6.0 没有这条启动期依赖,
  121. // pnpm hoisted 布局下 yazl 可能进了 app.asar,但子依赖 buffer-crc32 没有稳定随包进入产物;
  122. // 这里显式以 yazl 作为闭包根注入,让递归依赖收集把 ZIP 打包链路所需依赖一起补齐。
  123. "yazl",
  124. // yauzl 成为 desktop/services 的直接生产依赖后,pnpm list --prod 会把顶层 yauzl 节点
  125. // 去重成没有子依赖的空节点;electron-builder 的 pnpm collector 以先登记的空节点为准,
  126. // 跳过后面带完整子树的那个,于是 app.asar 里有 yauzl 却没有它的运行时依赖 pend,
  127. // 要到 bundle 校验阶段才报「缺少运行时依赖 pend」。这里以 yauzl 作为闭包根注入,
  128. // 与 bundle.mjs 的校验名单保持一致,让递归依赖收集把 pend 一起补进产物。
  129. "yauzl",
  130. // Bugfix: 飞书 SDK 被 desktop main/host 外置后,安装包运行时必须能从 app.asar 解析到它。
  131. // 这里显式注入 scoped 包,避免开发态正常、生产包启动时才报 Cannot find module。
  132. "@larksuiteoapi/node-sdk",
  133. // 生产态里 ssh2 虽然被打进 app.asar,但它的依赖链偶发被 electron-builder 漏拷。
  134. // 已出现线上报错 Cannot find module 'asn1'(Require stack: ssh2 keyParser)。
  135. // 这里把 ssh2 关键依赖链一起注入,避免远程 SSH 连接在已安装应用里因缺包直接失败。
  136. "asn1",
  137. "bcrypt-pbkdf",
  138. "tweetnacl",
  139. // electron-updater → builder-util-runtime → debug 运行时 require("ms")。
  140. // pnpm hoisted 布局下 electron-builder 偶发漏拷这个叶子依赖;3.4.0(ci/cua-v0.3.17 打的)
  141. // 已在线上触发安装包启动即报 Cannot find module 'ms'(Require stack: debug/src/common.js),
  142. // 自动更新链路直接崩。ms 是叶子包,显式注入即可让 debug 在 app.asar 内稳定解析。
  143. "ms",
  144. ];
  145. const WINDOWS_INSTALL_MANIFEST_NAME = ".zcode-install-manifest";
  146. async function writeWindowsInstallManifest(context) {
  147. if (context.electronPlatformName !== "win32") return;
  148. const root = context.appOutDir;
  149. const files = [];
  150. const visit = async (directory, relativeDirectory = "") => {
  151. for (const entry of await readdir(directory, { withFileTypes: true })) {
  152. const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
  153. const absolutePath = join(directory, entry.name);
  154. if (entry.isDirectory()) {
  155. await visit(absolutePath, relativePath);
  156. } else if (entry.isFile() || entry.isSymbolicLink()) {
  157. files.push(relativePath.replaceAll("/", "\\"));
  158. }
  159. }
  160. };
  161. await visit(root);
  162. files.sort();
  163. await writeFile(join(root, WINDOWS_INSTALL_MANIFEST_NAME), `${files.join("\r\n")}\r\n`, "utf8");
  164. }
  165. function resolveElectronDownloadMirror(env = process.env) {
  166. const existingMirror =
  167. env.ZCODE_ELECTRON_RUNTIME_MIRROR ||
  168. env.NPM_CONFIG_ELECTRON_MIRROR ||
  169. env.npm_config_electron_mirror ||
  170. env.npm_package_config_electron_mirror ||
  171. env.ELECTRON_MIRROR;
  172. if (existingMirror?.trim()) {
  173. return existingMirror.trim();
  174. }
  175. return DEFAULT_ELECTRON_MIRROR;
  176. }
  177. function assertPackagedCuaHelper(context) {
  178. if (targetPlatform.os !== "darwin" || !shouldPackageComputerUseHelper) return;
  179. const appPath = join(
  180. context.appOutDir,
  181. `${desktopProductIdentity.productName}.app`,
  182. "Contents",
  183. "Resources",
  184. "cua-helper",
  185. HELPER_APP_NAME,
  186. );
  187. if (!existsSync(appPath)) {
  188. throw new Error(`Packaged ZCode is missing bundled Computer Use Helper: ${appPath}`);
  189. }
  190. }
  191. const shouldEnableWindowsVsign =
  192. process.platform === "win32" && process.env.ZCODE_ENABLE_WINDOWS_SIGN === "1";
  193. const commandStdoutMaxBuffer = 64 * 1024 * 1024;
  194. // 产物后缀只标记后端环境(_TEST);身份靠 productName 区分,生产后端的 Preview 包没有后缀。
  195. const desktopArtifactEnvSuffix = resolveDesktopArtifactSuffix(process.env);
  196. const PACKAGING_PRUNE_PATTERNS = [
  197. "!**/*.map",
  198. "!**/*.pdb",
  199. "!**/__tests__/**",
  200. "!**/test/**",
  201. "!**/tests/**",
  202. "!**/example/**",
  203. "!**/examples/**",
  204. "!**/README*",
  205. "!**/CHANGELOG*",
  206. "!**/CONTRIBUTING*",
  207. "!**/CODE_OF_CONDUCT*",
  208. "!**/SECURITY*",
  209. ];
  210. function buildDesktopArtifactName(platformName, extension = "${ext}") {
  211. // 测试环境产物必须和正式安装包文件名区分,避免上传、下载或人工验收时混用。
  212. return `\${productName}-\${version}-${platformName}-\${arch}${desktopArtifactEnvSuffix}.${extension}`;
  213. }
  214. function runAsarCommand(args) {
  215. runCommand(process.execPath, [asarCliPath, ...args], {
  216. cwd: import.meta.dirname,
  217. env: process.env,
  218. });
  219. }
  220. function runAsarCommandAndReadStdout(args) {
  221. return runCommandAndReadStdout(process.execPath, [asarCliPath, ...args], {
  222. cwd: import.meta.dirname,
  223. env: process.env,
  224. // app.asar 在当前桌面包体积较大,asar list 输出可能超过默认缓冲并触发 ENOBUFS。
  225. // 这里显式放大缓冲,避免“为了判断是否需要注入”反而把打包流程误判失败。
  226. maxBuffer: commandStdoutMaxBuffer,
  227. stdio: ["ignore", "pipe", "inherit"],
  228. });
  229. }
  230. function runTimedSync(label, fn) {
  231. const startMs = Date.now();
  232. console.log(`[ci][timer] ${label} start`);
  233. try {
  234. return fn();
  235. } finally {
  236. console.log(`[ci][timer] ${label} end duration_ms=${Date.now() - startMs}`);
  237. }
  238. }
  239. async function runTimedAsync(label, fn) {
  240. const startMs = Date.now();
  241. console.log(`[ci][timer] ${label} start`);
  242. try {
  243. return await fn();
  244. } finally {
  245. console.log(`[ci][timer] ${label} end duration_ms=${Date.now() - startMs}`);
  246. }
  247. }
  248. function resolveAppAsarPath(context) {
  249. if (context.electronPlatformName === "darwin") {
  250. const appName = `${context.packager?.appInfo?.productFilename ?? "ZCode"}.app`;
  251. return resolve(context.appOutDir, appName, "Contents", "Resources", "app.asar");
  252. }
  253. return resolve(context.appOutDir, "resources", "app.asar");
  254. }
  255. function resolvePackagedResourcesDir(context) {
  256. if (context.electronPlatformName === "darwin") {
  257. const appName = `${context.packager?.appInfo?.productFilename ?? "ZCode"}.app`;
  258. return resolve(context.appOutDir, appName, "Contents", "Resources");
  259. }
  260. return resolve(context.appOutDir, "resources");
  261. }
  262. function normalizeAsarEntry(entry) {
  263. return entry.trim().replaceAll("\\", "/");
  264. }
  265. function resolveMissingRuntimeModules(appAsarPath) {
  266. const asarEntries = runAsarCommandAndReadStdout(["list", appAsarPath])
  267. .split("\n")
  268. .map(normalizeAsarEntry)
  269. .filter(Boolean);
  270. const asarEntrySet = new Set(asarEntries);
  271. const runtimeModules = collectRuntimeModuleClosureEntries(
  272. REQUIRED_ASAR_RUNTIME_MODULES,
  273. runtimeModuleLookupRoots,
  274. );
  275. const resolvableRuntimeModules = runtimeModules.filter((entry) => {
  276. if (!entry.sourceModulePath) {
  277. // 不同平台/安装布局下,部分运行时依赖可能被裁剪或未落到本次打包工作区。
  278. // 之前这里直接在 copy 阶段抛错会中断整个平台出包;改为记录告警并跳过该模块,
  279. // 让 afterPack 只处理当前环境确实可解析的依赖,避免 CI 因单个可选依赖缺失全量失败。
  280. console.warn(
  281. `[afterPack] runtime module not found, skip injection: ${entry.moduleName}; searched=${runtimeModuleLookupRoots
  282. .map((lookupRoot) => resolve(lookupRoot, "node_modules", entry.moduleName))
  283. .join(", ")}`,
  284. );
  285. return false;
  286. }
  287. return true;
  288. });
  289. return resolvableRuntimeModules.filter((entry) => {
  290. // 落位路径由依赖闭包给出:同名多版本时,非提升版本会落到
  291. // `node_modules/<父包>/node_modules/<name>`。这里必须按落位路径判断,
  292. // 否则嵌套版本会被「同名包已存在」误判为齐全而漏注入。
  293. const moduleRoot = `/${entry.installRelativePath}`;
  294. if (asarEntrySet.has(moduleRoot)) {
  295. return false;
  296. }
  297. for (const asarEntry of asarEntrySet) {
  298. if (asarEntry.startsWith(`${moduleRoot}/`)) {
  299. return false;
  300. }
  301. }
  302. return true;
  303. });
  304. }
  305. /**
  306. * 读出当前 archive 的 unpack 布局,供重写时原样保留。
  307. * `--unpack-dir` 只能接收一个表达式,重写前先取快照、重写时一次传全,
  308. * 避免 afterPack 每重写一次就丢一层 electron-builder 原本的 unpack 结果。
  309. */
  310. function resolveCurrentUnpackDirs(appAsarPath) {
  311. if (!existsSync(appAsarPath)) {
  312. return [];
  313. }
  314. return runTimedSync("afterPack:scan-unpack-layout", () =>
  315. resolveUnpackPackageDirsFromAsarList(
  316. runAsarCommandAndReadStdout(["list", "--is-pack", appAsarPath]),
  317. ),
  318. );
  319. }
  320. async function injectHoistedRuntimeModulesIntoAsar(context) {
  321. const appAsarPath = resolveAppAsarPath(context);
  322. if (!existsSync(appAsarPath)) {
  323. throw new Error(`打包产物缺少 app.asar: ${appAsarPath}`);
  324. }
  325. const missingRuntimeModules = runTimedSync("afterPack:scan-missing-runtime-modules", () =>
  326. resolveMissingRuntimeModules(appAsarPath),
  327. );
  328. if (missingRuntimeModules.length === 0) {
  329. // 之前 afterPack 每次都完整 extract/pack app.asar,即使运行时依赖已经齐全也会重复重写。
  330. // 这会把每次打包固定拉长十几秒到几十秒。先做缺失扫描,只有真的缺包才执行重写流程。
  331. console.log("[afterPack] runtime modules already complete, skip app.asar rewrite");
  332. return;
  333. }
  334. console.log(`[afterPack] missing runtime modules count=${missingRuntimeModules.length}`);
  335. // 重写前先快照当前 archive 的 unpack 布局,重写时原样保留。
  336. const preservedUnpackDirs = resolveCurrentUnpackDirs(appAsarPath);
  337. // CI 会把 TMPDIR 指到项目内 .tmp,GitLab get_sources/clean 可能在脚本启动前清掉该目录。
  338. // afterPack 里重写 app.asar 同样依赖 mkdtempSync,必须自己兜底创建父目录,避免后续签名阶段只看到 .app 消失。
  339. mkdirSync(tmpdir(), { recursive: true });
  340. const stagingDir = mkdtempSync(resolve(tmpdir(), "zcode-app-asar-"));
  341. try {
  342. runTimedSync("afterPack:asar-extract", () =>
  343. runAsarCommand(["extract", appAsarPath, stagingDir]),
  344. );
  345. runTimedSync("afterPack:copy-runtime-modules", () => {
  346. for (const runtimeModule of missingRuntimeModules) {
  347. const { moduleName, sourceModulePath, installRelativePath } = runtimeModule;
  348. // 按闭包给出的落位路径复制,而不是统一拍平到 node_modules/<name>。
  349. // 同名多版本(如 yazl 要 buffer-crc32@1.x、yauzl 要 ~0.2.x)必须各自就位,
  350. // 否则后复制的会覆盖先复制的,Node 解析链仍会拿到错误版本。
  351. const targetModulePath = resolve(stagingDir, ...installRelativePath.split("/"));
  352. if (!sourceModulePath) {
  353. throw new Error(
  354. `未找到运行时依赖 ${moduleName},已搜索: ${runtimeModuleLookupRoots
  355. .map((lookupRoot) => resolve(lookupRoot, "node_modules", moduleName))
  356. .join(", ")}`,
  357. );
  358. }
  359. // pnpm hoisted 布局下,electron-builder 可能把主包打进 app.asar,
  360. // 却漏掉它解析时还要去根 node_modules 找的运行时依赖。
  361. // 之前 require-in-the-middle 漏过 module-details-from-path,这次 @fiahfy/icns 又漏了 pngjs,
  362. // 最终都会在已安装应用里触发 Cannot find module 并让主进程启动直接崩溃。
  363. // 这里按 package.json 递归补齐依赖闭包,避免每次只补一个缺失包、上线后再暴露下一个子依赖。
  364. // 只靠 package.json 显式依赖、本包 node_modules 镜像、files include 都没让它稳定进 asar,
  365. // 所以在 afterPack 阶段直接重写 app.asar,先把这些运行时包补进去,再交给后续签名和出包。
  366. mkdirSync(dirname(targetModulePath), { recursive: true });
  367. rmSync(targetModulePath, { force: true, recursive: true });
  368. cpSync(sourceModulePath, targetModulePath, { recursive: true });
  369. }
  370. });
  371. await runTimedAsync("afterPack:asar-pack", () =>
  372. replaceAppAsarFromStaging({
  373. sourceDir: stagingDir,
  374. appAsarPath,
  375. unpackDirs: preservedUnpackDirs,
  376. runAsarCommand,
  377. }),
  378. );
  379. } finally {
  380. rmSync(stagingDir, { force: true, recursive: true });
  381. }
  382. }
  383. async function stripPackagedSourcemapReferences(context) {
  384. // electron-builder 的 files 规则能排除 .map 文件,但无法删除 JS/CSS 末尾
  385. // 指向 sourcemap 的注释;afterPack 注入运行时依赖后也可能重新带入第三方 sourceMappingURL。
  386. // 这里统一清理 app.asar 与 unpacked/extraResources,保证最终发布包不暴露 sourcemap 路径入口。
  387. await cleanupPackagedSourcemaps({
  388. appAsarPath: resolveAppAsarPath(context),
  389. resourcesDir: resolvePackagedResourcesDir(context),
  390. runAsarCommand,
  391. runTimedSync,
  392. runTimedAsync,
  393. // 这次重写同样会替换 app.asar,必须先快照 unpack 布局再原样带过去,
  394. // 否则 sourcemap 清理会把注入阶段刚恢复的 unpack 结果又抹掉一次。
  395. resolveUnpackDirs: resolveCurrentUnpackDirs,
  396. replaceAppAsarFromStaging: ({ sourceDir, appAsarPath, unpackDirs }) =>
  397. replaceAppAsarFromStaging({
  398. sourceDir,
  399. appAsarPath,
  400. unpackDirs,
  401. runAsarCommand,
  402. }),
  403. });
  404. }
  405. function assertPackagedNativeResourcePolicy(context) {
  406. const appAsarPath = resolveAppAsarPath(context);
  407. const entries = parseAsarListWithPackState(
  408. runAsarCommandAndReadStdout(["list", "--is-pack", appAsarPath]),
  409. );
  410. const violations = findDesktopNativePackageViolations(entries, targetPlatform.key);
  411. if (violations.length > 0) {
  412. // supportedArchitectures 允许工作区准备多平台依赖,但安装包只能携带目标平台资源。
  413. // 之前 Canvas 和 node-pty 的其他平台 native 被同时写进 asar/unpacked,包体被放大数百 MiB。
  414. throw new Error(`桌面 native 资源边界校验失败:\n- ${violations.join("\n- ")}`);
  415. }
  416. }
  417. function assertPackagedNodePtyPrebuild(context) {
  418. const targetBinaryPath = resolvePackagedNodePtyPrebuildPath({
  419. resourcesDir: resolvePackagedResourcesDir(context),
  420. platformKey: targetPlatform.key,
  421. });
  422. if (!existsSync(targetBinaryPath))
  423. throw new Error(`node-pty 预编译产物缺失: ${targetBinaryPath}`);
  424. }
  425. function assertPackagedCuaSharp(context) {
  426. if (!isSharpRequiredByComputerUse({ desktopPackageRoot })) return;
  427. const problems = [
  428. [
  429. "packages/browser-use-plugin",
  430. verifyStagedSharp({
  431. resourcesDir: resolvePackagedResourcesDir(context),
  432. targetPlatform,
  433. pluginRelativePath: "packages/browser-use-plugin",
  434. }),
  435. ],
  436. [
  437. "packages/zcode-cua-plugin",
  438. verifyStagedSharp({
  439. resourcesDir: resolvePackagedResourcesDir(context),
  440. targetPlatform,
  441. pluginRelativePath: "packages/zcode-cua-plugin",
  442. }),
  443. ],
  444. ].flatMap(([pluginPath, pluginProblems]) =>
  445. pluginProblems.map((problem) => `${pluginPath}: ${problem}`),
  446. );
  447. if (problems.length > 0) {
  448. throw new Error(
  449. `node_repl sharp runtime is incomplete in the packaged app:\n- ${problems.join("\n- ")}`,
  450. );
  451. }
  452. }
  453. function assertPackagedCuaKoffi(context) {
  454. const problems = verifyStagedKoffi({
  455. resourcesDir: resolvePackagedResourcesDir(context),
  456. targetPlatform,
  457. });
  458. if (problems.length > 0) {
  459. throw new Error(
  460. `CUA plugin koffi runtime is incomplete in the packaged app:\n- ${problems.join("\n- ")}`,
  461. );
  462. }
  463. }
  464. function assertSignedWindowsBrowserImportHelper(context) {
  465. if (
  466. !shouldPackageWindowsBrowserImportHelper ||
  467. context.electronPlatformName !== "win32" ||
  468. !shouldEnableWindowsVsign
  469. )
  470. return;
  471. const helperPath = resolve(context.appOutDir, "resources", "browser-import", HELPER_FILENAME);
  472. const appExecutablePath = resolve(
  473. context.appOutDir,
  474. `${context.packager.appInfo.productFilename}.exe`,
  475. );
  476. const script = [
  477. "$helper=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg0;",
  478. "$app=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg1;",
  479. "if($helper.Status -ne 'Valid' -or $app.Status -ne 'Valid'){",
  480. "[Console]::Error.WriteLine(('Authenticode status invalid: helper={0} ({1}); app={2} ({3})' -f $helper.Status,$helper.StatusMessage,$app.Status,$app.StatusMessage));",
  481. "exit 23};",
  482. "if($null -eq $helper.SignerCertificate -or $null -eq $app.SignerCertificate){",
  483. "[Console]::Error.WriteLine('Authenticode signer certificate missing');exit 24};",
  484. "if($helper.SignerCertificate.Thumbprint -ne $app.SignerCertificate.Thumbprint){",
  485. "[Console]::Error.WriteLine(('Authenticode signer mismatch: helper={0}; app={1}' -f $helper.SignerCertificate.Thumbprint,$app.SignerCertificate.Thumbprint));",
  486. "exit 25};",
  487. ].join("");
  488. // Bugfix 原因:extraResources 下的 EXE 是否进入 electron-builder 默认签名遍历会随版本变化;
  489. // 同时 Windows PowerShell 的 `-Command` 不会把尾随路径放进 `$args`,旧校验因此固定误报 exit 23。
  490. // 发布态改用 EncodedCommand,并从 PSHOME 显式加载系统 Security 模块,避免 pwsh 继承的
  491. // PSModulePath 让 Windows PowerShell 5.1 错误加载不兼容模块。
  492. runCommand(
  493. "powershell.exe",
  494. createWindowsPowerShellSecurityArgs(script, [helperPath, appExecutablePath]),
  495. );
  496. }
  497. function signWindowsBrowserImportHelper(context) {
  498. if (
  499. !shouldPackageWindowsBrowserImportHelper ||
  500. context.electronPlatformName !== "win32" ||
  501. !shouldEnableWindowsVsign
  502. )
  503. return;
  504. const helperPath = resolve(context.appOutDir, "resources", "browser-import", HELPER_FILENAME);
  505. runCommand("powershell.exe", [
  506. "-NoLogo",
  507. "-NoProfile",
  508. "-NonInteractive",
  509. "-ExecutionPolicy",
  510. "Bypass",
  511. "-File",
  512. resolve(workspaceRoot, "scripts/sign-windows.ps1"),
  513. "-FilePath",
  514. helperPath,
  515. ]);
  516. }
  517. /** @type {import("electron-builder").Configuration} */
  518. export default {
  519. appId: desktopProductIdentity.appId,
  520. // Linux deb 打包(fpm)会校验 package metadata 中的 homepage、author.email、maintainer。
  521. // CI 环境下若这些字段缺失会在产物阶段直接失败。这里统一在构建配置补齐,避免依赖外部注入。
  522. extraMetadata: {
  523. version: buildMetadata.appVersion,
  524. zcodeProductFlavor: desktopProductIdentity.flavor,
  525. homepage: "https://zcode.z.ai",
  526. author: {
  527. name: "ZCode",
  528. email: "dev@zcode.z.ai",
  529. },
  530. },
  531. // macOS 签名阶段会对 Electron Framework 下每个语言包逐个 codesign。
  532. // 默认全量语言会产生大量 locale.pak 签名调用,显著拉长打包时长。
  533. // 这里仅保留当前产品必需语言,减少签名文件数并缩短 CI 总耗时。
  534. electronLanguages: ["en-US", "zh-CN"],
  535. // pnpm workspace + semver range(如 ^41.0.3)下,electron-builder
  536. // 有时无法从依赖树里稳定推导出 Electron 版本,导致 bundle 直接中断。
  537. // 显式写死当前桌面端使用的 Electron 版本,避免打包阶段再做不可靠的猜测。
  538. electronVersion: "41.0.3",
  539. // 旧 Windows 协议注册可能在应用 JS 重写注册表前注入 --inspect-brk。
  540. // 在签名前关闭原生 Inspector 参数,覆盖升级后首次启动;保留 Agent 所需的 RunAsNode。
  541. ...(targetPlatform.os === "win32"
  542. ? { electronFuses: { enableNodeCliInspectArguments: false } }
  543. : {}),
  544. electronDownload: {
  545. // ELECTRON_MIRROR 是 @electron/get 的全局环境变量,会覆盖 dmg-builder 等
  546. // generic artifact 自己传入的 mirrorOptions,导致 builder 辅助包被错误拼到 Electron runtime 镜像目录。
  547. // 这里改用 electron-builder 的专用配置,只影响 Electron runtime zip 下载。
  548. mirror: resolveElectronDownloadMirror(),
  549. },
  550. productName: desktopProductIdentity.productName,
  551. directories: {
  552. // macOS arm64/x64 CI 可能共享同一个 checkout 并行打包。
  553. // 输出根目录允许按架构隔离,避免一个 job 清理 dist 时删除另一个 job 正在签名的 .app。
  554. output: desktopDistDir,
  555. buildResources: "build",
  556. },
  557. files: [
  558. "out/**/*",
  559. "package.json",
  560. // app.asar 会把桌面端运行时 node_modules 一并打进去,依赖包自带的 .map / README
  561. // 默认也会原样进入安装包。这里统一在主包层做一次裁剪,只移除非运行时文件,LICENSE 继续保留。
  562. ...PACKAGING_PRUNE_PATTERNS,
  563. ...createDesktopNativePackagePrunePatterns(targetPlatform.key),
  564. "!node_modules/@zcode/**",
  565. "!node_modules/react/**",
  566. "!node_modules/react-dom/**",
  567. ],
  568. asarUnpack: [
  569. // node-pty 的 target prebuild 还包含 spawn-helper / winpty-agent.exe 等辅助可执行文件,
  570. // 整个目标目录必须 unpack;其他平台目录已由 files 规则裁剪。
  571. `node_modules/node-pty/prebuilds/${targetPlatform.key}/**`,
  572. ],
  573. beforePack: async (context) => {
  574. runTimedSync("beforePack:restoreTargetNodePtyPrebuild", () =>
  575. restoreTargetNodePtyPrebuild({ desktopPackageRoot, targetPlatform }),
  576. );
  577. if (context.electronPlatformName !== "win32" || nsisInstallSectionPatched) {
  578. return;
  579. }
  580. nsisInstallSectionPath = resolve(
  581. dirname(requireFromConfig.resolve("app-builder-lib/package.json")),
  582. "templates",
  583. "nsis",
  584. "installSection.nsh",
  585. );
  586. const patchResult = await runTimedAsync("beforePack:patchNsisInstallSection", () =>
  587. patchNsisInstallSectionFile(nsisInstallSectionPath),
  588. );
  589. nsisInstallSectionPatched = true;
  590. nsisInstallSectionOriginalSource = patchResult.originalSource;
  591. if (patchResult.changed) {
  592. // electron-builder 在当前进程内随后才会编译 NSIS;等整个构建进程退出后恢复 node_modules
  593. // 中的上游模板,避免把一次打包的定制内容永久留在开发依赖里。
  594. process.once("exit", () => {
  595. restoreNsisInstallSectionFileSync({
  596. filePath: nsisInstallSectionPath,
  597. originalSource: nsisInstallSectionOriginalSource,
  598. });
  599. });
  600. }
  601. },
  602. afterExtract: async (context) => {
  603. // 修复:macOS 重命名阶段会删除归档顶层许可证,必须在 afterExtract 保留目标平台原文。
  604. const framework = context.packager.info.framework;
  605. const resources =
  606. context.electronPlatformName === "darwin"
  607. ? resolve(context.appOutDir, framework.distMacOsAppName, "Contents", "Resources")
  608. : resolve(context.appOutDir, "resources");
  609. await stageElectronNotices(context.appOutDir, resources, framework.version);
  610. },
  611. afterPack: async (context) => {
  612. const actualWindowsTarget =
  613. context.electronPlatformName === "win32"
  614. ? resolveElectronBuilderWindowsTarget({
  615. electronPlatformName: context.electronPlatformName,
  616. arch: context.arch,
  617. configuredTargetPlatform: targetPlatform,
  618. })
  619. : null;
  620. await runTimedAsync("afterPack:injectHoistedRuntimeModulesIntoAsar", () =>
  621. injectHoistedRuntimeModulesIntoAsar(context),
  622. );
  623. await runTimedAsync("afterPack:stripPackagedSourcemapReferences", () =>
  624. stripPackagedSourcemapReferences(context),
  625. );
  626. runTimedSync("afterPack:assertPackagedNativeResourcePolicy", () =>
  627. assertPackagedNativeResourcePolicy(context),
  628. );
  629. runTimedSync("afterPack:assertPackagedNodePtyPrebuild", () =>
  630. assertPackagedNodePtyPrebuild(context),
  631. );
  632. runTimedSync("afterPack:assertPackagedCuaSharp", () => assertPackagedCuaSharp(context));
  633. runTimedSync("afterPack:assertPackagedCuaKoffi", () => assertPackagedCuaKoffi(context));
  634. runTimedSync("afterPack:assertPackagedCuaHelper", () => assertPackagedCuaHelper(context));
  635. if (actualWindowsTarget && shouldPackageComputerUseHelper) {
  636. await runTimedAsync("afterPack:finalizePackagedWindowsCuaHelper", () =>
  637. finalizePackagedWindowsCuaHelper({
  638. resourcesDir: resolvePackagedResourcesDir(context),
  639. targetPlatform: actualWindowsTarget,
  640. electronVersion: desktopElectronVersion,
  641. }),
  642. );
  643. await runTimedAsync("afterPack:writeWindowsInstallManifest", () =>
  644. writeWindowsInstallManifest(context),
  645. );
  646. }
  647. if (shouldPackageWindowsBrowserImportHelper) {
  648. runTimedSync("afterPack:signWindowsBrowserImportHelper", () =>
  649. signWindowsBrowserImportHelper(context),
  650. );
  651. }
  652. },
  653. ...(shouldPackageWindowsBrowserImportHelper
  654. ? {
  655. afterSign: async (context) => {
  656. runTimedSync("afterSign:assertSignedWindowsBrowserImportHelper", () =>
  657. assertSignedWindowsBrowserImportHelper(context),
  658. );
  659. },
  660. }
  661. : {}),
  662. extraResources: [
  663. { from: resolve(workspaceRoot, noticesFileName), to: noticesFileName },
  664. ...(targetPlatform.os === "darwin"
  665. ? [
  666. ...(shouldPackageComputerUseHelper
  667. ? [
  668. {
  669. from: bundledCuaHelperSource,
  670. to: `cua-helper/${HELPER_APP_NAME}`,
  671. },
  672. ]
  673. : []),
  674. {
  675. // CUA 权限浮窗的吸附数据源(CGWindowListCopyWindowInfo,不需要任何 TCC 权限)。
  676. // 主进程按 process.resourcesPath 解析;缺失时 watcher fail-open,浮窗仍可用
  677. // 只是不吸附,所以这里不做存在性断言。
  678. from: "resources/macos-window-bounds/zcode-window-bounds",
  679. to: "macos-window-bounds/zcode-window-bounds",
  680. },
  681. ]
  682. : []),
  683. {
  684. // 正式包不能依赖仓库目录读取社区、反馈等内置兜底配置。
  685. // 显式放入 resources/config,与主进程的 process.resourcesPath 解析保持一致。
  686. from: resolve(workspaceRoot, "config/default.json"),
  687. to: "config/default.json",
  688. },
  689. {
  690. // Provider Registry 的 ZCode Built-in Config 是静态 Provider/Model 事实的唯一内置来源。
  691. // 显式随包发布,避免正式 Host 回退到旧 Catalog/Preset hardcode。
  692. from: builtinProviderConfig.sourcePath,
  693. to: "config/provider/zcode-builtin.json",
  694. },
  695. {
  696. // 应用图标:打包后放入 resources 目录,主进程通过 process.resourcesPath 加载
  697. from: "build/icon.png",
  698. to: "icon.png",
  699. },
  700. {
  701. // Windows 独立图标:开发态和打包态都统一走同一套任务栏/窗口图标资源。
  702. from: "build/icon_windows.png",
  703. to: "icon_windows.png",
  704. },
  705. ...(targetPlatform.os === "win32"
  706. ? [
  707. {
  708. // Windows 托盘图标:Tray 在打包态只能稳定读取 resources 下的独立资源。
  709. // 这里不复用窗口 PNG,避免通知区域在高 DPI 下退化成模糊缩放图。
  710. from: "build/icon.ico",
  711. to: "tray_icon.ico",
  712. },
  713. ]
  714. : []),
  715. ...(targetPlatform.os === "win32" && shouldPackageComputerUseHelper
  716. ? [
  717. {
  718. // 根因:electron-builder 会跳过 from 根目录下的 node_modules;主树与依赖树必须分开映射,
  719. // 否则安装包有 manifest/entry,却会在 Helper 启动时缺 express/Sharp。
  720. from: `bundled-tools/${targetPlatform.key}/cua-helper`,
  721. to: "tools/cua-helper",
  722. filter: ["**/*", "!node_modules{,/**/*}"],
  723. },
  724. {
  725. from: `bundled-tools/${targetPlatform.key}/cua-helper/node_modules`,
  726. to: "tools/cua-helper/node_modules",
  727. filter: ["**/*", "!**/*.map"],
  728. },
  729. ]
  730. : []),
  731. {
  732. // agent 运行时资产,打包到 resources/glm。
  733. // 桌面端内置的是 agent 的 JS bundle(glm/zcode.cjs,由 prepare:agent-bundle 生成),
  734. // Host 进程用 app 自带的 Electron Node runtime(ELECTRON_RUN_AS_NODE)执行 `zcode.cjs app-server --stdio`,
  735. // 不再随包内置独立 Node 二进制。远端 SSH/WSL 仍走原生二进制(无 Electron)。
  736. from: `bundled-agents/${targetPlatform.key}/glm`,
  737. to: "glm",
  738. filter: ["**/*", "!**/*.map"],
  739. },
  740. {
  741. // agent shell 之前完全依赖宿主系统 PATH,GUI 启动时经常拿不到用户自己装的 rg。
  742. // 这里把 ripgrep 作为桌面端内置 runtime tool 打进 resources/tools,
  743. // 后续 host/server 把该目录追加到 PATH;用户版本优先,缺失时再由随包 rg 兜底。
  744. from: `bundled-tools/${targetPlatform.key}/ripgrep`,
  745. to: "tools/ripgrep",
  746. filter: ["**/*"],
  747. },
  748. ...nativeSearchReleasePlan.extraResourceToolIds.map((toolId) => ({
  749. from: `bundled-tools/${targetPlatform.key}/${toolId}`,
  750. to: `tools/${toolId}`,
  751. filter: ["**/*"],
  752. })),
  753. ],
  754. // postinstall 会先优先复用 node-pty 自带的 Windows 预编译产物,其他平台再按需 electron-rebuild。
  755. // 打包阶段统一复用安装时准备好的原生文件,避免 electron-builder 再触发一轮不受控的本地编译。
  756. npmRebuild: false,
  757. // OAuth deep link 协议注册(macOS 打包后需要 Info.plist 中声明 CFBundleURLTypes)
  758. protocols: [
  759. {
  760. // 协议处理器的展示名之前使用小写 scheme,打包产物里的协议描述无法体现产品名。
  761. // 展示名跟随安装包身份;scheme 仍保持 zcode,因此两个应用中最后注册者会成为默认 handler。
  762. name: desktopProductIdentity.productName,
  763. schemes: ["zcode"],
  764. },
  765. ],
  766. /* Windows-only 精简:原 macOS 打包段(dmg/zip、codesign/notarize/entitlements)已整体移除。 */
  767. win: {
  768. target: ["nsis"],
  769. artifactName: buildDesktopArtifactName("win"),
  770. signExts: [".node", ".dll"],
  771. // Bugfix: Windows CI 之前完全依赖 electron-builder 内置 signtool.exe,
  772. // 一旦 runner 的证书链路要求改走 vsigntool,打包阶段就会在内置签名环节卡死。
  773. // 这里通过自定义 sign hook 把所有 Windows 可执行文件统一切到仓库内的 vsigntool 封装,
  774. // 既保留 electron-builder 的签名时机,又和 CI 机器上的签名基础设施保持一致。
  775. ...(shouldEnableWindowsVsign
  776. ? {
  777. signtoolOptions: {
  778. sign: "./scripts/sign-windows-hook.cjs",
  779. },
  780. }
  781. : {}),
  782. },
  783. /* Windows-only 精简:原 Linux 打包段(AppImage/deb/rpm/pacman)与 dmg 段已整体移除。 */
  784. nsis: {
  785. oneClick: false,
  786. allowToChangeInstallationDirectory: true,
  787. // Windows 安装流程使用独立安装图标,和应用运行时图标解耦。
  788. installerIcon: "build/icon_installer.ico",
  789. uninstallerIcon: "build/icon_installer.ico",
  790. installerHeaderIcon: "build/icon_installer.ico",
  791. },
  792. detectUpdateChannel: false,
  793. publish: {
  794. provider: "generic",
  795. // 当前 OSS/CDN 对多 Range 请求返回 206,但 Content-Type 仍是 application/x-msdownload,
  796. // electron-updater 会因缺少 multipart/byteranges 直接回退整包下载。关闭 multiple range 后仍走差分,
  797. // 只是按单 Range 顺序拉取差异块,避免 Windows 用户更新时从约 15MB 退化成 300MB+ 全量包。
  798. useMultipleRangeRequest: false,
  799. // 新客户端运行时使用服务端 manifest provider;这里仅保留 electron-builder 必需的
  800. // generic publish 占位,避免打包产物继续携带可配置的旧 stable feed。
  801. url: "http://localhost:8081",
  802. },
  803. };