bootstrap.mjs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. #!/usr/bin/env node
  2. import process from "node:process";
  3. import { existsSync, readFileSync } from "node:fs";
  4. import { delimiter, dirname, join, resolve } from "node:path";
  5. import { homedir } from "node:os";
  6. import { fileURLToPath } from "node:url";
  7. import { runCommand } from "./spawn-command.mjs";
  8. import { clearHoistedPatchedDependencyTargets } from "./bootstrap-patched-dependencies.mjs";
  9. const scriptDir = dirname(fileURLToPath(import.meta.url));
  10. const rootDir = resolve(scriptDir, "..");
  11. const gitCommand = "git";
  12. const withRemoteAssets = process.argv.includes("--with-remote");
  13. function prependPathEntries(pathValue, entries) {
  14. const currentEntries = pathValue ? pathValue.split(delimiter) : [];
  15. return [...entries, ...currentEntries].join(delimiter);
  16. }
  17. function resolvePinnedNodeBin() {
  18. if (process.platform === "win32") {
  19. return undefined;
  20. }
  21. const miseConfigPath = resolve(rootDir, "mise.toml");
  22. if (!existsSync(miseConfigPath)) {
  23. return undefined;
  24. }
  25. const miseConfig = readFileSync(miseConfigPath, "utf8");
  26. const match = miseConfig.match(/^\s*node\s*=\s*"([^"]+)"/m);
  27. const version = match?.[1]?.trim();
  28. if (!version) {
  29. return undefined;
  30. }
  31. const nvmNodeBin = join(homedir(), ".nvm", "versions", "node", `v${version}`, "bin");
  32. return existsSync(nvmNodeBin) ? nvmNodeBin : undefined;
  33. }
  34. function resolveUserPnpmBin() {
  35. if (process.platform === "win32") {
  36. return undefined;
  37. }
  38. const pnpmBin = join(homedir(), "Library", "pnpm");
  39. return existsSync(join(pnpmBin, "pnpm")) ? pnpmBin : undefined;
  40. }
  41. function resolvePnpmCommand() {
  42. if (!withRemoteAssets) {
  43. return process.platform === "win32" ? "pnpm.cmd" : "pnpm";
  44. }
  45. const userPnpmBin = resolveUserPnpmBin();
  46. if (userPnpmBin) {
  47. return join(userPnpmBin, process.platform === "win32" ? "pnpm.cmd" : "pnpm");
  48. }
  49. return process.platform === "win32" ? "pnpm.cmd" : "pnpm";
  50. }
  51. function resolveBootstrapWithRemoteEnv(baseEnv = process.env) {
  52. if (!withRemoteAssets) {
  53. return {};
  54. }
  55. // 修复原因:默认 dev:desktop 使用生产账号;远程构建若沿用通用 test 默认值,
  56. // 会把生产凭据发往测试模型地址并返回 401。入口统一选择环境并传给所有构建子进程。
  57. const zcodeEnv = baseEnv.ZCODE_ENV?.trim().toLowerCase() || "production";
  58. if (zcodeEnv !== "test" && zcodeEnv !== "production") {
  59. throw new Error(`Invalid ZCODE_ENV for bootstrap:with-remote: ${zcodeEnv}`);
  60. }
  61. const pathEntries = [resolvePinnedNodeBin(), resolveUserPnpmBin()].filter(Boolean);
  62. return {
  63. ZCODE_ENV: zcodeEnv,
  64. // bootstrap:with-remote 是手动远程资源初始化入口,自动化等非 TTY 环境里
  65. // pnpm install 可能要求确认清理 node_modules。只在该入口禁用确认,不改变 CI/生产构建命令。
  66. HUSKY: "0",
  67. PNPM_CONFIG_CONFIRM_MODULES_PURGE: "false",
  68. npm_config_confirm_modules_purge: "false",
  69. // remote assets 和 bootstrap build 同一轮里会触发大量 workspace 构建。
  70. // 这里把降峰值限制在 bootstrap:with-remote 子进程,不修改 build/build:bootstrap 的全局语义。
  71. PNPM_CONFIG_WORKSPACE_CONCURRENCY: "1",
  72. ZCODE_BOOTSTRAP_WITH_REMOTE: "1",
  73. ...(pathEntries.length > 0
  74. ? {
  75. PATH: prependPathEntries(baseEnv.PATH, pathEntries),
  76. }
  77. : {}),
  78. };
  79. }
  80. const bootstrapWithRemoteEnv = resolveBootstrapWithRemoteEnv();
  81. const pnpmCommand = resolvePnpmCommand();
  82. function runGit(args) {
  83. runCommand(gitCommand, args, {
  84. cwd: rootDir,
  85. env: process.env,
  86. });
  87. }
  88. function runPnpm(args, options = {}) {
  89. runCommand(pnpmCommand, args, {
  90. cwd: rootDir,
  91. env: {
  92. ...process.env,
  93. ...bootstrapWithRemoteEnv,
  94. ...options.env,
  95. },
  96. });
  97. }
  98. function runBootstrapServerBuild() {
  99. const serverDir = resolve(rootDir, "packages/server");
  100. // bootstrap:with-remote 的最终构建过去复用 build:bootstrap,导致 @zcode/server build
  101. // 内部再次嵌套 pnpm run build:remote;在本地低内存环境中 tsx/esbuild 子进程容易卡住或被停掉。
  102. // 同时不能按 dist 文件存在就跳过构建:开发时 version 经常不变,旧 entry-http 或 remote bundle
  103. // 会让本地/远端继续运行旧协议。这里仅保留直接执行等价入口的低内存优化,CI 和生产 build 脚本保持原样。
  104. runCommand(process.execPath, [resolve(rootDir, "node_modules/tsup/dist/cli-default.js")], {
  105. cwd: serverDir,
  106. env: {
  107. ...process.env,
  108. ...bootstrapWithRemoteEnv,
  109. },
  110. });
  111. runCommand(
  112. process.execPath,
  113. [resolve(rootDir, "node_modules/tsx/dist/cli.mjs"), "build-remote.ts"],
  114. {
  115. cwd: serverDir,
  116. env: {
  117. ...process.env,
  118. ...bootstrapWithRemoteEnv,
  119. },
  120. },
  121. );
  122. }
  123. function runBootstrapE2eReportBuild() {
  124. const e2eReportDir = resolve(rootDir, "packages/e2e-report");
  125. // Bugfix: bootstrap:with-remote 的最终构建不能再嵌套 pnpm build:node。
  126. // 低内存环境中 pnpm shim + tsc 会被 SIGKILL;这里只在 bootstrap runner 中直接执行等价入口。
  127. runCommand(
  128. process.execPath,
  129. [resolve(rootDir, "node_modules/typescript/bin/tsc"), "-p", "tsconfig.json"],
  130. {
  131. cwd: e2eReportDir,
  132. env: {
  133. ...process.env,
  134. ...bootstrapWithRemoteEnv,
  135. },
  136. },
  137. );
  138. runCommand(process.execPath, [resolve(rootDir, "node_modules/vite/bin/vite.js"), "build"], {
  139. cwd: e2eReportDir,
  140. env: {
  141. ...process.env,
  142. ...bootstrapWithRemoteEnv,
  143. },
  144. });
  145. }
  146. function runBootstrapStreamAnimateBuild() {
  147. const streamAnimateDir = resolve(rootDir, "packages/stream-animate");
  148. // Bugfix: bootstrap:with-remote 串行最终构建时,继续通过 pnpm 执行 stream-animate 的 tsc
  149. // 仍可能命中 shim 被 SIGKILL;这里仅在 bootstrap runner 中直接执行等价入口。
  150. runCommand(
  151. process.execPath,
  152. [resolve(rootDir, "node_modules/typescript/bin/tsc"), "-p", "tsconfig.server.json"],
  153. {
  154. cwd: streamAnimateDir,
  155. env: {
  156. ...process.env,
  157. ...bootstrapWithRemoteEnv,
  158. },
  159. },
  160. );
  161. runCommand(process.execPath, [resolve(rootDir, "node_modules/vite/bin/vite.js"), "build"], {
  162. cwd: streamAnimateDir,
  163. env: {
  164. ...process.env,
  165. ...bootstrapWithRemoteEnv,
  166. },
  167. });
  168. }
  169. function runBootstrapDesktopBuild() {
  170. const desktopDir = resolve(rootDir, "packages/desktop");
  171. // bootstrap:with-remote 的目标是完成远程资源和本地 runtime 初始化。
  172. // 继续触发 desktop app bundle 会进入生产构建脚本里的 tsup/vite 路径,在本地低内存环境中被 SIGKILL。
  173. // 这里仅在 bootstrap runner 中保留 build meta,生产/CI 的 build:no-runtime-assets 仍保持原语义。
  174. runCommand(process.execPath, ["scripts/build-metadata.mjs"], {
  175. cwd: desktopDir,
  176. env: {
  177. ...process.env,
  178. ...bootstrapWithRemoteEnv,
  179. },
  180. });
  181. console.log("[bootstrap:with-remote] skip desktop app bundle build; runtime assets are prepared");
  182. }
  183. function runBootstrapWithRemoteBuild() {
  184. for (const filter of ["@zcode/rpc", "@zcode/web", "@zcode/formal-proof"]) {
  185. // pnpm -r 会在 bootstrap:with-remote 的最终构建阶段并发启动多个 Vite/esbuild/tsup。
  186. // remote assets 已经占过一轮内存峰值,这里显式串行包构建,且不改变 build:bootstrap/CI 命令。
  187. runPnpm(["--filter", filter, "build"]);
  188. }
  189. runBootstrapE2eReportBuild();
  190. runBootstrapStreamAnimateBuild();
  191. runBootstrapServerBuild();
  192. runBootstrapDesktopBuild();
  193. }
  194. runGit(["submodule", "update", "--init", "--recursive", "apps/zcode-cli"]);
  195. const clearedPatchedDependencies = await clearHoistedPatchedDependencyTargets({
  196. rootDir,
  197. packageJsonPath: resolve(rootDir, "package.json"),
  198. });
  199. if (clearedPatchedDependencies.length > 0) {
  200. console.log(
  201. `[bootstrap] refreshed hoisted patched dependencies: ${clearedPatchedDependencies.join(", ")}`,
  202. );
  203. }
  204. runPnpm(withRemoteAssets ? ["install", "--config.confirmModulesPurge=false"] : ["install"]);
  205. // Desktop runtime 入口只准备本机资源;Source Server archive 由下方显式远程入口负责。
  206. runPnpm(["prepare:desktop-runtime"]);
  207. if (withRemoteAssets) {
  208. runBootstrapWithRemoteBuild();
  209. // Bug 原因:R3 首装只消费 Source Server archive,旧 bootstrap 只生成 legacy
  210. // manifest/components,导致开发态继续命中 gitignore 中的历史 dist-release。
  211. // 放在最终 workspace build 之后,确保 archive 收集的是本轮最新编译产物。
  212. runPnpm(["--filter", "@zcode/server-cli", "stage:remote-assets"]);
  213. } else {
  214. runPnpm(["run", "build:bootstrap"]);
  215. }