feat: chat stream messages

This commit is contained in:
Shivering Ocelot committed 2026-05-31 22:24:07 -05:00
1 parent bc71fa4d59
commit 5d2f7609f4
5 files changed
+131 -10

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
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();
}
}
}