Skip to content

Commit

Permalink
fix(web): do not rely on ReadableStream.from or new ReadableStream
Browse files Browse the repository at this point in the history
  • Loading branch information
KnightNiwrem committed Oct 7, 2023
1 parent 9b942be commit 25f5e2b
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions src/platform.web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,27 @@ import d from "https://cdn.skypack.dev/[email protected]";
export { d as debug };

// === Export system-specific operations
async function writeAsyncItrToStream<T>(
itr: AsyncIterable<T>,
writer: WritableStreamDefaultWriter<T>,
) {
for await (const chunk of itr) {
await writer.write(chunk);
}
await writer.close();
}

// Turn an AsyncIterable<Uint8Array> into a stream
export const itrToStream = (itr: AsyncIterable<Uint8Array>) => {
// do not assume ReadableStream.from to exist yet
const it = itr[Symbol.asyncIterator]();
return new ReadableStream({
async pull(controller) {
const chunk = await it.next();
if (chunk.done) controller.close();
else controller.enqueue(chunk.value);
},
});
// do not assume ReadableStream.from or new ReadableStream to exist yet
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();

writeAsyncItrToStream(itr, writer).catch((err) =>
console.error("Something went wrong with writing itrToStream")
);

return readable;
};

// === Base configuration for `fetch` calls
Expand Down

0 comments on commit 25f5e2b

Please sign in to comment.