From fbdbf297e18aed45d07765216ac2cae60a7a44e4 Mon Sep 17 00:00:00 2001 From: jhmaster2000 <32803471+jhmaster2000@users.noreply.github.com> Date: Thu, 30 Nov 2023 23:54:51 -0300 Subject: [PATCH] polyfills: fix console async iterator --- packages/bun-polyfills/src/global/console.ts | 26 ++++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/bun-polyfills/src/global/console.ts b/packages/bun-polyfills/src/global/console.ts index 4576f5a703..6f970e828d 100644 --- a/packages/bun-polyfills/src/global/console.ts +++ b/packages/bun-polyfills/src/global/console.ts @@ -9,14 +9,30 @@ // }; //} +const consoleAsyncIterChunks: string[] = []; //? Implements: for await (const line of console) { ... } console[Symbol.asyncIterator] = async function* () { - while (true) yield await new Promise(resolve => { - process.stdin.on('data', (data: Buffer | string) => { - const str = data.toString('utf-8').replaceAll(/[\r\n]+/g, ''); - resolve(str); + if (consoleAsyncIterChunks.length) { + for (const line of [...consoleAsyncIterChunks]) { + consoleAsyncIterChunks.shift(); + if (!line) continue; + yield line; + } + } + while (true) { + const p = await new Promise(resolve => { + process.stdin.once('data', (data: Buffer | string) => { + const str = data.toString('utf-8').split(/[\r\n]+/g); + resolve(str); + }); }); - }); + consoleAsyncIterChunks.push(...p); + for (const line of p) { + consoleAsyncIterChunks.shift(); + if (!line) continue; + yield line; + } + } } satisfies Console[typeof Symbol.asyncIterator]; //? Implements: Bun-exclusive console function