@nuvin/ink 6.6.7 → 7.0.0-alpha

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 (149) hide show
  1. package/build/ansi-tokenizer.d.ts +38 -0
  2. package/build/ansi-tokenizer.js +316 -0
  3. package/build/ansi-tokenizer.js.map +1 -0
  4. package/build/components/AnimationContext.d.ts +9 -0
  5. package/build/components/AnimationContext.js +13 -0
  6. package/build/components/AnimationContext.js.map +1 -0
  7. package/build/components/App.d.ts +11 -49
  8. package/build/components/App.js +412 -227
  9. package/build/components/App.js.map +1 -1
  10. package/build/components/AppContext.d.ts +33 -3
  11. package/build/components/AppContext.js +2 -1
  12. package/build/components/AppContext.js.map +1 -1
  13. package/build/components/Box.d.ts +15 -8
  14. package/build/components/Box.js +12 -10
  15. package/build/components/Box.js.map +1 -1
  16. package/build/components/CursorContext.d.ts +11 -0
  17. package/build/components/CursorContext.js +8 -0
  18. package/build/components/CursorContext.js.map +1 -0
  19. package/build/components/ErrorBoundary.d.ts +18 -0
  20. package/build/components/ErrorBoundary.js +23 -0
  21. package/build/components/ErrorBoundary.js.map +1 -0
  22. package/build/components/ErrorOverview.js +6 -6
  23. package/build/components/ErrorOverview.js.map +1 -1
  24. package/build/components/Static.js.map +1 -1
  25. package/build/components/StdinContext.d.ts +7 -1
  26. package/build/components/StdinContext.js +1 -0
  27. package/build/components/StdinContext.js.map +1 -1
  28. package/build/components/Text.d.ts +1 -1
  29. package/build/components/Text.js +1 -1
  30. package/build/components/Text.js.map +1 -1
  31. package/build/components/Transform.d.ts +1 -1
  32. package/build/cursor-helpers.d.ts +38 -0
  33. package/build/cursor-helpers.js +56 -0
  34. package/build/cursor-helpers.js.map +1 -0
  35. package/build/devtools-window-polyfill.js +7 -4
  36. package/build/devtools-window-polyfill.js.map +1 -1
  37. package/build/devtools.js +31 -6
  38. package/build/devtools.js.map +1 -1
  39. package/build/dom.d.ts +5 -1
  40. package/build/dom.js +20 -1
  41. package/build/dom.js.map +1 -1
  42. package/build/hooks/use-animation.d.ts +49 -0
  43. package/build/hooks/use-animation.js +87 -0
  44. package/build/hooks/use-animation.js.map +1 -0
  45. package/build/hooks/use-app.d.ts +5 -2
  46. package/build/hooks/use-app.js +1 -1
  47. package/build/hooks/use-box-metrics.d.ts +59 -0
  48. package/build/hooks/use-box-metrics.js +88 -0
  49. package/build/hooks/use-box-metrics.js.map +1 -0
  50. package/build/hooks/use-cursor.d.ts +12 -0
  51. package/build/hooks/use-cursor.js +29 -0
  52. package/build/hooks/use-cursor.js.map +1 -0
  53. package/build/hooks/use-focus-manager.d.ts +17 -2
  54. package/build/hooks/use-focus-manager.js +2 -1
  55. package/build/hooks/use-focus-manager.js.map +1 -1
  56. package/build/hooks/use-focus.d.ts +2 -1
  57. package/build/hooks/use-focus.js +5 -4
  58. package/build/hooks/use-focus.js.map +1 -1
  59. package/build/hooks/use-input.d.ts +40 -1
  60. package/build/hooks/use-input.js +84 -51
  61. package/build/hooks/use-input.js.map +1 -1
  62. package/build/hooks/use-is-screen-reader-enabled.d.ts +2 -1
  63. package/build/hooks/use-is-screen-reader-enabled.js +2 -1
  64. package/build/hooks/use-is-screen-reader-enabled.js.map +1 -1
  65. package/build/hooks/use-paste.d.ts +35 -0
  66. package/build/hooks/use-paste.js +62 -0
  67. package/build/hooks/use-paste.js.map +1 -0
  68. package/build/hooks/use-stderr.d.ts +1 -1
  69. package/build/hooks/use-stderr.js +1 -1
  70. package/build/hooks/use-stdin.d.ts +4 -2
  71. package/build/hooks/use-stdin.js +2 -1
  72. package/build/hooks/use-stdin.js.map +1 -1
  73. package/build/hooks/use-stdout.d.ts +1 -1
  74. package/build/hooks/use-stdout.js +1 -1
  75. package/build/hooks/use-window-size.d.ts +18 -0
  76. package/build/hooks/use-window-size.js +22 -0
  77. package/build/hooks/use-window-size.js.map +1 -0
  78. package/build/index.d.ts +14 -1
  79. package/build/index.js +7 -0
  80. package/build/index.js.map +1 -1
  81. package/build/ink.d.ts +86 -5
  82. package/build/ink.js +581 -80
  83. package/build/ink.js.map +1 -1
  84. package/build/input-parser.d.ts +10 -0
  85. package/build/input-parser.js +194 -0
  86. package/build/input-parser.js.map +1 -0
  87. package/build/kitty-keyboard.d.ts +23 -0
  88. package/build/kitty-keyboard.js +32 -0
  89. package/build/kitty-keyboard.js.map +1 -0
  90. package/build/log-update.d.ts +7 -1
  91. package/build/log-update.js +181 -56
  92. package/build/log-update.js.map +1 -1
  93. package/build/measure-element.d.ts +4 -0
  94. package/build/measure-element.js +4 -0
  95. package/build/measure-element.js.map +1 -1
  96. package/build/measure-text.js +3 -11
  97. package/build/measure-text.js.map +1 -1
  98. package/build/output.d.ts +2 -1
  99. package/build/output.js +62 -58
  100. package/build/output.js.map +1 -1
  101. package/build/parse-keypress.d.ts +9 -3
  102. package/build/parse-keypress.js +283 -13
  103. package/build/parse-keypress.js.map +1 -1
  104. package/build/reconciler.js +57 -37
  105. package/build/reconciler.js.map +1 -1
  106. package/build/render-background.js +2 -0
  107. package/build/render-background.js.map +1 -1
  108. package/build/render-border.d.ts +1 -1
  109. package/build/render-border.js +35 -24
  110. package/build/render-border.js.map +1 -1
  111. package/build/render-node-to-output.d.ts +1 -1
  112. package/build/render-node-to-output.js +35 -18
  113. package/build/render-node-to-output.js.map +1 -1
  114. package/build/render-to-string.d.ts +38 -0
  115. package/build/render-to-string.js +116 -0
  116. package/build/render-to-string.js.map +1 -0
  117. package/build/render.d.ts +91 -3
  118. package/build/render.js +17 -5
  119. package/build/render.js.map +1 -1
  120. package/build/sanitize-ansi.d.ts +2 -0
  121. package/build/sanitize-ansi.js +27 -0
  122. package/build/sanitize-ansi.js.map +1 -0
  123. package/build/squash-text-nodes.js +2 -1
  124. package/build/squash-text-nodes.js.map +1 -1
  125. package/build/styles.d.ts +75 -37
  126. package/build/styles.js +87 -44
  127. package/build/styles.js.map +1 -1
  128. package/build/utils.d.ts +9 -2
  129. package/build/utils.js +18 -3
  130. package/build/utils.js.map +1 -1
  131. package/build/wrap-text.js +7 -14
  132. package/build/wrap-text.js.map +1 -1
  133. package/build/write-synchronized.d.ts +4 -0
  134. package/build/write-synchronized.js +9 -0
  135. package/build/write-synchronized.js.map +1 -0
  136. package/package.json +45 -105
  137. package/readme.md +850 -64
  138. package/build/components/FixedLayout.d.ts +0 -12
  139. package/build/components/FixedLayout.js +0 -19
  140. package/build/components/FixedLayout.js.map +0 -1
  141. package/build/components/VirtualizedList.d.ts +0 -21
  142. package/build/components/VirtualizedList.js +0 -55
  143. package/build/components/VirtualizedList.js.map +0 -1
  144. package/build/hooks/use-mouse.d.ts +0 -15
  145. package/build/hooks/use-mouse.js +0 -121
  146. package/build/hooks/use-mouse.js.map +0 -1
  147. package/build/hooks/use-virtualization.d.ts +0 -19
  148. package/build/hooks/use-virtualization.js +0 -56
  149. package/build/hooks/use-virtualization.js.map +0 -1
