(reader)
| 11 | // ======================================== |
| 12 | |
| 13 | async function* parseSSE(reader) { |
| 14 | var decoder = new TextDecoder(); |
| 15 | var buffer = ''; |
| 16 | var hasData = false; |
| 17 | var message = { data: '', event: '', id: '', retry: null }; |
| 18 | var firstChunk = true; |
| 19 | |
| 20 | try { |
| 21 | while (true) { |
| 22 | var { done, value } = await reader.read(); |
| 23 | if (done) break; |
| 24 | |
| 25 | var chunk = decoder.decode(value, { stream: true }); |
| 26 | if (firstChunk) { |
| 27 | if (chunk.charCodeAt(0) === 0xFEFF) chunk = chunk.slice(1); |
| 28 | firstChunk = false; |
| 29 | } |
| 30 | buffer += chunk; |
| 31 | |
| 32 | var lines = buffer.split(/\r\n|\r|\n/); |
| 33 | buffer = lines.pop() || ''; |
| 34 | |
| 35 | for (var i = 0; i < lines.length; i++) { |
| 36 | var line = lines[i]; |
| 37 | if (!line) { |
| 38 | if (hasData) { |
| 39 | yield message; |
| 40 | hasData = false; |
| 41 | message = { data: '', event: '', id: '', retry: null }; |
| 42 | } |
| 43 | continue; |
| 44 | } |
| 45 | |
| 46 | var colonIndex = line.indexOf(':'); |
| 47 | if (colonIndex === 0) continue; |
| 48 | |
| 49 | var field, val; |
| 50 | if (colonIndex < 0) { |
| 51 | field = line; |
| 52 | val = ''; |
| 53 | } else { |
| 54 | field = line.slice(0, colonIndex); |
| 55 | val = line.slice(colonIndex + 1); |
| 56 | if (val[0] === ' ') val = val.slice(1); |
| 57 | } |
| 58 | |
| 59 | if (field === 'data') { |
| 60 | message.data += (hasData ? '\n' : '') + val; |
| 61 | hasData = true; |
| 62 | } else if (field === 'event') { |
| 63 | message.event = val; |
| 64 | } else if (field === 'id') { |
| 65 | if (!val.includes('\0')) message.id = val; |
| 66 | } else if (field === 'retry') { |
| 67 | var retryValue = parseInt(val, 10); |
| 68 | if (!isNaN(retryValue)) message.retry = retryValue; |
| 69 | } |
| 70 | } |
no outgoing calls
no test coverage detected