MCPcopy Create free account
hub / github.com/CommandCodeAI/BaseAI / LineDecoder

Class LineDecoder

packages/baseai/src/dev/utils/stream/stream.ts:372–477  ·  view source on GitHub ↗

* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally * reading lines from text. * * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258

Source from the content-addressed store, hash-verified

370 * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
371 */
372class LineDecoder {
373 // prettier-ignore
374 static NEWLINE_CHARS = new Set(['\n', '\r']);
375 static NEWLINE_REGEXP = /\r\n|[\n\r]/g;
376
377 buffer: string[];
378 trailingCR: boolean;
379 textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types.
380
381 constructor() {
382 this.buffer = [];
383 this.trailingCR = false;
384 }
385
386 decode(chunk: Bytes): string[] {
387 let text = this.decodeText(chunk);
388
389 if (this.trailingCR) {
390 text = '\r' + text;
391 this.trailingCR = false;
392 }
393 if (text.endsWith('\r')) {
394 this.trailingCR = true;
395 text = text.slice(0, -1);
396 }
397
398 if (!text) {
399 return [];
400 }
401
402 const trailingNewline = LineDecoder.NEWLINE_CHARS.has(
403 text[text.length - 1] || ''
404 );
405 let lines = text.split(LineDecoder.NEWLINE_REGEXP);
406
407 // if there is a trailing new line then the last entry will be an empty
408 // string which we don't care about
409 if (trailingNewline) {
410 lines.pop();
411 }
412
413 if (lines.length === 1 && !trailingNewline) {
414 this.buffer.push(lines[0]!);
415 return [];
416 }
417
418 if (this.buffer.length > 0) {
419 lines = [this.buffer.join('') + lines[0], ...lines.slice(1)];
420 this.buffer = [];
421 }
422
423 if (!trailingNewline) {
424 this.buffer = [lines.pop() || ''];
425 }
426
427 return lines;
428 }
429

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected