import { execSync } from "node:child_process"; export const PDS_PORT = 2584; export const PLC_PORT = 2583; export function getPidByPort(port: number): number | null { try { const platform = process.platform; if (platform === "darwin" || platform === "linux") { const result = execSync(`lsof -t -i :${port} | head -n 1`, { encoding: "utf-8", stdio: ["pipe", "pipe", "ignore"], }).trim(); if (result) { const pid = parseInt(result, 10); return Number.isNaN(pid) ? null : pid; } return null; } if (platform === "win32") { const result = execSync(`netstat -ano | findstr :${port}`, { encoding: "utf-8", stdio: ["pipe", "pipe", "ignore"], }); const match = result.match(/PID\s+(\d+)/i); if (match) { const pid = parseInt(match[1], 10); return Number.isNaN(pid) ? null : pid; } return null; } return null; } catch { return null; } } export function killDevNetwork(): number[] { const pids = [ ...new Set([getPidByPort(PDS_PORT), getPidByPort(PLC_PORT)].filter(Boolean)), ] as number[]; if (pids.length === 0) { console.log(" ℹ️ No process found on ports 2583 or 2584"); return pids; } for (const pid of pids) { try { process.kill(pid, "SIGTERM"); console.log(` ✅ Sent SIGTERM to PID ${pid}`); } catch (err) { console.log(` ⚠️ Could not kill PID ${pid}: ${err}`); } } return pids; } export async function waitForDevNetworkStop(pids: number[] = []): Promise { await new Promise((resolve) => setTimeout(resolve, 1000)); const portsToCheck = [PDS_PORT, PLC_PORT]; for (const port of portsToCheck) { const pid = getPidByPort(port); if (pid != null) { try { process.kill(pid, "SIGKILL"); console.log(` ✅ Sent SIGKILL to PID ${pid}`); } catch { // already stopped } } } for (const pid of pids) { try { process.kill(pid, "SIGKILL"); } catch { // already stopped } } } export function startDevNetworkInBackground(): void { const devNetworkCmd = "pnpm run dev:network"; const isUnix = process.platform !== "win32"; if (isUnix) { execSync(`${devNetworkCmd} > .output/dev-network.log 2>&1 &`, { stdio: "inherit", shell: "/bin/sh", }); console.log(" ✅ Dev-network started in background"); console.log(" 📝 Logs: .output/dev-network.log"); return; } execSync(`start cmd /c "${devNetworkCmd}"`, { stdio: "inherit", shell: "cmd.exe", }); console.log(" ✅ Dev-network started in new window"); }