"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = require("./config");
const util_http_1 = require("./util-http");
const util_os_1 = require("./util-os");
const const_1 = require("./const");
const cross_1 = require("./cross");
const outboundProxy = (0, config_1.defineConfig)(cross_1.CFG.outbound_proxy, '', v => {
    if (!v)
        return;
    try {
        (0, util_http_1.parseHttpUrl)(v); // just validate
        util_http_1.httpStream.defaultProxy = v;
        if (!v || process.env.HFS_SKIP_PROXY_TEST)
            return;
        const test = 'https://google.com';
        console.debug("Testing proxy using", test);
        (0, util_http_1.httpString)(test, { noRedirect: true }).catch(e => console.error(`Proxy test failed on ${test} : ${e?.errors?.[0] || e}`)); // `.errors` in case of AggregateError
    }
    catch {
        console.warn("Invalid URL", v);
        return '';
    }
});
config_1.configReady.then(async (startedWithoutConfig) => {
    if (!const_1.IS_WINDOWS || !startedWithoutConfig)
        return;
    // try to read Windows system setting for proxy
    const out = await (0, util_os_1.reg)('query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings');
    if (!Number(/ProxyEnable\s+\w+\s+(.+)/.exec(out)?.[1]))
        return;
    const read = /ProxyServer\s+\w+\s+(.+)/.exec(out)?.[1];
    if (!read)
        return;
    // it can be like "IP:PORT" or "http=IP:PORT;https=IP:PORT;ftp=IP:PORT"
    const url = (0, cross_1.prefix)('https://', /https=([\d:.]+)/.exec(out)?.[1]) // prefer https
        || (0, cross_1.prefix)('http://', /http=([\d:.]+)/.exec(out)?.[1])
        || !read.includes('=') && 'http://' + read; // simpler form
    if (!url)
        return;
    outboundProxy.set(url);
    console.log("Detected proxy", read);
});
