"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamingFetcher = void 0;
const axios_1 = __importDefault(require("axios"));
const DATA_EVENT_REGEX = /data: (.*)/;
const streamingFetcher = async (args) => {
    const headers = {
        "Content-Type": "application/json",
    };
    if (args.headers != null) {
        for (const [key, value] of Object.entries(args.headers)) {
            if (value != null) {
                headers[key] = value;
            }
        }
    }
    let response;
    try {
        response = await (0, axios_1.default)({
            url: args.url,
            params: args.queryParameters,
            method: args.method,
            headers,
            data: args.body,
            timeout: args.timeoutMs ?? 60_000,
            withCredentials: args.withCredentials,
            signal: args.abortController?.signal,
            responseType: "stream",
            adapter: args.adapter,
        });
    }
    catch (error) {
        args.onError?.(error);
        return;
    }
    response.data.on("data", (data) => {
        for (const line of data.toString().split("\n")) {
            const data = line.match(DATA_EVENT_REGEX)?.[1];
            if (data == null || data === args.terminator) {
                continue;
            }
            try {
                const parsed = JSON.parse(data);
                args.onData(parsed);
            }
            catch (error) {
                args.onError?.(error);
            }
        }
    });
    if (args.onFinish != null) {
        response.data.on("end", args.onFinish);
    }
};
exports.streamingFetcher = streamingFetcher;
