* Query the terminal for OSC color information. * * IMPORTANT: This function reads from stdin because OSC responses come through * the PTY which appears on stdin. This means it MUST be run BEFORE any other * stdin listeners (like OpenTUI) are attached. OSC detection runs at the very * start of
( ttyPath: string, query: string, )
| 106 | * @returns The raw response string or null if query failed |
| 107 | */ |
| 108 | async function sendOscQuery( |
| 109 | ttyPath: string, |
| 110 | query: string, |
| 111 | ): Promise<string | null> { |
| 112 | return new Promise((resolve) => { |
| 113 | // Guard: Must have TTY for both reading and writing |
| 114 | if (!process.stdin.isTTY) { |
| 115 | resolve(null) |
| 116 | return |
| 117 | } |
| 118 | |
| 119 | let ttyWriteFd: number | null = null |
| 120 | let timeoutId: NodeJS.Timeout | null = null |
| 121 | let resolved = false |
| 122 | let response = '' |
| 123 | let wasRawMode = false |
| 124 | let dataHandler: ((data: Buffer) => void) | null = null |
| 125 | |
| 126 | const cleanup = () => { |
| 127 | if (resolved) return |
| 128 | resolved = true |
| 129 | |
| 130 | if (timeoutId) { |
| 131 | clearTimeout(timeoutId) |
| 132 | timeoutId = null |
| 133 | } |
| 134 | |
| 135 | // Remove data handler from stdin |
| 136 | if (dataHandler) { |
| 137 | process.stdin.removeListener('data', dataHandler) |
| 138 | dataHandler = null |
| 139 | } |
| 140 | |
| 141 | // Restore raw mode state |
| 142 | if (process.stdin.isTTY && process.stdin.setRawMode) { |
| 143 | try { |
| 144 | process.stdin.setRawMode(wasRawMode) |
| 145 | } catch { |
| 146 | // Ignore errors restoring raw mode |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // Pause stdin so we leave it non-flowing before other listeners attach |
| 151 | try { |
| 152 | process.stdin.pause() |
| 153 | } catch { |
| 154 | // Ignore pause errors |
| 155 | } |
| 156 | |
| 157 | // Close TTY write fd |
| 158 | if (ttyWriteFd !== null) { |
| 159 | try { |
| 160 | closeSync(ttyWriteFd) |
| 161 | } catch { |
| 162 | // Ignore close errors |
| 163 | } |
| 164 | ttyWriteFd = null |
| 165 | } |
no test coverage detected