| 1 | import * as fs from "fs"; |
| 2 | |
| 3 | /** |
| 4 | * Reads input from stdin if available (when data is piped in) |
| 5 | * Returns null if stdin is a TTY (interactive terminal) or if no data available |
| 6 | */ |
| 7 | export function readStdinSync(): string | null { |
| 8 | try { |
| 9 | // In test environments, don't attempt to read stdin to avoid hanging |
| 10 | // But allow CI environments to read stdin when it's clearly piped |
| 11 | if ( |
| 12 | process.env.NODE_ENV === "test" || |
| 13 | process.env.VITEST === "true" || |
| 14 | process.env.JEST_WORKER_ID !== undefined || |
| 15 | process.env.CONTINUE_CLI_TEST === "true" |
| 16 | ) { |
| 17 | return null; |
| 18 | } |
| 19 | |
| 20 | // Special handling for CI environments - allow reading if stdin is clearly not a TTY |
| 21 | if (process.env.CI === "true" && process.stdin.isTTY === true) { |
| 22 | return null; |
| 23 | } |
| 24 | |
| 25 | // Check if stdin is a TTY (interactive terminal) |
| 26 | if (process.stdin.isTTY === true) { |
| 27 | // Definitely a TTY, don't read |
| 28 | return null; |
| 29 | } |
| 30 | |
| 31 | // If isTTY is false, we likely have piped input |
| 32 | if (process.stdin.isTTY === false) { |
| 33 | // Try to read stdin with a fallback |
| 34 | try { |
| 35 | const stdinData = fs.readFileSync(0, "utf8"); |
| 36 | return stdinData.trim(); |
| 37 | } catch { |
| 38 | return null; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // If isTTY is undefined, be cautious and check if we can read non-blockingly |
| 43 | // This handles cases where TTY detection is unreliable |
| 44 | try { |
| 45 | // Use readFileSync with fd 0 but wrap in timeout logic |
| 46 | const stdinData = fs.readFileSync(0, "utf8"); |
| 47 | return stdinData.trim(); |
| 48 | } catch { |
| 49 | // If we can't read (EAGAIN, EWOULDBLOCK, etc.), assume no piped input |
| 50 | return null; |
| 51 | } |
| 52 | } catch { |
| 53 | return null; |
| 54 | } |
| 55 | } |