Skip to content

Commit

Permalink
chore: drop Readable.fromWeb polyfill
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Nov 28, 2024
1 parent cb7fd22 commit 7b472ba
Showing 1 changed file with 1 addition and 75 deletions.
76 changes: 1 addition & 75 deletions packages/node-utils/src/edge-to-node/stream.ts
Original file line number Diff line number Diff line change
@@ -1,76 +1,2 @@
import { Readable } from 'node:stream'

interface FromWebOptions {
objectMode?: boolean
highWaterMark?: number
encoding?: BufferEncoding
signal?: AbortSignal
}

/**
* Code adapted from Node's stream.Readable.fromWeb(), because it has to run on Node@14
* @see https://github.com/nodejs/node/blob/bd462ad81bc30e547e52e699ee3b6fa3d7c882c9/lib/internal/webstreams/adapters.js#L458
*/
export function toToReadable(
webStream: ReadableStream,
options: FromWebOptions = {},
) {
const reader = webStream.getReader()
let closed = false
const { highWaterMark, encoding, objectMode = false, signal } = options

const readable = new Readable({
objectMode,
highWaterMark,
encoding,
// @ts-ignore signal exist only since Node@17
signal,
read() {
reader.read().then(
(chunk: any) => {
if (chunk.done) {
readable.push(null)
} else {
readable.push(chunk.value)
}
},
(error: any) => readable.destroy(error),
)
},

destroy(error: any, callback: (arg0: any) => void) {
function done() {
try {
callback(error)
} catch (error) {
// In a next tick because this is happening within
// a promise context, and if there are any errors
// thrown we don't want those to cause an unhandled
// rejection. Let's just escape the promise and
// handle it separately.
process.nextTick(() => {
throw error
})
}
}

if (!closed) {
reader.cancel(error).then(done, done)
return
}
done()
},
})

reader.closed.then(
() => {
closed = true
},
(error: any) => {
closed = true
readable.destroy(error)
},
)

return readable
}
export const toToReadable = Readable.fromWeb

0 comments on commit 7b472ba

Please sign in to comment.