Typed Web Streams Transform Pipeline

Split byte chunks into decoded text lines with a TransformStream, enforce a line-size ceiling and collect results type-safely.

TypescriptData Fetching

Code

typescriptsnippet
62 lines
export function createLineDecoder(): TransformStream<Uint8Array, string> {
  const decoder = new TextDecoder();
  let buffer = "";
  return new TransformStream<Uint8Array, string>({
    transform(chunk, controller) {
      buffer += decoder.decode(chunk, { stream: true });
      let newline = buffer.indexOf("\n");
      while (newline !== -1) {
        controller.enqueue(buffer.slice(0, newline).replace(/\r$/, ""));
        buffer = buffer.slice(newline + 1);
        newline = buffer.indexOf("\n");
      }
      if (buffer.length > 1_000_000) {
        controller.error(new RangeError("line exceeds the 1 MB limit"));
        buffer = "";
      }
    },
    flush(controller) {
      buffer += decoder.decode();
      if (buffer !== "") controller.enqueue(buffer.replace(/\r$/, ""));
      buffer = "";
    },
  });
}

export async function collectStream<Value>(stream: ReadableStream<Value>): Promise<Value[]> {
  if (!(stream instanceof ReadableStream)) throw new TypeError("stream must be a ReadableStream");
  const values: Value[] = [];
  const reader = stream.getReader();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) return values;
      values.push(value);
    }
  } finally {
    reader.releaseLock();
  }
}

async function* toChunks(text: string): AsyncGenerator<Uint8Array> {
  const bytes = new TextEncoder().encode(text);
  for (let offset = 0; offset < bytes.length; offset += 7) {
    yield bytes.slice(offset, offset + 7);
  }
}

const source = new ReadableStream<Uint8Array>({
  async start(controller) {
    for await (const chunk of toChunks("alpha\r\nbeta\ngamma")) controller.enqueue(chunk);
    controller.close();
  },
});
const lines = await collectStream(source.pipeThrough(createLineDecoder()));
console.log(lines);

const empty = new ReadableStream<Uint8Array>({
  start(controller) {
    controller.close();
  },
});
console.log(await collectStream(empty.pipeThrough(createLineDecoder())));

Inside the snippet

Read it one way: the functions createLineDecoder and collectStream, doing all the work.

The nesting pairs while (newline !== -1) with while (true) — the inner runs once per outer step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Failure is loud: TypeError aborts the current operation instead of degrading it.

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • The guard done short-circuits the flow with an early return when its condition holds.

Using it

Signature: export function createLineDecoder()

createLineDecoder is what another module would consume; nothing else here is load-bearing for callers.

Key statements

if (!(stream instanceof ReadableStream)) throw new TypeError("stream must be a ReadableStream");
for await (const chunk of toChunks("alpha\r\nbeta\ngamma")) controller.enqueue(chunk);
const lines = await collectStream(source.pipeThrough(createLineDecoder()));

FAQ

Does `createLineDecoder` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
What happens on invalid input?
The code throws `TypeError` — the guard `done` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `createLineDecoder`, `collectStream` at load time.