(
socket: Socket,
onMessage: (msg: T) => void,
parse: (text: string) => T = text => JSON.parse(text) as T,
options: NdjsonFramerOptions = {},
)
| 25 | * from slowOperations. |
| 26 | */ |
| 27 | export function attachNdjsonFramer<T = unknown>( |
| 28 | socket: Socket, |
| 29 | onMessage: (msg: T) => void, |
| 30 | parse: (text: string) => T = text => JSON.parse(text) as T, |
| 31 | options: NdjsonFramerOptions = {}, |
| 32 | ): void { |
| 33 | let buffer = '' |
| 34 | let bufferBytes = 0 |
| 35 | const maxFrameBytes = options.maxFrameBytes ?? Number.POSITIVE_INFINITY |
| 36 | |
| 37 | const rejectOversizedFrame = (bytes: number): void => { |
| 38 | const error = new Error( |
| 39 | `NDJSON frame exceeded ${maxFrameBytes} bytes (${bytes})`, |
| 40 | ) |
| 41 | options.onFrameError?.(error) |
| 42 | if (options.destroyOnFrameError ?? true) { |
| 43 | socket.destroy(error) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | const rejectInvalidFrame = (error: unknown): void => { |
| 48 | const frameError = |
| 49 | error instanceof Error ? error : new Error('Invalid NDJSON frame') |
| 50 | options.onInvalidFrame?.(frameError) |
| 51 | if (options.destroyOnInvalidFrame ?? false) { |
| 52 | socket.destroy(frameError) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | const emitLine = (line: string): void => { |
| 57 | if (!line.trim()) return |
| 58 | try { |
| 59 | onMessage(parse(line)) |
| 60 | } catch (error) { |
| 61 | rejectInvalidFrame(error) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | socket.on('data', (chunk: Buffer) => { |
| 66 | let start = 0 |
| 67 | for (let index = 0; index < chunk.length; index++) { |
| 68 | if (chunk[index] !== 0x0a) continue |
| 69 | |
| 70 | const segmentBytes = index - start |
| 71 | if ( |
| 72 | Number.isFinite(maxFrameBytes) && |
| 73 | bufferBytes + segmentBytes > maxFrameBytes |
| 74 | ) { |
| 75 | rejectOversizedFrame(bufferBytes + segmentBytes) |
| 76 | return |
| 77 | } |
| 78 | |
| 79 | buffer += chunk.subarray(start, index).toString('utf8') |
| 80 | emitLine(buffer) |
| 81 | buffer = '' |
| 82 | bufferBytes = 0 |
| 83 | start = index + 1 |
| 84 | } |
no test coverage detected