"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponseStream = void 0;
const tslib_1 = require("tslib");
class ResponseStream {
    constructor(stream) {
        this.eventChunkCb = null;
        this.bufferChunkCb = null;
        this.onFinishCb = null;
        this.stream = stream;
    }
    onEventChunk(cb) {
        this.eventChunkCb = cb;
    }
    onBufferChunk(cb) {
        this.bufferChunkCb = cb;
    }
    onFinish(cb) {
        this.onFinishCb = cb;
    }
    async start() {
        var _a, e_1, _b, _c;
        var _d, _e, _f;
        try {
            for (var _g = true, _h = tslib_1.__asyncValues(this.stream), _j; _j = await _h.next(), _a = _j.done, !_a; _g = true) {
                _c = _j.value;
                _g = false;
                const event = _c;
                if (this.stream.controller.signal.aborted) {
                    break;
                }
                const str = 'data: ' + JSON.stringify(event) + '\n\n';
                const buffer = Buffer.from(str, 'utf-8');
                (_d = this.eventChunkCb) === null || _d === void 0 ? void 0 : _d.call(this, event);
                (_e = this.bufferChunkCb) === null || _e === void 0 ? void 0 : _e.call(this, buffer);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_g && !_a && (_b = _h.return)) await _b.call(_h);
            }
            finally { if (e_1) throw e_1.error; }
        }
        (_f = this.onFinishCb) === null || _f === void 0 ? void 0 : _f.call(this);
    }
    abort() {
        this.stream.controller.abort();
    }
}
exports.ResponseStream = ResponseStream;
