bundled-npm-assets.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // 随包 npm:桌面 agent 跑在 Electron Node 上,用户机器没装 Node 时,stdio MCP 的 npm/npx
  2. // 回退到这里 stage 的 npm(规格:apps/zcode-cli/docs/design/v2/mcp-node-fallback.md)。
  3. //
  4. // 为什么下载 registry tarball 而不是加 pnpm 依赖:仓库用 node-linker=hoisted,npm 包的
  5. // npm/npx bin 会被链接进根 node_modules/.bin,覆盖开发者自己的 npm(新 npm 还不支持仓库
  6. // 锁定的 Node 小版本)。这里按固定版本 + registry sha512 下载并缓存,开发工具链不受影响。
  7. import { createHash, randomUUID } from "node:crypto";
  8. import { createReadStream } from "node:fs";
  9. import { access, cp, mkdir, mkdtemp, rename, rm } from "node:fs/promises";
  10. import { tmpdir } from "node:os";
  11. import { basename, join, relative, sep } from "node:path";
  12. import { downloadPrebuiltArchive } from "../../../scripts/prebuilt-binary-download.mjs";
  13. import { extractPrebuiltArchive } from "../../../scripts/prebuilt-binary-extract.mjs";
  14. // engines.node 必须接受 Electron 自带的 Node(Electron 44 = Node 24.21);升级时同步更新摘要。
  15. export const BUNDLED_NPM_VERSION = "12.2.0";
  16. export const BUNDLED_NPM_INTEGRITY =
  17. "sha512-ZsJjKpTnlmSXOLLXiU1xDCzC4Wlok4IwZmh/aw2KUuXytU7q6qMv/cUT7MoeSf95Slwuw/lRXYefGzGCspHPNQ==";
  18. /** 相对 glm 目录(zcode.cjs 所在目录)的位置;与 bootstrap mcp-node-fallback.ts 同一约定。 */
  19. export const BUNDLED_NPM_STAGED_SEGMENTS = ["node-runtime", "npm"];
  20. const NPM_REGISTRY_TARBALL_BASE = "https://registry.npmjs.org/npm/-/";
  21. const NPM_TARBALL_PACKAGE_DIR = "package";
  22. const NPM_REQUIRED_ENTRIES = ["bin/npm-cli.js", "bin/npx-cli.js"];
  23. // npm help 不受支持;去掉文档与 man 页省下约 3MB。
  24. const EXCLUDED_TOP_LEVEL_ENTRIES = new Set(["docs", "man"]);
  25. const SHA512_PREFIX = "sha512-";
  26. export function bundledNpmTarballUrl(version) {
  27. return `${NPM_REGISTRY_TARBALL_BASE}npm-${version}.tgz`;
  28. }
  29. /**
  30. * 校验并缓存 tarball,解包后拷进 `<glmDir>/node-runtime/npm`。返回 stage 后的 npm 根目录。
  31. * download / extract 可注入,测试无需网络。
  32. */
  33. export async function stageBundledNpm({
  34. cacheDir,
  35. download = downloadPrebuiltArchive,
  36. extract = extractPrebuiltArchive,
  37. glmDir,
  38. integrity = BUNDLED_NPM_INTEGRITY,
  39. version = BUNDLED_NPM_VERSION,
  40. }) {
  41. const tarballPath = await ensureVerifiedTarball({ cacheDir, download, integrity, version });
  42. const workDir = await mkdtemp(join(tmpdir(), "zcode-bundled-npm-"));
  43. try {
  44. extract({ archiveExt: "tgz", archivePath: tarballPath, cwd: workDir, extractDir: workDir });
  45. const packageRoot = join(workDir, NPM_TARBALL_PACKAGE_DIR);
  46. await assertNpmEntries(packageRoot);
  47. const targetRoot = join(glmDir, ...BUNDLED_NPM_STAGED_SEGMENTS);
  48. await rm(targetRoot, { force: true, recursive: true });
  49. await cp(packageRoot, targetRoot, {
  50. filter: (source) => !isExcludedTopLevelEntry(packageRoot, source),
  51. recursive: true,
  52. });
  53. return targetRoot;
  54. } finally {
  55. await rm(workDir, { force: true, recursive: true });
  56. }
  57. }
  58. async function ensureVerifiedTarball({ cacheDir, download, integrity, version }) {
  59. const tarballPath = join(cacheDir, `npm-${version}.tgz`);
  60. if (await isTarballValid(tarballPath, integrity)) return tarballPath;
  61. await mkdir(cacheDir, { recursive: true });
  62. const temporaryPath = `${tarballPath}.tmp-${process.pid}-${randomUUID()}`;
  63. try {
  64. await download(bundledNpmTarballUrl(version), temporaryPath);
  65. if (!(await isTarballValid(temporaryPath, integrity))) {
  66. throw new Error(`[bundled-npm] sha512 mismatch for npm@${version}`);
  67. }
  68. await rename(temporaryPath, tarballPath);
  69. return tarballPath;
  70. } finally {
  71. await rm(temporaryPath, { force: true });
  72. }
  73. }
  74. async function isTarballValid(tarballPath, integrity) {
  75. try {
  76. return (await sha512Integrity(tarballPath)) === integrity;
  77. } catch {
  78. return false;
  79. }
  80. }
  81. function sha512Integrity(path) {
  82. return new Promise((resolvePromise, rejectPromise) => {
  83. const hash = createHash("sha512");
  84. createReadStream(path)
  85. .on("error", rejectPromise)
  86. .on("data", (chunk) => hash.update(chunk))
  87. .on("end", () => resolvePromise(`${SHA512_PREFIX}${hash.digest("base64")}`));
  88. });
  89. }
  90. async function assertNpmEntries(packageRoot) {
  91. for (const entry of NPM_REQUIRED_ENTRIES) {
  92. const entryPath = join(packageRoot, ...entry.split("/"));
  93. try {
  94. await access(entryPath);
  95. } catch (error) {
  96. throw new Error(`[bundled-npm] missing npm entry ${entry} in ${packageRoot}`, {
  97. cause: error,
  98. });
  99. }
  100. }
  101. }
  102. function isExcludedTopLevelEntry(packageRoot, source) {
  103. const relativePath = relative(packageRoot, source);
  104. return !relativePath.includes(sep) && EXCLUDED_TOP_LEVEL_ENTRIES.has(basename(source));
  105. }