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