From bf69cd92b1b10295cc0358db376cd071041a24db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Iv=C3=A1n=20Vieitez=20Parra?= <3857362+corrideat@users.noreply.github.com> Date: Mon, 19 Feb 2024 16:21:13 +0100 Subject: [PATCH] Bugfix: encoding when readable and writable parts are mismatched --- package-lock.json | 4 +-- package.json | 2 +- src/encodeMultipartMessage.ts | 55 +++++++++++++++++++++-------------- 3 files changed, 36 insertions(+), 25 deletions(-) diff --git a/package-lock.json b/package-lock.json index a2d8a64..9456012 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@exact-realty/multipart-parser", - "version": "1.0.11", + "version": "1.0.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@exact-realty/multipart-parser", - "version": "1.0.11", + "version": "1.0.12", "license": "ISC", "devDependencies": { "@types/node": "^20.11.17", diff --git a/package.json b/package.json index 23ebed6..3936416 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/encodeMultipartMessage.ts b/src/encodeMultipartMessage.ts index dad2333..b162671 100644 --- a/src/encodeMultipartMessage.ts +++ b/src/encodeMultipartMessage.ts @@ -195,30 +195,41 @@ const encodeMultipartMessage = ( const reader = transformStream.readable.getReader(); const readableStream = new ReadableStream({ - 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(); + } }, });