package/build/ink.js CHANGED
@@ -6,26 +6,143 @@ import isInCi from 'is-in-ci';
6
6
  import autoBind from 'auto-bind';
7
7
  import signalExit from 'signal-exit';
8
8
  import patchConsole from 'patch-console';
9
- import { LegacyRoot } from 'react-reconciler/constants.js';
9
+ import { LegacyRoot, ConcurrentRoot } from 'react-reconciler/constants.js';
10
10
  import Yoga from 'yoga-layout';
11
11
  import wrapAnsi from 'wrap-ansi';
12
- import { isDev } from './utils.js';
12
+ import { getWindowSize } from './utils.js';
13
13
  import reconciler from './reconciler.js';
14
14
  import render from './renderer.js';
15
15
  import * as dom from './dom.js';
16
+ import { hideCursorEscape, showCursorEscape } from './cursor-helpers.js';
16
17
  import logUpdate from './log-update.js';
18
+ import { bsu, esu, shouldSynchronize } from './write-synchronized.js';
17
19
  import instances from './instances.js';
18
20
  import App from './components/App.js';
19
21
  import { accessibilityContext as AccessibilityContext } from './components/AccessibilityContext.js';
22
+ import { resolveFlags, } from './kitty-keyboard.js';
20
23
  const noop = () => { };
