Elffuss BraidHub

kikocis/continue public

44309e42d796 · 4.5 KiBRawPermalink
1export async function* toAsyncIterable(
2 nodeReadable: NodeJS.ReadableStream,
3): AsyncGenerator<Uint8Array> {
4 for await (const chunk of nodeReadable) {
5 // @ts-ignore
6 yield chunk as Uint8Array;
7 }
8}
9
10export 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
17 if (response.status !== 200) {
18 throw new Error(await response.text());
19 }
20
21 if (!response.body) {
22 throw new Error("No response body returned.");
23 }
24
25 // Get the major version of Node.js
26 const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
27 let chunks = 0;
28
29 try {
30 if (nodeMajorVersion >= 20) {
31 // Use the new API for Node 20 and above
32 const stream = (ReadableStream as any).from(response.body);
33 for await (const chunk of stream.pipeThrough(
34 new TextDecoderStream("utf-8"),
35 )) {
36 yield chunk;
37 chunks++;
38 }
39 } else {
40 // Fallback for Node versions below 20
41 // Streaming with this method doesn't work as version 20+ does
42 const decoder = new TextDecoder("utf-8");
43 const nodeStream = response.body as unknown as NodeJS.ReadableStream;
44 for await (const chunk of toAsyncIterable(nodeStream)) {
45 yield decoder.decode(chunk, { stream: true });
46 chunks++;
47 }
48 }
49 } catch (e) {
50 if (e instanceof Error) {
51 if (e.name.startsWith("AbortError")) {
52 return; // In case of client-side cancellation, just return
53 }
54 if (e.message.toLowerCase().includes("premature close")) {
55 // Premature close can happen for various reasons, including:
56 // - Malformed chunks of data received from the server
57 // - The server closed the connection before sending the complete response
58 // - Long delays from the server during streaming
59 // - 'Keep alive' header being used in combination with an http agent and a set, low number of maxSockets
60 if (chunks === 0) {
61 throw new Error(
62 "Stream was closed before any data was received. Try again. (Premature Close)",
63 );
64 } else {
65 throw new Error(
66 "The response was cancelled mid-stream. Try again. (Premature Close).",
67 );
68 }
69 }
70 }
71 throw e;
72 }
73}
74
75// Export for testing purposes
76export function parseDataLine(line: string): any {
77 const json = line.startsWith("data: ")
78 ? line.slice("data: ".length)
79 : line.slice("data:".length);
80
81 try {
82 const data = JSON.parse(json);
83 if (data.error) {
84 throw new Error(`Error streaming response: ${data.error}`);
85 }
86
87 return data;
88 } catch (e) {
89 // If the error was thrown by our error check, rethrow it
90 if (
91 e instanceof Error &&
92 e.message.startsWith("Error streaming response:")
93 ) {
94 throw e;
95 }
96 // Otherwise it's a JSON parsing error
97 throw new Error(`Malformed JSON sent from server: ${json}`);
98 }
99}
100
101function parseSseLine(line: string): { done: boolean; data: any } {
102 if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
103 return { done: true, data: undefined };
104 }
105 if (line.startsWith("data:")) {
106 return { done: false, data: parseDataLine(line) };
107 }
108 if (line.startsWith(": ping")) {
109 return { done: true, data: undefined };
110 }
111 return { done: false, data: undefined };
112}
113
114export async function* streamSse(response: Response): AsyncGenerator<any> {
115 let buffer = "";
116 for await (const value of streamResponse(response)) {
117 buffer += value;
118
119 let position: number;
120 while ((position = buffer.indexOf("\n")) >= 0) {
121 const line = buffer.slice(0, position);
122 buffer = buffer.slice(position + 1);
123
124 const { done, data } = parseSseLine(line);
125 if (done) {
126 break;
127 }
128 if (data) {
129 yield data;
130 }
131 }
132 }
133
134 if (buffer.length > 0) {
135 const { done, data } = parseSseLine(buffer);
136 if (!done && data) {
137 yield data;
138 }
139 }
140}
141
142export async function* streamJSON(response: Response): AsyncGenerator<any> {
143 let buffer = "";
144 for await (const value of streamResponse(response)) {
145 buffer += value;
146
147 let position;
148 while ((position = buffer.indexOf("\n")) >= 0) {
149 const line = buffer.slice(0, position);
150 try {
151 const data = JSON.parse(line);
152 yield data;
153 } catch (e) {
154 throw new Error(`Malformed JSON sent from server: ${line}`);
155 }
156 buffer = buffer.slice(position + 1);
157 }
158 }
159}