packaging.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { promisify } from "node:util";
  8. import { gunzipSync } from "node:zlib";
  9. import { afterEach, describe, expect, it } from "vitest";
  10. import {
  11. collectBareModuleSpecifiers,
  12. isNodePtyRuntimePath,
  13. resolveProductionPackageClosure,
  14. stageRelease,
  15. } from "../src/packaging/stage.js";
  16. import { resolveHostTarCommand } from "../src/packaging/tarCommand.js";
  17. const execFileAsync = promisify(execFile);
  18. async function runTar(args: string[]): Promise<void> {
  19. await execFileAsync(resolveHostTarCommand(), args);
  20. }
  21. const temporaryDirs: string[] = [];
  22. const macIt = process.platform === "darwin" ? it : it.skip;
  23. async function makeTempDir(): Promise<string> {
  24. const dir = await mkdtemp(join(tmpdir(), "zcode-server-stage-test-"));
  25. temporaryDirs.push(dir);
  26. return dir;
  27. }
  28. afterEach(async () => {
  29. await Promise.all(
  30. temporaryDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })),
  31. );
  32. });
  33. interface FakePackageSpec {
  34. dependencies?: Record<string, string>;
  35. optionalDependencies?: Record<string, string>;
  36. devDependencies?: Record<string, string>;
  37. files?: Record<string, string>;
  38. }
  39. async function writeFakePackage(
  40. nodeModulesDir: string,
  41. name: string,
  42. spec: FakePackageSpec = {},
  43. ): Promise<string> {
  44. const packageDir = join(nodeModulesDir, ...name.split("/"));
  45. await mkdir(packageDir, { recursive: true });
  46. await writeFile(
  47. join(packageDir, "package.json"),
  48. JSON.stringify({
  49. name,
  50. version: "0.0.1",
  51. main: "./index.js",
  52. dependencies: spec.dependencies,
  53. optionalDependencies: spec.optionalDependencies,
  54. devDependencies: spec.devDependencies,
  55. }),
  56. "utf8",
  57. );
  58. await writeFile(join(packageDir, "index.js"), "module.exports = {};\n", "utf8");
  59. for (const [relativePath, contents] of Object.entries(spec.files ?? {})) {
  60. const filePath = join(packageDir, ...relativePath.split("/"));
  61. await mkdir(join(filePath, ".."), { recursive: true });
  62. await writeFile(filePath, contents, "utf8");
  63. }
  64. return packageDir;
  65. }
  66. describe("collectBareModuleSpecifiers", () => {
  67. it("extracts bare imports, dynamic imports and requires as package names", () => {
  68. const source = [
  69. 'import { Hono } from "hono";',
  70. 'import { serve } from "@hono/node-server";',
  71. 'const pty = await import("node-pty");',
  72. 'const utils = require("node-pty/lib/utils");',
  73. ].join("\n");
  74. const names = collectBareModuleSpecifiers(source);
  75. expect(names).toContain("hono");
  76. expect(names).toContain("@hono/node-server");
  77. expect(names).toContain("node-pty");
  78. });
  79. it("ignores node builtins and relative specifiers", () => {
  80. const source = [
  81. 'import { readFile } from "node:fs/promises";',
  82. 'import local from "./local.js";',
  83. 'import parent from "../parent.js";',
  84. ].join("\n");
  85. expect(collectBareModuleSpecifiers(source).size).toBe(0);
  86. });
  87. });
  88. describe("resolveProductionPackageClosure", () => {
  89. it("collects transitive production dependencies but not dev dependencies", async () => {
  90. const root = await makeTempDir();
  91. const nodeModulesDir = join(root, "node_modules");
  92. await writeFakePackage(nodeModulesDir, "pkg-a", {
  93. dependencies: { "pkg-b": "*" },
  94. devDependencies: { "pkg-dev": "*" },
  95. });
  96. await writeFakePackage(nodeModulesDir, "pkg-b", {
  97. dependencies: { "@scope/pkg-c": "*" },
  98. });
  99. await writeFakePackage(nodeModulesDir, "@scope/pkg-c");
  100. await writeFakePackage(nodeModulesDir, "pkg-dev");
  101. const closure = await resolveProductionPackageClosure(["pkg-a"], nodeModulesDir);
  102. expect([...closure.keys()].sort()).toEqual(["@scope/pkg-c", "pkg-a", "pkg-b"]);
  103. });
  104. it("skips missing optional dependencies and unknown entry packages", async () => {
  105. const root = await makeTempDir();
  106. const nodeModulesDir = join(root, "node_modules");
  107. await writeFakePackage(nodeModulesDir, "pkg-a", {
  108. optionalDependencies: { "pkg-missing-optional": "*" },
  109. });
  110. const closure = await resolveProductionPackageClosure(
  111. ["pkg-a", "pkg-not-installed"],
  112. nodeModulesDir,
  113. );
  114. expect([...closure.keys()]).toEqual(["pkg-a"]);
  115. });
  116. });
  117. describe("isNodePtyRuntimePath", () => {
  118. it("keeps runtime files and the target platform prebuild only", () => {
  119. expect(isNodePtyRuntimePath("package.json", "linux-x64")).toBe(true);
  120. expect(isNodePtyRuntimePath("lib/index.js", "linux-x64")).toBe(true);
  121. expect(isNodePtyRuntimePath("typings/node-pty.d.ts", "linux-x64")).toBe(true);
  122. expect(isNodePtyRuntimePath("prebuilds/linux-x64/pty.node", "linux-x64")).toBe(true);
  123. expect(isNodePtyRuntimePath("LICENSE", "linux-x64")).toBe(true);
  124. });
  125. it("drops host build outputs, sources and other platform prebuilds", () => {
  126. expect(isNodePtyRuntimePath("build/Release/pty.node", "linux-x64")).toBe(false);
  127. expect(isNodePtyRuntimePath("build/Debug/pty.node", "linux-x64")).toBe(false);
  128. expect(isNodePtyRuntimePath("prebuilds/darwin-arm64/pty.node", "linux-x64")).toBe(false);
  129. expect(isNodePtyRuntimePath("src/unix/pty.cc", "linux-x64")).toBe(false);
  130. expect(isNodePtyRuntimePath("deps/winpty/x.h", "linux-x64")).toBe(false);
  131. expect(isNodePtyRuntimePath("scripts/post-install.js", "linux-x64")).toBe(false);
  132. });
  133. });
  134. describe("stageRelease", () => {
  135. async function makeStageFixture(): Promise<{
  136. distDir: string;
  137. workspaceNodeModulesDir: string;
  138. agentBundlePath: string;
  139. nodeBinaryPath: string;
  140. outputDir: string;
  141. notices: { thirdParty: string; node: string; nodeSource: string };
  142. }> {
  143. const root = await makeTempDir();
  144. const distDir = join(root, "dist");
  145. await mkdir(distDir, { recursive: true });
  146. await writeFile(
  147. join(distDir, "server-cli.js"),
  148. 'import "fake-dep";\nimport "node-pty";\n',
  149. "utf8",
  150. );
  151. await writeFile(join(distDir, "server-core.js"), 'import "node:fs";\n', "utf8");
  152. const workspaceNodeModulesDir = join(root, "node_modules");
  153. await writeFakePackage(workspaceNodeModulesDir, "fake-dep", {
  154. dependencies: { "fake-transitive": "*" },
  155. });
  156. await writeFakePackage(workspaceNodeModulesDir, "fake-transitive");
  157. await writeFakePackage(workspaceNodeModulesDir, "node-pty", {
  158. files: {
  159. LICENSE: "node-pty license\n",
  160. "lib/index.js": "module.exports = {};\n",
  161. "typings/node-pty.d.ts": "export {};\n",
  162. "build/Release/pty.node": "host-binary",
  163. "prebuilds/darwin-arm64/pty.node": "darwin-binary",
  164. "prebuilds/darwin-arm64/spawn-helper": "darwin-helper",
  165. "prebuilds/win32-x64/pty.node": "windows-binary",
  166. },
  167. });
  168. await writeFakePackage(workspaceNodeModulesDir, "@lydell/node-pty-linux-x64", {
  169. files: { "prebuilds/linux-x64/pty.node": "linux-binary" },
  170. });
  171. const agentBundlePath = join(root, "zcode.cjs");
  172. await writeFile(agentBundlePath, "// fake agent bundle\n", "utf8");
  173. const nodeBinaryPath = join(root, "node-binary");
  174. await writeFile(nodeBinaryPath, "#!/bin/sh\nexit 0\n", "utf8");
  175. const outputDir = join(root, "out");
  176. const notices = {
  177. thirdParty: "Copyright npm\nComplete terms\n",
  178. node: "Copyright Node\nComplete runtime terms\n",
  179. nodeSource: '{"version":"22.16.0"}\n',
  180. };
  181. return {
  182. distDir,
  183. workspaceNodeModulesDir,
  184. agentBundlePath,
  185. nodeBinaryPath,
  186. outputDir,
  187. notices,
  188. };
  189. }
  190. async function writeFakeNativeTools(
  191. toolsDir: string,
  192. tools: Record<string, string>,
  193. ): Promise<void> {
  194. for (const [tool, binaryName] of Object.entries(tools)) {
  195. await mkdir(join(toolsDir, tool), { recursive: true });
  196. await writeFile(join(toolsDir, tool, binaryName), tool, "utf8");
  197. await writeFile(
  198. join(toolsDir, tool, "THIRD-PARTY-NOTICES.txt"),
  199. `Copyright ${tool}\nFull terms\n`,
  200. "utf8",
  201. );
  202. await writeFile(join(toolsDir, tool, "SOURCES.json"), JSON.stringify({ tool }), "utf8");
  203. }
  204. }
  205. it("assembles the release layout for a linux target", async () => {
  206. const fixture = await makeStageFixture();
  207. const staged = await stageRelease({
  208. target: "linux-x64",
  209. appVersion: "9.9.9-test",
  210. archive: false,
  211. ...fixture,
  212. });
  213. const releaseDir = staged.releaseDir;
  214. expect(releaseDir.endsWith("zcode-server-linux-x64")).toBe(true);
  215. const launcher = await readFile(join(releaseDir, "bin", "zcode"), "utf8");
  216. expect(launcher).toContain('"$DIR/runtime/node"');
  217. expect(launcher).toContain('"$DIR/runtime/server-cli.js"');
  218. const launcherStat = await stat(join(releaseDir, "bin", "zcode"));
  219. // Bugfix: NTFS 不保留 POSIX exec 位(Windows 上 stat.mode 恒无 0o111 位),
  220. // 可执行性断言只在 POSIX 宿主上生效;Windows 宿主仍验证文件存在与内容。
  221. if (process.platform !== "win32") expect(launcherStat.mode & 0o111).not.toBe(0);
  222. const runtimePackageJson = JSON.parse(
  223. await readFile(join(releaseDir, "runtime", "package.json"), "utf8"),
  224. ) as { type?: string };
  225. expect(runtimePackageJson.type).toBe("module");
  226. for (const relativePath of [
  227. "runtime/server-cli.js",
  228. "runtime/server-core.js",
  229. "runtime/zcode.cjs",
  230. "runtime/node",
  231. "runtime/node_modules/fake-dep/package.json",
  232. "runtime/node_modules/fake-transitive/package.json",
  233. "runtime/node_modules/node-pty/lib/index.js",
  234. "runtime/node_modules/node-pty/LICENSE",
  235. "runtime/THIRD-PARTY-NOTICES.md",
  236. "runtime/LICENSE.node.txt",
  237. "runtime/NODE-SOURCES.json",
  238. "runtime/licenses/agent/THIRD-PARTY-NOTICES.md",
  239. "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node",
  240. ]) {
  241. await expect(stat(join(releaseDir, ...relativePath.split("/")))).resolves.toBeTruthy();
  242. }
  243. const nodeStat = await stat(join(releaseDir, "runtime", "node"));
  244. // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
  245. if (process.platform !== "win32") expect(nodeStat.mode & 0o111).not.toBe(0);
  246. // 交叉打包安全性:宿主编译产物与非目标平台 prebuilds 不进入发行包。
  247. await expect(stat(join(releaseDir, "runtime/node_modules/node-pty/build"))).rejects.toThrow();
  248. await expect(
  249. stat(join(releaseDir, "runtime/node_modules/node-pty/prebuilds/darwin-arm64")),
  250. ).rejects.toThrow();
  251. // linux 平台 pty.node 由 @lydell 平台包补齐。
  252. const linuxPty = await readFile(
  253. join(releaseDir, "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node"),
  254. "utf8",
  255. );
  256. expect(linuxPty).toBe("linux-binary");
  257. const manifest = JSON.parse(await readFile(join(releaseDir, "manifest.json"), "utf8")) as {
  258. product: string;
  259. target: string;
  260. appVersion: string;
  261. nodeVersion: string;
  262. entrypoints: { cli: string; core: string; agent: string };
  263. };
  264. expect(manifest.product).toBe("zcode-server");
  265. expect(manifest.target).toBe("linux-x64");
  266. expect(manifest.appVersion).toBe("9.9.9-test");
  267. expect(manifest.nodeVersion).toBe("22.16.0");
  268. expect(manifest.entrypoints).toEqual({
  269. cli: "runtime/server-cli.js",
  270. core: "runtime/server-core.js",
  271. agent: "runtime/zcode.cjs",
  272. });
  273. expect(staged.packagedDependencies).toEqual(["fake-dep", "fake-transitive", "node-pty"]);
  274. expect(staged.archivePath).toBeNull();
  275. });
  276. it("keeps official darwin prebuilds including spawn-helper for darwin targets", async () => {
  277. const fixture = await makeStageFixture();
  278. const staged = await stageRelease({
  279. target: "darwin-arm64",
  280. appVersion: "9.9.9-test",
  281. archive: false,
  282. ...fixture,
  283. });
  284. const prebuildDir = join(
  285. staged.releaseDir,
  286. "runtime/node_modules/node-pty/prebuilds/darwin-arm64",
  287. );
  288. await expect(stat(join(prebuildDir, "pty.node"))).resolves.toBeTruthy();
  289. const helperStat = await stat(join(prebuildDir, "spawn-helper"));
  290. // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
  291. if (process.platform !== "win32") expect(helperStat.mode & 0o111).not.toBe(0);
  292. });
  293. it("stages a Windows target with a cmd launcher and zip archive", async () => {
  294. const fixture = await makeStageFixture();
  295. const toolsDir = join(await makeTempDir(), "tools");
  296. await writeFakeNativeTools(toolsDir, { ripgrep: "rg.exe", ugrep: "ugrep.exe" });
  297. const staged = await stageRelease({
  298. target: "win32-x64",
  299. appVersion: "9.9.9-test",
  300. nativeToolsDir: toolsDir,
  301. ...fixture,
  302. });
  303. expect(staged.archivePath).toMatch(/\.zip$/u);
  304. expect(await readFile(join(staged.releaseDir, "bin", "zcode.cmd"), "utf8")).toContain(
  305. "node.exe",
  306. );
  307. await expect(stat(join(staged.releaseDir, "runtime", "node.exe"))).resolves.toBeTruthy();
  308. await expect(
  309. stat(join(staged.releaseDir, "runtime", "tools", "ripgrep", "rg.exe")),
  310. ).resolves.toBeTruthy();
  311. await expect(
  312. stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "ugrep.exe")),
  313. ).resolves.toBeTruthy();
  314. await expect(
  315. stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "THIRD-PARTY-NOTICES.txt")),
  316. ).resolves.toBeTruthy();
  317. await expect(stat(join(staged.releaseDir, "runtime", "tools", "bfs"))).rejects.toThrow();
  318. });
  319. it("每个可独立下载的组件归档都携带适用的第三方声明", async () => {
  320. const fixture = await makeStageFixture();
  321. const toolsDir = join(await makeTempDir(), "tools");
  322. await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
  323. const staged = await stageRelease({
  324. target: "linux-x64",
  325. appVersion: "9.9.9-test",
  326. nativeToolsDir: toolsDir,
  327. ...fixture,
  328. });
  329. const manifest = JSON.parse(
  330. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  331. ) as {
  332. components: Array<{ id: string; archivePath: string }>;
  333. };
  334. const expected: Record<string, string[]> = {
  335. "node-runtime": ["runtime/LICENSE.node.txt", "runtime/NODE-SOURCES.json"],
  336. "server-runtime": ["runtime/THIRD-PARTY-NOTICES.md", "runtime/node_modules/node-pty/LICENSE"],
  337. "agent-runtime": ["runtime/licenses/agent/THIRD-PARTY-NOTICES.md"],
  338. "native-search-tools": [
  339. "runtime/tools/ripgrep/THIRD-PARTY-NOTICES.txt",
  340. "runtime/tools/ugrep/SOURCES.json",
  341. ],
  342. };
  343. expect(manifest.components.map((component) => component.id).sort()).toEqual(
  344. Object.keys(expected).sort(),
  345. );
  346. const extractRoot = await makeTempDir();
  347. for (const component of manifest.components) {
  348. const extractDir = join(extractRoot, component.id);
  349. await mkdir(extractDir, { recursive: true });
  350. await runTar(["-xf", join(fixture.outputDir, component.archivePath), "-C", extractDir]);
  351. for (const member of expected[component.id] ?? []) {
  352. expect(await readFile(join(extractDir, member))).toEqual(
  353. await readFile(join(staged.releaseDir, member)),
  354. );
  355. }
  356. }
  357. });
  358. it.each([true, false])(
  359. "工具目录缺少声明或声明参数为空时拒绝组装发行包(componentArchives=%s)",
  360. async (componentArchives) => {
  361. const fixture = await makeStageFixture();
  362. const toolsDir = join(await makeTempDir(), "tools");
  363. await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
  364. await rm(join(toolsDir, "ripgrep", "THIRD-PARTY-NOTICES.txt"));
  365. await expect(
  366. stageRelease({
  367. target: "linux-x64",
  368. appVersion: "9.9.9-test",
  369. archive: false,
  370. nativeToolsDir: toolsDir,
  371. componentArchives,
  372. ...fixture,
  373. }),
  374. ).rejects.toThrow(/ENOENT/u);
  375. await expect(
  376. stageRelease({
  377. target: "linux-x64",
  378. appVersion: "9.9.9-test",
  379. archive: false,
  380. ...fixture,
  381. notices: { ...fixture.notices, node: " " },
  382. componentArchives,
  383. }),
  384. ).rejects.toThrow(/Missing distribution notice: node/u);
  385. },
  386. );
  387. macIt("omits macOS extended attributes from POSIX release archives", async () => {
  388. const fixture = await makeStageFixture();
  389. await execFileAsync("xattr", ["-w", "com.example.zcode", "value", fixture.nodeBinaryPath]);
  390. const staged = await stageRelease({
  391. target: "linux-x64",
  392. appVersion: "9.9.9-test",
  393. ...fixture,
  394. });
  395. const archive = gunzipSync(await readFile(staged.archivePath ?? ""));
  396. const tarText = archive.toString("latin1");
  397. expect(tarText).not.toContain("LIBARCHIVE.xattr");
  398. expect(tarText).not.toContain("SCHILY.xattr");
  399. });
  400. async function writeOfficialPluginFixture(
  401. officialPluginsDir: string,
  402. name: string,
  403. options: { mcpEntry?: string; withMcpEntryFile?: boolean; withManifest?: boolean } = {},
  404. ): Promise<void> {
  405. const pluginDir = join(officialPluginsDir, name);
  406. await mkdir(join(pluginDir, ".zcode-plugin"), { recursive: true });
  407. await writeFile(join(pluginDir, "README.md"), name, "utf8");
  408. // 真实官方插件的 package.json 都是 tracked 文件,是"该目录属于当前 checkout"的判据。
  409. await writeFile(
  410. join(pluginDir, "package.json"),
  411. JSON.stringify({ name: `@zcode/${name}`, private: true }),
  412. "utf8",
  413. );
  414. const manifest: Record<string, unknown> = {
  415. name: name.replace(/-plugin$/u, ""),
  416. version: "0.1.0",
  417. };
  418. if (options.mcpEntry) {
  419. manifest.mcpServers = {
  420. [name]: { command: "node", args: [`\${ZCODE_PLUGIN_ROOT}/${options.mcpEntry}`] },
  421. };
  422. if (options.withMcpEntryFile !== false) {
  423. const entryPath = join(pluginDir, ...options.mcpEntry.split("/"));
  424. await mkdir(join(entryPath, ".."), { recursive: true });
  425. await writeFile(entryPath, "// mcp server\n", "utf8");
  426. }
  427. }
  428. if (options.withManifest !== false) {
  429. await writeFile(
  430. join(pluginDir, ".zcode-plugin", "plugin.json"),
  431. JSON.stringify(manifest),
  432. "utf8",
  433. );
  434. }
  435. }
  436. it("stages the official plugin set and excludes the on-demand superpowers package", async () => {
  437. const fixture = await makeStageFixture();
  438. const officialPluginsDir = join(await makeTempDir(), "packages");
  439. const pluginNames = [
  440. "android-emulator-plugin",
  441. "browser-use-plugin",
  442. "document-skills-plugin",
  443. "ios-simulator-plugin",
  444. "restore-legacy-sessions-plugin",
  445. "skill-creator-plugin",
  446. "zcode-guide-plugin",
  447. "superpowers-plugin",
  448. ];
  449. const mcpRuntimePlugins = new Set([
  450. "android-emulator-plugin",
  451. "browser-use-plugin",
  452. "ios-simulator-plugin",
  453. ]);
  454. for (const name of pluginNames) {
  455. await writeOfficialPluginFixture(
  456. officialPluginsDir,
  457. name,
  458. mcpRuntimePlugins.has(name) ? { mcpEntry: "dist/mcp/server.js" } : {},
  459. );
  460. }
  461. const staged = await stageRelease({
  462. target: "linux-x64",
  463. appVersion: "9.9.9-test",
  464. archive: false,
  465. officialPluginsDir,
  466. ...fixture,
  467. });
  468. for (const name of pluginNames.filter((name) => name !== "superpowers-plugin")) {
  469. await expect(
  470. stat(join(staged.releaseDir, "runtime/packages", name, "README.md")),
  471. ).resolves.toBeTruthy();
  472. }
  473. for (const name of mcpRuntimePlugins) {
  474. await expect(
  475. stat(join(staged.releaseDir, "runtime/packages", name, "dist/mcp/server.js")),
  476. ).resolves.toBeTruthy();
  477. }
  478. await expect(
  479. stat(join(staged.releaseDir, "runtime/packages/superpowers-plugin")),
  480. ).rejects.toThrow();
  481. const manifest = JSON.parse(
  482. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  483. ) as {
  484. plugins?: string[];
  485. components?: Array<{ id: string }>;
  486. };
  487. expect(manifest.plugins).toEqual([
  488. "android-emulator",
  489. "browser-use",
  490. "document-skills",
  491. "ios-simulator",
  492. "restore-legacy-sessions",
  493. "skill-creator",
  494. "zcode-guide",
  495. ]);
  496. expect(manifest.components?.some((component) => component.id === "official-plugins")).toBe(
  497. true,
  498. );
  499. });
  500. it.each([true, false])(
  501. "fails closed on a missing MCP entry with componentArchives=%s",
  502. async (componentArchives) => {
  503. // Bug 原因:插件 dist 被 gitignore,干净 CI 工作区里 android-emulator / ios-simulator 没有
  504. // dist/mcp/server.js;legacy prepare-prebuilds.mjs 曾构建并断言该文件,切到 stageRelease 后只剩
  505. // 整目录复制,archive 会静默带上只有 plugin.json 与 skills、缺 MCP 入口的插件。staging 必须以
  506. // plugin.json 的 mcpServers 声明为事实源 fail-closed。
  507. const fixture = await makeStageFixture();
  508. const officialPluginsDir = join(await makeTempDir(), "packages");
  509. await writeOfficialPluginFixture(officialPluginsDir, "android-emulator-plugin", {
  510. mcpEntry: "dist/mcp/server.js",
  511. withMcpEntryFile: false,
  512. });
  513. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  514. await expect(
  515. stageRelease({
  516. target: "linux-x64",
  517. appVersion: "9.9.9-test",
  518. archive: false,
  519. officialPluginsDir,
  520. componentArchives,
  521. ...fixture,
  522. }),
  523. ).rejects.toThrow(/android-emulator-plugin[\s\S]*dist\/mcp\/server\.js/u);
  524. },
  525. );
  526. it("fails closed when a staged official plugin has no plugin manifest", async () => {
  527. const fixture = await makeStageFixture();
  528. const officialPluginsDir = join(await makeTempDir(), "packages");
  529. await writeOfficialPluginFixture(officialPluginsDir, "ios-simulator-plugin", {
  530. withManifest: false,
  531. });
  532. await expect(
  533. stageRelease({
  534. target: "linux-x64",
  535. appVersion: "9.9.9-test",
  536. archive: false,
  537. officialPluginsDir,
  538. ...fixture,
  539. }),
  540. ).rejects.toThrow(/ios-simulator-plugin[\s\S]*plugin\.json/u);
  541. });
  542. it("ignores orphaned *-plugin directories left behind by a previous checkout", async () => {
  543. // Bug 原因:CI 用 GIT_CLEAN_FLAGS "-e node_modules/" 跨 job 保留 node_modules,其它分支
  544. // (例如曾把 zcode-cua-plugin 改名为 computer-use-plugin 的分支)install 过的插件目录切回本
  545. // 分支后只剩 node_modules,tracked 文件全被 checkout 删掉。旧规则仅按 "-plugin" 后缀识别官方
  546. // 插件,会把这种僵尸目录当插件 stage,随后 fail-closed 校验读不到 plugin.json 而整段失败。
  547. const fixture = await makeStageFixture();
  548. const officialPluginsDir = join(await makeTempDir(), "packages");
  549. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  550. const orphanDir = join(officialPluginsDir, "computer-use-plugin");
  551. await mkdir(join(orphanDir, "node_modules", "@zcode", "computer-use"), { recursive: true });
  552. await writeFile(
  553. join(orphanDir, "node_modules", "@zcode", "computer-use", "package.json"),
  554. "{}",
  555. "utf8",
  556. );
  557. const staged = await stageRelease({
  558. target: "linux-x64",
  559. appVersion: "9.9.9-test",
  560. archive: false,
  561. officialPluginsDir,
  562. ...fixture,
  563. });
  564. await expect(
  565. stat(join(staged.releaseDir, "runtime/packages/computer-use-plugin")),
  566. ).rejects.toThrow();
  567. const manifest = JSON.parse(
  568. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  569. ) as { plugins?: string[] };
  570. expect(manifest.plugins).toEqual(["zcode-guide"]);
  571. });
  572. it("removes stale component archives before restaging a target", async () => {
  573. const fixture = await makeStageFixture();
  574. const staleDir = join(fixture.outputDir, "components", "linux-x64");
  575. await mkdir(staleDir, { recursive: true });
  576. await writeFile(join(staleDir, "stale-component.tar.gz"), "stale", "utf8");
  577. await stageRelease({
  578. target: "linux-x64",
  579. appVersion: "9.9.9-test",
  580. archive: false,
  581. ...fixture,
  582. });
  583. await expect(stat(join(staleDir, "stale-component.tar.gz"))).rejects.toThrow();
  584. });
  585. it.each(["linux-x64", "linux-arm64"] as const)(
  586. "stages an installable full %s archive without standalone components",
  587. async (target) => {
  588. const fixture = await makeStageFixture();
  589. await writeFakePackage(fixture.workspaceNodeModulesDir, "@lydell/node-pty-linux-arm64", {
  590. files: { "prebuilds/linux-arm64/pty.node": "linux-arm64-binary" },
  591. });
  592. const options = { ...fixture, target, appVersion: "9.9.9-test" };
  593. const original = await stageRelease(options);
  594. expect(original.componentArchivePaths.length).toBeGreaterThan(0);
  595. const expected = JSON.parse(
  596. await readFile(join(original.releaseDir, "manifest.json"), "utf8"),
  597. );
  598. for (const component of expected.components) {
  599. expect(component.archivePath).toBeTruthy();
  600. delete component.archivePath;
  601. }
  602. const staged = await stageRelease({ ...options, componentArchives: false });
  603. expect(staged.componentArchivePaths).toEqual([]);
  604. await expect(stat(join(fixture.outputDir, "components", target))).rejects.toMatchObject({
  605. code: "ENOENT",
  606. });
  607. await expect(stat(join(fixture.outputDir, ".components"))).rejects.toMatchObject({
  608. code: "ENOENT",
  609. });
  610. const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
  611. expect(manifest).toEqual(expected);
  612. // 用真实整包 installer 验证没有组件 archivePath 仍可安装,且整包摘要校验仍会拒绝错误身份。
  613. const { ReleaseInstaller } = await import(
  614. fileURLToPath(new URL("../src/runtime/releaseInstaller.ts", import.meta.url))
  615. );
  616. const { resolveServerLayout } = await import(
  617. fileURLToPath(new URL("../src/runtime/paths.ts", import.meta.url))
  618. );
  619. const installer = new ReleaseInstaller(
  620. resolveServerLayout(join(await makeTempDir(), "server")),
  621. );
  622. const archivePath = staged.archivePath!;
  623. const archiveSha256 = createHash("sha256")
  624. .update(await readFile(archivePath))
  625. .digest("hex");
  626. await expect(
  627. installer.installArchive({ archivePath, target, archiveSha256: "0".repeat(64) }),
  628. ).rejects.toThrow(/checksum mismatch/);
  629. const installed = await installer.installArchive({ archivePath, target, archiveSha256 });
  630. expect(
  631. JSON.parse(await readFile(join(installed.releaseDir, "manifest.json"), "utf8")),
  632. ).toEqual(expected);
  633. expect(await readFile(join(installed.releaseDir, "runtime", "zcode.cjs"))).toEqual(
  634. await readFile(fixture.agentBundlePath),
  635. );
  636. },
  637. );
  638. });