| 3 | const decoder = new TextDecoder('utf-8'); |
| 4 | |
| 5 | export const readStream = async (stream: ReactDOMServerReadableStream) => { |
| 6 | const chunks: Uint8Array[] = []; |
| 7 | |
| 8 | const writableStream = new WritableStream({ |
| 9 | write(chunk: Uint8Array) { |
| 10 | chunks.push(chunk); |
| 11 | }, |
| 12 | abort(reason) { |
| 13 | throw new Error('Stream aborted', { |
| 14 | cause: { |
| 15 | reason, |
| 16 | }, |
| 17 | }); |
| 18 | }, |
| 19 | }); |
| 20 | await stream.pipeTo(writableStream); |
| 21 | |
| 22 | let length = 0; |
| 23 | chunks.forEach((item) => { |
| 24 | length += item.length; |
| 25 | }); |
| 26 | const mergedChunks = new Uint8Array(length); |
| 27 | let offset = 0; |
| 28 | chunks.forEach((item) => { |
| 29 | mergedChunks.set(item, offset); |
| 30 | offset += item.length; |
| 31 | }); |
| 32 | |
| 33 | return decoder.decode(mergedChunks); |
| 34 | }; |