/** * Streaming utilities for piping LLM token streams into Lumina. * Use when the model streams JSON incrementally; these helpers tolerate incomplete output. */ /** * Parses possibly incomplete JSON by auto-closing unclosed brackets and strings. * Use in your LLM stream handler: append chunks to a buffer, call this on each chunk; * when it returns non-null, pass the result to `engine.load()` for progressive rendering. * * @param input - Raw or partial JSON string (e.g. from SSE or WebSocket chunks). * @returns Parsed object, or `null` if the string cannot be repaired to valid JSON. * @example * let buf = ""; * for await (const chunk of stream) { * buf += chunk; * const json = parsePartialJson(buf); * if (json) engine.load(json); * } */ export function parsePartialJson(input: string): any { let fixed = input.trim(); // 1. Remove trailing commas (common in streams) fixed = fixed.replace(/,(\s*[}\]])/g, '$1'); // 2. Count open brackets/braces const stack: string[] = []; let inString = false; let isEscaped = false; for (let i = 0; i < fixed.length; i++) { const char = fixed[i]; if (inString) { if (char === '\\') { isEscaped = !isEscaped; } else if (char === '"' && !isEscaped) { inString = false; } else { isEscaped = false; } continue; } if (char === '"') { inString = true; } else if (char === '{') { stack.push('}'); } else if (char === '[') { stack.push(']'); } else if (char === '}') { if (stack[stack.length - 1] === '}') stack.pop(); } else if (char === ']') { if (stack[stack.length - 1] === ']') stack.pop(); } } // 3. Auto-close strings if (inString) { fixed += '"'; // If we closed a property key "key": "val, we might need value closing // But usually streams cut off at value. "title": "my tit } // 4. Auto-close structural stack in reverse while (stack.length > 0) { fixed += stack.pop(); } try { return JSON.parse(fixed); } catch (e) { // If it still fails, return null or a safe fallback // console.warn("Stream parse failed, waiting for more chunks..."); return null; } } /** * Returns a function that parses partial JSON and invokes `callback` only after the stream * has been idle for `delay` ms. Reduces UI jitter when tokens arrive very fast. * * @param callback - Called with the parsed object when a valid parse occurs after the debounce. * @param delay - Idle time in ms before firing. Default 50. * @returns A function `(raw: string) => void` to call with each concatenated chunk. * @example * const onChunk = createDebouncedLoader((deck) => engine.load(deck), 80); * for await (const c of stream) { buffer += c; onChunk(buffer); } */ export function createDebouncedLoader( callback: (data: T) => void, delay = 50 ) { let timeout: any = null; return (rawData: string) => { const parsed = parsePartialJson(rawData); if (!parsed) return; // Skip invalid frames if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { callback(parsed); }, delay); }; } /** * Returns whether a slide object has the minimum fields needed to render. * Use when streaming to decide between showing the slide or a skeleton/placeholder. * * @param slide - A possible slide object (e.g. from `parsePartialJson` mid-stream). * @returns `true` if `slide.type` exists and type-specific required fields (e.g. `title` for statement, `features` for features) are present. * @example * const json = parsePartialJson(buffer); * if (json?.slides) json.slides.forEach((s, i) => { if (isSlideReady(s)) showSlide(i, s); else showSkeleton(i); }); */ export function isSlideReady(slide: any): boolean { if (!slide) return false; if (!slide.type) return false; // For statement, we need at least a title partial if (slide.type === 'statement' && typeof slide.title !== 'string') return false; // For features, we need the array to exist if (slide.type === 'features' && !Array.isArray(slide.features)) return false; return true; }