// EventSource cannot send headers, so task streams use fetch + ReadableStream // and keep the console key on the X-API-Key header. import { API_BASE, HubError, authHeaders } from "./api"; import type { TaskEvent } from "./types"; export interface StreamEvent extends TaskEvent { type?: string; } export async function streamTaskEvents( taskId: string, onEvent: (event: StreamEvent) => void, signal: AbortSignal ): Promise { const response = await fetch(API_BASE + "/tasks/" + encodeURIComponent(taskId) + "/stream", { headers: authHeaders(), signal, cache: "no-store", }); if (!response.ok) throw new HubError(response.status, response.statusText || "stream refused"); if (!response.body) return; const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; for (;;) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let boundary = buffer.indexOf("\n\n"); while (boundary >= 0) { const chunk = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2); emit(chunk, onEvent); boundary = buffer.indexOf("\n\n"); } } if (buffer.trim()) emit(buffer, onEvent); } function emit(block: string, onEvent: (event: StreamEvent) => void): void { block .split("\n") .filter((line) => line.startsWith("data:")) .forEach((line) => { try { onEvent(JSON.parse(line.slice(5).trim()) as StreamEvent); } catch { /* a partial frame is followed by the next chunk */ } }); }