Skip to content

Commit 55b7e5f

Browse files
authored
fix: create hasBytes promise before await (#3304)
To prevent the hasBytes promise rejecting before it is awaited, defer creation until it's about to be used.
1 parent 55bbd8c commit 55b7e5f

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

packages/utils/src/stream-utils.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ export function byteStream <T extends MessageStream> (stream: T, opts?: ByteStre
116116
const maxBufferSize = opts?.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE
117117
const readBuffer = new Uint8ArrayList()
118118

119-
let hasBytes = Promise.withResolvers<void>()
119+
let hasBytes: PromiseWithResolvers<void> | undefined
120120
let unwrapped = false
121121

122122
if (!isValid(stream)) {
@@ -129,24 +129,24 @@ export function byteStream <T extends MessageStream> (stream: T, opts?: ByteStre
129129
if (readBuffer.byteLength > maxBufferSize) {
130130
const readBufferSize = readBuffer.byteLength
131131
readBuffer.consume(readBuffer.byteLength)
132-
hasBytes.reject(new Error(`Read buffer overflow - ${readBufferSize} > ${maxBufferSize}`))
132+
hasBytes?.reject(new Error(`Read buffer overflow - ${readBufferSize} > ${maxBufferSize}`))
133133
}
134134

135-
hasBytes.resolve()
135+
hasBytes?.resolve()
136136
}
137137
stream.addEventListener('message', byteStreamOnMessageListener)
138138

139139
const byteStreamOnCloseListener = (evt: StreamCloseEvent): void => {
140140
if (evt.error != null) {
141-
hasBytes.reject(evt.error)
141+
hasBytes?.reject(evt.error)
142142
} else {
143-
hasBytes.resolve()
143+
hasBytes?.resolve()
144144
}
145145
}
146146
stream.addEventListener('close', byteStreamOnCloseListener)
147147

148148
const byteStreamOnRemoteCloseWrite = (): void => {
149-
hasBytes.resolve()
149+
hasBytes?.resolve()
150150
}
151151
stream.addEventListener('remoteCloseWrite', byteStreamOnRemoteCloseWrite)
152152

@@ -171,6 +171,7 @@ export function byteStream <T extends MessageStream> (stream: T, opts?: ByteStre
171171
}
172172

173173
const bytesToRead = options?.bytes ?? 1
174+
hasBytes = Promise.withResolvers<void>()
174175

175176
while (true) {
176177
if (readBuffer.byteLength >= bytesToRead) {

0 commit comments

Comments
 (0)