| 1 | export async function* toAsyncIterable( |
| 2 | nodeReadable: NodeJS.ReadableStream, |
| 3 | ): AsyncGenerator<Uint8Array> { |
| 4 | for await (const chunk of nodeReadable) { |
| 5 | // @ts-expect-error |
| 6 | yield chunk as Uint8Array; |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | export async function* streamResponse( |
| 11 | response: Response, |
| 12 | ): AsyncGenerator<string> { |
| 13 | if (response.status === 499) { |
| 14 | return; // In case of client-side cancellation, just return |
| 15 | } |
| 16 | if (response.status !== 200) { |
| 17 | throw new Error(await response.text()); |
| 18 | } |
| 19 | |
| 20 | if (!response.body) { |
| 21 | throw new Error("No response body returned."); |
| 22 | } |
| 23 | |
| 24 | // Get the major version of Node.js |
| 25 | const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10); |
| 26 | |
| 27 | try { |
| 28 | if (nodeMajorVersion >= 20) { |
| 29 | // Use the new API for Node 20 and above |
| 30 | const stream = (ReadableStream as any).from(response.body); |
| 31 | for await (const chunk of stream.pipeThrough( |
| 32 | new TextDecoderStream("utf-8"), |
| 33 | )) { |
| 34 | yield chunk; |
| 35 | } |
| 36 | } else { |
| 37 | // Fallback for Node versions below 20 |
| 38 | // Streaming with this method doesn't work as version 20+ does |
| 39 | const decoder = new TextDecoder("utf-8"); |
| 40 | const nodeStream = response.body as unknown as NodeJS.ReadableStream; |
| 41 | for await (const chunk of toAsyncIterable(nodeStream)) { |
| 42 | yield decoder.decode(chunk, { stream: true }); |
| 43 | } |
| 44 | } |
| 45 | } catch (e) { |
| 46 | if (e instanceof Error && e.name.startsWith("AbortError")) { |
| 47 | return; // In case of client-side cancellation, just return |
| 48 | } |
| 49 | throw e; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // Export for testing purposes |
| 54 | export function parseDataLine(line: string): any { |
| 55 | const json = line.startsWith("data: ") |
| 56 | ? line.slice("data: ".length) |
| 57 | : line.slice("data:".length); |
| 58 | |
| 59 | try { |
| 60 | const data = JSON.parse(json); |
| 61 | if (data.error) { |
| 62 | throw new Error(`Error streaming response: ${data.error}`); |
| 63 | } |
| 64 | |
| 65 | return data; |
| 66 | } catch (e) { |
| 67 | // If the error was thrown by our error check, rethrow it |
| 68 | if ( |
| 69 | e instanceof Error && |
| 70 | e.message.startsWith("Error streaming response:") |
| 71 | ) { |
| 72 | throw e; |
| 73 | } |
| 74 | // Otherwise it's a JSON parsing error |
| 75 | throw new Error(`Malformed JSON sent from server: ${json}`); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | function parseSseLine(line: string): { done: boolean; data: any } { |
| 80 | if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { |
| 81 | return { done: true, data: undefined }; |
| 82 | } |
| 83 | if (line.startsWith("data:")) { |
| 84 | return { done: false, data: parseDataLine(line) }; |
| 85 | } |
| 86 | if (line.startsWith(": ping")) { |
| 87 | return { done: true, data: undefined }; |
| 88 | } |
| 89 | return { done: false, data: undefined }; |
| 90 | } |
| 91 | |
| 92 | export async function* streamSse(response: Response): AsyncGenerator<any> { |
| 93 | let buffer = ""; |
| 94 | for await (const value of streamResponse(response)) { |
| 95 | buffer += value; |
| 96 | |
| 97 | let position: number; |
| 98 | while ((position = buffer.indexOf("\n")) >= 0) { |
| 99 | const line = buffer.slice(0, position); |
| 100 | buffer = buffer.slice(position + 1); |
| 101 | |
| 102 | const { done, data } = parseSseLine(line); |
| 103 | if (done) { |
| 104 | break; |
| 105 | } |
| 106 | if (data) { |
| 107 | yield data; |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | if (buffer.length > 0) { |
| 113 | const { done, data } = parseSseLine(buffer); |
| 114 | if (!done && data) { |
| 115 | yield data; |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | export async function* streamJSON(response: Response): AsyncGenerator<any> { |
| 121 | let buffer = ""; |
| 122 | for await (const value of streamResponse(response)) { |
| 123 | buffer += value; |
| 124 | |
| 125 | let position; |
| 126 | while ((position = buffer.indexOf("\n")) >= 0) { |
| 127 | const line = buffer.slice(0, position); |
| 128 | const data = JSON.parse(line); |
| 129 | yield data; |
| 130 | buffer = buffer.slice(position + 1); |
| 131 | } |
| 132 | } |
| 133 | } |