build-remote.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { readFileSync } from "node:fs";
  2. import { build, type Plugin } from "esbuild";
  3. import {
  4. REMOTE_SERVER_NATIVE_EXTERNALS,
  5. validateRemoteServerBundle,
  6. } from "./buildRemoteValidation.js";
  7. import { loadBuiltinProviderConfig } from "../../scripts/builtin-provider-config.mjs";
  8. import { stageThirdPartyNotices } from "../../scripts/third-party-notices.mjs";
  9. const { version, zcodeCompatibility } = JSON.parse(readFileSync("../../package.json", "utf-8")) as {
  10. version: string;
  11. zcodeCompatibility?: { minCompatibleVersion?: string };
  12. };
  13. const minCompatibleVersion = zcodeCompatibility?.minCompatibleVersion ?? version;
  14. const { content: zcodeBuiltinProviderConfigJson } = await loadBuiltinProviderConfig();
  15. /**
  16. * Let esbuild bundle node-pty's JS code normally, but keep .node native
  17. * addon files as external requires. node-pty's loadNativeModule() searches
  18. * for `./build/Release/pty.node` relative to itself, which matches our
  19. * deploy layout on the remote.
  20. *
  21. * CJS 格式而非 ESM:node-pty 内部大量使用 __dirname,ESM 里没有这个变量,
  22. * 用 CJS 输出可以直接原生支持,不需要任何 polyfill。
  23. */
  24. const nativeAddonPlugin: Plugin = {
  25. name: "native-addon",
  26. setup(build) {
  27. // Mark all .node files as external — they can't be bundled
  28. build.onResolve({ filter: /\.node$/ }, (args) => ({
  29. path: args.path,
  30. external: true,
  31. }));
  32. },
  33. };
  34. const buildResult = await build({
  35. entryPoints: ["src/entry-stdio.ts"],
  36. bundle: true,
  37. outfile: "dist/remote/zcode-server.cjs",
  38. platform: "node",
  39. format: "cjs",
  40. target: "node22",
  41. plugins: [nativeAddonPlugin],
  42. external: REMOTE_SERVER_NATIVE_EXTERNALS,
  43. // CJS 环境没有 import.meta.url,通过 banner 注入等价变量,
  44. // 再用 define 全局替换,这样源码无需关心最终打包格式。
  45. banner: {
  46. js: 'var __import_meta_url = require("url").pathToFileURL(__filename).href; var __import_meta_dirname = __dirname;',
  47. },
  48. define: {
  49. "import.meta.url": "__import_meta_url",
  50. "import.meta.dirname": "__import_meta_dirname",
  51. __ZCODE_VERSION__: JSON.stringify(version),
  52. __ZCODE_MIN_COMPATIBLE_VERSION__: JSON.stringify(minCompatibleVersion),
  53. __ZCODE_BUILTIN_PROVIDER_CONFIG_JSON__: JSON.stringify(zcodeBuiltinProviderConfigJson),
  54. },
  55. metafile: true,
  56. });
  57. const remoteBundleSource = readFileSync("dist/remote/zcode-server.cjs", "utf-8");
  58. const bundledInputs = Object.keys(buildResult.metafile.inputs);
  59. validateRemoteServerBundle({ bundledInputs, source: remoteBundleSource });
  60. // 修复:remote 单文件 bundle 内联第三方代码,dist/remote 也必须附完整声明。
  61. await stageThirdPartyNotices("dist/remote");
  62. console.log("Built dist/remote/zcode-server.cjs");