"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.syncFetch = syncFetch;
const node_worker_threads_1 = require("node:worker_threads");
const node_path_1 = require("node:path");
function syncFetch(url, options = {}, customOptions = {
    timeout: 30000
}) {
    const timeout = customOptions.timeout || 30000;
    const processingBuffer = 3000;
    const mainThreadTimeout = timeout + processingBuffer;
    const { port1, port2 } = new node_worker_threads_1.MessageChannel();
    const sleepBuffer = new SharedArrayBuffer(4);
    const sleepArray = new Int32Array(sleepBuffer);
    const worker = new node_worker_threads_1.Worker((0, node_path_1.join)(__dirname, 'sync-fetch-worker.mjs'), {
        name: 'sync-fetch',
        eval: false,
        workerData: {
            url,
            options,
            timeout,
            port: port2
        },
        transferList: [port2]
    });
    const { startTime } = performance.mark('axe-watcher:sync-fetch:start');
    let message;
    try {
        while (message === undefined) {
            if (performance.now() - startTime > mainThreadTimeout) {
                throw new Error(`Request timed out - worker thread did not respond within ${mainThreadTimeout}ms`);
            }
            Atomics.wait(sleepArray, 0, 0, 5);
            message = (0, node_worker_threads_1.receiveMessageOnPort)(port1);
        }
        const { data, error } = message.message;
        if (error) {
            const syncErr = new Error('Sync Fetch Failed');
            syncErr.cause = error;
            throw syncErr;
        }
        return data;
    }
    finally {
        performance.mark('axe-watcher:sync-fetch:end');
        port1.close();
        worker.terminate();
        const clone = structuredClone(options);
        clone.headers = sanitizeHeaders(clone.headers);
        performance.measure('axe-watcher:sync-fetch', {
            start: 'axe-watcher:sync-fetch:start',
            end: 'axe-watcher:sync-fetch:end',
            detail: {
                url,
                options: clone,
                timeout,
                status: message?.message.type || 'no-response',
                response: {
                    status: message?.message.data?.status,
                    statusText: message?.message.data?.statusText
                }
            }
        });
    }
}
function sanitizeHeaders(headers) {
    if (!headers) {
        return undefined;
    }
    const sanitized = {};
    for (const [key, value] of Object.entries(headers)) {
        if (key.toLowerCase() === 'x-api-key'.toLowerCase()) {
            sanitized[key.toLowerCase()] = 'REDACTED';
            continue;
        }
        sanitized[key.toLowerCase()] = value;
    }
    return sanitized;
}
//# sourceMappingURL=sync-fetch.js.map