"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchResponseToStreamEvents = fetchResponseToStreamEvents;
const tslib_1 = require("tslib");
const SSE_DATA_PREFIX = 'data: ';
function parseSSELine(line) {
    try {
        return JSON.parse(line.slice(SSE_DATA_PREFIX.length));
    }
    catch (_a) {
        return null;
    }
}
/** Fetch Response (text/event-stream) → AsyncIterable of stream events. Handles [DONE], errors; 4xx/5xx yield error. */
function fetchResponseToStreamEvents(response) {
    return tslib_1.__asyncGenerator(this, arguments, function* fetchResponseToStreamEvents_1() {
        var _a, _b;
        if (response.ok === false) {
            const message = response.statusText || (response.status ? `HTTP ${response.status}` : 'HTTP error');
            yield yield tslib_1.__await({ type: 'error', error: message });
            return yield tslib_1.__await(void 0);
        }
        const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();
        if (!reader) {
            return yield tslib_1.__await(void 0);
        }
        const decoder = new TextDecoder();
        let buffer = '';
        try {
            while (true) {
                const { done, value } = yield tslib_1.__await(reader.read());
                if (done) {
                    break;
                }
                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = (_b = lines.pop()) !== null && _b !== void 0 ? _b : '';
                for (const line of lines) {
                    const trimmed = line.trim();
                    if (trimmed === `${SSE_DATA_PREFIX}[DONE]`) {
                        yield yield tslib_1.__await({ type: 'response.done' });
                        continue;
                    }
                    if (!trimmed.startsWith(SSE_DATA_PREFIX)) {
                        continue;
                    }
                    const parsed = parseSSELine(trimmed);
                    if (!parsed) {
                        continue;
                    }
                    if (parsed.error) {
                        yield yield tslib_1.__await({
                            type: 'error',
                            error: parsed.error,
                        });
                        return yield tslib_1.__await(void 0);
                    }
                    yield yield tslib_1.__await(parsed);
                }
            }
            yield yield tslib_1.__await({ type: 'response.done' });
        }
        finally {
            reader.releaseLock();
        }
    });
}
//# sourceMappingURL=fetchResponseToStreamEvents.js.map
