ensure-electron-runtime.mjs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { spawn } from "node:child_process";
  2. import { access, readFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { dirname, join } from "node:path";
  5. const require = createRequire(import.meta.url);
  6. async function installedBinary(packageRoot) {
  7. try {
  8. const relativePath = (await readFile(join(packageRoot, "path.txt"), "utf8")).trim();
  9. if (!relativePath) return null;
  10. const binary = join(packageRoot, "dist", relativePath);
  11. await access(binary);
  12. return binary;
  13. } catch (error) {
  14. if (error.code === "ENOENT") return null;
  15. throw error;
  16. }
  17. }
  18. function installRuntime(packageRoot) {
  19. return new Promise((resolve, reject) => {
  20. // 新安装入口未配置镜像时会直连 GitHub;仅给安装子进程补既有镜像,避免影响 builder 辅助包下载。
  21. const env = {
  22. ...process.env,
  23. ELECTRON_MIRROR:
  24. process.env.ELECTRON_MIRROR?.trim() || "https://npmmirror.com/mirrors/electron/",
  25. };
  26. const child = spawn(process.execPath, [join(packageRoot, "install.js")], {
  27. cwd: packageRoot,
  28. env,
  29. stdio: "inherit",
  30. windowsHide: true,
  31. });
  32. child.once("error", reject);
  33. child.once("exit", (code, signal) => {
  34. if (code === 0) resolve();
  35. else reject(new Error(`Electron installation failed (${code ?? signal})`));
  36. });
  37. });
  38. }
  39. export async function ensureElectronRuntime({
  40. packageRoot = dirname(require.resolve("electron/package.json")),
  41. installRuntime: install = installRuntime,
  42. } = {}) {
  43. const existing = await installedBinary(packageRoot);
  44. if (existing) return existing;
  45. // Electron 42 起不再 postinstall 下载;dev 直接启动 dist,必须先等待官方安装完成。
  46. await install(packageRoot);
  47. const binary = await installedBinary(packageRoot);
  48. if (!binary) throw new Error("Electron binary unavailable after installation");
  49. return binary;
  50. }