* Parses a field line and updates the message accumulator. * Returns true if a field was added to the message.
( line: string, message: ServerSentEventParsedMessage, ignoreComments: boolean, )
| 41 | * Returns true if a field was added to the message. |
| 42 | */ |
| 43 | function parseLine( |
| 44 | line: string, |
| 45 | message: ServerSentEventParsedMessage, |
| 46 | ignoreComments: boolean, |
| 47 | ): boolean { |
| 48 | // Lines starting with colon are comments |
| 49 | if (line[0] === ":") { |
| 50 | if (ignoreComments) return false; |
| 51 | const value = line.slice(1); |
| 52 | message.comment = message.comment !== undefined |
| 53 | ? `${message.comment}\n${value}` |
| 54 | : value; |
| 55 | return true; |
| 56 | } |
| 57 | |
| 58 | // Parse field:value |
| 59 | const colonIndex = line.indexOf(":"); |
| 60 | let field: string; |
| 61 | let value: string; |
| 62 | |
| 63 | if (colonIndex === -1) { |
| 64 | // No colon means field name only, empty value |
| 65 | field = line; |
| 66 | value = ""; |
| 67 | } else { |
| 68 | field = line.slice(0, colonIndex); |
| 69 | // Remove single leading space from value if present |
| 70 | value = line[colonIndex + 1] === " " |
| 71 | ? line.slice(colonIndex + 2) |
| 72 | : line.slice(colonIndex + 1); |
| 73 | } |
| 74 | |
| 75 | switch (field) { |
| 76 | case "event": |
| 77 | message.event = value; |
| 78 | return true; |
| 79 | case "data": |
| 80 | // Accumulate data with newlines between |
| 81 | message.data = message.data !== undefined |
| 82 | ? `${message.data}\n${value}` |
| 83 | : value; |
| 84 | return true; |
| 85 | case "id": |
| 86 | // Per spec: ignore if value contains null character |
| 87 | if (!value.includes("\0")) { |
| 88 | message.id = value; |
| 89 | return true; |
| 90 | } |
| 91 | return false; |
| 92 | case "retry": |
| 93 | // Per spec: only set if value consists of ASCII digits only |
| 94 | if (/^\d+$/.test(value)) { |
| 95 | message.retry = parseInt(value, 10); |
| 96 | return true; |
| 97 | } |
| 98 | return false; |
| 99 | default: |
| 100 | // Unknown fields are ignored per spec |