| 6 | */ |
| 7 | |
| 8 | export async function readStdin(): Promise<string> { |
| 9 | const MAX_STDIN_SIZE = 8 * 1024 * 1024; // 8MB |
| 10 | return new Promise((resolve, reject) => { |
| 11 | let data = ''; |
| 12 | let totalSize = 0; |
| 13 | process.stdin.setEncoding('utf8'); |
| 14 | |
| 15 | const onReadable = () => { |
| 16 | let chunk; |
| 17 | while ((chunk = process.stdin.read()) !== null) { |
| 18 | if (totalSize + chunk.length > MAX_STDIN_SIZE) { |
| 19 | const remainingSize = MAX_STDIN_SIZE - totalSize; |
| 20 | data += chunk.slice(0, remainingSize); |
| 21 | console.warn( |
| 22 | `Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`, |
| 23 | ); |
| 24 | process.stdin.destroy(); // Stop reading further |
| 25 | break; |
| 26 | } |
| 27 | data += chunk; |
| 28 | totalSize += chunk.length; |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | const onEnd = () => { |
| 33 | cleanup(); |
| 34 | resolve(data); |
| 35 | }; |
| 36 | |
| 37 | const onError = (err: Error) => { |
| 38 | cleanup(); |
| 39 | reject(err); |
| 40 | }; |
| 41 | |
| 42 | const cleanup = () => { |
| 43 | process.stdin.removeListener('readable', onReadable); |
| 44 | process.stdin.removeListener('end', onEnd); |
| 45 | process.stdin.removeListener('error', onError); |
| 46 | }; |
| 47 | |
| 48 | process.stdin.on('readable', onReadable); |
| 49 | process.stdin.on('end', onEnd); |
| 50 | process.stdin.on('error', onError); |
| 51 | }); |
| 52 | } |