e2e-chromedriver-server.mjs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { spawn } from "node:child_process";
  2. import { createWriteStream } from "node:fs";
  3. import { mkdir } from "node:fs/promises";
  4. import { dirname } from "node:path";
  5. import { Browser, computeExecutablePath, detectBrowserPlatform } from "@puppeteer/browsers";
  6. import { electronToChromium } from "electron-to-chromium";
  7. export function resolveE2EChromedriverExecutable({ electronVersion, cacheDir, explicitPath }) {
  8. if (explicitPath) return explicitPath;
  9. const buildId = electronToChromium(electronVersion);
  10. if (!buildId) throw new Error(`Chromium mapping missing for Electron ${electronVersion}`);
  11. // WDIO launcher 已按该版本准备驱动;容器的兼容补丁由预取入口通过 explicitPath 提供。
  12. return computeExecutablePath({
  13. browser: Browser.CHROMEDRIVER,
  14. buildId,
  15. platform: detectBrowserPlatform(),
  16. cacheDir,
  17. });
  18. }
  19. /** 驱动自己持有系统分配的端口,避免探测后释放、实际绑定前被其它连接占用。 */
  20. export async function startE2EChromedriverServer({
  21. executablePath,
  22. prefixArgs = [],
  23. logPath,
  24. timeoutMs = 30_000,
  25. }) {
  26. await mkdir(dirname(logPath), { recursive: true });
  27. const log = createWriteStream(logPath);
  28. const child = spawn(
  29. executablePath,
  30. [...prefixArgs, "--port=0", "--allowed-ips=127.0.0.1", "--allowed-origins=*"],
  31. { env: { ...process.env, NODE_OPTIONS: "" }, stdio: ["ignore", "pipe", "pipe"] },
  32. );
  33. let exited = false;
  34. let output = "";
  35. let stopping;
  36. const killOnWorkerExit = () => child.kill();
  37. process.once("exit", killOnWorkerExit);
  38. const closed = new Promise((resolve) => {
  39. child.once("close", () => {
  40. exited = true;
  41. process.removeListener("exit", killOnWorkerExit);
  42. log.end(resolve);
  43. });
  44. });
  45. const stop = () => {
  46. stopping ??= (async () => {
  47. if (!exited) child.kill();
  48. const deadline = setTimeout(() => {
  49. if (!exited) child.kill("SIGKILL");
  50. }, 5_000);
  51. try {
  52. await closed;
  53. } finally {
  54. clearTimeout(deadline);
  55. }
  56. })();
  57. return stopping;
  58. };
  59. try {
  60. const port = await new Promise((resolve, reject) => {
  61. const deadline = setTimeout(
  62. () => finish(new Error(`ChromeDriver startup timed out; ${output.slice(-2000)}`)),
  63. timeoutMs,
  64. );
  65. let settled = false;
  66. function finish(error, actualPort) {
  67. if (settled) return;
  68. settled = true;
  69. clearTimeout(deadline);
  70. if (error) reject(error);
  71. else resolve(actualPort);
  72. }
  73. const capture = (chunk) => {
  74. log.write(chunk);
  75. output = (output + chunk.toString()).slice(-16_384);
  76. const ready = output.match(/ChromeDriver was started successfully on port (\d+)\./u);
  77. if (ready) {
  78. const actualPort = Number(ready[1]);
  79. if (actualPort > 0 && actualPort <= 65_535) finish(null, actualPort);
  80. else finish(new Error(`ChromeDriver reported invalid port ${ready[1]}`));
  81. }
  82. };
  83. child.stdout.on("data", capture);
  84. child.stderr.on("data", capture);
  85. child.once("error", (error) => finish(error));
  86. child.once("close", (code, signal) =>
  87. finish(new Error(`ChromeDriver exited before ready (${code}/${signal}); ${output}`)),
  88. );
  89. });
  90. return { hostname: "127.0.0.1", port, stop };
  91. } catch (error) {
  92. await stop();
  93. throw error;
  94. }
  95. }