import { networkInterfaces } from "node:os";
export function toAttachMobileUrl(apiUrl) {
    const url = new URL(apiUrl);
    url.pathname = "/";
    return url.toString();
}
export function createAttachUrlInfo(apiUrl, label = "API") {
    return { apiUrl, mobileUrl: toAttachMobileUrl(apiUrl), label };
}
export function getLanIpv4Addresses(provider = networkInterfaces) {
    const addresses = new Set();
    for (const entries of Object.values(provider())) {
        for (const entry of entries ?? []) {
            if (entry.internal || entry.family !== "IPv4")
                continue;
            if (!isLikelyLanIpv4(entry.address))
                continue;
            addresses.add(entry.address);
        }
    }
    return [...addresses].sort(compareIpv4);
}
export function createAttachUrlAlternatives(apiUrl, configuredHost, provider) {
    const primary = createAttachUrlInfo(apiUrl, "Configured");
    const alternatives = [primary];
    if (configuredHost !== "0.0.0.0" && configuredHost !== "::")
        return alternatives;
    const url = new URL(apiUrl);
    for (const address of getLanIpv4Addresses(provider)) {
        url.hostname = address;
        alternatives.push(createAttachUrlInfo(url.toString(), "LAN"));
    }
    return alternatives;
}
function isLikelyLanIpv4(address) {
    return address.startsWith("10.") || address.startsWith("192.168.") || /^172\.(1[6-9]|2\d|3[01])\./.test(address);
}
function compareIpv4(a, b) {
    const ap = a.split(".").map(Number);
    const bp = b.split(".").map(Number);
    for (let i = 0; i < 4; i++) {
        const diff = (ap[i] ?? 0) - (bp[i] ?? 0);
        if (diff !== 0)
            return diff;
    }
    return 0;
}
//# sourceMappingURL=attach-urls.js.map