build-sea.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { spawnSync } from "node:child_process";
  2. import { existsSync } from "node:fs";
  3. import { chmod, copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join, resolve } from "node:path";
  6. import { pathToFileURL } from "node:url";
  7. import { resolveSpawnRuntimeOptions } from "../../../../../scripts/spawn-command.mjs";
  8. import { resolveDownloadedNodeBinary } from "./sea-node-download.mjs";
  9. import {
  10. adHocCodesignArgs,
  11. hostTarget,
  12. isHostTarget,
  13. nodeReleaseArtifact,
  14. nodeReleaseUrl,
  15. outputBinaryName,
  16. parseBuildSeaArgs,
  17. postjectArgsForTarget,
  18. shouldAdHocSignMacTarget,
  19. supportedTargets,
  20. targetParts,
  21. } from "./sea-targets.mjs";
  22. import { removeWindowsAuthenticodeSignature } from "./windows-authenticode.mjs";
  23. import { collectSeaTuiAssets } from "./sea-tui-assets.mjs";
  24. import { collectSeaOfficialPluginAssets } from "./sea-official-plugin-assets.mjs";
  25. import { collectSeaBundledSkillAssets } from "./sea-bundled-skill-assets.mjs";
  26. import { collectSeaRuntimeToolAssets } from "./sea-runtime-tool-assets.mjs";
  27. import { prepareSeaRuntimeToolAssets } from "./sea-runtime-tool-prepare.mjs";
  28. import { collectSeaPlaywrightAssets } from "./sea-playwright-assets.mjs";
  29. import { collectSeaProviderConfigAssets } from "./sea-provider-config-assets.mjs";
  30. export {
  31. adHocCodesignArgs,
  32. hostTarget,
  33. isHostTarget,
  34. nodeReleaseArtifact,
  35. nodeReleaseUrl,
  36. outputBinaryName,
  37. parseBuildSeaArgs,
  38. postjectArgsForTarget,
  39. shouldAdHocSignMacTarget,
  40. supportedTargets,
  41. };
  42. const usage = `Usage:
  43. node scripts/build-sea.mjs
  44. node scripts/build-sea.mjs --target linux-x64 --target win-x64
  45. node scripts/build-sea.mjs --targets linux-x64,win-x64
  46. node scripts/build-sea.mjs --all
  47. node scripts/build-sea.mjs --node-binary linux-x64=/abs/path/node
  48. Supported targets:
  49. ${supportedTargets.join(", ")}
  50. `;
  51. const root = resolve(import.meta.dirname, "../../..");
  52. const repositoryRoot = resolve(root, "../..");
  53. const cliRoot = resolve(import.meta.dirname, "..");
  54. const dist = resolve(cliRoot, "dist");
  55. const cliBundle = resolve(dist, "zcode.cjs");
  56. const seaBlobForTarget = (target) => resolve(dist, `zcode-${target}.sea.blob`);
  57. const seaConfigForTarget = (target) => resolve(dist, `sea-config-${target}.json`);
  58. const seaAssetStagingForTarget = (target) => resolve(dist, "sea-assets", target);
  59. const nodeCache = resolve(dist, "sea-node-cache");
  60. const sentinelFusePrefix = "NODE_SEA_FUSE_";
  61. export const resolvePostjectBin = ({
  62. platform = process.platform,
  63. startDirectory = cliRoot,
  64. } = {}) => {
  65. const executable = platform === "win32" ? "postject.cmd" : "postject";
  66. let directory = startDirectory;
  67. // pnpm hoisted 布局会把 postject 放到仓库根 node_modules,而不是 CLI 子包下。
  68. // 从 CLI 包目录逐级向上找,避免 SEA 构建依赖某一种安装布局。
  69. while (true) {
  70. const candidate = resolve(directory, "node_modules", ".bin", executable);
  71. if (existsSync(candidate)) return candidate;
  72. const parent = dirname(directory);
  73. if (parent === directory) return undefined;
  74. directory = parent;
  75. }
  76. };
  77. const commandText = (command, args) => [command, ...args].join(" ");
  78. const run = (command, args, options = {}) => {
  79. const result = spawnSync(command, args, {
  80. cwd: cliRoot,
  81. encoding: "utf8",
  82. stdio: "inherit",
  83. ...options,
  84. ...resolveSpawnRuntimeOptions(command),
  85. });
  86. if (result.error) {
  87. throw new Error(`${commandText(command, args)} failed: ${result.error.message}`, {
  88. cause: result.error,
  89. });
  90. }
  91. if (result.status !== 0) {
  92. throw new Error(`${commandText(command, args)} failed`);
  93. }
  94. };
  95. const findSeaFuse = async (binary) => {
  96. const contents = await readFile(binary, "latin1");
  97. const match = contents.match(/NODE_SEA_FUSE_[a-z0-9]+:0/i);
  98. if (!match) {
  99. throw new Error(
  100. `Could not find a NODE_SEA_FUSE marker in ${binary}. ` +
  101. "Use an official Node.js binary with SEA support, or fall back to `pnpm build`.",
  102. );
  103. }
  104. return match[0].replace(/:0$/, "");
  105. };
  106. const resolveNodeBinary = async ({ nodeBinaries, nodeVersion, target }) => {
  107. const explicitBinary = nodeBinaries[target];
  108. if (explicitBinary) {
  109. if (!existsSync(explicitBinary)) {
  110. throw new Error(`Configured Node.js binary for ${target} does not exist: ${explicitBinary}`);
  111. }
  112. console.log(`[sea] using ${target} Node.js binary ${explicitBinary}`);
  113. return explicitBinary;
  114. }
  115. return resolveDownloadedNodeBinary({
  116. nodeCache,
  117. nodeVersion,
  118. target,
  119. });
  120. };
  121. const prepareSeaBlob = async (target) => {
  122. const seaBlob = seaBlobForTarget(target);
  123. const seaConfig = seaConfigForTarget(target);
  124. await prepareSeaRuntimeToolAssets({
  125. root: repositoryRoot,
  126. target,
  127. });
  128. const { assets: tuiAssets, manifest: tuiManifest } = await collectSeaTuiAssets({
  129. root,
  130. stagingDirectory: seaAssetStagingForTarget(target),
  131. target,
  132. });
  133. const { assets: pluginAssets, manifest: pluginManifest } = await collectSeaOfficialPluginAssets({
  134. requireRuntime: true,
  135. root,
  136. stagingDirectory: seaAssetStagingForTarget(`${target}-official-plugins`),
  137. });
  138. const { assets: bundledSkillAssets, manifest: bundledSkillManifest } =
  139. await collectSeaBundledSkillAssets({
  140. root,
  141. stagingDirectory: seaAssetStagingForTarget(`${target}-bundled-skills`),
  142. });
  143. const { assets: runtimeToolAssets, manifest: runtimeToolManifest } =
  144. await collectSeaRuntimeToolAssets({
  145. root: repositoryRoot,
  146. stagingDirectory: seaAssetStagingForTarget(`${target}-runtime-tools`),
  147. target,
  148. });
  149. const { assets: playwrightAssets, manifest: playwrightManifest } =
  150. await collectSeaPlaywrightAssets({
  151. root,
  152. stagingDirectory: seaAssetStagingForTarget(`${target}-playwright`),
  153. target,
  154. });
  155. const providerConfigAssets = await collectSeaProviderConfigAssets({ root: repositoryRoot });
  156. await writeFile(
  157. seaConfig,
  158. JSON.stringify(
  159. {
  160. assets: {
  161. ...tuiAssets,
  162. ...pluginAssets,
  163. ...bundledSkillAssets,
  164. ...runtimeToolAssets,
  165. ...playwrightAssets,
  166. ...providerConfigAssets,
  167. },
  168. disableExperimentalSEAWarning: true,
  169. main: "dist/zcode.cjs",
  170. output: `dist/zcode-${target}.sea.blob`,
  171. useCodeCache: false,
  172. useSnapshot: false,
  173. },
  174. null,
  175. 2,
  176. ),
  177. );
  178. console.log(
  179. `[sea] generating SEA blob for ${target} with ${tuiManifest.files.length} TUI assets, ${pluginManifest.plugins.length} official plugins, ${bundledSkillManifest.files.length} bundled skill files, ${runtimeToolManifest.tools.length} runtime tools, and ${playwrightManifest.files.length} Playwright assets`,
  180. );
  181. run(process.execPath, ["--experimental-sea-config", seaConfig]);
  182. return seaBlob;
  183. };
  184. const removeMacSignatureForInjection = (target, binaryPath) => {
  185. if (!shouldAdHocSignMacTarget(target)) return;
  186. console.log("[sea] removing macOS signature before injection");
  187. run("codesign", ["--remove-signature", binaryPath]);
  188. };
  189. const removeWindowsSignatureForInjection = async (target, binaryPath) => {
  190. const { releasePlatform } = targetParts(target);
  191. if (releasePlatform !== "win") return;
  192. // postject invalidates Node's original Authenticode signature; a stale PE
  193. // Security Directory can make downstream signing reject the SEA as bad Win32.
  194. const result = await removeWindowsAuthenticodeSignature(binaryPath);
  195. if (!result.removed) return;
  196. const action = result.truncated ? "removed and truncated" : "removed";
  197. console.log(
  198. `[sea] ${action} Windows Authenticode signature at offset ${result.certificateOffset}`,
  199. );
  200. };
  201. const adHocSignMacBinary = (target, binaryPath) => {
  202. if (!shouldAdHocSignMacTarget(target)) return;
  203. console.log("[sea] ad-hoc signing macOS binary after injection");
  204. run("codesign", adHocCodesignArgs(binaryPath));
  205. };
  206. const smokeTestHostTarget = async (target, binaryPath) => {
  207. if (isHostTarget(target)) {
  208. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-smoke-"));
  209. try {
  210. const env = {
  211. ...process.env,
  212. ZCODE_STORAGE_DIR: storageRoot,
  213. };
  214. delete env.ZCODE_BFS_BINARY;
  215. delete env.ZCODE_RG_BINARY;
  216. delete env.ZCODE_UGREP_BINARY;
  217. run(binaryPath, ["--version"], {
  218. env,
  219. });
  220. } finally {
  221. await rm(storageRoot, {
  222. force: true,
  223. recursive: true,
  224. });
  225. }
  226. return;
  227. }
  228. console.log(`[sea] skipping smoke test for foreign target ${target}`);
  229. };
  230. const buildTarget = async ({ nodeBinaries, nodeVersion, postjectBin, target }) => {
  231. const binaryPath = resolve(dist, outputBinaryName(target));
  232. const seaBlob = await prepareSeaBlob(target);
  233. const targetNodeBinary = await resolveNodeBinary({
  234. nodeBinaries,
  235. nodeVersion,
  236. target,
  237. });
  238. console.log(`[sea] building ${target} -> ${binaryPath}`);
  239. await copyFile(targetNodeBinary, binaryPath);
  240. await chmod(binaryPath, 0o755);
  241. const sentinelFuse = await findSeaFuse(binaryPath);
  242. if (!sentinelFuse.startsWith(sentinelFusePrefix)) {
  243. throw new Error(`Unexpected SEA fuse marker in ${binaryPath}: ${sentinelFuse}`);
  244. }
  245. removeMacSignatureForInjection(target, binaryPath);
  246. await removeWindowsSignatureForInjection(target, binaryPath);
  247. run(postjectBin, postjectArgsForTarget({ binaryPath, seaBlob, sentinelFuse, target }));
  248. adHocSignMacBinary(target, binaryPath);
  249. await smokeTestHostTarget(target, binaryPath);
  250. console.log(`[sea] binary written to ${binaryPath}`);
  251. };
  252. export const main = async (argv = process.argv.slice(2)) => {
  253. const options = parseBuildSeaArgs(argv);
  254. if (options.help) {
  255. console.log(usage);
  256. return;
  257. }
  258. if (!existsSync(cliBundle)) {
  259. throw new Error("Missing dist/zcode.cjs. Run `pnpm build` first.");
  260. }
  261. const postjectBin = resolvePostjectBin();
  262. if (!postjectBin) {
  263. throw new Error("Missing postject. Run `pnpm install` before `pnpm sea`.");
  264. }
  265. const nodeVersion = process.versions.node;
  266. for (const target of options.targets) {
  267. await buildTarget({
  268. nodeBinaries: options.nodeBinaries,
  269. nodeVersion,
  270. postjectBin,
  271. target,
  272. });
  273. }
  274. };
  275. const entryPath = process.argv[1];
  276. if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
  277. try {
  278. await main();
  279. } catch (error) {
  280. console.error(error instanceof Error ? error.message : String(error));
  281. process.exitCode = 1;
  282. }
  283. }