stdin-buffer.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /**
  2. * StdinBuffer buffers input and emits complete sequences.
  3. *
  4. * This is necessary because stdin data events can arrive in partial chunks,
  5. * especially for escape sequences like mouse events. Without buffering,
  6. * partial sequences can be misinterpreted as regular keypresses.
  7. *
  8. * For example, the mouse SGR sequence `\x1b[<35;20;5m` might arrive as:
  9. * - Event 1: `\x1b`
  10. * - Event 2: `[<35`
  11. * - Event 3: `;20;5m`
  12. *
  13. * The buffer accumulates these until a complete sequence is detected.
  14. * Call the `process()` method to feed input data.
  15. *
  16. * Based on code from OpenTUI (https://github.com/anomalyco/opentui)
  17. * MIT License - Copyright (c) 2025 opentui
  18. */
  19. import { EventEmitter } from "events";
  20. const ESC = "\x1b";
  21. const BRACKETED_PASTE_START = "\x1b[200~";
  22. const BRACKETED_PASTE_END = "\x1b[201~";
  23. /**
  24. * Check if a string is a complete escape sequence or needs more data
  25. */
  26. function isCompleteSequence(data: string): "complete" | "incomplete" | "not-escape" {
  27. if (!data.startsWith(ESC)) {
  28. return "not-escape";
  29. }
  30. if (data.length === 1) {
  31. return "incomplete";
  32. }
  33. const afterEsc = data.slice(1);
  34. // CSI sequences: ESC [
  35. if (afterEsc.startsWith("[")) {
  36. // Check for old-style mouse sequence: ESC[M + 3 bytes
  37. if (afterEsc.startsWith("[M")) {
  38. // Old-style mouse needs ESC[M + 3 bytes = 6 total
  39. return data.length >= 6 ? "complete" : "incomplete";
  40. }
  41. return isCompleteCsiSequence(data);
  42. }
  43. // OSC sequences: ESC ]
  44. if (afterEsc.startsWith("]")) {
  45. return isCompleteOscSequence(data);
  46. }
  47. // DCS sequences: ESC P ... ESC \ (includes XTVersion responses)
  48. if (afterEsc.startsWith("P")) {
  49. return isCompleteDcsSequence(data);
  50. }
  51. // APC sequences: ESC _ ... ESC \ (includes Kitty graphics responses)
  52. if (afterEsc.startsWith("_")) {
  53. return isCompleteApcSequence(data);
  54. }
  55. // SS3 sequences: ESC O
  56. if (afterEsc.startsWith("O")) {
  57. // ESC O followed by a single character
  58. return afterEsc.length >= 2 ? "complete" : "incomplete";
  59. }
  60. // Meta key sequences: ESC followed by a single character
  61. if (afterEsc.length === 1) {
  62. return "complete";
  63. }
  64. // Unknown escape sequence - treat as complete
  65. return "complete";
  66. }
  67. /**
  68. * Check if CSI sequence is complete
  69. * CSI sequences: ESC [ ... followed by a final byte (0x40-0x7E)
  70. */
  71. function isCompleteCsiSequence(data: string): "complete" | "incomplete" {
  72. if (!data.startsWith(`${ESC}[`)) {
  73. return "complete";
  74. }
  75. // Need at least ESC [ and one more character
  76. if (data.length < 3) {
  77. return "incomplete";
  78. }
  79. const payload = data.slice(2);
  80. // CSI sequences end with a byte in the range 0x40-0x7E (@-~)
  81. // This includes all letters and several special characters
  82. const lastChar = payload[payload.length - 1];
  83. const lastCharCode = lastChar.charCodeAt(0);
  84. if (lastCharCode >= 0x40 && lastCharCode <= 0x7e) {
  85. // Special handling for SGR mouse sequences
  86. // Format: ESC[<B;X;Ym or ESC[<B;X;YM
  87. if (payload.startsWith("<")) {
  88. // Must have format: <digits;digits;digits[Mm]
  89. const mouseMatch = /^<\d+;\d+;\d+[Mm]$/.test(payload);
  90. if (mouseMatch) {
  91. return "complete";
  92. }
  93. // If it ends with M or m but doesn't match the pattern, still incomplete
  94. if (lastChar === "M" || lastChar === "m") {
  95. // Check if we have the right structure
  96. const parts = payload.slice(1, -1).split(";");
  97. if (parts.length === 3 && parts.every((p) => /^\d+$/.test(p))) {
  98. return "complete";
  99. }
  100. }
  101. return "incomplete";
  102. }
  103. return "complete";
  104. }
  105. return "incomplete";
  106. }
  107. /**
  108. * Check if OSC sequence is complete
  109. * OSC sequences: ESC ] ... ST (where ST is ESC \ or BEL)
  110. */
  111. function isCompleteOscSequence(data: string): "complete" | "incomplete" {
  112. if (!data.startsWith(`${ESC}]`)) {
  113. return "complete";
  114. }
  115. // OSC sequences end with ST (ESC \) or BEL (\x07)
  116. if (data.endsWith(`${ESC}\\`) || data.endsWith("\x07")) {
  117. return "complete";
  118. }
  119. return "incomplete";
  120. }
  121. /**
  122. * Check if DCS (Device Control String) sequence is complete
  123. * DCS sequences: ESC P ... ST (where ST is ESC \)
  124. * Used for XTVersion responses like ESC P >| ... ESC \
  125. */
  126. function isCompleteDcsSequence(data: string): "complete" | "incomplete" {
  127. if (!data.startsWith(`${ESC}P`)) {
  128. return "complete";
  129. }
  130. // DCS sequences end with ST (ESC \)
  131. if (data.endsWith(`${ESC}\\`)) {
  132. return "complete";
  133. }
  134. return "incomplete";
  135. }
  136. /**
  137. * Check if APC (Application Program Command) sequence is complete
  138. * APC sequences: ESC _ ... ST (where ST is ESC \)
  139. * Used for Kitty graphics responses like ESC _ G ... ESC \
  140. */
  141. function isCompleteApcSequence(data: string): "complete" | "incomplete" {
  142. if (!data.startsWith(`${ESC}_`)) {
  143. return "complete";
  144. }
  145. // APC sequences end with ST (ESC \)
  146. if (data.endsWith(`${ESC}\\`)) {
  147. return "complete";
  148. }
  149. return "incomplete";
  150. }
  151. /**
  152. * Split accumulated buffer into complete sequences
  153. */
  154. function parseUnmodifiedKittyPrintableCodepoint(sequence: string): number | undefined {
  155. const match = sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);
  156. if (!match) return undefined;
  157. const codepoint = parseInt(match[1]!, 10);
  158. return codepoint >= 32 ? codepoint : undefined;
  159. }
  160. function extractCompleteSequences(buffer: string): { sequences: string[]; remainder: string } {
  161. const sequences: string[] = [];
  162. let pos = 0;
  163. while (pos < buffer.length) {
  164. const remaining = buffer.slice(pos);
  165. // Try to extract a sequence starting at this position
  166. if (remaining.startsWith(ESC)) {
  167. // Find the end of this escape sequence
  168. let seqEnd = 1;
  169. while (seqEnd <= remaining.length) {
  170. const candidate = remaining.slice(0, seqEnd);
  171. const status = isCompleteSequence(candidate);
  172. if (status === "complete") {
  173. // WezTerm with enable_kitty_keyboard sends the Escape key press as a
  174. // raw '\x1b' byte (simple text path in encode_kitty, ignoring
  175. // DISAMBIGUATE_ESCAPE_CODES) and the release as a full Kitty CSI-u
  176. // sequence. These arrive concatenated as '\x1b\x1b[27;...u'.
  177. // The buffer would normally treat '\x1b\x1b' as a complete meta-key
  178. // sequence (ESC + single char), leaving '[27;...u' to be typed as
  179. // plain text. If the character immediately following '\x1b\x1b'
  180. // would begin a new escape sequence, emit only the first ESC and
  181. // restart from the second.
  182. if (candidate === "\x1b\x1b") {
  183. const nextChar = remaining[seqEnd];
  184. if (
  185. nextChar === "[" || // CSI
  186. nextChar === "]" || // OSC
  187. nextChar === "O" || // SS3
  188. nextChar === "P" || // DCS
  189. nextChar === "_" // APC
  190. ) {
  191. sequences.push(ESC);
  192. pos += 1;
  193. break;
  194. }
  195. }
  196. sequences.push(candidate);
  197. pos += seqEnd;
  198. break;
  199. } else if (status === "incomplete") {
  200. seqEnd++;
  201. } else {
  202. // Should not happen when starting with ESC
  203. sequences.push(candidate);
  204. pos += seqEnd;
  205. break;
  206. }
  207. }
  208. if (seqEnd > remaining.length) {
  209. return { sequences, remainder: remaining };
  210. }
  211. } else {
  212. // Not an escape sequence - take a single character
  213. sequences.push(remaining[0]!);
  214. pos++;
  215. }
  216. }
  217. return { sequences, remainder: "" };
  218. }
  219. export type StdinBufferOptions = {
  220. /**
  221. * Maximum time to wait for sequence completion (default: 10ms)
  222. * After this time, the buffer is flushed even if incomplete
  223. */
  224. timeout?: number;
  225. };
  226. export type StdinBufferEventMap = {
  227. data: [string];
  228. paste: [string];
  229. };
  230. /**
  231. * Buffers stdin input and emits complete sequences via the 'data' event.
  232. * Handles partial escape sequences that arrive across multiple chunks.
  233. */
  234. export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
  235. private buffer: string = "";
  236. private timeout: ReturnType<typeof setTimeout> | null = null;
  237. private readonly timeoutMs: number;
  238. private pasteMode: boolean = false;
  239. private pasteBuffer: string = "";
  240. private pendingKittyPrintableCodepoint: number | undefined;
  241. constructor(options: StdinBufferOptions = {}) {
  242. super();
  243. this.timeoutMs = options.timeout ?? 10;
  244. }
  245. public process(data: string | Buffer): void {
  246. // Clear any pending timeout
  247. if (this.timeout) {
  248. clearTimeout(this.timeout);
  249. this.timeout = null;
  250. }
  251. // Handle high-byte conversion (for compatibility with parseKeypress)
  252. // If buffer has single byte > 127, convert to ESC + (byte - 128)
  253. let str: string;
  254. if (Buffer.isBuffer(data)) {
  255. if (data.length === 1 && data[0]! > 127) {
  256. const byte = data[0]! - 128;
  257. str = `\x1b${String.fromCharCode(byte)}`;
  258. } else {
  259. str = data.toString();
  260. }
  261. } else {
  262. str = data;
  263. }
  264. if (str.length === 0 && this.buffer.length === 0) {
  265. this.emitDataSequence("");
  266. return;
  267. }
  268. this.buffer += str;
  269. if (this.pasteMode) {
  270. this.pasteBuffer += this.buffer;
  271. this.buffer = "";
  272. const endIndex = this.pasteBuffer.indexOf(BRACKETED_PASTE_END);
  273. if (endIndex !== -1) {
  274. const pastedContent = this.pasteBuffer.slice(0, endIndex);
  275. const remaining = this.pasteBuffer.slice(endIndex + BRACKETED_PASTE_END.length);
  276. this.pasteMode = false;
  277. this.pasteBuffer = "";
  278. this.pendingKittyPrintableCodepoint = undefined;
  279. this.emit("paste", pastedContent);
  280. if (remaining.length > 0) {
  281. this.process(remaining);
  282. }
  283. }
  284. return;
  285. }
  286. const startIndex = this.buffer.indexOf(BRACKETED_PASTE_START);
  287. if (startIndex !== -1) {
  288. if (startIndex > 0) {
  289. const beforePaste = this.buffer.slice(0, startIndex);
  290. const result = extractCompleteSequences(beforePaste);
  291. for (const sequence of result.sequences) {
  292. this.emitDataSequence(sequence);
  293. }
  294. }
  295. this.pendingKittyPrintableCodepoint = undefined;
  296. this.buffer = this.buffer.slice(startIndex + BRACKETED_PASTE_START.length);
  297. this.pasteMode = true;
  298. this.pasteBuffer = this.buffer;
  299. this.buffer = "";
  300. const endIndex = this.pasteBuffer.indexOf(BRACKETED_PASTE_END);
  301. if (endIndex !== -1) {
  302. const pastedContent = this.pasteBuffer.slice(0, endIndex);
  303. const remaining = this.pasteBuffer.slice(endIndex + BRACKETED_PASTE_END.length);
  304. this.pasteMode = false;
  305. this.pasteBuffer = "";
  306. this.pendingKittyPrintableCodepoint = undefined;
  307. this.emit("paste", pastedContent);
  308. if (remaining.length > 0) {
  309. this.process(remaining);
  310. }
  311. }
  312. return;
  313. }
  314. const result = extractCompleteSequences(this.buffer);
  315. this.buffer = result.remainder;
  316. for (const sequence of result.sequences) {
  317. this.emitDataSequence(sequence);
  318. }
  319. if (this.buffer.length > 0) {
  320. this.timeout = setTimeout(() => {
  321. const flushed = this.flush();
  322. for (const sequence of flushed) {
  323. this.emitDataSequence(sequence);
  324. }
  325. }, this.timeoutMs);
  326. }
  327. }
  328. private emitDataSequence(sequence: string): void {
  329. const rawCodepoint = sequence.length === 1 ? sequence.codePointAt(0) : undefined;
  330. if (rawCodepoint !== undefined && rawCodepoint === this.pendingKittyPrintableCodepoint) {
  331. this.pendingKittyPrintableCodepoint = undefined;
  332. return;
  333. }
  334. this.pendingKittyPrintableCodepoint = parseUnmodifiedKittyPrintableCodepoint(sequence);
  335. this.emit("data", sequence);
  336. }
  337. flush(): string[] {
  338. if (this.timeout) {
  339. clearTimeout(this.timeout);
  340. this.timeout = null;
  341. }
  342. if (this.buffer.length === 0) {
  343. return [];
  344. }
  345. const sequences = [this.buffer];
  346. this.buffer = "";
  347. this.pendingKittyPrintableCodepoint = undefined;
  348. return sequences;
  349. }
  350. clear(): void {
  351. if (this.timeout) {
  352. clearTimeout(this.timeout);
  353. this.timeout = null;
  354. }
  355. this.buffer = "";
  356. this.pasteMode = false;
  357. this.pasteBuffer = "";
  358. this.pendingKittyPrintableCodepoint = undefined;
  359. }
  360. getBuffer(): string {
  361. return this.buffer;
  362. }
  363. destroy(): void {
  364. this.clear();
  365. }
  366. }