@opentui/core 0.8.0 → 0.8.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.
Files changed (36) hide show
  1. package/NativeScene.d.ts +10 -2
  2. package/NativeSession.d.ts +22 -2
  3. package/buffer.d.ts +2 -0
  4. package/{chunk-bun-6kxdhkdc.js → chunk-bun-vd3rj9kv.js} +451 -74
  5. package/{chunk-bun-6kxdhkdc.js.map → chunk-bun-vd3rj9kv.js.map} +10 -10
  6. package/{chunk-bun-x6cz4jyg.js → chunk-bun-wdetc10w.js} +222 -10
  7. package/chunk-bun-wdetc10w.js.map +35 -0
  8. package/{chunk-node-y0w0hq5m.js → chunk-node-m8mjyx7h.js} +222 -10
  9. package/chunk-node-m8mjyx7h.js.map +34 -0
  10. package/{chunk-node-q5ccgbk5.js → chunk-node-s9be55eh.js} +451 -74
  11. package/{chunk-node-q5ccgbk5.js.map → chunk-node-s9be55eh.js.map} +10 -10
  12. package/index.bun.js +684 -415
  13. package/index.bun.js.map +13 -12
  14. package/index.d.ts +1 -1
  15. package/index.node.js +684 -415
  16. package/index.node.js.map +13 -11
  17. package/native-abi.generated.d.ts +171 -3
  18. package/package.json +9 -9
  19. package/renderables/Image.d.ts +13 -1
  20. package/renderables/LineNumberRenderable.d.ts +1 -1
  21. package/renderables/Markdown.d.ts +1 -6
  22. package/renderables/ScrollBox.d.ts +1 -1
  23. package/renderables/Select.d.ts +0 -2
  24. package/renderables/TabSelect.d.ts +0 -3
  25. package/renderables/TextTable.d.ts +1 -8
  26. package/renderables/Video.d.ts +126 -0
  27. package/renderables/index.d.ts +1 -0
  28. package/renderables/markdown-parser.d.ts +1 -0
  29. package/renderer.d.ts +23 -2
  30. package/testing.bun.js +2 -2
  31. package/testing.js +2 -2
  32. package/yoga.bun.js +1 -1
  33. package/yoga.js +1 -1
  34. package/zig.d.ts +54 -2
  35. package/chunk-bun-x6cz4jyg.js.map +0 -35
  36. package/chunk-node-y0w0hq5m.js.map +0 -34
@@ -65,7 +65,7 @@ import {
65
65
  PositionType2,
66
66
  Unit2,
67
67
  Wrap2
68
- } from "./chunk-bun-x6cz4jyg.js";
68
+ } from "./chunk-bun-wdetc10w.js";
69
69
 
70
70
  // src/lib/border.ts
71
71
  var VALID_BORDER_STYLES = ["single", "double", "rounded", "heavy"];
