MCPcopy Create free account
hub / github.com/Effect-TS/effect / makeParser

Function makeParser

packages/experimental/src/Sse.ts:151–309  ·  view source on GitHub ↗
(onParse: (event: AnyEvent) => void, options?: DecodeOptions)

Source from the content-addressed store, hash-verified

149 * @category constructors
150 */
151export function makeParser(onParse: (event: AnyEvent) => void, options?: DecodeOptions): Parser {
152 const maxEventSize = options?.maxEventSize ?? defaultMaxEventSize
153
154 // Processing state
155 let isFirstChunk: boolean
156 let buffer: string
157 let startingPosition: number
158 let startingFieldLength: number
159
160 // Event state
161 let eventId: string | undefined
162 let lastEventId: string | undefined
163 let eventName: string | undefined
164 let data: string
165
166 reset()
167 return { feed, reset }
168
169 function reset(): void {
170 isFirstChunk = true
171 buffer = ""
172 startingPosition = 0
173 startingFieldLength = -1
174
175 eventId = undefined
176 eventName = undefined
177 data = ""
178 }
179
180 function feed(chunk: string): SseError | undefined {
181 buffer = buffer ? buffer + chunk : chunk
182
183 // Strip any UTF8 byte order mark (BOM) at the start of the stream.
184 // Note that we do not strip any non - UTF8 BOM, as eventsource streams are
185 // always decoded as UTF8 as per the specification.
186 if (isFirstChunk && hasBom(buffer)) {
187 buffer = buffer.slice(BOM.length)
188 }
189
190 isFirstChunk = false
191
192 // Set up chunk-specific processing state
193 const length = buffer.length
194 let position = 0
195 let discardTrailingNewline = false
196
197 // Read the current buffer byte by byte
198 while (position < length) {
199 // EventSource allows for carriage return + line feed, which means we
200 // need to ignore a linefeed character if the previous character was a
201 // carriage return
202 // @todo refactor to reduce nesting, consider checking previous byte?
203 // @todo but consider multiple chunks etc
204 if (discardTrailingNewline) {
205 if (buffer[position] === "\n") {
206 ++position
207 }
208 discardTrailingNewline = false

Callers 1

makeChannelFunction · 0.85

Calls 1

resetFunction · 0.70

Tested by

no test coverage detected