Spaces:
Sleeping
Sleeping
Download web/src/lib/sse.ts from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 2.67 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/web/src/lib/sse.ts
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/web/src/lib/sse.ts
-
curl -L -o sse.ts https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/web/src/lib/sse.ts
2.67 kB
| // Reading /api/ask's server-sent events from a fetch() body. EventSource can't POST, | |
| // so the stream is read by hand: bytes -> text -> blocks separated by a blank line -> | |
| // the JSON after "data: ". Comment lines (": ping", the keep-alive) are skipped. | |
| import type { AskEvent, SystemId } from './types' | |
| /** Complete events in `buffer`, and the unfinished tail to keep for the next chunk. */ | |
| export function parseEvents(buffer: string): { events: AskEvent[]; rest: string } { | |
| const blocks = buffer.replace(/\r\n/g, '\n').split('\n\n') | |
| const rest = blocks.pop() ?? '' // after the last blank line: not complete yet | |
| const events: AskEvent[] = [] | |
| for (const block of blocks) { | |
| const data = block | |
| .split('\n') | |
| .filter((line) => line.startsWith('data:')) | |
| .map((line) => line.slice(5).replace(/^ /, '')) | |
| .join('\n') | |
| if (data) events.push(JSON.parse(data) as AskEvent) | |
| } | |
| return { events, rest } | |
| } | |
| export type HistoryTurn = { question: string; answer: string } | |
| export type AskRequest = { question: string; system: SystemId; day?: string; history?: HistoryTurn[] } | |
| /** Why /api/ask refused before streaming (429 busy/limit, 422 bad input). */ | |
| export class AskRefused extends Error {} | |
| /** POST a question and call onEvent for each event as it arrives. Resolves when the | |
| * stream ends; rejects with AskRefused on an HTTP refusal; abort with `signal`. */ | |
| export async function ask( | |
| body: AskRequest, | |
| onEvent: (event: AskEvent) => void, | |
| signal?: AbortSignal, | |
| ): Promise<void> { | |
| const response = await fetch('/api/ask', { | |
| method: 'POST', | |
| headers: { 'content-type': 'application/json' }, | |
| body: JSON.stringify(body), | |
| signal, | |
| }) | |
| if (!response.ok || !response.body) throw new AskRefused(await refusal(response)) | |
| const reader = response.body.pipeThrough(new TextDecoderStream()).getReader() | |
| let buffer = '' | |
| for (;;) { | |
| const { value, done } = await reader.read() | |
| if (done) break | |
| const parsed = parseEvents(buffer + value) | |
| buffer = parsed.rest | |
| parsed.events.forEach(onEvent) | |
| } | |
| parseEvents(buffer + '\n\n').events.forEach(onEvent) // a last event without its blank line | |
| } | |
| /** The server's reason, readable: FastAPI sends {"detail": "..."} (a string for 429, | |
| * a list of field errors for 422). */ | |
| async function refusal(response: Response): Promise<string> { | |
| try { | |
| const body = await response.json() | |
| if (typeof body.detail === 'string') return body.detail | |
| if (Array.isArray(body.detail)) return body.detail.map((d: { msg: string }) => d.msg).join('; ') | |
| } catch { | |
| // not JSON: fall through | |
| } | |
| return `The server refused the question (HTTP ${response.status}).` | |
| } | |