packaging.test.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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 {
  17. assertNodePtyNativeMatchesJs,
  18. isTargetSpecificPackage,
  19. } from "../src/packaging/stageDependencies.js";
  20. import { resolveHostTarCommand } from "../src/packaging/tarCommand.js";
  21. const execFileAsync = promisify(execFile);
  22. async function runTar(args: string[]): Promise<void> {
  23. await execFileAsync(resolveHostTarCommand(), args);
  24. }
  25. const temporaryDirs: string[] = [];
  26. const macIt = process.platform === "darwin" ? it : it.skip;
  27. async function makeTempDir(): Promise<string> {
  28. const dir = await mkdtemp(join(tmpdir(), "zcode-server-stage-test-"));
  29. temporaryDirs.push(dir);
  30. return dir;
  31. }
  32. afterEach(async () => {
  33. await Promise.all(
  34. temporaryDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })),
  35. );
  36. });
  37. interface FakePackageSpec {
  38. version?: string;
  39. dependencies?: Record<string, string>;
  40. optionalDependencies?: Record<string, string>;
  41. devDependencies?: Record<string, string>;
  42. files?: Record<string, string>;
  43. }
  44. async function writeFakePackage(
  45. nodeModulesDir: string,
  46. name: string,
  47. spec: FakePackageSpec = {},
  48. ): Promise<string> {
  49. const packageDir = join(nodeModulesDir, ...name.split("/"));
  50. await mkdir(packageDir, { recursive: true });
  51. await writeFile(
  52. join(packageDir, "package.json"),
  53. JSON.stringify({
  54. name,
  55. version: spec.version ?? "0.0.1",
  56. main: "./index.js",
  57. dependencies: spec.dependencies,
  58. optionalDependencies: spec.optionalDependencies,
  59. devDependencies: spec.devDependencies,
  60. }),
  61. "utf8",
  62. );
  63. await writeFile(join(packageDir, "index.js"), "module.exports = {};\n", "utf8");
  64. for (const [relativePath, contents] of Object.entries(spec.files ?? {})) {
  65. const filePath = join(packageDir, ...relativePath.split("/"));
  66. await mkdir(join(filePath, ".."), { recursive: true });
  67. await writeFile(filePath, contents, "utf8");
  68. }
  69. return packageDir;
  70. }
  71. describe("collectBareModuleSpecifiers", () => {
  72. it("extracts bare imports, dynamic imports and requires as package names", () => {
  73. const source = [
  74. 'import { Hono } from "hono";',
  75. 'import { serve } from "@hono/node-server";',
  76. 'const pty = await import("node-pty");',
  77. 'const utils = require("node-pty/lib/utils");',
  78. ].join("\n");
  79. const names = collectBareModuleSpecifiers(source);
  80. expect(names).toContain("hono");
  81. expect(names).toContain("@hono/node-server");
  82. expect(names).toContain("node-pty");
  83. });
  84. it("ignores node builtins and relative specifiers", () => {
  85. const source = [
  86. 'import { readFile } from "node:fs/promises";',
  87. 'import local from "./local.js";',
  88. 'import parent from "../parent.js";',
  89. ].join("\n");
  90. expect(collectBareModuleSpecifiers(source).size).toBe(0);
  91. });
  92. });
  93. describe("resolveProductionPackageClosure", () => {
  94. it("collects transitive production dependencies but not dev dependencies", async () => {
  95. const root = await makeTempDir();
  96. const nodeModulesDir = join(root, "node_modules");
  97. await writeFakePackage(nodeModulesDir, "pkg-a", {
  98. dependencies: { "pkg-b": "*" },
  99. devDependencies: { "pkg-dev": "*" },
  100. });
  101. await writeFakePackage(nodeModulesDir, "pkg-b", {
  102. dependencies: { "@scope/pkg-c": "*" },
  103. });
  104. await writeFakePackage(nodeModulesDir, "@scope/pkg-c");
  105. await writeFakePackage(nodeModulesDir, "pkg-dev");
  106. const closure = await resolveProductionPackageClosure(["pkg-a"], nodeModulesDir);
  107. expect([...closure.keys()].sort()).toEqual(["@scope/pkg-c", "pkg-a", "pkg-b"]);
  108. });
  109. it("skips missing optional dependencies and unknown entry packages", async () => {
  110. const root = await makeTempDir();
  111. const nodeModulesDir = join(root, "node_modules");
  112. await writeFakePackage(nodeModulesDir, "pkg-a", {
  113. optionalDependencies: { "pkg-missing-optional": "*" },
  114. });
  115. const closure = await resolveProductionPackageClosure(
  116. ["pkg-a", "pkg-not-installed"],
  117. nodeModulesDir,
  118. );
  119. expect([...closure.keys()]).toEqual(["pkg-a"]);
  120. });
  121. });
  122. describe("isNodePtyRuntimePath", () => {
  123. it("keeps runtime files and the target platform prebuild only", () => {
  124. expect(isNodePtyRuntimePath("package.json", "linux-x64")).toBe(true);
  125. expect(isNodePtyRuntimePath("lib/index.js", "linux-x64")).toBe(true);
  126. expect(isNodePtyRuntimePath("typings/node-pty.d.ts", "linux-x64")).toBe(true);
  127. expect(isNodePtyRuntimePath("prebuilds/linux-x64/pty.node", "linux-x64")).toBe(true);
  128. expect(isNodePtyRuntimePath("LICENSE", "linux-x64")).toBe(true);
  129. });
  130. it("drops host build outputs, sources and other platform prebuilds", () => {
  131. expect(isNodePtyRuntimePath("build/Release/pty.node", "linux-x64")).toBe(false);
  132. expect(isNodePtyRuntimePath("build/Debug/pty.node", "linux-x64")).toBe(false);
  133. expect(isNodePtyRuntimePath("prebuilds/darwin-arm64/pty.node", "linux-x64")).toBe(false);
  134. expect(isNodePtyRuntimePath("src/unix/pty.cc", "linux-x64")).toBe(false);
  135. expect(isNodePtyRuntimePath("deps/winpty/x.h", "linux-x64")).toBe(false);
  136. expect(isNodePtyRuntimePath("scripts/post-install.js", "linux-x64")).toBe(false);
  137. });
  138. });
  139. describe("assertNodePtyNativeMatchesJs", () => {
  140. it("rejects a native prebuild whose source version differs from the node-pty JS", () => {
  141. // 现场组合:官方 node-pty 1.1.0 JS + @lydell 1.2.0-beta.10 native。
  142. expect(() =>
  143. assertNodePtyNativeMatchesJs({
  144. target: "linux-x64",
  145. jsVersion: "1.1.0",
  146. nativeSource: "@lydell/node-pty-linux-x64",
  147. nativeVersion: "1.2.0-beta.10",
  148. }),
  149. ).toThrow(/node-pty JS 1\.1\.0 .*@lydell\/node-pty-linux-x64 1\.2\.0-beta\.10/);
  150. });
  151. it("accepts JS and native from the same version", () => {
  152. expect(() =>
  153. assertNodePtyNativeMatchesJs({
  154. target: "linux-x64",
  155. jsVersion: "1.2.0-beta.10",
  156. nativeSource: "@lydell/node-pty-linux-x64",
  157. nativeVersion: "1.2.0-beta.10",
  158. }),
  159. ).not.toThrow();
  160. });
  161. });
  162. describe("stageRelease", () => {
  163. async function makeStageFixture(): Promise<{
  164. distDir: string;
  165. workspaceNodeModulesDir: string;
  166. agentBundlePath: string;
  167. bundledSkillsDir: string;
  168. nodeBinaryPath: string;
  169. outputDir: string;
  170. notices: { thirdParty: string; node: string; nodeSource: string };
  171. }> {
  172. const root = await makeTempDir();
  173. const distDir = join(root, "dist");
  174. await mkdir(distDir, { recursive: true });
  175. await writeFile(
  176. join(distDir, "server-cli.js"),
  177. 'import "fake-dep";\nimport "node-pty";\n',
  178. "utf8",
  179. );
  180. await writeFile(join(distDir, "server-core.js"), 'import "node:fs";\n', "utf8");
  181. const workspaceNodeModulesDir = join(root, "node_modules");
  182. await writeFakePackage(workspaceNodeModulesDir, "fake-dep", {
  183. dependencies: { "fake-transitive": "*" },
  184. });
  185. await writeFakePackage(workspaceNodeModulesDir, "fake-transitive");
  186. await writeFakePackage(workspaceNodeModulesDir, "node-pty", {
  187. version: "1.1.0",
  188. files: {
  189. LICENSE: "node-pty license\n",
  190. "lib/index.js": "// official node-pty js\n",
  191. "typings/node-pty.d.ts": "export {};\n",
  192. "build/Release/pty.node": "host-binary",
  193. "prebuilds/darwin-arm64/pty.node": "darwin-binary",
  194. "prebuilds/darwin-arm64/spawn-helper": "darwin-helper",
  195. "prebuilds/win32-x64/pty.node": "windows-binary",
  196. },
  197. });
  198. // 平台包是同版本 node-pty 的 linux 子集:JS 与 native 同在一个包里。
  199. await writeFakePackage(workspaceNodeModulesDir, "@lydell/node-pty-linux-x64", {
  200. version: "1.2.0-beta.10",
  201. files: {
  202. LICENSE: "platform license\n",
  203. "lib/index.js": "// platform node-pty js\n",
  204. "prebuilds/linux-x64/pty.node": "linux-binary",
  205. },
  206. });
  207. const bundledSkillsDir = join(root, "bundled-skills");
  208. await mkdir(join(bundledSkillsDir, "skills/dynamic-workflows"), { recursive: true });
  209. await writeFile(join(bundledSkillsDir, "README.md"), "bundled skills");
  210. await writeFile(join(bundledSkillsDir, "scratch.txt"), "local only");
  211. for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
  212. await writeFile(join(bundledSkillsDir, "skills/dynamic-workflows", name), `fixture ${name}`);
  213. }
  214. const agentBundlePath = join(root, "zcode.cjs");
  215. await writeFile(agentBundlePath, "// fake agent bundle\n", "utf8");
  216. const nodeBinaryPath = join(root, "node-binary");
  217. await writeFile(nodeBinaryPath, "#!/bin/sh\nexit 0\n", "utf8");
  218. const outputDir = join(root, "out");
  219. const notices = {
  220. thirdParty: "Copyright npm\nComplete terms\n",
  221. node: "Copyright Node\nComplete runtime terms\n",
  222. nodeSource: '{"version":"22.16.0"}\n',
  223. };
  224. return {
  225. distDir,
  226. workspaceNodeModulesDir,
  227. agentBundlePath,
  228. bundledSkillsDir,
  229. nodeBinaryPath,
  230. outputDir,
  231. notices,
  232. };
  233. }
  234. async function writeFakeNativeTools(
  235. toolsDir: string,
  236. tools: Record<string, string>,
  237. ): Promise<void> {
  238. for (const [tool, binaryName] of Object.entries(tools)) {
  239. await mkdir(join(toolsDir, tool), { recursive: true });
  240. await writeFile(join(toolsDir, tool, binaryName), tool, "utf8");
  241. await writeFile(
  242. join(toolsDir, tool, "THIRD-PARTY-NOTICES.txt"),
  243. `Copyright ${tool}\nFull terms\n`,
  244. "utf8",
  245. );
  246. await writeFile(join(toolsDir, tool, "SOURCES.json"), JSON.stringify({ tool }), "utf8");
  247. }
  248. }
  249. it("assembles the release layout for a linux target", async () => {
  250. const fixture = await makeStageFixture();
  251. const staged = await stageRelease({
  252. target: "linux-x64",
  253. appVersion: "9.9.9-test",
  254. archive: false,
  255. ...fixture,
  256. });
  257. const releaseDir = staged.releaseDir;
  258. expect(releaseDir.endsWith("zcode-server-linux-x64")).toBe(true);
  259. expect(
  260. JSON.parse(await readFile(join(releaseDir, "runtime", "package.json"), "utf8")),
  261. ).toMatchObject({
  262. zcodeCredentialFormat: 2,
  263. });
  264. const launcher = await readFile(join(releaseDir, "bin", "zcode"), "utf8");
  265. expect(launcher).toContain('"$DIR/runtime/node"');
  266. expect(launcher).toContain('"$DIR/runtime/server-cli.js"');
  267. const launcherStat = await stat(join(releaseDir, "bin", "zcode"));
  268. // Bugfix: NTFS 不保留 POSIX exec 位(Windows 上 stat.mode 恒无 0o111 位),
  269. // 可执行性断言只在 POSIX 宿主上生效;Windows 宿主仍验证文件存在与内容。
  270. if (process.platform !== "win32") expect(launcherStat.mode & 0o111).not.toBe(0);
  271. const runtimePackageJson = JSON.parse(
  272. await readFile(join(releaseDir, "runtime", "package.json"), "utf8"),
  273. ) as { type?: string };
  274. expect(runtimePackageJson.type).toBe("module");
  275. for (const relativePath of [
  276. "runtime/server-cli.js",
  277. "runtime/server-core.js",
  278. "runtime/zcode.cjs",
  279. "runtime/node",
  280. "runtime/node_modules/fake-dep/package.json",
  281. "runtime/node_modules/fake-transitive/package.json",
  282. "runtime/node_modules/node-pty/lib/index.js",
  283. "runtime/node_modules/node-pty/LICENSE",
  284. "runtime/THIRD-PARTY-NOTICES.md",
  285. "runtime/LICENSE.node.txt",
  286. "runtime/NODE-SOURCES.json",
  287. "runtime/licenses/agent/THIRD-PARTY-NOTICES.md",
  288. "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node",
  289. ]) {
  290. await expect(stat(join(releaseDir, ...relativePath.split("/")))).resolves.toBeTruthy();
  291. }
  292. const nodeStat = await stat(join(releaseDir, "runtime", "node"));
  293. // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
  294. if (process.platform !== "win32") expect(nodeStat.mode & 0o111).not.toBe(0);
  295. // 交叉打包安全性:宿主编译产物与非目标平台 prebuilds 不进入发行包。
  296. await expect(stat(join(releaseDir, "runtime/node_modules/node-pty/build"))).rejects.toThrow();
  297. await expect(
  298. stat(join(releaseDir, "runtime/node_modules/node-pty/prebuilds/darwin-arm64")),
  299. ).rejects.toThrow();
  300. // linux 平台 pty.node 由 @lydell 平台包补齐。
  301. const linuxPty = await readFile(
  302. join(releaseDir, "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node"),
  303. "utf8",
  304. );
  305. expect(linuxPty).toBe("linux-binary");
  306. // Bug 回归:旧 staging 只拷平台包的 pty.node(1.2.0-beta.10,resize 要 5 个参数),
  307. // JS 仍是官方 1.1.0(只传 3 个参数),远端终端 resize 必然失败。JS 必须与 native 同包同版本。
  308. const stagedNodePty = JSON.parse(
  309. await readFile(join(releaseDir, "runtime/node_modules/node-pty/package.json"), "utf8"),
  310. ) as { version: string };
  311. expect(stagedNodePty.version).toBe("1.2.0-beta.10");
  312. await expect(
  313. readFile(join(releaseDir, "runtime/node_modules/node-pty/lib/index.js"), "utf8"),
  314. ).resolves.toBe("// platform node-pty js\n");
  315. await expect(stat(join(releaseDir, "runtime/node_modules/node-pty/typings"))).rejects.toThrow();
  316. const manifest = JSON.parse(await readFile(join(releaseDir, "manifest.json"), "utf8")) as {
  317. product: string;
  318. target: string;
  319. appVersion: string;
  320. nodeVersion: string;
  321. entrypoints: { cli: string; core: string; agent: string };
  322. };
  323. expect(manifest.product).toBe("zcode-server");
  324. expect(manifest.target).toBe("linux-x64");
  325. expect(manifest.appVersion).toBe("9.9.9-test");
  326. expect(manifest.nodeVersion).toBe("22.16.0");
  327. expect(manifest.entrypoints).toEqual({
  328. cli: "runtime/server-cli.js",
  329. core: "runtime/server-core.js",
  330. agent: "runtime/zcode.cjs",
  331. });
  332. expect(staged.packagedDependencies).toEqual(["fake-dep", "fake-transitive", "node-pty"]);
  333. expect(staged.archivePath).toBeNull();
  334. });
  335. it("fails closed when the linux platform package cannot supply matching node-pty JS", async () => {
  336. const fixture = await makeStageFixture();
  337. // 只有 pty.node、没有 lib 的平台包无法提供同版本 JS;不能退回“官方 JS + 平台 native”混装。
  338. await rm(join(fixture.workspaceNodeModulesDir, "@lydell", "node-pty-linux-x64", "lib"), {
  339. recursive: true,
  340. force: true,
  341. });
  342. await expect(
  343. stageRelease({ target: "linux-x64", appVersion: "9.9.9-test", archive: false, ...fixture }),
  344. ).rejects.toThrow(/@lydell\/node-pty-linux-x64 does not ship node-pty JS/);
  345. });
  346. it("takes the whole linux platform package even when the workspace node-pty already has a linux native", async () => {
  347. const fixture = await makeStageFixture();
  348. // Bug 场景:同一 checkout 先做桌面 Linux 打包,beforePack 把平台包的 pty.node 回填进共享的
  349. // 官方 node-pty。旧逻辑看到 pty.node 已存在就跳过整包替换,产出官方 1.1.0 JS + 1.2.0-beta.10 native。
  350. const backfilledDir = join(
  351. fixture.workspaceNodeModulesDir,
  352. "node-pty",
  353. "prebuilds",
  354. "linux-x64",
  355. );
  356. await mkdir(backfilledDir, { recursive: true });
  357. await writeFile(join(backfilledDir, "pty.node"), "desktop-backfilled-binary", "utf8");
  358. const staged = await stageRelease({
  359. target: "linux-x64",
  360. appVersion: "9.9.9-test",
  361. archive: false,
  362. ...fixture,
  363. });
  364. const stagedNodePtyDir = join(staged.releaseDir, "runtime/node_modules/node-pty");
  365. const stagedNodePty = JSON.parse(
  366. await readFile(join(stagedNodePtyDir, "package.json"), "utf8"),
  367. ) as { version: string };
  368. expect(stagedNodePty.version).toBe("1.2.0-beta.10");
  369. await expect(readFile(join(stagedNodePtyDir, "lib/index.js"), "utf8")).resolves.toBe(
  370. "// platform node-pty js\n",
  371. );
  372. await expect(
  373. readFile(join(stagedNodePtyDir, "prebuilds/linux-x64/pty.node"), "utf8"),
  374. ).resolves.toBe("linux-binary");
  375. });
  376. it("keeps official darwin JS and prebuilds including spawn-helper for darwin targets", async () => {
  377. const fixture = await makeStageFixture();
  378. const staged = await stageRelease({
  379. target: "darwin-arm64",
  380. appVersion: "9.9.9-test",
  381. archive: false,
  382. ...fixture,
  383. });
  384. const prebuildDir = join(
  385. staged.releaseDir,
  386. "runtime/node_modules/node-pty/prebuilds/darwin-arm64",
  387. );
  388. await expect(stat(join(prebuildDir, "pty.node"))).resolves.toBeTruthy();
  389. // darwin 官方包自带同版本 prebuild,JS 保持官方包,不受 linux 平台包影响。
  390. await expect(
  391. readFile(join(staged.releaseDir, "runtime/node_modules/node-pty/lib/index.js"), "utf8"),
  392. ).resolves.toBe("// official node-pty js\n");
  393. const helperStat = await stat(join(prebuildDir, "spawn-helper"));
  394. // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
  395. if (process.platform !== "win32") expect(helperStat.mode & 0o111).not.toBe(0);
  396. });
  397. it("stages a Windows target with a cmd launcher and zip archive", async () => {
  398. const fixture = await makeStageFixture();
  399. const toolsDir = join(await makeTempDir(), "tools");
  400. await writeFakeNativeTools(toolsDir, { ripgrep: "rg.exe", ugrep: "ugrep.exe" });
  401. // Job 宿主属于必需的 server-runtime;漏包时必须在发布前失败。
  402. await expect(
  403. stageRelease({
  404. target: "win32-x64",
  405. appVersion: "9.9.9-test",
  406. nativeToolsDir: toolsDir,
  407. ...fixture,
  408. }),
  409. ).rejects.toThrow(/runtime-host/);
  410. await mkdir(join(toolsDir, "runtime-host"), { recursive: true });
  411. await writeFile(join(toolsDir, "runtime-host/zcode-runtime-host.exe"), "fixture runtime host");
  412. const staged = await stageRelease({
  413. target: "win32-x64",
  414. appVersion: "9.9.9-test",
  415. nativeToolsDir: toolsDir,
  416. ...fixture,
  417. });
  418. await expect(
  419. readFile(
  420. join(staged.releaseDir, "runtime/tools/runtime-host/zcode-runtime-host.exe"),
  421. "utf8",
  422. ),
  423. ).resolves.toBe("fixture runtime host");
  424. const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
  425. expect(
  426. manifest.components.find((component: { id: string }) => component.id === "server-runtime")
  427. .paths,
  428. ).toContain("runtime/tools/runtime-host");
  429. expect(
  430. manifest.components.find(
  431. (component: { id: string }) => component.id === "native-search-tools",
  432. ).paths,
  433. ).not.toContain("runtime/tools");
  434. expect(staged.archivePath).toMatch(/\.zip$/u);
  435. expect(await readFile(join(staged.releaseDir, "bin", "zcode.cmd"), "utf8")).toContain(
  436. "node.exe",
  437. );
  438. await expect(stat(join(staged.releaseDir, "runtime", "node.exe"))).resolves.toBeTruthy();
  439. await expect(
  440. stat(join(staged.releaseDir, "runtime", "tools", "ripgrep", "rg.exe")),
  441. ).resolves.toBeTruthy();
  442. await expect(
  443. stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "ugrep.exe")),
  444. ).resolves.toBeTruthy();
  445. await expect(
  446. stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "THIRD-PARTY-NOTICES.txt")),
  447. ).resolves.toBeTruthy();
  448. await expect(stat(join(staged.releaseDir, "runtime", "tools", "bfs"))).rejects.toThrow();
  449. });
  450. it("每个可独立下载的组件归档都携带适用的第三方声明", async () => {
  451. const fixture = await makeStageFixture();
  452. const toolsDir = join(await makeTempDir(), "tools");
  453. await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
  454. const staged = await stageRelease({
  455. target: "linux-x64",
  456. appVersion: "9.9.9-test",
  457. nativeToolsDir: toolsDir,
  458. ...fixture,
  459. });
  460. const manifest = JSON.parse(
  461. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  462. ) as {
  463. components: Array<{ id: string; archivePath: string }>;
  464. };
  465. const expected: Record<string, string[]> = {
  466. "node-runtime": ["runtime/LICENSE.node.txt", "runtime/NODE-SOURCES.json"],
  467. "server-runtime": ["runtime/THIRD-PARTY-NOTICES.md", "runtime/node_modules/node-pty/LICENSE"],
  468. "agent-runtime": ["runtime/licenses/agent/THIRD-PARTY-NOTICES.md"],
  469. "native-search-tools": [
  470. "runtime/tools/ripgrep/THIRD-PARTY-NOTICES.txt",
  471. "runtime/tools/ugrep/SOURCES.json",
  472. ],
  473. };
  474. expect(manifest.components.map((component) => component.id).sort()).toEqual(
  475. Object.keys(expected).sort(),
  476. );
  477. const extractRoot = await makeTempDir();
  478. for (const component of manifest.components) {
  479. const extractDir = join(extractRoot, component.id);
  480. await mkdir(extractDir, { recursive: true });
  481. await runTar(["-xf", join(fixture.outputDir, component.archivePath), "-C", extractDir]);
  482. for (const member of expected[component.id] ?? []) {
  483. expect(await readFile(join(extractDir, member))).toEqual(
  484. await readFile(join(staged.releaseDir, member)),
  485. );
  486. }
  487. }
  488. });
  489. it.each([true, false])(
  490. "工具目录缺少声明或声明参数为空时拒绝组装发行包(componentArchives=%s)",
  491. async (componentArchives) => {
  492. const fixture = await makeStageFixture();
  493. const toolsDir = join(await makeTempDir(), "tools");
  494. await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
  495. await rm(join(toolsDir, "ripgrep", "THIRD-PARTY-NOTICES.txt"));
  496. await expect(
  497. stageRelease({
  498. target: "linux-x64",
  499. appVersion: "9.9.9-test",
  500. archive: false,
  501. nativeToolsDir: toolsDir,
  502. componentArchives,
  503. ...fixture,
  504. }),
  505. ).rejects.toThrow(/ENOENT/u);
  506. await expect(
  507. stageRelease({
  508. target: "linux-x64",
  509. appVersion: "9.9.9-test",
  510. archive: false,
  511. ...fixture,
  512. notices: { ...fixture.notices, node: " " },
  513. componentArchives,
  514. }),
  515. ).rejects.toThrow(/Missing distribution notice: node/u);
  516. },
  517. );
  518. macIt("omits macOS extended attributes from POSIX release archives", async () => {
  519. const fixture = await makeStageFixture();
  520. await execFileAsync("xattr", ["-w", "com.example.zcode", "value", fixture.nodeBinaryPath]);
  521. const staged = await stageRelease({
  522. target: "linux-x64",
  523. appVersion: "9.9.9-test",
  524. ...fixture,
  525. });
  526. const archive = gunzipSync(await readFile(staged.archivePath ?? ""));
  527. const tarText = archive.toString("latin1");
  528. expect(tarText).not.toContain("LIBARCHIVE.xattr");
  529. expect(tarText).not.toContain("SCHILY.xattr");
  530. });
  531. it("bundled workflow skills ship in the agent component and affect its hash", async () => {
  532. const fixture = await makeStageFixture();
  533. const officialPluginsDir = join(await makeTempDir(), "packages");
  534. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  535. const options = {
  536. ...fixture,
  537. officialPluginsDir,
  538. target: "linux-x64" as const,
  539. appVersion: "test",
  540. archive: false,
  541. };
  542. const staged = await stageRelease(options);
  543. const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
  544. const component = manifest.components.find(
  545. (entry: { id: string }) => entry.id === "agent-runtime",
  546. );
  547. expect(component.paths).toContain("runtime/packages/bundled-skills");
  548. expect(manifest.plugins).not.toContain("bundled-skills");
  549. const archive = gunzipSync(
  550. await readFile(join(fixture.outputDir, component.archivePath)),
  551. ).toString("utf8");
  552. for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
  553. expect(
  554. await readFile(
  555. join(staged.releaseDir, "runtime/packages/bundled-skills/skills/dynamic-workflows", name),
  556. "utf8",
  557. ),
  558. ).toBe(`fixture ${name}`);
  559. expect(archive).toContain(`fixture ${name}`);
  560. }
  561. await writeFile(
  562. join(fixture.bundledSkillsDir, "skills/dynamic-workflows/examples.md"),
  563. "updated example",
  564. );
  565. const updated = await stageRelease(options);
  566. const next = JSON.parse(await readFile(join(updated.releaseDir, "manifest.json"), "utf8"));
  567. expect(
  568. next.components.find((entry: { id: string }) => entry.id === "agent-runtime").sha256,
  569. ).not.toBe(component.sha256);
  570. expect(
  571. next.components.find((entry: { id: string }) => entry.id === "official-plugins").sha256,
  572. ).toBe(
  573. manifest.components.find((entry: { id: string }) => entry.id === "official-plugins").sha256,
  574. );
  575. });
  576. it.each(["SKILL.md", "patterns.md", "examples.md", "entire-pack"])(
  577. "rejects missing bundled skill asset %s",
  578. async (missing) => {
  579. const fixture = await makeStageFixture();
  580. await rm(
  581. missing === "entire-pack"
  582. ? fixture.bundledSkillsDir
  583. : join(fixture.bundledSkillsDir, "skills/dynamic-workflows", missing),
  584. { recursive: true },
  585. );
  586. await expect(
  587. stageRelease({ ...fixture, target: "linux-x64", appVersion: "test", archive: false }),
  588. ).rejects.toThrow(/bundled skill/i);
  589. },
  590. );
  591. async function writeOfficialPluginFixture(
  592. officialPluginsDir: string,
  593. name: string,
  594. options: { mcpEntry?: string; withMcpEntryFile?: boolean; withManifest?: boolean } = {},
  595. ): Promise<void> {
  596. const pluginDir = join(officialPluginsDir, name);
  597. await mkdir(join(pluginDir, ".zcode-plugin"), { recursive: true });
  598. await writeFile(join(pluginDir, "README.md"), name, "utf8");
  599. // 真实官方插件的 package.json 都是 tracked 文件,是"该目录属于当前 checkout"的判据。
  600. await writeFile(
  601. join(pluginDir, "package.json"),
  602. JSON.stringify({ name: `@zcode/${name}`, private: true }),
  603. "utf8",
  604. );
  605. const manifest: Record<string, unknown> = {
  606. name: name.replace(/-plugin$/u, ""),
  607. version: "0.1.0",
  608. };
  609. if (options.mcpEntry) {
  610. manifest.mcpServers = {
  611. [name]: { command: "node", args: [`\${ZCODE_PLUGIN_ROOT}/${options.mcpEntry}`] },
  612. };
  613. if (options.withMcpEntryFile !== false) {
  614. const entryPath = join(pluginDir, ...options.mcpEntry.split("/"));
  615. await mkdir(join(entryPath, ".."), { recursive: true });
  616. await writeFile(entryPath, "// mcp server\n", "utf8");
  617. }
  618. }
  619. if (options.withManifest !== false) {
  620. await writeFile(
  621. join(pluginDir, ".zcode-plugin", "plugin.json"),
  622. JSON.stringify(manifest),
  623. "utf8",
  624. );
  625. }
  626. }
  627. it.each(["absent", "incomplete", "stale"])(
  628. "stages bundled skills from the agent source when the plugin cache is %s",
  629. async (cacheState) => {
  630. const fixture = await makeStageFixture();
  631. const officialPluginsDir = join(await makeTempDir(), "packages");
  632. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  633. if (cacheState !== "absent") {
  634. const cachedPackDir = join(officialPluginsDir, "bundled-skills");
  635. await mkdir(join(cachedPackDir, "skills/dynamic-workflows"), { recursive: true });
  636. await writeFile(join(cachedPackDir, "README.md"), "old cached pack");
  637. const files =
  638. cacheState === "stale" ? ["SKILL.md", "patterns.md", "examples.md"] : ["SKILL.md"];
  639. for (const name of files) {
  640. await writeFile(
  641. join(cachedPackDir, "skills/dynamic-workflows", name),
  642. "old cached skill",
  643. );
  644. }
  645. }
  646. // 冲突整合时两条复制路径曾并存:插件缓存缺文件会拒绝有效技能包,旧缓存会覆盖 Agent 源。
  647. // 技能包只从 bundledSkillsDir 读取,并只由 agent-runtime 交付。
  648. const staged = await stageRelease({
  649. ...fixture,
  650. target: "linux-x64",
  651. appVersion: "test",
  652. archive: false,
  653. officialPluginsDir,
  654. });
  655. const stagedPackDir = join(staged.releaseDir, "runtime/packages/bundled-skills");
  656. expect(await readFile(join(stagedPackDir, "README.md"), "utf8")).toBe("bundled skills");
  657. for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
  658. expect(await readFile(join(stagedPackDir, "skills/dynamic-workflows", name), "utf8")).toBe(
  659. `fixture ${name}`,
  660. );
  661. }
  662. // 保留发布白名单:本地临时文件不能进入发行包或组件归档。
  663. await expect(stat(join(stagedPackDir, "scratch.txt"))).rejects.toThrow();
  664. const manifest = JSON.parse(
  665. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  666. ) as {
  667. plugins: string[];
  668. components: Array<{ id: string; paths: string[]; archivePath: string }>;
  669. };
  670. expect(manifest.plugins).toEqual(["zcode-guide"]);
  671. const agentComponent = manifest.components.find((entry) => entry.id === "agent-runtime")!;
  672. expect(agentComponent.paths).toContain("runtime/packages/bundled-skills");
  673. const agentExtractDir = await makeTempDir();
  674. await runTar([
  675. "-xf",
  676. join(fixture.outputDir, agentComponent.archivePath),
  677. "-C",
  678. agentExtractDir,
  679. ]);
  680. expect(
  681. await readFile(
  682. join(
  683. agentExtractDir,
  684. "runtime/packages/bundled-skills/skills/dynamic-workflows/SKILL.md",
  685. ),
  686. "utf8",
  687. ),
  688. ).toBe("fixture SKILL.md");
  689. await expect(
  690. stat(join(agentExtractDir, "runtime/packages/bundled-skills/scratch.txt")),
  691. ).rejects.toThrow();
  692. const pluginComponent = manifest.components.find((entry) => entry.id === "official-plugins")!;
  693. const pluginExtractDir = await makeTempDir();
  694. await runTar([
  695. "-xf",
  696. join(fixture.outputDir, pluginComponent.archivePath),
  697. "-C",
  698. pluginExtractDir,
  699. ]);
  700. await expect(
  701. stat(join(pluginExtractDir, "runtime/packages/zcode-guide-plugin")),
  702. ).resolves.toBeTruthy();
  703. await expect(
  704. stat(join(pluginExtractDir, "runtime/packages/bundled-skills")),
  705. ).rejects.toThrow();
  706. },
  707. );
  708. it("stages the official plugin set and excludes the on-demand superpowers package", async () => {
  709. const fixture = await makeStageFixture();
  710. const officialPluginsDir = join(await makeTempDir(), "packages");
  711. const pluginNames = [
  712. "android-emulator-plugin",
  713. "browser-use-plugin",
  714. "document-skills-plugin",
  715. "ios-simulator-plugin",
  716. "restore-legacy-sessions-plugin",
  717. "skill-creator-plugin",
  718. "zcode-guide-plugin",
  719. "superpowers-plugin",
  720. ];
  721. const mcpRuntimePlugins = new Set([
  722. "android-emulator-plugin",
  723. "browser-use-plugin",
  724. "ios-simulator-plugin",
  725. ]);
  726. for (const name of pluginNames) {
  727. await writeOfficialPluginFixture(
  728. officialPluginsDir,
  729. name,
  730. mcpRuntimePlugins.has(name) ? { mcpEntry: "dist/mcp/server.js" } : {},
  731. );
  732. }
  733. const staged = await stageRelease({
  734. target: "linux-x64",
  735. appVersion: "9.9.9-test",
  736. archive: false,
  737. officialPluginsDir,
  738. ...fixture,
  739. });
  740. for (const name of pluginNames.filter((name) => name !== "superpowers-plugin")) {
  741. await expect(
  742. stat(join(staged.releaseDir, "runtime/packages", name, "README.md")),
  743. ).resolves.toBeTruthy();
  744. }
  745. for (const name of mcpRuntimePlugins) {
  746. await expect(
  747. stat(join(staged.releaseDir, "runtime/packages", name, "dist/mcp/server.js")),
  748. ).resolves.toBeTruthy();
  749. }
  750. await expect(
  751. stat(join(staged.releaseDir, "runtime/packages/superpowers-plugin")),
  752. ).rejects.toThrow();
  753. const manifest = JSON.parse(
  754. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  755. ) as {
  756. plugins?: string[];
  757. components?: Array<{ id: string }>;
  758. };
  759. expect(manifest.plugins).toEqual([
  760. "android-emulator",
  761. "browser-use",
  762. "document-skills",
  763. "ios-simulator",
  764. "restore-legacy-sessions",
  765. "skill-creator",
  766. "zcode-guide",
  767. ]);
  768. expect(manifest.components?.some((component) => component.id === "official-plugins")).toBe(
  769. true,
  770. );
  771. });
  772. it.each([true, false])(
  773. "fails closed on a missing MCP entry with componentArchives=%s",
  774. async (componentArchives) => {
  775. // Bug 原因:插件 dist 被 gitignore,干净 CI 工作区里 android-emulator / ios-simulator 没有
  776. // dist/mcp/server.js;legacy prepare-prebuilds.mjs 曾构建并断言该文件,切到 stageRelease 后只剩
  777. // 整目录复制,archive 会静默带上只有 plugin.json 与 skills、缺 MCP 入口的插件。staging 必须以
  778. // plugin.json 的 mcpServers 声明为事实源 fail-closed。
  779. const fixture = await makeStageFixture();
  780. const officialPluginsDir = join(await makeTempDir(), "packages");
  781. await writeOfficialPluginFixture(officialPluginsDir, "android-emulator-plugin", {
  782. mcpEntry: "dist/mcp/server.js",
  783. withMcpEntryFile: false,
  784. });
  785. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  786. await expect(
  787. stageRelease({
  788. target: "linux-x64",
  789. appVersion: "9.9.9-test",
  790. archive: false,
  791. officialPluginsDir,
  792. componentArchives,
  793. ...fixture,
  794. }),
  795. ).rejects.toThrow(/android-emulator-plugin[\s\S]*dist\/mcp\/server\.js/u);
  796. },
  797. );
  798. it("fails closed when a staged official plugin has no plugin manifest", async () => {
  799. const fixture = await makeStageFixture();
  800. const officialPluginsDir = join(await makeTempDir(), "packages");
  801. await writeOfficialPluginFixture(officialPluginsDir, "ios-simulator-plugin", {
  802. withManifest: false,
  803. });
  804. await expect(
  805. stageRelease({
  806. target: "linux-x64",
  807. appVersion: "9.9.9-test",
  808. archive: false,
  809. officialPluginsDir,
  810. ...fixture,
  811. }),
  812. ).rejects.toThrow(/ios-simulator-plugin[\s\S]*plugin\.json/u);
  813. });
  814. it("ignores orphaned *-plugin directories left behind by a previous checkout", async () => {
  815. // Bug 原因:CI 用 GIT_CLEAN_FLAGS "-e node_modules/" 跨 job 保留 node_modules,其它分支
  816. // (例如曾把 zcode-cua-plugin 改名为 computer-use-plugin 的分支)install 过的插件目录切回本
  817. // 分支后只剩 node_modules,tracked 文件全被 checkout 删掉。旧规则仅按 "-plugin" 后缀识别官方
  818. // 插件,会把这种僵尸目录当插件 stage,随后 fail-closed 校验读不到 plugin.json 而整段失败。
  819. const fixture = await makeStageFixture();
  820. const officialPluginsDir = join(await makeTempDir(), "packages");
  821. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  822. const orphanDir = join(officialPluginsDir, "computer-use-plugin");
  823. await mkdir(join(orphanDir, "node_modules", "@zcode", "computer-use"), { recursive: true });
  824. await writeFile(
  825. join(orphanDir, "node_modules", "@zcode", "computer-use", "package.json"),
  826. "{}",
  827. "utf8",
  828. );
  829. const staged = await stageRelease({
  830. target: "linux-x64",
  831. appVersion: "9.9.9-test",
  832. archive: false,
  833. officialPluginsDir,
  834. ...fixture,
  835. });
  836. await expect(
  837. stat(join(staged.releaseDir, "runtime/packages/computer-use-plugin")),
  838. ).rejects.toThrow();
  839. const manifest = JSON.parse(
  840. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  841. ) as { plugins?: string[] };
  842. expect(manifest.plugins).toEqual(["zcode-guide"]);
  843. });
  844. it("removes stale component archives before restaging a target", async () => {
  845. const fixture = await makeStageFixture();
  846. const staleDir = join(fixture.outputDir, "components", "linux-x64");
  847. await mkdir(staleDir, { recursive: true });
  848. await writeFile(join(staleDir, "stale-component.tar.gz"), "stale", "utf8");
  849. await stageRelease({
  850. target: "linux-x64",
  851. appVersion: "9.9.9-test",
  852. archive: false,
  853. ...fixture,
  854. });
  855. await expect(stat(join(staleDir, "stale-component.tar.gz"))).rejects.toThrow();
  856. });
  857. it.each(["linux-x64", "linux-arm64"] as const)(
  858. "stages an installable full %s archive without standalone components",
  859. async (target) => {
  860. const fixture = await makeStageFixture();
  861. await writeFakePackage(fixture.workspaceNodeModulesDir, "@lydell/node-pty-linux-arm64", {
  862. version: "1.2.0-beta.10",
  863. files: {
  864. "lib/index.js": "// platform node-pty js\n",
  865. "prebuilds/linux-arm64/pty.node": "linux-arm64-binary",
  866. },
  867. });
  868. const options = { ...fixture, target, appVersion: "9.9.9-test" };
  869. const original = await stageRelease(options);
  870. expect(original.componentArchivePaths.length).toBeGreaterThan(0);
  871. const expected = JSON.parse(
  872. await readFile(join(original.releaseDir, "manifest.json"), "utf8"),
  873. );
  874. for (const component of expected.components) {
  875. expect(component.archivePath).toBeTruthy();
  876. delete component.archivePath;
  877. }
  878. const staged = await stageRelease({ ...options, componentArchives: false });
  879. expect(staged.componentArchivePaths).toEqual([]);
  880. await expect(stat(join(fixture.outputDir, "components", target))).rejects.toMatchObject({
  881. code: "ENOENT",
  882. });
  883. await expect(stat(join(fixture.outputDir, ".components"))).rejects.toMatchObject({
  884. code: "ENOENT",
  885. });
  886. const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
  887. expect(manifest).toEqual(expected);
  888. // 用真实整包 installer 验证没有组件 archivePath 仍可安装,且整包摘要校验仍会拒绝错误身份。
  889. const { ReleaseInstaller } = await import(
  890. fileURLToPath(new URL("../src/runtime/releaseInstaller.ts", import.meta.url))
  891. );
  892. const { resolveServerLayout } = await import(
  893. fileURLToPath(new URL("../src/runtime/paths.ts", import.meta.url))
  894. );
  895. const installer = new ReleaseInstaller(
  896. resolveServerLayout(join(await makeTempDir(), "server")),
  897. );
  898. const archivePath = staged.archivePath!;
  899. const archiveSha256 = createHash("sha256")
  900. .update(await readFile(archivePath))
  901. .digest("hex");
  902. await expect(
  903. installer.installArchive({ archivePath, target, archiveSha256: "0".repeat(64) }),
  904. ).rejects.toThrow(/checksum mismatch/);
  905. const installed = await installer.installArchive({ archivePath, target, archiveSha256 });
  906. expect(
  907. JSON.parse(await readFile(join(installed.releaseDir, "manifest.json"), "utf8")),
  908. ).toEqual(expected);
  909. expect(await readFile(join(installed.releaseDir, "runtime", "zcode.cjs"))).toEqual(
  910. await readFile(fixture.agentBundlePath),
  911. );
  912. },
  913. );
  914. });
  915. it("stages only the target OS keyring binary", () => {
  916. expect(isTargetSpecificPackage("@napi-rs/keyring-linux-x64-gnu", "linux-x64")).toBe(true);
  917. expect(isTargetSpecificPackage("@napi-rs/keyring-win32-x64-msvc", "linux-x64")).toBe(false);
  918. expect(isTargetSpecificPackage("@napi-rs/keyring-linux-arm64-gnu", "linux-x64")).toBe(false);
  919. });