build-sea.test.mjs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. import assert from "node:assert/strict";
  2. import { execFile, spawnSync } from "node:child_process";
  3. import { createHash } from "node:crypto";
  4. import { createReadStream } from "node:fs";
  5. import { chmod, copyFile, cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  6. import { createServer } from "node:http";
  7. import { tmpdir } from "node:os";
  8. import { dirname, join } from "node:path";
  9. import { fileURLToPath, pathToFileURL } from "node:url";
  10. import test from "node:test";
  11. import { promisify } from "node:util";
  12. import {
  13. adHocCodesignArgs,
  14. hostTarget,
  15. isHostTarget,
  16. nodeReleaseArtifact,
  17. nodeReleaseUrl,
  18. outputBinaryName,
  19. parseBuildSeaArgs,
  20. postjectArgsForTarget,
  21. resolvePostjectBin,
  22. shouldAdHocSignMacTarget,
  23. supportedTargets,
  24. } from "../scripts/build-sea.mjs";
  25. import {
  26. readWindowsAuthenticodeDirectory,
  27. removeWindowsAuthenticodeSignature,
  28. removeWindowsAuthenticodeSignatureFromBuffer,
  29. } from "../scripts/windows-authenticode.mjs";
  30. import {
  31. collectSeaOfficialPluginAssets,
  32. officialSeaPlugins,
  33. seaOfficialPluginManifestAssetKey,
  34. } from "../scripts/sea-official-plugin-assets.mjs";
  35. import {
  36. bundledSkillPackRequiredPaths,
  37. collectSeaBundledSkillAssets,
  38. seaBundledSkillAssetPrefix,
  39. seaBundledSkillManifestAssetKey,
  40. } from "../scripts/sea-bundled-skill-assets.mjs";
  41. import {
  42. collectSeaTuiAssets,
  43. opentuiNativePackageForTarget,
  44. seaTuiAssetPrefix,
  45. } from "../scripts/sea-tui-assets.mjs";
  46. import {
  47. collectSeaRuntimeToolAssets,
  48. seaRuntimeToolManifestAssetKey,
  49. } from "../scripts/sea-runtime-tool-assets.mjs";
  50. import {
  51. prepareSeaRuntimeToolAssets,
  52. resolveSeaRuntimeToolPreparationPlan,
  53. } from "../scripts/sea-runtime-tool-prepare.mjs";
  54. import { packSourceAsDeterministicTarGzip } from "../../../../../scripts/deterministic-tar-archive.mjs";
  55. import { writeNativeSearchBundleMeta } from "../../../../../scripts/native-search-tools-bundle-meta.mjs";
  56. import { resolveNativeSearchPrebuiltPlan } from "../../../../../scripts/native-search-tools-config.mjs";
  57. import {
  58. collectSeaPlaywrightAssets,
  59. seaPlaywrightManifestAssetKey,
  60. } from "../scripts/sea-playwright-assets.mjs";
  61. import {
  62. collectSeaProviderConfigAssets,
  63. SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY,
  64. } from "../scripts/sea-provider-config-assets.mjs";
  65. const PE_FIXTURE_OFFSET = 0x80;
  66. const PE_SIGNATURE_SIZE = 4;
  67. const COFF_HEADER_SIZE = 20;
  68. const COFF_OPTIONAL_HEADER_SIZE_OFFSET = 16;
  69. const PE32_MAGIC = 0x10b;
  70. const PE32_PLUS_MAGIC = 0x20b;
  71. const PE32_OPTIONAL_HEADER_SIZE = 0xe0;
  72. const PE32_PLUS_OPTIONAL_HEADER_SIZE = 0xf0;
  73. const PE32_NUMBER_OF_DIRECTORIES_OFFSET = 92;
  74. const PE32_DATA_DIRECTORIES_OFFSET = 96;
  75. const PE32_PLUS_NUMBER_OF_DIRECTORIES_OFFSET = 108;
  76. const PE32_PLUS_DATA_DIRECTORIES_OFFSET = 112;
  77. const SECURITY_DIRECTORY_INDEX = 4;
  78. const DATA_DIRECTORY_ENTRY_SIZE = 8;
  79. const CERTIFICATE_OFFSET = 0x200;
  80. const CERTIFICATE_SIZE = 0x20;
  81. const DATA_DIRECTORY_COUNT = 16;
  82. const PE_SIGNATURE = 0x00004550;
  83. const DOS_MAGIC = 0x5a4d;
  84. test("includes the production ZCode Built-in Provider Config as a SEA asset", async () => {
  85. const root = fileURLToPath(new URL("../../../../..", import.meta.url));
  86. const assets = await collectSeaProviderConfigAssets({ root, env: { ZCODE_ENV: "production" } });
  87. const zcodeBuiltinFilePath = assets[SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY];
  88. assert.ok(zcodeBuiltinFilePath);
  89. assert.deepEqual(
  90. JSON.parse(await readFile(zcodeBuiltinFilePath, "utf8")),
  91. JSON.parse(
  92. await readFile(
  93. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  94. "utf8",
  95. ),
  96. ),
  97. );
  98. });
  99. const createMachOExecutableFixture = (label) => {
  100. const labelBytes = Buffer.from(label);
  101. const contents = Buffer.alloc(32 + labelBytes.length);
  102. contents.writeUInt32LE(0xfeedfacf, 0);
  103. contents.writeUInt32LE(0x0100000c, 4);
  104. contents.writeUInt32LE(2, 12);
  105. labelBytes.copy(contents, 32);
  106. return contents;
  107. };
  108. const createPeFixture = ({ pe32Plus = true, signed = true, trailingBytes = 0 } = {}) => {
  109. const optionalHeaderSize = pe32Plus ? PE32_PLUS_OPTIONAL_HEADER_SIZE : PE32_OPTIONAL_HEADER_SIZE;
  110. const magic = pe32Plus ? PE32_PLUS_MAGIC : PE32_MAGIC;
  111. const dataDirectoriesOffset = pe32Plus
  112. ? PE32_PLUS_DATA_DIRECTORIES_OFFSET
  113. : PE32_DATA_DIRECTORIES_OFFSET;
  114. const numberOfDirectoriesOffset = pe32Plus
  115. ? PE32_PLUS_NUMBER_OF_DIRECTORIES_OFFSET
  116. : PE32_NUMBER_OF_DIRECTORIES_OFFSET;
  117. const optionalHeaderOffset = PE_FIXTURE_OFFSET + PE_SIGNATURE_SIZE + COFF_HEADER_SIZE;
  118. const securityDirectoryEntryOffset =
  119. optionalHeaderOffset +
  120. dataDirectoriesOffset +
  121. SECURITY_DIRECTORY_INDEX * DATA_DIRECTORY_ENTRY_SIZE;
  122. const length = signed
  123. ? CERTIFICATE_OFFSET + CERTIFICATE_SIZE + trailingBytes
  124. : CERTIFICATE_OFFSET;
  125. const contents = Buffer.alloc(length);
  126. contents.writeUInt16LE(DOS_MAGIC, 0);
  127. contents.writeUInt32LE(PE_FIXTURE_OFFSET, 0x3c);
  128. contents.writeUInt32LE(PE_SIGNATURE, PE_FIXTURE_OFFSET);
  129. contents.writeUInt16LE(
  130. optionalHeaderSize,
  131. PE_FIXTURE_OFFSET + PE_SIGNATURE_SIZE + COFF_OPTIONAL_HEADER_SIZE_OFFSET,
  132. );
  133. contents.writeUInt16LE(magic, optionalHeaderOffset);
  134. contents.writeUInt32LE(DATA_DIRECTORY_COUNT, optionalHeaderOffset + numberOfDirectoriesOffset);
  135. if (signed) {
  136. contents.writeUInt32LE(CERTIFICATE_OFFSET, securityDirectoryEntryOffset);
  137. contents.writeUInt32LE(CERTIFICATE_SIZE, securityDirectoryEntryOffset + 4);
  138. contents.fill(0xa5, CERTIFICATE_OFFSET, CERTIFICATE_OFFSET + CERTIFICATE_SIZE);
  139. }
  140. return {
  141. contents,
  142. securityDirectoryEntryOffset,
  143. };
  144. };
  145. test("defaults SEA target to the current host platform and arch", () => {
  146. assert.deepEqual(
  147. parseBuildSeaArgs([], {
  148. hostArch: "arm64",
  149. hostPlatform: "darwin",
  150. }),
  151. {
  152. help: false,
  153. nodeBinaries: {},
  154. targets: ["darwin-arm64"],
  155. },
  156. );
  157. });
  158. test("keeps package SEA build scripts aligned with the existing all-target contract", async () => {
  159. const cliPackage = JSON.parse(
  160. await readFile(join(import.meta.dirname, "..", "package.json"), "utf8"),
  161. );
  162. const cliWorkspacePackage = JSON.parse(
  163. await readFile(join(import.meta.dirname, "..", "..", "..", "package.json"), "utf8"),
  164. );
  165. const rootPackage = JSON.parse(
  166. await readFile(join(import.meta.dirname, "..", "..", "..", "..", "..", "package.json"), "utf8"),
  167. );
  168. assert.equal(
  169. cliPackage.scripts["build:sea"],
  170. "pnpm --dir ../../../.. exec turbo --skip-infer --cwd apps/zcode-cli run build --filter=!@zcode/cli --force && pnpm build && node scripts/build-sea.mjs --all",
  171. );
  172. assert.equal(cliPackage.scripts["build:sea:all"], undefined);
  173. assert.equal(cliWorkspacePackage.scripts["build:sea"], "pnpm --filter @zcode/cli build:sea");
  174. assert.equal(cliWorkspacePackage.scripts["build:sea:all"], undefined);
  175. assert.equal(rootPackage.scripts["build:sea"], "pnpm --dir apps/zcode-cli build:sea");
  176. assert.equal(
  177. rootPackage.scripts["build:sea:all"],
  178. "pnpm install && pnpm --dir apps/zcode-cli build:sea",
  179. );
  180. });
  181. test("parses repeated and comma-separated SEA targets", () => {
  182. const parsed = parseBuildSeaArgs([
  183. "--",
  184. "--target",
  185. "linux-x64",
  186. "--targets=win-x64,darwin-x64",
  187. "--target",
  188. "linux-x64",
  189. ]);
  190. assert.deepEqual(parsed.targets, ["linux-x64", "win-x64", "darwin-x64"]);
  191. });
  192. test("parses all supported SEA targets", () => {
  193. assert.deepEqual(parseBuildSeaArgs(["--all"]).targets, supportedTargets);
  194. });
  195. test("uses node-binary targets when no explicit target selector is provided", () => {
  196. // Windows 会按宿主路径规则解析 binary 路径,不能硬编码 POSIX 绝对路径作为预期。
  197. const linuxBinary = join(tmpdir(), "node binaries", "linux", "node");
  198. const windowsBinary = join(tmpdir(), "node binaries", "win", "node.exe");
  199. const parsed = parseBuildSeaArgs([
  200. "--node-binary",
  201. `linux-x64=${linuxBinary}`,
  202. `--node-binary=win32-x64=${windowsBinary}`,
  203. ]);
  204. assert.deepEqual(parsed.targets, ["linux-x64", "win-x64"]);
  205. assert.equal(parsed.nodeBinaries["linux-x64"], linuxBinary);
  206. assert.equal(parsed.nodeBinaries["win-x64"], windowsBinary);
  207. });
  208. test("rejects unsupported SEA targets", () => {
  209. assert.throws(
  210. () => parseBuildSeaArgs(["--target", "linux-s390x"]),
  211. /Unsupported SEA target "linux-s390x"/,
  212. );
  213. });
  214. test("rejects empty SEA target selectors", () => {
  215. assert.throws(() => parseBuildSeaArgs(["--target="]), /Missing SEA target value/);
  216. });
  217. test("maps SEA targets to output binary names", () => {
  218. assert.equal(outputBinaryName("darwin-arm64"), "zcode-darwin-arm64");
  219. assert.equal(outputBinaryName("linux-x64"), "zcode-linux-x64");
  220. assert.equal(outputBinaryName("win-arm64"), "zcode-windows-arm64.exe");
  221. assert.equal(outputBinaryName("win-x64"), "zcode-windows-x64.exe");
  222. });
  223. test("prepares every SEA target in the desktop bundled-tools layout", () => {
  224. assert.deepEqual(
  225. supportedTargets.map((target) => {
  226. const plan = resolveSeaRuntimeToolPreparationPlan({ root: "/repo", target });
  227. return [target, plan.platformKey, plan.enabled];
  228. }),
  229. [
  230. ["darwin-arm64", "darwin-arm64", true],
  231. ["darwin-x64", "darwin-x64", true],
  232. ["linux-arm64", "linux-arm64", true],
  233. ["linux-x64", "linux-x64", true],
  234. ["win-arm64", "win32-arm64", true],
  235. ["win-x64", "win32-x64", true],
  236. ],
  237. );
  238. });
  239. test("downloads the complete SEA runtime tool set before asset collection", async () => {
  240. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-prepare-"));
  241. const archives = new Map();
  242. let requestCount = 0;
  243. const server = createServer((request, response) => {
  244. requestCount += 1;
  245. const archivePath = archives.get(request.url ?? "");
  246. if (!archivePath) {
  247. response.writeHead(404).end();
  248. return;
  249. }
  250. response.writeHead(200, { "content-type": "application/gzip" });
  251. createReadStream(archivePath).pipe(response);
  252. });
  253. await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
  254. try {
  255. const address = server.address();
  256. assert.ok(address && typeof address !== "string");
  257. const baseUrl = `http://127.0.0.1:${address.port}`;
  258. const nativeBaseUrl = `${baseUrl}/native`;
  259. const env = {
  260. NATIVE_SEARCH_RIPGREP_DOWNLOAD_BASE_URL: `${baseUrl}/microsoft-ripgrep`,
  261. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: nativeBaseUrl,
  262. };
  263. const outputDir = join(directory, "root/packages/desktop/bundled-tools/darwin-arm64");
  264. const nativePlan = resolveNativeSearchPrebuiltPlan({
  265. platform: "darwin",
  266. arch: "arm64",
  267. outputDir,
  268. env,
  269. });
  270. const fixtures = nativePlan.artifacts.map((artifact) => ({
  271. artifact,
  272. binaryName: artifact.binaryName,
  273. downloadUrl: artifact.downloadUrl,
  274. contents: createMachOExecutableFixture(`${artifact.toolId}-fixture`),
  275. toolId: artifact.toolId,
  276. }));
  277. for (const [index, fixture] of fixtures.entries()) {
  278. if (fixture.artifact.source === "official") {
  279. await mkdir(dirname(fixture.artifact.binaryPath), { recursive: true });
  280. await writeFile(fixture.artifact.binaryPath, fixture.contents);
  281. await chmod(fixture.artifact.binaryPath, 0o755);
  282. writeNativeSearchBundleMeta(fixture.artifact, nativePlan.platformKey);
  283. continue;
  284. }
  285. const sourcePath = join(directory, `source-${index}`, fixture.binaryName);
  286. const archivePath = join(directory, `archive-${index}.tar.gz`);
  287. await mkdir(dirname(sourcePath), { recursive: true });
  288. await writeFile(sourcePath, fixture.contents);
  289. await chmod(sourcePath, 0o755);
  290. packSourceAsDeterministicTarGzip(sourcePath, archivePath);
  291. fixture.artifact.archiveSha256 = createHash("sha256")
  292. .update(await readFile(archivePath))
  293. .digest("hex");
  294. archives.set(new URL(fixture.downloadUrl).pathname, archivePath);
  295. }
  296. await prepareSeaRuntimeToolAssets({
  297. root: join(directory, "root"),
  298. target: "darwin-arm64",
  299. env,
  300. prebuiltPlan: nativePlan,
  301. });
  302. const fixtureByToolId = new Map(fixtures.map((fixture) => [fixture.toolId, fixture.contents]));
  303. assert.deepEqual(await readFile(nativePlan.bfsPath), fixtureByToolId.get("bfs"));
  304. assert.deepEqual(await readFile(nativePlan.ugrepPath), fixtureByToolId.get("ugrep"));
  305. assert.deepEqual(await readFile(nativePlan.rgPath), fixtureByToolId.get("ripgrep"));
  306. assert.equal(requestCount, 2);
  307. } finally {
  308. await new Promise((resolvePromise, rejectPromise) => {
  309. server.close((error) => (error ? rejectPromise(error) : resolvePromise()));
  310. });
  311. await rm(directory, { force: true, recursive: true });
  312. }
  313. });
  314. test("maps SEA targets to OpenTUI native package names", () => {
  315. assert.equal(opentuiNativePackageForTarget("darwin-arm64"), "@mbears/opentui-core-darwin-arm64");
  316. assert.equal(opentuiNativePackageForTarget("linux-x64"), "@mbears/opentui-core-linux-x64");
  317. assert.equal(opentuiNativePackageForTarget("win-arm64"), "@mbears/opentui-core-win32-arm64");
  318. assert.equal(opentuiNativePackageForTarget("win-x64"), "@mbears/opentui-core-win32-x64");
  319. });
  320. for (const fixture of [
  321. {
  322. expectedTools: [
  323. ["bfs", "4.1.1", "bfs"],
  324. ["ripgrep", "14.1.1", "rg"],
  325. ["ugrep", "7.8.4", "ugrep"],
  326. ],
  327. platformKey: "darwin-arm64",
  328. target: "darwin-arm64",
  329. },
  330. {
  331. expectedTools: [
  332. ["bfs", "4.1.1", "bfs"],
  333. ["ripgrep", "14.1.1", "rg"],
  334. ["ugrep", "7.8.4", "ugrep"],
  335. ],
  336. platformKey: "darwin-x64",
  337. target: "darwin-x64",
  338. },
  339. {
  340. expectedTools: [
  341. ["bfs", "4.1.1", "bfs"],
  342. ["ripgrep", "14.1.1", "rg"],
  343. ["ugrep", "7.8.4", "ugrep"],
  344. ],
  345. platformKey: "linux-arm64",
  346. target: "linux-arm64",
  347. },
  348. {
  349. expectedTools: [
  350. ["bfs", "4.1.1", "bfs"],
  351. ["ripgrep", "14.1.1", "rg"],
  352. ["ugrep", "7.8.4", "ugrep"],
  353. ],
  354. platformKey: "linux-x64",
  355. target: "linux-x64",
  356. },
  357. {
  358. expectedTools: [
  359. ["ripgrep", "14.1.1", "rg.exe"],
  360. ["ugrep", "7.8.4", "ugrep.exe"],
  361. ],
  362. platformKey: "win32-arm64",
  363. target: "win-arm64",
  364. },
  365. {
  366. expectedTools: [
  367. ["ripgrep", "14.1.1", "rg.exe"],
  368. ["ugrep", "7.8.4", "ugrep.exe"],
  369. ],
  370. platformKey: "win32-x64",
  371. target: "win-x64",
  372. },
  373. ]) {
  374. test(`includes target runtime tools for ${fixture.target}`, async () => {
  375. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-tools-"));
  376. const root = join(directory, "root");
  377. const stagingDirectory = join(directory, "staging");
  378. try {
  379. for (const [toolId, , binaryName] of fixture.expectedTools) {
  380. await writeTestFile(
  381. root,
  382. `packages/desktop/bundled-tools/${fixture.platformKey}/${toolId}/${binaryName}`,
  383. `${fixture.target}:${toolId}`,
  384. );
  385. }
  386. // SEA 内嵌原生工具的许可声明与来源清单;材料取自仓库登记,fixture 根目录需带上同一份。
  387. const repositoryRoot = fileURLToPath(new URL("../../../../..", import.meta.url));
  388. await cp(
  389. join(repositoryRoot, "third-party/native-search"),
  390. join(root, "third-party/native-search"),
  391. { recursive: true },
  392. );
  393. const { assets, manifest } = await collectSeaRuntimeToolAssets({
  394. root,
  395. stagingDirectory,
  396. target: fixture.target,
  397. });
  398. assert.deepEqual(
  399. manifest.tools.map(({ id, version, binaryName }) => [id, version, binaryName]),
  400. fixture.expectedTools,
  401. );
  402. assert.equal(typeof assets[seaRuntimeToolManifestAssetKey], "string");
  403. for (const tool of manifest.tools) {
  404. const expectedBytes = Buffer.from(`${fixture.target}:${tool.id}`);
  405. assert.equal(tool.size, expectedBytes.byteLength);
  406. assert.equal(tool.sha256, createHash("sha256").update(expectedBytes).digest("hex"));
  407. const assetKey = `zcode-runtime-tools/${tool.id}/${tool.sha256}/${tool.binaryName}`;
  408. assert.equal(assets[assetKey].endsWith(tool.binaryName), true);
  409. }
  410. const notices = await readFile(assets["zcode-runtime-tools/THIRD-PARTY-NOTICES.txt"], "utf8");
  411. assert.ok(notices.startsWith("NATIVE SEARCH THIRD-PARTY NOTICES"));
  412. assert.deepEqual(
  413. await readFile(assets["zcode-runtime-tools/SOURCES.json"]),
  414. await readFile(join(root, "third-party/native-search/sources.json")),
  415. );
  416. } finally {
  417. await rm(directory, {
  418. force: true,
  419. recursive: true,
  420. });
  421. }
  422. });
  423. }
  424. test("fails SEA packaging when a target runtime tool is missing", async () => {
  425. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-tools-missing-"));
  426. try {
  427. await assert.rejects(
  428. collectSeaRuntimeToolAssets({
  429. root: directory,
  430. stagingDirectory: join(directory, "staging"),
  431. target: "darwin-arm64",
  432. }),
  433. /Missing SEA runtime tool bfs for darwin-arm64/,
  434. );
  435. } finally {
  436. await rm(directory, {
  437. force: true,
  438. recursive: true,
  439. });
  440. }
  441. });
  442. test("includes TUI workspace runtime package assets", async () => {
  443. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-assets-"));
  444. const root = join(import.meta.dirname, "../../..");
  445. try {
  446. const { manifest, assets } = await collectSeaTuiAssets({
  447. root,
  448. stagingDirectory: directory,
  449. target: "linux-x64",
  450. });
  451. const paths = new Set(manifest.files.map((file) => file.path));
  452. // SEA 从缓存目录导入 TUI 时无法回退到 workspace 链接,运行时 workspace
  453. // 依赖必须和第三方依赖一样完整进入 node_modules 形状的资产闭包。
  454. assert.equal(paths.has("node_modules/@zcode/tui/package.json"), true);
  455. assert.equal(paths.has("node_modules/@zcode/tui/dist/index.js"), true);
  456. assert.equal(paths.has("node_modules/@zcode/i18n/package.json"), true);
  457. assert.equal(paths.has("node_modules/@zcode/i18n/dist/index.js"), true);
  458. assert.equal(paths.has("node_modules/@zcode/contracts/package.json"), true);
  459. assert.equal(paths.has("node_modules/@zcode/contracts/dist/index.js"), true);
  460. assert.equal(paths.has("node_modules/@zcode/shared/package.json"), true);
  461. assert.equal(paths.has("node_modules/@zcode/shared/dist/index.js"), true);
  462. assert.equal(
  463. paths.has("node_modules/@zcode/shared/dist/workspace-hook-trust-store-file.js"),
  464. true,
  465. );
  466. assert.equal(paths.has("node_modules/@zcode/i18n/src/index.ts"), false);
  467. assert.equal(paths.has("node_modules/@zcode/contracts/src/index.ts"), false);
  468. assert.equal(paths.has("node_modules/@zcode/shared/src/index.ts"), false);
  469. const zodPackages = manifest.files.filter((file) => file.path.endsWith("/zod/package.json"));
  470. const zodVersions = await Promise.all(
  471. zodPackages.map(async (file) => {
  472. const metadata = JSON.parse(
  473. await readFile(assets[`${seaTuiAssetPrefix}${file.path}`], "utf8"),
  474. );
  475. return metadata.version.split(".")[0];
  476. }),
  477. );
  478. assert.deepEqual([...new Set(zodVersions)].sort(), ["3", "4"]);
  479. // 根 workspace 的源码 exports 不能原样进入只包含 dist 的 SEA runtime。
  480. for (const packageName of ["@zcode/shared", "@zcode/model-option-map"]) {
  481. const assetKey = `${seaTuiAssetPrefix}node_modules/${packageName}/package.json`;
  482. const stagedPackage = JSON.parse(await readFile(assets[assetKey], "utf8"));
  483. assert.equal(stagedPackage.exports["."], "./dist/index.js");
  484. const sourcePackage = JSON.parse(
  485. await readFile(
  486. join(root, "../..", "packages", packageName.split("/")[1], "package.json"),
  487. "utf8",
  488. ),
  489. );
  490. assert.equal(sourcePackage.exports["."], "./src/index.ts");
  491. }
  492. } finally {
  493. await rm(directory, {
  494. force: true,
  495. recursive: true,
  496. });
  497. }
  498. });
  499. test("loads TUI from an extracted SEA runtime dependency closure", async () => {
  500. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-runtime-"));
  501. const root = join(import.meta.dirname, "../../..");
  502. const stagingDirectory = join(directory, "staging");
  503. const runtimeDirectory = join(directory, "runtime");
  504. try {
  505. const { assets, manifest } = await collectSeaTuiAssets({
  506. root,
  507. stagingDirectory,
  508. target: hostTarget(),
  509. });
  510. for (const file of manifest.files) {
  511. const sourcePath = assets[`${seaTuiAssetPrefix}${file.path}`];
  512. assert.equal(typeof sourcePath, "string");
  513. const outputPath = join(runtimeDirectory, file.path);
  514. await mkdir(dirname(outputPath), {
  515. recursive: true,
  516. });
  517. await copyFile(sourcePath, outputPath);
  518. }
  519. // Windows 锁定进程已加载的 opentui.dll;子进程退出释放 DLL 后,父进程才能清理目录。
  520. const entryUrl = pathToFileURL(
  521. join(runtimeDirectory, "node_modules/@zcode/tui/dist/index.js"),
  522. ).href;
  523. await promisify(execFile)(
  524. process.execPath,
  525. [
  526. "--input-type=module",
  527. "--eval",
  528. 'import assert from "node:assert/strict"; const tui = await import(process.argv[1]); assert.equal(typeof tui.runTui, "function");',
  529. entryUrl,
  530. ],
  531. { cwd: runtimeDirectory, timeout: 30000 },
  532. );
  533. } finally {
  534. await rm(directory, {
  535. force: true,
  536. recursive: true,
  537. });
  538. }
  539. });
  540. test("includes the pinned Playwright runtime required by headless Browser Use", async () => {
  541. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-playwright-assets-"));
  542. const root = join(import.meta.dirname, "../../..");
  543. try {
  544. const { assets, manifest } = await collectSeaPlaywrightAssets({
  545. root,
  546. stagingDirectory: directory,
  547. target: "linux-x64",
  548. });
  549. const paths = new Set(manifest.files.map((file) => file.path));
  550. assert.equal(manifest.packageVersion, "1.59.1");
  551. assert.equal(typeof assets[seaPlaywrightManifestAssetKey], "string");
  552. assert.equal(paths.has("node_modules/playwright-core/package.json"), true);
  553. assert.equal(paths.has("node_modules/playwright-core/index.js"), true);
  554. assert.equal(paths.has("node_modules/playwright-core/lib/server/browserType.js"), true);
  555. } finally {
  556. await rm(directory, { force: true, recursive: true });
  557. }
  558. });
  559. test("keeps the Browser Use SEA release at 0.5.1 with complete runtime assets", async () => {
  560. const root = join(import.meta.dirname, "../../..");
  561. const browserUsePlugin = officialSeaPlugins.find((plugin) => plugin.name === "browser-use");
  562. assert.equal(browserUsePlugin?.version, "0.5.1");
  563. assert.deepEqual(browserUsePlugin?.requiredRuntimePaths, [
  564. "scripts/browser-client.mjs",
  565. "docs/api.json",
  566. "docs/documents.json",
  567. "docs/overview.md",
  568. "docs/recording.md",
  569. "docs/workflow.md",
  570. "skills/control-browser/SKILL.md",
  571. "skills/web-gui-tester/SKILL.md",
  572. ]);
  573. const packageJson = JSON.parse(
  574. await readFile(join(root, browserUsePlugin.rootPath, "package.json"), "utf8"),
  575. );
  576. const pluginManifest = JSON.parse(
  577. await readFile(join(root, browserUsePlugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  578. );
  579. assert.deepEqual(
  580. {
  581. manifest: pluginManifest.version,
  582. package: packageJson.version,
  583. sea: browserUsePlugin.version,
  584. },
  585. {
  586. manifest: "0.5.1",
  587. package: "0.5.1",
  588. sea: "0.5.1",
  589. },
  590. );
  591. // Bug 原因:新增录屏能力时重写了整段插件描述,并把原生 WebM 误写成 MP4。
  592. assert.equal(
  593. pluginManifest.description,
  594. "Built-in browser automation runtime and guidance for Desktop IAB and explicitly enabled CLI-managed headless CDP: open, navigate, inspect, click, type, screenshot, record workspace WebM videos, and verify web pages and local dev targets.",
  595. );
  596. });
  597. test("keeps SEA official plugin versions aligned with package and plugin manifests", async () => {
  598. const root = join(import.meta.dirname, "../../..");
  599. for (const plugin of officialSeaPlugins) {
  600. const packageJson = JSON.parse(
  601. await readFile(join(root, plugin.rootPath, "package.json"), "utf8"),
  602. );
  603. const pluginManifest = JSON.parse(
  604. await readFile(join(root, plugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  605. );
  606. assert.deepEqual(
  607. {
  608. manifest: pluginManifest.version,
  609. package: packageJson.version,
  610. sea: plugin.version,
  611. },
  612. {
  613. manifest: plugin.version,
  614. package: plugin.version,
  615. sea: plugin.version,
  616. },
  617. plugin.name,
  618. );
  619. }
  620. });
  621. test("includes bundled official plugin assets", async () => {
  622. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-assets-"));
  623. const root = join(import.meta.dirname, "../../..");
  624. try {
  625. const { assets, manifest } = await collectSeaOfficialPluginAssets({
  626. root,
  627. stagingDirectory: directory,
  628. });
  629. const iosPlugin = manifest.plugins.find((item) => item.name === "ios-simulator");
  630. const androidPlugin = manifest.plugins.find((item) => item.name === "android-emulator");
  631. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  632. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  633. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  634. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  635. const zcodeGuidePlugin = manifest.plugins.find((item) => item.name === "zcode-guide");
  636. const iosPaths = new Set(iosPlugin?.files.map((file) => file.path));
  637. const androidPaths = new Set(androidPlugin?.files.map((file) => file.path));
  638. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  639. const documentPaths = new Set(
  640. manifest.plugins
  641. .filter((plugin) =>
  642. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  643. )
  644. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  645. );
  646. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  647. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  648. const zcodeGuidePaths = new Set(zcodeGuidePlugin?.files.map((file) => file.path));
  649. assert.equal(typeof assets[seaOfficialPluginManifestAssetKey], "string");
  650. assert.equal(iosPlugin?.marketplace, "zcode-plugins-official");
  651. assert.equal(androidPlugin?.marketplace, "zcode-plugins-official");
  652. assert.equal(browserUsePlugin?.marketplace, "zcode-plugins-official");
  653. assert.equal(documentPlugin?.marketplace, "zcode-plugins-official");
  654. assert.equal(restorePlugin?.marketplace, "zcode-plugins-official");
  655. assert.equal(skillCreatorPlugin?.marketplace, "zcode-plugins-official");
  656. assert.equal(zcodeGuidePlugin?.marketplace, "zcode-plugins-official");
  657. // superpowers 已从内置 SEA 清单移除,断言它不再出现在 manifest 里。
  658. assert.equal(
  659. manifest.plugins.some((item) => item.name === "superpowers"),
  660. false,
  661. );
  662. assert.equal(iosPaths.has(".zcode-plugin/plugin.json"), true);
  663. assert.equal(iosPaths.has("commands/ios-dev.md"), true);
  664. assert.equal(iosPaths.has("skills/ios-dev/SKILL.md"), true);
  665. assert.equal(iosPaths.has("src/mcp/server.ts"), false);
  666. assert.equal(androidPaths.has(".zcode-plugin/plugin.json"), true);
  667. assert.equal(androidPaths.has("commands/android-dev.md"), true);
  668. assert.equal(androidPaths.has("skills/android-dev/SKILL.md"), true);
  669. assert.equal(androidPaths.has("skills/android-dev/scripts/setup-windows.ps1"), false);
  670. assert.equal(androidPaths.has("src/mcp/server.ts"), false);
  671. assert.equal(browserUsePaths.has(".zcode-plugin/plugin.json"), true);
  672. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  673. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  674. assert.equal(browserUsePaths.has("docs/api.json"), true);
  675. assert.equal(browserUsePaths.has("docs/documents.json"), true);
  676. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  677. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  678. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  679. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  680. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  681. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  682. assert.equal(
  683. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  684. true,
  685. );
  686. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  687. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  688. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  689. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  690. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  691. assert.equal(documentPaths.has(".zcode-plugin/plugin.json"), true);
  692. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  693. assert.equal(documentPaths.has("skills/docx-viewer/SKILL.md"), true);
  694. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  695. assert.equal(documentPaths.has("skills/pdf/scripts/pdf.py"), true);
  696. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  697. assert.equal(documentPaths.has("agents/visual-judge.md"), true);
  698. assert.equal(documentPaths.has("skills/pptx/scripts/general_judge.py"), false);
  699. assert.equal(documentPaths.has("skills/xlsx/SKILL.md"), true);
  700. assert.equal(documentPaths.has("skills/xlsx/xlsx.py"), true);
  701. assert.equal(
  702. [...documentPaths].some((path) =>
  703. /(?:^|\/)(?:\.venv|__pycache__|\.DS_Store)(?:\/|$)/u.test(path),
  704. ),
  705. false,
  706. );
  707. assert.equal(restorePaths.has(".zcode-plugin/plugin.json"), true);
  708. assert.equal(restorePaths.has("commands/restore-legacy-sessions.md"), true);
  709. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  710. assert.equal(
  711. restorePaths.has("skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs"),
  712. true,
  713. );
  714. assert.equal(
  715. restorePaths.has("skills/restore-legacy-sessions/scripts/restore-conversation.mjs"),
  716. true,
  717. );
  718. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  719. assert.equal(skillCreatorPaths.has(".zcode-plugin/plugin.json"), true);
  720. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  721. assert.equal(zcodeGuidePaths.has(".zcode-plugin/plugin.json"), true);
  722. assert.equal(zcodeGuidePaths.has("skills/zcode-configuration-guide/SKILL.md"), true);
  723. assert.equal(zcodeGuidePaths.has("skills/diagnosing-mcp/SKILL.md"), true);
  724. assert.equal(zcodeGuidePaths.has("skills/diagnosing-skills/SKILL.md"), true);
  725. assert.equal(zcodeGuidePaths.has("skills/diagnosing-commands/SKILL.md"), true);
  726. assert.equal(zcodeGuidePaths.has("skills/diagnosing-hooks/SKILL.md"), true);
  727. assert.equal(zcodeGuidePaths.has("skills/diagnosing-plugins/SKILL.md"), true);
  728. // 0.3.0:/workflow 与 dynamic-workflows 不再随 zcode-guide 发布(见 bundled skill pack 用例)。
  729. assert.equal(zcodeGuidePaths.has("commands/workflow.md"), false);
  730. assert.equal(zcodeGuidePaths.has("skills/dynamic-workflows/SKILL.md"), false);
  731. } finally {
  732. await rm(directory, {
  733. force: true,
  734. recursive: true,
  735. });
  736. }
  737. });
  738. test("includes the bundled skill pack as content-hashed SEA assets", async () => {
  739. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-assets-"));
  740. const root = join(import.meta.dirname, "../../..");
  741. try {
  742. const { assets, manifest } = await collectSeaBundledSkillAssets({
  743. root,
  744. stagingDirectory: directory,
  745. });
  746. const paths = new Set(manifest.files.map((file) => file.path));
  747. assert.equal(manifest.version, 1);
  748. assert.match(manifest.hash, /^[0-9a-f]{64}$/u);
  749. assert.equal(typeof assets[seaBundledSkillManifestAssetKey], "string");
  750. for (const requiredPath of bundledSkillPackRequiredPaths) {
  751. assert.equal(paths.has(requiredPath), true, requiredPath);
  752. assert.equal(typeof assets[`${seaBundledSkillAssetPrefix}${requiredPath}`], "string");
  753. }
  754. // 资产只来自 skills/:README 之类的包元数据不进二进制。
  755. assert.equal(
  756. [...paths].every((path) => path.startsWith("skills/")),
  757. true,
  758. );
  759. for (const file of manifest.files) {
  760. assert.match(file.sha256, /^[0-9a-f]{64}$/u);
  761. }
  762. } finally {
  763. await rm(directory, { force: true, recursive: true });
  764. }
  765. });
  766. test("rejects a bundled skill pack that lost a required file", async () => {
  767. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-incomplete-"));
  768. const root = join(directory, "root");
  769. try {
  770. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/SKILL.md", "# s");
  771. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/patterns.md", "#");
  772. await assert.rejects(
  773. collectSeaBundledSkillAssets({ root, stagingDirectory: join(directory, "staging") }),
  774. /Missing bundled skill pack required asset/u,
  775. );
  776. } finally {
  777. await rm(directory, { force: true, recursive: true });
  778. }
  779. });
  780. test("allows skill-only official plugins when SEA runtime assets are required", async () => {
  781. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-runtime-assets-"));
  782. const root = join(directory, "root");
  783. const stagingDirectory = join(directory, "staging");
  784. try {
  785. await writeVisualizePluginFixture(root);
  786. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  787. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  788. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  789. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  790. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  791. await writeTestFile(root, "packages/browser-use-plugin/skills/control-browser/SKILL.md", "");
  792. await writeTestFile(root, "packages/browser-use-plugin/skills/web-gui-tester/SKILL.md", "");
  793. await writeTestFile(root, "packages/browser-use-plugin/docs/api.json", "{}");
  794. await writeTestFile(root, "packages/browser-use-plugin/docs/documents.json", "[]");
  795. await writeTestFile(root, "packages/browser-use-plugin/docs/overview.md", "");
  796. await writeTestFile(root, "packages/browser-use-plugin/docs/recording.md", "");
  797. await writeTestFile(root, "packages/browser-use-plugin/docs/workflow.md", "");
  798. await writeTestFile(root, "packages/browser-use-plugin/scripts/browser-client.mjs", "");
  799. await writeDocumentPluginFixtures(root);
  800. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  801. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  802. await writeTestFile(
  803. root,
  804. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  805. "{}",
  806. );
  807. await writeTestFile(
  808. root,
  809. "packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md",
  810. "",
  811. );
  812. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  813. await writeTestFile(root, "packages/skill-creator-plugin/skills/skill-creator/SKILL.md", "");
  814. // 新增官方内容插件后也要提供 fixture,否则采集会先报 manifest 缺失,无法验证免运行时资源。
  815. await writeTestFile(root, "packages/plugin-creator-plugin/.zcode-plugin/plugin.json", "{}");
  816. await writeTestFile(root, "packages/plugin-creator-plugin/skills/plugin-creator/SKILL.md", "");
  817. // skill-creator 用作「带可执行 hook 的 skill-only 官方插件」载体(原先由 superpowers 覆盖)。
  818. // collector 按 officialSeaPlugins 登记 + 伪造目录采集,真实 skill-creator 是否带 hook 无关紧要。
  819. await writeTestFile(root, "packages/skill-creator-plugin/hooks/hooks.json", "{}");
  820. await writeTestFile(root, "packages/skill-creator-plugin/hooks/run-hook.cmd", "");
  821. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  822. await writeTestFile(
  823. root,
  824. "packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md",
  825. "",
  826. );
  827. const { manifest } = await collectSeaOfficialPluginAssets({
  828. requireRuntime: true,
  829. root,
  830. stagingDirectory,
  831. });
  832. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  833. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  834. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  835. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  836. const pluginCreatorPlugin = manifest.plugins.find((item) => item.name === "plugin-creator");
  837. const documentPaths = new Set(
  838. manifest.plugins
  839. .filter((plugin) =>
  840. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  841. )
  842. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  843. );
  844. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  845. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  846. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  847. const skillCreatorRunHook = skillCreatorPlugin?.files.find(
  848. (file) => file.path === "hooks/run-hook.cmd",
  849. );
  850. assert.ok(pluginCreatorPlugin);
  851. assert.equal(
  852. pluginCreatorPlugin.files.some((file) => file.path === "skills/plugin-creator/SKILL.md"),
  853. true,
  854. );
  855. assert.equal(
  856. pluginCreatorPlugin.files.some((file) => file.path === "dist/mcp/server.js"),
  857. false,
  858. );
  859. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  860. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  861. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  862. assert.equal(documentPaths.has("dist/mcp/server.js"), false);
  863. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  864. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  865. assert.equal(browserUsePaths.has("docs/api.json"), true);
  866. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  867. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  868. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  869. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  870. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  871. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  872. assert.equal(
  873. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  874. true,
  875. );
  876. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  877. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  878. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  879. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  880. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  881. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  882. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  883. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  884. assert.equal(skillCreatorPaths.has("hooks/hooks.json"), true);
  885. assert.equal(skillCreatorPaths.has("hooks/run-hook.cmd"), true);
  886. assert.equal(skillCreatorRunHook?.mode, 0o755);
  887. assert.equal(skillCreatorPaths.has("dist/mcp/server.js"), false);
  888. } finally {
  889. await rm(directory, {
  890. force: true,
  891. recursive: true,
  892. });
  893. }
  894. });
  895. test("requires SEA runtime assets for runtime-backed official plugins", async () => {
  896. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-missing-runtime-"));
  897. const root = join(directory, "root");
  898. const stagingDirectory = join(directory, "staging");
  899. try {
  900. await writeVisualizePluginFixture(root);
  901. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  902. // 宿主要先齐备,这条测试隔离的是 android-emulator 缺 runtime 这一种情况。
  903. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  904. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  905. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  906. await writeTestFile(root, "packages/documents-plugin/.zcode-plugin/plugin.json", "{}");
  907. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  908. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  909. await writeTestFile(
  910. root,
  911. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  912. "{}",
  913. );
  914. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  915. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  916. await assert.rejects(
  917. collectSeaOfficialPluginAssets({
  918. requireRuntime: true,
  919. root,
  920. stagingDirectory,
  921. }),
  922. /Missing android-emulator MCP runtime/,
  923. );
  924. } finally {
  925. await rm(directory, {
  926. force: true,
  927. recursive: true,
  928. });
  929. }
  930. });
  931. test("requires the Browser Use client alongside the SEA MCP runtime", async () => {
  932. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-browser-client-missing-"));
  933. const root = join(directory, "root");
  934. const stagingDirectory = join(directory, "staging");
  935. try {
  936. await writeVisualizePluginFixture(root);
  937. for (const pluginName of [
  938. "android-emulator-plugin",
  939. "browser-use-plugin",
  940. "documents-plugin",
  941. "ios-simulator-plugin",
  942. "restore-legacy-sessions-plugin",
  943. "skill-creator-plugin",
  944. "zcode-guide-plugin",
  945. ]) {
  946. await writeTestFile(root, `packages/${pluginName}/.zcode-plugin/plugin.json`, "{}");
  947. }
  948. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  949. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  950. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  951. await writeDocumentPluginFixtures(root);
  952. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  953. await assert.rejects(
  954. collectSeaOfficialPluginAssets({
  955. requireRuntime: true,
  956. root,
  957. stagingDirectory,
  958. }),
  959. /Missing browser-use runtime asset.*browser-client\.mjs/u,
  960. );
  961. } finally {
  962. await rm(directory, {
  963. force: true,
  964. recursive: true,
  965. });
  966. }
  967. });
  968. test("maps SEA targets to Node.js release artifacts and URLs", () => {
  969. assert.equal(nodeReleaseArtifact("darwin-arm64", "24.14.0"), "node-v24.14.0-darwin-arm64.tar.gz");
  970. assert.equal(nodeReleaseArtifact("linux-x64", "24.14.0"), "node-v24.14.0-linux-x64.tar.xz");
  971. assert.equal(nodeReleaseArtifact("win-arm64", "24.14.0"), "win-arm64/node.exe");
  972. assert.equal(nodeReleaseArtifact("win-x64", "24.14.0"), "win-x64/node.exe");
  973. assert.equal(
  974. nodeReleaseUrl("win-arm64", "24.14.0"),
  975. "https://nodejs.org/dist/v24.14.0/win-arm64/node.exe",
  976. );
  977. assert.equal(
  978. nodeReleaseUrl("win-x64", "24.14.0"),
  979. "https://nodejs.org/dist/v24.14.0/win-x64/node.exe",
  980. );
  981. });
  982. async function writeTestFile(root, relativePath, contents) {
  983. const filePath = join(root, relativePath);
  984. await mkdir(dirname(filePath), {
  985. recursive: true,
  986. });
  987. await writeFile(filePath, contents);
  988. }
  989. test("adds the Mach-O segment argument only for macOS targets", () => {
  990. assert.deepEqual(
  991. postjectArgsForTarget({
  992. binaryPath: "/tmp/zcode-darwin-arm64",
  993. seaBlob: "/tmp/zcode.sea.blob",
  994. sentinelFuse: "NODE_SEA_FUSE_test",
  995. target: "darwin-arm64",
  996. }),
  997. [
  998. "/tmp/zcode-darwin-arm64",
  999. "NODE_SEA_BLOB",
  1000. "/tmp/zcode.sea.blob",
  1001. "--sentinel-fuse",
  1002. "NODE_SEA_FUSE_test",
  1003. "--macho-segment-name",
  1004. "NODE_SEA",
  1005. ],
  1006. );
  1007. assert.deepEqual(
  1008. postjectArgsForTarget({
  1009. binaryPath: "/tmp/zcode-linux-x64",
  1010. seaBlob: "/tmp/zcode.sea.blob",
  1011. sentinelFuse: "NODE_SEA_FUSE_test",
  1012. target: "linux-x64",
  1013. }),
  1014. [
  1015. "/tmp/zcode-linux-x64",
  1016. "NODE_SEA_BLOB",
  1017. "/tmp/zcode.sea.blob",
  1018. "--sentinel-fuse",
  1019. "NODE_SEA_FUSE_test",
  1020. ],
  1021. );
  1022. });
  1023. test("ad-hoc signs only macOS targets built on macOS hosts", () => {
  1024. assert.deepEqual(adHocCodesignArgs("/tmp/zcode-darwin-arm64"), [
  1025. "--force",
  1026. "--sign",
  1027. "-",
  1028. "/tmp/zcode-darwin-arm64",
  1029. ]);
  1030. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "darwin" }), true);
  1031. assert.equal(shouldAdHocSignMacTarget("darwin-x64", { platform: "darwin" }), true);
  1032. assert.equal(shouldAdHocSignMacTarget("linux-x64", { platform: "darwin" }), false);
  1033. assert.equal(shouldAdHocSignMacTarget("win-x64", { platform: "darwin" }), false);
  1034. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "linux" }), false);
  1035. });
  1036. test("resolves postject from a hoisted ancestor node_modules", async () => {
  1037. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-postject-"));
  1038. const cliDirectory = join(directory, "apps", "zcode-cli", "packages", "cli");
  1039. const binDirectory = join(directory, "node_modules", ".bin");
  1040. const postjectPath = join(binDirectory, "postject");
  1041. try {
  1042. await mkdir(cliDirectory, { recursive: true });
  1043. await mkdir(binDirectory, { recursive: true });
  1044. await writeFile(postjectPath, "");
  1045. assert.equal(
  1046. resolvePostjectBin({
  1047. platform: "linux",
  1048. startDirectory: cliDirectory,
  1049. }),
  1050. postjectPath,
  1051. );
  1052. } finally {
  1053. await rm(directory, {
  1054. force: true,
  1055. recursive: true,
  1056. });
  1057. }
  1058. });
  1059. test("removes and truncates a trailing Windows Authenticode certificate table", () => {
  1060. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1061. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1062. assert.equal(result.removed, true);
  1063. assert.equal(result.truncated, true);
  1064. assert.equal(result.certificateOffset, CERTIFICATE_OFFSET);
  1065. assert.equal(result.certificateSize, CERTIFICATE_SIZE);
  1066. assert.equal(result.buffer.length, CERTIFICATE_OFFSET);
  1067. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1068. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1069. assert.deepEqual(readWindowsAuthenticodeDirectory(result.buffer), {
  1070. certificateOffset: 0,
  1071. certificateSize: 0,
  1072. securityDirectoryEntryOffset,
  1073. signed: false,
  1074. });
  1075. });
  1076. test("removes a PE32 Authenticode directory without truncating non-certificate trailing data", () => {
  1077. const trailingBytes = 16;
  1078. const { contents, securityDirectoryEntryOffset } = createPeFixture({
  1079. pe32Plus: false,
  1080. trailingBytes,
  1081. });
  1082. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1083. assert.equal(result.removed, true);
  1084. assert.equal(result.truncated, false);
  1085. assert.equal(result.buffer.length, CERTIFICATE_OFFSET + CERTIFICATE_SIZE + trailingBytes);
  1086. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1087. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1088. });
  1089. test("leaves unsigned Windows PE binaries unchanged", () => {
  1090. const { contents } = createPeFixture({
  1091. signed: false,
  1092. });
  1093. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1094. assert.equal(result.removed, false);
  1095. assert.equal(result.truncated, false);
  1096. assert.equal(result.buffer, contents);
  1097. });
  1098. test("rejects Windows Authenticode directories outside the file range", () => {
  1099. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1100. contents.writeUInt32LE(contents.length + CERTIFICATE_SIZE, securityDirectoryEntryOffset);
  1101. assert.throws(
  1102. () => removeWindowsAuthenticodeSignatureFromBuffer(contents),
  1103. /Invalid PE certificate table/,
  1104. );
  1105. });
  1106. test("removes Windows Authenticode signatures from files", async () => {
  1107. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-authenticode-"));
  1108. const binaryPath = join(directory, "zcode-windows-x64.exe");
  1109. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1110. try {
  1111. await writeFile(binaryPath, contents);
  1112. const result = await removeWindowsAuthenticodeSignature(binaryPath);
  1113. const updated = await readFile(binaryPath);
  1114. assert.deepEqual(result, {
  1115. certificateOffset: CERTIFICATE_OFFSET,
  1116. certificateSize: CERTIFICATE_SIZE,
  1117. removed: true,
  1118. truncated: true,
  1119. });
  1120. assert.equal(updated.length, CERTIFICATE_OFFSET);
  1121. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset), 0);
  1122. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1123. } finally {
  1124. await rm(directory, {
  1125. force: true,
  1126. recursive: true,
  1127. });
  1128. }
  1129. });
  1130. test("matches host targets using Node.js platform names", () => {
  1131. assert.equal(
  1132. hostTarget({
  1133. arch: "x64",
  1134. platform: "win32",
  1135. }),
  1136. "win-x64",
  1137. );
  1138. assert.equal(
  1139. isHostTarget("win32-x64", {
  1140. arch: "x64",
  1141. platform: "win32",
  1142. }),
  1143. true,
  1144. );
  1145. assert.equal(
  1146. isHostTarget("linux-x64", {
  1147. arch: "arm64",
  1148. platform: "darwin",
  1149. }),
  1150. false,
  1151. );
  1152. });
  1153. test("resolves Turbo from the repository while retaining the CLI workspace graph", () => {
  1154. const cliPackageRoot = new URL("..", import.meta.url);
  1155. // 回归原因:CLI 是嵌套 workspace,--workspace-root 会把 Turbo 限定到未安装 binary 的内层 node_modules。
  1156. const result = spawnSync(
  1157. "pnpm",
  1158. [
  1159. "--dir",
  1160. "../../../..",
  1161. "exec",
  1162. "turbo",
  1163. "--skip-infer",
  1164. "--cwd",
  1165. "apps/zcode-cli",
  1166. "run",
  1167. "build",
  1168. "--filter=!@zcode/cli",
  1169. "--force",
  1170. "--dry=json",
  1171. ],
  1172. {
  1173. cwd: cliPackageRoot,
  1174. encoding: "utf8",
  1175. shell: process.platform === "win32",
  1176. },
  1177. );
  1178. assert.equal(result.status, 0, result.stderr || result.stdout);
  1179. assert.match(result.stdout, /"taskId":/u);
  1180. assert.doesNotMatch(result.stdout, /"package": "@zcode\/cli"/u);
  1181. });
  1182. test("can be dynamically imported when argv[1] is missing", () => {
  1183. const scriptUrl = new URL("../scripts/build-sea.mjs", import.meta.url).href;
  1184. const result = spawnSync(
  1185. process.execPath,
  1186. [
  1187. "-e",
  1188. `import(${JSON.stringify(scriptUrl)}).then((m) => console.log(m.outputBinaryName("win-x64")))`,
  1189. ],
  1190. {
  1191. encoding: "utf8",
  1192. },
  1193. );
  1194. assert.equal(result.status, 0, result.stderr);
  1195. assert.equal(result.stdout.trim(), "zcode-windows-x64.exe");
  1196. });
  1197. async function writeDocumentPluginFixtures(root) {
  1198. for (const [name, skill] of [
  1199. ["documents", "docx"],
  1200. ["pdf", "pdf"],
  1201. ["presentations", "pptx"],
  1202. ["spreadsheets", "xlsx"],
  1203. ]) {
  1204. await writeTestFile(root, `packages/${name}-plugin/.zcode-plugin/plugin.json`, "{}");
  1205. await writeTestFile(root, `packages/${name}-plugin/agents/visual-judge.md`, "");
  1206. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}/SKILL.md`, "");
  1207. // 0.2.0 起文档插件带查看面板:viewer skill 与 office-runtime 构建产物都是必需资产。
  1208. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}-viewer/SKILL.md`, "");
  1209. for (const runtimePath of ["dist/server.mjs", "dist/ui/assets.json", "dist/ui/panel.html"]) {
  1210. await writeTestFile(root, `packages/${name}-plugin/${runtimePath}`, "");
  1211. }
  1212. }
  1213. await writeTestFile(root, "packages/image-search-plugin/.zcode-plugin/plugin.json", "{}");
  1214. await writeTestFile(root, "packages/image-search-plugin/.mcp.json", "{}");
  1215. }
  1216. async function writeVisualizePluginFixture(root) {
  1217. // 官方清单新增静态插件后,运行时缺失用例也必须先准备其内容,避免提前失败。
  1218. const plugin = officialSeaPlugins.find((item) => item.name === "visualize");
  1219. assert.ok(plugin);
  1220. await writeTestFile(root, "packages/visualize-plugin/.zcode-plugin/plugin.json", "{}");
  1221. for (const path of plugin.requiredSeedPaths) {
  1222. await writeTestFile(root, `packages/visualize-plugin/${path}`, "");
  1223. }
  1224. }