@@ -3223,9 +3223,6 @@ function renderFontToFrameBuffer2(buffer, {
3223
3223
  return { width: 0, height: 0 };
3224
3224
  }
3225
3225
  const colors = Array.isArray(color) ? color : [color];
3226
- if (y < 0 || y + fontDef.lines > height) {
3227
- return { width: 0, height: fontDef.lines };
3228
- }
3229
3226
  let currentX = x;
3230
3227
  const startX = x;
3231
3228
  for (let i = 0;i < text.length; i++) {
@@ -9921,6 +9918,12 @@ class OptimizedBuffer2 {
9921
9918
  this.drawText(afterText, x + end, y, fg, bg, attributes);
9922
9919
  }
9923
9920
  }
9921
+ drawTextFit(text, x, y, maxWidth, fg, bg, ellipsis = false) {
9922
+ this.guard();
9923
+ if (maxWidth < 1)
9924
+ return;
9925
+ this.drawChecked({ operation: "text", text, x, y, maxWidth, ellipsis, foreground: fg, background: bg });
9926
+ }
9924
9927
  fillRect(x, y, width, height, bg) {
9925
9928
  this.guard();
9926
9929
  if (width <= 0 || height <= 0)
@@ -14749,7 +14752,7 @@ class CodeRenderable2 extends TextBufferRenderable2 {
14749
14752
  if (this._content === value)
14750
14753
  return;
14751
14754
  this.runMutation(() => {
14752
- if (this._streaming && this._filetype && !this._drawUnstyledText) {
14755
+ if (this._hadInitialContent && this._shouldRenderTextBuffer && this._filetype && !this._drawUnstyledText) {
14753
14756
  this._content = value;
14754
14757
  this.invalidateHighlights();
14755
14758
  this.requestRender();
@@ -14921,7 +14924,8 @@ class CodeRenderable2 extends TextBufferRenderable2 {
14921
14924
  const isInitialContent = this._streaming && !this._hadInitialContent;
14922
14925
  const shouldDrawUnstyledNow = this._streaming ? isInitialContent && this._drawUnstyledText : this._drawUnstyledText;
14923
14926
  if (this._streaming && !isInitialContent) {
14924
- this.setShouldRenderTextBuffer(true);
14927
+ if (this._drawUnstyledText)
14928
+ this.setShouldRenderTextBuffer(true);
14925
14929
  } else if (shouldDrawUnstyledNow) {
14926
14930
  if (this._initialStyledText) {
14927
14931
  this.textBuffer.setStyledText(this._initialStyledText);
@@ -15827,6 +15831,18 @@ function resolveImageRenderProtocol2(requested, capabilities, hasResolution) {
15827
15831
  return "sixel";
15828
15832
  return "blocks";
15829
15833
  }
15834
+ function checkCrop2(crop, width = Infinity, height = Infinity) {
15835
+ const { left, top, width: cropWidth, height: cropHeight } = crop;
15836
+ const u32 = (value, min) => Number.isInteger(value) && value >= min && value <= 4294967295;
15837
+ if (!u32(left, 0) || !u32(top, 0) || !u32(cropWidth, 1) || !u32(cropHeight, 1))
15838
+ throw new RangeError("crop needs u32 left and top and a positive u32 width and height");
15839
+ if (left + cropWidth > width || top + cropHeight > height)
15840
+ throw new RangeError(`crop ${cropWidth}x${cropHeight} at ${left},${top} lies outside the ${width}x${height} source`);
15841
+ return { left, top, width: cropWidth, height: cropHeight };
15842
+ }
15843
+ function sameCrop2(a, b) {
15844
+ return a === b || !!a && !!b && a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;
15845
+ }
15830
15846
  function pixelResolution(ctx) {
15831
15847
  const terminalWidth = ctx.terminalWidth ?? 0;
15832
15848
  const terminalHeight = ctx.terminalHeight ?? 0;
@@ -15848,6 +15864,7 @@ class ImageRenderable2 extends Renderable2 {
15848
15864
  onLoad;
15849
15865
  onError;
15850
15866
  _fit;
15867
+ _crop;
15851
15868
  _protocol;
15852
15869
  loadPromise = null;
15853
15870
  constructor(ctx, options) {
@@ -15860,6 +15877,7 @@ class ImageRenderable2 extends Renderable2 {
15860
15877
  this.setNativeSceneImage();
15861
15878
  if (options.source !== undefined)
15862
15879
  this.source = options.source;
15880
+ this.crop = options.crop;
15863
15881
  } catch (error) {
15864
15882
  this.abortConstruction(error, () => this.destroySelf());
15865
15883
  }
@@ -15923,6 +15941,19 @@ class ImageRenderable2 extends Renderable2 {
15923
15941
  this._fit = next;
15924
15942
  this.requestRender();
15925
15943
  }
15944
+ get crop() {
15945
+ return this._crop && { ...this._crop };
15946
+ }
15947
+ set crop(value) {
15948
+ if (sameCrop2(this._crop, value ?? undefined) || this.isDestroyed)
15949
+ return;
15950
+ const next = this.acceptCrop(value ?? undefined, this._loadController ? null : this._image);
15951
+ if (next === null)
15952
+ return;
15953
+ this._ctx.nativeScene.setCrop(this, next);
15954
+ this._crop = next;
15955
+ this.requestRender();
15956
+ }
15926
15957
  get protocol() {
15927
15958
  return this._protocol;
15928
15959
  }
@@ -15945,7 +15976,7 @@ class ImageRenderable2 extends Renderable2 {
15945
15976
  const cellHeight = resolution.height / this._ctx.terminalHeight;
15946
15977
  return cellWidth > 0 && cellHeight > 0 ? cellHeight / cellWidth : 2;
15947
15978
  }
15948
- getFittedSize(targetWidth, targetHeight, cellAspectRatio = this.cellAspectRatio, sourceWidth = this._image?.width ?? 0, sourceHeight = this._image?.height ?? 0) {
15979
+ getFittedSize(targetWidth, targetHeight, cellAspectRatio = this.cellAspectRatio, sourceWidth = this.region()?.width ?? 0, sourceHeight = this.region()?.height ?? 0) {
15949
15980
  if (sourceWidth <= 0 || sourceHeight <= 0 || targetWidth <= 0 || targetHeight <= 0)
15950
15981
  return { width: 0, height: 0 };
15951
15982
  if (this._fit === "fill")
@@ -15994,19 +16025,17 @@ class ImageRenderable2 extends Renderable2 {
15994
16025
  const resolution = pixelResolution(this._ctx);
15995
16026
  const pixelWidth = resolution ? Math.max(1, Math.round(fitted.width * resolution.width / this._ctx.terminalWidth)) : 0;
15996
16027
  const pixelHeight = resolution ? Math.max(1, Math.round(fitted.height * resolution.height / this._ctx.terminalHeight)) : 0;
15997
- let sourceX = 0;
15998
- let sourceY = 0;
15999
- let sourceWidth = this._image.width;
16000
- let sourceHeight = this._image.height;
16028
+ const region = this.region();
16029
+ let { left: sourceX, top: sourceY, width: sourceWidth, height: sourceHeight } = region;
16001
16030
  if (this._fit === "cover") {
16002
16031
  const targetAspect = width / (height * this.cellAspectRatio);
16003
16032
  const sourceAspect = sourceWidth / sourceHeight;
16004
16033
  if (sourceAspect > targetAspect) {
16005
16034
  sourceWidth = Math.max(1, Math.round(sourceHeight * targetAspect));
16006
- sourceX = Math.floor((this._image.width - sourceWidth) / 2);
16035
+ sourceX += Math.floor((region.width - sourceWidth) / 2);
16007
16036
  } else {
16008
16037
  sourceHeight = Math.max(1, Math.round(sourceWidth / targetAspect));
16009
- sourceY = Math.floor((this._image.height - sourceHeight) / 2);
16038
+ sourceY += Math.floor((region.height - sourceHeight) / 2);
16010
16039
  }
16011
16040
  }
16012
16041
  buffer.drawImage(this._image, x, y, fitted.width, fitted.height, pixelWidth, pixelHeight, sourceX, sourceY, sourceWidth, sourceHeight, this._protocol);
@@ -16039,9 +16068,27 @@ class ImageRenderable2 extends Renderable2 {
16039
16068
  this.runCleanup((run) => {
16040
16069
  run(() => previous?.dispose());
16041
16070
  run(() => this.requestRender());
16071
+ run(() => this.acceptCrop(this._crop, image));
16042
16072
  run(() => this.onLoad?.(image));
16043
16073
  });
16044
16074
  }
16075
+ region() {
16076
+ const image = this._image;
16077
+ if (!image)
16078
+ return null;
16079
+ const crop = this._crop;
16080
+ if (crop && crop.left + crop.width <= image.width && crop.top + crop.height <= image.height)
16081
+ return crop;
16082
+ return { left: 0, top: 0, width: image.width, height: image.height };
16083
+ }
16084
+ acceptCrop(crop, image) {
16085
+ try {
16086
+ return crop && checkCrop2(crop, image?.width, image?.height);
16087
+ } catch (error) {
16088
+ queueMicrotask(() => this.isDestroyed || this.onError?.(error));
16089
+ return null;
16090
+ }
16091
+ }
16045
16092
  setNativeSceneImage(image = this._image, fit = this._fit, protocol = this._protocol) {
16046
16093
  this._ctx.nativeScene.setImage(this, image, fit, protocol, this.buffered ? this.frameBuffer : null);
16047
16094
  }
@@ -16531,6 +16578,15 @@ var scheduler = {
16531
16578
  }
16532
16579
  };
16533
16580
  var emptyOutput = new Uint8Array(0);
16581
+ var stdoutBudget = 65536;
16582
+ var immediatePolls = 64;
16583
+ var immediateAgeNs = 500000n;
16584
+ registerEnvVar2({
16585
+ name: "OTUI_STDOUT_THREAD",
16586
+ description: "Write terminal stdout from a native thread so slow links never block the JS thread; false keeps it on the JS thread.",
16587
+ type: "boolean",
16588
+ default: true
16589
+ });
16534
16590
 
16535
16591
  class ReadySessions {
16536
16592
  host;
@@ -16699,13 +16755,18 @@ class NativeSession2 {
16699
16755
  closeWait = completion();
16700
16756
  idleWait = null;
16701
16757
  presentationWait = null;
16758
+ imageUploadsPending = 0;
16702
16759
  transition = null;
16703
16760
  scheduled = null;
16704
16761
  output = null;
16762
+ stdoutPost = null;
16763
+ stdoutWriter;
16705
16764
  blocked = false;
16706
16765
  sinkErrorSeen = false;
16707
16766
  detached = false;
16708
16767
  closeDeadlineNs = null;
16768
+ closeCapNs = null;
16769
+ closeLate = null;
16709
16770
  closeRequested = false;
16710
16771
  closeInterruption = null;
16711
16772
  stopped = false;
@@ -16738,6 +16799,7 @@ class NativeSession2 {
16738
16799
  this.sinkWrite = sink.write;
16739
16800
  this.outputBufferSize = size;
16740
16801
  this.buffer = sink === process.stdout && process.stdout.fd === 1 ? null : new Uint8Array(size);
16802
+ this.stdoutWriter = this.buffer === null && env2.OTUI_STDOUT_THREAD !== false;
16741
16803
  this.scheduler = sessionScheduler(options.scheduler ?? scheduler, (error) => {
16742
16804
  if (this.stopped) {
16743
16805
  if (this.canDetach())
@@ -16795,6 +16857,9 @@ class NativeSession2 {
16795
16857
  get error() {
16796
16858
  return this._error;
16797
16859
  }
16860
+ get open() {
16861
+ return !this._error && !this.closeRequested && !this.exiting;
16862
+ }
16798
16863
  usesOutput(sink) {
16799
16864
  return this.sink === sink;
16800
16865
  }
@@ -16854,8 +16919,11 @@ class NativeSession2 {
16854
16919
  this.checkOpen();
16855
16920
  if (this.presentationWait)
16856
16921
  return this.presentationWait.promise;
16857
- if (!this.lib.sessionGetRendererState(this.context, this.session).framePending)
16922
+ const state = this.lib.sessionGetRendererState(this.context, this.session);
16923
+ if (!state.framePending) {
16924
+ this.imageUploadsPending = state.imageUploadsPending;
16858
16925
  return Promise.resolve();
16926
+ }
16859
16927
  const wait = this.presentationWait = completion();
16860
16928
  this.schedule();
16861
16929
  return wait.promise;
@@ -16955,6 +17023,7 @@ class NativeSession2 {
16955
17023
  try {
16956
17024
  this.closeRequested = true;
16957
17025
  this.closeDeadlineNs ??= this.scheduler.now() + this.closeTimeoutNs;
17026
+ this.closeCapNs ??= this.scheduler.now() + 10n * this.closeTimeoutNs;
16958
17027
  if (this.transition) {
16959
17028
  this.closeInterruption = new Error("NativeSession terminal transition interrupted by close");
16960
17029
  this.transition.wait.reject(this.closeInterruption);
@@ -16975,10 +17044,11 @@ class NativeSession2 {
16975
17044
  armCloseTimeout() {
16976
17045
  this.checkOpen();
16977
17046
  this.closeDeadlineNs ??= this.scheduler.now() + this.closeTimeoutNs;
17047
+ this.closeCapNs ??= this.scheduler.now() + 10n * this.closeTimeoutNs;
16978
17048
  this.schedule();
16979
17049
  }
16980
17050
  isCloseInterruption(error) {
16981
- return this.closeInterruption !== null && error === this.closeInterruption;
17051
+ return error != null && (error === this.closeInterruption || error === this.closeLate);
16982
17052
  }
16983
17053
  dispose() {
16984
17054
  this.lib.getYogaHost().assertMutable();
@@ -16998,6 +17068,10 @@ class NativeSession2 {
16998
17068
  this.lib.sessionCompleteOutput(this.context, this.session, this.output.ticket, true);
16999
17069
  this.output = null;
17000
17070
  }
17071
+ let viaWriter = this.stdoutWriter && (this.lib.sessionPostStdout(this.context, this.session, 0, true).written > 0 || !this.stdoutPost);
17072
+ this.stdoutPost = null;
17073
+ if (this.closeCapNs !== null)
17074
+ this.lib.sessionDropOutput(this.context, this.session);
17001
17075
  for (;; ) {
17002
17076
  const status = this.lib.sessionPumpExit(this.context, this.session);
17003
17077
  if (status === 4 /* Closed */)
@@ -17006,6 +17080,11 @@ class NativeSession2 {
17006
17080
  continue;
17007
17081
  if (status !== 2 /* OutputPending */)
17008
17082
  throw new Error("Unexpected native exit pump status");
17083
+ if (viaWriter) {
17084
+ if (this.exitThroughWriter())
17085
+ continue;
17086
+ viaWriter = false;
17087
+ }
17009
17088
  if (this.lib.sessionDrainStdout(this.context, this.session) === 0)
17010
17089
  return false;
17011
17090
  }
@@ -17014,12 +17093,23 @@ class NativeSession2 {
17014
17093
  return false;
17015
17094
  }
17016
17095
  }
17096
+ exitThroughWriter() {
17097
+ try {
17098
+ if (!this.lib.sessionPostStdout(this.context, this.session, stdoutBudget, false).inFlight)
17099
+ return false;
17100
+ } catch (error) {
17101
+ if (error instanceof NativeError2 && error.status === -24 /* UnsupportedResource */)
17102
+ return false;
17103
+ throw error;
17104
+ }
17105
+ return this.lib.sessionPostStdout(this.context, this.session, 0, true).written > 0;
17106
+ }
17017
17107
  checkOpen() {
17018
17108
  this.lib.getYogaHost().assertMutable();
17019
17109
  if (this._error)
17020
17110
  throw this._error;
17021
17111
  if (this.stopped || this.closeRequested)
17022
- throw new Error("NativeSession is closing or disposed");
17112
+ throw this.closeLate ?? new Error("NativeSession is closing or disposed");
17023
17113
  this.owner?.checkOpen();
17024
17114
  }
17025
17115
  changeTerminal(kind, options) {
@@ -17116,19 +17206,40 @@ class NativeSession2 {
17116
17206
  if (this._error)
17117
17207
  throw this._error;
17118
17208
  const now = this.scheduler.now();
17119
- const expired = this.closeDeadlineNs !== null && now >= this.closeDeadlineNs;
17209
+ const expired = !this.stdoutPost && this.closeDeadlineNs !== null && now >= this.closeDeadlineNs;
17210
+ const capped = !this.closeLate && this.closeCapNs !== null && now >= this.closeCapNs;
17120
17211
  if (this.output?.completed) {
17121
17212
  if (this.output.ticket)
17122
17213
  this.lib.sessionCompleteOutput(this.context, this.session, this.output.ticket, true);
17123
17214
  this.output = null;
17124
17215
  this.completePresentation();
17125
17216
  }
17126
- const result = this.output ? null : this.lib.sessionPump(this.context, this.session, now, 1);
17127
- if (expired && result?.status !== 4 /* Closed */) {
17128
- throw new Error("NativeSession graceful close timed out; output cancelled without restoration");
17217
+ const start = !capped && this.sink.writableLength === 0 && this.sink.writableCorked === 0;
17218
+ if (this.stdoutPost)
17219
+ this.postStdout(now, start);
17220
+ if (this.stdoutPost)
17221
+ deadlineNs = this.pollDeadline(now);
17222
+ const result = this.output || this.stdoutPost ? null : this.lib.sessionPump(this.context, this.session, now, 1);
17223
+ if ((expired || capped) && result?.status !== 4 /* Closed */) {
17224
+ if (this.closeLate) {
17225
+ throw new Error("NativeSession graceful close timed out; output cancelled without restoration");
17226
+ }
17227
+ this.closeLate = new Error("NativeSession graceful close ran late; queued output was dropped");
17228
+ this.closeRequested = true;
17229
+ this.lib.sessionDropOutput(this.context, this.session);
17230
+ this.presentationWait?.reject(this.closeLate);
17231
+ this.presentationWait = null;
17232
+ this.closeDeadlineNs = now + this.closeTimeoutNs;
17233
+ this.schedule();
17234
+ return;
17129
17235
  }
17130
- if (!result)
17236
+ if (!result) {
17237
+ if (deadlineNs === 0n) {
17238
+ deadlineNs = null;
17239
+ this.schedule();
17240
+ }
17131
17241
  return;
17242
+ }
17132
17243
  switch (result.status) {
17133
17244
  case 0 /* Idle */:
17134
17245
  if (this.transition) {
@@ -17155,14 +17266,15 @@ class NativeSession2 {
17155
17266
  deadlineNs = result.deadlineNs;
17156
17267
  break;
17157
17268
  case 4 /* Closed */:
17158
- this.finish(null);
17269
+ this.finish(this.closeLate);
17159
17270
  break;
17160
17271
  }
17161
17272
  } catch (error) {
17162
17273
  this.finish(asError(error));
17163
17274
  } finally {
17164
- if (this.closeDeadlineNs !== null && (deadlineNs === null || this.closeDeadlineNs < deadlineNs)) {
17165
- deadlineNs = this.closeDeadlineNs;
17275
+ for (const closeNs of [this.stdoutPost ? null : this.closeDeadlineNs, this.closeLate ? null : this.closeCapNs]) {
17276
+ if (closeNs !== null && (deadlineNs === null || closeNs < deadlineNs))
17277
+ deadlineNs = closeNs;
17166
17278
  }
17167
17279
  if (deadlineNs !== null)
17168
17280
  this.schedule(deadlineNs);
@@ -17174,10 +17286,25 @@ class NativeSession2 {
17174
17286
  this.writeSink(emptyOutput, null);
17175
17287
  return;
17176
17288
  }
17289
+ if (this.stdoutWriter) {
17290
+ const now = this.scheduler.now();
17291
+ try {
17292
+ this.postStdout(now, true);
17293
+ this.schedule();
17294
+ return;
17295
+ } catch (error) {
17296
+ if (!(error instanceof NativeError2) || error.status !== -24 /* UnsupportedResource */)
17297
+ throw error;
17298
+ this.stdoutWriter = false;
17299
+ }
17300
+ }
17177
17301
  try {
17178
17302
  const written = this.lib.sessionDrainStdout(this.context, this.session);
17303
+ const now = this.scheduler.now();
17304
+ if (written > 0 && this.closeDeadlineNs !== null)
17305
+ this.closeDeadlineNs = now + this.closeTimeoutNs;
17179
17306
  this.completePresentation();
17180
- this.schedule(written === 0 ? this.scheduler.now() + 1000000n : null);
17307
+ this.schedule(written === 0 ? now + 1000000n : null);
17181
17308
  return;
17182
17309
  } catch (error) {
17183
17310
  if (!(error instanceof NativeError2) || error.status !== -24 /* UnsupportedResource */)
@@ -17192,6 +17319,27 @@ class NativeSession2 {
17192
17319
  throw new Error("NativeSession output ticket exceeds its buffer");
17193
17320
  this.writeSink(this.buffer.subarray(0, ticket.byteCount), ticket);
17194
17321
  }
17322
+ postStdout(now, start) {
17323
+ const posted = this.stdoutPost;
17324
+ const { written, inFlight } = this.lib.sessionPostStdout(this.context, this.session, start ? stdoutBudget : 0, false);
17325
+ if (written > 0)
17326
+ this.completePresentation();
17327
+ if (this.closeDeadlineNs !== null)
17328
+ this.closeDeadlineNs = now + this.closeTimeoutNs;
17329
+ if (!inFlight)
17330
+ this.stdoutPost = null;
17331
+ else if (!posted || written > 0)
17332
+ this.stdoutPost = { since: now, polls: 0 };
17333
+ else
17334
+ posted.polls++;
17335
+ }
17336
+ pollDeadline(now) {
17337
+ const post = this.stdoutPost;
17338
+ if (post.polls < immediatePolls && now - post.since < immediateAgeNs)
17339
+ return 0n;
17340
+ const age = (now - post.since) / 8n;
17341
+ return now + (age < 1000000n ? 1000000n : age > 50000000n ? 50000000n : age);
17342
+ }
17195
17343
  writeSink(bytes, ticket) {
17196
17344
  if (this.output)
17197
17345
  throw new Error("NativeSession output is already in flight");
@@ -17218,7 +17366,11 @@ class NativeSession2 {
17218
17366
  }
17219
17367
  }
17220
17368
  completePresentation() {
17221
- if (this.presentationWait && !this.lib.sessionGetRendererState(this.context, this.session).framePending) {
17369
+ if (!this.presentationWait)
17370
+ return;
17371
+ const state = this.lib.sessionGetRendererState(this.context, this.session);
17372
+ if (!state.framePending) {
17373
+ this.imageUploadsPending = state.imageUploadsPending;
17222
17374
  this.presentationWait.resolve();
17223
17375
  this.presentationWait = null;
17224
17376
  }
@@ -17254,7 +17406,7 @@ class NativeSession2 {
17254
17406
  this.finishing = true;
17255
17407
  try {
17256
17408
  this.stopped = true;
17257
- this._error ??= error;
17409
+ this._error ??= error === this.closeLate ? null : error;
17258
17410
  const scheduled = this.scheduled;
17259
17411
  this.scheduled = null;
17260
17412
  try {
@@ -17308,6 +17460,7 @@ class NativeSession2 {
17308
17460
  this.detach();
17309
17461
  else
17310
17462
  this.schedule();
17463
+ this._error ??= error;
17311
17464
  if (!this._disposed && !this._error)
17312
17465
  return;
17313
17466
  for (const wait of [this.closeWait, this.idleWait, this.presentationWait, this.transition?.wait]) {
@@ -17351,6 +17504,8 @@ class Capture extends EventEmitter6 {
17351
17504
  return this.output.length;
17352
17505
  }
17353
17506
  write(stream, data) {
17507
+ if (this.output.length >= 1000)
17508
+ this.output.shift();
17354
17509
  this.output.push({ stream, output: data });
17355
17510
  this.emit("write", stream, data);
17356
17511
  }
@@ -19427,6 +19582,7 @@ class EditBufferRenderable2 extends Renderable2 {
19427
19582
  // src/renderer.ts
19428
19583
  import { appendFileSync, writeFileSync } from "fs";
19429
19584
  import { Writable as Writable3 } from "stream";
19585
+ import { StringDecoder } from "string_decoder";
19430
19586
 
19431
19587
  // src/ansi.ts
19432
19588
  var ANSI = {
@@ -19745,6 +19901,19 @@ class NativeScene {
19745
19901
  const { renderLib: lib, context } = this.driver;
19746
19902
  lib.sceneSetImage(context, renderable._getSceneHandle(this), image?._getContextHandle(lib, context) ?? null, fit, protocol, buffer?._getSceneHandle(this) ?? null);
19747
19903
  }
19904
+ setVideo(renderable, fit, buffer) {
19905
+ this.flushStaged();
19906
+ const { renderLib: lib, context } = this.driver;
19907
+ lib.sceneSetVideo(context, renderable._getSceneHandle(this), fit, buffer?._getSceneHandle(this) ?? null);
19908
+ }
19909
+ setCrop(renderable, crop) {
19910
+ this.flushStaged();
19911
+ this.driver.renderLib.sceneSetCrop(this.driver.context, renderable._getSceneHandle(this), crop);
19912
+ }
19913
+ videoNode(renderable) {
19914
+ this.flushStaged();
19915
+ return { lib: this.driver.renderLib, context: this.driver.context, node: renderable._getSceneHandle(this) };
19916
+ }
19748
19917
  setScroll(renderable, options) {
19749
19918
  this.flushStaged();
19750
19919
  this.driver.renderLib.sceneSetScroll(this.driver.context, renderable._getSceneHandle(this), options);
@@ -20890,6 +21059,7 @@ function resolveModes(config) {
20890
21059
  }
20891
21060
  var STDOUT_TAB_WIDTH = 8;
20892
21061
  var graphemeSegmenter2 = new Intl.Segmenter(undefined, { granularity: "grapheme" });
21062
+ var STDOUT_ESCAPE = /\x1b(?:\[[\x20-\x3f]*([\x40-\x7e])?|[\]PX^_][^\x00-\x1f]*(\x07)?|[\x20-\x2f]*([\x30-\x7e])?)/g;
20893
21063
  function snapshotRowWidths(snapshot, rowColumns) {
20894
21064
  return snapshot.withBuffers(({ width, height, char }) => {
20895
21065
  const widths = [];
@@ -20902,6 +21072,9 @@ function snapshotRowWidths(snapshot, rowColumns) {
20902
21072
  return widths;
20903
21073
  });
20904
21074
  }
21075
+ var CAPTURED_STDOUT_MAX_BYTES = 64 * 1024 * 1024;
21076
+ var CAPTURED_STDOUT_HIGH_WATER_BYTES = CAPTURED_STDOUT_MAX_BYTES / 2;
21077
+ var capturedRowBytes = (cells) => 3072 + 48 * cells;
20905
21078
  function runCleanups(cleanups) {
20906
21079
  let failure;
20907
21080
  for (const cleanup of cleanups) {
@@ -20917,9 +21090,13 @@ function runCleanups(cleanups) {
20917
21090
 
20918
21091
  class ExternalOutputQueue {
20919
21092
  maxCells;
21093
+ onDrain;
20920
21094
  commits = [];
20921
- constructor(maxCells) {
21095
+ capturedBytes = 0;
21096
+ drainPending = false;
21097
+ constructor(maxCells, onDrain) {
20922
21098
  this.maxCells = maxCells;
21099
+ this.onDrain = onDrain;
20923
21100
  }
20924
21101
  owns(snapshot) {
20925
21102
  return this.commits.some((commit) => commit.snapshot === snapshot);
@@ -20927,7 +21104,7 @@ class ExternalOutputQueue {
20927
21104
  get size() {
20928
21105
  return this.commits.length;
20929
21106
  }
20930
- writeSnapshots(commits) {
21107
+ writeSnapshots(commits, captured) {
20931
21108
  for (const { rowColumns, snapshot } of commits) {
20932
21109
  if (!Number.isInteger(rowColumns) || rowColumns < 0 || rowColumns > snapshot.width) {
20933
21110
  throw new RangeError("Scrollback commit rowColumns must be an integer from 0 to the snapshot width");
@@ -20936,15 +21113,91 @@ class ExternalOutputQueue {
20936
21113
  throw new Error("Scrollback snapshot exceeds the Session output capacity");
20937
21114
  }
20938
21115
  }
20939
- const entries = commits.map((commit) => ({
20940
- ...commit,
20941
- cells: commit.snapshot.width * commit.snapshot.height,
20942
- rowWidths: snapshotRowWidths(commit.snapshot, commit.rowColumns)
20943
- }));
20944
- for (const entry of entries)
21116
+ const entries = commits.map((commit) => this.entry(commit, captured, 0));
21117
+ for (const entry of entries) {
20945
21118
  this.commits.push(entry);
21119
+ this.capturedBytes += entry.bytes;
21120
+ }
20946
21121
  return entries;
20947
21122
  }
21123
+ entry(commit, captured, dropped) {
21124
+ const cells = commit.snapshot.width * commit.snapshot.height;
21125
+ const rowWidths = snapshotRowWidths(commit.snapshot, commit.rowColumns);
21126
+ return { ...commit, cells, rowWidths, bytes: captured ? capturedRowBytes(cells) : 0, dropped };
21127
+ }
21128
+ writable() {
21129
+ if (this.capturedBytes >= CAPTURED_STDOUT_HIGH_WATER_BYTES)
21130
+ this.drainPending = true;
21131
+ return !this.drainPending;
21132
+ }
21133
+ takeDrain(force = false) {
21134
+ if (!this.drainPending || !force && this.capturedBytes >= CAPTURED_STDOUT_HIGH_WATER_BYTES)
21135
+ return false;
21136
+ this.drainPending = false;
21137
+ return true;
21138
+ }
21139
+ collapse(limits, marker) {
21140
+ if (this.capturedBytes <= CAPTURED_STDOUT_MAX_BYTES && limits.trimmed === 0)
21141
+ return null;
21142
+ const kept = [];
21143
+ const removed = new Set;
21144
+ const runs = [];
21145
+ let bytes = this.capturedBytes;
21146
+ let open = false;
21147
+ let partial = false;
21148
+ let boundary = -1;
21149
+ const endRow = () => {
21150
+ if (partial)
21151
+ runs.at(-1).rows += 1;
21152
+ partial = false;
21153
+ };
21154
+ const close = () => {
21155
+ endRow();
21156
+ open = false;
21157
+ };
21158
+ for (const [index, commit] of this.commits.entries()) {
21159
+ if (index === limits.boundary) {
21160
+ close();
21161
+ boundary = kept.length + runs.length;
21162
+ }
21163
+ if (index === limits.incoming && limits.trimmed > 0) {
21164
+ if (!open)
21165
+ runs.push({ index: kept.length, rows: 0 });
21166
+ runs.at(-1).rows += limits.trimmed;
21167
+ open = true;
21168
+ partial = false;
21169
+ }
21170
+ if (index < limits.start || commit.bytes === 0 || bytes <= CAPTURED_STDOUT_HIGH_WATER_BYTES && !partial) {
21171
+ if (commit.bytes === 0)
21172
+ endRow();
21173
+ else
21174
+ close();
21175
+ kept.push(commit);
21176
+ continue;
21177
+ }
21178
+ if (!open)
21179
+ runs.push({ index: kept.length, rows: 0 });
21180
+ open = true;
21181
+ partial = !commit.endsRow;
21182
+ runs.at(-1).rows += commit.dropped || (commit.endsRow ? 1 : 0);
21183
+ removed.add(commit.snapshot);
21184
+ bytes -= commit.bytes;
21185
+ }
21186
+ close();
21187
+ if (runs.length === 0)
21188
+ return null;
21189
+ const markers = runs.map((run) => marker(run.rows));
21190
+ for (let run = runs.length - 1;run >= 0; run--) {
21191
+ const entry = this.entry(markers[run], true, runs[run].rows);
21192
+ kept.splice(runs[run].index, 0, entry);
21193
+ this.capturedBytes += entry.bytes;
21194
+ }
21195
+ const gone = this.commits.filter((commit) => removed.has(commit.snapshot));
21196
+ this.commits = kept;
21197
+ this.drainPending = true;
21198
+ this.release(gone, false);
21199
+ return { markers, removed, boundary: boundary < 0 ? kept.length : boundary };
21200
+ }
20948
21201
  batch(limit) {
20949
21202
  if (!(limit >= 1))
20950
21203
  throw new RangeError("ExternalOutputQueue.batch requires a limit of at least 1");
@@ -20967,8 +21220,15 @@ class ExternalOutputQueue {
20967
21220
  return output;
20968
21221
  }
20969
21222
  drop(count) {
20970
- for (const commit of this.commits.splice(0, count))
21223
+ this.release(this.commits.splice(0, count));
21224
+ }
21225
+ release(removed, drain = true) {
21226
+ for (const commit of removed) {
21227
+ this.capturedBytes -= commit.bytes;
20971
21228
  commit.snapshot.destroy();
21229
+ }
21230
+ if (drain && this.drainPending && this.capturedBytes < CAPTURED_STDOUT_HIGH_WATER_BYTES)
21231
+ this.onDrain();
20972
21232
  }
20973
21233
  clear() {
20974
21234
  this.drop(this.commits.length);
@@ -21247,6 +21507,7 @@ var CliRenderEvents2;
21247
21507
  CliRenderEvents["RESIZE"] = "resize";
21248
21508
  CliRenderEvents["FRAME"] = "frame";
21249
21509
  CliRenderEvents["RENDER_ERROR"] = "render:error";
21510
+ CliRenderEvents["FRAME_DROPPED"] = "frame:dropped";
21250
21511
  CliRenderEvents["HANDLER_ERROR"] = "handler:error";
21251
21512
  CliRenderEvents["EXTERNAL_OUTPUT"] = "external_output";
21252
21513
  CliRenderEvents["FOCUS"] = "focus";
@@ -21403,11 +21664,16 @@ class CliRenderer2 extends EventEmitter8 {
21403
21664
  pendingSplitFooterTransition = null;
21404
21665
  forceFullRepaintRequested = false;
21405
21666
  maxSplitCommitsPerFrame = 8;
21667
+ splitCommitLimit = this.maxSplitCommitsPerFrame;
21668
+ droppedFrames = 0;
21669
+ dropRetried = false;
21406
21670
  _terminalWidth = 0;
21407
21671
  _terminalHeight = 0;
21408
21672
  _terminalIsSetup = false;
21409
21673
  externalOutputQueue;
21410
21674
  pendingExternalOutputMode = null;
21675
+ stdoutDecoder = new StringDecoder("utf8");
21676
+ stdoutEscape = "";
21411
21677
  realStdoutWrite;
21412
21678
  _useConsole = true;
21413
21679
  sigwinchHandler = (() => {
@@ -21580,15 +21846,13 @@ Captured external output:
21580
21846
  }
21581
21847
  });
21582
21848
  this.nativeSession = driver;
21583
- this.externalOutputQueue = new ExternalOutputQueue(Number(driver.maxWriteBytes / 24n));
21849
+ this.externalOutputQueue = new ExternalOutputQueue(Number(driver.maxWriteBytes / 24n), () => process.nextTick(() => !this._isDestroyed && this.externalOutputQueue.takeDrain() && this.stdout.emit("drain")));
21584
21850
  this.nativeDestroyWait = Promise.withResolvers();
21585
21851
  this.nativeClosed = this.nativeSession.closed.finally(() => this.nativeDestroyWait.promise).finally(() => {
21586
21852
  if (this.nativeSession.error && !this.nativeSession.disposed)
21587
21853
  this.nativeSession.dispose();
21588
- this.leaveRawMode();
21854
+ this.leaveRawMode(this.flushTerminalInputOnClose);
21589
21855
  this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler);
21590
- if (this.flushTerminalInputOnClose)
21591
- this.lib.terminalFlushInput();
21592
21856
  this.releaseStreamLease();
21593
21857
  });
21594
21858
  this.nativeClosed.catch(() => {});
@@ -22072,6 +22336,9 @@ Captured external output:
22072
22336
  this.applyExternalOutputMode(mode);
22073
22337
  return;
22074
22338
  }
22339
+ if (mode === "passthrough" && !this.rendering && !this.pendingNativeMode && this.externalOutputQueue.size === 0) {
22340
+ this.flushStdoutDecoder();
22341
+ }
22075
22342
  if (this.rendering || this.pendingNativeMode || this.externalOutputQueue.size > 0) {
22076
22343
  this.pendingExternalOutputMode = mode;
22077
22344
  this.requestRender();
@@ -22128,6 +22395,11 @@ Captured external output:
22128
22395
  if (pendingMode === null || this.externalOutputQueue.size > 0 && !(pendingMode === "capture-stdout" && this._screenMode === "split-footer")) {
22129
22396
  return;
22130
22397
  }
22398
+ if (pendingMode === "passthrough") {
22399
+ this.flushStdoutDecoder();
22400
+ if (this.externalOutputQueue.size > 0)
22401
+ return;
22402
+ }
22131
22403
  const previousMode = this._externalOutputMode;
22132
22404
  this.pendingExternalOutputMode = null;
22133
22405
  if (previousMode === pendingMode) {
@@ -22190,7 +22462,7 @@ Captured external output:
22190
22462
  return this.nativeSession.triggerNotification(message, title);
22191
22463
  }
22192
22464
  setProgramStatus(status) {
22193
- if (this._isDestroyed)
22465
+ if (!this.nativeSession.open)
22194
22466
  return false;
22195
22467
  return this.nativeSession.setProgramStatus(status);
22196
22468
  }
@@ -22548,6 +22820,7 @@ Captured external output:
22548
22820
  if (!this._terminalIsSetup || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
22549
22821
  throw new Error("resetSplitFooterForReplay requires an active terminal");
22550
22822
  }
22823
+ this.flushStdoutDecoder();
22551
22824
  if (this.rendering || this.externalOutputQueue.size > 0) {
22552
22825
  this.pendingNativeReplay = { options, remaining: this.externalOutputQueue.size };
22553
22826
  this.requestRender();
@@ -22635,24 +22908,27 @@ Captured external output:
22635
22908
  }
22636
22909
  ]);
22637
22910
  }
22638
- enqueueSplitCommits(commits) {
22911
+ enqueueSplitCommits(commits, captured = false) {
22639
22912
  for (const commit of commits)
22640
22913
  commit.nativeSnapshot = commit.snapshot._getSceneHandle(this.nativeScene);
22641
22914
  const width = Math.max(this.width, 1);
22642
22915
  let column = this.getPendingSplitTailColumn();
22643
- for (const entry of this.externalOutputQueue.writeSnapshots(commits)) {
22916
+ for (const entry of this.externalOutputQueue.writeSnapshots(commits, captured)) {
22644
22917
  column = this.getSplitTailColumnAfterCommit(entry, column, width);
22645
22918
  }
22646
22919
  this.queuedSplitTail = { column, width };
22647
22920
  this.requestRender();
22921
+ if (!captured)
22922
+ this.emitExternalOutput(commits);
22923
+ }
22924
+ emitExternalOutput(commits) {
22648
22925
  if (this.listenerCount("external_output" /* EXTERNAL_OUTPUT */) > 0) {
22649
22926
  for (const commit of commits)
22650
22927
  this.emit("external_output" /* EXTERNAL_OUTPUT */, commit);
22651
22928
  }
22652
22929
  }
22653
- splitStdoutRows(text) {
22930
+ splitStdoutRows(text, tailColumn) {
22654
22931
  const width = Math.max(1, this.width);
22655
- const tailColumn = this.getPendingSplitTailColumn();
22656
22932
  const rows = [];
22657
22933
  let rowStart = 0;
22658
22934
  let line = "";
@@ -22667,7 +22943,7 @@ Captured external output:
22667
22943
  if (segment === `
22668
22944
  ` || segment === `\r
22669
22945
  `) {
22670
- rows.push({ line, cells, trailingNewline: true });
22946
+ rows.push({ line, cells, trailingNewline: true, endsRow: true });
22671
22947
  rowStart = rows.length;
22672
22948
  line = "";
22673
22949
  cells = 0;
@@ -22679,7 +22955,7 @@ Captured external output:
22679
22955
  const graphemeCells = stringWidth(grapheme);
22680
22956
  if (column > 0 && column + graphemeCells > width) {
22681
22957
  const padding = Math.max(0, width - column);
22682
- rows.push({ line: line + " ".repeat(padding), cells: cells + padding, trailingNewline: false });
22958
+ rows.push({ line: line + " ".repeat(padding), cells: cells + padding, trailingNewline: false, endsRow: true });
22683
22959
  line = "";
22684
22960
  cells = 0;
22685
22961
  }
@@ -22687,12 +22963,12 @@ Captured external output:
22687
22963
  cells += graphemeCells;
22688
22964
  }
22689
22965
  if (line.length > 0) {
22690
- rows.push({ line, cells, trailingNewline: false });
22966
+ const column = (rows.length === 0 && tailColumn < width ? tailColumn : 0) + cells;
22967
+ rows.push({ line, cells, trailingNewline: false, endsRow: column >= width });
22691
22968
  }
22692
22969
  return rows;
22693
22970
  }
22694
- createStdoutSnapshotCommits(text) {
22695
- const rows = this.splitStdoutRows(text);
22971
+ createStdoutSnapshotCommits(rows) {
22696
22972
  if (rows.length === 0) {
22697
22973
  return [];
22698
22974
  }
@@ -22709,7 +22985,7 @@ Captured external output:
22709
22985
  height: 1
22710
22986
  });
22711
22987
  snapshotRoot.add(snapshotRenderable);
22712
- for (const { line, cells, trailingNewline } of rows) {
22988
+ for (const { line, cells, trailingNewline, endsRow } of rows) {
22713
22989
  const snapshotWidth = Math.max(1, cells);
22714
22990
  snapshotContext.width = snapshotWidth;
22715
22991
  snapshotRoot.resize(snapshotWidth, 1);
@@ -22719,7 +22995,7 @@ Captured external output:
22719
22995
  id: "captured-stdout-snapshot",
22720
22996
  owner: this.nativeScene
22721
22997
  });
22722
- commits.push({ snapshot, rowColumns: cells, startOnNewLine: false, trailingNewline });
22998
+ commits.push({ snapshot, rowColumns: cells, startOnNewLine: false, trailingNewline, endsRow });
22723
22999
  snapshotContext.renderSnapshot(snapshotRoot, snapshot);
22724
23000
  }
22725
23001
  return commits;
@@ -22731,27 +23007,70 @@ Captured external output:
22731
23007
  runCleanups([() => snapshotRoot?.destroyRecursively(), () => snapshotContext.destroy()]);
22732
23008
  }
22733
23009
  }
23010
+ flushStdoutDecoder() {
23011
+ const text = this.stdoutDecoder.end();
23012
+ if (text && this.nativeSession.open)
23013
+ this.interceptStdoutWrite(text);
23014
+ this.stdoutEscape = "";
23015
+ }
22734
23016
  interceptStdoutWrite = (chunk, encoding, callback) => {
22735
23017
  const resolvedCallback = typeof encoding === "function" ? encoding : callback;
22736
- const resolvedEncoding = typeof encoding === "string" ? encoding : undefined;
22737
- const text = typeof chunk === "string" ? chunk : chunk?.toString(resolvedEncoding) ?? "";
23018
+ let writable = true;
22738
23019
  if (this._externalOutputMode === "capture-stdout" && this._screenMode === "split-footer" && this._splitHeight > 0) {
22739
- const commits = this.createStdoutSnapshotCommits(text);
23020
+ const bytes = ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.from(String(chunk ?? ""), Buffer.isEncoding(encoding) ? encoding : undefined);
23021
+ const decoded = this.stdoutEscape + this.stdoutDecoder.write(bytes);
23022
+ this.stdoutEscape = "";
23023
+ const text = decoded.replace(STDOUT_ESCAPE, (match, csi, bel, esc, offset) => {
23024
+ if (offset + match.length === decoded.length && (csi ?? bel ?? esc) === undefined) {
23025
+ this.stdoutEscape = match.slice(0, 2);
23026
+ }
23027
+ return "";
23028
+ });
23029
+ const queue = this.externalOutputQueue;
23030
+ const rows = this.splitStdoutRows(text, this.getPendingSplitTailColumn());
23031
+ let added = rows.reduce((sum, row) => sum + capturedRowBytes(Math.max(1, row.cells)), 0);
23032
+ let trimmed = 0;
23033
+ if (queue.capturedBytes + added > CAPTURED_STDOUT_MAX_BYTES) {
23034
+ while (added > CAPTURED_STDOUT_HIGH_WATER_BYTES)
23035
+ added -= capturedRowBytes(Math.max(1, rows[trimmed++].cells));
23036
+ }
23037
+ const commits = this.createStdoutSnapshotCommits(rows.slice(trimmed));
22740
23038
  try {
22741
- this.enqueueSplitCommits(commits);
23039
+ this.enqueueSplitCommits(commits, true);
22742
23040
  } catch (error) {
22743
23041
  for (const commit of commits) {
22744
- if (!this.externalOutputQueue.owns(commit.snapshot))
23042
+ if (!queue.owns(commit.snapshot))
22745
23043
  commit.snapshot.destroy();
22746
23044
  }
22747
23045
  throw error;
22748
23046
  }
23047
+ const limits = {
23048
+ start: this.nativeSplitAcceptedCount,
23049
+ boundary: this.pendingNativeReplay?.remaining ?? Infinity,
23050
+ incoming: queue.size - commits.length,
23051
+ trimmed
23052
+ };
23053
+ const collapsed = queue.collapse(limits, (rows2) => this.createDroppedRowCommit(rows2));
23054
+ if (collapsed) {
23055
+ this.queuedSplitTail = null;
23056
+ if (this.pendingNativeReplay)
23057
+ this.pendingNativeReplay.remaining = collapsed.boundary;
23058
+ }
23059
+ this.emitExternalOutput(collapsed?.markers ?? []);
23060
+ this.emitExternalOutput(commits.filter((commit) => !collapsed?.removed.has(commit.snapshot)));
23061
+ writable = queue.writable();
22749
23062
  }
22750
23063
  if (typeof resolvedCallback === "function") {
22751
23064
  process.nextTick(resolvedCallback);
22752
23065
  }
22753
- return true;
23066
+ return writable;
22754
23067
  };
23068
+ createDroppedRowCommit(rows) {
23069
+ const text = `[${rows} lines dropped]`.slice(0, Math.max(1, this.width));
23070
+ const [commit] = this.createStdoutSnapshotCommits(this.splitStdoutRows(text, 0));
23071
+ commit.nativeSnapshot = commit.snapshot._getSceneHandle(this.nativeScene);
23072
+ return { ...commit, startOnNewLine: true, trailingNewline: true, endsRow: true };
23073
+ }
22755
23074
  getSplitPinnedRenderOffset() {
22756
23075
  return this._screenMode === "split-footer" ? Math.max(this._terminalHeight - this._splitHeight, 0) : 0;
22757
23076
  }
@@ -24076,6 +24395,9 @@ Captured external output:
24076
24395
  if (!this._terminalIsSetup || this.nativeTerminalTransition) {
24077
24396
  throw new Error("Native scene suspension requires completed terminal setup and no pending transition");
24078
24397
  }
24398
+ this.flushStdoutDecoder();
24399
+ const { context, session } = this.nativeSession;
24400
+ const restored = this.lib.sessionGetTerminalState(context, session) === 4 /* Suspended */;
24079
24401
  const flushNativeSplit = this.externalOutputQueue.size > 0 || this.pendingNativeReplay;
24080
24402
  if (flushNativeSplit)
24081
24403
  this.lib.getYogaHost().assertMutable();
@@ -24096,7 +24418,8 @@ Captured external output:
24096
24418
  } else {
24097
24419
  nativeTransition = this.nativeSession.suspend();
24098
24420
  }
24099
- nativeTransition = this.trackNativeTerminalTransition(nativeTransition);
24421
+ const settled = nativeTransition.finally(() => this._isDestroyed || restored || this.leaveRawMode(true));
24422
+ nativeTransition = this.trackNativeTerminalTransition(settled);
24100
24423
  if (this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
24101
24424
  this._previousControlState = this._controlState;
24102
24425
  this._suspendedMouseEnabled = this._useMouse;
@@ -24121,9 +24444,6 @@ Captured external output:
24121
24444
  this.stdin.removeListener("data", this.stdinListener);
24122
24445
  this.stopTerminalKeepAlive();
24123
24446
  this.themeModeState?.cancelRefresh();
24124
- if (this.stdin.setRawMode) {
24125
- this.stdin.setRawMode(false);
24126
- }
24127
24447
  this.stdin.pause();
24128
24448
  return nativeTransition;
24129
24449
  }
@@ -24242,10 +24562,14 @@ Captured external output:
24242
24562
  this.nativeSession.close();
24243
24563
  } catch (error) {
24244
24564
  this.externalOutputQueue.clear();
24245
- this.nativeSession.dispose();
24246
- console.error("Native split output cancelled during close:", error);
24565
+ if (!this.nativeSession.isCloseInterruption(error)) {
24566
+ this.nativeSession.dispose();
24567
+ console.error("Native split output cancelled during close:", error);
24568
+ }
24247
24569
  }
24248
24570
  });
24571
+ const drain = () => this.externalOutputQueue.takeDrain(true) && this.stdout.emit("drain");
24572
+ this.nativeClosed.then(drain, drain);
24249
24573
  this.finalizeDestroy();
24250
24574
  }
24251
24575
  cleanupBeforeDestroy() {
@@ -24308,6 +24632,7 @@ Captured external output:
24308
24632
  } catch (e) {
24309
24633
  console.error("Error pausing stdin during destroy:", e);
24310
24634
  }
24635
+ this.flushStdoutDecoder();
24311
24636
  this.externalOutputMode = "passthrough";
24312
24637
  }
24313
24638
  finalizeDestroy() {
@@ -24375,7 +24700,7 @@ Captured external output:
24375
24700
  this._externalOutputMode = "passthrough";
24376
24701
  this.pendingExternalOutputMode = null;
24377
24702
  this.stdout.write = this.realStdoutWrite;
24378
- const discardInput = this._terminalIsSetup && this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */;
24703
+ const discardInput = this._terminalIsSetup && (this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */ || this.nativeTerminalTransition !== null);
24379
24704
  if (discardInput) {
24380
24705
  const bufferedInput = this.stdin.readableLength;
24381
24706
  if (bufferedInput > 0)
@@ -24398,12 +24723,14 @@ Captured external output:
24398
24723
  this.nativeDestroyWait?.resolve();
24399
24724
  this.resolveIdleIfNeeded();
24400
24725
  }
24401
- leaveRawMode() {
24726
+ leaveRawMode(flushInput = false) {
24402
24727
  try {
24403
24728
  this.stdin.setRawMode?.(false);
24404
24729
  } catch (e) {
24405
24730
  console.error("Error disabling raw mode:", e);
24406
24731
  }
24732
+ if (flushInput && this.stdin === process.stdin)
24733
+ this.lib.terminalFlushInput();
24407
24734
  }
24408
24735
  releaseStreamLease() {
24409
24736
  if (!this._streamLeaseAcquired)
@@ -24563,6 +24890,10 @@ Captured external output:
24563
24890
  } else {
24564
24891
  this.clearFrameTimer();
24565
24892
  }
24893
+ } else if (nativeStatus === "dropped" && (this._isRunning || this.immediateRerenderRequested)) {
24894
+ const immediate = this.immediateRerenderRequested;
24895
+ this.immediateRerenderRequested = false;
24896
+ this.scheduleFrame(immediate ? this.minTargetFrameTime : this.targetFrameTime);
24566
24897
  } else {
24567
24898
  this.immediateRerenderRequested = false;
24568
24899
  this.clearFrameTimer();
@@ -24570,7 +24901,7 @@ Captured external output:
24570
24901
  }
24571
24902
  } catch (error) {
24572
24903
  renderFailed = true;
24573
- if (this.canRender) {
24904
+ if (this.canRender && !this.nativeSession.isCloseInterruption(error)) {
24574
24905
  const renderError = error instanceof Error ? error : new Error(String(error));
24575
24906
  const event = { error: renderError, renderable: this.root.takeCurrentRenderable() };
24576
24907
  const handled = this.emit("render:error" /* RENDER_ERROR */, event);
@@ -24627,10 +24958,40 @@ Captured external output:
24627
24958
  this.ordinaryFrameWaitControlState = this._controlState;
24628
24959
  this.loop();
24629
24960
  }
24961
+ handleDroppedFrame(commits) {
24962
+ const state = this.lib.sessionGetRendererState(this.nativeSession.context, this.nativeSession.session);
24963
+ if (state.droppedFrameBytes === 0)
24964
+ return false;
24965
+ const counted = state.droppedFrames !== this.droppedFrames;
24966
+ this.droppedFrames = state.droppedFrames;
24967
+ if (commits && commits.length > 1) {
24968
+ this.splitCommitLimit = 1;
24969
+ return true;
24970
+ }
24971
+ if (!commits?.length) {
24972
+ if (!counted && !this.dropRetried)
24973
+ this.requestRender();
24974
+ this.dropRetried = true;
24975
+ }
24976
+ if (commits?.length === 1) {
24977
+ this.externalOutputQueue.drop(1);
24978
+ this.queuedSplitTail = null;
24979
+ if (this.pendingNativeReplay)
24980
+ this.pendingNativeReplay.remaining -= 1;
24981
+ }
24982
+ if (counted) {
24983
+ const event = {
24984
+ bytes: state.droppedFrameBytes,
24985
+ limit: Number(this.nativeSession.maxAtomicWriteBytes)
24986
+ };
24987
+ this.emit("frame:dropped" /* FRAME_DROPPED */, event);
24988
+ }
24989
+ return true;
24990
+ }
24630
24991
  async presentNativeScene() {
24631
24992
  if (this.isSplitCursorSeedFrameBlocked())
24632
24993
  return "blocked";
24633
- const commits = this._splitHeight > 0 && this._externalOutputMode === "capture-stdout" ? this.pendingNativeReplay?.remaining === 0 ? [] : this.externalOutputQueue.batch(Math.min(this.maxSplitCommitsPerFrame, this.pendingNativeReplay?.remaining ?? Infinity)) : null;
24994
+ const commits = this._splitHeight > 0 && this._externalOutputMode === "capture-stdout" ? this.pendingNativeReplay?.remaining === 0 ? [] : this.externalOutputQueue.batch(Math.min(this.splitCommitLimit, this.pendingNativeReplay?.remaining ?? Infinity)) : null;
24634
24995
  const split = commits === null ? null : this.nativeScene.commitSplit(commits.map((commit) => ({ ...commit, snapshot: commit.nativeSnapshot })), this.getSplitPinnedRenderOffset(), this.forceFullRepaintRequested);
24635
24996
  const status = split?.status ?? this.nativeScene.commit(this.forceFullRepaintRequested);
24636
24997
  if (commits && (status === 1 /* Pending */ || status === 0 /* Presented */)) {
@@ -24647,6 +25008,11 @@ Captured external output:
24647
25008
  this.scheduleRenderAfterOutputIdle();
24648
25009
  return "retryable-skip";
24649
25010
  case 3 /* Failed */:
25011
+ if (this.handleDroppedFrame(commits)) {
25012
+ if (commits?.length)
25013
+ this.requestRender();
25014
+ return "dropped";
25015
+ }
24650
25016
  console.error("[CliRenderer] Native frame render failed; waiting for the next render request to force repaint");
24651
25017
  return "failed";
24652
25018
  default:
@@ -24662,6 +25028,9 @@ Captured external output:
24662
25028
  this.applyPendingExternalOutputModeIfReady();
24663
25029
  }
24664
25030
  this.forceFullRepaintRequested = false;
25031
+ this.dropRetried = false;
25032
+ if (status === 1 /* Pending */ && this.nativeSession.imageUploadsPending)
25033
+ this.requestRender();
24665
25034
  return "rendered";
24666
25035
  }
24667
25036
  completeNativeSplitCommits(commits) {
@@ -24673,6 +25042,7 @@ Captured external output:
24673
25042
  this.externalOutputQueue.drop(commits.length);
24674
25043
  if (this.pendingNativeReplay)
24675
25044
  this.pendingNativeReplay.remaining -= commits.length;
25045
+ this.splitCommitLimit = this.maxSplitCommitsPerFrame;
24676
25046
  this.nativeSplitAcceptedCount = 0;
24677
25047
  this.pendingSplitFooterTransition = null;
24678
25048
  }
@@ -24695,19 +25065,26 @@ Captured external output:
24695
25065
  continue;
24696
25066
  }
24697
25067
  }
25068
+ remaining = Math.min(remaining, this.externalOutputQueue.size);
24698
25069
  if (remaining === 0)
24699
25070
  break;
24700
- const commits = this.externalOutputQueue.batch(Math.min(remaining, this.maxSplitCommitsPerFrame, this.pendingNativeReplay?.remaining ?? Infinity));
25071
+ const commits = this.externalOutputQueue.batch(Math.min(remaining, this.splitCommitLimit, this.pendingNativeReplay?.remaining ?? Infinity));
24701
25072
  if (this.lib.sessionGetRendererState(driver.context, driver.session).framePending) {
24702
25073
  throw new Error("Native split output flush requires no pending frame presentation");
24703
25074
  }
24704
25075
  const result = driver.renderSplit(null, commits.map((commit) => ({ ...commit, snapshot: commit.nativeSnapshot })), this.getSplitPinnedRenderOffset(), false);
24705
- if (result.status === 3 /* Failed */)
24706
- throw new Error("Native split output frame failed");
25076
+ if (result.status === 3 /* Failed */) {
25077
+ if (!this.handleDroppedFrame(commits))
25078
+ throw new Error("Native split output frame failed");
25079
+ if (commits.length === 1)
25080
+ remaining -= 1;
25081
+ continue;
25082
+ }
24707
25083
  if (result.status === 2 /* Skipped */) {
24708
25084
  await driver.idle();
24709
25085
  continue;
24710
25086
  }
25087
+ this.nativeSplitAcceptedCount = commits.length;
24711
25088
  await driver.whenPresented();
24712
25089
  remaining -= commits.length;
24713
25090
  this.completeNativeSplitCommits(commits);
@@ -25090,7 +25467,7 @@ Captured external output:
25090
25467
  }
25091
25468
  }
25092
25469
 
25093
- export { isValidBorderStyle2, parseBorderStyle2, BorderChars2, getBorderFromSides2, getBorderSides2, borderCharsToArray2, BorderCharArrays2, KeyEvent2, PasteEvent2, KeyHandler2, InternalKeyHandler2, fonts2, measureText2, getCharacterPositions2, coordinateToCharacterIndex2, renderFontToFrameBuffer2, hastToStyledText2, SystemClock2, nonAlphanumericKeys2, terminalNamedSingleStrokeKeys2, parseKeypress2, LinearScrollAccel2, MacOSScrollAccel2, parseAlign2, parseAlignItems2, parseBoxSizing2, parseDimension2, parseDirection2, parseDisplay2, parseEdge2, parseFlexDirection2, parseGutter2, parseJustify2, parseLogLevel2, parseMeasureMode2, parseOverflow2, parsePositionType2, parseUnit2, parseWrap2, MouseParser2, Selection2, convertGlobalToLocalSelection2, ASCIIFontSelectionHelper2, StdinParser2, addDefaultParsers2, TreeSitterClient2, treeSitterToTextChunks2, treeSitterToStyledText2, DataPathsManager2, getDataPaths2, extensionToFiletype2, basenameToFiletype2, extToFiletype2, pathToFiletype2, infoStringToFiletype2, getTreeSitterClient2, destroyTreeSitterClient2, ExtmarksController2, createExtmarksController2, TerminalPalette2, createTerminalPalette2, normalizeTerminalPalette2, buildTerminalPaletteSignature2, decodePasteBytes2, stripAnsiSequences2, createHostClipboard2, createClipboard2, ClipboardTarget2, createRendererClipboardAdapter2, normalizeMarkdownLinkTarget, detectLinks2, acquireSessionBufferLease2, ResourceContext2, OptimizedBuffer2, h2, isVNode2, maybeMakeRenderable2, wrapWithDelegates2, instantiate2, delegate2, LayoutEvents2, RenderableEvents2, isRenderable2, BaseRenderable2, Renderable2, RootRenderable2, TextBuffer2, TextBufferView2, EditBuffer2, measureEditText2, EditorView2, Timeline2, engine2, getTimelineEngine2, createTimeline2, ANSI, BoxRenderable2, wheelDirection, scrollOnce, TextBufferRenderable2, CodeRenderable2, ImageLoadError2, ImageError2, imageInfo2, NativeImage2, NativeImagePool2, resolveImageRenderProtocol2, ImageRenderable2, isTextNodeRenderable2, TextNodeRenderable2, RootTextNodeRenderable2, TextRenderable2, NativeSession2, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture2, ConsolePosition2, TerminalConsole2, EditBufferRenderableEvents2, isEditBufferRenderable2, EditBufferRenderable2, buildKittyKeyboardFlags2, MouseEvent2, MouseButton2, createCliRenderer2, CliRenderEvents2, RendererControlState2, CliRenderer2 };
25470
+ export { isValidBorderStyle2, parseBorderStyle2, BorderChars2, getBorderFromSides2, getBorderSides2, borderCharsToArray2, BorderCharArrays2, KeyEvent2, PasteEvent2, KeyHandler2, InternalKeyHandler2, fonts2, measureText2, getCharacterPositions2, coordinateToCharacterIndex2, renderFontToFrameBuffer2, hastToStyledText2, SystemClock2, nonAlphanumericKeys2, terminalNamedSingleStrokeKeys2, parseKeypress2, LinearScrollAccel2, MacOSScrollAccel2, parseAlign2, parseAlignItems2, parseBoxSizing2, parseDimension2, parseDirection2, parseDisplay2, parseEdge2, parseFlexDirection2, parseGutter2, parseJustify2, parseLogLevel2, parseMeasureMode2, parseOverflow2, parsePositionType2, parseUnit2, parseWrap2, MouseParser2, Selection2, convertGlobalToLocalSelection2, ASCIIFontSelectionHelper2, StdinParser2, addDefaultParsers2, TreeSitterClient2, treeSitterToTextChunks2, treeSitterToStyledText2, DataPathsManager2, getDataPaths2, extensionToFiletype2, basenameToFiletype2, extToFiletype2, pathToFiletype2, infoStringToFiletype2, getTreeSitterClient2, destroyTreeSitterClient2, ExtmarksController2, createExtmarksController2, TerminalPalette2, createTerminalPalette2, normalizeTerminalPalette2, buildTerminalPaletteSignature2, decodePasteBytes2, stripAnsiSequences2, createHostClipboard2, createClipboard2, ClipboardTarget2, createRendererClipboardAdapter2, normalizeMarkdownLinkTarget, detectLinks2, acquireSessionBufferLease2, ResourceContext2, OptimizedBuffer2, h2, isVNode2, maybeMakeRenderable2, wrapWithDelegates2, instantiate2, delegate2, LayoutEvents2, RenderableEvents2, isRenderable2, BaseRenderable2, Renderable2, RootRenderable2, TextBuffer2, TextBufferView2, EditBuffer2, measureEditText2, EditorView2, Timeline2, engine2, getTimelineEngine2, createTimeline2, ANSI, BoxRenderable2, wheelDirection, scrollOnce, TextBufferRenderable2, CodeRenderable2, ImageLoadError2, ImageError2, imageInfo2, NativeImage2, NativeImagePool2, resolveImageRenderProtocol2, checkCrop2, sameCrop2, ImageRenderable2, isTextNodeRenderable2, TextNodeRenderable2, RootTextNodeRenderable2, TextRenderable2, NativeSession2, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture2, ConsolePosition2, TerminalConsole2, EditBufferRenderableEvents2, isEditBufferRenderable2, EditBufferRenderable2, buildKittyKeyboardFlags2, MouseEvent2, MouseButton2, createCliRenderer2, CliRenderEvents2, RendererControlState2, CliRenderer2 };
25094
25471
 
25095
- //# debugId=A4020884D6EB9A5C64756E2164756E21
25096
- //# sourceMappingURL=chunk-bun-6kxdhkdc.js.map
25472
+ //# debugId=751AC9A49368602364756E2164756E21
25473
+ //# sourceMappingURL=chunk-bun-vd3rj9kv.js.map