"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetSystemCACache = resetSystemCACache;
exports.mergeCA = mergeCA;
exports.systemCA = systemCA;
const system_ca_1 = require("system-ca");
const fs_1 = require("fs");
const tls_1 = require("tls");
let systemCertsCachePromise;
function resetSystemCACache(systemCAOpts = {}) {
    systemCertsCachePromise = undefined;
    systemCertsCached(systemCAOpts).catch(() => undefined);
}
function systemCertsCached(systemCAOpts = {}) {
    if (systemCertsCachePromise)
        return systemCertsCachePromise;
    systemCertsCachePromise = (async () => {
        const certs = await (0, system_ca_1.systemCertsAsync)(systemCAOpts);
        return { certs, asyncFallbackError: systemCAOpts.asyncFallbackError };
    })();
    systemCertsCachePromise.catch(() => {
    });
    return systemCertsCachePromise;
}
function certToString(cert) {
    return typeof cert === 'string'
        ? cert
        : Buffer.from(cert.buffer, cert.byteOffset, cert.byteLength).toString('utf8');
}
function mergeCA(...args) {
    const ca = new Set();
    for (const item of args) {
        if (!item)
            continue;
        const caList = Array.isArray(item) ? item : [item];
        for (const cert of caList) {
            ca.add(certToString(cert));
        }
    }
    return [...ca].join('\n');
}
async function systemCA(existingOptions = {}) {
    let readTLSCAFilePromise;
    if (existingOptions.tlsCAFile) {
        readTLSCAFilePromise = fs_1.promises.readFile(existingOptions.tlsCAFile, 'utf8');
        readTLSCAFilePromise.catch(() => {
        });
    }
    let systemCertsError;
    let asyncFallbackError;
    let systemCerts = [];
    const messages = [];
    try {
        if (!existingOptions.excludeSystemCerts) {
            const systemCertsResult = await systemCertsCached();
            asyncFallbackError = systemCertsResult.asyncFallbackError;
            systemCerts = systemCertsResult.certs;
        }
    }
    catch (err) {
        systemCertsError = err;
    }
    return {
        ca: mergeCA(systemCerts, tls_1.rootCertificates, existingOptions.ca, await readTLSCAFilePromise),
        asyncFallbackError: asyncFallbackError,
        systemCertsError,
        systemCACount: systemCerts.length + tls_1.rootCertificates.length,
        messages,
    };
}
//# sourceMappingURL=system-ca.js.map