@yoyo-org/progressive-json
Version:
Stream and render JSON data as it arrives - perfect for AI responses, large datasets, and real-time updates
55 lines (54 loc) • 2.07 kB
JavaScript
export async function fetchSSEWithAuth(url, processor, options) {
let eventSource = null;
try {
eventSource = new EventSource(url);
let connectionOpened = false;
eventSource.onopen = () => {
connectionOpened = true;
console.log("SSE connection opened");
};
eventSource.onmessage = (event) => {
connectionOpened = true;
try {
// Handle [DONE] signal
if (event.data === "[DONE]") {
eventSource === null || eventSource === void 0 ? void 0 : eventSource.close();
processor.onStreamComplete(processor.getStore());
return;
}
// Convert SSE data to chunk format expected by processor
const chunk = new TextEncoder().encode(event.data + "\n");
processor.processChunk(chunk);
}
catch (error) {
processor.handleStreamError(error);
}
};
eventSource.onerror = (error) => {
console.error("SSE error:", error);
// Handle authentication errors
if (!connectionOpened && (eventSource === null || eventSource === void 0 ? void 0 : eventSource.readyState) === EventSource.CLOSED) {
processor.handleStreamError(new Error("Authentication failed. Please sign in again."));
}
else {
processor.handleStreamError(new Error("Connection lost"));
}
eventSource === null || eventSource === void 0 ? void 0 : eventSource.close();
};
// Handle abort/cleanup
const cleanup = () => {
if (eventSource) {
eventSource.close();
eventSource = null;
}
};
// Store cleanup function on processor for stop() method
processor._sseCleanup = cleanup;
}
catch (error) {
if (eventSource) {
eventSource.close();
}
throw error;
}
}