termkit-ui 0.0.0-stage → 0.1.0

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +9 -0
  3. package/README.md +153 -2
  4. package/dist/components/display/layout.d.ts +91 -0
  5. package/dist/components/display/table.d.ts +53 -0
  6. package/dist/components/progress/index.d.ts +2 -0
  7. package/dist/components/progress/progressBar.d.ts +102 -0
  8. package/dist/components/progress/spinner.d.ts +107 -0
  9. package/dist/components/prompts/base.d.ts +53 -0
  10. package/dist/components/prompts/confirm.d.ts +46 -0
  11. package/dist/components/prompts/index.d.ts +6 -0
  12. package/dist/components/prompts/input.d.ts +46 -0
  13. package/dist/components/prompts/multiselect.d.ts +100 -0
  14. package/dist/components/prompts/number.d.ts +58 -0
  15. package/dist/components/prompts/password.d.ts +45 -0
  16. package/dist/components/prompts/select.d.ts +84 -0
  17. package/dist/core/ansi/escapes.d.ts +154 -0
  18. package/dist/core/caps/detect.d.ts +74 -0
  19. package/dist/core/errors/index.d.ts +73 -0
  20. package/dist/core/styles/index.d.ts +12 -0
  21. package/dist/core/width/string-width.d.ts +42 -0
  22. package/dist/engine/guard/terminal-guard.d.ts +84 -0
  23. package/dist/engine/keyboard/parser.d.ts +79 -0
  24. package/dist/engine/renderer/coordinator.d.ts +85 -0
  25. package/dist/index.d.ts +13 -0
  26. package/dist/testing/index.d.ts +127 -0
  27. package/package.json +77 -4
  28. package/src/components/display/layout.js +224 -0
  29. package/src/components/display/table.js +179 -0
  30. package/src/components/progress/index.js +6 -0
  31. package/src/components/progress/progressBar.js +153 -0
  32. package/src/components/progress/spinner.js +195 -0
  33. package/src/components/prompts/base.js +237 -0
  34. package/src/components/prompts/confirm.js +68 -0
  35. package/src/components/prompts/index.js +10 -0
  36. package/src/components/prompts/input.js +107 -0
  37. package/src/components/prompts/multiselect.js +205 -0
  38. package/src/components/prompts/number.js +140 -0
  39. package/src/components/prompts/password.js +77 -0
  40. package/src/components/prompts/select.js +171 -0
  41. package/src/core/ansi/escapes.js +52 -0
  42. package/src/core/caps/detect.js +167 -0
  43. package/src/core/errors/index.js +106 -0
  44. package/src/core/styles/index.js +174 -0
  45. package/src/core/width/string-width.js +244 -0
  46. package/src/engine/guard/terminal-guard.js +188 -0
  47. package/src/engine/keyboard/parser.js +285 -0
  48. package/src/engine/renderer/coordinator.js +263 -0
  49. package/src/index.js +17 -0
  50. package/src/testing/index.js +250 -0
