build-native-search-tools.test.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. import { spawnSync } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join } from "node:path";
  6. import { pathToFileURL } from "node:url";
  7. import { describe, expect, it } from "vitest";
  8. import {
  9. MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET,
  10. LEGACY_REMOTE_RIPGREP_VERSION,
  11. LINUX_NATIVE_SEARCH_GLIBC_BASELINE,
  12. NATIVE_SEARCH_BFS_CONFIGURE_ARGS,
  13. NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS,
  14. NATIVE_SEARCH_PREBUILT_RELEASES,
  15. NATIVE_SEARCH_PRODUCER_ARCHIVE_SHA256_BY_TARGET,
  16. NATIVE_SEARCH_RIPGREP_REVISION,
  17. NATIVE_SEARCH_SOURCE_ARCHIVES,
  18. NATIVE_SEARCH_TOOL_VERSIONS,
  19. getExpectedUgrepFeatureContract,
  20. getNativeSearchProducerOutputIds,
  21. getNativeSearchRuntimeToolIdsForPlatform,
  22. getNativeSearchSourceArchivesForTarget,
  23. resolveNativeSearchBuildPlan,
  24. resolveNativeSearchPrebuiltRelease,
  25. resolveNativeSearchPrebuiltDownloadBaseUrl,
  26. resolveNativeSearchPrebuiltPlan,
  27. resolveNativeSearchRipgrepDownloadBaseUrl,
  28. resolveNativeSearchReleasePlan,
  29. } from "../../../scripts/native-search-tools-config.mjs";
  30. import {
  31. assertLinuxNativeSearchBuildEnvironment,
  32. createBfsBuildEnvironment,
  33. resolveNativeUnixBuildConfig,
  34. } from "../../../scripts/native-search-tools-unix.mjs";
  35. import { resolveNativeWindowsBuildConfig } from "../../../scripts/native-search-tools-windows.mjs";
  36. import {
  37. getAllowedLinuxNativeSearchDependencies,
  38. getRequiredGlibcVersions,
  39. verifyLinuxGlibcBaseline,
  40. verifyBuiltNativeSearchProducerOutputs,
  41. verifyBuiltNativeSearchTools,
  42. verifyMacosDeploymentTarget,
  43. verifyNativeSearchBinaryTarget,
  44. } from "../../../scripts/native-search-tools-verify.mjs";
  45. import { readWindowsPeMetadata } from "../../../scripts/native-search-tools-windows-pe.mjs";
  46. import {
  47. packNativeSearchPrebuiltArtifacts,
  48. resolveNativeSearchPackagedArtifactPath,
  49. } from "../../../scripts/package-native-search-tools.mjs";
  50. const rootPackageJson = JSON.parse(
  51. readFileSync(join(import.meta.dirname, "../../../package.json"), "utf8"),
  52. ) as { scripts: Record<string, string> };
  53. const windowsNativeSearchCmake = readFileSync(
  54. join(import.meta.dirname, "../../../scripts/native-search-tools-windows/CMakeLists.txt"),
  55. "utf8",
  56. );
  57. // 内网依赖源由环境显式配置;用中性主机,测试不依赖仓库默认的内网地址(开源导出里默认地址为空)。
  58. const INTRANET_ENV = { INTRANET_MACHINE_HOST: "intranet-deps.example" };
  59. const INTRANET_DEPS_BASE_URL = "http://intranet-deps.example:12345/zcode/deps";
  60. describe("native search build", () => {
  61. it("通过简洁的 host-target producer 命令打包原生搜索工具", () => {
  62. expect(rootPackageJson.scripts["pack:native-search"]).toBe(
  63. "node scripts/package-native-search-tools.mjs",
  64. );
  65. expect(rootPackageJson.scripts).not.toHaveProperty("pack:native-search:linux:rocky8");
  66. expect(rootPackageJson.scripts["ci:ensure-native-search-deps"]).toBe(
  67. "node scripts/ensure-native-search-deps.mjs",
  68. );
  69. expect(rootPackageJson.scripts).not.toHaveProperty("package:native-search");
  70. });
  71. it("固定 native search 工具版本、生产源码与完整性摘要", () => {
  72. expect(NATIVE_SEARCH_TOOL_VERSIONS).toEqual({
  73. bfs: "4.1.1",
  74. ripgrep: "14.1.1",
  75. ugrep: "7.8.4",
  76. });
  77. expect(NATIVE_SEARCH_RIPGREP_REVISION).toBe("4649aa9700");
  78. expect(LEGACY_REMOTE_RIPGREP_VERSION).toBe("v13.0.0-10");
  79. expect(NATIVE_SEARCH_PREBUILT_RELEASES).toEqual({
  80. bfs: "v4.1.1-1",
  81. ripgrep: "v14.1.1-1",
  82. ugrep: "v7.8.4-1",
  83. });
  84. expect(LINUX_NATIVE_SEARCH_GLIBC_BASELINE).toBe("2.28");
  85. expect(resolveNativeSearchPrebuiltRelease("bfs", "linux")).toBe("v4.1.1-2");
  86. expect(resolveNativeSearchPrebuiltRelease("ugrep", "linux")).toBe("v7.8.4-1");
  87. expect(resolveNativeSearchPrebuiltRelease("bfs", "darwin")).toBe("v4.1.1-1");
  88. expect(resolveNativeSearchPrebuiltRelease("ugrep", "win32")).toBe("v7.8.4-1");
  89. expect(NATIVE_SEARCH_SOURCE_ARCHIVES.map(({ id, version }) => `${id}@${version}`)).toEqual([
  90. "bfs@4.1.1",
  91. "ugrep@7.8.4",
  92. "oniguruma@6.9.10",
  93. "pcre2@10.43",
  94. "zlib@1.3.1",
  95. "bzip2@1.0.8",
  96. "zstd@1.5.6",
  97. "brotli@1.1.0",
  98. ]);
  99. for (const source of NATIVE_SEARCH_SOURCE_ARCHIVES) {
  100. expect(source.url).toMatch(/^https:\/\//);
  101. expect(source.sha256).toMatch(/^[a-f0-9]{64}$/);
  102. }
  103. expect(NATIVE_SEARCH_SOURCE_ARCHIVES.find(({ id }) => id === "ugrep")).toEqual({
  104. id: "ugrep",
  105. version: "7.8.4",
  106. url: "https://codeload.github.com/Genivia/ugrep/tar.gz/550599a6434fc5315fb6ecd415a5d859e6d846a8",
  107. sha256: "0b3ed2dc7c3902d89f2ef8b66961db2e31a32f240fa2a2e0eb8d559827f36dab",
  108. });
  109. expect(NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS).toEqual({
  110. "darwin-arm64": {
  111. archiveExt: "tar.gz",
  112. releaseFileName: "ripgrep-v14.1.1-1-aarch64-apple-darwin.tar.gz",
  113. revision: NATIVE_SEARCH_RIPGREP_REVISION,
  114. sha256: "84ff9b227b9aad651be0ac4cf7802a190015bfba3dfa6b015cc7aa89dd8c5c2b",
  115. },
  116. "darwin-x64": {
  117. archiveExt: "tar.gz",
  118. releaseFileName: "ripgrep-v14.1.1-1-x86_64-apple-darwin.tar.gz",
  119. revision: NATIVE_SEARCH_RIPGREP_REVISION,
  120. sha256: "cfedd7993342bc5f90310ce73a00cbf5d3b5237654c9bfc18b383f0e829f3b11",
  121. },
  122. "linux-arm64": {
  123. archiveExt: "tar.gz",
  124. releaseFileName: "ripgrep-v14.1.1-1-aarch64-unknown-linux-musl.tar.gz",
  125. revision: null,
  126. sha256: "98c0371366a9db920ed6c196083e8030511055e5f128b3bde2ca56bbddf85b9a",
  127. },
  128. "linux-x64": {
  129. archiveExt: "tar.gz",
  130. releaseFileName: "ripgrep-v14.1.1-1-x86_64-unknown-linux-musl.tar.gz",
  131. revision: NATIVE_SEARCH_RIPGREP_REVISION,
  132. sha256: "1154dd91f7b144cee490b91f1ab27ce04f8f01d8876cde2d9c0eff845c8ab012",
  133. },
  134. "win32-x64": {
  135. archiveExt: "zip",
  136. releaseFileName: "ripgrep-v14.1.1-1-x86_64-pc-windows-msvc.zip",
  137. revision: NATIVE_SEARCH_RIPGREP_REVISION,
  138. sha256: "ede1d7f533f30d7e2870f77139d0fb9d7591daad5260b80d6a525e0bb5bd440e",
  139. },
  140. "win32-arm64": {
  141. archiveExt: "zip",
  142. releaseFileName: "ripgrep-v14.1.1-1-aarch64-pc-windows-msvc.zip",
  143. revision: NATIVE_SEARCH_RIPGREP_REVISION,
  144. sha256: "88660d96f822d2e0329e254031068e82028f9c13efcec9b2d78c5a19d3f9ac47",
  145. },
  146. });
  147. expect(NATIVE_SEARCH_PRODUCER_ARCHIVE_SHA256_BY_TARGET).toEqual({
  148. "darwin-arm64": {
  149. bfs: "696f73eaff50d3c3de8a8ee36746a89693dd6ff0d010b05cd3b4b3eb2a369781",
  150. ugrep: "01ea803e3fc3b94e796a9376e4d062a5490fe08e5760c6173e72b8f31546a4f3",
  151. },
  152. "darwin-x64": {
  153. bfs: "d993d72530749fa777339a7546f03338499abf235e2147d4adcd086641c6376f",
  154. ugrep: "6a2bedd9ccf53a2ac574d2fa498a36dcbe21e957b40442f9493180c6dad4dea9",
  155. },
  156. "linux-arm64": {
  157. bfs: "dabdde935a02f89dd0c48c5cd0ec756a87d300fd5ace85a78e6a9eb51d771118",
  158. ugrep: "bf3b99c0af41f50c0ec3031b32ab8f67fa95b5581add18fad5163ece978d31ba",
  159. },
  160. "linux-x64": {
  161. bfs: "9adf5759000021dd8fcd99670461cc43863f9172fb16f2f9a3e49c700311e7a0",
  162. ugrep: "13732f50fe63da07f3472f627f611b75359153163d07a0eb01e7c54125ae930e",
  163. },
  164. "win32-arm64": {
  165. ugrep: "e9de73f1b542105203d586b19b4d57b8ecf2bf780f23e86c66a0fb7f56d51024",
  166. },
  167. "win32-x64": {
  168. ugrep: "7bbd8e56540d2019a343688f1fc0ddb2ff5f0988090c577d2b9d6f4a8a86be21",
  169. },
  170. });
  171. });
  172. it("预编译资源按目标固定为 producer 或 Microsoft release", () => {
  173. const darwin = resolveNativeSearchPrebuiltPlan({
  174. platform: "darwin",
  175. arch: "arm64",
  176. env: INTRANET_ENV,
  177. });
  178. expect(darwin.artifacts.map(({ toolId, downloadUrl }) => [toolId, downloadUrl])).toEqual([
  179. [
  180. "bfs",
  181. `${INTRANET_DEPS_BASE_URL}/native-search-tools/bfs-v4.1.1-1/bfs-v4.1.1-1-aarch64-apple-darwin.tar.gz`,
  182. ],
  183. [
  184. "ugrep",
  185. `${INTRANET_DEPS_BASE_URL}/native-search-tools/ugrep-v7.8.4-1/ugrep-v7.8.4-1-aarch64-apple-darwin.tar.gz`,
  186. ],
  187. [
  188. "ripgrep",
  189. `${INTRANET_DEPS_BASE_URL}/native-search-tools/ripgrep-v14.1.1-1/ripgrep-v14.1.1-1-aarch64-apple-darwin.tar.gz`,
  190. ],
  191. ]);
  192. const linux = resolveNativeSearchPrebuiltPlan({ platform: "linux", arch: "x64", env: INTRANET_ENV });
  193. expect(
  194. linux.artifacts.map(({ toolId, releaseFileName, source }) => [
  195. toolId,
  196. releaseFileName,
  197. source,
  198. ]),
  199. ).toEqual([
  200. ["bfs", "bfs-v4.1.1-2-x86_64-unknown-linux-gnu.tar.gz", "producer"],
  201. ["ugrep", "ugrep-v7.8.4-1-x86_64-unknown-linux-gnu.tar.gz", "producer"],
  202. ["ripgrep", "ripgrep-v14.1.1-1-x86_64-unknown-linux-musl.tar.gz", "official"],
  203. ]);
  204. expect(linux.artifacts.slice(0, 2).map(({ downloadUrl }) => downloadUrl)).toEqual([
  205. `${INTRANET_DEPS_BASE_URL}/native-search-tools/bfs-v4.1.1-2/bfs-v4.1.1-2-x86_64-unknown-linux-gnu.tar.gz`,
  206. `${INTRANET_DEPS_BASE_URL}/native-search-tools/ugrep-v7.8.4-1/ugrep-v7.8.4-1-x86_64-unknown-linux-gnu.tar.gz`,
  207. ]);
  208. expect(linux.artifacts.slice(0, 2).map(({ archiveSha256 }) => archiveSha256)).toEqual([
  209. NATIVE_SEARCH_PRODUCER_ARCHIVE_SHA256_BY_TARGET["linux-x64"].bfs,
  210. NATIVE_SEARCH_PRODUCER_ARCHIVE_SHA256_BY_TARGET["linux-x64"].ugrep,
  211. ]);
  212. expect(linux.artifacts.at(-1)).toMatchObject({
  213. archiveSha256: NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS["linux-x64"].sha256,
  214. downloadUrl:
  215. `${INTRANET_DEPS_BASE_URL}/native-search-tools/ripgrep-v14.1.1-1/ripgrep-v14.1.1-1-x86_64-unknown-linux-musl.tar.gz`,
  216. });
  217. const windows = resolveNativeSearchPrebuiltPlan({ platform: "win32", arch: "x64", env: INTRANET_ENV });
  218. expect(windows.artifacts).toMatchObject([
  219. {
  220. archiveExt: "zip",
  221. binaryName: "ugrep.exe",
  222. releaseFileName: "ugrep-v7.8.4-1-x86_64-pc-windows-msvc.zip",
  223. toolId: "ugrep",
  224. },
  225. {
  226. archiveExt: "zip",
  227. binaryName: "rg.exe",
  228. releaseFileName: "ripgrep-v14.1.1-1-x86_64-pc-windows-msvc.zip",
  229. source: "official",
  230. toolId: "ripgrep",
  231. },
  232. ]);
  233. expect(
  234. resolveNativeSearchPrebuiltPlan({ platform: "win32", arch: "arm64" }).artifacts,
  235. ).toMatchObject([
  236. {
  237. releaseFileName: "ugrep-v7.8.4-1-aarch64-pc-windows-msvc.zip",
  238. toolId: "ugrep",
  239. },
  240. {
  241. archiveSha256: NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS["win32-arm64"].sha256,
  242. releaseFileName: "ripgrep-v14.1.1-1-aarch64-pc-windows-msvc.zip",
  243. source: "official",
  244. toolId: "ripgrep",
  245. },
  246. ]);
  247. for (const [platformKey, sha256ByTool] of Object.entries(
  248. NATIVE_SEARCH_PRODUCER_ARCHIVE_SHA256_BY_TARGET,
  249. )) {
  250. const [platform, arch] = platformKey.split("-") as [
  251. "darwin" | "linux" | "win32",
  252. "arm64" | "x64",
  253. ];
  254. const producerArtifacts = resolveNativeSearchPrebuiltPlan({
  255. platform,
  256. arch,
  257. }).artifacts.filter(({ source }) => source === "producer");
  258. for (const [toolId, archiveSha256] of Object.entries(sha256ByTool)) {
  259. expect(producerArtifacts.find((artifact) => artifact.toolId === toolId)).toMatchObject({
  260. archiveSha256,
  261. });
  262. }
  263. }
  264. for (const [platformKey, asset] of Object.entries(NATIVE_SEARCH_OFFICIAL_RIPGREP_ASSETS)) {
  265. const [platform, arch] = platformKey.split("-") as [
  266. "darwin" | "linux" | "win32",
  267. "arm64" | "x64",
  268. ];
  269. const ripgrepArtifact = resolveNativeSearchPrebuiltPlan({ platform, arch }).artifacts.find(
  270. ({ toolId }) => toolId === "ripgrep",
  271. );
  272. expect(ripgrepArtifact).toMatchObject({
  273. archiveSha256: asset.sha256,
  274. release: "v14.1.1-1",
  275. releaseFileName: asset.releaseFileName,
  276. source: "official",
  277. });
  278. }
  279. });
  280. it("预编译资源 base url 支持与既有 ripgrep 相同的显式覆盖", () => {
  281. expect(resolveNativeSearchRipgrepDownloadBaseUrl(INTRANET_ENV)).toBe(
  282. `${INTRANET_DEPS_BASE_URL}/native-search-tools/ripgrep-v14.1.1-1`,
  283. );
  284. expect(
  285. resolveNativeSearchPrebuiltDownloadBaseUrl({
  286. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: "https://example.test/native-search/",
  287. }),
  288. ).toBe("https://example.test/native-search");
  289. expect(
  290. resolveNativeSearchRipgrepDownloadBaseUrl({
  291. NATIVE_SEARCH_RIPGREP_DOWNLOAD_BASE_URL: "https://example.test/ripgrep/",
  292. }),
  293. ).toBe("https://example.test/ripgrep");
  294. expect(
  295. resolveNativeSearchRipgrepDownloadBaseUrl({
  296. ZCODE_DEPS_BASE_URL: "https://deps.example.test/zcode/deps/",
  297. }),
  298. ).toBe("https://deps.example.test/zcode/deps/native-search-tools/ripgrep-v14.1.1-1");
  299. });
  300. it("producer 按下载契约生成稳定的 tar.gz 与 Windows zip", async () => {
  301. const root = mkdtempSync(join(tmpdir(), "zcode-native-search-package-test-"));
  302. try {
  303. for (const [platform, arch] of [
  304. ["darwin", "arm64"],
  305. ["win32", "arm64"],
  306. ["win32", "x64"],
  307. ] as const) {
  308. const prebuiltPlan = resolveNativeSearchPrebuiltPlan({
  309. platform,
  310. arch,
  311. outputDir: join(root, "binaries", `${platform}-${arch}`),
  312. });
  313. const producerArtifacts = prebuiltPlan.artifacts.filter(
  314. ({ source }) => source === "producer",
  315. );
  316. for (const artifact of producerArtifacts) {
  317. mkdirSync(dirname(artifact.binaryPath), { recursive: true });
  318. writeFileSync(artifact.binaryPath, `${platform}-${arch}-${artifact.toolId}`);
  319. chmodSync(artifact.binaryPath, 0o755);
  320. }
  321. const firstOutput = join(root, "first");
  322. const secondOutput = join(root, "second");
  323. await packNativeSearchPrebuiltArtifacts({ prebuiltPlan, artifactsDir: firstOutput });
  324. await packNativeSearchPrebuiltArtifacts({ prebuiltPlan, artifactsDir: secondOutput });
  325. for (const artifact of producerArtifacts) {
  326. const relativeArchivePath = join(
  327. "native-search-tools",
  328. `${artifact.toolId}-${artifact.release}`,
  329. artifact.releaseFileName,
  330. );
  331. const digest = (base: string) =>
  332. createHash("sha256")
  333. .update(readFileSync(join(base, relativeArchivePath)))
  334. .digest("hex");
  335. expect(digest(firstOutput)).toBe(digest(secondOutput));
  336. }
  337. for (const artifact of prebuiltPlan.artifacts.filter(
  338. ({ source }) => source === "official",
  339. )) {
  340. expect(() =>
  341. readFileSync(
  342. join(
  343. firstOutput,
  344. "native-search-tools",
  345. `${artifact.toolId}-${artifact.release}`,
  346. artifact.releaseFileName,
  347. ),
  348. ),
  349. ).toThrow();
  350. }
  351. }
  352. } finally {
  353. rmSync(root, { force: true, recursive: true });
  354. }
  355. });
  356. it("producer 可以生成候选归档,固定摘要由发布边界校验", async () => {
  357. const root = mkdtempSync(join(tmpdir(), "zcode-native-search-unpinned-release-test-"));
  358. try {
  359. const prebuiltPlan = resolveNativeSearchPrebuiltPlan({
  360. platform: "linux",
  361. arch: "x64",
  362. outputDir: join(root, "binaries"),
  363. });
  364. for (const artifact of prebuiltPlan.artifacts.filter(({ source }) => source === "producer")) {
  365. mkdirSync(dirname(artifact.binaryPath), { recursive: true });
  366. writeFileSync(artifact.binaryPath, `not-the-published-${artifact.toolId}`);
  367. chmodSync(artifact.binaryPath, 0o755);
  368. }
  369. const artifactsDir = join(root, "artifacts");
  370. await expect(
  371. packNativeSearchPrebuiltArtifacts({ prebuiltPlan, artifactsDir }),
  372. ).resolves.toBeUndefined();
  373. for (const artifact of prebuiltPlan.artifacts.filter(({ source }) => source === "producer")) {
  374. const archivePath = resolveNativeSearchPackagedArtifactPath({ artifact, artifactsDir });
  375. expect(readFileSync(archivePath).byteLength).toBeGreaterThan(0);
  376. expect(sha256(archivePath)).not.toBe(artifact.archiveSha256);
  377. }
  378. } finally {
  379. rmSync(root, { force: true, recursive: true });
  380. }
  381. });
  382. it("Windows zip producer 在不同时区生成相同字节", () => {
  383. const root = mkdtempSync(join(tmpdir(), "zcode-native-search-zip-timezone-test-"));
  384. try {
  385. const prebuiltPlan = resolveNativeSearchPrebuiltPlan({
  386. platform: "win32",
  387. arch: "x64",
  388. outputDir: join(root, "binaries"),
  389. });
  390. const producerArtifacts = prebuiltPlan.artifacts.filter(
  391. ({ source }) => source === "producer",
  392. );
  393. for (const artifact of producerArtifacts) {
  394. mkdirSync(dirname(artifact.binaryPath), { recursive: true });
  395. writeFileSync(artifact.binaryPath, `win32-x64-${artifact.toolId}`);
  396. }
  397. const utcOutput = join(root, "utc");
  398. const shanghaiOutput = join(root, "shanghai");
  399. packageNativeSearchInTimezone(prebuiltPlan, utcOutput, "UTC");
  400. packageNativeSearchInTimezone(prebuiltPlan, shanghaiOutput, "Asia/Shanghai");
  401. for (const artifact of producerArtifacts) {
  402. const relativeArchivePath = join(
  403. "native-search-tools",
  404. `${artifact.toolId}-${artifact.release}`,
  405. artifact.releaseFileName,
  406. );
  407. expect(sha256(join(utcOutput, relativeArchivePath))).toBe(
  408. sha256(join(shanghaiOutput, relativeArchivePath)),
  409. );
  410. }
  411. } finally {
  412. rmSync(root, { force: true, recursive: true });
  413. }
  414. });
  415. it("各目标只下载 producer 实际需要的锁定源码", () => {
  416. const versionsFor = (platform: "darwin" | "linux" | "win32", arch: "arm64" | "x64") =>
  417. Object.fromEntries(
  418. getNativeSearchSourceArchivesForTarget({ platform, arch })
  419. .filter(({ id }) => id in NATIVE_SEARCH_TOOL_VERSIONS)
  420. .map(({ id, version }) => [id, version]),
  421. );
  422. const unixProducerVersions = {
  423. bfs: NATIVE_SEARCH_TOOL_VERSIONS.bfs,
  424. ugrep: NATIVE_SEARCH_TOOL_VERSIONS.ugrep,
  425. };
  426. expect(versionsFor("darwin", "arm64")).toEqual(unixProducerVersions);
  427. expect(versionsFor("darwin", "x64")).toEqual(unixProducerVersions);
  428. expect(versionsFor("linux", "arm64")).toEqual(unixProducerVersions);
  429. expect(versionsFor("linux", "x64")).toEqual(unixProducerVersions);
  430. expect(versionsFor("win32", "arm64")).toEqual({
  431. ugrep: NATIVE_SEARCH_TOOL_VERSIONS.ugrep,
  432. });
  433. expect(versionsFor("win32", "x64")).toEqual({
  434. ugrep: NATIVE_SEARCH_TOOL_VERSIONS.ugrep,
  435. });
  436. });
  437. it("按编译平台分支固定 ugrep 的 PCRE2 feature contract", () => {
  438. expect(getExpectedUgrepFeatureContract("darwin")).toBe(
  439. "; -P:pcre2; -z:zlib,bzip2,zstd,brotli,7z,tar/pax/cpio/zip",
  440. );
  441. expect(getExpectedUgrepFeatureContract("linux")).toBe(
  442. "; -P:pcre2jit; -z:zlib,bzip2,zstd,brotli,7z,tar/pax/cpio/zip",
  443. );
  444. expect(getExpectedUgrepFeatureContract("win32")).toBe(
  445. "; -P:pcre2jit; -z:zlib,bzip2,zstd,brotli,7z,tar/pax/cpio/zip",
  446. );
  447. });
  448. it("区分最终 runtime 工具与各目标 producer 输出", () => {
  449. expect(getNativeSearchRuntimeToolIdsForPlatform("darwin")).toEqual(["bfs", "ugrep", "ripgrep"]);
  450. expect(getNativeSearchRuntimeToolIdsForPlatform("linux")).toEqual(["bfs", "ugrep", "ripgrep"]);
  451. expect(getNativeSearchRuntimeToolIdsForPlatform("win32")).toEqual(["ugrep", "ripgrep"]);
  452. for (const platform of ["darwin", "linux"] as const) {
  453. for (const arch of ["arm64", "x64"] as const) {
  454. expect(getNativeSearchProducerOutputIds({ platform, arch })).toEqual(["bfs", "ugrep"]);
  455. }
  456. }
  457. for (const arch of ["arm64", "x64"] as const) {
  458. expect(getNativeSearchProducerOutputIds({ platform: "win32", arch })).toEqual(["ugrep"]);
  459. }
  460. });
  461. it("只为已经完成 E2E 的 platform-arch 启用 desktop release", () => {
  462. expect(resolveNativeSearchReleasePlan({ platform: "darwin", arch: "arm64" })).toMatchObject({
  463. enabled: true,
  464. runtimeToolIds: ["bfs", "ugrep", "ripgrep"],
  465. extraResourceToolIds: ["bfs", "ugrep"],
  466. });
  467. expect(resolveNativeSearchReleasePlan({ platform: "darwin", arch: "x64" })).toMatchObject({
  468. enabled: true,
  469. runtimeToolIds: ["bfs", "ugrep", "ripgrep"],
  470. extraResourceToolIds: ["bfs", "ugrep"],
  471. });
  472. for (const arch of ["arm64", "x64"]) {
  473. expect(resolveNativeSearchReleasePlan({ platform: "linux", arch })).toMatchObject({
  474. enabled: true,
  475. runtimeToolIds: ["bfs", "ugrep", "ripgrep"],
  476. extraResourceToolIds: ["bfs", "ugrep"],
  477. });
  478. }
  479. for (const arch of ["arm64", "x64"] as const) {
  480. expect(resolveNativeSearchReleasePlan({ platform: "win32", arch })).toMatchObject({
  481. enabled: true,
  482. runtimeToolIds: ["ugrep", "ripgrep"],
  483. extraResourceToolIds: ["ugrep"],
  484. });
  485. }
  486. });
  487. it("source plan 不下载官方 rg 或目标不需要的 Unix-only 源码", () => {
  488. expect(
  489. getNativeSearchSourceArchivesForTarget({ platform: "darwin", arch: "arm64" }).map(
  490. ({ id }) => id,
  491. ),
  492. ).toEqual(["bfs", "ugrep", "oniguruma", "pcre2", "zlib", "bzip2", "zstd", "brotli"]);
  493. expect(
  494. getNativeSearchSourceArchivesForTarget({ platform: "win32", arch: "x64" }).map(
  495. ({ id }) => id,
  496. ),
  497. ).toEqual(["ugrep", "pcre2", "zlib", "bzip2", "zstd", "brotli"]);
  498. expect(
  499. getNativeSearchSourceArchivesForTarget({ platform: "win32", arch: "arm64" }).map(
  500. ({ id }) => id,
  501. ),
  502. ).toEqual(["ugrep", "pcre2", "zlib", "bzip2", "zstd", "brotli"]);
  503. for (const platform of ["darwin", "linux"] as const) {
  504. for (const arch of ["arm64", "x64"] as const) {
  505. expect(
  506. getNativeSearchSourceArchivesForTarget({ platform, arch }).map(({ id }) => id),
  507. ).not.toContain("ripgrep");
  508. }
  509. }
  510. });
  511. it.each([
  512. ["darwin", "arm64", "bfs", "bfs"],
  513. ["darwin", "x64", "ugrep", "ugrep"],
  514. ["linux", "arm64", "bfs", "bfs"],
  515. ["linux", "x64", "ugrep", "ugrep"],
  516. ["darwin", "arm64", "ripgrep", "rg"],
  517. ["linux", "x64", "ripgrep", "rg"],
  518. ["win32", "arm64", "ugrep", "ugrep.exe"],
  519. ["win32", "arm64", "ripgrep", "rg.exe"],
  520. ["win32", "x64", "ugrep", "ugrep.exe"],
  521. ["win32", "x64", "ripgrep", "rg.exe"],
  522. ] as const)("为 %s-%s 生成 %s sidecar 路径", (platform, arch, toolId, binaryName) => {
  523. const outputDir = join(tmpdir(), `zcode-native-search-${platform}-${arch}`);
  524. const plan = resolveNativeSearchBuildPlan({ platform, arch, outputDir });
  525. expect(plan.platformKey).toBe(`${platform}-${arch}`);
  526. expect(plan.binaries[toolId]).toBe(join(outputDir, toolId, binaryName));
  527. expect(plan.bfsPath).toBe(platform === "win32" ? undefined : join(outputDir, "bfs", "bfs"));
  528. });
  529. it("为 Darwin 和 Linux 提供各自的平台构建 flags", () => {
  530. const darwin = resolveNativeUnixBuildConfig({
  531. platform: "darwin",
  532. arch: "arm64",
  533. hostPlatform: "darwin",
  534. hostArch: "arm64",
  535. env: {},
  536. });
  537. expect(darwin.cc).toBe("clang");
  538. expect(darwin.cxx).toBe("clang++");
  539. expect(darwin.brotliOsDefine).toBe("OS_MACOSX");
  540. expect(darwin.bfsCppFlags).toEqual([
  541. "-Dposix_spawn_file_actions_addfchdir=__bfs_poison_addfchdir_macos_26_0",
  542. "-Dfdclosedir=__bfs_poison_fdclosedir_macos_26_4",
  543. ]);
  544. expect(NATIVE_SEARCH_BFS_CONFIGURE_ARGS).toEqual([
  545. "--enable-release",
  546. "--with-oniguruma",
  547. "--without-libselinux",
  548. "--without-libacl",
  549. "--without-liburing",
  550. "--without-libcap",
  551. ]);
  552. expect(darwin.pcre2ConfigureArgs).toEqual(["--disable-jit"]);
  553. expect(darwin.targetCompilerArgs).toEqual(["-arch", "arm64"]);
  554. expect(darwin.ugrepLdFlags).toEqual(["-Wl,-x"]);
  555. expect(darwin.usesRosettaCrossBuild).toBe(false);
  556. expect(darwin.cargoTargetTriple).toBeUndefined();
  557. expect(darwin.macosDeploymentTarget).toBe(MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET);
  558. const darwinX64 = resolveNativeUnixBuildConfig({
  559. platform: "darwin",
  560. arch: "x64",
  561. hostPlatform: "darwin",
  562. hostArch: "arm64",
  563. env: {},
  564. });
  565. expect(darwinX64.targetCompilerArgs).toEqual(["-arch", "x86_64"]);
  566. expect(darwinX64.ugrepConfigureArgs).toEqual(["--host=x86_64-apple-darwin", "--disable-avx2"]);
  567. expect(darwinX64.usesRosettaCrossBuild).toBe(true);
  568. expect(darwinX64.cargoTargetTriple).toBeUndefined();
  569. expect(darwinX64.macosDeploymentTarget).toBe(MACOS_NATIVE_SEARCH_DEPLOYMENT_TARGET);
  570. const linux = resolveNativeUnixBuildConfig({
  571. platform: "linux",
  572. arch: "x64",
  573. hostPlatform: "linux",
  574. hostArch: "x64",
  575. env: {},
  576. });
  577. expect(linux.cc).toBe("gcc");
  578. expect(linux.cxx).toBe("g++");
  579. expect(linux.brotliOsDefine).toBe("OS_LINUX");
  580. expect(linux.bfsCppFlags).toEqual([]);
  581. expect(linux.pcre2ConfigureArgs).toEqual(["--enable-jit", "--with-pic"]);
  582. expect(linux.ugrepConfigureArgs).toEqual(["--disable-avx2"]);
  583. expect(linux.ugrepLdFlags).toEqual(["-Wl,-x", "-static-libgcc", "-static-libstdc++"]);
  584. expect(linux.macosDeploymentTarget).toBeUndefined();
  585. });
  586. it("bfs 构建 flags 不记录随机临时目录", () => {
  587. const sourcePath = "/tmp/zcode-native-search-build-random/sources/bfs";
  588. const prefix = "/tmp/zcode-native-search-build-random/prefix";
  589. const config = resolveNativeUnixBuildConfig({
  590. platform: "darwin",
  591. arch: "arm64",
  592. hostPlatform: "darwin",
  593. hostArch: "arm64",
  594. env: {},
  595. });
  596. const env = createBfsBuildEnvironment({ sourcePath, prefix, env: {}, config });
  597. // Bugfix:createBfsBuildEnvironment 用宿主 path.relative 算出 prefix 的相对路径,
  598. // Windows 上是 `..\..\prefix\include`,而这里原来写死 POSIX 字面量,两条断言在
  599. // Windows 上都对不上。用宿主 join 组装期望片段,断言仍然表达同一个「相对 prefix 布局」。
  600. expect(env.EXTRA_CPPFLAGS).toContain(`-I${join("../../prefix/include")}`);
  601. expect(env.EXTRA_LDFLAGS).toBe(`-L${join("../../prefix/lib")}`);
  602. expect(env.EXTRA_LDLIBS).toBe("-lonig");
  603. expect(env.PKG_CONFIG).toBe("true");
  604. expect(env.VERSION).toBe("4.1.1");
  605. expect(Object.values(env).join(" ")).not.toContain("zcode-native-search-build-random");
  606. });
  607. it("Linux verifier 应拒绝 bfs/ugrep 动态依赖 C++ runtime", () => {
  608. const forbiddenCppDependencies = [
  609. "libc++.so.1",
  610. "libc++abi.so.1",
  611. "libgcc_s.so.1",
  612. "libstdc++.so.6",
  613. ];
  614. for (const arch of ["x64", "arm64"] as const) {
  615. const bfsDependencies = getAllowedLinuxNativeSearchDependencies("bfs", arch);
  616. const ugrepDependencies = getAllowedLinuxNativeSearchDependencies("ugrep", arch);
  617. for (const dependency of forbiddenCppDependencies) {
  618. expect(bfsDependencies).not.toContain(dependency);
  619. expect(ugrepDependencies).not.toContain(dependency);
  620. }
  621. expect(getAllowedLinuxNativeSearchDependencies("ripgrep", arch)).toEqual([]);
  622. }
  623. expect(getAllowedLinuxNativeSearchDependencies("bfs", "x64")).toContain("ld-linux-x86-64.so.2");
  624. expect(getAllowedLinuxNativeSearchDependencies("bfs", "arm64")).toContain(
  625. "ld-linux-aarch64.so.1",
  626. );
  627. });
  628. it("Linux producer 按实际 Node、glibc、CC 与 CXX 能力放行", () => {
  629. expect(() =>
  630. assertLinuxNativeSearchBuildEnvironment({
  631. nodeVersion: "24.14.0",
  632. glibcVersion: "2.28",
  633. gccVersion: "12.2.1",
  634. cxxVersion: "12.2.1",
  635. }),
  636. ).not.toThrow();
  637. expect(() =>
  638. assertLinuxNativeSearchBuildEnvironment({
  639. nodeVersion: "22.16.0",
  640. glibcVersion: "2.28",
  641. gccVersion: "12.2.1",
  642. cxxVersion: "12.2.1",
  643. }),
  644. ).toThrow("Node 24");
  645. expect(() =>
  646. assertLinuxNativeSearchBuildEnvironment({
  647. nodeVersion: "24.14.0",
  648. glibcVersion: "2.36",
  649. gccVersion: "12.2.1",
  650. cxxVersion: "12.2.1",
  651. }),
  652. ).toThrow("glibc 2.28");
  653. expect(() =>
  654. assertLinuxNativeSearchBuildEnvironment({
  655. nodeVersion: "24.14.0",
  656. glibcVersion: "2.28",
  657. gccVersion: "8.5.0",
  658. cxxVersion: "12.2.1",
  659. }),
  660. ).toThrow("GCC 12");
  661. expect(() =>
  662. assertLinuxNativeSearchBuildEnvironment({
  663. nodeVersion: "24.14.0",
  664. glibcVersion: "2.28",
  665. gccVersion: "12.2.1",
  666. cxxVersion: "13.2.1",
  667. }),
  668. ).toThrow("G++ 12");
  669. });
  670. it("Linux ABI gate 接受 GLIBC_2.28 ceiling 并拒绝更高 symbol version", () => {
  671. const versionInfo = [
  672. " 0x0010: Name: GLIBC_2.2.5 Flags: none Version: 5",
  673. " 0x0020: Name: GLIBC_2.17 Flags: none Version: 4",
  674. " 0x0030: Name: GLIBC_2.28 Flags: none Version: 3",
  675. " 0x0040: Name: GLIBCXX_3.4.21 Flags: none Version: 2",
  676. ].join("\n");
  677. expect(getRequiredGlibcVersions(versionInfo)).toEqual(["2.2.5", "2.17", "2.28"]);
  678. expect(() => verifyLinuxGlibcBaseline(versionInfo, "bfs")).not.toThrow();
  679. expect(() => verifyLinuxGlibcBaseline(`${versionInfo}\nName: GLIBC_2.29`, "ugrep")).toThrow(
  680. "GLIBC_2.29",
  681. );
  682. expect(() => verifyLinuxGlibcBaseline("Version symbols section", "bfs")).toThrow(
  683. "missing GLIBC symbol versions",
  684. );
  685. });
  686. it("macOS verifier 接受更低 deployment target 且拒绝提高系统下限", () => {
  687. expect(() =>
  688. verifyMacosDeploymentTarget("cmd LC_BUILD_VERSION\n minos 11.0\n", "rg-arm64", {
  689. allowLowerDeploymentTarget: true,
  690. }),
  691. ).not.toThrow();
  692. expect(() =>
  693. verifyMacosDeploymentTarget(
  694. "cmd LC_VERSION_MIN_MACOSX\ncmdsize 16\nversion 10.12\nsdk 15.5\n",
  695. "rg-x64",
  696. { allowLowerDeploymentTarget: true },
  697. ),
  698. ).not.toThrow();
  699. expect(() =>
  700. verifyMacosDeploymentTarget("cmd LC_BUILD_VERSION\n minos 12.0\n", "bfs"),
  701. ).not.toThrow();
  702. expect(() =>
  703. verifyMacosDeploymentTarget("cmd LC_BUILD_VERSION\n minos 11.0\n", "lower-bfs"),
  704. ).toThrow("expected target is 12.0");
  705. expect(() =>
  706. verifyMacosDeploymentTarget("cmd LC_BUILD_VERSION\n minos 13.0\n", "future-rg", {
  707. allowLowerDeploymentTarget: true,
  708. }),
  709. ).toThrow("maximum supported target is 12.0");
  710. });
  711. it("拒绝 Windows Unix build 和未经验证的 Unix 跨架构构建", () => {
  712. expect(() =>
  713. resolveNativeUnixBuildConfig({
  714. platform: "win32",
  715. arch: "x64",
  716. hostPlatform: "win32",
  717. hostArch: "x64",
  718. }),
  719. ).toThrow("does not support platform win32");
  720. expect(() =>
  721. resolveNativeUnixBuildConfig({
  722. platform: "darwin",
  723. arch: "arm64",
  724. hostPlatform: "darwin",
  725. hostArch: "x64",
  726. }),
  727. ).toThrow("must run natively for darwin-arm64");
  728. });
  729. it("Windows producer 复用 MSVC/CMake 支持 x64 与 ARM64 target 并固定 UTF-8 编译契约", () => {
  730. const x64Config = resolveNativeWindowsBuildConfig({
  731. platform: "win32",
  732. arch: "x64",
  733. hostPlatform: "win32",
  734. hostArch: "x64",
  735. env: {},
  736. });
  737. expect(x64Config).toMatchObject({
  738. arch: "x64",
  739. cmake: "cmake",
  740. generator: "Visual Studio 17 2022",
  741. generatorArchitecture: "x64",
  742. platform: "win32",
  743. });
  744. const arm64Config = resolveNativeWindowsBuildConfig({
  745. platform: "win32",
  746. arch: "arm64",
  747. hostPlatform: "win32",
  748. hostArch: "x64",
  749. env: {},
  750. });
  751. expect(arm64Config).toMatchObject({
  752. arch: "arm64",
  753. generatorArchitecture: "ARM64",
  754. platform: "win32",
  755. });
  756. expect(x64Config).not.toHaveProperty("cargo");
  757. expect(arm64Config).not.toHaveProperty("cargo");
  758. expect(windowsNativeSearchCmake).toMatch(
  759. /target_compile_options\(zcode_ugrep_contract INTERFACE[\s\S]*?\/utf-8[\s\S]*?\n\)/,
  760. );
  761. expect(() =>
  762. resolveNativeWindowsBuildConfig({
  763. platform: "win32",
  764. arch: "x64",
  765. hostPlatform: "linux",
  766. hostArch: "x64",
  767. }),
  768. ).toThrow("must run on Windows");
  769. });
  770. it("Windows verifier 读取 PE machine/import table 并拒绝动态 CRT", () => {
  771. const root = mkdtempSync(join(tmpdir(), "zcode-native-search-pe-test-"));
  772. try {
  773. const validPath = join(root, "valid-ugrep.exe");
  774. const validArm64Path = join(root, "valid-arm64-ugrep.exe");
  775. const invalidPath = join(root, "invalid-ugrep.exe");
  776. const invalidThirdPartyPath = join(root, "invalid-third-party-ugrep.exe");
  777. writeFileSync(validPath, createPeFixture(0x8664, "KERNEL32.dll"));
  778. writeFileSync(validArm64Path, createPeFixture(0xaa64, "KERNEL32.dll"));
  779. writeFileSync(invalidPath, createPeFixture(0x8664, "api-ms-win-crt-runtime-l1-1-0.dll"));
  780. writeFileSync(invalidThirdPartyPath, createPeFixture(0x8664, "libpcre2-8-0.dll"));
  781. expect(readWindowsPeMetadata(validPath)).toEqual({
  782. imports: ["KERNEL32.dll"],
  783. machine: 0x8664,
  784. });
  785. expect(readWindowsPeMetadata(validArm64Path)).toEqual({
  786. imports: ["KERNEL32.dll"],
  787. machine: 0xaa64,
  788. });
  789. expect(() =>
  790. verifyBuiltNativeSearchProducerOutputs({
  791. ugrepPath: validPath,
  792. platform: "win32",
  793. arch: "x64",
  794. hostArch: "x64",
  795. hostPlatform: "linux",
  796. producerOutputIds: ["ugrep"],
  797. }),
  798. ).not.toThrow();
  799. expect(() =>
  800. verifyBuiltNativeSearchProducerOutputs({
  801. ugrepPath: validArm64Path,
  802. platform: "win32",
  803. arch: "arm64",
  804. hostArch: "arm64",
  805. hostPlatform: "linux",
  806. producerOutputIds: ["ugrep"],
  807. }),
  808. ).not.toThrow();
  809. expect(() =>
  810. verifyBuiltNativeSearchTools({
  811. ugrepPath: validPath,
  812. rgPath: validPath,
  813. platform: "win32",
  814. arch: "x64",
  815. hostArch: "x64",
  816. hostPlatform: "linux",
  817. }),
  818. ).not.toThrow();
  819. expect(() =>
  820. verifyBuiltNativeSearchTools({
  821. ugrepPath: invalidPath,
  822. rgPath: validPath,
  823. platform: "win32",
  824. arch: "x64",
  825. hostArch: "x64",
  826. hostPlatform: "linux",
  827. }),
  828. ).toThrow("non-static runtime dependencies: api-ms-win-crt-runtime-l1-1-0.dll");
  829. expect(() =>
  830. verifyBuiltNativeSearchTools({
  831. ugrepPath: invalidThirdPartyPath,
  832. rgPath: validPath,
  833. platform: "win32",
  834. arch: "x64",
  835. hostArch: "x64",
  836. hostPlatform: "linux",
  837. }),
  838. ).toThrow("non-static runtime dependencies: libpcre2-8-0.dll");
  839. } finally {
  840. rmSync(root, { force: true, recursive: true });
  841. }
  842. });
  843. it("下载侧静态 verifier 应按 Mach-O、ELF 与 PE header 拒绝错误目标架构", () => {
  844. const root = mkdtempSync(join(tmpdir(), "zcode-native-search-target-verifier-test-"));
  845. try {
  846. const machoPath = join(root, "darwin-arm64");
  847. const elfPath = join(root, "linux-x64");
  848. const pePath = join(root, "win32-x64.exe");
  849. writeFileSync(machoPath, createMachOFixture(0x0100000c));
  850. writeFileSync(elfPath, createElfFixture(0x3e));
  851. writeFileSync(pePath, createPeFixture(0x8664, "KERNEL32.dll"));
  852. expect(() =>
  853. verifyNativeSearchBinaryTarget(machoPath, { platform: "darwin", arch: "arm64" }),
  854. ).not.toThrow();
  855. expect(() =>
  856. verifyNativeSearchBinaryTarget(machoPath, { platform: "darwin", arch: "x64" }),
  857. ).toThrow("expected 0x1000007 for x64");
  858. expect(() =>
  859. verifyNativeSearchBinaryTarget(elfPath, { platform: "linux", arch: "x64" }),
  860. ).not.toThrow();
  861. expect(() =>
  862. verifyNativeSearchBinaryTarget(elfPath, { platform: "linux", arch: "arm64" }),
  863. ).toThrow("expected 0xb7 for arm64");
  864. expect(() =>
  865. verifyNativeSearchBinaryTarget(pePath, { platform: "win32", arch: "x64" }),
  866. ).not.toThrow();
  867. expect(() =>
  868. verifyNativeSearchBinaryTarget(pePath, { platform: "win32", arch: "arm64" }),
  869. ).toThrow("expected 0xaa64 for arm64");
  870. } finally {
  871. rmSync(root, { force: true, recursive: true });
  872. }
  873. });
  874. });
  875. function sha256(path: string): string {
  876. return createHash("sha256").update(readFileSync(path)).digest("hex");
  877. }
  878. function packageNativeSearchInTimezone(
  879. prebuiltPlan: ReturnType<typeof resolveNativeSearchPrebuiltPlan>,
  880. artifactsDir: string,
  881. timezone: string,
  882. ): void {
  883. const packageScriptUrl = pathToFileURL(
  884. join(import.meta.dirname, "../../../scripts/package-native-search-tools.mjs"),
  885. ).href;
  886. const script = `
  887. import { packNativeSearchPrebuiltArtifacts } from ${JSON.stringify(packageScriptUrl)};
  888. await packNativeSearchPrebuiltArtifacts(${JSON.stringify({ prebuiltPlan, artifactsDir })});
  889. `;
  890. const result = spawnSync(process.execPath, ["--input-type=module", "--eval", script], {
  891. encoding: "utf8",
  892. env: { ...process.env, TZ: timezone },
  893. });
  894. if (result.status !== 0) {
  895. throw new Error(`timezone package failed (${timezone}):\n${result.stderr || result.stdout}`);
  896. }
  897. }
  898. function createMachOFixture(cpuType: number): Buffer {
  899. const buffer = Buffer.alloc(32);
  900. buffer.writeUInt32LE(0xfeedfacf, 0);
  901. buffer.writeUInt32LE(cpuType, 4);
  902. buffer.writeUInt32LE(2, 12);
  903. return buffer;
  904. }
  905. function createElfFixture(machine: number): Buffer {
  906. const buffer = Buffer.alloc(64);
  907. buffer.write("\x7fELF", 0, "binary");
  908. buffer[4] = 2;
  909. buffer[5] = 1;
  910. buffer.writeUInt16LE(3, 16);
  911. buffer.writeUInt16LE(machine, 18);
  912. return buffer;
  913. }
  914. function createPeFixture(machine: number, dependency: string): Buffer {
  915. const buffer = Buffer.alloc(1024);
  916. const peOffset = 0x80;
  917. const optionalHeaderOffset = peOffset + 24;
  918. const optionalHeaderSize = 0xf0;
  919. const sectionTableOffset = optionalHeaderOffset + optionalHeaderSize;
  920. const sectionRva = 0x1000;
  921. const sectionRawOffset = 0x200;
  922. buffer.write("MZ", 0, "ascii");
  923. buffer.writeUInt32LE(peOffset, 0x3c);
  924. buffer.write("PE\0\0", peOffset, "ascii");
  925. buffer.writeUInt16LE(machine, peOffset + 4);
  926. buffer.writeUInt16LE(1, peOffset + 6);
  927. buffer.writeUInt16LE(optionalHeaderSize, peOffset + 20);
  928. buffer.writeUInt16LE(0x20b, optionalHeaderOffset);
  929. buffer.writeUInt32LE(sectionRva, optionalHeaderOffset + 112 + 8);
  930. buffer.writeUInt32LE(40, optionalHeaderOffset + 112 + 12);
  931. buffer.writeUInt32LE(0x200, sectionTableOffset + 8);
  932. buffer.writeUInt32LE(sectionRva, sectionTableOffset + 12);
  933. buffer.writeUInt32LE(0x200, sectionTableOffset + 16);
  934. buffer.writeUInt32LE(sectionRawOffset, sectionTableOffset + 20);
  935. buffer.writeUInt32LE(sectionRva + 0x40, sectionRawOffset + 12);
  936. buffer.writeUInt32LE(sectionRva + 0x60, sectionRawOffset + 16);
  937. buffer.write(`${dependency}\0`, sectionRawOffset + 0x40, "ascii");
  938. return buffer;
  939. }