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

Function makeParser

packages/effect/src/encoding/Sse.ts:279–415  ·  view source on GitHub ↗
(onParse: (event: AnyEvent) => void, options?: DecodeOptions)

Source from the content-addressed store, hash-verified

277 * @since 4.0.0
278 */
279export function makeParser(onParse: (event: AnyEvent) => void, options?: DecodeOptions): Parser {
280 const maxEventSize = options?.maxEventSize ?? defaultMaxEventSize
281 const dispatchEmptyNamedEvents = options?.dispatchEmptyNamedEvents === true
282
283 // Processing state
284 let isFirstChunk: boolean
285 // Pieces of the unterminated line, joined once when the line ends
286 let pending: Array<string>
287 let pendingLength: number
288 let discardTrailingNewline: boolean
289 // Incremented by `reset`, so `feed` can stop if `onParse` resets the parser
290 let generation = 0
291
292 // Event state
293 let lastEventId: string | undefined
294 let eventName: string | undefined
295 let data: string
296
297 reset()
298 return { feed, reset }
299
300 function reset(): void {
301 generation++
302 isFirstChunk = true
303 pending = []
304 pendingLength = 0
305 discardTrailingNewline = false
306
307 lastEventId = undefined
308 eventName = undefined
309 data = ""
310 }
311
312 function feed(chunk: string): SseError | undefined {
313 // Empty chunks must not consume the leading BOM check below
314 if (chunk.length === 0) return
315
316 // Strip a UTF-8 byte order mark (BOM) at the start of the stream
317 if (isFirstChunk && chunk.startsWith(BOM)) {
318 chunk = chunk.slice(BOM.length)
319 }
320
321 isFirstChunk = false
322
323 const length = chunk.length
324 const currentGeneration = generation
325 let position = 0
326
327 while (position < length) {
328 // Skip the LF of a CRLF, whose CR may have ended the previous chunk
329 if (discardTrailingNewline) {
330 discardTrailingNewline = false
331 if (chunk.charCodeAt(position) === LF) {
332 ++position
333 continue
334 }
335 }
336

Callers 1

decodeFunction · 0.70

Calls 1

resetFunction · 0.70

Tested by

no test coverage detected