Elffuss BraidHub

kikocis/continue public

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