// @ts-ignore - package-info.js is generated
import { PACKAGE_NAME, PACKAGE_VERSION } from './haveibeenpwned/package-info.js';
export async function baseFetch({ baseUrl, endpoint, headers, timeoutMs, signal, userAgent, queryParams, }) {
    const requestInit = {
        headers: buildHeaders(userAgent, headers),
        signal: buildSignal(timeoutMs, signal),
    };
    const url = buildUrl(baseUrl, endpoint, queryParams);
    return fetch(url, requestInit);
}
export function buildUrl(baseUrl, endpoint, queryParams) {
    const base = baseUrl.replace(/\/$/g, '');
    const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
    const url = new URL(`${base}${normalizedEndpoint}`);
    if (queryParams) {
        for (const [key, value] of Object.entries(queryParams)) {
            url.searchParams.set(key, value);
        }
    }
    return url.toString();
}
export function buildHeaders(userAgent, extra) {
    const headers = { ...extra };
    if (userAgent) {
        headers['User-Agent'] = userAgent;
    }
    else if (typeof navigator === 'undefined') {
        headers['User-Agent'] = `${PACKAGE_NAME} ${PACKAGE_VERSION}`;
    }
    return headers;
}
function buildSignal(timeoutMs, signal) {
    const signals = [];
    if (timeoutMs)
        signals.push(AbortSignal.timeout(timeoutMs));
    if (signal)
        signals.push(signal);
    if (signals.length === 0)
        return undefined;
    if (signals.length === 1)
        return signals[0];
    return AbortSignal.any(signals);
}
//# sourceMappingURL=base-fetch.js.map