(text)
| 31 | // Parse complete SSE event blocks. The caller is responsible for buffering |
| 32 | // incomplete trailing data between chunks. |
| 33 | function parseSSEEvents(text) { |
| 34 | const events = []; |
| 35 | const lines = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n'); |
| 36 | let currentEvent = { data: '', event: 'message', id: '' }; |
| 37 | |
| 38 | for (const line of lines) { |
| 39 | if (line === '') { |
| 40 | if (currentEvent.data !== '') { |
| 41 | events.push({ |
| 42 | ...currentEvent, |
| 43 | data: currentEvent.data.endsWith('\n') |
| 44 | ? currentEvent.data.slice(0, -1) |
| 45 | : currentEvent.data |
| 46 | }); |
| 47 | } |
| 48 | currentEvent = { data: '', event: 'message', id: '' }; |
| 49 | continue; |
| 50 | } |
| 51 | |
| 52 | if (line.startsWith(':')) { |
| 53 | continue; |
| 54 | } |
| 55 | |
| 56 | const colonIndex = line.indexOf(':'); |
| 57 | const field = colonIndex === -1 ? line : line.slice(0, colonIndex); |
| 58 | let value = colonIndex === -1 ? '' : line.slice(colonIndex + 1); |
| 59 | if (value.startsWith(' ')) { |
| 60 | value = value.slice(1); |
| 61 | } |
| 62 | |
| 63 | if (field === 'data') { |
| 64 | currentEvent.data += value + '\n'; |
| 65 | } else if (field === 'event') { |
| 66 | currentEvent.event = value || 'message'; |
| 67 | } else if (field === 'id') { |
| 68 | currentEvent.id = value; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | return events; |
| 73 | } |
| 74 | |
| 75 | function findCompleteSSEBoundary(buffer) { |
| 76 | const normalized = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); |
no outgoing calls
no test coverage detected