export default class Stream { constructor (id) { this.id = id; this.partialContent = ""; this.eof = false; this.listeners = { data: [], end: [], }; let onResponse = (msg) => { if (this.eof) return; if (msg.eof) { this.eof = true; this.handle('end'); } else { this.partialContent += msg.data; this.handle('data', msg.data); } }; this.contentPromise = new Promise((resolve, reject) => { this.handle("end", () => { resolve(this.partialContent); }); }); } feed (chunk) { if (this.eof) return; this.partialContent += chunk; this.handle('data', chunk); } close () { this.eof = true; this.handle('end', this.partialContent); } getContent () { return this.contentPromise; } handle (event, ...args) { for (let fn of this.listeners[event]) { fn(...args) } } on (event, callback) { this.listeners[event].push(callback); if (event == "data" && this.partialContent) { callback(this.partialContent); } if (event == "end" && this.eof) { callback(); } } }