"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.internalIPSync = exports.internalIP = exports.getAllLocalHostname = void 0;
const tslib_1 = require("tslib");
const os_1 = tslib_1.__importDefault(require("os"));
const ipaddr_js_1 = tslib_1.__importDefault(require("ipaddr.js"));
const default_gateway_1 = tslib_1.__importDefault(require("default-gateway"));
const enum_1 = require("@/@types/enum");
const getAllLocalHostname = async () => {
    const hostV4 = await exports.internalIP(enum_1.GatewayFamily.V4);
    const hostV6 = await exports.internalIP(enum_1.GatewayFamily.V6);
    return [hostV4, hostV6, '127.0.0.1', 'localhost', '0.0.0.0', '::'];
};
exports.getAllLocalHostname = getAllLocalHostname;
const internalIP = async (family) => {
    try {
        const { gateway } = await default_gateway_1.default[family]();
        return findIp(gateway);
    }
    catch {
        // ignore
    }
};
exports.internalIP = internalIP;
const internalIPSync = (family) => {
    try {
        const { gateway } = default_gateway_1.default[family].sync();
        return findIp(gateway);
    }
    catch {
        // ignore
    }
};
exports.internalIPSync = internalIPSync;
function findIp(gateway) {
    const gatewayIp = ipaddr_js_1.default.parse(gateway);
    // Look for the matching interface in all local interfaces.
    for (const addresses of Object.values(os_1.default.networkInterfaces())) {
        for (const { cidr } of addresses) {
            const net = ipaddr_js_1.default.parseCIDR(cidr);
            if (net[0] && net[0].kind() === gatewayIp.kind() && gatewayIp.match(net)) {
                return net[0].toString();
            }
        }
    }
}
