brf/server/lib/split.ts
2025-12-13 21:12:08 +01:00

39 lines
775 B
TypeScript

import { TransformStream } from 'stream/web'
const defaultMatcher = /\r?\n/
export type Decoder = {
decode: (chunk: Uint8Array) => string
}
interface Options {
decoder?: Decoder
}
export default function split(matcher?: RegExp | null, { decoder }: Options = {}) {
matcher ??= defaultMatcher
let rest: string | null | undefined = null
return new TransformStream({
start() {},
transform(chunk, controller) {
if (chunk) {
if (decoder) {
chunk = decoder.decode(chunk)
}
const lines = ((rest == null ? '' : rest) + chunk).split(matcher)
rest = lines.pop()
for (const line of lines) {
controller.enqueue(line)
}
} else {
controller.terminate()
}
},
})
}