Skip to content

Commit

Permalink
Bugfix: encoding when readable and writable parts are mismatched
Browse files Browse the repository at this point in the history
  • Loading branch information
corrideat committed Feb 19, 2024
1 parent 91213f1 commit bf69cd9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 25 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@exact-realty/multipart-parser",
"version": "1.0.11",
"version": "1.0.12",
"description": "TypeScript streaming parser for MIME multipart messages",
"main": "dist/index.cjs",
"types": "./dist/index.d.cts",
Expand Down
55 changes: 33 additions & 22 deletions src/encodeMultipartMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,30 +195,41 @@ const encodeMultipartMessage = (
const reader = transformStream.readable.getReader();

const readableStream = new ReadableStream<ArrayBuffer>({
async pull(controller) {
return Promise.all([
!finishedEncoding && asyncEncoder.next(),
reader.read(),
]).then(async ([encodingResult, readResult]) => {
if (encodingResult && encodingResult.done) {
finishedEncoding = true;
await transformStream.writable.close();
}

if (readResult.done) {
const terminator = new Uint8Array([0x0d, 0x0a]);
controller.enqueue(
terminator.buffer.slice(
terminator.byteOffset,
terminator.byteOffset + terminator.byteLength,
),
);
controller.close();
return;
start(controller) {
(async () => {
for (;;) {
try {
const readResult = await reader.read();
if (readResult.done) {
const terminator = new Uint8Array([0x0d, 0x0a]);
controller.enqueue(
terminator.buffer.slice(
terminator.byteOffset,
terminator.byteOffset +
terminator.byteLength,
),
);
controller.close();
return;
}

controller.enqueue(readResult.value);
} catch (readError) {
console.error('Read error:', readError);
controller.error(readError);
return;
}
}
})().catch(() => {});
},
async pull() {
if (finishedEncoding) return;

controller.enqueue(readResult.value);
});
const encodingResult = await asyncEncoder.next();
if (encodingResult.done) {
finishedEncoding = true;
await transformStream.writable.close();
}
},
});

Expand Down

0 comments on commit bf69cd9

Please sign in to comment.