sse.ts 865 B

12345678910111213141516171819202122232425262728
  1. import type { SseEventType } from './types';
  2. export interface ParsedSseEvent {
  3. type: SseEventType;
  4. data: Record<string, unknown>;
  5. }
  6. export function parseSseChunk(previous: string, chunk: string): { events: ParsedSseEvent[]; remainder: string } {
  7. const buffer = previous + chunk;
  8. const rawEvents = buffer.split('\n\n');
  9. const remainder = rawEvents.pop() ?? '';
  10. const events: ParsedSseEvent[] = [];
  11. for (const raw of rawEvents) {
  12. const eventMatch = raw.match(/^event:\s*(.+)$/m);
  13. const dataMatch = raw.match(/^data:\s*(.+)$/m);
  14. if (!eventMatch || !dataMatch) continue;
  15. const type = eventMatch[1].trim() as SseEventType;
  16. try {
  17. events.push({ type, data: JSON.parse(dataMatch[1]) });
  18. } catch {
  19. events.push({ type: 'error', data: { message: 'SSE 数据解析失败' } });
  20. }
  21. }
  22. return { events, remainder };
  23. }