Forge
csharpdeeb25a2
1using System.Net.Http;
2using System.Runtime.CompilerServices;
3using System.Text;
4using System.Text.Json;
5
6namespace CascadeIDE.Features.Intercom.Transport;
7
8internal static class IntercomSseParser
9{
10 public static async IAsyncEnumerable<IntercomTransportEventEnvelopeDto> ReadEnvelopesAsync(
11 HttpResponseMessage response,
12 [EnumeratorCancellation] CancellationToken ct)
13 {
14 await using var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
15 using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
16
17 var dataLines = new List<string>();
18 while (true)
19 {
20 ct.ThrowIfCancellationRequested();
21 var line = await reader.ReadLineAsync(ct).ConfigureAwait(false);
22 if (line is null)
23 break;
24
25 if (line.Length == 0)
26 {
27 if (dataLines.Count == 0)
28 continue;
29
30 var json = string.Join('\n', dataLines);
31 dataLines.Clear();
32 IntercomTransportEventEnvelopeDto? envelope;
33 try
34 {
35 envelope = JsonSerializer.Deserialize<IntercomTransportEventEnvelopeDto>(json, IntercomTransportJson.Web);
36 }
37 catch (JsonException)
38 {
39 continue;
40 }
41
42 if (envelope is not null)
43 yield return envelope;
44 continue;
45 }
46
47 if (line.StartsWith("data:", StringComparison.Ordinal))
48 dataLines.Add(line["data:".Length..].TrimStart());
49 }
50 }
51}
52
View only · write via MCP/CIDE