| 37 | }; |
| 38 | |
| 39 | function createJsonLineParser(onMessage: (msg: any) => void): (chunk: Buffer) => void { |
| 40 | let buffer = ""; |
| 41 | return (chunk: Buffer) => { |
| 42 | buffer += chunk.toString("utf8"); |
| 43 | while (true) { |
| 44 | const idx = buffer.indexOf("\n"); |
| 45 | if (idx === -1) return; |
| 46 | const line = buffer.slice(0, idx); |
| 47 | buffer = buffer.slice(idx + 1); |
| 48 | if (!line.trim()) continue; |
| 49 | try { |
| 50 | onMessage(JSON.parse(line)); |
| 51 | } catch { |
| 52 | // ignore |
| 53 | } |
| 54 | } |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | function writeJsonLine(socket: net.Socket, msg: any): void { |
| 59 | socket.write(JSON.stringify(msg) + "\n"); |