|
| 1 | +const http = require("http"); |
| 2 | +const net = require("net"); |
| 3 | +const path = require("path"); |
| 4 | +const { spawn, spawnSync } = require("child_process"); |
| 5 | + |
| 6 | +const repoRoot = path.resolve(__dirname, "..", ".."); |
| 7 | +const frontendDir = path.join(repoRoot, "frontend"); |
| 8 | +const desktopDir = path.join(repoRoot, "desktop"); |
| 9 | + |
| 10 | +function parsePort(value) { |
| 11 | + const n = Number.parseInt(String(value || "").trim(), 10); |
| 12 | + return Number.isInteger(n) && n >= 1 && n <= 65535 ? n : null; |
| 13 | +} |
| 14 | + |
| 15 | +function log(message) { |
| 16 | + process.stdout.write(`[dev] ${message}\n`); |
| 17 | +} |
| 18 | + |
| 19 | +function prefixPipe(stream, prefix) { |
| 20 | + if (!stream) return; |
| 21 | + let pending = ""; |
| 22 | + stream.setEncoding("utf8"); |
| 23 | + stream.on("data", (chunk) => { |
| 24 | + pending += chunk; |
| 25 | + const lines = pending.split(/\r?\n/); |
| 26 | + pending = lines.pop() || ""; |
| 27 | + for (const line of lines) { |
| 28 | + process.stdout.write(`${prefix} ${line}\n`); |
| 29 | + } |
| 30 | + }); |
| 31 | + stream.on("end", () => { |
| 32 | + const tail = pending.trim(); |
| 33 | + if (tail) process.stdout.write(`${prefix} ${tail}\n`); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +function isPortAvailable(port, host) { |
| 38 | + return new Promise((resolve) => { |
| 39 | + const server = net.createServer(); |
| 40 | + const done = (ok) => { |
| 41 | + try { |
| 42 | + server.close(); |
| 43 | + } catch {} |
| 44 | + resolve(ok); |
| 45 | + }; |
| 46 | + server.once("error", () => done(false)); |
| 47 | + server.once("listening", () => done(true)); |
| 48 | + server.listen(port, host); |
| 49 | + }); |
| 50 | +} |
| 51 | + |
| 52 | +async function choosePort({ label, envName, preferredPort, host, searchLimit = 20 }) { |
| 53 | + if (preferredPort != null) { |
| 54 | + const ok = await isPortAvailable(preferredPort, host); |
| 55 | + if (!ok) throw new Error(`${label}端口 ${preferredPort} 已被占用,请修改环境变量 ${envName}`); |
| 56 | + return preferredPort; |
| 57 | + } |
| 58 | + |
| 59 | + const startPort = envName === "NUXT_PORT" ? 3000 : 10392; |
| 60 | + for (let port = startPort; port <= startPort + searchLimit; port += 1) { |
| 61 | + if (await isPortAvailable(port, host)) return port; |
| 62 | + } |
| 63 | + throw new Error(`未找到可用的${label}端口(起始 ${startPort})`); |
| 64 | +} |
| 65 | + |
| 66 | +function httpReady(url) { |
| 67 | + return new Promise((resolve) => { |
| 68 | + const req = http.get(url, (res) => { |
| 69 | + res.resume(); |
| 70 | + resolve(true); |
| 71 | + }); |
| 72 | + req.on("error", () => resolve(false)); |
| 73 | + req.setTimeout(1000, () => { |
| 74 | + req.destroy(); |
| 75 | + resolve(false); |
| 76 | + }); |
| 77 | + }); |
| 78 | +} |
| 79 | + |
| 80 | +async function waitForUrl(url, child, timeoutMs) { |
| 81 | + const startedAt = Date.now(); |
| 82 | + while (Date.now() - startedAt < timeoutMs) { |
| 83 | + if (child.exitCode != null) { |
| 84 | + throw new Error(`前端进程提前退出,exitCode=${child.exitCode}`); |
| 85 | + } |
| 86 | + if (await httpReady(url)) return; |
| 87 | + await new Promise((resolve) => setTimeout(resolve, 300)); |
| 88 | + } |
| 89 | + throw new Error(`等待前端启动超时:${url}`); |
| 90 | +} |
| 91 | + |
| 92 | +function killChild(child) { |
| 93 | + if (!child || child.killed || child.exitCode != null) return; |
| 94 | + if (process.platform === "win32") { |
| 95 | + spawnSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore" }); |
| 96 | + return; |
| 97 | + } |
| 98 | + try { |
| 99 | + child.kill("SIGTERM"); |
| 100 | + } catch {} |
| 101 | +} |
| 102 | + |
| 103 | +function spawnLogged(command, args, options, prefix) { |
| 104 | + const child = spawn(command, args, { |
| 105 | + ...options, |
| 106 | + shell: process.platform === "win32", |
| 107 | + stdio: ["inherit", "pipe", "pipe"], |
| 108 | + }); |
| 109 | + prefixPipe(child.stdout, `${prefix}`); |
| 110 | + prefixPipe(child.stderr, `${prefix}`); |
| 111 | + return child; |
| 112 | +} |
| 113 | + |
| 114 | +async function main() { |
| 115 | + const frontendHost = String(process.env.NUXT_HOST || "127.0.0.1").trim() || "127.0.0.1"; |
| 116 | + const requestedFrontendPort = parsePort(process.env.NUXT_PORT); |
| 117 | + const requestedBackendPort = parsePort(process.env.WECHAT_TOOL_PORT); |
| 118 | + const frontendPort = await choosePort({ |
| 119 | + label: "前端", |
| 120 | + envName: "NUXT_PORT", |
| 121 | + preferredPort: requestedFrontendPort, |
| 122 | + host: frontendHost, |
| 123 | + }); |
| 124 | + const backendPort = await choosePort({ |
| 125 | + label: "后端", |
| 126 | + envName: "WECHAT_TOOL_PORT", |
| 127 | + preferredPort: requestedBackendPort, |
| 128 | + host: "127.0.0.1", |
| 129 | + }); |
| 130 | + const startUrl = `http://${frontendHost}:${frontendPort}`; |
| 131 | + |
| 132 | + log(`frontend=${startUrl}`); |
| 133 | + log(`backend=http://127.0.0.1:${backendPort}/api`); |
| 134 | + |
| 135 | + const sharedEnv = { |
| 136 | + ...process.env, |
| 137 | + NUXT_HOST: frontendHost, |
| 138 | + NUXT_PORT: String(frontendPort), |
| 139 | + WECHAT_TOOL_PORT: String(backendPort), |
| 140 | + ELECTRON_START_URL: startUrl, |
| 141 | + }; |
| 142 | + |
| 143 | + const npmCommand = "npm"; |
| 144 | + const electronCommand = "electron"; |
| 145 | + const children = new Set(); |
| 146 | + let shuttingDown = false; |
| 147 | + |
| 148 | + const shutdown = (exitCode) => { |
| 149 | + if (shuttingDown) return; |
| 150 | + shuttingDown = true; |
| 151 | + for (const child of children) killChild(child); |
| 152 | + process.exitCode = exitCode; |
| 153 | + }; |
| 154 | + |
| 155 | + process.on("SIGINT", () => shutdown(130)); |
| 156 | + process.on("SIGTERM", () => shutdown(143)); |
| 157 | + |
| 158 | + const frontend = spawnLogged(npmCommand, ["run", "dev"], { cwd: frontendDir, env: sharedEnv }, "[frontend]"); |
| 159 | + children.add(frontend); |
| 160 | + frontend.once("exit", (code, signal) => { |
| 161 | + log(`frontend exited code=${code} signal=${signal}`); |
| 162 | + shutdown(code == null ? 1 : code); |
| 163 | + }); |
| 164 | + |
| 165 | + await waitForUrl(startUrl, frontend, 60_000); |
| 166 | + log("frontend is ready, starting Electron"); |
| 167 | + |
| 168 | + const electron = spawnLogged(electronCommand, ["."], { cwd: desktopDir, env: sharedEnv }, "[electron]"); |
| 169 | + children.add(electron); |
| 170 | + electron.once("exit", (code, signal) => { |
| 171 | + log(`electron exited code=${code} signal=${signal}`); |
| 172 | + shutdown(code == null ? 0 : code); |
| 173 | + }); |
| 174 | +} |
| 175 | + |
| 176 | +main().catch((err) => { |
| 177 | + process.stderr.write(`[dev] ${err?.stack || err}\n`); |
| 178 | + process.exit(1); |
| 179 | +}); |
0 commit comments