"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findProcessUsingPort = findProcessUsingPort;
exports.killProcess = killProcess;
exports.findAvailablePort = findAvailablePort;
const child_process_1 = require("child_process");
const util_1 = require("util");
const execAsync = (0, util_1.promisify)(child_process_1.exec);
/**
* Find process using a specific port
* @param port - The port to check
* @returns Promise resolving to process ID if found, null otherwise
*/
async function findProcessUsingPort(port) {
try {
// For Windows
if (process.platform === 'win32') {
const { stdout } = await execAsync(`netstat -ano | findstr :${port}`);
// Extract PID from the output
const match = stdout.match(/LISTENING\s+(\d+)/);
if (match && match[1]) {
return parseInt(match[1], 10);
}
}
// For Unix-based systems (Linux, macOS)
else {
const { stdout } = await execAsync(`lsof -i :${port} -t`);
if (stdout.trim()) {
return parseInt(stdout.trim(), 10);
}
}
return null;
}
catch (error) {
// If command failed, assume no process is using this port
return null;
}
}
/**
* Attempt to kill a process by its ID
* @param pid - Process ID to kill
* @returns Promise resolving to boolean indicating if process was killed
*/
async function killProcess(pid) {
try {
if (process.platform === 'win32') {
await execAsync(`taskkill /F /PID ${pid}`);
}
else {
await execAsync(`kill -9 ${pid}`);
}
return true;
}
catch (error) {
console.error(`Failed to kill process ${pid}:`, error instanceof Error ? error.message : String(error));
return false;
}
}
/**
* Find an available port starting from the preferred port
* @param preferredPort - The port to start checking from
* @param maxAttempts - Maximum number of ports to check
* @returns Promise resolving to available port
*/
async function findAvailablePort(preferredPort, maxAttempts = 10) {
let port = preferredPort;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const pid = await findProcessUsingPort(port);
if (!pid) {
return port; // Port is available
}
console.log(`Port ${port} is in use by process ${pid}, trying next port...`);
port++;
}
// If we've tried all ports in range and none are available, return a random port
return preferredPort + Math.floor(Math.random() * 1000) + 1000;
}
//# sourceMappingURL=port.js.map