"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    checkPort: function() {
        return checkPort;
    },
    scanPortRange: function() {
        return scanPortRange;
    }
});
const _net = /*#__PURE__*/ _interop_require_default(require("net"));
const _cluster = /*#__PURE__*/ _interop_require_default(require("cluster"));
const _os = require("os");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const numCPUs = (0, _os.cpus)().length;
const commonServices = {
    80: "HTTP",
    443: "HTTPS",
    22: "SSH",
    21: "FTP",
    3306: "MySQL",
    5432: "PostgreSQL",
    27017: "MongoDB",
    6379: "Redis",
    8080: "HTTP-Alternate",
    8443: "HTTPS-Alternate"
};
async function checkPort(host, port) {
    console.log("Worker defined " + host + ":" + port);
    return new Promise((resolve)=>{
        const socket = new _net.default.Socket();
        const timeout = 1000;
        socket.setTimeout(timeout);
        socket.on("connect", ()=>{
            socket.destroy();
            resolve({
                port,
                status: "open",
                service: commonServices[port]
            });
        });
        socket.on("timeout", ()=>{
            socket.destroy();
            resolve({
                port,
                status: "closed"
            });
        });
        socket.on("error", ()=>{
            socket.destroy();
            resolve({
                port,
                status: "closed"
            });
        });
        socket.connect(port, host);
    });
}
async function scanPortRange(host, start, end, specificPorts = []) {
    const portsToScan = [
        ...Array.from({
            length: end - start + 1
        }, (_, i)=>start + i),
        ...specificPorts
    ].filter((value, index, self)=>self.indexOf(value) === index);
    const chunkSize = Math.ceil(portsToScan.length / numCPUs);
    const chunks = Array.from({
        length: numCPUs
    }, (_, i)=>portsToScan.slice(i * chunkSize, (i + 1) * chunkSize));
    if (_cluster.default.isPrimary) {
        console.log(`Primary ${process.pid} is running`);
        console.log(`Starting scan on ${host} for ports ${start}-${end} and specific ports: ${specificPorts.join(", ")}`);
        console.log(`Number of CPU cores: ${numCPUs}`);
        const results = [];
        const workers = new Set();
        _cluster.default.on("exit", (worker, code, signal)=>{
            console.log(`Worker ${worker.process.pid} died. Signal: ${signal}. Code: ${code}`);
            workers.delete(worker);
            if (workers.size === 0) {
                console.log("All workers completed");
                process.emit("allWorkersCompleted", results);
            }
        });
        return new Promise((resolve, reject)=>{
            const timeout = setTimeout(()=>{
                for (const worker of workers){
                    worker.kill();
                }
                reject(new Error("Scan timeout after 30 seconds"));
            }, 30000);
            process.once("allWorkersCompleted", (finalResults)=>{
                clearTimeout(timeout);
                resolve(finalResults.sort((a, b)=>a.port - b.port));
            });
            chunks.forEach((chunk, index)=>{
                try {
                    const worker = _cluster.default.fork();
                    workers.add(worker);
                    console.log(`Created worker ${worker.process.pid} for chunk ${index + 1}/${chunks.length}`);
                    worker.on("message", (msg)=>{
                        console.log(`Received results from worker ${worker.process.pid}: ${msg.length} ports`);
                        results.push(...msg);
                    });
                    worker.on("error", (error)=>{
                        console.error(`Worker ${worker.process.pid} error:`, error);
                    });
                    worker.send({
                        host,
                        ports: chunk
                    });
                } catch (error) {
                    console.error("Error creating worker:", error);
                }
            });
        });
    } else {
        console.log(`Worker ${process.pid} started`);
        return new Promise((resolve)=>{
            process.on("message", async (msg)=>{
                try {
                    console.log(`Worker ${process.pid} received ${msg.ports.length} ports to scan`);
                    const results = [];
                    const promises = msg.ports.map((port)=>checkPort(msg.host, port));
                    const workerResults = await Promise.all(promises);
                    results.push(...workerResults);
                    if (process.send) {
                        process.send(results);
                        console.log(`Worker ${process.pid} completed scanning`);
                    }
                    process.exit(0);
                } catch (error) {
                    console.error(`Worker ${process.pid} error:`, error);
                    process.exit(1);
                }
            });
        });
    }
}
if (require.main === module) {
    const host = process.argv[2] || "localhost";
    scanPortRange(host, 80, 8888, [
        27017
    ]).then((results)=>{
        console.log("\nScan Results:");
        const openPorts = results.filter((r)=>r.status === "open");
        if (openPorts.length === 0) {
            console.log("No open ports found");
        } else {
            console.table(openPorts);
        }
        process.exit(0);
    }).catch((error)=>{
        console.error("Error during scan:", error);
        process.exit(1);
    });
}

//# sourceMappingURL=check-ports.js.map