Open History to see the last commit
1import { Effect, Stream } from "effect";
2
3export interface CollectedUint8StreamText {
4 readonly text: string;
5 readonly truncated: boolean;
6 readonly bytes: number;
7}
8
9interface CollectState {
10 readonly text: string;
11 readonly bytes: number;
12 readonly truncated: boolean;
13}
14
15export const collectUint8StreamText = <E>(input: {
16 readonly stream: Stream.Stream<Uint8Array, E>;
17 readonly maxBytes?: number | undefined;
18 readonly truncatedMarker?: string | null | undefined;
19}): Effect.Effect<CollectedUint8StreamText, E> => {
20 const decoder = new TextDecoder();
21 const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
22 const truncatedMarker = input.truncatedMarker ?? "";
23
24 return input.stream.pipe(
25 Stream.runFold(
26 (): CollectState => ({
27 text: "",
28 bytes: 0,
29 truncated: false,
30 }),
31 (state, chunk): CollectState => {
32 if (state.truncated) {
33 return state;
34 }
35
36 const remainingBytes = maxBytes - state.bytes;
37 if (remainingBytes <= 0) {
38 return {
39 ...state,
40 text: `${state.text}${truncatedMarker}`,
41 truncated: true,
42 };
43 }
44
45 const nextChunk =
46 chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
47 const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
48 const bytes = state.bytes + nextChunk.byteLength;
49 const truncated = chunk.byteLength > remainingBytes;
50
51 return {
52 text: truncated ? `${text}${truncatedMarker}` : text,
53 bytes,
54 truncated,
55 };
56 },
57 ),
58 Effect.map(
59 (state): CollectedUint8StreamText => ({
60 text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
61 bytes: state.bytes,
62 truncated: state.truncated,
63 }),
64 ),
65 );
66};