Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(web): do not rely on ReadableStream.from or new ReadableStream #493

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions src/platform.web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,44 @@ 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>,
) {
let writeOrCloseErr;
let isWriteDone = false;
try {
for await (const chunk of itr) {
await writer.write(chunk);
}
isWriteDone = true;
await writer.close();
} catch (err) {
console.error(
`${isWriteDone ? "Stream error:" : "Chunk error:"} ${err}`,
);
writeOrCloseErr = err;
}
if (writeOrCloseErr) {
try {
await writer.abort(writeOrCloseErr);
} catch (err) {
console.error(`Abort error: ${err}`);
}
}
}

// Turn an AsyncIterable<Uint8Array> into a stream
export const itrToStream = (itr: AsyncIterable<Uint8Array>) =>
ReadableStream.from(itr);
export const itrToStream = (itr: AsyncIterable<Uint8Array>) => {
// do not assume ReadableStream.from or new ReadableStream to exist yet
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();

// This should never throw
writeAsyncItrToStream(itr, writer);

return readable;
};

// === Base configuration for `fetch` calls
export const baseFetchConfig = (_apiRoot: string) => ({});
Expand Down
Loading