返回源码地图

packages/coding-agent/src/modes/rpc/jsonl.ts

v1.3.0 · 71023aec1546 · 10:LF-only分帧、跨chunk UTF8与EOF剩余行

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { Readable } from "node:stream";
2import { StringDecoder } from "node:string_decoder";
3
4/**
5 * Serialize a single strict JSONL record.
6 *
7 * Framing is LF-only. Payload strings may contain other Unicode separators such as
8 * U+2028 and U+2029. Clients must split records on `\n` only.
9 */
10export function serializeJsonLine(value: unknown): string {
11 return `${JSON.stringify(value)}\n`;
12}
13
14/**
15 * Attach an LF-only JSONL reader to a stream.
16 *
17 * This intentionally does not use Node readline. Readline splits on additional
18 * Unicode separators that are valid inside JSON strings and therefore does not
19 * implement strict JSONL framing.
20 */
21export function attachJsonlLineReader(stream: Readable, onLine: (line: string) => void): () => void {
22 const decoder = new StringDecoder("utf8");
23 let buffer = "";
24
25 const emitLine = (line: string) => {
26 onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
27 };
28
29 const onData = (chunk: string | Buffer) => {
30 buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
31
32 while (true) {
33 const newlineIndex = buffer.indexOf("\n");
34 if (newlineIndex === -1) {
35 return;
36 }
37
38 emitLine(buffer.slice(0, newlineIndex));
39 buffer = buffer.slice(newlineIndex + 1);
40 }
41 };
42
43 const onEnd = () => {
44 buffer += decoder.end();
45 if (buffer.length > 0) {
46 emitLine(buffer);
47 buffer = "";
48 }
49 };
50
51 stream.on("data", onData);
52 stream.on("end", onEnd);
53
54 return () => {
55 stream.off("data", onData);
56 stream.off("end", onEnd);
57 };
58}