@f5-sales-demo/pi-tui 19.51.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,481 @@
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
+
21
+ const ESC = "\x1b";
22
+ const BRACKETED_PASTE_START = "\x1b[200~";
23
+ const BRACKETED_PASTE_END = "\x1b[201~";
24
+
25
+ // How long after flushing an incomplete escape we will still stitch a late
26
+ // continuation back onto it. Generous because the same render stall that split
27
+ // the keypress also delays processing of its second half.
28
+ const ESCAPE_CONTINUATION_WINDOW_MS = 2000;
29
+
30
+ /**
31
+ * Does `combined` (a just-flushed incomplete-escape prefix joined with the next
32
+ * chunk) look like a fragmented CSI/SS3/OSC/DCS/APC sequence being stitched back
33
+ * together — as opposed to an Escape keypress followed by ordinary typed text?
34
+ * Only the former should be reassembled.
35
+ */
36
+ function isEscapeContinuation(combined: string): boolean {
37
+ if (combined.length < 2 || !combined.startsWith(ESC)) {
38
+ return false;
39
+ }
40
+ // Only CSI (ESC [). That is the family that fragments as keyboard input —
41
+ // arrows, function keys, modifyOtherKeys (ESC[27;5;99~), kitty (ESC[99;5u).
42
+ // OSC/DCS/APC are string-terminated terminal *responses*, not fragmented
43
+ // keypresses, and must never be glued onto unrelated input.
44
+ return combined[1] === "[";
45
+ }
46
+
47
+ /**
48
+ * Check if a string is a complete escape sequence or needs more data
49
+ */
50
+ function isCompleteSequence(data: string): "complete" | "incomplete" | "not-escape" {
51
+ if (!data.startsWith(ESC)) {
52
+ return "not-escape";
53
+ }
54
+
55
+ if (data.length === 1) {
56
+ return "incomplete";
57
+ }
58
+
59
+ const afterEsc = data.slice(1);
60
+
61
+ // CSI sequences: ESC [
62
+ if (afterEsc.startsWith("[")) {
63
+ // Check for old-style mouse sequence: ESC[M + 3 bytes
64
+ if (afterEsc.startsWith("[M")) {
65
+ // Old-style mouse needs ESC[M + 3 bytes = 6 total
66
+ return data.length >= 6 ? "complete" : "incomplete";
67
+ }
68
+ return isCompleteCsiSequence(data);
69
+ }
70
+
71
+ // OSC sequences: ESC ]
72
+ if (afterEsc.startsWith("]")) {
73
+ return isCompleteOscSequence(data);
74
+ }
75
+
76
+ // DCS sequences: ESC P ... ESC \ (includes XTVersion responses)
77
+ if (afterEsc.startsWith("P")) {
78
+ return isCompleteDcsSequence(data);
79
+ }
80
+
81
+ // APC sequences: ESC _ ... ESC \ (includes Kitty graphics responses)
82
+ if (afterEsc.startsWith("_")) {
83
+ return isCompleteApcSequence(data);
84
+ }
85
+
86
+ // SS3 sequences: ESC O
87
+ if (afterEsc.startsWith("O")) {
88
+ // ESC O followed by a single character
89
+ return afterEsc.length >= 2 ? "complete" : "incomplete";
90
+ }
91
+
92
+ // Meta key sequences: ESC followed by a single character
93
+ if (afterEsc.length === 1) {
94
+ return "complete";
95
+ }
96
+
97
+ // Unknown escape sequence - treat as complete
98
+ return "complete";
99
+ }
100
+
101
+ /**
102
+ * Check if CSI sequence is complete
103
+ * CSI sequences: ESC [ ... followed by a final byte (0x40-0x7E)
104
+ */
105
+ function isCompleteCsiSequence(data: string): "complete" | "incomplete" {
106
+ if (!data.startsWith(`${ESC}[`)) {
107
+ return "complete";
108
+ }
109
+
110
+ // Need at least ESC [ and one more character
111
+ if (data.length < 3) {
112
+ return "incomplete";
113
+ }
114
+
115
+ const payload = data.slice(2);
116
+
117
+ // CSI sequences end with a byte in the range 0x40-0x7E (@-~)
118
+ // This includes all letters and several special characters
119
+ const lastChar = payload[payload.length - 1];
120
+ const lastCharCode = lastChar.charCodeAt(0);
121
+
122
+ if (lastCharCode >= 0x40 && lastCharCode <= 0x7e) {
123
+ // Special handling for SGR mouse sequences
124
+ // Format: ESC[<B;X;Ym or ESC[<B;X;YM
125
+ if (payload.startsWith("<")) {
126
+ // Must have format: <digits;digits;digits[Mm]
127
+ const mouseMatch = /^<\d+;\d+;\d+[Mm]$/.test(payload);
128
+ if (mouseMatch) {
129
+ return "complete";
130
+ }
131
+ // If it ends with M or m but doesn't match the pattern, still incomplete
132
+ if (lastChar === "M" || lastChar === "m") {
133
+ // Check if we have the right structure
134
+ const parts = payload.slice(1, -1).split(";");
135
+ if (parts.length === 3 && parts.every(p => /^\d+$/.test(p))) {
136
+ return "complete";
137
+ }
138
+ }
139
+
140
+ return "incomplete";
141
+ }
142
+
143
+ return "complete";
144
+ }
145
+
146
+ return "incomplete";
147
+ }
148
+
149
+ /**
150
+ * Check if OSC sequence is complete
151
+ * OSC sequences: ESC ] ... ST (where ST is ESC \ or BEL)
152
+ */
153
+ function isCompleteOscSequence(data: string): "complete" | "incomplete" {
154
+ if (!data.startsWith(`${ESC}]`)) {
155
+ return "complete";
156
+ }
157
+
158
+ // OSC sequences end with ST (ESC \) or BEL (\x07)
159
+ if (data.endsWith(`${ESC}\\`) || data.endsWith("\x07")) {
160
+ return "complete";
161
+ }
162
+
163
+ return "incomplete";
164
+ }
165
+
166
+ /**
167
+ * Check if DCS (Device Control String) sequence is complete
168
+ * DCS sequences: ESC P ... ST (where ST is ESC \)
169
+ * Used for XTVersion responses like ESC P >| ... ESC \
170
+ */
171
+ function isCompleteDcsSequence(data: string): "complete" | "incomplete" {
172
+ if (!data.startsWith(`${ESC}P`)) {
173
+ return "complete";
174
+ }
175
+
176
+ // DCS sequences end with ST (ESC \)
177
+ if (data.endsWith(`${ESC}\\`)) {
178
+ return "complete";
179
+ }
180
+
181
+ return "incomplete";
182
+ }
183
+
184
+ /**
185
+ * Check if APC (Application Program Command) sequence is complete
186
+ * APC sequences: ESC _ ... ST (where ST is ESC \)
187
+ * Used for Kitty graphics responses like ESC _ G ... ESC \
188
+ */
189
+ function isCompleteApcSequence(data: string): "complete" | "incomplete" {
190
+ if (!data.startsWith(`${ESC}_`)) {
191
+ return "complete";
192
+ }
193
+
194
+ // APC sequences end with ST (ESC \)
195
+ if (data.endsWith(`${ESC}\\`)) {
196
+ return "complete";
197
+ }
198
+
199
+ return "incomplete";
200
+ }
201
+
202
+ /**
203
+ * Split accumulated buffer into complete sequences
204
+ */
205
+ function extractCompleteSequences(buffer: string): { sequences: string[]; remainder: string } {
206
+ const sequences: string[] = [];
207
+ let pos = 0;
208
+
209
+ while (pos < buffer.length) {
210
+ const remaining = buffer.slice(pos);
211
+
212
+ // Try to extract a sequence starting at this position
213
+ if (remaining.startsWith(ESC)) {
214
+ // Find the end of this escape sequence
215
+ let seqEnd = 1;
216
+ while (seqEnd <= remaining.length) {
217
+ const candidate = remaining.slice(0, seqEnd);
218
+ const status = isCompleteSequence(candidate);
219
+
220
+ if (status === "complete") {
221
+ sequences.push(candidate);
222
+ pos += seqEnd;
223
+ break;
224
+ } else if (status === "incomplete") {
225
+ seqEnd++;
226
+ } else {
227
+ // Should not happen when starting with ESC
228
+ sequences.push(candidate);
229
+ pos += seqEnd;
230
+ break;
231
+ }
232
+ }
233
+
234
+ if (seqEnd > remaining.length) {
235
+ return { sequences, remainder: remaining };
236
+ }
237
+ } else {
238
+ // Not an escape sequence - take a single character
239
+ sequences.push(remaining[0]!);
240
+ pos++;
241
+ }
242
+ }
243
+
244
+ return { sequences, remainder: "" };
245
+ }
246
+
247
+ export type StdinBufferOptions = {
248
+ /**
249
+ * Maximum time to wait for sequence completion (default: 50ms)
250
+ * After this time, the buffer is flushed even if incomplete.
251
+ *
252
+ * This is effectively the "ESC hold" window: a lone ESC (the Escape key)
253
+ * registers after this delay, and a multi-byte escape sequence fragmented
254
+ * across stdin reads (common under heavy render load) has this long to
255
+ * reassemble before its tail would leak as individual printable characters.
256
+ * 50ms is the standard ESC timeout — long enough to survive multi-frame
257
+ * stalls, short enough to feel instant.
258
+ */
259
+ timeout?: number;
260
+ };
261
+
262
+ export type StdinBufferEventMap = {
263
+ data: [string];
264
+ paste: [string];
265
+ };
266
+
267
+ /**
268
+ * Buffers stdin input and emits complete sequences via the 'data' event.
269
+ * Handles partial escape sequences that arrive across multiple chunks.
270
+ */
271
+ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
272
+ #buffer: string = "";
273
+ #timeout?: NodeJS.Timeout;
274
+ readonly #timeoutMs: number;
275
+ #pasteMode: boolean = false;
276
+ #pasteBuffer: string = "";
277
+ // An incomplete escape sequence we flushed on timeout, kept so a continuation
278
+ // arriving in the next read (a keypress fragmented across stdin reads by an
279
+ // extreme render stall) can be reassembled instead of leaking its tail as text.
280
+ #pendingEscape: string | null = null;
281
+ #pendingEscapeAt = 0;
282
+
283
+ constructor(options: StdinBufferOptions = {}) {
284
+ super();
285
+ this.#timeoutMs = options.timeout ?? 50;
286
+ }
287
+
288
+ process(data: string | Buffer): void {
289
+ // Clear any pending timeout
290
+ if (this.#timeout) {
291
+ clearTimeout(this.#timeout);
292
+ this.#timeout = undefined;
293
+ }
294
+
295
+ // Handle high-byte conversion (for compatibility with parseKeypress)
296
+ // If buffer has single byte > 127, convert to ESC + (byte - 128)
297
+ let str: string;
298
+ if (Buffer.isBuffer(data)) {
299
+ if (data.length === 1 && data[0]! > 127) {
300
+ const byte = data[0]! - 128;
301
+ str = `\x1b${String.fromCharCode(byte)}`;
302
+ } else {
303
+ str = data.toString();
304
+ }
305
+ } else {
306
+ str = data;
307
+ }
308
+
309
+ // If we recently flushed an incomplete escape (its hold window expired before
310
+ // the rest of the keypress arrived), stitch this continuation back onto it so
311
+ // it parses as one sequence. The lone ESC was already delivered as a harmless
312
+ // Escape; here we recover the CSI/SS3 tail that would otherwise leak as text.
313
+ if (this.#pendingEscape !== null) {
314
+ const prefix = this.#pendingEscape;
315
+ this.#pendingEscape = null;
316
+ if (
317
+ !str.startsWith(ESC) && // a bare tail, not a fresh escape sequence of its own
318
+ Date.now() - this.#pendingEscapeAt < ESCAPE_CONTINUATION_WINDOW_MS &&
319
+ isEscapeContinuation(prefix + str)
320
+ ) {
321
+ str = prefix + str;
322
+ }
323
+ }
324
+
325
+ if (str.length === 0 && this.#buffer.length === 0) {
326
+ this.emit("data", "");
327
+ return;
328
+ }
329
+
330
+ this.#buffer += str;
331
+
332
+ if (this.#pasteMode) {
333
+ this.#pasteBuffer += this.#buffer;
334
+ this.#buffer = "";
335
+
336
+ const endIndex = this.#pasteBuffer.indexOf(BRACKETED_PASTE_END);
337
+ if (endIndex !== -1) {
338
+ const pastedContent = this.#pasteBuffer.slice(0, endIndex);
339
+ const remaining = this.#pasteBuffer.slice(endIndex + BRACKETED_PASTE_END.length);
340
+
341
+ this.#pasteMode = false;
342
+ this.#pasteBuffer = "";
343
+
344
+ this.emit("paste", pastedContent);
345
+
346
+ if (remaining.length > 0) {
347
+ this.process(remaining);
348
+ }
349
+ }
350
+ return;
351
+ }
352
+
353
+ const startIndex = this.#buffer.indexOf(BRACKETED_PASTE_START);
354
+ if (startIndex !== -1) {
355
+ if (startIndex > 0) {
356
+ const beforePaste = this.#buffer.slice(0, startIndex);
357
+ const result = extractCompleteSequences(beforePaste);
358
+ for (const sequence of result.sequences) {
359
+ this.emit("data", sequence);
360
+ }
361
+ }
362
+
363
+ this.#buffer = this.#buffer.slice(startIndex + BRACKETED_PASTE_START.length);
364
+ this.#pasteMode = true;
365
+ this.#pasteBuffer = this.#buffer;
366
+ this.#buffer = "";
367
+
368
+ const endIndex = this.#pasteBuffer.indexOf(BRACKETED_PASTE_END);
369
+ if (endIndex !== -1) {
370
+ const pastedContent = this.#pasteBuffer.slice(0, endIndex);
371
+ const remaining = this.#pasteBuffer.slice(endIndex + BRACKETED_PASTE_END.length);
372
+
373
+ this.#pasteMode = false;
374
+ this.#pasteBuffer = "";
375
+
376
+ this.emit("paste", pastedContent);
377
+
378
+ if (remaining.length > 0) {
379
+ this.process(remaining);
380
+ }
381
+ }
382
+ return;
383
+ }
384
+
385
+ const result = extractCompleteSequences(this.#buffer);
386
+ this.#buffer = result.remainder;
387
+
388
+ for (const sequence of result.sequences) {
389
+ this.emit("data", sequence);
390
+ }
391
+
392
+ if (this.#buffer.length > 0) {
393
+ this.#timeout = setTimeout(() => {
394
+ const flushed = this.flush();
395
+
396
+ for (const sequence of flushed) {
397
+ this.emit("data", sequence);
398
+ }
399
+
400
+ // Remember a flushed incomplete escape so a continuation arriving in
401
+ // the next read can be reassembled (see process()). Only a genuinely
402
+ // incomplete trailing fragment qualifies — a complete sequence (e.g.
403
+ // one peeled out of a de-blobbed probe response) is not a keypress
404
+ // awaiting its tail and must not glue onto the next read.
405
+ const last = flushed[flushed.length - 1];
406
+ // biome-ignore lint/complexity/useOptionalChain: the explicit undefined check narrows `last` to string for isCompleteSequence(last) below; optional chaining would not.
407
+ if (last !== undefined && last.startsWith(ESC) && isCompleteSequence(last) === "incomplete") {
408
+ this.#pendingEscape = last;
409
+ this.#pendingEscapeAt = Date.now();
410
+ }
411
+ }, this.#timeoutMs);
412
+ }
413
+ }
414
+
415
+ flush(): string[] {
416
+ if (this.#timeout) {
417
+ clearTimeout(this.#timeout);
418
+ this.#timeout = undefined;
419
+ }
420
+
421
+ if (this.#buffer.length === 0) {
422
+ return [];
423
+ }
424
+
425
+ // Re-split the abandoned buffer into individual complete sequences instead
426
+ // of emitting it whole. Under render load a terminal *response* can arrive
427
+ // before its terminator (notably an OSC 11 reply missing its ST); the
428
+ // tokenizer then treats it as incomplete and, while scanning for the
429
+ // terminator, absorbs any following replies (DA1, Kitty) into one fragment.
430
+ // Emitting that as a single event defeats the terminal's anchored
431
+ // single-sequence matchers, so the whole blob leaks into the editor as text
432
+ // (#1446). Split an unterminated string sequence (OSC/DCS/APC) at an
433
+ // embedded ESC that introduces a new sequence so each reply is recognized
434
+ // and swallowed on its own.
435
+ const out: string[] = [];
436
+ let work = this.#buffer;
437
+ this.#buffer = "";
438
+
439
+ while (work.length > 0) {
440
+ const { sequences, remainder } = extractCompleteSequences(work);
441
+ out.push(...sequences);
442
+ if (remainder.length === 0) {
443
+ break;
444
+ }
445
+ // The remainder is an incomplete ESC-led fragment. If it absorbed a
446
+ // later sequence (an embedded ESC beyond the introducer), peel off the
447
+ // abandoned prefix and re-extract from the embedded boundary; otherwise
448
+ // it is a genuine trailing fragment (e.g. a lone Escape keypress or a
449
+ // half-arrived CSI) and is emitted as-is.
450
+ const embeddedEsc = remainder.indexOf(ESC, 1);
451
+ if (embeddedEsc > 0) {
452
+ out.push(remainder.slice(0, embeddedEsc));
453
+ work = remainder.slice(embeddedEsc);
454
+ } else {
455
+ out.push(remainder);
456
+ break;
457
+ }
458
+ }
459
+
460
+ return out;
461
+ }
462
+
463
+ clear(): void {
464
+ if (this.#timeout) {
465
+ clearTimeout(this.#timeout);
466
+ this.#timeout = undefined;
467
+ }
468
+ this.#buffer = "";
469
+ this.#pasteMode = false;
470
+ this.#pasteBuffer = "";
471
+ this.#pendingEscape = null;
472
+ }
473
+
474
+ getBuffer(): string {
475
+ return this.#buffer;
476
+ }
477
+
478
+ destroy(): void {
479
+ this.clear();
480
+ }
481
+ }
package/src/symbols.ts ADDED
@@ -0,0 +1,24 @@
1
+ export interface BoxSymbols {
2
+ topLeft: string;
3
+ topRight: string;
4
+ bottomLeft: string;
5
+ bottomRight: string;
6
+ horizontal: string;
7
+ vertical: string;
8
+ teeDown: string;
9
+ teeUp: string;
10
+ teeLeft: string;
11
+ teeRight: string;
12
+ cross: string;
13
+ }
14
+
15
+ export interface SymbolTheme {
16
+ cursor: string;
17
+ inputCursor: string;
18
+ boxRound: Omit<BoxSymbols, "teeDown" | "teeUp" | "teeLeft" | "teeRight" | "cross">;
19
+ boxSharp: BoxSymbols;
20
+ table: BoxSymbols;
21
+ quoteBorder: string;
22
+ hrChar: string;
23
+ spinnerFrames: string[];
24
+ }