| | | 1 | | using System.Text; |
| | | 2 | | |
| | | 3 | | namespace Kestrun.Sse; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Formats Server-Sent Events (SSE) payloads according to the SSE wire format. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class SseEventFormatter |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Formats a single SSE event payload. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="eventName">Optional event name.</param> |
| | | 14 | | /// <param name="data">Event payload data (may be multi-line).</param> |
| | | 15 | | /// <param name="id">Optional event ID.</param> |
| | | 16 | | /// <param name="retryMs">Optional reconnect interval in milliseconds.</param> |
| | | 17 | | /// <returns>A formatted SSE payload string.</returns> |
| | | 18 | | public static string Format(string? eventName, string data, string? id = null, int? retryMs = null) |
| | | 19 | | { |
| | 7 | 20 | | var sb = new StringBuilder(capacity: Math.Max(64, data.Length + 32)); |
| | | 21 | | |
| | 7 | 22 | | if (retryMs is not null) |
| | | 23 | | { |
| | 3 | 24 | | _ = sb.Append("retry: ").Append(retryMs.Value).Append('\n'); |
| | | 25 | | } |
| | | 26 | | |
| | 7 | 27 | | if (!string.IsNullOrWhiteSpace(id)) |
| | | 28 | | { |
| | 3 | 29 | | _ = sb.Append("id: ").Append(id).Append('\n'); |
| | | 30 | | } |
| | | 31 | | |
| | 7 | 32 | | if (!string.IsNullOrWhiteSpace(eventName)) |
| | | 33 | | { |
| | 5 | 34 | | _ = sb.Append("event: ").Append(eventName).Append('\n'); |
| | | 35 | | } |
| | | 36 | | |
| | 7 | 37 | | using (var sr = new StringReader(data)) |
| | | 38 | | { |
| | | 39 | | string? line; |
| | 15 | 40 | | while ((line = sr.ReadLine()) is not null) |
| | | 41 | | { |
| | 8 | 42 | | _ = sb.Append("data: ").Append(line).Append('\n'); |
| | | 43 | | } |
| | 7 | 44 | | } |
| | | 45 | | |
| | 7 | 46 | | _ = sb.Append('\n'); |
| | 7 | 47 | | return sb.ToString(); |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Formats an SSE comment payload (useful for keep-alives). |
| | | 52 | | /// </summary> |
| | | 53 | | /// <param name="comment">Comment text.</param> |
| | | 54 | | /// <returns>A formatted SSE comment payload string.</returns> |
| | | 55 | | public static string FormatComment(string comment) => |
| | | 56 | | // Comment lines start with ':' |
| | 1 | 57 | | $": {comment}\n\n"; |
| | | 58 | | } |