24
+ const textEncoder = new TextEncoder();
25
+ const yieldImmediate = async () => new Promise(resolve => {
26
+ setImmediate(resolve);
27
+ });
28
+ const kittyQueryEscapeByte = 0x1b;
29
+ const kittyQueryOpenBracketByte = 0x5b;
30
+ const kittyQueryQuestionMarkByte = 0x3f;
31
+ const kittyQueryLetterByte = 0x75;
32
+ const zeroByte = 0x30;
33
+ const nineByte = 0x39;
34
+ const isDigitByte = (byte) => byte >= zeroByte && byte <= nineByte;
35
+ const matchKittyQueryResponse = (buffer, startIndex) => {
36
+ if (buffer[startIndex] !== kittyQueryEscapeByte ||
37
+ buffer[startIndex + 1] !== kittyQueryOpenBracketByte ||
38
+ buffer[startIndex + 2] !== kittyQueryQuestionMarkByte) {
39
+ return undefined;
40
+ }
41
+ let index = startIndex + 3;
42
+ const digitsStartIndex = index;
43
+ while (index < buffer.length && isDigitByte(buffer[index])) {
44
+ index++;
45
+ }
46
+ if (index === digitsStartIndex) {
47
+ return undefined;
48
+ }
49
+ if (index === buffer.length) {
50
+ return { state: 'partial' };
51
+ }
52
+ if (buffer[index] === kittyQueryLetterByte) {
53
+ return { state: 'complete', endIndex: index };
54
+ }
55
+ return undefined;
56
+ };
57
+ const hasCompleteKittyQueryResponse = (buffer) => {
58
+ for (let index = 0; index < buffer.length; index++) {
59
+ const match = matchKittyQueryResponse(buffer, index);
60
+ if (match?.state === 'complete') {
61
+ return true;
62
+ }
63
+ }
64
+ return false;
65
+ };
66
+ const stripKittyQueryResponsesAndTrailingPartial = (buffer) => {
67
+ const keptBytes = [];
68
+ let index = 0;
69
+ while (index < buffer.length) {
70
+ const match = matchKittyQueryResponse(buffer, index);
71
+ if (match?.state === 'complete') {
72
+ index = match.endIndex + 1;
73
+ continue;
74
+ }
75
+ if (match?.state === 'partial') {
76
+ break;
77
+ }
78
+ keptBytes.push(buffer[index]);
79
+ index++;
80
+ }
81
+ return keptBytes;
82
+ };
83
+ const shouldClearTerminalForFrame = ({ isTty, viewportRows, previousOutputHeight, nextOutputHeight, isUnmounting, }) => {
84
+ if (!isTty) {
85
+ return false;
86
+ }
87
+ const hadPreviousFrame = previousOutputHeight > 0;
88
+ const wasFullscreen = previousOutputHeight >= viewportRows;
89
+ const wasOverflowing = previousOutputHeight > viewportRows;
90
+ const isOverflowing = nextOutputHeight > viewportRows;
91
+ const isLeavingFullscreen = wasFullscreen && nextOutputHeight < viewportRows;
92
+ const shouldClearOnUnmount = isUnmounting && wasFullscreen;
93
+ return (
94
+ // Overflowing frames still need full clear fallback.
95
+ wasOverflowing ||
96
+ (isOverflowing && hadPreviousFrame) ||
97
+ // Clear when shrinking from fullscreen to non-fullscreen output.
98
+ isLeavingFullscreen ||
99
+ // Preserve legacy unmount behavior for fullscreen frames: final teardown
100
+ // render should clear once to avoid leaving a scrolled viewport state.
101
+ shouldClearOnUnmount);
102
+ };
103
+ const isErrorInput = (value) => {
104
+ return (value instanceof Error ||
105
+ Object.prototype.toString.call(value) === '[object Error]');
106
+ };
107
+ const getWritableStreamState = (stdout) => {
108
+ const canWriteToStdout = !stdout.destroyed && !stdout.writableEnded && (stdout.writable ?? true);
109
+ const hasWritableState = stdout._writableState !== undefined || stdout.writableLength !== undefined;
110
+ return {
111
+ canWriteToStdout,
112
+ hasWritableState,
113
+ };
114
+ };
115
+ const settleThrottle = (throttled, canWriteToStdout) => {
116
+ if (!throttled ||
117
+ typeof throttled.flush !== 'function') {
118
+ return;
119
+ }
120
+ const throttledValue = throttled;
121
+ if (canWriteToStdout) {
122
+ throttledValue.flush();
123
+ }
124
+ else if (typeof throttledValue.cancel === 'function') {
125
+ throttledValue.cancel();
126
+ }
127
+ };
21
128
  export default class Ink {
129
+ /**
130
+ Whether this instance is using concurrent rendering mode.
131
+ */
132
+ isConcurrent;
22
133
  options;
23
134
  log;
135
+ cursorPosition;
24
136
  throttledLog;
25
137
  isScreenReaderEnabled;
138
+ interactive;
139
+ renderThrottleMs;
140
+ alternateScreen;
26
141
  // Ignore last render after unmounting a tree to prevent empty output before exit
27
142
  isUnmounted;
143
+ isUnmounting;
28
144
  lastOutput;
145
+ lastOutputToRender;
29
146
  lastOutputHeight;
30
147
  lastTerminalWidth;
31
148
  container;
@@ -34,8 +151,15 @@ export default class Ink {
34
151
  // so that it's rerendered every time, not just new static parts, like in non-debug mode
35
152
  fullStaticOutput;
36
153
  exitPromise;
154
+ exitResult;
155
+ beforeExitHandler;
37
156
  restoreConsole;
38
157
  unsubscribeResize;
158
+ throttledOnRender;
159
+ hasPendingThrottledRender = false;
160
+ kittyProtocolEnabled = false;
161
+ cancelKittyDetection;
162
+ nextRenderCommit;
39
163
  constructor(options) {
40
164
  autoBind(this);
41
165
  this.options = options;
@@ -44,63 +168,103 @@ export default class Ink {
44
168
  this.isScreenReaderEnabled =
45
169
  options.isScreenReaderEnabled ??
46
170
  process.env['INK_SCREEN_READER'] === 'true';
171
+ // CI detection takes precedence: even a TTY stdout in CI defaults to non-interactive.
172
+ // Using Boolean(isTTY) (rather than an 'in' guard) correctly handles piped streams
173
+ // where the property is absent (e.g. `node app.js | cat`).
174
+ this.interactive = this.resolveInteractiveOption(options.interactive);
175
+ this.alternateScreen = false;
47
176
  const unthrottled = options.debug || this.isScreenReaderEnabled;
48
177
  const maxFps = options.maxFps ?? 30;
178
+ // Treat non-positive maxFps as an internal fallback case, not a supported
179
+ // "disable throttling" mode. Keep animation scheduling on a normal cadence
180
+ // so future changes don't accidentally reintroduce zero-delay loops.
49
181
  const renderThrottleMs = maxFps > 0 ? Math.max(1, Math.ceil(1000 / maxFps)) : 0;
50
- this.rootNode.onRender = unthrottled
51
- ? this.onRender
52
- : throttle(this.onRender, renderThrottleMs, {
182
+ this.renderThrottleMs = unthrottled ? 0 : renderThrottleMs;
183
+ if (unthrottled) {
184
+ this.rootNode.onRender = this.onRender;
185
+ this.throttledOnRender = undefined;
186
+ }
187
+ else {
188
+ const throttled = throttle(this.onRender, renderThrottleMs, {
53
189
  leading: true,
54
190
  trailing: true,
55
191
  });
192
+ this.rootNode.onRender = () => {
193
+ this.hasPendingThrottledRender = true;
194
+ throttled();
195
+ };
196
+ this.throttledOnRender = throttled;
197
+ }
56
198
  this.rootNode.onImmediateRender = this.onRender;
57
199
  this.log = logUpdate.create(options.stdout, {
58
200
  incremental: options.incrementalRendering,
59
201
  });
202
+ this.cursorPosition = undefined;
60
203
  this.throttledLog = unthrottled
61
204
  ? this.log
62
- : throttle(this.log, undefined, {
205
+ : throttle((output) => {
206
+ const shouldWrite = this.log.willRender(output);
207
+ const sync = this.shouldSync();
208
+ if (sync && shouldWrite) {
209
+ this.options.stdout.write(bsu);
210
+ }
211
+ this.log(output);
212
+ if (sync && shouldWrite) {
213
+ this.options.stdout.write(esu);
214
+ }
215
+ }, undefined, {
63
216
  leading: true,
64
217
  trailing: true,
65
218
  });
66
219
  // Ignore last render after unmounting a tree to prevent empty output before exit
67
220
  this.isUnmounted = false;
221
+ this.isUnmounting = false;
222
+ // Store concurrent mode setting
223
+ this.isConcurrent = options.concurrent ?? false;
68
224
  // Store last output to only rerender when needed
69
225
  this.lastOutput = '';
226
+ this.lastOutputToRender = '';
70
227
  this.lastOutputHeight = 0;
71
- this.lastTerminalWidth = this.getTerminalWidth();
228
+ this.lastTerminalWidth = getWindowSize(this.options.stdout).columns;
72
229
  // This variable is used only in debug mode to store full static output
73
230
  // so that it's rerendered every time, not just new static parts, like in non-debug mode
74
231
  this.fullStaticOutput = '';
232
+ // Use ConcurrentRoot for concurrent mode, LegacyRoot for legacy mode
233
+ const rootTag = options.concurrent ? ConcurrentRoot : LegacyRoot;
75
234
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
76
- this.container = reconciler.createContainer(this.rootNode, LegacyRoot, null, false, null, 'id', () => { }, () => { }, () => { }, () => { }, null);
235
+ this.container = reconciler.createContainer(this.rootNode, rootTag, null, false, null, 'id', () => { }, () => { }, () => { }, () => { });
77
236
  // Unmount when process exits
78
237
  this.unsubscribeExit = signalExit(this.unmount, { alwaysLast: false });
79
- if (isDev()) {
238
+ this.setAlternateScreen(Boolean(options.alternateScreen));
239
+ if (process.env['DEV'] === 'true') {
80
240
  // @ts-expect-error outdated types
81
241
  reconciler.injectIntoDevTools();
82
242
  }
83
243
  if (options.patchConsole) {
84
244
  this.patchConsole();
85
245
  }
86
- if (!isInCi) {
246
+ if (this.interactive) {
87
247
  options.stdout.on('resize', this.resized);
88
248
  this.unsubscribeResize = () => {
89
249
  options.stdout.off('resize', this.resized);
90
250
  };
91
251
  }
252
+ this.initKittyKeyboard();
253
+ this.exitPromise = new Promise((resolve, reject) => {
254
+ this.resolveExitPromise = resolve;
255
+ this.rejectExitPromise = reject;
256
+ });
257
+ // Prevent global unhandled-rejection crashes when app code exits with an
258
+ // error but consumers never call waitUntilExit().
259
+ void this.exitPromise.catch(noop);
92
260
  }
93
- getTerminalWidth = () => {
94
- // The 'columns' property can be undefined or 0 when not using a TTY.
95
- // In that case we fall back to 80.
96
- return this.options.stdout.columns || 80;
97
- };
98
261
  resized = () => {
99
- const currentWidth = this.getTerminalWidth();
262
+ const currentWidth = getWindowSize(this.options.stdout).columns;
100
263
  if (currentWidth < this.lastTerminalWidth) {
101
264
  // We clear the screen when decreasing terminal width to prevent duplicate overlapping re-renders.
102
265
  this.log.clear();
103
266
  this.lastOutput = '';
267
+ this.lastOutputToRender = '';
104
268
  }
105
269
  this.calculateLayout();
106
270
  this.onRender();
@@ -109,15 +273,44 @@ export default class Ink {
109
273
  resolveExitPromise = () => { };
110
274
  rejectExitPromise = () => { };
111
275
  unsubscribeExit = () => { };
276
+ handleAppExit = (errorOrResult) => {
277
+ if (this.isUnmounted || this.isUnmounting) {
278
+ return;
279
+ }
280
+ if (isErrorInput(errorOrResult)) {
281
+ this.unmount(errorOrResult);
282
+ return;
283
+ }
284
+ this.exitResult = errorOrResult;
285
+ this.unmount();
286
+ };
287
+ setCursorPosition = (position) => {
288
+ this.cursorPosition = position;
289
+ this.log.setCursorPosition(position);
290
+ };
291
+ restoreLastOutput = () => {
292
+ if (!this.interactive) {
293
+ return;
294
+ }
295
+ // Clear() resets log-update's cursor state, so replay the latest cursor intent
296
+ // before restoring output after external stdout/stderr writes.
297
+ this.log.setCursorPosition(this.cursorPosition);
298
+ this.log(this.lastOutputToRender || this.lastOutput + '\n');
299
+ };
112
300
  calculateLayout = () => {
113
- const terminalWidth = this.getTerminalWidth();
301
+ const terminalWidth = getWindowSize(this.options.stdout).columns;
114
302
  this.rootNode.yogaNode.setWidth(terminalWidth);
115
303
  this.rootNode.yogaNode.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
116
304
  };
117
305
  onRender = () => {
306
+ this.hasPendingThrottledRender = false;
118
307
  if (this.isUnmounted) {
119
308
  return;
120
309
  }
310
+ if (this.nextRenderCommit) {
311
+ this.nextRenderCommit.resolve();
312
+ this.nextRenderCommit = undefined;
313
+ }
121
314
  const startTime = performance.now();
122
315
  const { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);
123
316
  this.options.onRender?.({ renderTime: performance.now() - startTime });
@@ -127,18 +320,26 @@ export default class Ink {
127
320
  if (hasStaticOutput) {
128
321
  this.fullStaticOutput += staticOutput;
129
322
  }
323
+ this.lastOutput = output;
324
+ this.lastOutputToRender = output;
325
+ this.lastOutputHeight = outputHeight;
130
326
  this.options.stdout.write(this.fullStaticOutput + output);
131
327
  return;
132
328
  }
133
- if (isInCi) {
329
+ if (!this.interactive) {
134
330
  if (hasStaticOutput) {
135
331
  this.options.stdout.write(staticOutput);
136
332
  }
137
333
  this.lastOutput = output;
334
+ this.lastOutputToRender = output + '\n';
138
335
  this.lastOutputHeight = outputHeight;
139
336
  return;
140
337
  }
141
338
  if (this.isScreenReaderEnabled) {
339
+ const sync = this.shouldSync();
340
+ if (sync) {
341
+ this.options.stdout.write(bsu);
342
+ }
142
343
  if (hasStaticOutput) {
143
344
  // We need to erase the main output before writing new static output
144
345
  const erase = this.lastOutputHeight > 0
@@ -149,9 +350,12 @@ export default class Ink {
149
350
  this.lastOutputHeight = 0;
150
351
  }
151
352
  if (output === this.lastOutput && !hasStaticOutput) {
353
+ if (sync) {
354
+ this.options.stdout.write(esu);
355
+ }
152
356
  return;
153
357
  }
154
- const terminalWidth = this.options.stdout.columns || 80;
358
+ const terminalWidth = getWindowSize(this.options.stdout).columns;
155
359
  const wrappedOutput = wrapAnsi(output, terminalWidth, {
156
360
  trim: false,
157
361
  hard: true,
@@ -167,42 +371,31 @@ export default class Ink {
167
371
  this.options.stdout.write(erase + wrappedOutput);
168
372
  }
169
373
  this.lastOutput = output;
374
+ this.lastOutputToRender = wrappedOutput;
170
375
  this.lastOutputHeight =
171
376
  wrappedOutput === '' ? 0 : wrappedOutput.split('\n').length;
377
+ if (sync) {
378
+ this.options.stdout.write(esu);
379
+ }
172
380
  return;
173
381
  }
174
382
  if (hasStaticOutput) {
175
383
  this.fullStaticOutput += staticOutput;
176
384
  }
177
- if (!this.options.incrementalRendering &&
178
- this.lastOutputHeight >= this.options.stdout.rows) {
179
- this.options.stdout.write(ansiEscapes.clearTerminal + this.fullStaticOutput + output);
180
- this.lastOutput = output;
181
- this.lastOutputHeight = outputHeight;
182
- this.log.sync(output);
183
- return;
184
- }
185
- // To ensure static output is cleanly rendered before main output, clear main output first
186
- if (hasStaticOutput) {
187
- this.log.clear();
188
- this.options.stdout.write(staticOutput);
189
- this.log(output);
190
- }
191
- if (!hasStaticOutput && output !== this.lastOutput) {
192
- this.throttledLog(output);
193
- }
194
- this.lastOutput = output;
195
- this.lastOutputHeight = outputHeight;
385
+ this.renderInteractiveFrame(output, outputHeight, hasStaticOutput ? staticOutput : '');
196
386
  };
197
387
  render(node) {
198
388
  const tree = (React.createElement(AccessibilityContext.Provider, { value: { isScreenReaderEnabled: this.isScreenReaderEnabled } },
199
- React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, exitOnCtrlC: this.options.exitOnCtrlC, onExit: this.unmount }, node)));
200
- // @ts-expect-error the types for `react-reconciler` are not up to date with the library.
201
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
202
- reconciler.updateContainerSync(tree, this.container, null, noop);
203
- // @ts-expect-error the types for `react-reconciler` are not up to date with the library.
204
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
205
- reconciler.flushSyncWork();
389
+ React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, exitOnCtrlC: this.options.exitOnCtrlC, interactive: this.interactive, renderThrottleMs: this.renderThrottleMs, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, setCursorPosition: this.setCursorPosition, onExit: this.handleAppExit, onWaitUntilRenderFlush: this.waitUntilRenderFlush }, node)));
390
+ if (this.options.concurrent) {
391
+ // Concurrent mode: use updateContainer (async scheduling)
392
+ reconciler.updateContainer(tree, this.container, null, noop);
393
+ }
394
+ else {
395
+ // Legacy mode: use updateContainerSync + flushSyncWork (sync)
396
+ reconciler.updateContainerSync(tree, this.container, null, noop);
397
+ reconciler.flushSyncWork();
398
+ }
206
399
  }
207
400
  writeToStdout(data) {
208
401
  if (this.isUnmounted) {
@@ -212,13 +405,20 @@ export default class Ink {
212
405
  this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);
213
406
  return;
214
407
  }
215
- if (isInCi) {
408
+ if (!this.interactive) {
216
409
  this.options.stdout.write(data);
217
410
  return;
218
411
  }
412
+ const sync = this.shouldSync();
413
+ if (sync) {
414
+ this.options.stdout.write(bsu);
415
+ }
219
416
  this.log.clear();
220
417
  this.options.stdout.write(data);
221
- this.log(this.lastOutput);
418
+ this.restoreLastOutput();
419
+ if (sync) {
420
+ this.options.stdout.write(esu);
421
+ }
222
422
  }
223
423
  writeToStderr(data) {
224
424
  if (this.isUnmounted) {
@@ -229,61 +429,192 @@ export default class Ink {
229
429
  this.options.stdout.write(this.fullStaticOutput + this.lastOutput);
230
430
  return;
231
431
  }
232
- if (isInCi) {
432
+ if (!this.interactive) {
233
433
  this.options.stderr.write(data);
234
434
  return;
235
435
  }
436
+ const sync = this.shouldSync();
437
+ if (sync) {
438
+ this.options.stdout.write(bsu);
439
+ }
236
440
  this.log.clear();
237
441
  this.options.stderr.write(data);
238
- this.log(this.lastOutput);
442
+ this.restoreLastOutput();
443
+ if (sync) {
444
+ this.options.stdout.write(esu);
445
+ }
239
446
  }
240
- // eslint-disable-next-line @typescript-eslint/ban-types
447
+ // eslint-disable-next-line @typescript-eslint/no-restricted-types
241
448
  unmount(error) {
242
- if (this.isUnmounted) {
449
+ if (this.isUnmounted || this.isUnmounting) {
243
450
  return;
244
451
  }
245
- this.calculateLayout();
246
- this.onRender();
452
+ this.isUnmounting = true;
453
+ if (this.beforeExitHandler) {
454
+ process.off('beforeExit', this.beforeExitHandler);
455
+ this.beforeExitHandler = undefined;
456
+ }
457
+ const stdout = this.options.stdout;
458
+ const { canWriteToStdout, hasWritableState } = getWritableStreamState(stdout);
459
+ // Clear any pending throttled render timer on unmount. When stdout is writable,
460
+ // flush so the final frame is emitted; otherwise cancel to avoid delayed callbacks.
461
+ settleThrottle(this.throttledOnRender, canWriteToStdout);
462
+ if (canWriteToStdout) {
463
+ // If throttling is enabled and there is already a pending render, flushing above
464
+ // is sufficient. Also avoid calling onRender() again when static output already
465
+ // exists, as that can duplicate <Static> children output on exit (see issue #397).
466
+ const shouldRenderFinalFrame = !this.throttledOnRender ||
467
+ (!this.hasPendingThrottledRender && this.fullStaticOutput === '');
468
+ if (shouldRenderFinalFrame) {
469
+ this.calculateLayout();
470
+ this.onRender();
471
+ }
472
+ }
473
+ // Mark as unmounted after the final render but before stdout writes
474
+ // that could re-enter exit() via synchronous write callbacks.
475
+ this.isUnmounted = true;
247
476
  this.unsubscribeExit();
477
+ // Flush any pending throttled log writes if possible, otherwise cancel to
478
+ // prevent delayed callbacks from writing to a closed stream.
479
+ settleThrottle(this.throttledLog, canWriteToStdout);
248
480
  if (typeof this.restoreConsole === 'function') {
481
+ // Once unmount starts, Ink stops trying to manage teardown-time
482
+ // console output. Restoring the native console before React cleanup keeps
483
+ // unmount behavior simple and avoids special-case handling for custom
484
+ // streams, fullscreen frames, and alternate-screen teardown.
249
485
  this.restoreConsole();
250
486
  }
251
- if (typeof this.unsubscribeResize === 'function') {
252
- this.unsubscribeResize();
253
- }
254
- // CIs don't handle erasing ansi escapes well, so it's better to
255
- // only render last frame of non-static output
256
- if (isInCi) {
257
- this.options.stdout.write(this.lastOutput + '\n');
258
- }
259
- else if (!this.options.debug) {
260
- this.log.done();
261
- }
262
- this.isUnmounted = true;
263
- // @ts-expect-error the types for `react-reconciler` are not up to date with the library.
264
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
265
- reconciler.updateContainerSync(null, this.container, null, noop);
266
- // @ts-expect-error the types for `react-reconciler` are not up to date with the library.
267
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
268
- reconciler.flushSyncWork();
269
- instances.delete(this.options.stdout);
270
- if (error instanceof Error) {
271
- this.rejectExitPromise(error);
487
+ const finishUnmount = () => {
488
+ if (typeof this.unsubscribeResize === 'function') {
489
+ this.unsubscribeResize();
490
+ }
491
+ // Cancel any in-progress auto-detection before checking protocol state
492
+ if (this.cancelKittyDetection) {
493
+ this.cancelKittyDetection();
494
+ }
495
+ if (canWriteToStdout) {
496
+ if (this.kittyProtocolEnabled) {
497
+ this.writeBestEffort(this.options.stdout, '\u001B[<u');
498
+ }
499
+ // Alternate-screen content is disposable by design. We intentionally
500
+ // leave it active until React cleanup finishes, then restore the
501
+ // primary buffer without replaying prior frames, hook writes, or
502
+ // diagnostics onto it. Trying to preserve teardown output across the
503
+ // buffer switch adds fragile lifecycle-specific behavior, so Ink keeps
504
+ // alternate-screen teardown intentionally simple and best-effort.
505
+ if (this.alternateScreen) {
506
+ this.writeBestEffort(this.options.stdout, ansiEscapes.exitAlternativeScreen);
507
+ this.writeBestEffort(this.options.stdout, showCursorEscape);
508
+ this.alternateScreen = false;
509
+ }
510
+ if (!this.interactive) {
511
+ // Non-interactive environments don't handle erasing ansi escapes well.
512
+ // In debug mode, each render already writes to stdout, so only a trailing
513
+ // newline is needed. In non-debug mode, write the last frame now (it was
514
+ // deferred during rendering).
515
+ this.options.stdout.write(this.options.debug ? '\n' : this.lastOutput + '\n');
516
+ }
517
+ else if (!this.options.debug) {
518
+ this.log.done();
519
+ }
520
+ }
521
+ this.kittyProtocolEnabled = false;
522
+ instances.delete(this.options.stdout);
523
+ // Ensure all queued writes have been processed before resolving the
524
+ // exit promise. For real writable streams, queue an empty write as a
525
+ // barrier — its callback fires only after all prior writes complete.
526
+ // For non-stream objects (e.g. test spies), resolve on next tick.
527
+ //
528
+ // When called from signal-exit during process shutdown (error is a
529
+ // number or null rather than undefined/Error), resolve synchronously
530
+ // because the event loop is draining and async callbacks won't fire.
531
+ const { exitResult } = this;
532
+ const resolveOrReject = () => {
533
+ if (isErrorInput(error)) {
534
+ this.rejectExitPromise(error);
535
+ }
536
+ else {
537
+ this.resolveExitPromise(exitResult);
538
+ }
539
+ };
540
+ const isProcessExiting = error !== undefined && !isErrorInput(error);
541
+ if (isProcessExiting) {
542
+ resolveOrReject();
543
+ }
544
+ else if (canWriteToStdout && hasWritableState) {
545
+ this.options.stdout.write('', resolveOrReject);
546
+ }
547
+ else {
548
+ setImmediate(resolveOrReject);
549
+ }
550
+ };
551
+ const concurrentReconciler = reconciler;
552
+ if (this.options.concurrent) {
553
+ reconciler.updateContainerSync(null, this.container, null, noop);
554
+ reconciler.flushSyncWork();
555
+ concurrentReconciler.flushPassiveEffects?.();
556
+ finishUnmount();
272
557
  }
273
558
  else {
274
- this.resolveExitPromise();
559
+ // Legacy mode: use updateContainerSync + flushSyncWork (sync)
560
+ reconciler.updateContainerSync(null, this.container, null, noop);
561
+ reconciler.flushSyncWork();
562
+ finishUnmount();
275
563
  }
276
564
  }
277
565
  async waitUntilExit() {
278
- this.exitPromise ||= new Promise((resolve, reject) => {
279
- this.resolveExitPromise = resolve;
280
- this.rejectExitPromise = reject;
281
- });
566
+ if (!this.beforeExitHandler) {
567
+ this.beforeExitHandler = () => {
568
+ this.unmount();
569
+ };
570
+ process.once('beforeExit', this.beforeExitHandler);
571
+ }
282
572
  return this.exitPromise;
283
573
  }
574
+ async waitUntilRenderFlush() {
575
+ if (this.isUnmounted || this.isUnmounting) {
576
+ await this.awaitExit();
577
+ return;
578
+ }
579
+ // Yield to the macrotask queue so that React's scheduler has a chance to
580
+ // fire passive effects and process any work they enqueued.
581
+ await yieldImmediate();
582
+ if (this.isUnmounted || this.isUnmounting) {
583
+ await this.awaitExit();
584
+ return;
585
+ }
586
+ // In concurrent mode, React's scheduler may still be mid-render after
587
+ // the yield. Wait for the next render commit instead of polling.
588
+ if (this.isConcurrent && this.hasPendingConcurrentWork()) {
589
+ await Promise.race([this.awaitNextRender(), this.awaitExit()]);
590
+ if (this.isUnmounted || this.isUnmounting) {
591
+ this.nextRenderCommit = undefined;
592
+ await this.awaitExit();
593
+ return;
594
+ }
595
+ }
596
+ reconciler.flushSyncWork();
597
+ const stdout = this.options.stdout;
598
+ const { canWriteToStdout, hasWritableState } = getWritableStreamState(stdout);
599
+ // Flush pending throttled render/log timers so their output is included in this wait.
600
+ settleThrottle(this.throttledOnRender, canWriteToStdout);
601
+ settleThrottle(this.throttledLog, canWriteToStdout);
602
+ if (canWriteToStdout && hasWritableState) {
603
+ await new Promise(resolve => {
604
+ this.options.stdout.write('', () => {
605
+ resolve();
606
+ });
607
+ });
608
+ return;
609
+ }
610
+ await yieldImmediate();
611
+ }
284
612
  clear() {
285
- if (!isInCi && !this.options.debug) {
613
+ if (this.interactive && !this.options.debug) {
286
614
  this.log.clear();
615
+ // Sync lastOutput so that unmount's final onRender
616
+ // sees it as unchanged and log-update skips it
617
+ this.log.sync(this.lastOutputToRender || this.lastOutput + '\n');
287
618
  }
288
619
  }
289
620
  patchConsole() {
@@ -302,5 +633,175 @@ export default class Ink {
302
633
  }
303
634
  });
304
635
  }
636
+ setAlternateScreen(enabled) {
637
+ this.alternateScreen = this.resolveAlternateScreenOption(enabled, this.interactive);
638
+ if (this.alternateScreen) {
639
+ this.writeBestEffort(this.options.stdout, ansiEscapes.enterAlternativeScreen);
640
+ this.writeBestEffort(this.options.stdout, hideCursorEscape);
641
+ }
642
+ }
643
+ resolveInteractiveOption(interactive) {
644
+ return interactive ?? (!isInCi && Boolean(this.options.stdout.isTTY));
645
+ }
646
+ resolveAlternateScreenOption(alternateScreen, interactive) {
647
+ return (Boolean(alternateScreen) &&
648
+ interactive &&
649
+ Boolean(this.options.stdout.isTTY));
650
+ }
651
+ shouldSync() {
652
+ return shouldSynchronize(this.options.stdout, this.interactive);
653
+ }
654
+ // Best-effort write: streams may already be destroyed during shutdown.
655
+ writeBestEffort(stream, data) {
656
+ try {
657
+ stream.write(data);
658
+ }
659
+ catch { }
660
+ }
661
+ // Waits for the exit promise to settle, suppressing any rejection.
662
+ // Errors are surfaced via waitUntilExit() instead.
663
+ async awaitExit() {
664
+ try {
665
+ await this.exitPromise;
666
+ }
667
+ catch { }
668
+ }
669
+ hasPendingConcurrentWork() {
670
+ const concurrentContainer = this.container;
671
+ return ((concurrentContainer.pendingLanes ?? 0) !== 0 &&
672
+ concurrentContainer.callbackNode !== undefined &&
673
+ concurrentContainer.callbackNode !== null);
674
+ }
675
+ async awaitNextRender() {
676
+ if (!this.nextRenderCommit) {
677
+ let resolveRender;
678
+ const promise = new Promise(resolve => {
679
+ resolveRender = resolve;
680
+ });
681
+ this.nextRenderCommit = { promise, resolve: resolveRender };
682
+ }
683
+ return this.nextRenderCommit.promise;
684
+ }
685
+ renderInteractiveFrame(output, outputHeight, staticOutput) {
686
+ const hasStaticOutput = staticOutput !== '';
687
+ const isTty = this.options.stdout.isTTY;
688
+ // Detect fullscreen: output fills or exceeds terminal height.
689
+ // Only apply when writing to a real TTY — piped output always gets trailing newlines.
690
+ const viewportRows = isTty ? getWindowSize(this.options.stdout).rows : 24;
691
+ const isFullscreen = isTty && outputHeight >= viewportRows;
692
+ const outputToRender = isFullscreen ? output : output + '\n';
693
+ const shouldClearTerminal = shouldClearTerminalForFrame({
694
+ isTty,
695
+ viewportRows,
696
+ previousOutputHeight: this.lastOutputHeight,
697
+ nextOutputHeight: outputHeight,
698
+ isUnmounting: this.isUnmounting,
699
+ });
700
+ if (shouldClearTerminal) {
701
+ const sync = this.shouldSync();
702
+ if (sync) {
703
+ this.options.stdout.write(bsu);
704
+ }
705
+ this.options.stdout.write(ansiEscapes.clearTerminal + this.fullStaticOutput + output);
706
+ this.lastOutput = output;
707
+ this.lastOutputToRender = outputToRender;
708
+ this.lastOutputHeight = outputHeight;
709
+ this.log.sync(outputToRender);
710
+ if (sync) {
711
+ this.options.stdout.write(esu);
712
+ }
713
+ return;
714
+ }
715
+ // To ensure static output is cleanly rendered before main output, clear main output first
716
+ if (hasStaticOutput) {
717
+ const sync = this.shouldSync();
718
+ if (sync) {
719
+ this.options.stdout.write(bsu);
720
+ }
721
+ this.log.clear();
722
+ this.options.stdout.write(staticOutput);
723
+ this.log(outputToRender);
724
+ if (sync) {
725
+ this.options.stdout.write(esu);
726
+ }
727
+ }
728
+ else if (output !== this.lastOutput || this.log.isCursorDirty()) {
729
+ // ThrottledLog manages its own bsu/esu at actual write time
730
+ this.throttledLog(outputToRender);
731
+ }
732
+ this.lastOutput = output;
733
+ this.lastOutputToRender = outputToRender;
734
+ this.lastOutputHeight = outputHeight;
735
+ }
736
+ initKittyKeyboard() {
737
+ // Protocol is opt-in: if kittyKeyboard is not specified, do nothing
738
+ if (!this.options.kittyKeyboard) {
739
+ return;
740
+ }
741
+ const opts = this.options.kittyKeyboard;
742
+ const mode = opts.mode ?? 'auto';
743
+ if (mode === 'disabled') {
744
+ return;
745
+ }
746
+ const flags = opts.flags ?? ['disambiguateEscapeCodes'];
747
+ // 'enabled' force-enables the protocol as long as both streams are TTYs,
748
+ // regardless of the interactive setting (e.g. even in CI).
749
+ if (mode === 'enabled') {
750
+ if (this.options.stdin.isTTY && this.options.stdout.isTTY) {
751
+ this.enableKittyProtocol(flags);
752
+ }
753
+ return;
754
+ }
755
+ // Auto mode: require interactive + TTY
756
+ if (!this.interactive ||
757
+ !this.options.stdin.isTTY ||
758
+ !this.options.stdout.isTTY) {
759
+ return;
760
+ }
761
+ // Auto mode: query the terminal for kitty keyboard protocol support.
762
+ // The CSI ? u query is safe to send to any terminal — unsupporting
763
+ // terminals simply won't respond, and the 200ms timeout handles that.
764
+ // This avoids maintaining a hardcoded whitelist of terminal names.
765
+ this.confirmKittySupport(flags);
766
+ }
767
+ confirmKittySupport(flags) {
768
+ const { stdin, stdout } = this.options;
769
+ let responseBuffer = [];
770
+ const cleanup = () => {
771
+ this.cancelKittyDetection = undefined;
772
+ clearTimeout(timer);
773
+ stdin.removeListener('data', onData);
774
+ // Re-emit any buffered data that wasn't the protocol response,
775
+ // so it isn't lost from Ink's normal input pipeline.
776
+ // Clear responseBuffer afterwards to make cleanup idempotent.
777
+ const remaining = stripKittyQueryResponsesAndTrailingPartial(responseBuffer);
778
+ responseBuffer = [];
779
+ if (remaining.length > 0) {
780
+ stdin.unshift(Uint8Array.from(remaining));
781
+ }
782
+ };
783
+ const onData = (data) => {
784
+ const chunk = typeof data === 'string' ? textEncoder.encode(data) : data;
785
+ for (const byte of chunk) {
786
+ responseBuffer.push(byte);
787
+ }
788
+ if (hasCompleteKittyQueryResponse(responseBuffer)) {
789
+ cleanup();
790
+ if (!this.isUnmounted) {
791
+ this.enableKittyProtocol(flags);
792
+ }
793
+ }
794
+ };
795
+ // Attach listener before writing the query so that synchronous
796
+ // or immediate responses are not missed.
797
+ stdin.on('data', onData);
798
+ const timer = setTimeout(cleanup, 200);
799
+ this.cancelKittyDetection = cleanup;
800
+ stdout.write('\u001B[?u');
801
+ }
802
+ enableKittyProtocol(flags) {
803
+ this.options.stdout.write(`\u001B[>${resolveFlags(flags)}u`);
804
+ this.kittyProtocolEnabled = true;
805
+ }
305
806
  }
306
807
  //# sourceMappingURL=ink.js.map