// DOM Parser polyfill  ---
import { root } from "@hpcc-js/util";
import { DOMParser } from "@xmldom/xmldom";
root.DOMParser = DOMParser;

//  fetch setup for Node.js ---
import * as https from "node:https";
import { Buffer } from "node:buffer";
import { fetch, Agent } from "undici";

//  NodeJS >= v18 has native fetch  ---
if (root.fetch === undefined) {
    throw new Error("@hpcc-js/comms requires Node.js >= 18.0.0 for native fetch support");
}
root.__hpcc_undiciFetch = fetch;
root.__hpcc_rejectUnauthorizedAgent = new Agent({
    connect: {
        rejectUnauthorized: false
    }
});

import { trustwave } from "./pem/trustwave.ts";

let globalCA = "";
if (https.globalAgent.options.ca !== undefined) {
    if (Array.isArray(https.globalAgent.options.ca) && https.globalAgent.options.ca.length) {
        if (typeof https.globalAgent.options.ca[0] === "string") {
            globalCA = https.globalAgent.options.ca.join("\n");
        } else if (https.globalAgent.options.ca[0] instanceof Buffer) {
            globalCA = https.globalAgent.options.ca.map(row => row.toString()).join("\n");
        }
    } else if (typeof https.globalAgent.options.ca === "string") {
        globalCA = https.globalAgent.options.ca;
    } else if (https.globalAgent.options.ca instanceof Buffer) {
        globalCA = https.globalAgent.options.ca.toString();
    }
    globalCA += "\n";
}

root.__hpcc_trustwaveAgent = new https.Agent({
    ca: globalCA + trustwave
});

export * from "./index.common.ts";

//  Client Tools  ---
export * from "./clienttools/eclcc.ts";
export * from "./clienttools/eclMeta.ts";