@@ -0,0 +1,106 @@
1
+ /**
2
+ * @fileoverview Structured error hierarchy and stable error codes for TermKit.
3
+ */
4
+
5
+ /**
6
+ * Base error class for all TermKit errors.
7
+ */
8
+ export class TermKitError extends Error {
9
+ /**
10
+ * @param {string} message
11
+ * @param {string} [code='ERR_TERMKIT']
12
+ */
13
+ constructor(message, code = 'ERR_TERMKIT') {
14
+ super(message);
15
+ this.name = 'TermKitError';
16
+ /** @type {string} */
17
+ this.code = code;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Thrown when an interactive prompt or operation is cancelled by the user or signal.
23
+ */
24
+ export class CancelError extends TermKitError {
25
+ /**
26
+ * @param {string} [message]
27
+ * @param {'ctrl-c' | 'escape' | 'stream-closed' | 'abort'} [reason='ctrl-c']
28
+ */
29
+ constructor(message, reason = 'ctrl-c') {
30
+ super(message || `Prompt cancelled by user (${reason}).`, 'ERR_CANCELED');
31
+ this.name = 'CancelError';
32
+ /** @type {'ctrl-c' | 'escape' | 'stream-closed' | 'abort'} */
33
+ this.reason = reason;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Thrown when a prompt is invoked in a non-interactive environment without a default value.
39
+ */
40
+ export class NonInteractiveError extends TermKitError {
41
+ /**
42
+ * @param {string} promptName
43
+ * @param {string} [message]
44
+ */
45
+ constructor(promptName, message) {
46
+ super(
47
+ message ||
48
+ `Cannot prompt for '${promptName}' in a non-interactive environment without a default value.`,
49
+ 'ERR_NON_INTERACTIVE'
50
+ );
51
+ this.name = 'NonInteractiveError';
52
+ /** @type {string} */
53
+ this.promptName = promptName;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Thrown or reported when prompt validation fails.
59
+ * Guarantees that secret inputs are never echoed in error messages.
60
+ */
61
+ export class ValidationError extends TermKitError {
62
+ /**
63
+ * @param {string} promptName
64
+ * @param {string} validationMessage
65
+ * @param {boolean} [isSecret=false]
66
+ */
67
+ constructor(promptName, validationMessage, isSecret = false) {
68
+ super(validationMessage, 'ERR_VALIDATION');
69
+ this.name = 'ValidationError';
70
+ /** @type {string} */
71
+ this.promptName = promptName;
72
+ /** @type {boolean} */
73
+ this.isSecret = isSecret;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Thrown when invalid configuration options are supplied to a component.
79
+ */
80
+ export class ConfigurationError extends TermKitError {
81
+ /**
82
+ * @param {string} optionName
83
+ * @param {string} detail
84
+ */
85
+ constructor(optionName, detail) {
86
+ super(`Invalid configuration for option '${optionName}': ${detail}`, 'ERR_INVALID_CONFIG');
87
+ this.name = 'ConfigurationError';
88
+ /** @type {string} */
89
+ this.optionName = optionName;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Thrown when the target stream ends unexpectedly during an active component.
95
+ */
96
+ export class StreamClosedError extends TermKitError {
97
+ /**
98
+ * @param {'stdin' | 'stdout' | 'stderr'} stream
99
+ */
100
+ constructor(stream) {
101
+ super(`Stream '${stream}' closed unexpectedly.`, 'ERR_STREAM_CLOSED');
102
+ this.name = 'StreamClosedError';
103
+ /** @type {'stdin' | 'stdout' | 'stderr'} */
104
+ this.stream = stream;
105
+ }
106
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * @fileoverview Nesting-safe ANSI styling engine with color depth degradation.
3
+ */
4
+
5
+ import { SGR } from '../ansi/escapes.js';
6
+ import { detectCapabilities } from '../caps/detect.js';
7
+
8
+ /**
9
+ * RGB to 256-color palette converter.
10
+ * @param {number} r
11
+ * @param {number} g
12
+ * @param {number} b
13
+ * @returns {number}
14
+ */
15
+ function rgbTo256(r, g, b) {
16
+ if (r === g && g === b) {
17
+ if (r < 8) return 16;
18
+ if (r > 248) return 231;
19
+ return Math.round(((r - 8) / 247) * 23) + 232;
20
+ }
21
+ const rIdx = Math.round((r / 255) * 5);
22
+ const gIdx = Math.round((g / 255) * 5);
23
+ const bIdx = Math.round((b / 255) * 5);
24
+ return 16 + 36 * rIdx + 6 * gIdx + bIdx;
25
+ }
26
+
27
+ /**
28
+ * RGB to standard 16-color ANSI converter.
29
+ * @param {number} r
30
+ * @param {number} g
31
+ * @param {number} b
32
+ * @returns {number}
33
+ */
34
+ function rgbTo16(r, g, b) {
35
+ const code256 = rgbTo256(r, g, b);
36
+ if (code256 < 16) return code256;
37
+ const brightness = (r * 299 + g * 587 + b * 114) / 1000;
38
+ if (brightness < 64) return 30; // Black
39
+ if (r > g && r > b) return brightness > 160 ? 91 : 31; // Red
40
+ if (g > r && g > b) return brightness > 160 ? 92 : 32; // Green
41
+ if (r > 160 && g > 160 && b < 100) return brightness > 160 ? 93 : 33; // Yellow
42
+ if (b > r && b > g) return brightness > 160 ? 94 : 34; // Blue
43
+ if (r > 120 && b > 120 && g < 100) return brightness > 160 ? 95 : 35; // Magenta
44
+ if (g > 120 && b > 120 && r < 100) return brightness > 160 ? 96 : 36; // Cyan
45
+ return brightness > 160 ? 97 : 37; // White
46
+ }
47
+
48
+ /**
49
+ * Creates a nesting-safe styling instance with a specified color depth level.
50
+ * @param {Object} [options]
51
+ * @param {number} [options.colorLevel] - 0 (none), 1 (16), 2 (256), 3 (TrueColor)
52
+ */
53
+ export function createStyleEngine(options = {}) {
54
+ const caps = detectCapabilities();
55
+ const colorLevel = options.colorLevel !== undefined ? options.colorLevel : caps.colorLevel;
56
+
57
+ /**
58
+ * Applies open/close sequences with nesting safety.
59
+ * @param {string} open
60
+ * @param {string} close
61
+ * @param {string} text
62
+ * @returns {string}
63
+ */
64
+ function applyStyle(open, close, text) {
65
+ if (colorLevel === 0 || typeof text !== 'string' || text.length === 0) {
66
+ return String(text);
67
+ }
68
+ // Nesting safety: if text contains close sequence, reopen it immediately
69
+ const sanitized = text.includes(close) ? text.replaceAll(close, close + open) : text;
70
+ return `${open}${sanitized}${close}`;
71
+ }
72
+
73
+ /**
74
+ * Builds a chainable style function.
75
+ * @param {Array<{ open: string, close: string }>} modifiers
76
+ * @returns {any}
77
+ */
78
+ function buildStyler(modifiers = []) {
79
+ /**
80
+ * @param {any} input
81
+ * @returns {string}
82
+ */
83
+ const styler = function (input) {
84
+ let str = String(input);
85
+ if (colorLevel === 0) return str;
86
+ for (const mod of modifiers) {
87
+ str = applyStyle(mod.open, mod.close, str);
88
+ }
89
+ return str;
90
+ };
91
+
92
+ // Chainable modifier properties
93
+ const props = {
94
+ // Modifiers
95
+ bold: SGR.bold,
96
+ dim: SGR.dim,
97
+ italic: SGR.italic,
98
+ underline: SGR.underline,
99
+ inverse: SGR.inverse,
100
+ strikethrough: SGR.strikethrough,
101
+
102
+ // Colors
103
+ black: SGR.black,
104
+ red: SGR.red,
105
+ green: SGR.green,
106
+ yellow: SGR.yellow,
107
+ blue: SGR.blue,
108
+ magenta: SGR.magenta,
109
+ cyan: SGR.cyan,
110
+ white: SGR.white,
111
+ gray: SGR.gray,
112
+
113
+ // Backgrounds
114
+ bgBlack: SGR.bgBlack,
115
+ bgRed: SGR.bgRed,
116
+ bgGreen: SGR.bgGreen,
117
+ bgYellow: SGR.bgYellow,
118
+ bgBlue: SGR.bgBlue,
119
+ bgMagenta: SGR.bgMagenta,
120
+ bgCyan: SGR.bgCyan,
121
+ bgWhite: SGR.bgWhite
122
+ };
123
+
124
+ for (const [key, val] of Object.entries(props)) {
125
+ Object.defineProperty(styler, key, {
126
+ get() {
127
+ return buildStyler([...modifiers, val]);
128
+ }
129
+ });
130
+ }
131
+
132
+ // TrueColor / 256 / 16 color methods
133
+ /**
134
+ * @param {number} r
135
+ * @param {number} g
136
+ * @param {number} b
137
+ */
138
+ styler.rgb = function (r, g, b) {
139
+ let open = '';
140
+ if (colorLevel >= 3) {
141
+ open = `\x1b[38;2;${r};${g};${b}m`;
142
+ } else if (colorLevel === 2) {
143
+ open = `\x1b[38;5;${rgbTo256(r, g, b)}m`;
144
+ } else if (colorLevel === 1) {
145
+ open = `\x1b[${rgbTo16(r, g, b)}m`;
146
+ } else {
147
+ open = '';
148
+ }
149
+ return buildStyler([...modifiers, { open, close: '\x1b[39m' }]);
150
+ };
151
+
152
+ /**
153
+ * @param {string} hexCode
154
+ */
155
+ styler.hex = function (hexCode) {
156
+ const cleanHex = hexCode.replace(/^#/, '');
157
+ const num = parseInt(cleanHex, 16);
158
+ const r = (num >> 16) & 255;
159
+ const g = (num >> 8) & 255;
160
+ const b = num & 255;
161
+ return styler.rgb(r, g, b);
162
+ };
163
+
164
+ return styler;
165
+ }
166
+
167
+ return buildStyler();
168
+ }
169
+
170
+ /** Global default style function automatically configured by detected capabilities */
171
+ export const style = createStyleEngine();
172
+ export const colors = style;
173
+
174
+ export * from '../width/string-width.js';
@@ -0,0 +1,244 @@
1
+ /**
2
+ * @fileoverview Accurate Unicode and ANSI string width calculation.
3
+ * Zero external dependencies. Uses Intl.Segmenter, East Asian Width table, and grapheme analysis.
4
+ */
5
+
6
+ // ANSI Escape Code regular expression (covers SGR, CSI, OSC, and standard VT100 escapes)
7
+ const ANSI_REGEX =
8
+ /(?:\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\))|(?:\u001B\[[0-?]*[ -/]*[@-~])|[\u001B\u009B][[\]()#;?]*(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-ntqry=><~])/g;
9
+
10
+ /**
11
+ * Remove all ANSI escape codes from a string.
12
+ * @param {string} str
13
+ * @returns {string}
14
+ */
15
+ export function stripAnsi(str) {
16
+ if (typeof str !== 'string') return '';
17
+ return str.replace(ANSI_REGEX, '');
18
+ }
19
+
20
+ /**
21
+ * East Asian Width (EAW) ranges for Wide (W) and Fullwidth (F) characters.
22
+ * Extracted from Unicode 15.0 UAX #11.
23
+ * @type {Array<[number, number]>}
24
+ */
25
+ const EAW_RANGES = [
26
+ [0x1100, 0x115f], // Hangul Jamo
27
+ [0x231a, 0x231b], // Watch, Hourglass
28
+ [0x2329, 0x232a], // Left/right-pointing angle bracket
29
+ [0x2e80, 0x303e], // CJK Radicals Supplement .. CJK Symbols and Punctuation
30
+ [0x3040, 0x4dbf], // Hiragana .. CJK Unified Ideographs Extension A
31
+ [0x4e00, 0xa4cf], // CJK Unified Ideographs .. Yi Radicals
32
+ [0xac00, 0xd7a3], // Hangul Syllables
33
+ [0xf900, 0xfaff], // CJK Compatibility Ideographs
34
+ [0xfe10, 0xfe19], // Vertical Forms
35
+ [0xfe30, 0xfe6f], // CJK Compatibility Forms
36
+ [0xff01, 0xff60], // Fullwidth Forms
37
+ [0xffe0, 0xffe6], // Fullwidth Signs
38
+ [0x1f300, 0x1f64f], // Miscellaneous Symbols and Pictographs .. Emoticons
39
+ [0x1f900, 0x1f9ff], // Supplemental Symbols and Pictographs
40
+ [0x20000, 0x2fffd], // CJK Unified Ideographs Extension B ..
41
+ [0x30000, 0x3fffd] // CJK Unified Ideographs Extension G ..
42
+ ];
43
+
44
+ /**
45
+ * Binary search to check if a code point is East Asian Fullwidth or Wide.
46
+ * @param {number} codePoint
47
+ * @returns {boolean}
48
+ */
49
+ function isEastAsianWide(codePoint) {
50
+ let low = 0;
51
+ let high = EAW_RANGES.length - 1;
52
+ while (low <= high) {
53
+ const mid = (low + high) >> 1;
54
+ const [start, end] = EAW_RANGES[mid];
55
+ if (codePoint < start) {
56
+ high = mid - 1;
57
+ } else if (codePoint > end) {
58
+ low = mid + 1;
59
+ } else {
60
+ return true;
61
+ }
62
+ }
63
+ return false;
64
+ }
65
+
66
+ // Global cached Intl.Segmenter instance
67
+ /** @type {Intl.Segmenter | null} */
68
+ let segmenterInstance = null;
69
+
70
+ function getSegmenter() {
71
+ if (!segmenterInstance) {
72
+ segmenterInstance = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
73
+ }
74
+ return segmenterInstance;
75
+ }
76
+
77
+ /**
78
+ * Calculate the visual column width of a string in a terminal.
79
+ * Correctly strips ANSI escape codes and accounts for emojis, ZWJ sequences,
80
+ * East Asian characters, combining diacritics, and zero-width codes.
81
+ *
82
+ * @param {string} str
83
+ * @returns {number}
84
+ */
85
+ export function stringWidth(str) {
86
+ if (typeof str !== 'string' || str.length === 0) return 0;
87
+
88
+ // 1. Strip ANSI escape sequences
89
+ const clean = stripAnsi(str);
90
+ if (clean.length === 0) return 0;
91
+
92
+ // 2. Fast-path for pure printable ASCII
93
+ let isAsciiOnly = true;
94
+ for (let i = 0; i < clean.length; i++) {
95
+ const code = clean.charCodeAt(i);
96
+ if (code < 32 || code >= 127) {
97
+ isAsciiOnly = false;
98
+ break;
99
+ }
100
+ }
101
+ if (isAsciiOnly) {
102
+ return clean.length;
103
+ }
104
+
105
+ // 3. Segment into grapheme clusters
106
+ const segmenter = getSegmenter();
107
+ let totalWidth = 0;
108
+
109
+ for (const { segment } of segmenter.segment(clean)) {
110
+ const firstCodePoint = segment.codePointAt(0) || 0;
111
+
112
+ // Check zero-width characters (Control chars, ZWSP, soft hyphen, BOM)
113
+ if (
114
+ (firstCodePoint >= 0x0000 && firstCodePoint <= 0x001f) ||
115
+ (firstCodePoint >= 0x007f && firstCodePoint <= 0x009f) ||
116
+ firstCodePoint === 0x200b || // Zero Width Space
117
+ firstCodePoint === 0x200c || // Zero Width Non-Joiner
118
+ firstCodePoint === 0x200d || // Zero Width Joiner (standalone)
119
+ firstCodePoint === 0x00ad || // Soft Hyphen
120
+ firstCodePoint === 0xfeff // BOM
121
+ ) {
122
+ totalWidth += 0;
123
+ continue;
124
+ }
125
+
126
+ // Check combining diacritical marks (General Category M)
127
+ // Combining Diacritical Marks: 0x0300 - 0x036F
128
+ if (firstCodePoint >= 0x0300 && firstCodePoint <= 0x036f) {
129
+ totalWidth += 0;
130
+ continue;
131
+ }
132
+
133
+ // Check if segment is an emoji sequence (e.g., ZWJ, skin tone, regional flags)
134
+ // If segment contains ZWJ or regional indicator pair, or is in emoji ranges
135
+ if (
136
+ segment.includes('\u200D') || // ZWJ sequence (e.g. 👨‍👩‍👧‍👦, 👩‍💻)
137
+ (firstCodePoint >= 0x1f1e6 && firstCodePoint <= 0x1f1ff) || // Regional indicator flags
138
+ (firstCodePoint >= 0x1f300 && firstCodePoint <= 0x1faff) || // Symbols / Pictographs
139
+ (firstCodePoint >= 0x2600 && firstCodePoint <= 0x27bf) // Misc symbols (e.g. ⚡, ✈, ✨)
140
+ ) {
141
+ totalWidth += 2;
142
+ continue;
143
+ }
144
+
145
+ // Check East Asian Wide / Fullwidth characters
146
+ if (isEastAsianWide(firstCodePoint)) {
147
+ totalWidth += 2;
148
+ continue;
149
+ }
150
+
151
+ // Default standard character width
152
+ totalWidth += 1;
153
+ }
154
+
155
+ return totalWidth;
156
+ }
157
+
158
+ /**
159
+ * Alias for stringWidth.
160
+ * @param {string} str
161
+ * @returns {number}
162
+ */
163
+ export const visibleLength = stringWidth;
164
+
165
+ /**
166
+ * Truncate a string to a maximum visual column width, appending an optional ellipsis.
167
+ * Preserves ANSI styling codes.
168
+ *
169
+ * @param {string} str
170
+ * @param {number} maxWidth
171
+ * @param {string} [ellipsis]
172
+ * @returns {string}
173
+ */
174
+ export function truncate(str, maxWidth, ellipsis = '…') {
175
+ if (stringWidth(str) <= maxWidth) {
176
+ return str;
177
+ }
178
+
179
+ const finalEllipsis = ellipsis;
180
+ const ellipsisWidth = stringWidth(finalEllipsis);
181
+ const targetWidth = Math.max(0, maxWidth - ellipsisWidth);
182
+ const segmenter = getSegmenter();
183
+
184
+ let accumulatedWidth = 0;
185
+ let result = '';
186
+
187
+ for (const { segment } of segmenter.segment(str)) {
188
+ // If segment is ANSI sequence, always include it without incrementing width
189
+ if (segment.startsWith('\x1b')) {
190
+ result += segment;
191
+ continue;
192
+ }
193
+
194
+ const segWidth = stringWidth(segment);
195
+ if (accumulatedWidth + segWidth > targetWidth) {
196
+ break;
197
+ }
198
+ result += segment;
199
+ accumulatedWidth += segWidth;
200
+ }
201
+
202
+ return result + finalEllipsis;
203
+ }
204
+
205
+ /**
206
+ * Wrap text cleanly to fit within maxWidth columns.
207
+ *
208
+ * @param {string} str
209
+ * @param {number} maxWidth
210
+ * @returns {string[]}
211
+ */
212
+ export function wrapText(str, maxWidth) {
213
+ if (!str) return [''];
214
+ const lines = [];
215
+ const rawLines = str.split('\n');
216
+
217
+ for (const rawLine of rawLines) {
218
+ if (stringWidth(rawLine) <= maxWidth) {
219
+ lines.push(rawLine);
220
+ continue;
221
+ }
222
+
223
+ const words = rawLine.split(' ');
224
+ let currentLine = '';
225
+
226
+ for (const word of words) {
227
+ const testLine = currentLine.length === 0 ? word : `${currentLine} ${word}`;
228
+ if (stringWidth(testLine) <= maxWidth) {
229
+ currentLine = testLine;
230
+ } else {
231
+ if (currentLine.length > 0) {
232
+ lines.push(currentLine);
233
+ }
234
+ currentLine = word;
235
+ }
236
+ }
237
+
238
+ if (currentLine.length > 0) {
239
+ lines.push(currentLine);
240
+ }
241
+ }
242
+
243
+ return lines;
244
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * @fileoverview Terminal State Guard.
3
+ * Manages raw mode, cursor visibility, signal traps, and guaranteed exit cleanup.
4
+ */
5
+
6
+ /**
7
+ * @typedef {() => void} CleanupTask
8
+ */
9
+
10
+ class TerminalGuardManager {
11
+ constructor() {
12
+ /** @type {Set<CleanupTask>} */
13
+ this._cleanups = new Set();
14
+ /** @type {boolean} */
15
+ this._isRawMode = false;
16
+ /** @type {boolean} */
17
+ this._isCursorHidden = false;
18
+ /** @type {NodeJS.ReadableStream | null} */
19
+ this._rawStream = null;
20
+ /** @type {NodeJS.WritableStream | null} */
21
+ this._cursorStream = null;
22
+ /** @type {boolean} */
23
+ this._signalsAttached = false;
24
+
25
+ this._onSigInt = this._handleSignal.bind(this, 'SIGINT', 130);
26
+ this._onSigTerm = this._handleSignal.bind(this, 'SIGTERM', 143);
27
+ this._onExit = this.restore.bind(this);
28
+ this._onUncaughtException = this._handleException.bind(this);
29
+ }
30
+
31
+ /**
32
+ * Attach process signal handlers once.
33
+ * @private
34
+ */
35
+ _ensureSignals() {
36
+ if (this._signalsAttached) return;
37
+ this._signalsAttached = true;
38
+
39
+ process.on('SIGINT', this._onSigInt);
40
+ process.on('SIGTERM', this._onSigTerm);
41
+ process.on('exit', this._onExit);
42
+ process.on('uncaughtExceptionMonitor', this._onUncaughtException);
43
+ }
44
+
45
+ /**
46
+ * Detach process signal handlers if no cleanups remain.
47
+ * @private
48
+ */
49
+ _maybeDetachSignals() {
50
+ if (this._cleanups.size > 0 || this._isRawMode || this._isCursorHidden) return;
51
+ if (!this._signalsAttached) return;
52
+
53
+ process.removeListener('SIGINT', this._onSigInt);
54
+ process.removeListener('SIGTERM', this._onSigTerm);
55
+ process.removeListener('exit', this._onExit);
56
+ process.removeListener('uncaughtExceptionMonitor', this._onUncaughtException);
57
+ this._signalsAttached = false;
58
+ }
59
+
60
+ /**
61
+ * Signal handler for SIGINT/SIGTERM.
62
+ * @private
63
+ * @param {string} signal
64
+ * @param {number} exitCode
65
+ */
66
+ _handleSignal(signal, exitCode) {
67
+ this.restore();
68
+ // Allow default exit
69
+ process.exit(exitCode);
70
+ }
71
+
72
+ /**
73
+ * Exception monitor handler.
74
+ * @private
75
+ * @param {Error} error
76
+ */
77
+ _handleException(error) {
78
+ // Unconditionally restore terminal on crash without swallowing error
79
+ this.restore();
80
+ }
81
+
82
+ /**
83
+ * Register a custom cleanup task.
84
+ * @param {CleanupTask} cleanup
85
+ * @returns {() => void} Unsubscribe function
86
+ */
87
+ register(cleanup) {
88
+ this._cleanups.add(cleanup);
89
+ this._ensureSignals();
90
+ return () => {
91
+ this._cleanups.delete(cleanup);
92
+ this._maybeDetachSignals();
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Enable raw mode safely on an input stream.
98
+ * @param {NodeJS.ReadableStream} [stream]
99
+ */
100
+ enableRawMode(stream = process.stdin) {
101
+ this._ensureSignals();
102
+ const ttyStream = /** @type {any} */ (stream);
103
+ if (typeof ttyStream.setRawMode === 'function') {
104
+ ttyStream.setRawMode(true);
105
+ this._isRawMode = true;
106
+ this._rawStream = stream;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Disable raw mode safely.
112
+ */
113
+ disableRawMode() {
114
+ if (this._rawStream && typeof /** @type {any} */ (this._rawStream).setRawMode === 'function') {
115
+ try {
116
+ /** @type {any} */ (this._rawStream).setRawMode(false);
117
+ } catch {
118
+ // Ignore stream already closed
119
+ }
120
+ }
121
+ this._isRawMode = false;
122
+ this._rawStream = null;
123
+ this._maybeDetachSignals();
124
+ }
125
+
126
+ /**
127
+ * Hide the terminal cursor safely.
128
+ * @param {NodeJS.WritableStream} [stream]
129
+ */
130
+ hideCursor(stream = process.stderr) {
131
+ this._ensureSignals();
132
+ this._isCursorHidden = true;
133
+ this._cursorStream = stream;
134
+ try {
135
+ stream.write('\x1b[?25l');
136
+ } catch {
137
+ // Ignore write errors
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Show the terminal cursor safely.
143
+ * @param {NodeJS.WritableStream} [stream]
144
+ */
145
+ showCursor(stream = this._cursorStream || process.stderr) {
146
+ try {
147
+ stream.write('\x1b[?25h');
148
+ } catch {
149
+ // Ignore write errors
150
+ }
151
+ this._isCursorHidden = false;
152
+ this._cursorStream = null;
153
+ this._maybeDetachSignals();
154
+ }
155
+
156
+ /**
157
+ * Restore terminal to pristine state:
158
+ * Disables raw mode, shows cursor, and executes all registered cleanup callbacks.
159
+ */
160
+ restore() {
161
+ // 1. Show cursor
162
+ if (this._isCursorHidden) {
163
+ this.showCursor();
164
+ }
165
+
166
+ // 2. Disable raw mode
167
+ if (this._isRawMode) {
168
+ this.disableRawMode();
169
+ }
170
+
171
+ // 3. Execute registered cleanups in reverse order
172
+ const tasks = Array.from(this._cleanups).reverse();
173
+ for (const task of tasks) {
174
+ try {
175
+ task();
176
+ } catch {
177
+ // Continue restoring remaining tasks even if one fails
178
+ }
179
+ }
180
+ this._cleanups.clear();
181
+ this._maybeDetachSignals();
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Global singleton terminal state guard.
187
+ */
188
+ export const terminalGuard = new TerminalGuardManager();