build-sea.test.mjs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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 ../../../.. build:sea:prepare && 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. // session-control 只有子路径导出,没有 dist/index.js,仍须随 shared 打入 SEA。
  470. assert.equal(paths.has("node_modules/@zcode/session-control/dist/contract.js"), true);
  471. const zodPackages = manifest.files.filter((file) => file.path.endsWith("/zod/package.json"));
  472. const zodVersions = await Promise.all(
  473. zodPackages.map(async (file) => {
  474. const metadata = JSON.parse(
  475. await readFile(assets[`${seaTuiAssetPrefix}${file.path}`], "utf8"),
  476. );
  477. return metadata.version.split(".")[0];
  478. }),
  479. );
  480. assert.deepEqual([...new Set(zodVersions)].sort(), ["3", "4"]);
  481. // 根 workspace 的源码 exports 不能原样进入只包含 dist 的 SEA runtime。
  482. for (const packageName of ["@zcode/shared", "@zcode/model-option-map"]) {
  483. const assetKey = `${seaTuiAssetPrefix}node_modules/${packageName}/package.json`;
  484. const stagedPackage = JSON.parse(await readFile(assets[assetKey], "utf8"));
  485. assert.equal(stagedPackage.exports["."], "./dist/index.js");
  486. const sourcePackage = JSON.parse(
  487. await readFile(
  488. join(root, "../..", "packages", packageName.split("/")[1], "package.json"),
  489. "utf8",
  490. ),
  491. );
  492. assert.equal(sourcePackage.exports["."], "./src/index.ts");
  493. }
  494. } finally {
  495. await rm(directory, {
  496. force: true,
  497. recursive: true,
  498. });
  499. }
  500. });
  501. test("loads TUI from an extracted SEA runtime dependency closure", async () => {
  502. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-runtime-"));
  503. const root = join(import.meta.dirname, "../../..");
  504. const stagingDirectory = join(directory, "staging");
  505. const runtimeDirectory = join(directory, "runtime");
  506. try {
  507. const { assets, manifest } = await collectSeaTuiAssets({
  508. root,
  509. stagingDirectory,
  510. target: hostTarget(),
  511. });
  512. for (const file of manifest.files) {
  513. const sourcePath = assets[`${seaTuiAssetPrefix}${file.path}`];
  514. assert.equal(typeof sourcePath, "string");
  515. const outputPath = join(runtimeDirectory, file.path);
  516. await mkdir(dirname(outputPath), {
  517. recursive: true,
  518. });
  519. await copyFile(sourcePath, outputPath);
  520. }
  521. // Windows 锁定进程已加载的 opentui.dll;子进程退出释放 DLL 后,父进程才能清理目录。
  522. const entryUrl = pathToFileURL(
  523. join(runtimeDirectory, "node_modules/@zcode/tui/dist/index.js"),
  524. ).href;
  525. await promisify(execFile)(
  526. process.execPath,
  527. [
  528. "--input-type=module",
  529. "--eval",
  530. 'import assert from "node:assert/strict"; const tui = await import(process.argv[1]); assert.equal(typeof tui.runTui, "function");',
  531. entryUrl,
  532. ],
  533. { cwd: runtimeDirectory, timeout: 30000 },
  534. );
  535. } finally {
  536. await rm(directory, {
  537. force: true,
  538. recursive: true,
  539. });
  540. }
  541. });
  542. test("includes the pinned Playwright runtime required by headless Browser Use", async () => {
  543. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-playwright-assets-"));
  544. const root = join(import.meta.dirname, "../../..");
  545. try {
  546. const { assets, manifest } = await collectSeaPlaywrightAssets({
  547. root,
  548. stagingDirectory: directory,
  549. target: "linux-x64",
  550. });
  551. const paths = new Set(manifest.files.map((file) => file.path));
  552. assert.equal(manifest.packageVersion, "1.59.1");
  553. assert.equal(typeof assets[seaPlaywrightManifestAssetKey], "string");
  554. assert.equal(paths.has("node_modules/playwright-core/package.json"), true);
  555. assert.equal(paths.has("node_modules/playwright-core/index.js"), true);
  556. assert.equal(paths.has("node_modules/playwright-core/lib/server/browserType.js"), true);
  557. } finally {
  558. await rm(directory, { force: true, recursive: true });
  559. }
  560. });
  561. test("keeps the Browser Use SEA release at 0.5.1 with complete runtime assets", async () => {
  562. const root = join(import.meta.dirname, "../../..");
  563. const browserUsePlugin = officialSeaPlugins.find((plugin) => plugin.name === "browser-use");
  564. assert.equal(browserUsePlugin?.version, "0.5.1");
  565. assert.deepEqual(browserUsePlugin?.requiredRuntimePaths, [
  566. "scripts/browser-client.mjs",
  567. "docs/api.json",
  568. "docs/documents.json",
  569. "docs/overview.md",
  570. "docs/recording.md",
  571. "docs/workflow.md",
  572. "skills/control-browser/SKILL.md",
  573. "skills/web-gui-tester/SKILL.md",
  574. ]);
  575. const packageJson = JSON.parse(
  576. await readFile(join(root, browserUsePlugin.rootPath, "package.json"), "utf8"),
  577. );
  578. const pluginManifest = JSON.parse(
  579. await readFile(join(root, browserUsePlugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  580. );
  581. assert.deepEqual(
  582. {
  583. manifest: pluginManifest.version,
  584. package: packageJson.version,
  585. sea: browserUsePlugin.version,
  586. },
  587. {
  588. manifest: "0.5.1",
  589. package: "0.5.1",
  590. sea: "0.5.1",
  591. },
  592. );
  593. // Bug 原因:新增录屏能力时重写了整段插件描述,并把原生 WebM 误写成 MP4。
  594. assert.equal(
  595. pluginManifest.description,
  596. "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.",
  597. );
  598. });
  599. test("includes bundled official plugin assets", async () => {
  600. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-assets-"));
  601. const root = join(import.meta.dirname, "../../..");
  602. try {
  603. const { assets, manifest } = await collectSeaOfficialPluginAssets({
  604. root,
  605. stagingDirectory: directory,
  606. });
  607. const iosPlugin = manifest.plugins.find((item) => item.name === "ios-simulator");
  608. const androidPlugin = manifest.plugins.find((item) => item.name === "android-emulator");
  609. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  610. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  611. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  612. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  613. const zcodeGuidePlugin = manifest.plugins.find((item) => item.name === "zcode-guide");
  614. const iosPaths = new Set(iosPlugin?.files.map((file) => file.path));
  615. const androidPaths = new Set(androidPlugin?.files.map((file) => file.path));
  616. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  617. const documentPaths = new Set(
  618. manifest.plugins
  619. .filter((plugin) =>
  620. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  621. )
  622. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  623. );
  624. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  625. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  626. const zcodeGuidePaths = new Set(zcodeGuidePlugin?.files.map((file) => file.path));
  627. assert.equal(typeof assets[seaOfficialPluginManifestAssetKey], "string");
  628. assert.equal(iosPlugin?.marketplace, "zcode-plugins-official");
  629. assert.equal(androidPlugin?.marketplace, "zcode-plugins-official");
  630. assert.equal(browserUsePlugin?.marketplace, "zcode-plugins-official");
  631. assert.equal(documentPlugin?.marketplace, "zcode-plugins-official");
  632. assert.equal(restorePlugin?.marketplace, "zcode-plugins-official");
  633. assert.equal(skillCreatorPlugin?.marketplace, "zcode-plugins-official");
  634. assert.equal(zcodeGuidePlugin?.marketplace, "zcode-plugins-official");
  635. // superpowers 已从内置 SEA 清单移除,断言它不再出现在 manifest 里。
  636. assert.equal(
  637. manifest.plugins.some((item) => item.name === "superpowers"),
  638. false,
  639. );
  640. assert.equal(iosPaths.has(".zcode-plugin/plugin.json"), true);
  641. assert.equal(iosPaths.has("commands/ios-dev.md"), true);
  642. assert.equal(iosPaths.has("skills/ios-dev/SKILL.md"), true);
  643. assert.equal(iosPaths.has("src/mcp/server.ts"), false);
  644. assert.equal(androidPaths.has(".zcode-plugin/plugin.json"), true);
  645. assert.equal(androidPaths.has("commands/android-dev.md"), true);
  646. assert.equal(androidPaths.has("skills/android-dev/SKILL.md"), true);
  647. assert.equal(androidPaths.has("skills/android-dev/scripts/setup-windows.ps1"), false);
  648. assert.equal(androidPaths.has("src/mcp/server.ts"), false);
  649. assert.equal(browserUsePaths.has(".zcode-plugin/plugin.json"), true);
  650. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  651. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  652. assert.equal(browserUsePaths.has("docs/api.json"), true);
  653. assert.equal(browserUsePaths.has("docs/documents.json"), true);
  654. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  655. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  656. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  657. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  658. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  659. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  660. assert.equal(
  661. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  662. true,
  663. );
  664. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  665. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  666. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  667. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  668. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  669. assert.equal(documentPaths.has(".zcode-plugin/plugin.json"), true);
  670. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  671. assert.equal(documentPaths.has("skills/docx-viewer/SKILL.md"), true);
  672. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  673. assert.equal(documentPaths.has("skills/pdf/scripts/pdf.py"), true);
  674. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  675. assert.equal(documentPaths.has("agents/visual-judge.md"), true);
  676. assert.equal(documentPaths.has("skills/pptx/scripts/general_judge.py"), false);
  677. assert.equal(documentPaths.has("skills/xlsx/SKILL.md"), true);
  678. assert.equal(documentPaths.has("skills/xlsx/xlsx.py"), true);
  679. assert.equal(
  680. [...documentPaths].some((path) =>
  681. /(?:^|\/)(?:\.venv|__pycache__|\.DS_Store)(?:\/|$)/u.test(path),
  682. ),
  683. false,
  684. );
  685. assert.equal(restorePaths.has(".zcode-plugin/plugin.json"), true);
  686. assert.equal(restorePaths.has("commands/restore-legacy-sessions.md"), true);
  687. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  688. assert.equal(
  689. restorePaths.has("skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs"),
  690. true,
  691. );
  692. assert.equal(
  693. restorePaths.has("skills/restore-legacy-sessions/scripts/restore-conversation.mjs"),
  694. true,
  695. );
  696. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  697. assert.equal(skillCreatorPaths.has(".zcode-plugin/plugin.json"), true);
  698. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  699. assert.equal(zcodeGuidePaths.has(".zcode-plugin/plugin.json"), true);
  700. assert.equal(zcodeGuidePaths.has("skills/zcode-configuration-guide/SKILL.md"), true);
  701. assert.equal(zcodeGuidePaths.has("skills/diagnosing-mcp/SKILL.md"), true);
  702. assert.equal(zcodeGuidePaths.has("skills/diagnosing-skills/SKILL.md"), true);
  703. assert.equal(zcodeGuidePaths.has("skills/diagnosing-commands/SKILL.md"), true);
  704. assert.equal(zcodeGuidePaths.has("skills/diagnosing-hooks/SKILL.md"), true);
  705. assert.equal(zcodeGuidePaths.has("skills/diagnosing-plugins/SKILL.md"), true);
  706. // 0.3.0:/workflow 与 dynamic-workflows 不再随 zcode-guide 发布(见 bundled skill pack 用例)。
  707. assert.equal(zcodeGuidePaths.has("commands/workflow.md"), false);
  708. assert.equal(zcodeGuidePaths.has("skills/dynamic-workflows/SKILL.md"), false);
  709. // design:技能、规则、脚本、hook 与全量设计资源都要进 SEA;包内 test/ 与 .claude-plugin/ 清单不进。
  710. const designPlugin = manifest.plugins.find((item) => item.name === "design");
  711. const designPaths = new Set(designPlugin?.files.map((file) => file.path));
  712. assert.equal(designPlugin?.marketplace, "zcode-plugins-official");
  713. for (const path of [
  714. ".zcode-plugin/plugin.json",
  715. "skills/design/SKILL.md",
  716. "skills/design/references/output.md",
  717. "skills/design/scripts/design-lint.mjs",
  718. "skills/design/scripts/design-tokens.mjs",
  719. "skills/design/design-resources/NOTICE.md",
  720. "skills/design/design-resources/LICENSE.md",
  721. "hooks/hooks.json",
  722. "hooks/run-hook.cmd",
  723. "hooks/design-rules",
  724. ])
  725. assert.equal(designPaths.has(path), true, `design SEA asset missing ${path}`);
  726. assert.equal(
  727. [...designPaths].some(
  728. (path) => path.startsWith("test/") || path.startsWith(".claude-plugin/"),
  729. ),
  730. false,
  731. );
  732. } finally {
  733. await rm(directory, {
  734. force: true,
  735. recursive: true,
  736. });
  737. }
  738. });
  739. test("includes the bundled skill pack as content-hashed SEA assets", async () => {
  740. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-assets-"));
  741. const root = join(import.meta.dirname, "../../..");
  742. try {
  743. const { assets, manifest } = await collectSeaBundledSkillAssets({
  744. root,
  745. stagingDirectory: directory,
  746. });
  747. const paths = new Set(manifest.files.map((file) => file.path));
  748. assert.equal(manifest.version, 1);
  749. assert.match(manifest.hash, /^[0-9a-f]{64}$/u);
  750. assert.equal(typeof assets[seaBundledSkillManifestAssetKey], "string");
  751. for (const requiredPath of bundledSkillPackRequiredPaths) {
  752. assert.equal(paths.has(requiredPath), true, requiredPath);
  753. assert.equal(typeof assets[`${seaBundledSkillAssetPrefix}${requiredPath}`], "string");
  754. }
  755. // 资产只来自 skills/:README 之类的包元数据不进二进制。
  756. assert.equal(
  757. [...paths].every((path) => path.startsWith("skills/")),
  758. true,
  759. );
  760. for (const file of manifest.files) {
  761. assert.match(file.sha256, /^[0-9a-f]{64}$/u);
  762. }
  763. } finally {
  764. await rm(directory, { force: true, recursive: true });
  765. }
  766. });
  767. test("rejects a bundled skill pack that lost a required file", async () => {
  768. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-incomplete-"));
  769. const root = join(directory, "root");
  770. try {
  771. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/SKILL.md", "# s");
  772. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/patterns.md", "#");
  773. await assert.rejects(
  774. collectSeaBundledSkillAssets({ root, stagingDirectory: join(directory, "staging") }),
  775. /Missing bundled skill pack required asset/u,
  776. );
  777. } finally {
  778. await rm(directory, { force: true, recursive: true });
  779. }
  780. });
  781. test("allows skill-only official plugins when SEA runtime assets are required", async () => {
  782. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-runtime-assets-"));
  783. const root = join(directory, "root");
  784. const stagingDirectory = join(directory, "staging");
  785. try {
  786. await writeVisualizePluginFixture(root);
  787. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  788. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  789. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  790. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  791. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  792. await writeTestFile(root, "packages/browser-use-plugin/skills/control-browser/SKILL.md", "");
  793. await writeTestFile(root, "packages/browser-use-plugin/skills/web-gui-tester/SKILL.md", "");
  794. await writeTestFile(root, "packages/browser-use-plugin/docs/api.json", "{}");
  795. await writeTestFile(root, "packages/browser-use-plugin/docs/documents.json", "[]");
  796. await writeTestFile(root, "packages/browser-use-plugin/docs/overview.md", "");
  797. await writeTestFile(root, "packages/browser-use-plugin/docs/recording.md", "");
  798. await writeTestFile(root, "packages/browser-use-plugin/docs/workflow.md", "");
  799. await writeTestFile(root, "packages/browser-use-plugin/scripts/browser-client.mjs", "");
  800. await writeDocumentPluginFixtures(root);
  801. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  802. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  803. await writeTestFile(
  804. root,
  805. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  806. "{}",
  807. );
  808. await writeTestFile(
  809. root,
  810. "packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md",
  811. "",
  812. );
  813. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  814. await writeTestFile(root, "packages/skill-creator-plugin/skills/skill-creator/SKILL.md", "");
  815. // 新增官方内容插件后也要提供 fixture,否则采集会先报 manifest 缺失,无法验证免运行时资源。
  816. await writeTestFile(root, "packages/plugin-creator-plugin/.zcode-plugin/plugin.json", "{}");
  817. await writeTestFile(root, "packages/plugin-creator-plugin/skills/plugin-creator/SKILL.md", "");
  818. // skill-creator 用作「带可执行 hook 的 skill-only 官方插件」载体(原先由 superpowers 覆盖)。
  819. // collector 按 officialSeaPlugins 登记 + 伪造目录采集,真实 skill-creator 是否带 hook 无关紧要。
  820. await writeTestFile(root, "packages/skill-creator-plugin/hooks/hooks.json", "{}");
  821. await writeTestFile(root, "packages/skill-creator-plugin/hooks/run-hook.cmd", "");
  822. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  823. await writeTestFile(
  824. root,
  825. "packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md",
  826. "",
  827. );
  828. await writeTestFile(root, "packages/zcode-site-plugin/.zcode-plugin/plugin.json", "{}");
  829. await writeTestFile(root, "packages/zcode-site-plugin/scripts/zcode-site.mjs", "");
  830. await writeTestFile(root, "packages/zcode-site-plugin/skills/site-deploy/SKILL.md", "");
  831. await writeTestFile(root, "packages/zcode-site-plugin/scripts/stage.mjs", "");
  832. await writeTestFile(root, "packages/zcode-site-plugin/scripts/errors.mjs", "");
  833. // 0.4.0 起带 Sites 面板:插件自己构建的 server 与面板页面是必需运行时产物。
  834. await writeTestFile(root, "packages/zcode-site-plugin/dist/server.mjs", "");
  835. await writeTestFile(root, "packages/zcode-site-plugin/dist/ui/panel.html", "");
  836. // design 是带 hook 的纯内容型插件:requiresRuntime:false,只需 seed 必需文件。
  837. const designPlugin = officialSeaPlugins.find((plugin) => plugin.name === "design");
  838. await writeTestFile(root, "packages/design-plugin/.zcode-plugin/plugin.json", "{}");
  839. for (const seedPath of designPlugin?.requiredSeedPaths ?? [])
  840. await writeTestFile(root, join("packages/design-plugin", seedPath), "");
  841. const { manifest } = await collectSeaOfficialPluginAssets({
  842. requireRuntime: true,
  843. root,
  844. stagingDirectory,
  845. });
  846. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  847. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  848. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  849. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  850. const pluginCreatorPlugin = manifest.plugins.find((item) => item.name === "plugin-creator");
  851. const designSeaPlugin = manifest.plugins.find((item) => item.name === "design");
  852. assert.equal(
  853. designSeaPlugin?.files.find((file) => file.path === "hooks/design-rules")?.mode,
  854. 0o755,
  855. );
  856. assert.equal(
  857. designSeaPlugin?.files.some((file) => file.path === "dist/mcp/server.js"),
  858. false,
  859. );
  860. const documentPaths = new Set(
  861. manifest.plugins
  862. .filter((plugin) =>
  863. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  864. )
  865. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  866. );
  867. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  868. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  869. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  870. const skillCreatorRunHook = skillCreatorPlugin?.files.find(
  871. (file) => file.path === "hooks/run-hook.cmd",
  872. );
  873. assert.ok(pluginCreatorPlugin);
  874. assert.equal(
  875. pluginCreatorPlugin.files.some((file) => file.path === "skills/plugin-creator/SKILL.md"),
  876. true,
  877. );
  878. assert.equal(
  879. pluginCreatorPlugin.files.some((file) => file.path === "dist/mcp/server.js"),
  880. false,
  881. );
  882. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  883. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  884. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  885. assert.equal(documentPaths.has("dist/mcp/server.js"), false);
  886. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  887. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  888. assert.equal(browserUsePaths.has("docs/api.json"), true);
  889. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  890. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  891. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  892. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  893. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  894. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  895. assert.equal(
  896. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  897. true,
  898. );
  899. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  900. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  901. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  902. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  903. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  904. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  905. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  906. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  907. assert.equal(skillCreatorPaths.has("hooks/hooks.json"), true);
  908. assert.equal(skillCreatorPaths.has("hooks/run-hook.cmd"), true);
  909. assert.equal(skillCreatorRunHook?.mode, 0o755);
  910. assert.equal(skillCreatorPaths.has("dist/mcp/server.js"), false);
  911. } finally {
  912. await rm(directory, {
  913. force: true,
  914. recursive: true,
  915. });
  916. }
  917. });
  918. test("requires SEA runtime assets for runtime-backed official plugins", async () => {
  919. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-missing-runtime-"));
  920. const root = join(directory, "root");
  921. const stagingDirectory = join(directory, "staging");
  922. try {
  923. await writeVisualizePluginFixture(root);
  924. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  925. // 宿主要先齐备,这条测试隔离的是 android-emulator 缺 runtime 这一种情况。
  926. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  927. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  928. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  929. await writeTestFile(root, "packages/documents-plugin/.zcode-plugin/plugin.json", "{}");
  930. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  931. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  932. await writeTestFile(
  933. root,
  934. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  935. "{}",
  936. );
  937. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  938. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  939. await assert.rejects(
  940. collectSeaOfficialPluginAssets({
  941. requireRuntime: true,
  942. root,
  943. stagingDirectory,
  944. }),
  945. /Missing android-emulator MCP runtime/,
  946. );
  947. } finally {
  948. await rm(directory, {
  949. force: true,
  950. recursive: true,
  951. });
  952. }
  953. });
  954. test("requires the Browser Use client alongside the SEA MCP runtime", async () => {
  955. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-browser-client-missing-"));
  956. const root = join(directory, "root");
  957. const stagingDirectory = join(directory, "staging");
  958. try {
  959. await writeVisualizePluginFixture(root);
  960. for (const pluginName of [
  961. "android-emulator-plugin",
  962. "browser-use-plugin",
  963. "documents-plugin",
  964. "ios-simulator-plugin",
  965. "restore-legacy-sessions-plugin",
  966. "skill-creator-plugin",
  967. "zcode-guide-plugin",
  968. ]) {
  969. await writeTestFile(root, `packages/${pluginName}/.zcode-plugin/plugin.json`, "{}");
  970. }
  971. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  972. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  973. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  974. await writeDocumentPluginFixtures(root);
  975. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  976. await assert.rejects(
  977. collectSeaOfficialPluginAssets({
  978. requireRuntime: true,
  979. root,
  980. stagingDirectory,
  981. }),
  982. /Missing browser-use runtime asset.*browser-client\.mjs/u,
  983. );
  984. } finally {
  985. await rm(directory, {
  986. force: true,
  987. recursive: true,
  988. });
  989. }
  990. });
  991. test("maps SEA targets to Node.js release artifacts and URLs", () => {
  992. assert.equal(nodeReleaseArtifact("darwin-arm64", "24.14.0"), "node-v24.14.0-darwin-arm64.tar.gz");
  993. assert.equal(nodeReleaseArtifact("linux-x64", "24.14.0"), "node-v24.14.0-linux-x64.tar.xz");
  994. assert.equal(nodeReleaseArtifact("win-arm64", "24.14.0"), "win-arm64/node.exe");
  995. assert.equal(nodeReleaseArtifact("win-x64", "24.14.0"), "win-x64/node.exe");
  996. assert.equal(
  997. nodeReleaseUrl("win-arm64", "24.14.0"),
  998. "https://nodejs.org/dist/v24.14.0/win-arm64/node.exe",
  999. );
  1000. assert.equal(
  1001. nodeReleaseUrl("win-x64", "24.14.0"),
  1002. "https://nodejs.org/dist/v24.14.0/win-x64/node.exe",
  1003. );
  1004. });
  1005. async function writeTestFile(root, relativePath, contents) {
  1006. const filePath = join(root, relativePath);
  1007. await mkdir(dirname(filePath), {
  1008. recursive: true,
  1009. });
  1010. await writeFile(filePath, contents);
  1011. }
  1012. test("adds the Mach-O segment argument only for macOS targets", () => {
  1013. assert.deepEqual(
  1014. postjectArgsForTarget({
  1015. binaryPath: "/tmp/zcode-darwin-arm64",
  1016. seaBlob: "/tmp/zcode.sea.blob",
  1017. sentinelFuse: "NODE_SEA_FUSE_test",
  1018. target: "darwin-arm64",
  1019. }),
  1020. [
  1021. "/tmp/zcode-darwin-arm64",
  1022. "NODE_SEA_BLOB",
  1023. "/tmp/zcode.sea.blob",
  1024. "--sentinel-fuse",
  1025. "NODE_SEA_FUSE_test",
  1026. "--macho-segment-name",
  1027. "NODE_SEA",
  1028. ],
  1029. );
  1030. assert.deepEqual(
  1031. postjectArgsForTarget({
  1032. binaryPath: "/tmp/zcode-linux-x64",
  1033. seaBlob: "/tmp/zcode.sea.blob",
  1034. sentinelFuse: "NODE_SEA_FUSE_test",
  1035. target: "linux-x64",
  1036. }),
  1037. [
  1038. "/tmp/zcode-linux-x64",
  1039. "NODE_SEA_BLOB",
  1040. "/tmp/zcode.sea.blob",
  1041. "--sentinel-fuse",
  1042. "NODE_SEA_FUSE_test",
  1043. ],
  1044. );
  1045. });
  1046. test("ad-hoc signs only macOS targets built on macOS hosts", () => {
  1047. assert.deepEqual(adHocCodesignArgs("/tmp/zcode-darwin-arm64"), [
  1048. "--force",
  1049. "--sign",
  1050. "-",
  1051. "/tmp/zcode-darwin-arm64",
  1052. ]);
  1053. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "darwin" }), true);
  1054. assert.equal(shouldAdHocSignMacTarget("darwin-x64", { platform: "darwin" }), true);
  1055. assert.equal(shouldAdHocSignMacTarget("linux-x64", { platform: "darwin" }), false);
  1056. assert.equal(shouldAdHocSignMacTarget("win-x64", { platform: "darwin" }), false);
  1057. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "linux" }), false);
  1058. });
  1059. test("resolves postject from a hoisted ancestor node_modules", async () => {
  1060. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-postject-"));
  1061. const cliDirectory = join(directory, "apps", "zcode-cli", "packages", "cli");
  1062. const binDirectory = join(directory, "node_modules", ".bin");
  1063. const postjectPath = join(binDirectory, "postject");
  1064. try {
  1065. await mkdir(cliDirectory, { recursive: true });
  1066. await mkdir(binDirectory, { recursive: true });
  1067. await writeFile(postjectPath, "");
  1068. assert.equal(
  1069. resolvePostjectBin({
  1070. platform: "linux",
  1071. startDirectory: cliDirectory,
  1072. }),
  1073. postjectPath,
  1074. );
  1075. } finally {
  1076. await rm(directory, {
  1077. force: true,
  1078. recursive: true,
  1079. });
  1080. }
  1081. });
  1082. test("removes and truncates a trailing Windows Authenticode certificate table", () => {
  1083. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1084. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1085. assert.equal(result.removed, true);
  1086. assert.equal(result.truncated, true);
  1087. assert.equal(result.certificateOffset, CERTIFICATE_OFFSET);
  1088. assert.equal(result.certificateSize, CERTIFICATE_SIZE);
  1089. assert.equal(result.buffer.length, CERTIFICATE_OFFSET);
  1090. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1091. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1092. assert.deepEqual(readWindowsAuthenticodeDirectory(result.buffer), {
  1093. certificateOffset: 0,
  1094. certificateSize: 0,
  1095. securityDirectoryEntryOffset,
  1096. signed: false,
  1097. });
  1098. });
  1099. test("removes a PE32 Authenticode directory without truncating non-certificate trailing data", () => {
  1100. const trailingBytes = 16;
  1101. const { contents, securityDirectoryEntryOffset } = createPeFixture({
  1102. pe32Plus: false,
  1103. trailingBytes,
  1104. });
  1105. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1106. assert.equal(result.removed, true);
  1107. assert.equal(result.truncated, false);
  1108. assert.equal(result.buffer.length, CERTIFICATE_OFFSET + CERTIFICATE_SIZE + trailingBytes);
  1109. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1110. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1111. });
  1112. test("leaves unsigned Windows PE binaries unchanged", () => {
  1113. const { contents } = createPeFixture({
  1114. signed: false,
  1115. });
  1116. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1117. assert.equal(result.removed, false);
  1118. assert.equal(result.truncated, false);
  1119. assert.equal(result.buffer, contents);
  1120. });
  1121. test("rejects Windows Authenticode directories outside the file range", () => {
  1122. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1123. contents.writeUInt32LE(contents.length + CERTIFICATE_SIZE, securityDirectoryEntryOffset);
  1124. assert.throws(
  1125. () => removeWindowsAuthenticodeSignatureFromBuffer(contents),
  1126. /Invalid PE certificate table/,
  1127. );
  1128. });
  1129. test("removes Windows Authenticode signatures from files", async () => {
  1130. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-authenticode-"));
  1131. const binaryPath = join(directory, "zcode-windows-x64.exe");
  1132. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1133. try {
  1134. await writeFile(binaryPath, contents);
  1135. const result = await removeWindowsAuthenticodeSignature(binaryPath);
  1136. const updated = await readFile(binaryPath);
  1137. assert.deepEqual(result, {
  1138. certificateOffset: CERTIFICATE_OFFSET,
  1139. certificateSize: CERTIFICATE_SIZE,
  1140. removed: true,
  1141. truncated: true,
  1142. });
  1143. assert.equal(updated.length, CERTIFICATE_OFFSET);
  1144. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset), 0);
  1145. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1146. } finally {
  1147. await rm(directory, {
  1148. force: true,
  1149. recursive: true,
  1150. });
  1151. }
  1152. });
  1153. test("matches host targets using Node.js platform names", () => {
  1154. assert.equal(
  1155. hostTarget({
  1156. arch: "x64",
  1157. platform: "win32",
  1158. }),
  1159. "win-x64",
  1160. );
  1161. assert.equal(
  1162. isHostTarget("win32-x64", {
  1163. arch: "x64",
  1164. platform: "win32",
  1165. }),
  1166. true,
  1167. );
  1168. assert.equal(
  1169. isHostTarget("linux-x64", {
  1170. arch: "arm64",
  1171. platform: "darwin",
  1172. }),
  1173. false,
  1174. );
  1175. });
  1176. test("builds SEA dependencies from the root workspace graph", async () => {
  1177. const repositoryRoot = new URL("../../../../../", import.meta.url);
  1178. const rootPackage = JSON.parse(await readFile(new URL("package.json", repositoryRoot), "utf8"));
  1179. const filters = [...rootPackage.scripts["build:sea:prepare"].matchAll(/--filter=("[^"]+"|\S+)/gu)]
  1180. .map((match) => match[1].replaceAll('"', ""))
  1181. .flatMap((filter) => ["--filter", filter]);
  1182. // 回归原因:CLI 子 workspace 的 Turbo 图看不到根 session-control,build:sea 不会生成其 dist。
  1183. const result = spawnSync("pnpm", [...filters, "list", "--depth", "-1", "--json"], {
  1184. cwd: repositoryRoot,
  1185. encoding: "utf8",
  1186. shell: process.platform === "win32",
  1187. });
  1188. assert.equal(result.status, 0, result.stderr || result.stdout);
  1189. const names = JSON.parse(result.stdout).map((pkg) => pkg.name);
  1190. assert.ok(names.includes("@zcode/session-control"));
  1191. assert.ok(!names.includes("@zcode/cli"));
  1192. });
  1193. test("can be dynamically imported when argv[1] is missing", () => {
  1194. const scriptUrl = new URL("../scripts/build-sea.mjs", import.meta.url).href;
  1195. const result = spawnSync(
  1196. process.execPath,
  1197. [
  1198. "-e",
  1199. `import(${JSON.stringify(scriptUrl)}).then((m) => console.log(m.outputBinaryName("win-x64")))`,
  1200. ],
  1201. {
  1202. encoding: "utf8",
  1203. },
  1204. );
  1205. assert.equal(result.status, 0, result.stderr);
  1206. assert.equal(result.stdout.trim(), "zcode-windows-x64.exe");
  1207. });
  1208. async function writeDocumentPluginFixtures(root) {
  1209. for (const [name, skill] of [
  1210. ["documents", "docx"],
  1211. ["pdf", "pdf"],
  1212. ["presentations", "pptx"],
  1213. ["spreadsheets", "xlsx"],
  1214. ]) {
  1215. await writeTestFile(root, `packages/${name}-plugin/.zcode-plugin/plugin.json`, "{}");
  1216. await writeTestFile(root, `packages/${name}-plugin/agents/visual-judge.md`, "");
  1217. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}/SKILL.md`, "");
  1218. // 0.2.0 起文档插件带查看面板:viewer skill 与 office-runtime 构建产物都是必需资产。
  1219. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}-viewer/SKILL.md`, "");
  1220. for (const runtimePath of ["dist/server.mjs", "dist/ui/assets.json", "dist/ui/panel.html"]) {
  1221. await writeTestFile(root, `packages/${name}-plugin/${runtimePath}`, "");
  1222. }
  1223. }
  1224. await writeTestFile(root, "packages/image-search-plugin/.zcode-plugin/plugin.json", "{}");
  1225. await writeTestFile(root, "packages/image-search-plugin/.mcp.json", "{}");
  1226. }
  1227. async function writeVisualizePluginFixture(root) {
  1228. // 官方清单新增静态插件后,运行时缺失用例也必须先准备其内容,避免提前失败。
  1229. const plugin = officialSeaPlugins.find((item) => item.name === "visualize");
  1230. assert.ok(plugin);
  1231. await writeTestFile(root, "packages/visualize-plugin/.zcode-plugin/plugin.json", "{}");
  1232. for (const path of plugin.requiredSeedPaths) {
  1233. await writeTestFile(root, `packages/visualize-plugin/${path}`, "");
  1234. }
  1235. }