builtin-provider-config-build.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import assert from "node:assert/strict";
  2. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, resolve } from "node:path";
  5. import { createRequire } from "node:module";
  6. import { pathToFileURL } from "node:url";
  7. import test from "node:test";
  8. import { execFile } from "node:child_process";
  9. import { promisify } from "node:util";
  10. import { build } from "esbuild";
  11. import {
  12. loadBuiltinProviderConfig,
  13. resolveBuiltinProviderBuildEnvironment,
  14. stageBuiltinProviderConfig,
  15. } from "../builtin-provider-config.mjs";
  16. import { buildCli } from "../../apps/zcode-cli/packages/cli/scripts/build.mjs";
  17. import {
  18. collectSeaProviderConfigAssets,
  19. SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY,
  20. } from "../../apps/zcode-cli/packages/cli/scripts/sea-provider-config-assets.mjs";
  21. const repositoryRoot = resolve(import.meta.dirname, "../..");
  22. const productionFile = "config/provider/zcode-builtin.json";
  23. const testFile = "config/provider/zcode-builtin.test.json";
  24. const baseline = JSON.parse(await readFile(resolve(repositoryRoot, productionFile), "utf8"));
  25. test("both environments load the decoder through a portable file URL", async () => {
  26. // 在独立进程中检查真实入口传给 tsx 的参数,让非 Windows CI 也能捕获盘符路径回归。
  27. await promisify(execFile)(
  28. process.execPath,
  29. [
  30. "--experimental-test-module-mocks",
  31. "--input-type=module",
  32. "-e",
  33. `
  34. import assert from "node:assert/strict";
  35. import { mock } from "node:test";
  36. import { tsImport } from "tsx/esm/api";
  37. let calls = 0;
  38. mock.module("tsx/esm/api", { namedExports: {
  39. tsImport: async (specifier, parent) => {
  40. assert.equal(new URL(specifier).protocol, "file:");
  41. calls++;
  42. return tsImport(specifier, parent);
  43. },
  44. }});
  45. const { loadBuiltinProviderConfig } = await import("./scripts/builtin-provider-config.mjs");
  46. for (const environment of ["production", "test"]) {
  47. await loadBuiltinProviderConfig({ env: { ZCODE_ENV: environment } });
  48. }
  49. assert.equal(calls, 2);
  50. `,
  51. ],
  52. { cwd: repositoryRoot },
  53. );
  54. });
  55. async function fixture(t) {
  56. const root = await mkdtemp(resolve(tmpdir(), "zcode-builtin-build-"));
  57. t.after(() => rm(root, { recursive: true, force: true }));
  58. await mkdir(resolve(root, "config/provider"), { recursive: true });
  59. await writeFile(resolve(root, productionFile), JSON.stringify({ ...baseline, revision: 101 }));
  60. await writeFile(resolve(root, testFile), JSON.stringify({ ...baseline, revision: 202 }));
  61. return root;
  62. }
  63. for (const [environment, file, revision] of [
  64. ["test", testFile, 202],
  65. ["production", productionFile, 101],
  66. ]) {
  67. test(`${environment} selects and stages only its own validated release`, async (t) => {
  68. const root = await fixture(t);
  69. const directory = resolve(root, "dist/provider");
  70. const result = await stageBuiltinProviderConfig({
  71. root,
  72. directory,
  73. env: { ZCODE_ENV: environment, NODE_ENV: "production" },
  74. });
  75. assert.equal(result.environment, environment);
  76. assert.equal(result.sourcePath, resolve(root, file));
  77. assert.equal(
  78. JSON.parse(await readFile(resolve(directory, "zcode-builtin.json"), "utf8")).revision,
  79. revision,
  80. );
  81. const assets = await collectSeaProviderConfigAssets({ root, env: { ZCODE_ENV: environment } });
  82. assert.equal(assets[SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY], resolve(root, file));
  83. });
  84. test(`${environment} CLI bundle and its adjacent resource agree`, async (t) => {
  85. const root = await fixture(t);
  86. const rootDirectory = resolve(root, "apps/zcode-cli");
  87. const cliDirectory = resolve(rootDirectory, "packages/cli");
  88. await mkdir(resolve(cliDirectory, "src"), { recursive: true });
  89. await writeFile(resolve(cliDirectory, "src/main.ts"), "console.log('fixture CLI');");
  90. // CLI 构建会把仓库根声明作为伴随文件复制到 dist;缺失时构建应失败而不是生成空声明。
  91. await writeFile(resolve(root, "THIRD-PARTY-NOTICES.md"), "fixture notices\n");
  92. await buildCli({
  93. rootDirectory,
  94. cliDirectory,
  95. version: "1.0.0",
  96. sourcemap: false,
  97. env: { ZCODE_ENV: environment },
  98. });
  99. assert.match(await readFile(resolve(cliDirectory, "dist/zcode.cjs"), "utf8"), /fixture CLI/);
  100. assert.equal(
  101. await readFile(resolve(cliDirectory, "dist/THIRD-PARTY-NOTICES.md"), "utf8"),
  102. "fixture notices\n",
  103. );
  104. assert.equal(
  105. JSON.parse(await readFile(resolve(cliDirectory, "dist/provider/zcode-builtin.json"), "utf8"))
  106. .revision,
  107. revision,
  108. );
  109. });
  110. }
  111. test("environment precedence is explicit env > env files > test; NODE_ENV alone is not production", async (t) => {
  112. const root = await fixture(t);
  113. assert.equal(
  114. await resolveBuiltinProviderBuildEnvironment({ root, env: { NODE_ENV: "production" } }),
  115. "test",
  116. );
  117. await writeFile(resolve(root, ".env"), "ZCODE_ENV=production\n");
  118. assert.equal(await resolveBuiltinProviderBuildEnvironment({ root, env: {} }), "production");
  119. await writeFile(resolve(root, ".env.production"), "ZCODE_ENV=test\n");
  120. assert.equal(
  121. await resolveBuiltinProviderBuildEnvironment({ root, env: { NODE_ENV: "production" } }),
  122. "test",
  123. );
  124. assert.equal(
  125. await resolveBuiltinProviderBuildEnvironment({
  126. root,
  127. env: { ZCODE_ENV: " production ", NODE_ENV: "production" },
  128. }),
  129. "production",
  130. );
  131. await assert.rejects(
  132. loadBuiltinProviderConfig({ root, env: { ZCODE_ENV: "staging" } }),
  133. /ZCODE_ENV/,
  134. );
  135. });
  136. test("reused JS still gets fresh config after switching environment or updating the same environment", async (t) => {
  137. const root = await fixture(t);
  138. const directory = resolve(root, "dist/provider");
  139. await mkdir(resolve(root, "dist"));
  140. const js = resolve(root, "dist/zcode.cjs");
  141. await writeFile(js, "existing CLI JS");
  142. for (const [environment, revision] of [
  143. ["production", 101],
  144. ["test", 202],
  145. ["test", 203],
  146. ]) {
  147. if (revision === 203)
  148. await writeFile(resolve(root, testFile), JSON.stringify({ ...baseline, revision }));
  149. await stageBuiltinProviderConfig({ root, directory, env: { ZCODE_ENV: environment } });
  150. assert.equal(
  151. JSON.parse(await readFile(resolve(directory, "zcode-builtin.json"), "utf8")).revision,
  152. revision,
  153. );
  154. assert.equal(await readFile(js, "utf8"), "existing CLI JS");
  155. }
  156. });
  157. for (const invalid of [null, "{broken", "{}", JSON.stringify({ ...baseline, config: {} })]) {
  158. test(`invalid selected config fails without falling back (${invalid ?? "missing"})`, async (t) => {
  159. const root = await fixture(t);
  160. if (invalid === null) await rm(resolve(root, testFile));
  161. else await writeFile(resolve(root, testFile), invalid);
  162. await assert.rejects(
  163. loadBuiltinProviderConfig({ root, env: { ZCODE_ENV: "test" } }),
  164. /zcode-builtin.test.json/,
  165. );
  166. await assert.rejects(collectSeaProviderConfigAssets({ root, env: { ZCODE_ENV: "test" } }));
  167. assert.equal(
  168. JSON.parse(
  169. (await loadBuiltinProviderConfig({ root, env: { ZCODE_ENV: "production" } })).content,
  170. ).revision,
  171. 101,
  172. );
  173. });
  174. }
  175. test("both repository configurations pass the runtime release decoder", async () => {
  176. for (const environment of ["test", "production"]) {
  177. assert.ok(
  178. (await loadBuiltinProviderConfig({ root: repositoryRoot, env: { ZCODE_ENV: environment } }))
  179. .content.length > 0,
  180. );
  181. }
  182. });
  183. test("Turbo and bootstrap include the out-of-workspace configuration inputs", async () => {
  184. const turbo = JSON.parse(
  185. await readFile(resolve(repositoryRoot, "apps/zcode-cli/turbo.json"), "utf8"),
  186. );
  187. for (const taskName of ["@zcode/cli#build", "build:desktop-agent"]) {
  188. const task = turbo.tasks[taskName];
  189. assert.ok(task.env.includes("ZCODE_ENV"));
  190. assert.ok(task.env.includes("NODE_ENV"));
  191. for (const input of [
  192. productionFile,
  193. testFile,
  194. "scripts/builtin-provider-config.mjs",
  195. "packages/provider/src/**",
  196. "packages/provider-node/src/zcode-builtin-release.ts",
  197. ]) {
  198. assert.ok(task.inputs.includes(`$TURBO_ROOT$/../../${input}`), `${taskName}: ${input}`);
  199. }
  200. }
  201. const bootstrap = await readFile(
  202. resolve(repositoryRoot, "scripts/build-desktop-agent-cli.mjs"),
  203. "utf8",
  204. );
  205. assert.match(bootstrap, /await stageBuiltinProviderConfig\(/);
  206. });
  207. test("real tsup config bundling retains helper location and embeds selected release", async (t) => {
  208. const originalEnvironment = process.env.ZCODE_ENV;
  209. t.after(() => {
  210. if (originalEnvironment === undefined) delete process.env.ZCODE_ENV;
  211. else process.env.ZCODE_ENV = originalEnvironment;
  212. });
  213. // 使用 tsup 自己依赖的配置加载器,覆盖其先 bundle 配置文件再执行的真实路径。
  214. const { bundleRequire } = createRequire(import.meta.resolve("tsup"))("bundle-require");
  215. for (const environment of ["test", "production"]) {
  216. process.env.ZCODE_ENV = environment;
  217. const expected = await loadBuiltinProviderConfig();
  218. for (const packageName of ["server", "zcode-server-cli", "desktop"]) {
  219. const filepath = resolve(repositoryRoot, "packages", packageName, "tsup.config.ts");
  220. const { mod } = await bundleRequire({ filepath, cwd: dirname(filepath), format: "esm" });
  221. if (packageName === "desktop") {
  222. assert.equal(JSON.parse(mod.default[0].define.__ZCODE_ENV__), environment);
  223. continue;
  224. }
  225. const defines = mod.SERVER_HTTP_DEFINES ?? mod.SERVER_CLI_DEFINES;
  226. const result = await build({
  227. stdin: { contents: "export default __ZCODE_BUILTIN_PROVIDER_CONFIG_JSON__;" },
  228. define: defines,
  229. write: false,
  230. format: "esm",
  231. });
  232. const { default: embedded } = await import(
  233. `data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString("base64")}`
  234. );
  235. assert.equal(embedded, expected.content);
  236. }
  237. const { default: builder } = await import(
  238. `${pathToFileURL(resolve(repositoryRoot, "packages/desktop/electron-builder.config.js")).href}?env=${environment}`
  239. );
  240. const resource = builder.extraResources.find(
  241. (entry) => entry.to === "config/provider/zcode-builtin.json",
  242. );
  243. assert.equal(resource.from, expected.sourcePath);
  244. }
  245. });