@@ -10,6 +10,9 @@ export async function* toAsyncIterable(
10
10
export async function * streamResponse (
11
11
response : Response ,
12
12
) : AsyncGenerator < string > {
13
+ if ( response . status === 499 ) {
14
+ return ; // In case of client-side cancellation, just return
15
+ }
13
16
if ( response . status !== 200 ) {
14
17
throw new Error ( await response . text ( ) ) ;
15
18
}
@@ -21,22 +24,29 @@ export async function* streamResponse(
21
24
// Get the major version of Node.js
22
25
const nodeMajorVersion = parseInt ( process . versions . node . split ( "." ) [ 0 ] , 10 ) ;
23
26
24
- if ( nodeMajorVersion >= 20 ) {
25
- // Use the new API for Node 20 and above
26
- const stream = ( ReadableStream as any ) . from ( response . body ) ;
27
- for await ( const chunk of stream . pipeThrough (
28
- new TextDecoderStream ( "utf-8" ) ,
29
- ) ) {
30
- yield chunk ;
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
+ }
31
44
}
32
- } else {
33
- // Fallback for Node versions below 20
34
- // Streaming with this method doesn't work as version 20+ does
35
- const decoder = new TextDecoder ( "utf-8" ) ;
36
- const nodeStream = response . body as unknown as NodeJS . ReadableStream ;
37
- for await ( const chunk of toAsyncIterable ( nodeStream ) ) {
38
- yield decoder . decode ( chunk , { stream : true } ) ;
45
+ } catch ( e ) {
46
+ if ( e instanceof Error && e . name . startsWith ( "AbortError" ) ) {
47
+ return ; // In case of client-side cancellation, just return
39
48
}
49
+ throw e ;
40
50
}
41
51
}
42
52
0 commit comments