import { GLChatMessageChunk, GLChatMessageStatus } from './types'; /** * JSON.parse, but with reviver, so it can parse nested values * * @param {string} val Stringified JSON * @returns {Record} A JSON object, or if can't parse * the string, return the original string. */ function parseNested(val: string): Record | string { try { return JSON.parse(val, (_, val) => { if (typeof val === 'string') { return parseNested(val); } return val; }); } catch { return val; } } /** * Process raw chunk from stream into GLChat chunk objects. * * @param {unknown} value Raw chunk from API. * @returns {GLChatMessageChunk} Message chunk in object format. * @throws GeneralError, if the chunk is not a string. */ export function processGLChatChunk(value: unknown): GLChatMessageChunk { if (typeof value !== 'string') { throw new Error('Chunk is not a string'); } const stringChunk = value.replace(/^data:/, ''); let rawChunk: { status: GLChatMessageStatus; message: string }; try { rawChunk = JSON.parse(stringChunk); } catch { throw new Error('Chunk is not a valid JSON'); } let parsedMessage; try { parsedMessage = rawChunk.status === 'data' ? parseNested(rawChunk.message) : rawChunk.message; } catch { throw new Error('Data chunk is not a valid JSON'); } return { ...rawChunk, message: parsedMessage, } as GLChatMessageChunk; }