bundledNpmAssets.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { existsSync } from "node:fs";
  4. import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import { promisify } from "node:util";
  8. import { runInNewContext } from "node:vm";
  9. import { afterEach, describe, expect, it, vi } from "vitest";
  10. import {
  11. BUNDLED_NPM_INTEGRITY,
  12. BUNDLED_NPM_VERSION,
  13. bundledNpmTarballUrl,
  14. stageBundledNpm,
  15. } from "../scripts/bundled-npm-assets.mjs";
  16. const execFileAsync = promisify(execFile);
  17. const roots: string[] = [];
  18. const spawnArgsSegments = ["node_modules", "@npmcli", "run-script", "lib", "make-spawn-args.js"];
  19. // 保留 npm 的原始 spawn-options 结构,测试执行 stage 后的模块而不只检查补丁字符串。
  20. const spawnArgsSource = `module.exports = options => {
  21. const { cmd, args, env: spawnEnv, stdioString, stdio, path, scriptShell } = options
  22. const spawnOpts = {
  23. env: spawnEnv,
  24. stdioString,
  25. stdio,
  26. cwd: path,
  27. shell: scriptShell,
  28. }
  29. return [cmd, args, spawnOpts]
  30. }
  31. `;
  32. async function makeRoot(): Promise<string> {
  33. const root = await mkdtemp(join(tmpdir(), "zcode-bundled-npm-"));
  34. roots.push(root);
  35. return root;
  36. }
  37. afterEach(async () => {
  38. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  39. });
  40. /** 按 npm registry tarball 布局(顶层 package/)打一个最小 npm 包。 */
  41. async function createFakeNpmTarball(
  42. root: string,
  43. options: { withNpx?: boolean; spawnSource?: string } = {},
  44. ) {
  45. const sourceRoot = join(root, "source");
  46. const packageRoot = join(sourceRoot, "package");
  47. await mkdir(join(packageRoot, "bin"), { recursive: true });
  48. await mkdir(join(packageRoot, "docs"), { recursive: true });
  49. await mkdir(join(packageRoot, "man", "man1"), { recursive: true });
  50. await mkdir(join(packageRoot, "node_modules", "dep"), { recursive: true });
  51. await writeFile(join(packageRoot, "package.json"), '{"name":"npm"}');
  52. await writeFile(join(packageRoot, "bin", "npm-cli.js"), "// npm");
  53. if (options.withNpx !== false) {
  54. await writeFile(join(packageRoot, "bin", "npx-cli.js"), "// npx");
  55. }
  56. await writeFile(join(packageRoot, "docs", "index.html"), "docs");
  57. await writeFile(join(packageRoot, "man", "man1", "npm.1"), "man");
  58. await writeFile(join(packageRoot, "node_modules", "dep", "index.js"), "// dep");
  59. await mkdir(join(packageRoot, ...spawnArgsSegments.slice(0, -1)), { recursive: true });
  60. await writeFile(join(packageRoot, ...spawnArgsSegments), options.spawnSource ?? spawnArgsSource);
  61. const tarballPath = join(root, "npm.tgz");
  62. await execFileAsync("tar", ["-czf", tarballPath, "-C", sourceRoot, "package"]);
  63. const integrity = `sha512-${createHash("sha512")
  64. .update(await readFile(tarballPath))
  65. .digest("base64")}`;
  66. return { integrity, tarballPath };
  67. }
  68. describe("bundled npm constants", () => {
  69. it("pins an exact npm version and its registry sha512", () => {
  70. expect(BUNDLED_NPM_VERSION).toMatch(/^\d+\.\d+\.\d+$/);
  71. expect(BUNDLED_NPM_INTEGRITY).toMatch(/^sha512-[A-Za-z0-9+/]+=*$/);
  72. expect(bundledNpmTarballUrl("12.2.0")).toBe("https://registry.npmjs.org/npm/-/npm-12.2.0.tgz");
  73. });
  74. });
  75. describe("stageBundledNpm", () => {
  76. it.each([
  77. { platform: "win32", electron: "44.7.0", hidden: true },
  78. { platform: "win32", electron: undefined, hidden: false },
  79. { platform: "darwin", electron: "44.7.0", hidden: false },
  80. { platform: "linux", electron: "44.7.0", hidden: false },
  81. ])(
  82. "hides run-script children only on Windows Electron ($platform, $electron)",
  83. async ({ platform, electron, hidden }) => {
  84. const root = await makeRoot();
  85. const fake = await createFakeNpmTarball(root);
  86. const stagedRoot = await stageBundledNpm({
  87. cacheDir: join(root, "cache"),
  88. download: async (_url: string, destination: string) =>
  89. copyFile(fake.tarballPath, destination),
  90. glmDir: join(root, "glm"),
  91. integrity: fake.integrity,
  92. version: "1.2.3",
  93. });
  94. const module = {
  95. exports: undefined as unknown as (options: Record<string, unknown>) => unknown[],
  96. };
  97. runInNewContext(await readFile(join(stagedRoot, ...spawnArgsSegments), "utf8"), {
  98. module,
  99. process: { platform, versions: { electron }, env: { ELECTRON_RUN_AS_NODE: "1" } },
  100. });
  101. const env = { PATH: "example-path", example: "value" };
  102. const args = ["space argument", "中文参数"];
  103. const [command, actualArgs, spawnOptions] = module.exports({
  104. cmd: "example-bin",
  105. args,
  106. env,
  107. stdio: "inherit",
  108. stdioString: true,
  109. path: "example cwd",
  110. scriptShell: "example-shell",
  111. });
  112. expect(command).toBe("example-bin");
  113. expect(actualArgs).toBe(args);
  114. expect(spawnOptions).toEqual({
  115. env,
  116. stdio: "inherit",
  117. stdioString: true,
  118. cwd: "example cwd",
  119. shell: "example-shell",
  120. windowsHide: hidden,
  121. });
  122. expect((spawnOptions as { env: unknown }).env).toBe(env);
  123. },
  124. );
  125. it.each([
  126. { name: "missing", source: "module.exports = () => []" },
  127. { name: "repeated", source: spawnArgsSource + spawnArgsSource },
  128. ])("rejects a $name patch anchor before replacing staged files", async ({ source }) => {
  129. const root = await makeRoot();
  130. const fake = await createFakeNpmTarball(root, { spawnSource: source });
  131. const glmDir = join(root, "glm");
  132. const previousRoot = join(glmDir, "node-runtime", "npm");
  133. await mkdir(previousRoot, { recursive: true });
  134. await writeFile(join(previousRoot, "previous.txt"), "previous npm");
  135. await expect(
  136. stageBundledNpm({
  137. cacheDir: join(root, "cache"),
  138. download: async (_url: string, destination: string) =>
  139. copyFile(fake.tarballPath, destination),
  140. glmDir,
  141. integrity: fake.integrity,
  142. version: "1.2.3",
  143. }),
  144. ).rejects.toThrow(/run-script.*spawn-options/);
  145. expect(await readFile(join(previousRoot, "previous.txt"), "utf8")).toBe("previous npm");
  146. });
  147. it("re-stages the same patched source without changing the verified archive", async () => {
  148. const root = await makeRoot();
  149. const fake = await createFakeNpmTarball(root);
  150. const download = vi.fn(async (_url: string, destination: string) =>
  151. copyFile(fake.tarballPath, destination),
  152. );
  153. const options = {
  154. cacheDir: join(root, "cache"),
  155. download,
  156. glmDir: join(root, "glm"),
  157. integrity: fake.integrity,
  158. version: "1.2.3",
  159. };
  160. const stagedRoot = await stageBundledNpm(options);
  161. const firstSource = await readFile(join(stagedRoot, ...spawnArgsSegments), "utf8");
  162. await stageBundledNpm(options);
  163. expect(await readFile(join(stagedRoot, ...spawnArgsSegments), "utf8")).toBe(firstSource);
  164. expect(firstSource).not.toBe(spawnArgsSource);
  165. expect(await readFile(join(options.cacheDir, "npm-1.2.3.tgz"))).toEqual(
  166. await readFile(fake.tarballPath),
  167. );
  168. expect(download).toHaveBeenCalledTimes(1);
  169. });
  170. it("downloads, verifies and stages npm without docs and man pages", async () => {
  171. const root = await makeRoot();
  172. const fake = await createFakeNpmTarball(root);
  173. const download = vi.fn(async (_url: string, destination: string) => {
  174. await copyFile(fake.tarballPath, destination);
  175. });
  176. const glmDir = join(root, "glm");
  177. const stagedRoot = await stageBundledNpm({
  178. cacheDir: join(root, "cache"),
  179. download,
  180. glmDir,
  181. integrity: fake.integrity,
  182. version: "1.2.3",
  183. });
  184. expect(stagedRoot).toBe(join(glmDir, "node-runtime", "npm"));
  185. expect(download).toHaveBeenCalledWith(
  186. "https://registry.npmjs.org/npm/-/npm-1.2.3.tgz",
  187. expect.any(String),
  188. );
  189. expect(existsSync(join(stagedRoot, "bin", "npm-cli.js"))).toBe(true);
  190. expect(existsSync(join(stagedRoot, "bin", "npx-cli.js"))).toBe(true);
  191. expect(existsSync(join(stagedRoot, "node_modules", "dep", "index.js"))).toBe(true);
  192. expect(existsSync(join(stagedRoot, "docs"))).toBe(false);
  193. expect(existsSync(join(stagedRoot, "man"))).toBe(false);
  194. });
  195. it("reuses a verified cached tarball without downloading", async () => {
  196. const root = await makeRoot();
  197. const fake = await createFakeNpmTarball(root);
  198. const cacheDir = join(root, "cache");
  199. await mkdir(cacheDir, { recursive: true });
  200. await copyFile(fake.tarballPath, join(cacheDir, "npm-1.2.3.tgz"));
  201. const download = vi.fn();
  202. await stageBundledNpm({
  203. cacheDir,
  204. download,
  205. glmDir: join(root, "glm"),
  206. integrity: fake.integrity,
  207. version: "1.2.3",
  208. });
  209. expect(download).not.toHaveBeenCalled();
  210. });
  211. it("replaces a corrupt cached tarball", async () => {
  212. const root = await makeRoot();
  213. const fake = await createFakeNpmTarball(root);
  214. const cacheDir = join(root, "cache");
  215. await mkdir(cacheDir, { recursive: true });
  216. await writeFile(join(cacheDir, "npm-1.2.3.tgz"), "corrupt");
  217. const download = vi.fn(async (_url: string, destination: string) => {
  218. await copyFile(fake.tarballPath, destination);
  219. });
  220. await stageBundledNpm({
  221. cacheDir,
  222. download,
  223. glmDir: join(root, "glm"),
  224. integrity: fake.integrity,
  225. version: "1.2.3",
  226. });
  227. expect(download).toHaveBeenCalledTimes(1);
  228. expect(await readFile(join(cacheDir, "npm-1.2.3.tgz"))).toEqual(
  229. await readFile(fake.tarballPath),
  230. );
  231. });
  232. it("rejects a download whose sha512 does not match and keeps no cache", async () => {
  233. const root = await makeRoot();
  234. const fake = await createFakeNpmTarball(root);
  235. const cacheDir = join(root, "cache");
  236. await expect(
  237. stageBundledNpm({
  238. cacheDir,
  239. download: async (_url: string, destination: string) => {
  240. await copyFile(fake.tarballPath, destination);
  241. },
  242. glmDir: join(root, "glm"),
  243. integrity: "sha512-AAAA",
  244. version: "1.2.3",
  245. }),
  246. ).rejects.toThrow(/sha512 mismatch/);
  247. expect(existsSync(join(cacheDir, "npm-1.2.3.tgz"))).toBe(false);
  248. });
  249. it("fails when the package has no npx entry", async () => {
  250. const root = await makeRoot();
  251. const fake = await createFakeNpmTarball(root, { withNpx: false });
  252. await expect(
  253. stageBundledNpm({
  254. cacheDir: join(root, "cache"),
  255. download: async (_url: string, destination: string) => {
  256. await copyFile(fake.tarballPath, destination);
  257. },
  258. glmDir: join(root, "glm"),
  259. integrity: fake.integrity,
  260. version: "1.2.3",
  261. }),
  262. ).rejects.toThrow(/npx-cli\.js/);
  263. });
  264. });