"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 streamingFetcher = async (args) => {
    const headers = {};
    if (args.body !== undefined) {
        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,
            transitional: {
                clarifyTimeoutError: true,
            },
            withCredentials: args.withCredentials,
            signal: args.abortController?.signal,
            responseType: "stream",
            adapter: args.adapter,
        });
    }
    catch (error) {
        args.onError?.(error);
        return;
    }
    if (args.onData != null) {
        const { onData } = args;
        response.data.on("data", (data) => {
            for (const line of data.toString().split("\n")) {
                let data = line;
                if (!data.startsWith("data: ")) {
                    continue;
                }
                data = data.substring(6);
                try {
                    const parsed = JSON.parse(data);
                    onData(parsed);
                }
                catch (error) {
                    args.onError?.(error);
                }
            }
        });
    }
    if (args.onFinish != null) {
        response.data.on("end", args.onFinish);
    }
    return response.data;
};
exports.streamingFetcher = streamingFetcher;
