(stdin: NodeJS.ReadStream = process.stdin)
| 1662 | */ |
| 1663 | /* eslint-disable custom-rules/no-sync-fs -- must be sync; called from signal handler / unmount */ |
| 1664 | export function drainStdin(stdin: NodeJS.ReadStream = process.stdin): void { |
| 1665 | if (!stdin.isTTY) return; |
| 1666 | // Drain Node's stream buffer (bytes libuv already pulled in). read() |
| 1667 | // returns null when empty — never blocks. |
| 1668 | try { |
| 1669 | while (stdin.read() !== null) { |
| 1670 | /* discard */ |
| 1671 | } |
| 1672 | } catch { |
| 1673 | /* stream may be destroyed */ |
| 1674 | } |
| 1675 | // No /dev/tty on Windows; CONIN$ doesn't support O_NONBLOCK semantics. |
| 1676 | // Windows Terminal also doesn't buffer mouse reports the same way. |
| 1677 | if (process.platform === 'win32') return; |
| 1678 | // termios is per-device: flip stdin to raw so canonical-mode line |
| 1679 | // buffering doesn't hide partial input from the non-blocking read. |
| 1680 | // Restored in the finally block. |
| 1681 | const tty = stdin as NodeJS.ReadStream & { |
| 1682 | isRaw?: boolean; |
| 1683 | setRawMode?: (raw: boolean) => void; |
| 1684 | }; |
| 1685 | const wasRaw = tty.isRaw === true; |
| 1686 | // Drain the kernel TTY buffer via a fresh O_NONBLOCK fd. Bounded at 64 |
| 1687 | // reads (64KB) — a real mouse burst is a few hundred bytes; the cap |
| 1688 | // guards against a terminal that ignores O_NONBLOCK. |
| 1689 | let fd = -1; |
| 1690 | try { |
| 1691 | // setRawMode inside try: on revoked TTY (SIGHUP/SSH disconnect) the |
| 1692 | // ioctl throws EBADF — same recovery path as openSync/readSync below. |
| 1693 | if (!wasRaw) tty.setRawMode?.(true); |
| 1694 | fd = openSync('/dev/tty', fsConstants.O_RDONLY | fsConstants.O_NONBLOCK); |
| 1695 | const buf = Buffer.alloc(1024); |
| 1696 | for (let i = 0; i < 64; i++) { |
| 1697 | if (readSync(fd, buf, 0, buf.length, null) <= 0) break; |
| 1698 | } |
| 1699 | } catch { |
| 1700 | // EAGAIN (buffer empty — expected), ENXIO/ENOENT (no controlling tty), |
| 1701 | // EBADF/EIO (TTY revoked — SIGHUP, SSH disconnect) |
| 1702 | } finally { |
| 1703 | if (fd >= 0) { |
| 1704 | try { |
| 1705 | closeSync(fd); |
| 1706 | } catch { |
| 1707 | /* ignore */ |
| 1708 | } |
| 1709 | } |
| 1710 | if (!wasRaw) { |
| 1711 | try { |
| 1712 | tty.setRawMode?.(false); |
| 1713 | } catch { |
| 1714 | /* TTY may be gone */ |
| 1715 | } |
| 1716 | } |
| 1717 | } |
| 1718 | } |
| 1719 | /* eslint-enable custom-rules/no-sync-fs */ |
| 1720 | |
| 1721 | const CONSOLE_STDOUT_METHODS = ['log', 'info', 'debug', 'dir', 'dirxml', 'count', 'countReset', 'group', 'groupCollapsed', 'groupEnd', 'table', 'time', 'timeEnd', 'timeLog'] as const; |
no test coverage detected