"use strict";
/*
 * Tencent is pleased to support the open source community by making
 * Hippy available.
 *
 * Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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("@debug-server-next/@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();
            }
        }
    }
}
