@opentui/core 0.2.1 → 0.2.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.
@@ -10462,6 +10462,12 @@ function createExtmarksController(editBuffer, editorView) {
10462
10462
 
10463
10463
  // src/lib/terminal-palette.ts
10464
10464
  var SYSTEM_CLOCK2 = new SystemClock;
10465
+ registerEnvVar({
10466
+ name: "OTUI_PALETTE_IDLE_TIMEOUT_MS",
10467
+ description: "Milliseconds of silence after palette queries before using fallback colors.",
10468
+ type: "number",
10469
+ default: 300
10470
+ });
10465
10471
  var OSC4_RESPONSE = /\x1b]4;(\d+);(?:(?:rgb:)([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)|#([0-9a-fA-F]{6}))(?:\x07|\x1b\\)/g;
10466
10472
  var OSC_SPECIAL_RESPONSE = /\x1b](\d+);(?:(?:rgb:)([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)|#([0-9a-fA-F]{6}))(?:\x07|\x1b\\)/g;
10467
10473
  function scaleComponent(comp) {
@@ -10487,18 +10493,21 @@ class TerminalPalette {
10487
10493
  writeFn;
10488
10494
  activeQuerySessions = [];
10489
10495
  inLegacyTmux;
10496
+ inTmux;
10490
10497
  oscSource;
10491
10498
  clock;
10492
- constructor(stdin, stdout, writeFn, isLegacyTmux, oscSource, clock) {
10499
+ constructor(options) {
10500
+ const { stdin, stdout, writeFn, isLegacyTmux, isTmux, oscSource, clock } = options;
10493
10501
  this.stdin = stdin;
10494
10502
  this.stdout = stdout;
10495
10503
  this.writeFn = writeFn || ((data) => stdout.write(data));
10496
10504
  this.inLegacyTmux = isLegacyTmux ?? false;
10505
+ this.inTmux = isTmux ?? this.inLegacyTmux;
10497
10506
  this.oscSource = oscSource;
10498
10507
  this.clock = clock ?? SYSTEM_CLOCK2;
10499
10508
  }
10500
- writeOsc(osc) {
10501
- const data = this.inLegacyTmux ? wrapForTmux(osc) : osc;
10509
+ writeOsc(osc, wrapForLegacyTmux = false) {
10510
+ const data = wrapForLegacyTmux && this.inLegacyTmux ? wrapForTmux(osc) : osc;
10502
10511
  return this.writeFn(data);
10503
10512
  }
10504
10513
  cleanup() {
@@ -10593,10 +10602,10 @@ class TerminalPalette {
10593
10602
  finish(false);
10594
10603
  }, timeoutMs);
10595
10604
  session.subscribeInput(onData);
10596
- this.writeOsc("\x1B]4;0;?\x07");
10605
+ this.writeOsc("\x1B]4;0;?\x07", true);
10597
10606
  });
10598
10607
  }
10599
- async queryPalette(indices, timeoutMs = 1200) {
10608
+ async queryPalette(indices, timeoutMs = 1200, idleTimeoutMs = env.OTUI_PALETTE_IDLE_TIMEOUT_MS) {
10600
10609
  const out = this.stdout;
10601
10610
  const results = new Map;
10602
10611
  indices.forEach((i) => results.set(i, null));
@@ -10631,14 +10640,15 @@ class TerminalPalette {
10631
10640
  finish();
10632
10641
  return;
10633
10642
  }
10634
- idleTimer = session.resetTimer(idleTimer, finish, 150);
10643
+ idleTimer = session.resetTimer(idleTimer, finish, idleTimeoutMs);
10635
10644
  };
10636
10645
  session.setTimer(finish, timeoutMs);
10637
10646
  session.subscribeInput(onData);
10638
- this.writeOsc(indices.map((i) => `\x1B]4;${i};?\x07`).join(""));
10647
+ this.writeOsc(indices.map((i) => `\x1B]4;${i};?\x07`).join(""), true);
10648
+ idleTimer = session.resetTimer(idleTimer, finish, idleTimeoutMs);
10639
10649
  });
10640
10650
  }
10641
- async querySpecialColors(timeoutMs = 1200) {
10651
+ async querySpecialColors(timeoutMs = 1200, idleTimeoutMs = env.OTUI_PALETTE_IDLE_TIMEOUT_MS) {
10642
10652
  const out = this.stdout;
10643
10653
  const results = {
10644
10654
  10: null,
@@ -10651,6 +10661,7 @@ class TerminalPalette {
10651
10661
  17: null,
10652
10662
  19: null
10653
10663
  };
10664
+ const queries = this.inTmux ? [10, 11, 12] : [10, 11, 12, 13, 14, 15, 16, 17, 19];
10654
10665
  if (!out.isTTY || !this.stdin.isTTY) {
10655
10666
  return results;
10656
10667
  }
@@ -10680,28 +10691,18 @@ class TerminalPalette {
10680
10691
  }
10681
10692
  if (buffer.length > 8192)
10682
10693
  buffer = buffer.slice(-4096);
10683
- const done = Object.values(results).filter((v) => v !== null).length;
10684
- if (done === Object.keys(results).length) {
10694
+ if (queries.every((idx) => results[idx] !== null)) {
10685
10695
  finish();
10686
10696
  return;
10687
10697
  }
10688
10698
  if (!updated)
10689
10699
  return;
10690
- idleTimer = session.resetTimer(idleTimer, finish, 150);
10700
+ idleTimer = session.resetTimer(idleTimer, finish, idleTimeoutMs);
10691
10701
  };
10692
10702
  session.setTimer(finish, timeoutMs);
10693
10703
  session.subscribeInput(onData);
10694
- this.writeOsc([
10695
- "\x1B]10;?\x07",
10696
- "\x1B]11;?\x07",
10697
- "\x1B]12;?\x07",
10698
- "\x1B]13;?\x07",
10699
- "\x1B]14;?\x07",
10700
- "\x1B]15;?\x07",
10701
- "\x1B]16;?\x07",
10702
- "\x1B]17;?\x07",
10703
- "\x1B]19;?\x07"
10704
- ].join(""));
10704
+ this.writeOsc(queries.map((idx) => `\x1B]${idx};?\x07`).join(""));
10705
+ idleTimer = session.resetTimer(idleTimer, finish, idleTimeoutMs);
10705
10706
  });
10706
10707
  }
10707
10708
  async detect(options) {
@@ -10722,9 +10723,10 @@ class TerminalPalette {
10722
10723
  };
10723
10724
  }
10724
10725
  const indicesToQuery = [...Array(size).keys()];
10726
+ const idleTimeout = env.OTUI_PALETTE_IDLE_TIMEOUT_MS;
10725
10727
  const [paletteResults, specialColors] = await Promise.all([
10726
- this.queryPalette(indicesToQuery, timeout),
10727
- this.querySpecialColors(timeout)
10728
+ this.queryPalette(indicesToQuery, timeout, idleTimeout),
10729
+ this.querySpecialColors(timeout, idleTimeout)
10728
10730
  ]);
10729
10731
  return {
10730
10732
  palette: [...Array(size).keys()].map((i) => paletteResults.get(i) ?? null),
@@ -10740,8 +10742,8 @@ class TerminalPalette {
10740
10742
  };
10741
10743
  }
10742
10744
  }
10743
- function createTerminalPalette(stdin, stdout, writeFn, isLegacyTmux, oscSource, clock) {
10744
- return new TerminalPalette(stdin, stdout, writeFn, isLegacyTmux, oscSource, clock);
10745
+ function createTerminalPalette(options) {
10746
+ return new TerminalPalette(options);
10745
10747
  }
10746
10748
  var DEFAULT_FOREGROUND_FALLBACK = RGBA.fromInts(...DEFAULT_FOREGROUND_RGB);
10747
10749
  var DEFAULT_BACKGROUND_FALLBACK = RGBA.fromInts(...DEFAULT_BACKGROUND_RGB);
@@ -10826,1449 +10828,1563 @@ function detectLinks(chunks, context) {
10826
10828
  }
10827
10829
  return chunks;
10828
10830
  }
10829
- // src/zig.ts
10830
- import { dlopen as dlopen2, toArrayBuffer as toArrayBuffer5, JSCallback, ptr as ptr5 } from "bun:ffi";
10831
- import { existsSync as existsSync2, writeFileSync } from "fs";
10832
- import { EventEmitter as EventEmitter4 } from "events";
10833
-
10834
- // src/buffer.ts
10835
- import { toArrayBuffer, ptr } from "bun:ffi";
10836
- function packDrawOptions(border2, shouldFill, titleAlignment, bottomTitleAlignment) {
10837
- let packed = 0;
10838
- if (border2 === true) {
10839
- packed |= 15;
10840
- } else if (Array.isArray(border2)) {
10841
- if (border2.includes("top"))
10842
- packed |= 8;
10843
- if (border2.includes("right"))
10844
- packed |= 4;
10845
- if (border2.includes("bottom"))
10846
- packed |= 2;
10847
- if (border2.includes("left"))
10848
- packed |= 1;
10849
- }
10850
- if (shouldFill) {
10851
- packed |= 1 << 4;
10852
- }
10853
- const alignmentMap = {
10854
- left: 0,
10855
- center: 1,
10856
- right: 2
10857
- };
10858
- const alignment = alignmentMap[titleAlignment];
10859
- const bottomAlignment = alignmentMap[bottomTitleAlignment];
10860
- packed |= alignment << 5;
10861
- packed |= bottomAlignment << 7;
10862
- return packed;
10831
+ // src/platform/ffi.ts
10832
+ import { fileURLToPath as fileURLToPath2 } from "url";
10833
+ var FFIType = {
10834
+ char: "char",
10835
+ int8_t: "int8_t",
10836
+ i8: "i8",
10837
+ uint8_t: "uint8_t",
10838
+ u8: "u8",
10839
+ int16_t: "int16_t",
10840
+ i16: "i16",
10841
+ uint16_t: "uint16_t",
10842
+ u16: "u16",
10843
+ int32_t: "int32_t",
10844
+ i32: "i32",
10845
+ int: "int",
10846
+ uint32_t: "uint32_t",
10847
+ u32: "u32",
10848
+ int64_t: "int64_t",
10849
+ i64: "i64",
10850
+ uint64_t: "uint64_t",
10851
+ u64: "u64",
10852
+ double: "double",
10853
+ f64: "f64",
10854
+ float: "float",
10855
+ f32: "f32",
10856
+ bool: "bool",
10857
+ ptr: "ptr",
10858
+ pointer: "pointer",
10859
+ void: "void",
10860
+ cstring: "cstring",
10861
+ function: "function",
10862
+ usize: "usize",
10863
+ callback: "callback",
10864
+ napi_env: "napi_env",
10865
+ napi_value: "napi_value",
10866
+ buffer: "buffer"
10867
+ };
10868
+ var FFI_UNAVAILABLE = "OpenTUI native FFI is not available for this runtime yet";
10869
+ var BUN_DLOPEN_NULL = "Bun FFI backend does not support dlopen(null)";
10870
+ var LIBRARY_CLOSED = "Cannot create FFI callback after library.close() has been called";
10871
+ var NODE_CALLBACK_THREADSAFE = "Node FFI callbacks are same-thread only and do not support threadsafe callbacks";
10872
+ var NODE_NAPI_UNSUPPORTED = "Node FFI backend does not support Bun N-API FFI types";
10873
+ var NODE_POINTER_OVERRIDE = "Node FFI backend does not support FFIFunction.ptr overrides";
10874
+ var NODE_PTR_VALUE = "node:ffi ptr() only supports ArrayBuffer and ArrayBufferView values backed by ArrayBuffer";
10875
+ var NODE_STRING_RETURN = "Node FFI backend does not normalize string return values (yet)";
10876
+ var NODE_USIZE_UNSUPPORTED = "Node FFI backend does not support usize until (yet)";
10877
+ var POINTER_NEGATIVE = "Pointer must be non-negative";
10878
+ var POINTER_UNSAFE = "Pointer exceeds safe integer range";
10879
+ function unavailable(cause) {
10880
+ throw new Error(FFI_UNAVAILABLE, { cause });
10863
10881
  }
10864
-
10865
- class OptimizedBuffer {
10866
- static fbIdCounter = 0;
10867
- id;
10868
- lib;
10869
- bufferPtr;
10870
- _width;
10871
- _height;
10872
- _widthMethod;
10873
- respectAlpha = false;
10874
- _rawBuffers = null;
10875
- _destroyed = false;
10876
- get ptr() {
10877
- return this.bufferPtr;
10878
- }
10879
- guard() {
10880
- if (this._destroyed)
10881
- throw new Error(`Buffer ${this.id} is destroyed`);
10882
- }
10883
- ensureRawBufferViews() {
10884
- if (this._rawBuffers !== null) {
10885
- return;
10882
+ function createUnsupportedBackend(cause) {
10883
+ return {
10884
+ dlopen() {
10885
+ return unavailable(cause);
10886
+ },
10887
+ ptr() {
10888
+ return unavailable(cause);
10889
+ },
10890
+ suffix: "",
10891
+ toArrayBuffer() {
10892
+ return unavailable(cause);
10886
10893
  }
10887
- const size = this._width * this._height;
10888
- const charPtr = this.lib.bufferGetCharPtr(this.bufferPtr);
10889
- const fgPtr = this.lib.bufferGetFgPtr(this.bufferPtr);
10890
- const bgPtr = this.lib.bufferGetBgPtr(this.bufferPtr);
10891
- const attributesPtr = this.lib.bufferGetAttributesPtr(this.bufferPtr);
10892
- this._rawBuffers = {
10893
- char: new Uint32Array(toArrayBuffer(charPtr, 0, size * 4)),
10894
- fg: new Uint16Array(toArrayBuffer(fgPtr, 0, size * 4 * 2)),
10895
- bg: new Uint16Array(toArrayBuffer(bgPtr, 0, size * 4 * 2)),
10896
- attributes: new Uint32Array(toArrayBuffer(attributesPtr, 0, size * 4))
10897
- };
10898
- }
10899
- get buffers() {
10900
- this.guard();
10901
- this.ensureRawBufferViews();
10902
- return this._rawBuffers;
10903
- }
10904
- constructor(lib, ptr2, width, height, options) {
10905
- this.id = options.id || `fb_${OptimizedBuffer.fbIdCounter++}`;
10906
- this.lib = lib;
10907
- this.respectAlpha = options.respectAlpha || false;
10908
- this._width = width;
10909
- this._height = height;
10910
- this._widthMethod = options.widthMethod || "unicode";
10911
- this.bufferPtr = ptr2;
10894
+ };
10895
+ }
10896
+ var isBun = typeof process !== "undefined" && typeof process.versions === "object" && process.versions !== null && typeof process.versions.bun === "string";
10897
+ var backend = await loadBackend();
10898
+ function importModule(specifier) {
10899
+ return import(specifier);
10900
+ }
10901
+ async function loadBackend() {
10902
+ if (isBun) {
10903
+ return createBunBackend(await importModule("bun:ffi"));
10912
10904
  }
10913
- static create(width, height, widthMethod, options = {}) {
10914
- const lib = resolveRenderLib();
10915
- const respectAlpha = options.respectAlpha || false;
10916
- const id = options.id && options.id.trim() !== "" ? options.id : "unnamed buffer";
10917
- const buffer = lib.createOptimizedBuffer(width, height, widthMethod, respectAlpha, id);
10918
- return buffer;
10905
+ try {
10906
+ const nodeFfi = await importModule("node:ffi");
10907
+ return createNodeBackend(nodeFfi.default ?? nodeFfi);
10908
+ } catch (error) {
10909
+ return createUnsupportedBackend(error);
10919
10910
  }
10920
- get widthMethod() {
10921
- return this._widthMethod;
10911
+ }
10912
+ function toPointer(value) {
10913
+ if (isBun && typeof value === "bigint") {
10914
+ return toSafeNumberPointer(value);
10922
10915
  }
10923
- get width() {
10924
- return this._width;
10916
+ if (!isBun && typeof value === "number") {
10917
+ return toSafeBigIntPointer(value);
10925
10918
  }
10926
- get height() {
10927
- return this._height;
10919
+ return value;
10920
+ }
10921
+ function ffiBool(value) {
10922
+ return value ? 1 : 0;
10923
+ }
10924
+ function toSafeNumberPointer(pointer) {
10925
+ if (pointer < 0n) {
10926
+ throw new Error(POINTER_NEGATIVE);
10928
10927
  }
10929
- setRespectAlpha(respectAlpha) {
10930
- this.guard();
10931
- this.lib.bufferSetRespectAlpha(this.bufferPtr, respectAlpha);
10932
- this.respectAlpha = respectAlpha;
10928
+ if (pointer > BigInt(Number.MAX_SAFE_INTEGER)) {
10929
+ throw new Error(POINTER_UNSAFE);
10933
10930
  }
10934
- getNativeId() {
10935
- this.guard();
10936
- return this.lib.bufferGetId(this.bufferPtr);
10931
+ return Number(pointer);
10932
+ }
10933
+ function toSafeBigIntPointer(pointer) {
10934
+ if (pointer < 0) {
10935
+ throw new Error(POINTER_NEGATIVE);
10937
10936
  }
10938
- getRealCharBytes(addLineBreaks = false) {
10939
- this.guard();
10940
- const realSize = this.lib.bufferGetRealCharSize(this.bufferPtr);
10941
- const outputBuffer = new Uint8Array(realSize);
10942
- const bytesWritten = this.lib.bufferWriteResolvedChars(this.bufferPtr, outputBuffer, addLineBreaks);
10943
- return outputBuffer.slice(0, bytesWritten);
10937
+ if (!Number.isSafeInteger(pointer)) {
10938
+ throw new Error(POINTER_UNSAFE);
10944
10939
  }
10945
- getSpanLines() {
10946
- this.guard();
10947
- const { char, fg: fg2, bg: bg2, attributes } = this.buffers;
10948
- const lines = [];
10949
- const CHAR_FLAG_CONTINUATION = 3221225472 | 0;
10950
- const CHAR_FLAG_MASK = 3221225472 | 0;
10951
- const realTextBytes = this.getRealCharBytes(true);
10952
- const realTextLines = new TextDecoder().decode(realTextBytes).split(`
10953
- `);
10954
- for (let y = 0;y < this._height; y++) {
10955
- const spans = [];
10956
- let currentSpan = null;
10957
- const lineChars = [...realTextLines[y] || ""];
10958
- let charIdx = 0;
10959
- for (let x = 0;x < this._width; x++) {
10960
- const i = y * this._width + x;
10961
- const cp = char[i];
10962
- const cellFg = RGBA.fromArray(fg2.slice(i * 4, i * 4 + 4));
10963
- const cellBg = RGBA.fromArray(bg2.slice(i * 4, i * 4 + 4));
10964
- const cellAttrs = attributes[i] & 255;
10965
- const isContinuation = (cp & CHAR_FLAG_MASK) === CHAR_FLAG_CONTINUATION;
10966
- const cellChar = isContinuation ? "" : lineChars[charIdx++] ?? " ";
10967
- if (currentSpan && currentSpan.fg.equals(cellFg) && currentSpan.bg.equals(cellBg) && currentSpan.attributes === cellAttrs) {
10968
- currentSpan.text += cellChar;
10969
- currentSpan.width += 1;
10970
- } else {
10971
- if (currentSpan) {
10972
- spans.push(currentSpan);
10973
- }
10974
- currentSpan = {
10975
- text: cellChar,
10976
- fg: cellFg,
10977
- bg: cellBg,
10978
- attributes: cellAttrs,
10979
- width: 1
10980
- };
10981
- }
10940
+ return BigInt(pointer);
10941
+ }
10942
+ function createManagedCallback(raw, callbacks) {
10943
+ let ptr = raw.ptr;
10944
+ let closed = false;
10945
+ const instance = {
10946
+ get ptr() {
10947
+ return ptr;
10948
+ },
10949
+ get threadsafe() {
10950
+ return raw.threadsafe;
10951
+ },
10952
+ close() {
10953
+ if (closed) {
10954
+ return;
10982
10955
  }
10983
- if (currentSpan) {
10984
- spans.push(currentSpan);
10956
+ closed = true;
10957
+ callbacks.delete(instance);
10958
+ try {
10959
+ raw.close();
10960
+ } finally {
10961
+ ptr = null;
10985
10962
  }
10986
- lines.push({ spans });
10987
10963
  }
10988
- return lines;
10989
- }
10990
- clear(bg2 = RGBA.fromValues(0, 0, 0, 1)) {
10991
- this.guard();
10992
- this.lib.bufferClear(this.bufferPtr, bg2);
10993
- }
10994
- setCell(x, y, char, fg2, bg2, attributes = 0) {
10995
- this.guard();
10996
- this.lib.bufferSetCell(this.bufferPtr, x, y, char, fg2, bg2, attributes);
10997
- }
10998
- setCellWithAlphaBlending(x, y, char, fg2, bg2, attributes = 0) {
10999
- this.guard();
11000
- this.lib.bufferSetCellWithAlphaBlending(this.bufferPtr, x, y, char, fg2, bg2, attributes);
11001
- }
11002
- drawText(text, x, y, fg2, bg2, attributes = 0, selection2) {
11003
- this.guard();
11004
- if (!selection2) {
11005
- this.lib.bufferDrawText(this.bufferPtr, text, x, y, fg2, bg2, attributes);
11006
- return;
11007
- }
11008
- const { start, end } = selection2;
11009
- let selectionBg;
11010
- let selectionFg;
11011
- if (selection2.bgColor) {
11012
- selectionBg = selection2.bgColor;
11013
- selectionFg = selection2.fgColor || fg2;
11014
- } else {
11015
- const defaultBg = bg2 || RGBA.fromValues(0, 0, 0, 0);
11016
- selectionFg = defaultBg.a > 0 ? defaultBg : RGBA.fromValues(0, 0, 0, 1);
11017
- selectionBg = fg2;
11018
- }
11019
- if (start > 0) {
11020
- const beforeText = text.slice(0, start);
11021
- this.lib.bufferDrawText(this.bufferPtr, beforeText, x, y, fg2, bg2, attributes);
11022
- }
11023
- if (end > start) {
11024
- const selectedText = text.slice(start, end);
11025
- this.lib.bufferDrawText(this.bufferPtr, selectedText, x + start, y, selectionFg, selectionBg, attributes);
11026
- }
11027
- if (end < text.length) {
11028
- const afterText = text.slice(end);
11029
- this.lib.bufferDrawText(this.bufferPtr, afterText, x + end, y, fg2, bg2, attributes);
11030
- }
11031
- }
11032
- fillRect(x, y, width, height, bg2) {
11033
- this.lib.bufferFillRect(this.bufferPtr, x, y, width, height, bg2);
11034
- }
11035
- colorMatrix(matrix, cellMask, strength = 1, target = 3 /* Both */) {
11036
- this.guard();
11037
- if (matrix.length !== 16)
11038
- throw new RangeError(`colorMatrix matrix must have length 16, got ${matrix.length}`);
11039
- const cellMaskCount = Math.floor(cellMask.length / 3);
11040
- this.lib.bufferColorMatrix(this.bufferPtr, ptr(matrix), ptr(cellMask), cellMaskCount, strength, target);
11041
- }
11042
- colorMatrixUniform(matrix, strength = 1, target = 3 /* Both */) {
11043
- this.guard();
11044
- if (matrix.length !== 16)
11045
- throw new RangeError(`colorMatrixUniform matrix must have length 16, got ${matrix.length}`);
11046
- if (strength === 0)
11047
- return;
11048
- this.lib.bufferColorMatrixUniform(this.bufferPtr, ptr(matrix), strength, target);
11049
- }
11050
- drawFrameBuffer(destX, destY, frameBuffer, sourceX, sourceY, sourceWidth, sourceHeight) {
11051
- this.guard();
11052
- this.lib.drawFrameBuffer(this.bufferPtr, destX, destY, frameBuffer.ptr, sourceX, sourceY, sourceWidth, sourceHeight);
11053
- }
11054
- destroy() {
11055
- if (this._destroyed)
11056
- return;
11057
- this._destroyed = true;
11058
- this.lib.destroyOptimizedBuffer(this.bufferPtr);
11059
- }
11060
- drawTextBuffer(textBufferView, x, y) {
11061
- this.guard();
11062
- this.lib.bufferDrawTextBufferView(this.bufferPtr, textBufferView.ptr, x, y);
11063
- }
11064
- drawEditorView(editorView, x, y) {
11065
- this.guard();
11066
- this.lib.bufferDrawEditorView(this.bufferPtr, editorView.ptr, x, y);
11067
- }
11068
- drawSuperSampleBuffer(x, y, pixelDataPtr, pixelDataLength, format, alignedBytesPerRow) {
11069
- this.guard();
11070
- this.lib.bufferDrawSuperSampleBuffer(this.bufferPtr, x, y, pixelDataPtr, pixelDataLength, format, alignedBytesPerRow);
11071
- }
11072
- drawPackedBuffer(dataPtr, dataLen, posX, posY, terminalWidthCells, terminalHeightCells) {
11073
- this.guard();
11074
- this.lib.bufferDrawPackedBuffer(this.bufferPtr, dataPtr, dataLen, posX, posY, terminalWidthCells, terminalHeightCells);
11075
- }
11076
- drawGrayscaleBuffer(posX, posY, intensities, srcWidth, srcHeight, fg2 = null, bg2 = null) {
11077
- this.guard();
11078
- this.lib.bufferDrawGrayscaleBuffer(this.bufferPtr, posX, posY, ptr(intensities), srcWidth, srcHeight, fg2, bg2);
11079
- }
11080
- drawGrayscaleBufferSupersampled(posX, posY, intensities, srcWidth, srcHeight, fg2 = null, bg2 = null) {
11081
- this.guard();
11082
- this.lib.bufferDrawGrayscaleBufferSupersampled(this.bufferPtr, posX, posY, ptr(intensities), srcWidth, srcHeight, fg2, bg2);
11083
- }
11084
- resize(width, height) {
11085
- this.guard();
11086
- if (this._width === width && this._height === height)
11087
- return;
11088
- this._width = width;
11089
- this._height = height;
11090
- this._rawBuffers = null;
11091
- this.lib.bufferResize(this.bufferPtr, width, height);
11092
- }
11093
- drawBox(options) {
11094
- this.guard();
11095
- const style = parseBorderStyle(options.borderStyle, "single");
11096
- const borderChars = options.customBorderChars ?? BorderCharArrays[style];
11097
- const packedOptions = packDrawOptions(options.border, options.shouldFill ?? false, options.titleAlignment || "left", options.bottomTitleAlignment || "left");
11098
- this.lib.bufferDrawBox(this.bufferPtr, options.x, options.y, options.width, options.height, borderChars, packedOptions, options.borderColor, options.backgroundColor, options.title ?? null, options.bottomTitle ?? null);
11099
- }
11100
- pushScissorRect(x, y, width, height) {
11101
- this.guard();
11102
- this.lib.bufferPushScissorRect(this.bufferPtr, x, y, width, height);
11103
- }
11104
- popScissorRect() {
11105
- this.guard();
11106
- this.lib.bufferPopScissorRect(this.bufferPtr);
11107
- }
11108
- clearScissorRects() {
11109
- this.guard();
11110
- this.lib.bufferClearScissorRects(this.bufferPtr);
11111
- }
11112
- pushOpacity(opacity) {
11113
- this.guard();
11114
- this.lib.bufferPushOpacity(this.bufferPtr, Math.max(0, Math.min(1, opacity)));
11115
- }
11116
- popOpacity() {
11117
- this.guard();
11118
- this.lib.bufferPopOpacity(this.bufferPtr);
11119
- }
11120
- getCurrentOpacity() {
11121
- this.guard();
11122
- return this.lib.bufferGetCurrentOpacity(this.bufferPtr);
11123
- }
11124
- clearOpacity() {
11125
- this.guard();
11126
- this.lib.bufferClearOpacity(this.bufferPtr);
11127
- }
11128
- encodeUnicode(text) {
11129
- this.guard();
11130
- return this.lib.encodeUnicode(text, this._widthMethod);
11131
- }
11132
- freeUnicode(encoded) {
11133
- this.guard();
11134
- this.lib.freeUnicode(encoded);
11135
- }
11136
- drawGrid(options) {
11137
- this.guard();
11138
- const columnCount = Math.max(0, options.columnOffsets.length - 1);
11139
- const rowCount = Math.max(0, options.rowOffsets.length - 1);
11140
- this.lib.bufferDrawGrid(this.bufferPtr, options.borderChars, options.borderFg, options.borderBg, options.columnOffsets, columnCount, options.rowOffsets, rowCount, {
11141
- drawInner: options.drawInner,
11142
- drawOuter: options.drawOuter
11143
- });
11144
- }
11145
- drawChar(char, x, y, fg2, bg2, attributes = 0) {
11146
- this.guard();
11147
- this.lib.bufferDrawChar(this.bufferPtr, char, x, y, fg2, bg2, attributes);
11148
- }
11149
- }
11150
-
11151
- // ../../node_modules/.bun/bun-ffi-structs@0.1.2+1fb4c65d43e298b9/node_modules/bun-ffi-structs/index.js
11152
- import { ptr as ptr2, toArrayBuffer as toArrayBuffer2 } from "bun:ffi";
11153
- function fatalError(...args) {
11154
- const message = args.join(" ");
11155
- console.error("FATAL ERROR:", message);
11156
- throw new Error(message);
11157
- }
11158
- var pointerSize = process.arch === "x64" || process.arch === "arm64" ? 8 : 4;
11159
- var typeSizes = {
11160
- u8: 1,
11161
- bool_u8: 1,
11162
- bool_u32: 4,
11163
- u16: 2,
11164
- i16: 2,
11165
- u32: 4,
11166
- u64: 8,
11167
- f32: 4,
11168
- f64: 8,
11169
- pointer: pointerSize,
11170
- i32: 4
11171
- };
11172
- var primitiveKeys = Object.keys(typeSizes);
11173
- function isPrimitiveType(type) {
11174
- return typeof type === "string" && primitiveKeys.includes(type);
11175
- }
11176
- var typeAlignments = { ...typeSizes };
11177
- var typeGetters = {
11178
- u8: (view, offset) => view.getUint8(offset),
11179
- bool_u8: (view, offset) => Boolean(view.getUint8(offset)),
11180
- bool_u32: (view, offset) => Boolean(view.getUint32(offset, true)),
11181
- u16: (view, offset) => view.getUint16(offset, true),
11182
- i16: (view, offset) => view.getInt16(offset, true),
11183
- u32: (view, offset) => view.getUint32(offset, true),
11184
- u64: (view, offset) => view.getBigUint64(offset, true),
11185
- f32: (view, offset) => view.getFloat32(offset, true),
11186
- f64: (view, offset) => view.getFloat64(offset, true),
11187
- i32: (view, offset) => view.getInt32(offset, true),
11188
- pointer: (view, offset) => pointerSize === 8 ? view.getBigUint64(offset, true) : BigInt(view.getUint32(offset, true))
11189
- };
11190
- function isObjectPointerDef(type) {
11191
- return typeof type === "object" && type !== null && type.__type === "objectPointer";
11192
- }
11193
- function alignOffset(offset, align) {
11194
- return offset + (align - 1) & ~(align - 1);
10964
+ };
10965
+ callbacks.add(instance);
10966
+ return instance;
11195
10967
  }
11196
- function enumTypeError(value) {
11197
- throw new TypeError(`Invalid enum value: ${value}`);
10968
+ function normalizeBunDefinitions(definitions) {
10969
+ return Object.fromEntries(Object.entries(definitions).map(([name, definition]) => [name, normalizeBunDefinition(definition)]));
11198
10970
  }
11199
- function defineEnum(mapping, base = "u32") {
11200
- const reverse2 = Object.fromEntries(Object.entries(mapping).map(([k, v]) => [v, k]));
10971
+ function normalizeBunDefinition(definition) {
11201
10972
  return {
11202
- __type: "enum",
11203
- type: base,
11204
- to(value) {
11205
- return typeof value === "number" ? value : mapping[value] ?? enumTypeError(String(value));
11206
- },
11207
- from(value) {
11208
- return reverse2[value] ?? enumTypeError(String(value));
11209
- },
11210
- enum: mapping
10973
+ args: definition.args,
10974
+ returns: definition.returns,
10975
+ ptr: definition.ptr == null ? undefined : toBunPointer(definition.ptr),
10976
+ threadsafe: definition.threadsafe
11211
10977
  };
11212
10978
  }
11213
- function isEnum(type) {
11214
- return typeof type === "object" && type.__type === "enum";
11215
- }
11216
- function isStruct(type) {
11217
- return typeof type === "object" && type.__type === "struct";
10979
+ function toBunPointer(pointer) {
10980
+ return typeof pointer === "bigint" ? toSafeNumberPointer(pointer) : pointer;
11218
10981
  }
11219
- function primitivePackers(type) {
11220
- let pack;
11221
- let unpack;
11222
- switch (type) {
11223
- case "u8":
11224
- pack = (view, off, val) => view.setUint8(off, val);
11225
- unpack = (view, off) => view.getUint8(off);
11226
- break;
11227
- case "bool_u8":
11228
- pack = (view, off, val) => view.setUint8(off, val ? 1 : 0);
11229
- unpack = (view, off) => Boolean(view.getUint8(off));
11230
- break;
11231
- case "bool_u32":
11232
- pack = (view, off, val) => view.setUint32(off, val ? 1 : 0, true);
11233
- unpack = (view, off) => Boolean(view.getUint32(off, true));
11234
- break;
11235
- case "u16":
11236
- pack = (view, off, val) => view.setUint16(off, val, true);
11237
- unpack = (view, off) => view.getUint16(off, true);
11238
- break;
11239
- case "i16":
11240
- pack = (view, off, val) => view.setInt16(off, val, true);
11241
- unpack = (view, off) => view.getInt16(off, true);
11242
- break;
11243
- case "u32":
11244
- pack = (view, off, val) => view.setUint32(off, val, true);
11245
- unpack = (view, off) => view.getUint32(off, true);
11246
- break;
11247
- case "i32":
11248
- pack = (view, off, val) => view.setInt32(off, val, true);
11249
- unpack = (view, off) => view.getInt32(off, true);
11250
- break;
11251
- case "u64":
11252
- pack = (view, off, val) => view.setBigUint64(off, BigInt(val), true);
11253
- unpack = (view, off) => view.getBigUint64(off, true);
11254
- break;
11255
- case "f32":
11256
- pack = (view, off, val) => view.setFloat32(off, val, true);
11257
- unpack = (view, off) => view.getFloat32(off, true);
11258
- break;
11259
- case "f64":
11260
- pack = (view, off, val) => view.setFloat64(off, val, true);
11261
- unpack = (view, off) => view.getFloat64(off, true);
11262
- break;
11263
- case "pointer":
11264
- pack = (view, off, val) => {
11265
- pointerSize === 8 ? view.setBigUint64(off, val ? BigInt(val) : 0n, true) : view.setUint32(off, val ? Number(val) : 0, true);
11266
- };
11267
- unpack = (view, off) => {
11268
- const bint = pointerSize === 8 ? view.getBigUint64(off, true) : BigInt(view.getUint32(off, true));
11269
- return Number(bint);
11270
- };
11271
- break;
11272
- default:
11273
- fatalError(`Unsupported primitive type: ${type}`);
11274
- }
11275
- return { pack, unpack };
11276
- }
11277
- var { pack: pointerPacker, unpack: pointerUnpacker } = primitivePackers("pointer");
11278
- function packObjectArray(val) {
11279
- const buffer = new ArrayBuffer(val.length * pointerSize);
11280
- const bufferView = new DataView(buffer);
11281
- for (let i = 0;i < val.length; i++) {
11282
- const instance = val[i];
11283
- const ptrValue = instance?.ptr ?? null;
11284
- pointerPacker(bufferView, i * pointerSize, ptrValue);
11285
- }
11286
- return bufferView;
11287
- }
11288
- var encoder = new TextEncoder;
11289
- var decoder = new TextDecoder;
11290
- function defineStruct(fields, structDefOptions) {
11291
- let offset = 0;
11292
- let maxAlign = 1;
11293
- const layout = [];
11294
- const lengthOfFields = {};
11295
- const lengthOfRequested = [];
11296
- const arrayFieldsMetadata = {};
11297
- for (const [name, typeOrStruct, options = {}] of fields) {
11298
- if (options.condition && !options.condition()) {
11299
- continue;
11300
- }
11301
- let size = 0, align = 0;
11302
- let pack;
11303
- let unpack;
11304
- let needsLengthOf = false;
11305
- let lengthOfDef = null;
11306
- if (isPrimitiveType(typeOrStruct)) {
11307
- size = typeSizes[typeOrStruct];
11308
- align = typeAlignments[typeOrStruct];
11309
- ({ pack, unpack } = primitivePackers(typeOrStruct));
11310
- } else if (typeof typeOrStruct === "string" && typeOrStruct === "cstring") {
11311
- size = pointerSize;
11312
- align = pointerSize;
11313
- pack = (view, off, val) => {
11314
- const bufPtr = val ? ptr2(encoder.encode(val + "\x00")) : null;
11315
- pointerPacker(view, off, bufPtr);
11316
- };
11317
- unpack = (view, off) => {
11318
- const ptrVal = pointerUnpacker(view, off);
11319
- return ptrVal;
11320
- };
11321
- } else if (typeof typeOrStruct === "string" && typeOrStruct === "char*") {
11322
- size = pointerSize;
11323
- align = pointerSize;
11324
- pack = (view, off, val) => {
11325
- const bufPtr = val ? ptr2(encoder.encode(val)) : null;
11326
- pointerPacker(view, off, bufPtr);
11327
- };
11328
- unpack = (view, off) => {
11329
- const ptrVal = pointerUnpacker(view, off);
11330
- return ptrVal;
11331
- };
11332
- needsLengthOf = true;
11333
- } else if (isEnum(typeOrStruct)) {
11334
- const base = typeOrStruct.type;
11335
- size = typeSizes[base];
11336
- align = typeAlignments[base];
11337
- const { pack: packEnum } = primitivePackers(base);
11338
- pack = (view, off, val) => {
11339
- const num = typeOrStruct.to(val);
11340
- packEnum(view, off, num);
11341
- };
11342
- unpack = (view, off) => {
11343
- const raw = typeGetters[base](view, off);
11344
- return typeOrStruct.from(raw);
11345
- };
11346
- } else if (isStruct(typeOrStruct)) {
11347
- if (options.asPointer === true) {
11348
- size = pointerSize;
11349
- align = pointerSize;
11350
- pack = (view, off, val, obj, options2) => {
11351
- if (!val) {
11352
- pointerPacker(view, off, null);
10982
+ function createBunBackend(bun) {
10983
+ return {
10984
+ dlopen(path5, symbols) {
10985
+ if (path5 === null) {
10986
+ throw new Error(BUN_DLOPEN_NULL);
10987
+ }
10988
+ const library = bun.dlopen(path5, normalizeBunDefinitions(symbols));
10989
+ const callbacks = new Set;
10990
+ let closed = false;
10991
+ return {
10992
+ symbols: library.symbols,
10993
+ createCallback(callback, definition) {
10994
+ if (closed) {
10995
+ throw new Error(LIBRARY_CLOSED);
10996
+ }
10997
+ const raw = new bun.JSCallback(callback, normalizeBunDefinition(definition));
10998
+ return createManagedCallback(raw, callbacks);
10999
+ },
11000
+ close() {
11001
+ if (closed) {
11353
11002
  return;
11354
11003
  }
11355
- const nestedBuf = typeOrStruct.pack(val, options2);
11356
- pointerPacker(view, off, ptr2(nestedBuf));
11357
- };
11358
- unpack = (view, off) => {
11359
- throw new Error("Not implemented yet");
11360
- };
11361
- } else {
11362
- size = typeOrStruct.size;
11363
- align = typeOrStruct.align;
11364
- pack = (view, off, val, obj, options2) => {
11365
- const nestedBuf = typeOrStruct.pack(val, options2);
11366
- const nestedView = new Uint8Array(nestedBuf);
11367
- const dView = new Uint8Array(view.buffer);
11368
- dView.set(nestedView, off);
11369
- };
11370
- unpack = (view, off) => {
11371
- const slice = view.buffer.slice(off, off + size);
11372
- return typeOrStruct.unpack(slice);
11373
- };
11374
- }
11375
- } else if (isObjectPointerDef(typeOrStruct)) {
11376
- size = pointerSize;
11377
- align = pointerSize;
11378
- pack = (view, off, value) => {
11379
- const ptrValue = value?.ptr ?? null;
11380
- if (ptrValue === undefined) {
11381
- console.warn(`Field '${name}' expected object with '.ptr' property, but got undefined pointer value from:`, value);
11382
- pointerPacker(view, off, null);
11383
- } else {
11384
- pointerPacker(view, off, ptrValue);
11004
+ closed = true;
11005
+ try {
11006
+ library.close();
11007
+ } finally {
11008
+ for (const callback of [...callbacks]) {
11009
+ callback.close();
11010
+ }
11011
+ }
11385
11012
  }
11386
11013
  };
11387
- unpack = (view, off) => {
11388
- return pointerUnpacker(view, off);
11389
- };
11390
- } else if (Array.isArray(typeOrStruct) && typeOrStruct.length === 1 && typeOrStruct[0] !== undefined) {
11391
- const [def] = typeOrStruct;
11392
- size = pointerSize;
11393
- align = pointerSize;
11394
- let arrayElementSize;
11395
- if (isEnum(def)) {
11396
- arrayElementSize = typeSizes[def.type];
11397
- pack = (view, off, val, obj) => {
11398
- if (!val || val.length === 0) {
11399
- pointerPacker(view, off, null);
11400
- return;
11014
+ },
11015
+ ptr: bun.ptr,
11016
+ suffix: bun.suffix,
11017
+ toArrayBuffer(pointer, offset, length) {
11018
+ return bun.toArrayBuffer(toBunPointer(pointer), offset, length);
11019
+ }
11020
+ };
11021
+ }
11022
+ function createNodeBackend(nodeFfi) {
11023
+ return {
11024
+ dlopen(path5, symbols) {
11025
+ const { lib, functions } = nodeFfi.dlopen(toNodeLibraryPath(path5), normalizeNodeDefinitions(symbols));
11026
+ const callbacks = new Set;
11027
+ let closed = false;
11028
+ let libraryClosed = false;
11029
+ return {
11030
+ symbols: functions,
11031
+ createCallback(callback, definition) {
11032
+ if (closed) {
11033
+ throw new Error(LIBRARY_CLOSED);
11401
11034
  }
11402
- const buffer = new ArrayBuffer(val.length * arrayElementSize);
11403
- const bufferView = new DataView(buffer);
11404
- for (let i = 0;i < val.length; i++) {
11405
- const num = def.to(val[i]);
11406
- bufferView.setUint32(i * arrayElementSize, num, true);
11035
+ if (definition.threadsafe) {
11036
+ throw new Error(NODE_CALLBACK_THREADSAFE);
11407
11037
  }
11408
- pointerPacker(view, off, ptr2(buffer));
11409
- };
11410
- unpack = null;
11411
- needsLengthOf = true;
11412
- lengthOfDef = def;
11413
- } else if (isStruct(def)) {
11414
- arrayElementSize = def.size;
11415
- pack = (view, off, val, obj, options2) => {
11416
- if (!val || val.length === 0) {
11417
- pointerPacker(view, off, null);
11038
+ const callbackPointer = lib.registerCallback(normalizeNodeDefinition(definition), callback);
11039
+ const raw = {
11040
+ ptr: callbackPointer,
11041
+ threadsafe: false,
11042
+ close() {
11043
+ if (!libraryClosed) {
11044
+ lib.unregisterCallback(callbackPointer);
11045
+ }
11046
+ }
11047
+ };
11048
+ return createManagedCallback(raw, callbacks);
11049
+ },
11050
+ close() {
11051
+ if (closed) {
11418
11052
  return;
11419
11053
  }
11420
- const buffer = new ArrayBuffer(val.length * arrayElementSize);
11421
- const bufferView = new DataView(buffer);
11422
- for (let i = 0;i < val.length; i++) {
11423
- def.packInto(val[i], bufferView, i * arrayElementSize, options2);
11424
- }
11425
- pointerPacker(view, off, ptr2(buffer));
11426
- };
11427
- unpack = (view, off) => {
11428
- throw new Error("Not implemented yet");
11429
- };
11430
- } else if (isPrimitiveType(def)) {
11431
- arrayElementSize = typeSizes[def];
11432
- const { pack: primitivePack } = primitivePackers(def);
11433
- pack = (view, off, val) => {
11434
- if (!val || val.length === 0) {
11435
- pointerPacker(view, off, null);
11436
- return;
11054
+ closed = true;
11055
+ try {
11056
+ libraryClosed = true;
11057
+ lib.close();
11058
+ } finally {
11059
+ for (const callback of [...callbacks]) {
11060
+ callback.close();
11061
+ }
11437
11062
  }
11438
- const buffer = new ArrayBuffer(val.length * arrayElementSize);
11439
- const bufferView = new DataView(buffer);
11440
- for (let i = 0;i < val.length; i++) {
11441
- primitivePack(bufferView, i * arrayElementSize, val[i]);
11442
- }
11443
- pointerPacker(view, off, ptr2(buffer));
11444
- };
11445
- unpack = null;
11446
- needsLengthOf = true;
11447
- lengthOfDef = def;
11448
- } else if (isObjectPointerDef(def)) {
11449
- arrayElementSize = pointerSize;
11450
- pack = (view, off, val) => {
11451
- if (!val || val.length === 0) {
11452
- pointerPacker(view, off, null);
11453
- return;
11454
- }
11455
- const packedView = packObjectArray(val);
11456
- pointerPacker(view, off, ptr2(packedView.buffer));
11457
- };
11458
- unpack = () => {
11459
- throw new Error("not implemented yet");
11460
- };
11461
- } else {
11462
- throw new Error(`Unsupported array element type for ${name}: ${JSON.stringify(def)}`);
11463
- }
11464
- const lengthOfField = Object.values(lengthOfFields).find((f) => f.lengthOf === name);
11465
- if (lengthOfField && isPrimitiveType(lengthOfField.type)) {
11466
- const { pack: lengthPack } = primitivePackers(lengthOfField.type);
11467
- arrayFieldsMetadata[name] = {
11468
- elementSize: arrayElementSize,
11469
- arrayOffset: offset,
11470
- lengthOffset: lengthOfField.offset,
11471
- lengthPack
11472
- };
11473
- }
11474
- } else {
11475
- throw new Error(`Unsupported field type for ${name}: ${JSON.stringify(typeOrStruct)}`);
11476
- }
11477
- offset = alignOffset(offset, align);
11478
- if (options.unpackTransform) {
11479
- const originalUnpack = unpack;
11480
- unpack = (view, off) => options.unpackTransform(originalUnpack(view, off));
11481
- }
11482
- if (options.packTransform) {
11483
- const originalPack = pack;
11484
- pack = (view, off, val, obj, packOptions) => originalPack(view, off, options.packTransform(val), obj, packOptions);
11485
- }
11486
- if (options.optional) {
11487
- const originalPack = pack;
11488
- if (isStruct(typeOrStruct) && !options.asPointer) {
11489
- pack = (view, off, val, obj, packOptions) => {
11490
- if (val || options.mapOptionalInline) {
11491
- originalPack(view, off, val, obj, packOptions);
11492
- }
11493
- };
11494
- } else {
11495
- pack = (view, off, val, obj, packOptions) => originalPack(view, off, val ?? 0, obj, packOptions);
11496
- }
11497
- }
11498
- if (options.lengthOf) {
11499
- const originalPack = pack;
11500
- pack = (view, off, val, obj, packOptions) => {
11501
- const targetValue = obj[options.lengthOf];
11502
- let length = 0;
11503
- if (targetValue) {
11504
- if (typeof targetValue === "string") {
11505
- length = Buffer.byteLength(targetValue);
11506
- } else {
11507
- length = targetValue.length;
11508
- }
11509
- }
11510
- return originalPack(view, off, length, obj, packOptions);
11511
- };
11512
- }
11513
- let validateFunctions;
11514
- if (options.validate) {
11515
- validateFunctions = Array.isArray(options.validate) ? options.validate : [options.validate];
11516
- }
11517
- const layoutField = {
11518
- name,
11519
- offset,
11520
- size,
11521
- align,
11522
- validate: validateFunctions,
11523
- optional: !!options.optional || !!options.lengthOf || options.default !== undefined,
11524
- default: options.default,
11525
- pack,
11526
- unpack,
11527
- type: typeOrStruct,
11528
- lengthOf: options.lengthOf
11529
- };
11530
- layout.push(layoutField);
11531
- if (options.lengthOf) {
11532
- lengthOfFields[options.lengthOf] = layoutField;
11533
- }
11534
- if (needsLengthOf) {
11535
- const def = typeof typeOrStruct === "string" && typeOrStruct === "char*" ? "char*" : lengthOfDef;
11536
- if (!def)
11537
- fatalError(`Internal error: needsLengthOf=true but def is null for ${name}`);
11538
- lengthOfRequested.push({ requester: layoutField, def });
11539
- }
11540
- offset += size;
11541
- maxAlign = Math.max(maxAlign, align);
11542
- }
11543
- for (const { requester, def } of lengthOfRequested) {
11544
- const lengthOfField = lengthOfFields[requester.name];
11545
- if (!lengthOfField) {
11546
- if (def === "char*") {
11547
- continue;
11548
- }
11549
- throw new Error(`lengthOf field not found for array field ${requester.name}`);
11550
- }
11551
- if (def === "char*") {
11552
- requester.unpack = (view, off) => {
11553
- const ptrAddress = pointerUnpacker(view, off);
11554
- const length = lengthOfField.unpack(view, lengthOfField.offset);
11555
- if (ptrAddress === 0) {
11556
- return null;
11557
- }
11558
- const byteLength = typeof length === "bigint" ? Number(length) : length;
11559
- if (byteLength === 0) {
11560
- return "";
11561
- }
11562
- const buffer = toArrayBuffer2(ptrAddress, 0, byteLength);
11563
- return decoder.decode(buffer);
11564
- };
11565
- } else if (isPrimitiveType(def)) {
11566
- const elemSize = typeSizes[def];
11567
- const { unpack: primitiveUnpack } = primitivePackers(def);
11568
- requester.unpack = (view, off) => {
11569
- const result = [];
11570
- const length = lengthOfField.unpack(view, lengthOfField.offset);
11571
- const ptrAddress = pointerUnpacker(view, off);
11572
- if (ptrAddress === 0n && length > 0) {
11573
- throw new Error(`Array field ${requester.name} has null pointer but length ${length}.`);
11574
11063
  }
11575
- if (ptrAddress === 0n || length === 0) {
11576
- return [];
11577
- }
11578
- const buffer = toArrayBuffer2(ptrAddress, 0, length * elemSize);
11579
- const bufferView = new DataView(buffer);
11580
- for (let i = 0;i < length; i++) {
11581
- result.push(primitiveUnpack(bufferView, i * elemSize));
11582
- }
11583
- return result;
11584
- };
11585
- } else {
11586
- const elemSize = def.type === "u32" ? 4 : 8;
11587
- requester.unpack = (view, off) => {
11588
- const result = [];
11589
- const length = lengthOfField.unpack(view, lengthOfField.offset);
11590
- const ptrAddress = pointerUnpacker(view, off);
11591
- if (ptrAddress === 0n && length > 0) {
11592
- throw new Error(`Array field ${requester.name} has null pointer but length ${length}.`);
11593
- }
11594
- if (ptrAddress === 0n || length === 0) {
11595
- return [];
11596
- }
11597
- const buffer = toArrayBuffer2(ptrAddress, 0, length * elemSize);
11598
- const bufferView = new DataView(buffer);
11599
- for (let i = 0;i < length; i++) {
11600
- result.push(def.from(bufferView.getUint32(i * elemSize, true)));
11601
- }
11602
- return result;
11603
11064
  };
11604
- }
11605
- }
11606
- const totalSize = alignOffset(offset, maxAlign);
11607
- const description = layout.map((f) => ({
11608
- name: f.name,
11609
- offset: f.offset,
11610
- size: f.size,
11611
- align: f.align,
11612
- optional: f.optional,
11613
- type: f.type,
11614
- lengthOf: f.lengthOf
11615
- }));
11616
- const layoutByName = new Map(description.map((f) => [f.name, f]));
11617
- const arrayFields = new Map(Object.entries(arrayFieldsMetadata));
11618
- return {
11619
- __type: "struct",
11620
- size: totalSize,
11621
- align: maxAlign,
11622
- hasMapValue: !!structDefOptions?.mapValue,
11623
- layoutByName,
11624
- arrayFields,
11625
- pack(obj, options) {
11626
- const buf = new ArrayBuffer(totalSize);
11627
- const view = new DataView(buf);
11628
- let mappedObj = obj;
11629
- if (structDefOptions?.mapValue) {
11630
- mappedObj = structDefOptions.mapValue(obj);
11631
- }
11632
- for (const field of layout) {
11633
- const value = mappedObj[field.name] ?? field.default;
11634
- if (!field.optional && value === undefined) {
11635
- fatalError(`Packing non-optional field '${field.name}' but value is undefined (and no default provided)`);
11636
- }
11637
- if (field.validate) {
11638
- for (const validateFn of field.validate) {
11639
- validateFn(value, field.name, {
11640
- hints: options?.validationHints,
11641
- input: mappedObj
11642
- });
11643
- }
11644
- }
11645
- field.pack(view, field.offset, value, mappedObj, options);
11646
- }
11647
- return view.buffer;
11648
11065
  },
11649
- packInto(obj, view, offset2, options) {
11650
- let mappedObj = obj;
11651
- if (structDefOptions?.mapValue) {
11652
- mappedObj = structDefOptions.mapValue(obj);
11653
- }
11654
- for (const field of layout) {
11655
- const value = mappedObj[field.name] ?? field.default;
11656
- if (!field.optional && value === undefined) {
11657
- console.warn(`packInto missing value for non-optional field '${field.name}' at offset ${offset2 + field.offset}. Writing default or zero.`);
11658
- }
11659
- if (field.validate) {
11660
- for (const validateFn of field.validate) {
11661
- validateFn(value, field.name, {
11662
- hints: options?.validationHints,
11663
- input: mappedObj
11664
- });
11665
- }
11666
- }
11667
- field.pack(view, offset2 + field.offset, value, mappedObj, options);
11668
- }
11669
- },
11670
- unpack(buf) {
11671
- if (buf.byteLength < totalSize) {
11672
- fatalError(`Buffer size (${buf.byteLength}) is smaller than struct size (${totalSize}) for unpacking.`);
11673
- }
11674
- const view = new DataView(buf);
11675
- const result = structDefOptions?.default ? { ...structDefOptions.default } : {};
11676
- for (const field of layout) {
11677
- if (!field.unpack) {
11678
- continue;
11679
- }
11680
- try {
11681
- result[field.name] = field.unpack(view, field.offset);
11682
- } catch (e) {
11683
- console.error(`Error unpacking field '${field.name}' at offset ${field.offset}:`, e);
11684
- throw e;
11066
+ ptr(value) {
11067
+ if (ArrayBuffer.isView(value)) {
11068
+ if (!(value.buffer instanceof ArrayBuffer)) {
11069
+ throw new TypeError(NODE_PTR_VALUE);
11685
11070
  }
11071
+ return nodeFfi.getRawPointer(value.buffer) + BigInt(value.byteOffset);
11686
11072
  }
11687
- if (structDefOptions?.reduceValue) {
11688
- return structDefOptions.reduceValue(result);
11073
+ if (value instanceof ArrayBuffer) {
11074
+ return nodeFfi.getRawPointer(value);
11689
11075
  }
11690
- return result;
11076
+ throw new TypeError(NODE_PTR_VALUE);
11691
11077
  },
11692
- packList(objects, options) {
11693
- if (objects.length === 0) {
11694
- return new ArrayBuffer(0);
11695
- }
11696
- const buffer = new ArrayBuffer(totalSize * objects.length);
11697
- const view = new DataView(buffer);
11698
- for (let i = 0;i < objects.length; i++) {
11699
- let mappedObj = objects[i];
11700
- if (structDefOptions?.mapValue) {
11701
- mappedObj = structDefOptions.mapValue(objects[i]);
11702
- }
11703
- for (const field of layout) {
11704
- const value = mappedObj[field.name] ?? field.default;
11705
- if (!field.optional && value === undefined) {
11706
- fatalError(`Packing non-optional field '${field.name}' at index ${i} but value is undefined (and no default provided)`);
11707
- }
11708
- if (field.validate) {
11709
- for (const validateFn of field.validate) {
11710
- validateFn(value, field.name, {
11711
- hints: options?.validationHints,
11712
- input: mappedObj
11713
- });
11714
- }
11715
- }
11716
- field.pack(view, i * totalSize + field.offset, value, mappedObj, options);
11717
- }
11718
- }
11719
- return buffer;
11720
- },
11721
- unpackList(buf, count) {
11722
- if (count === 0) {
11723
- return [];
11724
- }
11725
- const expectedSize = totalSize * count;
11726
- if (buf.byteLength < expectedSize) {
11727
- fatalError(`Buffer size (${buf.byteLength}) is smaller than expected size (${expectedSize}) for unpacking ${count} structs.`);
11728
- }
11729
- const view = new DataView(buf);
11730
- const results = [];
11731
- for (let i = 0;i < count; i++) {
11732
- const offset2 = i * totalSize;
11733
- const result = structDefOptions?.default ? { ...structDefOptions.default } : {};
11734
- for (const field of layout) {
11735
- if (!field.unpack) {
11736
- continue;
11737
- }
11738
- try {
11739
- result[field.name] = field.unpack(view, offset2 + field.offset);
11740
- } catch (e) {
11741
- console.error(`Error unpacking field '${field.name}' at index ${i}, offset ${offset2 + field.offset}:`, e);
11742
- throw e;
11743
- }
11744
- }
11745
- if (structDefOptions?.reduceValue) {
11746
- results.push(structDefOptions.reduceValue(result));
11747
- } else {
11748
- results.push(result);
11749
- }
11750
- }
11751
- return results;
11752
- },
11753
- describe() {
11754
- return description;
11078
+ suffix: nodeFfi.suffix,
11079
+ toArrayBuffer(pointer, offset, length) {
11080
+ return nodeFfi.toArrayBuffer(toBigIntPointer(pointer) + BigInt(offset ?? 0), length, false);
11755
11081
  }
11756
11082
  };
11757
11083
  }
11084
+ function toNodeLibraryPath(path5) {
11085
+ return path5 instanceof URL ? fileURLToPath2(path5) : path5;
11086
+ }
11087
+ function normalizeNodeDefinitions(definitions) {
11088
+ return Object.fromEntries(Object.entries(definitions).map(([name, definition]) => [name, normalizeNodeDefinition(definition)]));
11089
+ }
11090
+ function normalizeNodeDefinition(definition) {
11091
+ if (definition.ptr != null) {
11092
+ throw new Error(NODE_POINTER_OVERRIDE);
11093
+ }
11094
+ return {
11095
+ parameters: (definition.args ?? []).map((type) => toNodeFFIType(type, "parameter")),
11096
+ result: toNodeFFIType(definition.returns ?? FFIType.void, "result")
11097
+ };
11098
+ }
11099
+ function toNodeFFIType(type, position) {
11100
+ switch (type) {
11101
+ case FFIType.char:
11102
+ return "char";
11103
+ case FFIType.int8_t:
11104
+ case FFIType.i8:
11105
+ return "i8";
11106
+ case FFIType.uint8_t:
11107
+ case FFIType.u8:
11108
+ return "u8";
11109
+ case FFIType.int16_t:
11110
+ case FFIType.i16:
11111
+ return "i16";
11112
+ case FFIType.uint16_t:
11113
+ case FFIType.u16:
11114
+ return "u16";
11115
+ case FFIType.int32_t:
11116
+ case FFIType.int:
11117
+ case FFIType.i32:
11118
+ return "i32";
11119
+ case FFIType.uint32_t:
11120
+ case FFIType.u32:
11121
+ return "u32";
11122
+ case FFIType.int64_t:
11123
+ case FFIType.i64:
11124
+ return "i64";
11125
+ case FFIType.uint64_t:
11126
+ case FFIType.u64:
11127
+ return "u64";
11128
+ case FFIType.double:
11129
+ case FFIType.f64:
11130
+ return "f64";
11131
+ case FFIType.float:
11132
+ case FFIType.f32:
11133
+ return "f32";
11134
+ case FFIType.bool:
11135
+ return "bool";
11136
+ case FFIType.ptr:
11137
+ case FFIType.pointer:
11138
+ return "pointer";
11139
+ case FFIType.void:
11140
+ return "void";
11141
+ case FFIType.cstring:
11142
+ if (position === "result") {
11143
+ throw new Error(NODE_STRING_RETURN);
11144
+ }
11145
+ return "string";
11146
+ case FFIType.function:
11147
+ case FFIType.callback:
11148
+ return "pointer";
11149
+ case FFIType.usize:
11150
+ throw new Error(NODE_USIZE_UNSUPPORTED);
11151
+ case FFIType.napi_env:
11152
+ case FFIType.napi_value:
11153
+ throw new Error(NODE_NAPI_UNSUPPORTED);
11154
+ case FFIType.buffer:
11155
+ return "buffer";
11156
+ default:
11157
+ return unsupportedNodeFFIType(type);
11158
+ }
11159
+ }
11160
+ function unsupportedNodeFFIType(type) {
11161
+ throw new Error(`Unsupported FFIType for node:ffi: ${String(type)}`);
11162
+ }
11163
+ function toBigIntPointer(pointer) {
11164
+ return typeof pointer === "bigint" ? pointer : BigInt(pointer);
11165
+ }
11166
+ var dlopen = backend.dlopen;
11167
+ var ptr = backend.ptr;
11168
+ var suffix = backend.suffix;
11169
+ var toArrayBuffer = backend.toArrayBuffer;
11170
+
11171
+ // src/zig.ts
11172
+ import { existsSync as existsSync2, writeFileSync } from "fs";
11173
+ import { EventEmitter as EventEmitter4 } from "events";
11174
+
11175
+ // src/buffer.ts
11176
+ function packDrawOptions(border2, shouldFill, titleAlignment, bottomTitleAlignment) {
11177
+ let packed = 0;
11178
+ if (border2 === true) {
11179
+ packed |= 15;
11180
+ } else if (Array.isArray(border2)) {
11181
+ if (border2.includes("top"))
11182
+ packed |= 8;
11183
+ if (border2.includes("right"))
11184
+ packed |= 4;
11185
+ if (border2.includes("bottom"))
11186
+ packed |= 2;
11187
+ if (border2.includes("left"))
11188
+ packed |= 1;
11189
+ }
11190
+ if (shouldFill) {
11191
+ packed |= 1 << 4;
11192
+ }
11193
+ const alignmentMap = {
11194
+ left: 0,
11195
+ center: 1,
11196
+ right: 2
11197
+ };
11198
+ const alignment = alignmentMap[titleAlignment];
11199
+ const bottomAlignment = alignmentMap[bottomTitleAlignment];
11200
+ packed |= alignment << 5;
11201
+ packed |= bottomAlignment << 7;
11202
+ return packed;
11203
+ }
11758
11204
 
11759
- // src/zig-structs.ts
11760
- import { ptr as ptr3, toArrayBuffer as toArrayBuffer3 } from "bun:ffi";
11761
- var rgbaPackTransform = (rgba) => rgba ? ptr3(rgba.buffer) : null;
11762
- var rgbaUnpackTransform = (ptr4) => ptr4 ? RGBA.fromArray(new Uint16Array(toArrayBuffer3(ptr4, 0, 8))) : undefined;
11763
- var StyledChunkStruct = defineStruct([
11764
- ["text", "char*"],
11765
- ["text_len", "u64", { lengthOf: "text" }],
11766
- [
11767
- "fg",
11768
- "pointer",
11769
- {
11770
- optional: true,
11771
- packTransform: rgbaPackTransform,
11772
- unpackTransform: rgbaUnpackTransform
11773
- }
11774
- ],
11775
- [
11776
- "bg",
11777
- "pointer",
11778
- {
11779
- optional: true,
11780
- packTransform: rgbaPackTransform,
11781
- unpackTransform: rgbaUnpackTransform
11782
- }
11783
- ],
11784
- ["attributes", "u32", { default: 0 }],
11785
- ["link", "char*", { default: "" }],
11786
- ["link_len", "u64", { lengthOf: "link" }]
11787
- ], {
11788
- mapValue: (chunk) => {
11789
- const normalizedFg = normalizeColorValue(chunk.fg ?? null);
11790
- const normalizedBg = normalizeColorValue(chunk.bg ?? null);
11791
- if (!chunk.link || typeof chunk.link === "string") {
11792
- return {
11793
- ...chunk,
11794
- fg: normalizedFg?.rgba ?? null,
11795
- bg: normalizedBg?.rgba ?? null
11796
- };
11205
+ class OptimizedBuffer {
11206
+ static fbIdCounter = 0;
11207
+ id;
11208
+ lib;
11209
+ bufferPtr;
11210
+ _width;
11211
+ _height;
11212
+ _widthMethod;
11213
+ respectAlpha = false;
11214
+ _rawBuffers = null;
11215
+ _destroyed = false;
11216
+ get ptr() {
11217
+ return this.bufferPtr;
11218
+ }
11219
+ guard() {
11220
+ if (this._destroyed)
11221
+ throw new Error(`Buffer ${this.id} is destroyed`);
11222
+ }
11223
+ ensureRawBufferViews() {
11224
+ if (this._rawBuffers !== null) {
11225
+ return;
11797
11226
  }
11798
- return {
11799
- ...chunk,
11800
- fg: normalizedFg?.rgba ?? null,
11801
- bg: normalizedBg?.rgba ?? null,
11802
- link: chunk.link.url
11227
+ const size = this._width * this._height;
11228
+ const charPtr = this.lib.bufferGetCharPtr(this.bufferPtr);
11229
+ const fgPtr = this.lib.bufferGetFgPtr(this.bufferPtr);
11230
+ const bgPtr = this.lib.bufferGetBgPtr(this.bufferPtr);
11231
+ const attributesPtr = this.lib.bufferGetAttributesPtr(this.bufferPtr);
11232
+ this._rawBuffers = {
11233
+ char: new Uint32Array(toArrayBuffer(charPtr, 0, size * 4)),
11234
+ fg: new Uint16Array(toArrayBuffer(fgPtr, 0, size * 4 * 2)),
11235
+ bg: new Uint16Array(toArrayBuffer(bgPtr, 0, size * 4 * 2)),
11236
+ attributes: new Uint32Array(toArrayBuffer(attributesPtr, 0, size * 4))
11803
11237
  };
11804
11238
  }
11805
- });
11806
- var HighlightStruct = defineStruct([
11807
- ["start", "u32"],
11808
- ["end", "u32"],
11809
- ["styleId", "u32"],
11810
- ["priority", "u8", { default: 0 }],
11811
- ["hlRef", "u16", { default: 0 }]
11812
- ]);
11813
- var LogicalCursorStruct = defineStruct([
11814
- ["row", "u32"],
11815
- ["col", "u32"],
11816
- ["offset", "u32"]
11817
- ]);
11818
- var VisualCursorStruct = defineStruct([
11819
- ["visualRow", "u32"],
11820
- ["visualCol", "u32"],
11821
- ["logicalRow", "u32"],
11822
- ["logicalCol", "u32"],
11823
- ["offset", "u32"]
11824
- ]);
11825
- var UnicodeMethodEnum = defineEnum({ wcwidth: 0, unicode: 1 }, "u8");
11826
- var TerminalCapabilitiesStruct = defineStruct([
11827
- ["kitty_keyboard", "bool_u8"],
11828
- ["kitty_graphics", "bool_u8"],
11829
- ["rgb", "bool_u8"],
11830
- ["ansi256", "bool_u8"],
11831
- ["unicode", UnicodeMethodEnum],
11832
- ["sgr_pixels", "bool_u8"],
11833
- ["color_scheme_updates", "bool_u8"],
11834
- ["explicit_width", "bool_u8"],
11835
- ["scaled_text", "bool_u8"],
11836
- ["sixel", "bool_u8"],
11837
- ["focus_tracking", "bool_u8"],
11838
- ["sync", "bool_u8"],
11839
- ["bracketed_paste", "bool_u8"],
11840
- ["hyperlinks", "bool_u8"],
11841
- ["osc52", "bool_u8"],
11842
- ["explicit_cursor_positioning", "bool_u8"],
11843
- ["term_name", "char*"],
11844
- ["term_name_len", "u64", { lengthOf: "term_name" }],
11845
- ["term_version", "char*"],
11846
- ["term_version_len", "u64", { lengthOf: "term_version" }],
11847
- ["term_from_xtversion", "bool_u8"]
11848
- ]);
11849
- var EncodedCharStruct = defineStruct([
11850
- ["width", "u8"],
11851
- ["char", "u32"]
11852
- ]);
11853
- var LineInfoStruct = defineStruct([
11854
- ["startCols", ["u32"]],
11855
- ["startColsLen", "u32", { lengthOf: "startCols" }],
11856
- ["widthCols", ["u32"]],
11857
- ["widthColsLen", "u32", { lengthOf: "widthCols" }],
11858
- ["sources", ["u32"]],
11859
- ["sourcesLen", "u32", { lengthOf: "sources" }],
11860
- ["wraps", ["u32"]],
11861
- ["wrapsLen", "u32", { lengthOf: "wraps" }],
11862
- ["widthColsMax", "u32"]
11863
- ]);
11864
- var MeasureResultStruct = defineStruct([
11865
- ["lineCount", "u32"],
11866
- ["widthColsMax", "u32"]
11867
- ]);
11868
- var CursorStateStruct = defineStruct([
11869
- ["x", "u32"],
11870
- ["y", "u32"],
11871
- ["visible", "bool_u8"],
11872
- ["style", "u8"],
11873
- ["blinking", "bool_u8"],
11874
- ["r", "f32"],
11875
- ["g", "f32"],
11876
- ["b", "f32"],
11877
- ["a", "f32"]
11878
- ]);
11879
- var CursorStyleOptionsStruct = defineStruct([
11880
- ["style", "u8", { default: 255 }],
11881
- ["blinking", "u8", { default: 255 }],
11882
- [
11883
- "color",
11884
- "pointer",
11885
- {
11886
- optional: true,
11887
- packTransform: rgbaPackTransform,
11888
- unpackTransform: rgbaUnpackTransform
11239
+ get buffers() {
11240
+ this.guard();
11241
+ this.ensureRawBufferViews();
11242
+ return this._rawBuffers;
11243
+ }
11244
+ constructor(lib, ptr2, width, height, options) {
11245
+ this.id = options.id || `fb_${OptimizedBuffer.fbIdCounter++}`;
11246
+ this.lib = lib;
11247
+ this.respectAlpha = options.respectAlpha || false;
11248
+ this._width = width;
11249
+ this._height = height;
11250
+ this._widthMethod = options.widthMethod || "unicode";
11251
+ this.bufferPtr = ptr2;
11252
+ }
11253
+ static create(width, height, widthMethod, options = {}) {
11254
+ const lib = resolveRenderLib();
11255
+ const respectAlpha = options.respectAlpha || false;
11256
+ const id = options.id && options.id.trim() !== "" ? options.id : "unnamed buffer";
11257
+ const buffer = lib.createOptimizedBuffer(width, height, widthMethod, respectAlpha, id);
11258
+ return buffer;
11259
+ }
11260
+ get widthMethod() {
11261
+ return this._widthMethod;
11262
+ }
11263
+ get width() {
11264
+ return this._width;
11265
+ }
11266
+ get height() {
11267
+ return this._height;
11268
+ }
11269
+ setRespectAlpha(respectAlpha) {
11270
+ this.guard();
11271
+ this.lib.bufferSetRespectAlpha(this.bufferPtr, respectAlpha);
11272
+ this.respectAlpha = respectAlpha;
11273
+ }
11274
+ getNativeId() {
11275
+ this.guard();
11276
+ return this.lib.bufferGetId(this.bufferPtr);
11277
+ }
11278
+ getRealCharBytes(addLineBreaks = false) {
11279
+ this.guard();
11280
+ const realSize = this.lib.bufferGetRealCharSize(this.bufferPtr);
11281
+ const outputBuffer = new Uint8Array(realSize);
11282
+ const bytesWritten = this.lib.bufferWriteResolvedChars(this.bufferPtr, outputBuffer, addLineBreaks);
11283
+ return outputBuffer.slice(0, bytesWritten);
11284
+ }
11285
+ getSpanLines() {
11286
+ this.guard();
11287
+ const { char, fg: fg2, bg: bg2, attributes } = this.buffers;
11288
+ const lines = [];
11289
+ const CHAR_FLAG_CONTINUATION = 3221225472 | 0;
11290
+ const CHAR_FLAG_MASK = 3221225472 | 0;
11291
+ const realTextBytes = this.getRealCharBytes(true);
11292
+ const realTextLines = new TextDecoder().decode(realTextBytes).split(`
11293
+ `);
11294
+ for (let y = 0;y < this._height; y++) {
11295
+ const spans = [];
11296
+ let currentSpan = null;
11297
+ const lineChars = [...realTextLines[y] || ""];
11298
+ let charIdx = 0;
11299
+ for (let x = 0;x < this._width; x++) {
11300
+ const i = y * this._width + x;
11301
+ const cp = char[i];
11302
+ const cellFg = RGBA.fromArray(fg2.slice(i * 4, i * 4 + 4));
11303
+ const cellBg = RGBA.fromArray(bg2.slice(i * 4, i * 4 + 4));
11304
+ const cellAttrs = attributes[i] & 255;
11305
+ const isContinuation = (cp & CHAR_FLAG_MASK) === CHAR_FLAG_CONTINUATION;
11306
+ const cellChar = isContinuation ? "" : lineChars[charIdx++] ?? " ";
11307
+ if (currentSpan && currentSpan.fg.equals(cellFg) && currentSpan.bg.equals(cellBg) && currentSpan.attributes === cellAttrs) {
11308
+ currentSpan.text += cellChar;
11309
+ currentSpan.width += 1;
11310
+ } else {
11311
+ if (currentSpan) {
11312
+ spans.push(currentSpan);
11313
+ }
11314
+ currentSpan = {
11315
+ text: cellChar,
11316
+ fg: cellFg,
11317
+ bg: cellBg,
11318
+ attributes: cellAttrs,
11319
+ width: 1
11320
+ };
11321
+ }
11322
+ }
11323
+ if (currentSpan) {
11324
+ spans.push(currentSpan);
11325
+ }
11326
+ lines.push({ spans });
11889
11327
  }
11890
- ],
11891
- ["cursor", "u8", { default: 255 }]
11892
- ]);
11893
- var GridDrawOptionsStruct = defineStruct([
11894
- ["drawInner", "bool_u8", { default: true }],
11895
- ["drawOuter", "bool_u8", { default: true }]
11896
- ]);
11897
- var BuildOptionsStruct = defineStruct([
11898
- ["gpaSafeStats", "bool_u8"],
11899
- ["gpaMemoryLimitTracking", "bool_u8"]
11900
- ]);
11901
- var AllocatorStatsStruct = defineStruct([
11902
- ["totalRequestedBytes", "u64"],
11903
- ["activeAllocations", "u64"],
11904
- ["smallAllocations", "u64"],
11905
- ["largeAllocations", "u64"],
11906
- ["requestedBytesValid", "bool_u8"]
11907
- ]);
11908
- var GrowthPolicyEnum = defineEnum({ grow: 0, block: 1 }, "u8");
11909
- var NativeSpanFeedOptionsStruct = defineStruct([
11910
- ["chunkSize", "u32", { default: 64 * 1024 }],
11911
- ["initialChunks", "u32", { default: 2 }],
11912
- ["maxBytes", "u64", { default: 0n }],
11913
- ["growthPolicy", GrowthPolicyEnum, { default: "grow" }],
11914
- ["autoCommitOnFull", "bool_u8", { default: true }],
11915
- ["spanQueueCapacity", "u32", { default: 0 }]
11916
- ]);
11917
- var NativeSpanFeedStatsStruct = defineStruct([
11918
- ["bytesWritten", "u64"],
11919
- ["spansCommitted", "u64"],
11920
- ["chunks", "u32"],
11921
- ["pendingSpans", "u32"]
11922
- ]);
11923
- var SpanInfoStruct = defineStruct([
11924
- ["chunkPtr", "pointer"],
11925
- ["offset", "u32"],
11926
- ["len", "u32"],
11927
- ["chunkIndex", "u32"],
11928
- ["reserved", "u32", { default: 0 }]
11929
- ], {
11930
- reduceValue: (value) => ({
11931
- chunkPtr: value.chunkPtr,
11932
- offset: value.offset,
11933
- len: value.len,
11934
- chunkIndex: value.chunkIndex
11935
- })
11936
- });
11937
- var ReserveInfoStruct = defineStruct([
11938
- ["ptr", "pointer"],
11939
- ["len", "u32"],
11940
- ["reserved", "u32", { default: 0 }]
11941
- ], {
11942
- reduceValue: (value) => ({
11943
- ptr: value.ptr,
11944
- len: value.len
11945
- })
11946
- });
11947
-
11948
- // src/platform/ffi.ts
11949
- import { fileURLToPath as fileURLToPath2 } from "url";
11950
- var FFIType = {
11951
- char: "char",
11952
- int8_t: "int8_t",
11953
- i8: "i8",
11954
- uint8_t: "uint8_t",
11955
- u8: "u8",
11956
- int16_t: "int16_t",
11957
- i16: "i16",
11958
- uint16_t: "uint16_t",
11959
- u16: "u16",
11960
- int32_t: "int32_t",
11961
- i32: "i32",
11962
- int: "int",
11963
- uint32_t: "uint32_t",
11964
- u32: "u32",
11965
- int64_t: "int64_t",
11966
- i64: "i64",
11967
- uint64_t: "uint64_t",
11968
- u64: "u64",
11969
- double: "double",
11970
- f64: "f64",
11971
- float: "float",
11972
- f32: "f32",
11973
- bool: "bool",
11974
- ptr: "ptr",
11975
- pointer: "pointer",
11976
- void: "void",
11977
- cstring: "cstring",
11978
- function: "function",
11979
- usize: "usize",
11980
- callback: "callback",
11981
- napi_env: "napi_env",
11982
- napi_value: "napi_value",
11983
- buffer: "buffer"
11984
- };
11985
- var FFI_UNAVAILABLE = "OpenTUI native FFI is not available for this runtime yet";
11986
- var BUN_DLOPEN_NULL = "Bun FFI backend does not support dlopen(null)";
11987
- var LIBRARY_CLOSED = "Cannot create FFI callback after library.close() has been called";
11988
- var NODE_CALLBACK_THREADSAFE = "Node FFI callbacks are same-thread only and do not support threadsafe callbacks";
11989
- var NODE_NAPI_UNSUPPORTED = "Node FFI backend does not support Bun N-API FFI types";
11990
- var NODE_POINTER_OVERRIDE = "Node FFI backend does not support FFIFunction.ptr overrides";
11991
- var NODE_PTR_VALUE = "node:ffi ptr() only supports ArrayBuffer and ArrayBufferView values backed by ArrayBuffer";
11992
- var NODE_STRING_RETURN = "Node FFI backend does not normalize string return values (yet)";
11993
- var NODE_USIZE_UNSUPPORTED = "Node FFI backend does not support usize until (yet)";
11994
- var POINTER_NEGATIVE = "Pointer must be non-negative";
11995
- var POINTER_UNSAFE = "Pointer exceeds safe integer range";
11996
- function unavailable(cause) {
11997
- throw new Error(FFI_UNAVAILABLE, { cause });
11998
- }
11999
- function createUnsupportedBackend(cause) {
12000
- return {
12001
- dlopen() {
12002
- return unavailable(cause);
12003
- },
12004
- ptr() {
12005
- return unavailable(cause);
12006
- },
12007
- suffix: "",
12008
- toArrayBuffer() {
12009
- return unavailable(cause);
11328
+ return lines;
11329
+ }
11330
+ clear(bg2 = RGBA.fromValues(0, 0, 0, 1)) {
11331
+ this.guard();
11332
+ this.lib.bufferClear(this.bufferPtr, bg2);
11333
+ }
11334
+ setCell(x, y, char, fg2, bg2, attributes = 0) {
11335
+ this.guard();
11336
+ this.lib.bufferSetCell(this.bufferPtr, x, y, char, fg2, bg2, attributes);
11337
+ }
11338
+ setCellWithAlphaBlending(x, y, char, fg2, bg2, attributes = 0) {
11339
+ this.guard();
11340
+ this.lib.bufferSetCellWithAlphaBlending(this.bufferPtr, x, y, char, fg2, bg2, attributes);
11341
+ }
11342
+ drawText(text, x, y, fg2, bg2, attributes = 0, selection2) {
11343
+ this.guard();
11344
+ if (!selection2) {
11345
+ this.lib.bufferDrawText(this.bufferPtr, text, x, y, fg2, bg2, attributes);
11346
+ return;
12010
11347
  }
12011
- };
12012
- }
12013
- var isBun = typeof process !== "undefined" && typeof process.versions === "object" && process.versions !== null && typeof process.versions.bun === "string";
12014
- var backend = await loadBackend();
12015
- function importModule(specifier) {
12016
- return import(specifier);
11348
+ const { start, end } = selection2;
11349
+ let selectionBg;
11350
+ let selectionFg;
11351
+ if (selection2.bgColor) {
11352
+ selectionBg = selection2.bgColor;
11353
+ selectionFg = selection2.fgColor || fg2;
11354
+ } else {
11355
+ const defaultBg = bg2 || RGBA.fromValues(0, 0, 0, 0);
11356
+ selectionFg = defaultBg.a > 0 ? defaultBg : RGBA.fromValues(0, 0, 0, 1);
11357
+ selectionBg = fg2;
11358
+ }
11359
+ if (start > 0) {
11360
+ const beforeText = text.slice(0, start);
11361
+ this.lib.bufferDrawText(this.bufferPtr, beforeText, x, y, fg2, bg2, attributes);
11362
+ }
11363
+ if (end > start) {
11364
+ const selectedText = text.slice(start, end);
11365
+ this.lib.bufferDrawText(this.bufferPtr, selectedText, x + start, y, selectionFg, selectionBg, attributes);
11366
+ }
11367
+ if (end < text.length) {
11368
+ const afterText = text.slice(end);
11369
+ this.lib.bufferDrawText(this.bufferPtr, afterText, x + end, y, fg2, bg2, attributes);
11370
+ }
11371
+ }
11372
+ fillRect(x, y, width, height, bg2) {
11373
+ this.lib.bufferFillRect(this.bufferPtr, x, y, width, height, bg2);
11374
+ }
11375
+ colorMatrix(matrix, cellMask, strength = 1, target = 3 /* Both */) {
11376
+ this.guard();
11377
+ if (matrix.length !== 16)
11378
+ throw new RangeError(`colorMatrix matrix must have length 16, got ${matrix.length}`);
11379
+ const cellMaskCount = Math.floor(cellMask.length / 3);
11380
+ this.lib.bufferColorMatrix(this.bufferPtr, ptr(matrix), ptr(cellMask), cellMaskCount, strength, target);
11381
+ }
11382
+ colorMatrixUniform(matrix, strength = 1, target = 3 /* Both */) {
11383
+ this.guard();
11384
+ if (matrix.length !== 16)
11385
+ throw new RangeError(`colorMatrixUniform matrix must have length 16, got ${matrix.length}`);
11386
+ if (strength === 0)
11387
+ return;
11388
+ this.lib.bufferColorMatrixUniform(this.bufferPtr, ptr(matrix), strength, target);
11389
+ }
11390
+ drawFrameBuffer(destX, destY, frameBuffer, sourceX, sourceY, sourceWidth, sourceHeight) {
11391
+ this.guard();
11392
+ this.lib.drawFrameBuffer(this.bufferPtr, destX, destY, frameBuffer.ptr, sourceX, sourceY, sourceWidth, sourceHeight);
11393
+ }
11394
+ destroy() {
11395
+ if (this._destroyed)
11396
+ return;
11397
+ this._destroyed = true;
11398
+ this.lib.destroyOptimizedBuffer(this.bufferPtr);
11399
+ }
11400
+ drawTextBuffer(textBufferView, x, y) {
11401
+ this.guard();
11402
+ this.lib.bufferDrawTextBufferView(this.bufferPtr, textBufferView.ptr, x, y);
11403
+ }
11404
+ drawEditorView(editorView, x, y) {
11405
+ this.guard();
11406
+ this.lib.bufferDrawEditorView(this.bufferPtr, editorView.ptr, x, y);
11407
+ }
11408
+ drawSuperSampleBuffer(x, y, pixelDataPtr, pixelDataLength, format, alignedBytesPerRow) {
11409
+ this.guard();
11410
+ this.lib.bufferDrawSuperSampleBuffer(this.bufferPtr, x, y, toPointer(pixelDataPtr), pixelDataLength, format, alignedBytesPerRow);
11411
+ }
11412
+ drawPackedBuffer(dataPtr, dataLen, posX, posY, terminalWidthCells, terminalHeightCells) {
11413
+ this.guard();
11414
+ this.lib.bufferDrawPackedBuffer(this.bufferPtr, toPointer(dataPtr), dataLen, posX, posY, terminalWidthCells, terminalHeightCells);
11415
+ }
11416
+ drawGrayscaleBuffer(posX, posY, intensities, srcWidth, srcHeight, fg2 = null, bg2 = null) {
11417
+ this.guard();
11418
+ this.lib.bufferDrawGrayscaleBuffer(this.bufferPtr, posX, posY, ptr(intensities), srcWidth, srcHeight, fg2, bg2);
11419
+ }
11420
+ drawGrayscaleBufferSupersampled(posX, posY, intensities, srcWidth, srcHeight, fg2 = null, bg2 = null) {
11421
+ this.guard();
11422
+ this.lib.bufferDrawGrayscaleBufferSupersampled(this.bufferPtr, posX, posY, ptr(intensities), srcWidth, srcHeight, fg2, bg2);
11423
+ }
11424
+ resize(width, height) {
11425
+ this.guard();
11426
+ if (this._width === width && this._height === height)
11427
+ return;
11428
+ this._width = width;
11429
+ this._height = height;
11430
+ this._rawBuffers = null;
11431
+ this.lib.bufferResize(this.bufferPtr, width, height);
11432
+ }
11433
+ drawBox(options) {
11434
+ this.guard();
11435
+ const style = parseBorderStyle(options.borderStyle, "single");
11436
+ const borderChars = options.customBorderChars ?? BorderCharArrays[style];
11437
+ const packedOptions = packDrawOptions(options.border, options.shouldFill ?? false, options.titleAlignment || "left", options.bottomTitleAlignment || "left");
11438
+ this.lib.bufferDrawBox(this.bufferPtr, options.x, options.y, options.width, options.height, borderChars, packedOptions, options.borderColor, options.backgroundColor, options.title ?? null, options.bottomTitle ?? null);
11439
+ }
11440
+ pushScissorRect(x, y, width, height) {
11441
+ this.guard();
11442
+ this.lib.bufferPushScissorRect(this.bufferPtr, x, y, width, height);
11443
+ }
11444
+ popScissorRect() {
11445
+ this.guard();
11446
+ this.lib.bufferPopScissorRect(this.bufferPtr);
11447
+ }
11448
+ clearScissorRects() {
11449
+ this.guard();
11450
+ this.lib.bufferClearScissorRects(this.bufferPtr);
11451
+ }
11452
+ pushOpacity(opacity) {
11453
+ this.guard();
11454
+ this.lib.bufferPushOpacity(this.bufferPtr, Math.max(0, Math.min(1, opacity)));
11455
+ }
11456
+ popOpacity() {
11457
+ this.guard();
11458
+ this.lib.bufferPopOpacity(this.bufferPtr);
11459
+ }
11460
+ getCurrentOpacity() {
11461
+ this.guard();
11462
+ return this.lib.bufferGetCurrentOpacity(this.bufferPtr);
11463
+ }
11464
+ clearOpacity() {
11465
+ this.guard();
11466
+ this.lib.bufferClearOpacity(this.bufferPtr);
11467
+ }
11468
+ encodeUnicode(text) {
11469
+ this.guard();
11470
+ return this.lib.encodeUnicode(text, this._widthMethod);
11471
+ }
11472
+ freeUnicode(encoded) {
11473
+ this.guard();
11474
+ this.lib.freeUnicode(encoded);
11475
+ }
11476
+ drawGrid(options) {
11477
+ this.guard();
11478
+ const columnCount = Math.max(0, options.columnOffsets.length - 1);
11479
+ const rowCount = Math.max(0, options.rowOffsets.length - 1);
11480
+ this.lib.bufferDrawGrid(this.bufferPtr, options.borderChars, options.borderFg, options.borderBg, options.columnOffsets, columnCount, options.rowOffsets, rowCount, {
11481
+ drawInner: options.drawInner,
11482
+ drawOuter: options.drawOuter
11483
+ });
11484
+ }
11485
+ drawChar(char, x, y, fg2, bg2, attributes = 0) {
11486
+ this.guard();
11487
+ this.lib.bufferDrawChar(this.bufferPtr, char, x, y, fg2, bg2, attributes);
11488
+ }
12017
11489
  }
12018
- async function loadBackend() {
12019
- if (isBun) {
12020
- return createBunBackend(await importModule("bun:ffi"));
11490
+
11491
+ // ../../node_modules/.bun/bun-ffi-structs@0.2.2+1fb4c65d43e298b9/node_modules/bun-ffi-structs/dist/index.js
11492
+ var FFI_LOAD_ERROR = "bun-ffi-structs requires Bun or Node.js with node:ffi enabled (--experimental-ffi --allow-ffi).";
11493
+ var backend2 = await loadBackend2();
11494
+ async function loadBackend2() {
11495
+ if (typeof process !== "undefined" && "bun" in process.versions) {
11496
+ return createBunBackend2(await importModule2("bun:ffi"));
12021
11497
  }
12022
11498
  try {
12023
- const nodeFfi = await importModule("node:ffi");
12024
- return createNodeBackend(nodeFfi.default ?? nodeFfi);
11499
+ return createNodeBackend2(await importModule2("node:ffi"));
12025
11500
  } catch (error) {
12026
- return createUnsupportedBackend(error);
11501
+ throw new Error(FFI_LOAD_ERROR, {
11502
+ cause: error instanceof Error ? error : undefined
11503
+ });
12027
11504
  }
12028
11505
  }
12029
- function toPointer(value) {
12030
- if (typeof value === "bigint") {
12031
- return toSafeNumberPointer(value);
12032
- }
12033
- return value;
11506
+ function importModule2(specifier) {
11507
+ return import(specifier).then((module) => module.default ?? module);
12034
11508
  }
12035
- function toSafeNumberPointer(pointer) {
12036
- if (pointer < 0n) {
12037
- throw new Error(POINTER_NEGATIVE);
12038
- }
12039
- if (pointer > BigInt(Number.MAX_SAFE_INTEGER)) {
12040
- throw new Error(POINTER_UNSAFE);
12041
- }
12042
- return Number(pointer);
11509
+ function createBunBackend2(bun) {
11510
+ return {
11511
+ ptr: bun.ptr,
11512
+ toArrayBuffer(pointer, offset, length) {
11513
+ return bun.toArrayBuffer(toBunPointer2(pointer), offset, length);
11514
+ }
11515
+ };
12043
11516
  }
12044
- function createManagedCallback(raw, callbacks) {
12045
- let ptr4 = raw.ptr;
12046
- let closed = false;
12047
- const instance = {
12048
- get ptr() {
12049
- return ptr4;
12050
- },
12051
- get threadsafe() {
12052
- return raw.threadsafe;
12053
- },
12054
- close() {
12055
- if (closed) {
12056
- return;
11517
+ function createNodeBackend2(nodeFfi) {
11518
+ return {
11519
+ ptr(value) {
11520
+ if (ArrayBuffer.isView(value)) {
11521
+ return nodeFfi.getRawPointer(value.buffer) + BigInt(value.byteOffset);
12057
11522
  }
12058
- closed = true;
12059
- callbacks.delete(instance);
12060
- try {
12061
- raw.close();
12062
- } finally {
12063
- ptr4 = null;
11523
+ if (value instanceof ArrayBuffer) {
11524
+ return nodeFfi.getRawPointer(value);
12064
11525
  }
11526
+ throw new TypeError("node:ffi ptr() only supports ArrayBuffer and ArrayBufferView values.");
11527
+ },
11528
+ toArrayBuffer(pointer, offset, length) {
11529
+ return nodeFfi.toArrayBuffer(toBigIntPointer2(pointer) + BigInt(offset ?? 0), length, false);
12065
11530
  }
12066
11531
  };
12067
- callbacks.add(instance);
12068
- return instance;
12069
11532
  }
12070
- function normalizeBunDefinitions(definitions) {
12071
- return Object.fromEntries(Object.entries(definitions).map(([name, definition]) => [name, normalizeBunDefinition(definition)]));
11533
+ function toBigIntPointer2(pointer) {
11534
+ return typeof pointer === "bigint" ? pointer : BigInt(pointer);
12072
11535
  }
12073
- function normalizeBunDefinition(definition) {
11536
+ function toBunPointer2(pointer) {
11537
+ return typeof pointer === "bigint" ? Number(pointer) : pointer;
11538
+ }
11539
+ var ptr2 = backend2.ptr;
11540
+ var toArrayBuffer2 = backend2.toArrayBuffer;
11541
+ function fatalError(...args) {
11542
+ const message = args.join(" ");
11543
+ console.error("FATAL ERROR:", message);
11544
+ throw new Error(message);
11545
+ }
11546
+ var pointerSize = process.arch === "x64" || process.arch === "arm64" ? 8 : 4;
11547
+ var isBun2 = typeof process !== "undefined" && "bun" in process.versions;
11548
+ var typeSizes = {
11549
+ u8: 1,
11550
+ bool_u8: 1,
11551
+ bool_u32: 4,
11552
+ u16: 2,
11553
+ i16: 2,
11554
+ u32: 4,
11555
+ u64: 8,
11556
+ f32: 4,
11557
+ f64: 8,
11558
+ pointer: pointerSize,
11559
+ i32: 4,
11560
+ i64: 8
11561
+ };
11562
+ var primitiveKeys = Object.keys(typeSizes);
11563
+ function isPrimitiveType(type) {
11564
+ return typeof type === "string" && primitiveKeys.includes(type);
11565
+ }
11566
+ var typeAlignments = { ...typeSizes };
11567
+ var typeGetters = {
11568
+ u8: (view, offset) => view.getUint8(offset),
11569
+ bool_u8: (view, offset) => Boolean(view.getUint8(offset)),
11570
+ bool_u32: (view, offset) => Boolean(view.getUint32(offset, true)),
11571
+ u16: (view, offset) => view.getUint16(offset, true),
11572
+ i16: (view, offset) => view.getInt16(offset, true),
11573
+ u32: (view, offset) => view.getUint32(offset, true),
11574
+ u64: (view, offset) => view.getBigUint64(offset, true),
11575
+ f32: (view, offset) => view.getFloat32(offset, true),
11576
+ f64: (view, offset) => view.getFloat64(offset, true),
11577
+ i32: (view, offset) => view.getInt32(offset, true),
11578
+ i64: (view, offset) => view.getBigInt64(offset, true),
11579
+ pointer: (view, offset) => pointerSize === 8 ? view.getBigUint64(offset, true) : BigInt(view.getUint32(offset, true))
11580
+ };
11581
+ function isObjectPointerDef(type) {
11582
+ return typeof type === "object" && type !== null && type.__type === "objectPointer";
11583
+ }
11584
+ function alignOffset(offset, align) {
11585
+ return offset + (align - 1) & ~(align - 1);
11586
+ }
11587
+ function enumTypeError(value) {
11588
+ throw new TypeError(`Invalid enum value: ${value}`);
11589
+ }
11590
+ function defineEnum(mapping, base = "u32") {
11591
+ const reverse2 = Object.fromEntries(Object.entries(mapping).map(([k, v]) => [v, k]));
12074
11592
  return {
12075
- args: definition.args,
12076
- returns: definition.returns,
12077
- ptr: definition.ptr == null ? undefined : toBunPointer(definition.ptr),
12078
- threadsafe: definition.threadsafe
11593
+ __type: "enum",
11594
+ type: base,
11595
+ to(value) {
11596
+ return typeof value === "number" ? value : mapping[value] ?? enumTypeError(String(value));
11597
+ },
11598
+ from(value) {
11599
+ return reverse2[value] ?? enumTypeError(String(value));
11600
+ },
11601
+ enum: mapping
12079
11602
  };
12080
11603
  }
12081
- function toBunPointer(pointer) {
12082
- return typeof pointer === "bigint" ? toSafeNumberPointer(pointer) : pointer;
11604
+ function isEnum(type) {
11605
+ return typeof type === "object" && type.__type === "enum";
12083
11606
  }
12084
- function createBunBackend(bun) {
12085
- return {
12086
- dlopen(path5, symbols) {
12087
- if (path5 === null) {
12088
- throw new Error(BUN_DLOPEN_NULL);
11607
+ function isStruct(type) {
11608
+ return typeof type === "object" && type.__type === "struct";
11609
+ }
11610
+ function primitivePackers(type) {
11611
+ let pack;
11612
+ let unpack;
11613
+ switch (type) {
11614
+ case "u8":
11615
+ pack = (view, off, val) => view.setUint8(off, val);
11616
+ unpack = (view, off) => view.getUint8(off);
11617
+ break;
11618
+ case "bool_u8":
11619
+ pack = (view, off, val) => view.setUint8(off, val ? 1 : 0);
11620
+ unpack = (view, off) => Boolean(view.getUint8(off));
11621
+ break;
11622
+ case "bool_u32":
11623
+ pack = (view, off, val) => view.setUint32(off, val ? 1 : 0, true);
11624
+ unpack = (view, off) => Boolean(view.getUint32(off, true));
11625
+ break;
11626
+ case "u16":
11627
+ pack = (view, off, val) => view.setUint16(off, val, true);
11628
+ unpack = (view, off) => view.getUint16(off, true);
11629
+ break;
11630
+ case "i16":
11631
+ pack = (view, off, val) => view.setInt16(off, val, true);
11632
+ unpack = (view, off) => view.getInt16(off, true);
11633
+ break;
11634
+ case "u32":
11635
+ pack = (view, off, val) => view.setUint32(off, val, true);
11636
+ unpack = (view, off) => view.getUint32(off, true);
11637
+ break;
11638
+ case "i32":
11639
+ pack = (view, off, val) => view.setInt32(off, val, true);
11640
+ unpack = (view, off) => view.getInt32(off, true);
11641
+ break;
11642
+ case "i64":
11643
+ pack = (view, off, val) => view.setBigInt64(off, BigInt(val), true);
11644
+ unpack = (view, off) => view.getBigInt64(off, true);
11645
+ break;
11646
+ case "u64":
11647
+ pack = (view, off, val) => view.setBigUint64(off, BigInt(val), true);
11648
+ unpack = (view, off) => view.getBigUint64(off, true);
11649
+ break;
11650
+ case "f32":
11651
+ pack = (view, off, val) => view.setFloat32(off, val, true);
11652
+ unpack = (view, off) => view.getFloat32(off, true);
11653
+ break;
11654
+ case "f64":
11655
+ pack = (view, off, val) => view.setFloat64(off, val, true);
11656
+ unpack = (view, off) => view.getFloat64(off, true);
11657
+ break;
11658
+ case "pointer":
11659
+ pack = (view, off, val) => {
11660
+ pointerSize === 8 ? view.setBigUint64(off, val ? BigInt(val) : 0n, true) : view.setUint32(off, val ? Number(val) : 0, true);
11661
+ };
11662
+ unpack = (view, off) => {
11663
+ if (pointerSize === 8) {
11664
+ const value = view.getBigUint64(off, true);
11665
+ return isBun2 ? Number(value) : value;
11666
+ }
11667
+ return view.getUint32(off, true);
11668
+ };
11669
+ break;
11670
+ default:
11671
+ fatalError(`Unsupported primitive type: ${type}`);
11672
+ }
11673
+ return { pack, unpack };
11674
+ }
11675
+ var { pack: pointerPacker, unpack: pointerUnpacker } = primitivePackers("pointer");
11676
+ var retainedPointerTargets = new WeakMap;
11677
+ function retainPointerTarget(owner, target) {
11678
+ const retained = retainedPointerTargets.get(owner);
11679
+ if (retained) {
11680
+ retained.push(target);
11681
+ } else {
11682
+ retainedPointerTargets.set(owner, [target]);
11683
+ }
11684
+ }
11685
+ function retainIfPointerTargets(owner, target) {
11686
+ if (retainedPointerTargets.has(target)) {
11687
+ retainPointerTarget(owner, target);
11688
+ }
11689
+ }
11690
+ function isNullPointer(pointer) {
11691
+ return pointer == null || pointer === 0 || pointer === 0n;
11692
+ }
11693
+ function toItemCount(length) {
11694
+ return typeof length === "bigint" ? Number(length) : length;
11695
+ }
11696
+ function packObjectArray(val) {
11697
+ const buffer = new ArrayBuffer(val.length * pointerSize);
11698
+ const bufferView = new DataView(buffer);
11699
+ for (let i = 0;i < val.length; i++) {
11700
+ const instance = val[i];
11701
+ const ptrValue = instance?.ptr ?? null;
11702
+ pointerPacker(bufferView, i * pointerSize, ptrValue);
11703
+ }
11704
+ return bufferView;
11705
+ }
11706
+ var encoder = new TextEncoder;
11707
+ var decoder = new TextDecoder;
11708
+ function defineStruct(fields, structDefOptions) {
11709
+ let offset = 0;
11710
+ let maxAlign = 1;
11711
+ const layout = [];
11712
+ const lengthOfFields = {};
11713
+ const lengthOfRequested = [];
11714
+ const arrayFieldsMetadata = {};
11715
+ for (const [name, typeOrStruct, options = {}] of fields) {
11716
+ if (options.condition && !options.condition()) {
11717
+ continue;
11718
+ }
11719
+ let size = 0, align = 0;
11720
+ let pack;
11721
+ let unpack;
11722
+ let needsLengthOf = false;
11723
+ let lengthOfDef = null;
11724
+ if (isPrimitiveType(typeOrStruct)) {
11725
+ size = typeSizes[typeOrStruct];
11726
+ align = typeAlignments[typeOrStruct];
11727
+ ({ pack, unpack } = primitivePackers(typeOrStruct));
11728
+ } else if (typeof typeOrStruct === "string" && typeOrStruct === "cstring") {
11729
+ size = pointerSize;
11730
+ align = pointerSize;
11731
+ pack = (view, off, val) => {
11732
+ if (!val) {
11733
+ pointerPacker(view, off, null);
11734
+ return;
11735
+ }
11736
+ const bytes = encoder.encode(val + "\x00");
11737
+ const bufPtr = ptr2(bytes);
11738
+ pointerPacker(view, off, bufPtr);
11739
+ retainPointerTarget(view.buffer, bytes);
11740
+ };
11741
+ unpack = (view, off) => {
11742
+ const ptrVal = pointerUnpacker(view, off);
11743
+ return ptrVal;
11744
+ };
11745
+ } else if (typeof typeOrStruct === "string" && typeOrStruct === "char*") {
11746
+ size = pointerSize;
11747
+ align = pointerSize;
11748
+ pack = (view, off, val) => {
11749
+ if (!val) {
11750
+ pointerPacker(view, off, null);
11751
+ return;
11752
+ }
11753
+ const bytes = encoder.encode(val);
11754
+ const bufPtr = ptr2(bytes);
11755
+ pointerPacker(view, off, bufPtr);
11756
+ retainPointerTarget(view.buffer, bytes);
11757
+ };
11758
+ unpack = (view, off) => {
11759
+ const ptrVal = pointerUnpacker(view, off);
11760
+ return ptrVal;
11761
+ };
11762
+ needsLengthOf = true;
11763
+ } else if (isEnum(typeOrStruct)) {
11764
+ const base = typeOrStruct.type;
11765
+ size = typeSizes[base];
11766
+ align = typeAlignments[base];
11767
+ const { pack: packEnum } = primitivePackers(base);
11768
+ pack = (view, off, val) => {
11769
+ const num = typeOrStruct.to(val);
11770
+ packEnum(view, off, num);
11771
+ };
11772
+ unpack = (view, off) => {
11773
+ const raw = typeGetters[base](view, off);
11774
+ return typeOrStruct.from(raw);
11775
+ };
11776
+ } else if (isStruct(typeOrStruct)) {
11777
+ if (options.asPointer === true) {
11778
+ size = pointerSize;
11779
+ align = pointerSize;
11780
+ pack = (view, off, val, obj, options2) => {
11781
+ if (!val) {
11782
+ pointerPacker(view, off, null);
11783
+ return;
11784
+ }
11785
+ const nestedBuf = typeOrStruct.pack(val, options2);
11786
+ pointerPacker(view, off, ptr2(nestedBuf));
11787
+ retainPointerTarget(view.buffer, nestedBuf);
11788
+ };
11789
+ unpack = (view, off) => {
11790
+ throw new Error("Not implemented yet");
11791
+ };
11792
+ } else {
11793
+ size = typeOrStruct.size;
11794
+ align = typeOrStruct.align;
11795
+ pack = (view, off, val, obj, options2) => {
11796
+ const nestedBuf = typeOrStruct.pack(val, options2);
11797
+ const nestedView = new Uint8Array(nestedBuf);
11798
+ const dView = new Uint8Array(view.buffer);
11799
+ dView.set(nestedView, off);
11800
+ retainIfPointerTargets(view.buffer, nestedBuf);
11801
+ };
11802
+ unpack = (view, off) => {
11803
+ const slice = view.buffer.slice(off, off + size);
11804
+ return typeOrStruct.unpack(slice);
11805
+ };
12089
11806
  }
12090
- const library = bun.dlopen(path5, normalizeBunDefinitions(symbols));
12091
- const callbacks = new Set;
12092
- let closed = false;
12093
- return {
12094
- symbols: library.symbols,
12095
- createCallback(callback, definition) {
12096
- if (closed) {
12097
- throw new Error(LIBRARY_CLOSED);
11807
+ } else if (isObjectPointerDef(typeOrStruct)) {
11808
+ size = pointerSize;
11809
+ align = pointerSize;
11810
+ pack = (view, off, value) => {
11811
+ const ptrValue = value?.ptr ?? null;
11812
+ if (ptrValue === undefined) {
11813
+ console.warn(`Field '${name}' expected object with '.ptr' property, but got undefined pointer value from:`, value);
11814
+ pointerPacker(view, off, null);
11815
+ } else {
11816
+ pointerPacker(view, off, ptrValue);
11817
+ }
11818
+ };
11819
+ unpack = (view, off) => {
11820
+ return pointerUnpacker(view, off);
11821
+ };
11822
+ } else if (Array.isArray(typeOrStruct) && typeOrStruct.length === 1 && typeOrStruct[0] !== undefined) {
11823
+ const [def] = typeOrStruct;
11824
+ size = pointerSize;
11825
+ align = pointerSize;
11826
+ let arrayElementSize;
11827
+ if (isEnum(def)) {
11828
+ arrayElementSize = typeSizes[def.type];
11829
+ pack = (view, off, val, obj) => {
11830
+ if (!val || val.length === 0) {
11831
+ pointerPacker(view, off, null);
11832
+ return;
12098
11833
  }
12099
- const raw = new bun.JSCallback(callback, normalizeBunDefinition(definition));
12100
- return createManagedCallback(raw, callbacks);
12101
- },
12102
- close() {
12103
- if (closed) {
11834
+ const buffer = new ArrayBuffer(val.length * arrayElementSize);
11835
+ const bufferView = new DataView(buffer);
11836
+ for (let i = 0;i < val.length; i++) {
11837
+ const num = def.to(val[i]);
11838
+ bufferView.setUint32(i * arrayElementSize, num, true);
11839
+ }
11840
+ pointerPacker(view, off, ptr2(buffer));
11841
+ retainPointerTarget(view.buffer, buffer);
11842
+ };
11843
+ unpack = null;
11844
+ needsLengthOf = true;
11845
+ lengthOfDef = def;
11846
+ } else if (isStruct(def)) {
11847
+ arrayElementSize = def.size;
11848
+ pack = (view, off, val, obj, options2) => {
11849
+ if (!val || val.length === 0) {
11850
+ pointerPacker(view, off, null);
12104
11851
  return;
12105
11852
  }
12106
- closed = true;
12107
- try {
12108
- library.close();
12109
- } finally {
12110
- for (const callback of [...callbacks]) {
12111
- callback.close();
12112
- }
11853
+ const buffer = new ArrayBuffer(val.length * arrayElementSize);
11854
+ const bufferView = new DataView(buffer);
11855
+ for (let i = 0;i < val.length; i++) {
11856
+ def.packInto(val[i], bufferView, i * arrayElementSize, options2);
11857
+ }
11858
+ pointerPacker(view, off, ptr2(buffer));
11859
+ retainPointerTarget(view.buffer, buffer);
11860
+ };
11861
+ unpack = (view, off) => {
11862
+ throw new Error("Not implemented yet");
11863
+ };
11864
+ } else if (isPrimitiveType(def)) {
11865
+ arrayElementSize = typeSizes[def];
11866
+ const { pack: primitivePack } = primitivePackers(def);
11867
+ pack = (view, off, val) => {
11868
+ if (!val || val.length === 0) {
11869
+ pointerPacker(view, off, null);
11870
+ return;
11871
+ }
11872
+ const buffer = new ArrayBuffer(val.length * arrayElementSize);
11873
+ const bufferView = new DataView(buffer);
11874
+ for (let i = 0;i < val.length; i++) {
11875
+ primitivePack(bufferView, i * arrayElementSize, val[i]);
11876
+ }
11877
+ pointerPacker(view, off, ptr2(buffer));
11878
+ retainPointerTarget(view.buffer, buffer);
11879
+ };
11880
+ unpack = null;
11881
+ needsLengthOf = true;
11882
+ lengthOfDef = def;
11883
+ } else if (isObjectPointerDef(def)) {
11884
+ arrayElementSize = pointerSize;
11885
+ pack = (view, off, val) => {
11886
+ if (!val || val.length === 0) {
11887
+ pointerPacker(view, off, null);
11888
+ return;
11889
+ }
11890
+ const packedView = packObjectArray(val);
11891
+ pointerPacker(view, off, ptr2(packedView.buffer));
11892
+ retainPointerTarget(view.buffer, packedView.buffer);
11893
+ };
11894
+ unpack = () => {
11895
+ throw new Error("not implemented yet");
11896
+ };
11897
+ } else {
11898
+ throw new Error(`Unsupported array element type for ${name}: ${JSON.stringify(def)}`);
11899
+ }
11900
+ const lengthOfField = Object.values(lengthOfFields).find((f) => f.lengthOf === name);
11901
+ if (lengthOfField && isPrimitiveType(lengthOfField.type)) {
11902
+ const { pack: lengthPack } = primitivePackers(lengthOfField.type);
11903
+ arrayFieldsMetadata[name] = {
11904
+ elementSize: arrayElementSize,
11905
+ arrayOffset: offset,
11906
+ lengthOffset: lengthOfField.offset,
11907
+ lengthPack
11908
+ };
11909
+ }
11910
+ } else {
11911
+ throw new Error(`Unsupported field type for ${name}: ${JSON.stringify(typeOrStruct)}`);
11912
+ }
11913
+ offset = alignOffset(offset, align);
11914
+ if (options.unpackTransform) {
11915
+ const originalUnpack = unpack;
11916
+ unpack = (view, off) => options.unpackTransform(originalUnpack(view, off));
11917
+ }
11918
+ if (options.packTransform) {
11919
+ const originalPack = pack;
11920
+ pack = (view, off, val, obj, packOptions) => originalPack(view, off, options.packTransform(val), obj, packOptions);
11921
+ }
11922
+ if (options.optional) {
11923
+ const originalPack = pack;
11924
+ if (isStruct(typeOrStruct) && !options.asPointer) {
11925
+ pack = (view, off, val, obj, packOptions) => {
11926
+ if (val || options.mapOptionalInline) {
11927
+ originalPack(view, off, val, obj, packOptions);
11928
+ }
11929
+ };
11930
+ } else {
11931
+ pack = (view, off, val, obj, packOptions) => originalPack(view, off, val ?? 0, obj, packOptions);
11932
+ }
11933
+ }
11934
+ if (options.lengthOf) {
11935
+ const originalPack = pack;
11936
+ pack = (view, off, val, obj, packOptions) => {
11937
+ const targetValue = obj[options.lengthOf];
11938
+ let length = 0;
11939
+ if (targetValue) {
11940
+ if (typeof targetValue === "string") {
11941
+ length = Buffer.byteLength(targetValue);
11942
+ } else {
11943
+ length = targetValue.length;
12113
11944
  }
12114
11945
  }
11946
+ return originalPack(view, off, length, obj, packOptions);
11947
+ };
11948
+ }
11949
+ let validateFunctions;
11950
+ if (options.validate) {
11951
+ validateFunctions = Array.isArray(options.validate) ? options.validate : [options.validate];
11952
+ }
11953
+ const layoutField = {
11954
+ name,
11955
+ offset,
11956
+ size,
11957
+ align,
11958
+ validate: validateFunctions,
11959
+ optional: !!options.optional || !!options.lengthOf || options.default !== undefined,
11960
+ default: options.default,
11961
+ pack,
11962
+ unpack,
11963
+ type: typeOrStruct,
11964
+ lengthOf: options.lengthOf
11965
+ };
11966
+ layout.push(layoutField);
11967
+ if (options.lengthOf) {
11968
+ lengthOfFields[options.lengthOf] = layoutField;
11969
+ }
11970
+ if (needsLengthOf) {
11971
+ const def = typeof typeOrStruct === "string" && typeOrStruct === "char*" ? "char*" : lengthOfDef;
11972
+ if (!def)
11973
+ fatalError(`Internal error: needsLengthOf=true but def is null for ${name}`);
11974
+ lengthOfRequested.push({ requester: layoutField, def });
11975
+ }
11976
+ offset += size;
11977
+ maxAlign = Math.max(maxAlign, align);
11978
+ }
11979
+ for (const { requester, def } of lengthOfRequested) {
11980
+ const lengthOfField = lengthOfFields[requester.name];
11981
+ if (!lengthOfField) {
11982
+ if (def === "char*") {
11983
+ continue;
11984
+ }
11985
+ throw new Error(`lengthOf field not found for array field ${requester.name}`);
11986
+ }
11987
+ if (def === "char*") {
11988
+ const relativeOffset = lengthOfField.offset - requester.offset;
11989
+ requester.unpack = (view, off) => {
11990
+ const ptrAddress = pointerUnpacker(view, off);
11991
+ const length = lengthOfField.unpack(view, off + relativeOffset);
11992
+ if (isNullPointer(ptrAddress)) {
11993
+ return null;
11994
+ }
11995
+ const byteLength = toItemCount(length);
11996
+ if (byteLength === 0) {
11997
+ return "";
11998
+ }
11999
+ const buffer = toArrayBuffer2(ptrAddress, 0, byteLength);
12000
+ return decoder.decode(buffer);
12001
+ };
12002
+ } else if (isPrimitiveType(def)) {
12003
+ const elemSize = typeSizes[def];
12004
+ const { unpack: primitiveUnpack } = primitivePackers(def);
12005
+ const relativeOffset = lengthOfField.offset - requester.offset;
12006
+ requester.unpack = (view, off) => {
12007
+ const result = [];
12008
+ const length = lengthOfField.unpack(view, off + relativeOffset);
12009
+ const itemCount = toItemCount(length);
12010
+ const ptrAddress = pointerUnpacker(view, off);
12011
+ if (isNullPointer(ptrAddress) && itemCount > 0) {
12012
+ throw new Error(`Array field ${requester.name} has null pointer but length ${length}.`);
12013
+ }
12014
+ if (isNullPointer(ptrAddress) || itemCount === 0) {
12015
+ return [];
12016
+ }
12017
+ const buffer = toArrayBuffer2(ptrAddress, 0, itemCount * elemSize);
12018
+ const bufferView = new DataView(buffer);
12019
+ for (let i = 0;i < itemCount; i++) {
12020
+ result.push(primitiveUnpack(bufferView, i * elemSize));
12021
+ }
12022
+ return result;
12023
+ };
12024
+ } else {
12025
+ const elemSize = def.type === "u32" ? 4 : 8;
12026
+ const relativeOffset = lengthOfField.offset - requester.offset;
12027
+ requester.unpack = (view, off) => {
12028
+ const result = [];
12029
+ const length = lengthOfField.unpack(view, off + relativeOffset);
12030
+ const itemCount = toItemCount(length);
12031
+ const ptrAddress = pointerUnpacker(view, off);
12032
+ if (isNullPointer(ptrAddress) && itemCount > 0) {
12033
+ throw new Error(`Array field ${requester.name} has null pointer but length ${length}.`);
12034
+ }
12035
+ if (isNullPointer(ptrAddress) || itemCount === 0) {
12036
+ return [];
12037
+ }
12038
+ const buffer = toArrayBuffer2(ptrAddress, 0, itemCount * elemSize);
12039
+ const bufferView = new DataView(buffer);
12040
+ for (let i = 0;i < itemCount; i++) {
12041
+ result.push(def.from(bufferView.getUint32(i * elemSize, true)));
12042
+ }
12043
+ return result;
12115
12044
  };
12116
- },
12117
- ptr: bun.ptr,
12118
- suffix: bun.suffix,
12119
- toArrayBuffer(pointer, offset, length) {
12120
- return bun.toArrayBuffer(toBunPointer(pointer), offset, length);
12121
12045
  }
12122
- };
12123
- }
12124
- function createNodeBackend(nodeFfi) {
12046
+ }
12047
+ const totalSize = alignOffset(offset, maxAlign);
12048
+ const description = layout.map((f) => ({
12049
+ name: f.name,
12050
+ offset: f.offset,
12051
+ size: f.size,
12052
+ align: f.align,
12053
+ optional: f.optional,
12054
+ type: f.type,
12055
+ lengthOf: f.lengthOf
12056
+ }));
12057
+ const layoutByName = new Map(description.map((f) => [f.name, f]));
12058
+ const arrayFields = new Map(Object.entries(arrayFieldsMetadata));
12125
12059
  return {
12126
- dlopen(path5, symbols) {
12127
- const { lib, functions } = nodeFfi.dlopen(toNodeLibraryPath(path5), normalizeNodeDefinitions(symbols));
12128
- const callbacks = new Set;
12129
- let closed = false;
12130
- let libraryClosed = false;
12131
- return {
12132
- symbols: functions,
12133
- createCallback(callback, definition) {
12134
- if (closed) {
12135
- throw new Error(LIBRARY_CLOSED);
12060
+ __type: "struct",
12061
+ size: totalSize,
12062
+ align: maxAlign,
12063
+ hasMapValue: !!structDefOptions?.mapValue,
12064
+ layoutByName,
12065
+ arrayFields,
12066
+ pack(obj, options) {
12067
+ const buf = new ArrayBuffer(totalSize);
12068
+ const view = new DataView(buf);
12069
+ let mappedObj = obj;
12070
+ if (structDefOptions?.mapValue) {
12071
+ mappedObj = structDefOptions.mapValue(obj);
12072
+ }
12073
+ for (const field of layout) {
12074
+ const value = mappedObj[field.name] ?? field.default;
12075
+ if (!field.optional && value === undefined) {
12076
+ fatalError(`Packing non-optional field '${field.name}' but value is undefined (and no default provided)`);
12077
+ }
12078
+ if (field.validate) {
12079
+ for (const validateFn of field.validate) {
12080
+ validateFn(value, field.name, {
12081
+ hints: options?.validationHints,
12082
+ input: mappedObj
12083
+ });
12136
12084
  }
12137
- if (definition.threadsafe) {
12138
- throw new Error(NODE_CALLBACK_THREADSAFE);
12085
+ }
12086
+ field.pack(view, field.offset, value, mappedObj, options);
12087
+ }
12088
+ return view.buffer;
12089
+ },
12090
+ packInto(obj, view, offset2, options) {
12091
+ let mappedObj = obj;
12092
+ if (structDefOptions?.mapValue) {
12093
+ mappedObj = structDefOptions.mapValue(obj);
12094
+ }
12095
+ for (const field of layout) {
12096
+ const value = mappedObj[field.name] ?? field.default;
12097
+ if (!field.optional && value === undefined) {
12098
+ console.warn(`packInto missing value for non-optional field '${field.name}' at offset ${offset2 + field.offset}. Writing default or zero.`);
12099
+ }
12100
+ if (field.validate) {
12101
+ for (const validateFn of field.validate) {
12102
+ validateFn(value, field.name, {
12103
+ hints: options?.validationHints,
12104
+ input: mappedObj
12105
+ });
12139
12106
  }
12140
- const callbackPointer = lib.registerCallback(normalizeNodeDefinition(definition), callback);
12141
- const raw = {
12142
- ptr: callbackPointer,
12143
- threadsafe: false,
12144
- close() {
12145
- if (!libraryClosed) {
12146
- lib.unregisterCallback(callbackPointer);
12147
- }
12148
- }
12149
- };
12150
- return createManagedCallback(raw, callbacks);
12151
- },
12152
- close() {
12153
- if (closed) {
12154
- return;
12107
+ }
12108
+ field.pack(view, offset2 + field.offset, value, mappedObj, options);
12109
+ }
12110
+ },
12111
+ unpack(buf) {
12112
+ if (buf.byteLength < totalSize) {
12113
+ fatalError(`Buffer size (${buf.byteLength}) is smaller than struct size (${totalSize}) for unpacking.`);
12114
+ }
12115
+ const view = new DataView(buf);
12116
+ const result = structDefOptions?.default ? { ...structDefOptions.default } : {};
12117
+ for (const field of layout) {
12118
+ if (!field.unpack) {
12119
+ continue;
12120
+ }
12121
+ try {
12122
+ result[field.name] = field.unpack(view, field.offset);
12123
+ } catch (e) {
12124
+ console.error(`Error unpacking field '${field.name}' at offset ${field.offset}:`, e);
12125
+ throw e;
12126
+ }
12127
+ }
12128
+ if (structDefOptions?.reduceValue) {
12129
+ return structDefOptions.reduceValue(result);
12130
+ }
12131
+ return result;
12132
+ },
12133
+ packList(objects, options) {
12134
+ if (objects.length === 0) {
12135
+ return new ArrayBuffer(0);
12136
+ }
12137
+ const buffer = new ArrayBuffer(totalSize * objects.length);
12138
+ const view = new DataView(buffer);
12139
+ for (let i = 0;i < objects.length; i++) {
12140
+ let mappedObj = objects[i];
12141
+ if (structDefOptions?.mapValue) {
12142
+ mappedObj = structDefOptions.mapValue(objects[i]);
12143
+ }
12144
+ for (const field of layout) {
12145
+ const value = mappedObj[field.name] ?? field.default;
12146
+ if (!field.optional && value === undefined) {
12147
+ fatalError(`Packing non-optional field '${field.name}' at index ${i} but value is undefined (and no default provided)`);
12155
12148
  }
12156
- closed = true;
12157
- try {
12158
- libraryClosed = true;
12159
- lib.close();
12160
- } finally {
12161
- for (const callback of [...callbacks]) {
12162
- callback.close();
12149
+ if (field.validate) {
12150
+ for (const validateFn of field.validate) {
12151
+ validateFn(value, field.name, {
12152
+ hints: options?.validationHints,
12153
+ input: mappedObj
12154
+ });
12163
12155
  }
12164
12156
  }
12157
+ field.pack(view, i * totalSize + field.offset, value, mappedObj, options);
12165
12158
  }
12166
- };
12159
+ }
12160
+ return buffer;
12167
12161
  },
12168
- ptr(value) {
12169
- if (ArrayBuffer.isView(value)) {
12170
- if (!(value.buffer instanceof ArrayBuffer)) {
12171
- throw new TypeError(NODE_PTR_VALUE);
12172
- }
12173
- return nodeFfi.getRawPointer(value.buffer) + BigInt(value.byteOffset);
12162
+ unpackList(buf, count) {
12163
+ if (count === 0) {
12164
+ return [];
12174
12165
  }
12175
- if (value instanceof ArrayBuffer) {
12176
- return nodeFfi.getRawPointer(value);
12166
+ const expectedSize = totalSize * count;
12167
+ if (buf.byteLength < expectedSize) {
12168
+ fatalError(`Buffer size (${buf.byteLength}) is smaller than expected size (${expectedSize}) for unpacking ${count} structs.`);
12177
12169
  }
12178
- throw new TypeError(NODE_PTR_VALUE);
12179
- },
12180
- suffix: nodeFfi.suffix,
12181
- toArrayBuffer(pointer, offset, length) {
12182
- return nodeFfi.toArrayBuffer(toBigIntPointer(pointer) + BigInt(offset ?? 0), length, false);
12183
- }
12184
- };
12185
- }
12186
- function toNodeLibraryPath(path5) {
12187
- return path5 instanceof URL ? fileURLToPath2(path5) : path5;
12188
- }
12189
- function normalizeNodeDefinitions(definitions) {
12190
- return Object.fromEntries(Object.entries(definitions).map(([name, definition]) => [name, normalizeNodeDefinition(definition)]));
12191
- }
12192
- function normalizeNodeDefinition(definition) {
12193
- if (definition.ptr != null) {
12194
- throw new Error(NODE_POINTER_OVERRIDE);
12195
- }
12196
- return {
12197
- parameters: (definition.args ?? []).map((type) => toNodeFFIType(type, "parameter")),
12198
- result: toNodeFFIType(definition.returns ?? FFIType.void, "result")
12199
- };
12200
- }
12201
- function toNodeFFIType(type, position) {
12202
- switch (type) {
12203
- case FFIType.char:
12204
- return "char";
12205
- case FFIType.int8_t:
12206
- case FFIType.i8:
12207
- return "i8";
12208
- case FFIType.uint8_t:
12209
- case FFIType.u8:
12210
- return "u8";
12211
- case FFIType.int16_t:
12212
- case FFIType.i16:
12213
- return "i16";
12214
- case FFIType.uint16_t:
12215
- case FFIType.u16:
12216
- return "u16";
12217
- case FFIType.int32_t:
12218
- case FFIType.int:
12219
- case FFIType.i32:
12220
- return "i32";
12221
- case FFIType.uint32_t:
12222
- case FFIType.u32:
12223
- return "u32";
12224
- case FFIType.int64_t:
12225
- case FFIType.i64:
12226
- return "i64";
12227
- case FFIType.uint64_t:
12228
- case FFIType.u64:
12229
- return "u64";
12230
- case FFIType.double:
12231
- case FFIType.f64:
12232
- return "f64";
12233
- case FFIType.float:
12234
- case FFIType.f32:
12235
- return "f32";
12236
- case FFIType.bool:
12237
- return "bool";
12238
- case FFIType.ptr:
12239
- case FFIType.pointer:
12240
- return "pointer";
12241
- case FFIType.void:
12242
- return "void";
12243
- case FFIType.cstring:
12244
- if (position === "result") {
12245
- throw new Error(NODE_STRING_RETURN);
12170
+ const view = new DataView(buf);
12171
+ const results = [];
12172
+ for (let i = 0;i < count; i++) {
12173
+ const offset2 = i * totalSize;
12174
+ const result = structDefOptions?.default ? { ...structDefOptions.default } : {};
12175
+ for (const field of layout) {
12176
+ if (!field.unpack) {
12177
+ continue;
12178
+ }
12179
+ try {
12180
+ result[field.name] = field.unpack(view, offset2 + field.offset);
12181
+ } catch (e) {
12182
+ console.error(`Error unpacking field '${field.name}' at index ${i}, offset ${offset2 + field.offset}:`, e);
12183
+ throw e;
12184
+ }
12185
+ }
12186
+ if (structDefOptions?.reduceValue) {
12187
+ results.push(structDefOptions.reduceValue(result));
12188
+ } else {
12189
+ results.push(result);
12190
+ }
12246
12191
  }
12247
- return "string";
12248
- case FFIType.function:
12249
- case FFIType.callback:
12250
- return "pointer";
12251
- case FFIType.usize:
12252
- throw new Error(NODE_USIZE_UNSUPPORTED);
12253
- case FFIType.napi_env:
12254
- case FFIType.napi_value:
12255
- throw new Error(NODE_NAPI_UNSUPPORTED);
12256
- case FFIType.buffer:
12257
- return "buffer";
12258
- default:
12259
- return unsupportedNodeFFIType(type);
12260
- }
12261
- }
12262
- function unsupportedNodeFFIType(type) {
12263
- throw new Error(`Unsupported FFIType for node:ffi: ${String(type)}`);
12264
- }
12265
- function toBigIntPointer(pointer) {
12266
- return typeof pointer === "bigint" ? pointer : BigInt(pointer);
12192
+ return results;
12193
+ },
12194
+ describe() {
12195
+ return description;
12196
+ }
12197
+ };
12267
12198
  }
12268
- var dlopen = backend.dlopen;
12269
- var ptr4 = backend.ptr;
12270
- var suffix = backend.suffix;
12271
- var toArrayBuffer4 = backend.toArrayBuffer;
12199
+
12200
+ // src/zig-structs.ts
12201
+ var rgbaPackTransform = (rgba) => rgba ? ptr(rgba.buffer) : null;
12202
+ var rgbaUnpackTransform = (ptr3) => ptr3 ? RGBA.fromArray(new Uint16Array(toArrayBuffer(ptr3, 0, 8))) : undefined;
12203
+ var StyledChunkStruct = defineStruct([
12204
+ ["text", "char*"],
12205
+ ["text_len", "u64", { lengthOf: "text" }],
12206
+ [
12207
+ "fg",
12208
+ "pointer",
12209
+ {
12210
+ optional: true,
12211
+ packTransform: rgbaPackTransform,
12212
+ unpackTransform: rgbaUnpackTransform
12213
+ }
12214
+ ],
12215
+ [
12216
+ "bg",
12217
+ "pointer",
12218
+ {
12219
+ optional: true,
12220
+ packTransform: rgbaPackTransform,
12221
+ unpackTransform: rgbaUnpackTransform
12222
+ }
12223
+ ],
12224
+ ["attributes", "u32", { default: 0 }],
12225
+ ["link", "char*", { default: "" }],
12226
+ ["link_len", "u64", { lengthOf: "link" }]
12227
+ ], {
12228
+ mapValue: (chunk) => {
12229
+ const normalizedFg = normalizeColorValue(chunk.fg ?? null);
12230
+ const normalizedBg = normalizeColorValue(chunk.bg ?? null);
12231
+ if (!chunk.link || typeof chunk.link === "string") {
12232
+ return {
12233
+ ...chunk,
12234
+ fg: normalizedFg?.rgba ?? null,
12235
+ bg: normalizedBg?.rgba ?? null
12236
+ };
12237
+ }
12238
+ return {
12239
+ ...chunk,
12240
+ fg: normalizedFg?.rgba ?? null,
12241
+ bg: normalizedBg?.rgba ?? null,
12242
+ link: chunk.link.url
12243
+ };
12244
+ }
12245
+ });
12246
+ var HighlightStruct = defineStruct([
12247
+ ["start", "u32"],
12248
+ ["end", "u32"],
12249
+ ["styleId", "u32"],
12250
+ ["priority", "u8", { default: 0 }],
12251
+ ["hlRef", "u16", { default: 0 }]
12252
+ ]);
12253
+ var LogicalCursorStruct = defineStruct([
12254
+ ["row", "u32"],
12255
+ ["col", "u32"],
12256
+ ["offset", "u32"]
12257
+ ]);
12258
+ var VisualCursorStruct = defineStruct([
12259
+ ["visualRow", "u32"],
12260
+ ["visualCol", "u32"],
12261
+ ["logicalRow", "u32"],
12262
+ ["logicalCol", "u32"],
12263
+ ["offset", "u32"]
12264
+ ]);
12265
+ var UnicodeMethodEnum = defineEnum({ wcwidth: 0, unicode: 1 }, "u8");
12266
+ var TerminalCapabilitiesStruct = defineStruct([
12267
+ ["kitty_keyboard", "bool_u8"],
12268
+ ["kitty_graphics", "bool_u8"],
12269
+ ["rgb", "bool_u8"],
12270
+ ["ansi256", "bool_u8"],
12271
+ ["unicode", UnicodeMethodEnum],
12272
+ ["sgr_pixels", "bool_u8"],
12273
+ ["color_scheme_updates", "bool_u8"],
12274
+ ["explicit_width", "bool_u8"],
12275
+ ["scaled_text", "bool_u8"],
12276
+ ["sixel", "bool_u8"],
12277
+ ["focus_tracking", "bool_u8"],
12278
+ ["sync", "bool_u8"],
12279
+ ["bracketed_paste", "bool_u8"],
12280
+ ["hyperlinks", "bool_u8"],
12281
+ ["osc52", "bool_u8"],
12282
+ ["explicit_cursor_positioning", "bool_u8"],
12283
+ ["in_tmux", "bool_u8"],
12284
+ ["term_name", "char*"],
12285
+ ["term_name_len", "u64", { lengthOf: "term_name" }],
12286
+ ["term_version", "char*"],
12287
+ ["term_version_len", "u64", { lengthOf: "term_version" }],
12288
+ ["term_from_xtversion", "bool_u8"]
12289
+ ]);
12290
+ var EncodedCharStruct = defineStruct([
12291
+ ["width", "u8"],
12292
+ ["char", "u32"]
12293
+ ]);
12294
+ var LineInfoStruct = defineStruct([
12295
+ ["startCols", ["u32"]],
12296
+ ["startColsLen", "u32", { lengthOf: "startCols" }],
12297
+ ["widthCols", ["u32"]],
12298
+ ["widthColsLen", "u32", { lengthOf: "widthCols" }],
12299
+ ["sources", ["u32"]],
12300
+ ["sourcesLen", "u32", { lengthOf: "sources" }],
12301
+ ["wraps", ["u32"]],
12302
+ ["wrapsLen", "u32", { lengthOf: "wraps" }],
12303
+ ["widthColsMax", "u32"]
12304
+ ]);
12305
+ var MeasureResultStruct = defineStruct([
12306
+ ["lineCount", "u32"],
12307
+ ["widthColsMax", "u32"]
12308
+ ]);
12309
+ var CursorStateStruct = defineStruct([
12310
+ ["x", "u32"],
12311
+ ["y", "u32"],
12312
+ ["visible", "bool_u8"],
12313
+ ["style", "u8"],
12314
+ ["blinking", "bool_u8"],
12315
+ ["r", "f32"],
12316
+ ["g", "f32"],
12317
+ ["b", "f32"],
12318
+ ["a", "f32"]
12319
+ ]);
12320
+ var CursorStyleOptionsStruct = defineStruct([
12321
+ ["style", "u8", { default: 255 }],
12322
+ ["blinking", "u8", { default: 255 }],
12323
+ [
12324
+ "color",
12325
+ "pointer",
12326
+ {
12327
+ optional: true,
12328
+ packTransform: rgbaPackTransform,
12329
+ unpackTransform: rgbaUnpackTransform
12330
+ }
12331
+ ],
12332
+ ["cursor", "u8", { default: 255 }]
12333
+ ]);
12334
+ var GridDrawOptionsStruct = defineStruct([
12335
+ ["drawInner", "bool_u8", { default: true }],
12336
+ ["drawOuter", "bool_u8", { default: true }]
12337
+ ]);
12338
+ var BuildOptionsStruct = defineStruct([
12339
+ ["gpaSafeStats", "bool_u8"],
12340
+ ["gpaMemoryLimitTracking", "bool_u8"]
12341
+ ]);
12342
+ var AllocatorStatsStruct = defineStruct([
12343
+ ["totalRequestedBytes", "u64"],
12344
+ ["activeAllocations", "u64"],
12345
+ ["smallAllocations", "u64"],
12346
+ ["largeAllocations", "u64"],
12347
+ ["requestedBytesValid", "bool_u8"]
12348
+ ]);
12349
+ var GrowthPolicyEnum = defineEnum({ grow: 0, block: 1 }, "u8");
12350
+ var NativeSpanFeedOptionsStruct = defineStruct([
12351
+ ["chunkSize", "u32", { default: 64 * 1024 }],
12352
+ ["initialChunks", "u32", { default: 2 }],
12353
+ ["maxBytes", "u64", { default: 0n }],
12354
+ ["growthPolicy", GrowthPolicyEnum, { default: "grow" }],
12355
+ ["autoCommitOnFull", "bool_u8", { default: true }],
12356
+ ["spanQueueCapacity", "u32", { default: 0 }]
12357
+ ]);
12358
+ var NativeSpanFeedStatsStruct = defineStruct([
12359
+ ["bytesWritten", "u64"],
12360
+ ["spansCommitted", "u64"],
12361
+ ["chunks", "u32"],
12362
+ ["pendingSpans", "u32"]
12363
+ ]);
12364
+ var SpanInfoStruct = defineStruct([
12365
+ ["chunkPtr", "pointer"],
12366
+ ["offset", "u32"],
12367
+ ["len", "u32"],
12368
+ ["chunkIndex", "u32"],
12369
+ ["reserved", "u32", { default: 0 }]
12370
+ ], {
12371
+ reduceValue: (value) => ({
12372
+ chunkPtr: value.chunkPtr,
12373
+ offset: value.offset,
12374
+ len: value.len,
12375
+ chunkIndex: value.chunkIndex
12376
+ })
12377
+ });
12378
+ var ReserveInfoStruct = defineStruct([
12379
+ ["ptr", "pointer"],
12380
+ ["len", "u32"],
12381
+ ["reserved", "u32", { default: 0 }]
12382
+ ], {
12383
+ reduceValue: (value) => ({
12384
+ ptr: value.ptr,
12385
+ len: value.len
12386
+ })
12387
+ });
12272
12388
 
12273
12389
  // src/zig.ts
12274
12390
  var module = await import(`@opentui/core-${process.platform}-${process.arch}/index.ts`);
@@ -12321,19 +12437,18 @@ var MOUSE_STYLE_TO_ID = { default: 0, pointer: 1, text: 2, crosshair: 3, move: 4
12321
12437
  var globalTraceSymbols = null;
12322
12438
  var globalFFILogPath = null;
12323
12439
  var exitHandlerRegistered = false;
12324
- var toPointer2 = toPointer;
12325
12440
  function toNumber(value) {
12326
12441
  return typeof value === "bigint" ? Number(value) : value;
12327
12442
  }
12328
12443
  function rgbaPtr(value) {
12329
- return ptr5(value.buffer);
12444
+ return ptr(value.buffer);
12330
12445
  }
12331
12446
  function optionalRgbaPtr(value) {
12332
12447
  return value ? rgbaPtr(value) : null;
12333
12448
  }
12334
12449
  function getOpenTUILib(libPath) {
12335
12450
  const resolvedLibPath = libPath || targetLibPath;
12336
- const rawSymbols = dlopen2(resolvedLibPath, {
12451
+ const rawSymbols = dlopen(resolvedLibPath, {
12337
12452
  setLogCallback: {
12338
12453
  args: ["ptr"],
12339
12454
  returns: "void"
@@ -13345,6 +13460,7 @@ function getOpenTUILib(libPath) {
13345
13460
  });
13346
13461
  if (env.OTUI_DEBUG_FFI || env.OTUI_TRACE_FFI) {
13347
13462
  return {
13463
+ ...rawSymbols,
13348
13464
  symbols: convertToDebugSymbols(rawSymbols.symbols)
13349
13465
  };
13350
13466
  }
@@ -13494,8 +13610,8 @@ class FFIRenderLib {
13494
13610
  opentui;
13495
13611
  encoder = new TextEncoder;
13496
13612
  decoder = new TextDecoder;
13497
- logCallbackWrapper;
13498
- eventCallbackWrapper;
13613
+ logCallbackWrapper = null;
13614
+ eventCallbackWrapper = null;
13499
13615
  _nativeEvents = new EventEmitter4;
13500
13616
  _anyEventHandlers = [];
13501
13617
  nativeSpanFeedCallbackWrapper = null;
@@ -13509,13 +13625,13 @@ class FFIRenderLib {
13509
13625
  if (this.logCallbackWrapper) {
13510
13626
  return;
13511
13627
  }
13512
- const logCallback = new JSCallback((level, msgPtr, msgLenBigInt) => {
13628
+ const logCallback = this.opentui.createCallback((level, msgPtr, msgLenBigInt) => {
13513
13629
  try {
13514
13630
  const msgLen = typeof msgLenBigInt === "bigint" ? Number(msgLenBigInt) : msgLenBigInt;
13515
13631
  if (msgLen === 0 || !msgPtr) {
13516
13632
  return;
13517
13633
  }
13518
- const msgBuffer = toArrayBuffer5(msgPtr, 0, msgLen);
13634
+ const msgBuffer = toArrayBuffer(msgPtr, 0, msgLen);
13519
13635
  const msgBytes = new Uint8Array(msgBuffer);
13520
13636
  const message = this.decoder.decode(msgBytes);
13521
13637
  switch (level) {
@@ -13554,19 +13670,19 @@ class FFIRenderLib {
13554
13670
  if (this.eventCallbackWrapper) {
13555
13671
  return;
13556
13672
  }
13557
- const eventCallback = new JSCallback((namePtr, nameLenBigInt, dataPtr, dataLenBigInt) => {
13673
+ const eventCallback = this.opentui.createCallback((namePtr, nameLenBigInt, dataPtr, dataLenBigInt) => {
13558
13674
  try {
13559
13675
  const nameLen = typeof nameLenBigInt === "bigint" ? Number(nameLenBigInt) : nameLenBigInt;
13560
13676
  const dataLen = typeof dataLenBigInt === "bigint" ? Number(dataLenBigInt) : dataLenBigInt;
13561
13677
  if (nameLen === 0 || !namePtr) {
13562
13678
  return;
13563
13679
  }
13564
- const nameBuffer = toArrayBuffer5(namePtr, 0, nameLen);
13680
+ const nameBuffer = toArrayBuffer(namePtr, 0, nameLen);
13565
13681
  const nameBytes = new Uint8Array(nameBuffer);
13566
13682
  const eventName = this.decoder.decode(nameBytes);
13567
13683
  let eventData;
13568
13684
  if (dataLen > 0 && dataPtr) {
13569
- eventData = toArrayBuffer5(dataPtr, 0, dataLen).slice();
13685
+ eventData = toArrayBuffer(dataPtr, 0, dataLen).slice();
13570
13686
  } else {
13571
13687
  eventData = new ArrayBuffer(0);
13572
13688
  }
@@ -13593,8 +13709,8 @@ class FFIRenderLib {
13593
13709
  if (this.nativeSpanFeedCallbackWrapper) {
13594
13710
  return this.nativeSpanFeedCallbackWrapper;
13595
13711
  }
13596
- const callback = new JSCallback((streamPtr, eventId, arg0, arg1) => {
13597
- const handler = this.nativeSpanFeedHandlers.get(toPointer2(streamPtr));
13712
+ const callback = this.opentui.createCallback((streamPtr, eventId, arg0, arg1) => {
13713
+ const handler = this.nativeSpanFeedHandlers.get(streamPtr);
13598
13714
  if (handler) {
13599
13715
  handler(eventId, arg0, arg1);
13600
13716
  }
@@ -13614,7 +13730,7 @@ class FFIRenderLib {
13614
13730
  createRenderer(width, height, options = {}) {
13615
13731
  const testing = options.testing ?? false;
13616
13732
  const remote = options.remote ?? false;
13617
- return this.opentui.symbols.createRenderer(width, height, testing, remote);
13733
+ return this.opentui.symbols.createRenderer(width, height, ffiBool(testing), ffiBool(remote));
13618
13734
  }
13619
13735
  setTerminalEnvVar(renderer, key, value) {
13620
13736
  const keyBytes = this.encoder.encode(key);
@@ -13625,10 +13741,10 @@ class FFIRenderLib {
13625
13741
  this.opentui.symbols.destroyRenderer(renderer);
13626
13742
  }
13627
13743
  setUseThread(renderer, useThread) {
13628
- this.opentui.symbols.setUseThread(renderer, useThread);
13744
+ this.opentui.symbols.setUseThread(renderer, ffiBool(useThread));
13629
13745
  }
13630
13746
  setClearOnShutdown(renderer, clear) {
13631
- this.opentui.symbols.setClearOnShutdown(renderer, clear);
13747
+ this.opentui.symbols.setClearOnShutdown(renderer, ffiBool(clear));
13632
13748
  }
13633
13749
  setBackgroundColor(renderer, color) {
13634
13750
  this.opentui.symbols.setBackgroundColor(renderer, rgbaPtr(color));
@@ -13677,41 +13793,41 @@ class FFIRenderLib {
13677
13793
  for (let index = 0;index < palette.length; index++) {
13678
13794
  paletteBuffer.set(palette[index].buffer, index * 4);
13679
13795
  }
13680
- this.opentui.symbols.rendererSetPaletteState(renderer, ptr5(paletteBuffer), palette.length, rgbaPtr(defaultForeground), rgbaPtr(defaultBackground), paletteEpoch >>> 0);
13796
+ this.opentui.symbols.rendererSetPaletteState(renderer, ptr(paletteBuffer), palette.length, rgbaPtr(defaultForeground), rgbaPtr(defaultBackground), paletteEpoch >>> 0);
13681
13797
  }
13682
13798
  bufferGetCharPtr(buffer) {
13683
- const ptr6 = this.opentui.symbols.bufferGetCharPtr(buffer);
13684
- if (!ptr6) {
13799
+ const ptr3 = this.opentui.symbols.bufferGetCharPtr(buffer);
13800
+ if (!ptr3) {
13685
13801
  throw new Error("Failed to get char pointer");
13686
13802
  }
13687
- return ptr6;
13803
+ return ptr3;
13688
13804
  }
13689
13805
  bufferGetFgPtr(buffer) {
13690
- const ptr6 = this.opentui.symbols.bufferGetFgPtr(buffer);
13691
- if (!ptr6) {
13806
+ const ptr3 = this.opentui.symbols.bufferGetFgPtr(buffer);
13807
+ if (!ptr3) {
13692
13808
  throw new Error("Failed to get fg pointer");
13693
13809
  }
13694
- return ptr6;
13810
+ return ptr3;
13695
13811
  }
13696
13812
  bufferGetBgPtr(buffer) {
13697
- const ptr6 = this.opentui.symbols.bufferGetBgPtr(buffer);
13698
- if (!ptr6) {
13813
+ const ptr3 = this.opentui.symbols.bufferGetBgPtr(buffer);
13814
+ if (!ptr3) {
13699
13815
  throw new Error("Failed to get bg pointer");
13700
13816
  }
13701
- return ptr6;
13817
+ return ptr3;
13702
13818
  }
13703
13819
  bufferGetAttributesPtr(buffer) {
13704
- const ptr6 = this.opentui.symbols.bufferGetAttributesPtr(buffer);
13705
- if (!ptr6) {
13820
+ const ptr3 = this.opentui.symbols.bufferGetAttributesPtr(buffer);
13821
+ if (!ptr3) {
13706
13822
  throw new Error("Failed to get attributes pointer");
13707
13823
  }
13708
- return ptr6;
13824
+ return ptr3;
13709
13825
  }
13710
13826
  bufferGetRespectAlpha(buffer) {
13711
13827
  return this.opentui.symbols.bufferGetRespectAlpha(buffer);
13712
13828
  }
13713
13829
  bufferSetRespectAlpha(buffer, respectAlpha) {
13714
- this.opentui.symbols.bufferSetRespectAlpha(buffer, respectAlpha);
13830
+ this.opentui.symbols.bufferSetRespectAlpha(buffer, ffiBool(respectAlpha));
13715
13831
  }
13716
13832
  bufferGetId(buffer) {
13717
13833
  const maxLen = 256;
@@ -13724,7 +13840,7 @@ class FFIRenderLib {
13724
13840
  return this.opentui.symbols.bufferGetRealCharSize(buffer);
13725
13841
  }
13726
13842
  bufferWriteResolvedChars(buffer, outputBuffer, addLineBreaks) {
13727
- const bytesWritten = this.opentui.symbols.bufferWriteResolvedChars(buffer, outputBuffer, outputBuffer.length, addLineBreaks);
13843
+ const bytesWritten = this.opentui.symbols.bufferWriteResolvedChars(buffer, outputBuffer, outputBuffer.length, ffiBool(addLineBreaks));
13728
13844
  return typeof bytesWritten === "bigint" ? Number(bytesWritten) : bytesWritten;
13729
13845
  }
13730
13846
  getBufferWidth(buffer) {
@@ -13783,7 +13899,7 @@ class FFIRenderLib {
13783
13899
  drawInner: options.drawInner,
13784
13900
  drawOuter: options.drawOuter
13785
13901
  });
13786
- this.opentui.symbols.bufferDrawGrid(buffer, borderChars, rgbaPtr(borderFg), rgbaPtr(borderBg), columnOffsets, columnCount, rowOffsets, rowCount, ptr5(optionsBuffer));
13902
+ this.opentui.symbols.bufferDrawGrid(buffer, borderChars, rgbaPtr(borderFg), rgbaPtr(borderBg), columnOffsets, columnCount, rowOffsets, rowCount, ptr(optionsBuffer));
13787
13903
  }
13788
13904
  bufferDrawBox(buffer, x, y, width, height, borderChars, packedOptions, borderColor, backgroundColor, title, bottomTitle) {
13789
13905
  const titleBytes = title ? this.encoder.encode(title) : null;
@@ -13816,14 +13932,14 @@ class FFIRenderLib {
13816
13932
  this.opentui.symbols.resizeRenderer(renderer, width, height);
13817
13933
  }
13818
13934
  setCursorPosition(renderer, x, y, visible) {
13819
- this.opentui.symbols.setCursorPosition(renderer, x, y, visible);
13935
+ this.opentui.symbols.setCursorPosition(renderer, x, y, ffiBool(visible));
13820
13936
  }
13821
13937
  setCursorColor(renderer, color) {
13822
13938
  this.opentui.symbols.setCursorColor(renderer, rgbaPtr(color));
13823
13939
  }
13824
13940
  getCursorState(renderer) {
13825
13941
  const cursorBuffer = new ArrayBuffer(CursorStateStruct.size);
13826
- this.opentui.symbols.getCursorState(renderer, ptr5(cursorBuffer));
13942
+ this.opentui.symbols.getCursorState(renderer, ptr(cursorBuffer));
13827
13943
  const struct = CursorStateStruct.unpack(cursorBuffer);
13828
13944
  return {
13829
13945
  x: struct.x,
@@ -13839,16 +13955,16 @@ class FFIRenderLib {
13839
13955
  const blinking = options.blinking != null ? options.blinking ? 1 : 0 : 255;
13840
13956
  const cursor = options.cursor != null ? MOUSE_STYLE_TO_ID[options.cursor] : 255;
13841
13957
  const buffer = CursorStyleOptionsStruct.pack({ style, blinking, color: options.color, cursor });
13842
- this.opentui.symbols.setCursorStyleOptions(renderer, ptr5(buffer));
13958
+ this.opentui.symbols.setCursorStyleOptions(renderer, ptr(buffer));
13843
13959
  }
13844
13960
  render(renderer, force) {
13845
- this.opentui.symbols.render(renderer, force);
13961
+ this.opentui.symbols.render(renderer, ffiBool(force));
13846
13962
  }
13847
13963
  repaintSplitFooter(renderer, pinnedRenderOffset, force) {
13848
- return this.opentui.symbols.repaintSplitFooter(renderer, pinnedRenderOffset, force);
13964
+ return this.opentui.symbols.repaintSplitFooter(renderer, pinnedRenderOffset, ffiBool(force));
13849
13965
  }
13850
13966
  commitSplitFooterSnapshot(renderer, snapshot, rowColumns, startOnNewLine, trailingNewline, pinnedRenderOffset, force, beginFrame = true, finalizeFrame = true) {
13851
- return this.opentui.symbols.commitSplitFooterSnapshot(renderer, snapshot.ptr, rowColumns, startOnNewLine, trailingNewline, pinnedRenderOffset, force, beginFrame, finalizeFrame);
13967
+ return this.opentui.symbols.commitSplitFooterSnapshot(renderer, snapshot.ptr, rowColumns, ffiBool(startOnNewLine), ffiBool(trailingNewline), pinnedRenderOffset, ffiBool(force), ffiBool(beginFrame), ffiBool(finalizeFrame));
13852
13968
  }
13853
13969
  createOptimizedBuffer(width, height, widthMethod, respectAlpha = false, id) {
13854
13970
  if (Number.isNaN(width) || Number.isNaN(height)) {
@@ -13857,7 +13973,7 @@ class FFIRenderLib {
13857
13973
  const widthMethodCode = widthMethod === "wcwidth" ? 0 : 1;
13858
13974
  const idToUse = id || "unnamed buffer";
13859
13975
  const idBytes = this.encoder.encode(idToUse);
13860
- const bufferPtr = this.opentui.symbols.createOptimizedBuffer(width, height, respectAlpha, widthMethodCode, idBytes, idBytes.length);
13976
+ const bufferPtr = this.opentui.symbols.createOptimizedBuffer(width, height, ffiBool(respectAlpha), widthMethodCode, idBytes, idBytes.length);
13861
13977
  if (!bufferPtr) {
13862
13978
  throw new Error(`Failed to create optimized buffer: ${width}x${height}`);
13863
13979
  }
@@ -13874,7 +13990,7 @@ class FFIRenderLib {
13874
13990
  this.opentui.symbols.drawFrameBuffer(targetBufferPtr, destX, destY, bufferPtr, srcX, srcY, srcWidth, srcHeight);
13875
13991
  }
13876
13992
  setDebugOverlay(renderer, enabled, corner) {
13877
- this.opentui.symbols.setDebugOverlay(renderer, enabled, corner);
13993
+ this.opentui.symbols.setDebugOverlay(renderer, ffiBool(enabled), corner);
13878
13994
  }
13879
13995
  clearTerminal(renderer) {
13880
13996
  this.opentui.symbols.clearTerminal(renderer);
@@ -13928,7 +14044,7 @@ class FFIRenderLib {
13928
14044
  this.opentui.symbols.restoreTerminalModes(renderer);
13929
14045
  }
13930
14046
  enableMouse(renderer, enableMovement) {
13931
- this.opentui.symbols.enableMouse(renderer, enableMovement);
14047
+ this.opentui.symbols.enableMouse(renderer, ffiBool(enableMovement));
13932
14048
  }
13933
14049
  disableMouse(renderer) {
13934
14050
  this.opentui.symbols.disableMouse(renderer);
@@ -13946,7 +14062,7 @@ class FFIRenderLib {
13946
14062
  return this.opentui.symbols.getKittyKeyboardFlags(renderer);
13947
14063
  }
13948
14064
  setupTerminal(renderer, useAlternateScreen) {
13949
- this.opentui.symbols.setupTerminal(renderer, useAlternateScreen);
14065
+ this.opentui.symbols.setupTerminal(renderer, ffiBool(useAlternateScreen));
13950
14066
  }
13951
14067
  suspendRenderer(renderer) {
13952
14068
  this.opentui.symbols.suspendRenderer(renderer);
@@ -13964,7 +14080,7 @@ class FFIRenderLib {
13964
14080
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
13965
14081
  if (bytes.length === 0)
13966
14082
  return;
13967
- this.opentui.symbols.writeOut(renderer, ptr5(bytes), bytes.length);
14083
+ this.opentui.symbols.writeOut(renderer, ptr(bytes), bytes.length);
13968
14084
  }
13969
14085
  createTextBuffer(widthMethod) {
13970
14086
  const widthMethodCode = widthMethod === "wcwidth" ? 0 : 1;
@@ -14011,14 +14127,14 @@ class FFIRenderLib {
14011
14127
  this.opentui.symbols.textBufferSetTabWidth(buffer, width);
14012
14128
  }
14013
14129
  textBufferRegisterMemBuffer(buffer, bytes, owned = false) {
14014
- const result = this.opentui.symbols.textBufferRegisterMemBuffer(buffer, bytes, bytes.length, owned);
14130
+ const result = this.opentui.symbols.textBufferRegisterMemBuffer(buffer, bytes, bytes.length, ffiBool(owned));
14015
14131
  if (result === 65535) {
14016
14132
  throw new Error("Failed to register memory buffer");
14017
14133
  }
14018
14134
  return result;
14019
14135
  }
14020
14136
  textBufferReplaceMemBuffer(buffer, memId, bytes, owned = false) {
14021
- return this.opentui.symbols.textBufferReplaceMemBuffer(buffer, memId, bytes, bytes.length, owned);
14137
+ return this.opentui.symbols.textBufferReplaceMemBuffer(buffer, memId, bytes, bytes.length, ffiBool(owned));
14022
14138
  }
14023
14139
  textBufferClearMemRegistry(buffer) {
14024
14140
  this.opentui.symbols.textBufferClearMemRegistry(buffer);
@@ -14042,7 +14158,7 @@ class FFIRenderLib {
14042
14158
  return;
14043
14159
  }
14044
14160
  const chunksBuffer = StyledChunkStruct.packList(chunks);
14045
- this.opentui.symbols.textBufferSetStyledText(buffer, ptr5(chunksBuffer), chunks.length);
14161
+ this.opentui.symbols.textBufferSetStyledText(buffer, ptr(chunksBuffer), chunks.length);
14046
14162
  }
14047
14163
  textBufferGetLineCount(buffer) {
14048
14164
  return this.opentui.symbols.textBufferGetLineCount(buffer);
@@ -14053,7 +14169,7 @@ class FFIRenderLib {
14053
14169
  }
14054
14170
  getPlainTextBytes(buffer, maxLength) {
14055
14171
  const outBuffer = new Uint8Array(maxLength);
14056
- const actualLen = this.textBufferGetPlainText(buffer, ptr5(outBuffer), maxLength);
14172
+ const actualLen = this.textBufferGetPlainText(buffer, ptr(outBuffer), maxLength);
14057
14173
  if (actualLen === 0) {
14058
14174
  return null;
14059
14175
  }
@@ -14061,7 +14177,7 @@ class FFIRenderLib {
14061
14177
  }
14062
14178
  textBufferGetTextRange(buffer, startOffset, endOffset, maxLength) {
14063
14179
  const outBuffer = new Uint8Array(maxLength);
14064
- const actualLen = this.opentui.symbols.textBufferGetTextRange(buffer, startOffset, endOffset, ptr5(outBuffer), maxLength);
14180
+ const actualLen = this.opentui.symbols.textBufferGetTextRange(buffer, startOffset, endOffset, ptr(outBuffer), maxLength);
14065
14181
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14066
14182
  if (len === 0) {
14067
14183
  return null;
@@ -14070,7 +14186,7 @@ class FFIRenderLib {
14070
14186
  }
14071
14187
  textBufferGetTextRangeByCoords(buffer, startRow, startCol, endRow, endCol, maxLength) {
14072
14188
  const outBuffer = new Uint8Array(maxLength);
14073
- const actualLen = this.opentui.symbols.textBufferGetTextRangeByCoords(buffer, startRow, startCol, endRow, endCol, ptr5(outBuffer), maxLength);
14189
+ const actualLen = this.opentui.symbols.textBufferGetTextRangeByCoords(buffer, startRow, startCol, endRow, endCol, ptr(outBuffer), maxLength);
14074
14190
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14075
14191
  if (len === 0) {
14076
14192
  return null;
@@ -14143,7 +14259,7 @@ class FFIRenderLib {
14143
14259
  }
14144
14260
  textBufferViewGetLineInfo(view) {
14145
14261
  const outBuffer = new ArrayBuffer(LineInfoStruct.size);
14146
- this.textBufferViewGetLineInfoDirect(view, ptr5(outBuffer));
14262
+ this.textBufferViewGetLineInfoDirect(view, ptr(outBuffer));
14147
14263
  const struct = LineInfoStruct.unpack(outBuffer);
14148
14264
  const lineStartCols = struct.startCols;
14149
14265
  const lineWidthCols = struct.widthCols;
@@ -14158,7 +14274,7 @@ class FFIRenderLib {
14158
14274
  }
14159
14275
  textBufferViewGetLogicalLineInfo(view) {
14160
14276
  const outBuffer = new ArrayBuffer(LineInfoStruct.size);
14161
- this.textBufferViewGetLogicalLineInfoDirect(view, ptr5(outBuffer));
14277
+ this.textBufferViewGetLogicalLineInfoDirect(view, ptr(outBuffer));
14162
14278
  const struct = LineInfoStruct.unpack(outBuffer);
14163
14279
  const lineStartCols = struct.startCols;
14164
14280
  const lineWidthCols = struct.widthCols;
@@ -14190,7 +14306,7 @@ class FFIRenderLib {
14190
14306
  }
14191
14307
  textBufferViewGetSelectedTextBytes(view, maxLength) {
14192
14308
  const outBuffer = new Uint8Array(maxLength);
14193
- const actualLen = this.textBufferViewGetSelectedText(view, ptr5(outBuffer), maxLength);
14309
+ const actualLen = this.textBufferViewGetSelectedText(view, ptr(outBuffer), maxLength);
14194
14310
  if (actualLen === 0) {
14195
14311
  return null;
14196
14312
  }
@@ -14198,7 +14314,7 @@ class FFIRenderLib {
14198
14314
  }
14199
14315
  textBufferViewGetPlainTextBytes(view, maxLength) {
14200
14316
  const outBuffer = new Uint8Array(maxLength);
14201
- const actualLen = this.textBufferViewGetPlainText(view, ptr5(outBuffer), maxLength);
14317
+ const actualLen = this.textBufferViewGetPlainText(view, ptr(outBuffer), maxLength);
14202
14318
  if (actualLen === 0) {
14203
14319
  return null;
14204
14320
  }
@@ -14211,11 +14327,11 @@ class FFIRenderLib {
14211
14327
  this.opentui.symbols.textBufferViewSetTabIndicatorColor(view, rgbaPtr(color));
14212
14328
  }
14213
14329
  textBufferViewSetTruncate(view, truncate) {
14214
- this.opentui.symbols.textBufferViewSetTruncate(view, truncate);
14330
+ this.opentui.symbols.textBufferViewSetTruncate(view, ffiBool(truncate));
14215
14331
  }
14216
14332
  textBufferViewMeasureForDimensions(view, width, height) {
14217
14333
  const resultBuffer = new ArrayBuffer(MeasureResultStruct.size);
14218
- const resultPtr = ptr5(new Uint8Array(resultBuffer));
14334
+ const resultPtr = ptr(new Uint8Array(resultBuffer));
14219
14335
  const success = this.opentui.symbols.textBufferViewMeasureForDimensions(view, width, height, resultPtr);
14220
14336
  if (!success) {
14221
14337
  return null;
@@ -14225,11 +14341,11 @@ class FFIRenderLib {
14225
14341
  }
14226
14342
  textBufferAddHighlightByCharRange(buffer, highlight) {
14227
14343
  const packedHighlight = HighlightStruct.pack(highlight);
14228
- this.opentui.symbols.textBufferAddHighlightByCharRange(buffer, ptr5(packedHighlight));
14344
+ this.opentui.symbols.textBufferAddHighlightByCharRange(buffer, ptr(packedHighlight));
14229
14345
  }
14230
14346
  textBufferAddHighlight(buffer, lineIdx, highlight) {
14231
14347
  const packedHighlight = HighlightStruct.pack(highlight);
14232
- this.opentui.symbols.textBufferAddHighlight(buffer, lineIdx, ptr5(packedHighlight));
14348
+ this.opentui.symbols.textBufferAddHighlight(buffer, lineIdx, ptr(packedHighlight));
14233
14349
  }
14234
14350
  textBufferRemoveHighlightsByRef(buffer, hlRef) {
14235
14351
  this.opentui.symbols.textBufferRemoveHighlightsByRef(buffer, hlRef);
@@ -14245,12 +14361,12 @@ class FFIRenderLib {
14245
14361
  }
14246
14362
  textBufferGetLineHighlights(buffer, lineIdx) {
14247
14363
  const outCountBuf = new BigUint64Array(1);
14248
- const nativePtr = this.opentui.symbols.textBufferGetLineHighlightsPtr(buffer, lineIdx, ptr5(outCountBuf));
14364
+ const nativePtr = this.opentui.symbols.textBufferGetLineHighlightsPtr(buffer, lineIdx, ptr(outCountBuf));
14249
14365
  if (!nativePtr)
14250
14366
  return [];
14251
14367
  const count = Number(outCountBuf[0]);
14252
14368
  const byteLen = count * HighlightStruct.size;
14253
- const raw = toArrayBuffer5(nativePtr, 0, byteLen);
14369
+ const raw = toArrayBuffer(nativePtr, 0, byteLen);
14254
14370
  const results = HighlightStruct.unpackList(raw, count);
14255
14371
  this.opentui.symbols.textBufferFreeLineHighlights(nativePtr, count);
14256
14372
  return results;
@@ -14264,7 +14380,7 @@ class FFIRenderLib {
14264
14380
  }
14265
14381
  getBuildOptions() {
14266
14382
  const optionsBuffer = new ArrayBuffer(BuildOptionsStruct.size);
14267
- this.opentui.symbols.getBuildOptions(ptr5(optionsBuffer));
14383
+ this.opentui.symbols.getBuildOptions(ptr(optionsBuffer));
14268
14384
  const options = BuildOptionsStruct.unpack(optionsBuffer);
14269
14385
  return {
14270
14386
  gpaSafeStats: !!options.gpaSafeStats,
@@ -14273,7 +14389,7 @@ class FFIRenderLib {
14273
14389
  }
14274
14390
  getAllocatorStats() {
14275
14391
  const statsBuffer = new ArrayBuffer(AllocatorStatsStruct.size);
14276
- this.opentui.symbols.getAllocatorStats(ptr5(statsBuffer));
14392
+ this.opentui.symbols.getAllocatorStats(ptr(statsBuffer));
14277
14393
  const stats = AllocatorStatsStruct.unpack(statsBuffer);
14278
14394
  return {
14279
14395
  totalRequestedBytes: toNumber(stats.totalRequestedBytes),
@@ -14303,14 +14419,14 @@ class FFIRenderLib {
14303
14419
  this.opentui.symbols.editorViewSetViewportSize(view, width, height);
14304
14420
  }
14305
14421
  editorViewSetViewport(view, x, y, width, height, moveCursor) {
14306
- this.opentui.symbols.editorViewSetViewport(view, x, y, width, height, moveCursor);
14422
+ this.opentui.symbols.editorViewSetViewport(view, x, y, width, height, ffiBool(moveCursor));
14307
14423
  }
14308
14424
  editorViewGetViewport(view) {
14309
14425
  const x = new Uint32Array(1);
14310
14426
  const y = new Uint32Array(1);
14311
14427
  const width = new Uint32Array(1);
14312
14428
  const height = new Uint32Array(1);
14313
- this.opentui.symbols.editorViewGetViewport(view, ptr5(x), ptr5(y), ptr5(width), ptr5(height));
14429
+ this.opentui.symbols.editorViewGetViewport(view, ptr(x), ptr(y), ptr(width), ptr(height));
14314
14430
  return {
14315
14431
  offsetX: x[0],
14316
14432
  offsetY: y[0],
@@ -14340,7 +14456,7 @@ class FFIRenderLib {
14340
14456
  }
14341
14457
  editorViewGetLineInfo(view) {
14342
14458
  const outBuffer = new ArrayBuffer(LineInfoStruct.size);
14343
- this.opentui.symbols.editorViewGetLineInfoDirect(view, ptr5(outBuffer));
14459
+ this.opentui.symbols.editorViewGetLineInfoDirect(view, ptr(outBuffer));
14344
14460
  const struct = LineInfoStruct.unpack(outBuffer);
14345
14461
  const lineStartCols = struct.startCols;
14346
14462
  const lineWidthCols = struct.widthCols;
@@ -14355,7 +14471,7 @@ class FFIRenderLib {
14355
14471
  }
14356
14472
  editorViewGetLogicalLineInfo(view) {
14357
14473
  const outBuffer = new ArrayBuffer(LineInfoStruct.size);
14358
- this.opentui.symbols.editorViewGetLogicalLineInfoDirect(view, ptr5(outBuffer));
14474
+ this.opentui.symbols.editorViewGetLogicalLineInfoDirect(view, ptr(outBuffer));
14359
14475
  const struct = LineInfoStruct.unpack(outBuffer);
14360
14476
  const lineStartCols = struct.startCols;
14361
14477
  const lineWidthCols = struct.widthCols;
@@ -14393,7 +14509,7 @@ class FFIRenderLib {
14393
14509
  }
14394
14510
  editBufferGetText(buffer, maxLength) {
14395
14511
  const outBuffer = new Uint8Array(maxLength);
14396
- const actualLen = this.opentui.symbols.editBufferGetText(buffer, ptr5(outBuffer), maxLength);
14512
+ const actualLen = this.opentui.symbols.editBufferGetText(buffer, ptr(outBuffer), maxLength);
14397
14513
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14398
14514
  if (len === 0)
14399
14515
  return null;
@@ -14448,7 +14564,7 @@ class FFIRenderLib {
14448
14564
  }
14449
14565
  editBufferGetCursorPosition(buffer) {
14450
14566
  const cursorBuffer = new ArrayBuffer(LogicalCursorStruct.size);
14451
- this.opentui.symbols.editBufferGetCursorPosition(buffer, ptr5(cursorBuffer));
14567
+ this.opentui.symbols.editBufferGetCursorPosition(buffer, ptr(cursorBuffer));
14452
14568
  return LogicalCursorStruct.unpack(cursorBuffer);
14453
14569
  }
14454
14570
  editBufferGetId(buffer) {
@@ -14466,7 +14582,7 @@ class FFIRenderLib {
14466
14582
  }
14467
14583
  editBufferUndo(buffer, maxLength) {
14468
14584
  const outBuffer = new Uint8Array(maxLength);
14469
- const actualLen = this.opentui.symbols.editBufferUndo(buffer, ptr5(outBuffer), maxLength);
14585
+ const actualLen = this.opentui.symbols.editBufferUndo(buffer, ptr(outBuffer), maxLength);
14470
14586
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14471
14587
  if (len === 0)
14472
14588
  return null;
@@ -14474,7 +14590,7 @@ class FFIRenderLib {
14474
14590
  }
14475
14591
  editBufferRedo(buffer, maxLength) {
14476
14592
  const outBuffer = new Uint8Array(maxLength);
14477
- const actualLen = this.opentui.symbols.editBufferRedo(buffer, ptr5(outBuffer), maxLength);
14593
+ const actualLen = this.opentui.symbols.editBufferRedo(buffer, ptr(outBuffer), maxLength);
14478
14594
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14479
14595
  if (len === 0)
14480
14596
  return null;
@@ -14494,22 +14610,22 @@ class FFIRenderLib {
14494
14610
  }
14495
14611
  editBufferGetNextWordBoundary(buffer) {
14496
14612
  const cursorBuffer = new ArrayBuffer(LogicalCursorStruct.size);
14497
- this.opentui.symbols.editBufferGetNextWordBoundary(buffer, ptr5(cursorBuffer));
14613
+ this.opentui.symbols.editBufferGetNextWordBoundary(buffer, ptr(cursorBuffer));
14498
14614
  return LogicalCursorStruct.unpack(cursorBuffer);
14499
14615
  }
14500
14616
  editBufferGetPrevWordBoundary(buffer) {
14501
14617
  const cursorBuffer = new ArrayBuffer(LogicalCursorStruct.size);
14502
- this.opentui.symbols.editBufferGetPrevWordBoundary(buffer, ptr5(cursorBuffer));
14618
+ this.opentui.symbols.editBufferGetPrevWordBoundary(buffer, ptr(cursorBuffer));
14503
14619
  return LogicalCursorStruct.unpack(cursorBuffer);
14504
14620
  }
14505
14621
  editBufferGetEOL(buffer) {
14506
14622
  const cursorBuffer = new ArrayBuffer(LogicalCursorStruct.size);
14507
- this.opentui.symbols.editBufferGetEOL(buffer, ptr5(cursorBuffer));
14623
+ this.opentui.symbols.editBufferGetEOL(buffer, ptr(cursorBuffer));
14508
14624
  return LogicalCursorStruct.unpack(cursorBuffer);
14509
14625
  }
14510
14626
  editBufferOffsetToPosition(buffer, offset) {
14511
14627
  const cursorBuffer = new ArrayBuffer(LogicalCursorStruct.size);
14512
- const success = this.opentui.symbols.editBufferOffsetToPosition(buffer, offset, ptr5(cursorBuffer));
14628
+ const success = this.opentui.symbols.editBufferOffsetToPosition(buffer, offset, ptr(cursorBuffer));
14513
14629
  if (!success)
14514
14630
  return null;
14515
14631
  return LogicalCursorStruct.unpack(cursorBuffer);
@@ -14522,7 +14638,7 @@ class FFIRenderLib {
14522
14638
  }
14523
14639
  editBufferGetTextRange(buffer, startOffset, endOffset, maxLength) {
14524
14640
  const outBuffer = new Uint8Array(maxLength);
14525
- const actualLen = this.opentui.symbols.editBufferGetTextRange(buffer, startOffset, endOffset, ptr5(outBuffer), maxLength);
14641
+ const actualLen = this.opentui.symbols.editBufferGetTextRange(buffer, startOffset, endOffset, ptr(outBuffer), maxLength);
14526
14642
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14527
14643
  if (len === 0)
14528
14644
  return null;
@@ -14530,7 +14646,7 @@ class FFIRenderLib {
14530
14646
  }
14531
14647
  editBufferGetTextRangeByCoords(buffer, startRow, startCol, endRow, endCol, maxLength) {
14532
14648
  const outBuffer = new Uint8Array(maxLength);
14533
- const actualLen = this.opentui.symbols.editBufferGetTextRangeByCoords(buffer, startRow, startCol, endRow, endCol, ptr5(outBuffer), maxLength);
14649
+ const actualLen = this.opentui.symbols.editBufferGetTextRangeByCoords(buffer, startRow, startCol, endRow, endCol, ptr(outBuffer), maxLength);
14534
14650
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14535
14651
  if (len === 0)
14536
14652
  return null;
@@ -14556,7 +14672,7 @@ class FFIRenderLib {
14556
14672
  editorViewSetLocalSelection(view, anchorX, anchorY, focusX, focusY, bgColor, fgColor, updateCursor, followCursor) {
14557
14673
  const bg2 = optionalRgbaPtr(bgColor);
14558
14674
  const fg2 = optionalRgbaPtr(fgColor);
14559
- return this.opentui.symbols.editorViewSetLocalSelection(view, anchorX, anchorY, focusX, focusY, bg2, fg2, updateCursor, followCursor);
14675
+ return this.opentui.symbols.editorViewSetLocalSelection(view, anchorX, anchorY, focusX, focusY, bg2, fg2, ffiBool(updateCursor), ffiBool(followCursor));
14560
14676
  }
14561
14677
  editorViewUpdateSelection(view, end, bgColor, fgColor) {
14562
14678
  const bg2 = optionalRgbaPtr(bgColor);
@@ -14566,14 +14682,14 @@ class FFIRenderLib {
14566
14682
  editorViewUpdateLocalSelection(view, anchorX, anchorY, focusX, focusY, bgColor, fgColor, updateCursor, followCursor) {
14567
14683
  const bg2 = optionalRgbaPtr(bgColor);
14568
14684
  const fg2 = optionalRgbaPtr(fgColor);
14569
- return this.opentui.symbols.editorViewUpdateLocalSelection(view, anchorX, anchorY, focusX, focusY, bg2, fg2, updateCursor, followCursor);
14685
+ return this.opentui.symbols.editorViewUpdateLocalSelection(view, anchorX, anchorY, focusX, focusY, bg2, fg2, ffiBool(updateCursor), ffiBool(followCursor));
14570
14686
  }
14571
14687
  editorViewResetLocalSelection(view) {
14572
14688
  this.opentui.symbols.editorViewResetLocalSelection(view);
14573
14689
  }
14574
14690
  editorViewGetSelectedTextBytes(view, maxLength) {
14575
14691
  const outBuffer = new Uint8Array(maxLength);
14576
- const actualLen = this.opentui.symbols.editorViewGetSelectedTextBytes(view, ptr5(outBuffer), maxLength);
14692
+ const actualLen = this.opentui.symbols.editorViewGetSelectedTextBytes(view, ptr(outBuffer), maxLength);
14577
14693
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14578
14694
  if (len === 0)
14579
14695
  return null;
@@ -14582,12 +14698,12 @@ class FFIRenderLib {
14582
14698
  editorViewGetCursor(view) {
14583
14699
  const row = new Uint32Array(1);
14584
14700
  const col = new Uint32Array(1);
14585
- this.opentui.symbols.editorViewGetCursor(view, ptr5(row), ptr5(col));
14701
+ this.opentui.symbols.editorViewGetCursor(view, ptr(row), ptr(col));
14586
14702
  return { row: row[0], col: col[0] };
14587
14703
  }
14588
14704
  editorViewGetText(view, maxLength) {
14589
14705
  const outBuffer = new Uint8Array(maxLength);
14590
- const actualLen = this.opentui.symbols.editorViewGetText(view, ptr5(outBuffer), maxLength);
14706
+ const actualLen = this.opentui.symbols.editorViewGetText(view, ptr(outBuffer), maxLength);
14591
14707
  const len = typeof actualLen === "bigint" ? Number(actualLen) : actualLen;
14592
14708
  if (len === 0)
14593
14709
  return null;
@@ -14595,7 +14711,7 @@ class FFIRenderLib {
14595
14711
  }
14596
14712
  editorViewGetVisualCursor(view) {
14597
14713
  const cursorBuffer = new ArrayBuffer(VisualCursorStruct.size);
14598
- this.opentui.symbols.editorViewGetVisualCursor(view, ptr5(cursorBuffer));
14714
+ this.opentui.symbols.editorViewGetVisualCursor(view, ptr(cursorBuffer));
14599
14715
  return VisualCursorStruct.unpack(cursorBuffer);
14600
14716
  }
14601
14717
  editorViewMoveUpVisual(view) {
@@ -14612,27 +14728,27 @@ class FFIRenderLib {
14612
14728
  }
14613
14729
  editorViewGetNextWordBoundary(view) {
14614
14730
  const cursorBuffer = new ArrayBuffer(VisualCursorStruct.size);
14615
- this.opentui.symbols.editorViewGetNextWordBoundary(view, ptr5(cursorBuffer));
14731
+ this.opentui.symbols.editorViewGetNextWordBoundary(view, ptr(cursorBuffer));
14616
14732
  return VisualCursorStruct.unpack(cursorBuffer);
14617
14733
  }
14618
14734
  editorViewGetPrevWordBoundary(view) {
14619
14735
  const cursorBuffer = new ArrayBuffer(VisualCursorStruct.size);
14620
- this.opentui.symbols.editorViewGetPrevWordBoundary(view, ptr5(cursorBuffer));
14736
+ this.opentui.symbols.editorViewGetPrevWordBoundary(view, ptr(cursorBuffer));
14621
14737
  return VisualCursorStruct.unpack(cursorBuffer);
14622
14738
  }
14623
14739
  editorViewGetEOL(view) {
14624
14740
  const cursorBuffer = new ArrayBuffer(VisualCursorStruct.size);
14625
- this.opentui.symbols.editorViewGetEOL(view, ptr5(cursorBuffer));
14741
+ this.opentui.symbols.editorViewGetEOL(view, ptr(cursorBuffer));
14626
14742
  return VisualCursorStruct.unpack(cursorBuffer);
14627
14743
  }
14628
14744
  editorViewGetVisualSOL(view) {
14629
14745
  const cursorBuffer = new ArrayBuffer(VisualCursorStruct.size);
14630
- this.opentui.symbols.editorViewGetVisualSOL(view, ptr5(cursorBuffer));
14746
+ this.opentui.symbols.editorViewGetVisualSOL(view, ptr(cursorBuffer));
14631
14747
  return VisualCursorStruct.unpack(cursorBuffer);
14632
14748
  }
14633
14749
  editorViewGetVisualEOL(view) {
14634
14750
  const cursorBuffer = new ArrayBuffer(VisualCursorStruct.size);
14635
- this.opentui.symbols.editorViewGetVisualEOL(view, ptr5(cursorBuffer));
14751
+ this.opentui.symbols.editorViewGetVisualEOL(view, ptr(cursorBuffer));
14636
14752
  return VisualCursorStruct.unpack(cursorBuffer);
14637
14753
  }
14638
14754
  bufferPushScissorRect(buffer, x, y, width, height) {
@@ -14658,7 +14774,7 @@ class FFIRenderLib {
14658
14774
  }
14659
14775
  getTerminalCapabilities(renderer) {
14660
14776
  const capsBuffer = new ArrayBuffer(TerminalCapabilitiesStruct.size);
14661
- this.opentui.symbols.getTerminalCapabilities(renderer, ptr5(capsBuffer));
14777
+ this.opentui.symbols.getTerminalCapabilities(renderer, ptr(capsBuffer));
14662
14778
  const caps = TerminalCapabilitiesStruct.unpack(capsBuffer);
14663
14779
  return {
14664
14780
  kitty_keyboard: caps.kitty_keyboard,
@@ -14677,6 +14793,7 @@ class FFIRenderLib {
14677
14793
  hyperlinks: caps.hyperlinks,
14678
14794
  osc52: caps.osc52,
14679
14795
  explicit_cursor_positioning: caps.explicit_cursor_positioning,
14796
+ in_tmux: caps.in_tmux,
14680
14797
  terminal: {
14681
14798
  name: caps.term_name ?? "",
14682
14799
  version: caps.term_version ?? "",
@@ -14693,7 +14810,7 @@ class FFIRenderLib {
14693
14810
  const widthMethodCode = widthMethod === "wcwidth" ? 0 : 1;
14694
14811
  const outPtrBuffer = new ArrayBuffer(8);
14695
14812
  const outLenBuffer = new ArrayBuffer(8);
14696
- const success = this.opentui.symbols.encodeUnicode(textBytes, textBytes.length, ptr5(outPtrBuffer), ptr5(outLenBuffer), widthMethodCode);
14813
+ const success = this.opentui.symbols.encodeUnicode(textBytes, textBytes.length, ptr(outPtrBuffer), ptr(outLenBuffer), widthMethodCode);
14697
14814
  if (!success) {
14698
14815
  return null;
14699
14816
  }
@@ -14705,7 +14822,7 @@ class FFIRenderLib {
14705
14822
  return { ptr: resultPtr, data: [] };
14706
14823
  }
14707
14824
  const byteLen = resultLen * EncodedCharStruct.size;
14708
- const raw = toArrayBuffer5(resultPtr, 0, byteLen);
14825
+ const raw = toArrayBuffer(resultPtr, 0, byteLen);
14709
14826
  const data = EncodedCharStruct.unpackList(raw, resultLen);
14710
14827
  return { ptr: resultPtr, data };
14711
14828
  }
@@ -14717,37 +14834,37 @@ class FFIRenderLib {
14717
14834
  }
14718
14835
  registerNativeSpanFeedStream(stream, handler) {
14719
14836
  const callback = this.ensureNativeSpanFeedCallback();
14720
- this.nativeSpanFeedHandlers.set(toPointer2(stream), handler);
14837
+ this.nativeSpanFeedHandlers.set(stream, handler);
14721
14838
  this.opentui.symbols.streamSetCallback(stream, callback.ptr);
14722
14839
  }
14723
14840
  unregisterNativeSpanFeedStream(stream) {
14724
14841
  this.opentui.symbols.streamSetCallback(stream, null);
14725
- this.nativeSpanFeedHandlers.delete(toPointer2(stream));
14842
+ this.nativeSpanFeedHandlers.delete(stream);
14726
14843
  }
14727
14844
  createNativeSpanFeed(options) {
14728
14845
  const optionsBuffer = options == null ? null : NativeSpanFeedOptionsStruct.pack(options);
14729
- const streamPtr = this.opentui.symbols.createNativeSpanFeed(optionsBuffer ? ptr5(optionsBuffer) : null);
14846
+ const streamPtr = this.opentui.symbols.createNativeSpanFeed(optionsBuffer ? ptr(optionsBuffer) : null);
14730
14847
  if (!streamPtr) {
14731
14848
  throw new Error("Failed to create stream");
14732
14849
  }
14733
- return toPointer2(streamPtr);
14850
+ return streamPtr;
14734
14851
  }
14735
14852
  attachNativeSpanFeed(stream) {
14736
14853
  return this.opentui.symbols.attachNativeSpanFeed(stream);
14737
14854
  }
14738
14855
  destroyNativeSpanFeed(stream) {
14739
14856
  this.opentui.symbols.destroyNativeSpanFeed(stream);
14740
- this.nativeSpanFeedHandlers.delete(toPointer2(stream));
14857
+ this.nativeSpanFeedHandlers.delete(stream);
14741
14858
  }
14742
14859
  streamWrite(stream, data) {
14743
14860
  const bytes = typeof data === "string" ? this.encoder.encode(data) : data;
14744
- return this.opentui.symbols.streamWrite(stream, ptr5(bytes), bytes.length);
14861
+ return this.opentui.symbols.streamWrite(stream, ptr(bytes), bytes.length);
14745
14862
  }
14746
14863
  streamCommit(stream) {
14747
14864
  return this.opentui.symbols.streamCommit(stream);
14748
14865
  }
14749
14866
  streamDrainSpans(stream, outBuffer, maxSpans) {
14750
- const count = this.opentui.symbols.streamDrainSpans(stream, ptr5(outBuffer), maxSpans);
14867
+ const count = this.opentui.symbols.streamDrainSpans(stream, ptr(outBuffer), maxSpans);
14751
14868
  return toNumber(count);
14752
14869
  }
14753
14870
  streamClose(stream) {
@@ -14755,11 +14872,11 @@ class FFIRenderLib {
14755
14872
  }
14756
14873
  streamSetOptions(stream, options) {
14757
14874
  const optionsBuffer = NativeSpanFeedOptionsStruct.pack(options);
14758
- return this.opentui.symbols.streamSetOptions(stream, ptr5(optionsBuffer));
14875
+ return this.opentui.symbols.streamSetOptions(stream, ptr(optionsBuffer));
14759
14876
  }
14760
14877
  streamGetStats(stream) {
14761
14878
  const statsBuffer = new ArrayBuffer(NativeSpanFeedStatsStruct.size);
14762
- const status = this.opentui.symbols.streamGetStats(stream, ptr5(statsBuffer));
14879
+ const status = this.opentui.symbols.streamGetStats(stream, ptr(statsBuffer));
14763
14880
  if (status !== 0) {
14764
14881
  return null;
14765
14882
  }
@@ -14773,7 +14890,7 @@ class FFIRenderLib {
14773
14890
  }
14774
14891
  streamReserve(stream, minLen) {
14775
14892
  const reserveBuffer = new ArrayBuffer(ReserveInfoStruct.size);
14776
- const status = this.opentui.symbols.streamReserve(stream, minLen, ptr5(reserveBuffer));
14893
+ const status = this.opentui.symbols.streamReserve(stream, minLen, ptr(reserveBuffer));
14777
14894
  if (status !== 0) {
14778
14895
  return { status, info: null };
14779
14896
  }
@@ -14814,7 +14931,7 @@ class FFIRenderLib {
14814
14931
  return;
14815
14932
  }
14816
14933
  const chunksBuffer = StyledChunkStruct.packList(nonEmptyChunks);
14817
- this.opentui.symbols.editorViewSetPlaceholderStyledText(view, ptr5(chunksBuffer), nonEmptyChunks.length);
14934
+ this.opentui.symbols.editorViewSetPlaceholderStyledText(view, ptr(chunksBuffer), nonEmptyChunks.length);
14818
14935
  }
14819
14936
  editorViewSetTabIndicator(view, indicator) {
14820
14937
  this.opentui.symbols.editorViewSetTabIndicator(view, indicator);
@@ -14869,9 +14986,9 @@ class TextBuffer {
14869
14986
  _textBytes;
14870
14987
  _memId;
14871
14988
  _appendedChunks = [];
14872
- constructor(lib, ptr6) {
14989
+ constructor(lib, ptr3) {
14873
14990
  this.lib = lib;
14874
- this.bufferPtr = ptr6;
14991
+ this.bufferPtr = ptr3;
14875
14992
  }
14876
14993
  static create(widthMethod) {
14877
14994
  const lib = resolveRenderLib();
@@ -16597,9 +16714,9 @@ class TextBufferView {
16597
16714
  viewPtr;
16598
16715
  textBuffer;
16599
16716
  _destroyed = false;
16600
- constructor(lib, ptr6, textBuffer) {
16717
+ constructor(lib, ptr3, textBuffer) {
16601
16718
  this.lib = lib;
16602
- this.viewPtr = ptr6;
16719
+ this.viewPtr = ptr3;
16603
16720
  this.textBuffer = textBuffer;
16604
16721
  }
16605
16722
  static create(textBuffer) {
@@ -16739,19 +16856,19 @@ class EditBuffer extends EventEmitter6 {
16739
16856
  _singleTextBytes = null;
16740
16857
  _singleTextMemId = null;
16741
16858
  _syntaxStyle;
16742
- constructor(lib, ptr6) {
16859
+ constructor(lib, ptr3) {
16743
16860
  super();
16744
16861
  this.lib = lib;
16745
- this.bufferPtr = ptr6;
16746
- this.textBufferPtr = lib.editBufferGetTextBuffer(ptr6);
16747
- this.id = lib.editBufferGetId(ptr6);
16862
+ this.bufferPtr = ptr3;
16863
+ this.textBufferPtr = lib.editBufferGetTextBuffer(ptr3);
16864
+ this.id = lib.editBufferGetId(ptr3);
16748
16865
  EditBuffer.registry.set(this.id, this);
16749
16866
  EditBuffer.subscribeToNativeEvents(lib);
16750
16867
  }
16751
16868
  static create(widthMethod) {
16752
16869
  const lib = resolveRenderLib();
16753
- const ptr6 = lib.createEditBuffer(widthMethod);
16754
- return new EditBuffer(lib, ptr6);
16870
+ const ptr3 = lib.createEditBuffer(widthMethod);
16871
+ return new EditBuffer(lib, ptr3);
16755
16872
  }
16756
16873
  static subscribeToNativeEvents(lib) {
16757
16874
  if (EditBuffer.nativeEventsSubscribed)
@@ -17044,9 +17161,9 @@ class EditorView {
17044
17161
  _destroyed = false;
17045
17162
  _extmarksController;
17046
17163
  _textBufferViewPtr;
17047
- constructor(lib, ptr6, editBuffer) {
17164
+ constructor(lib, ptr3, editBuffer) {
17048
17165
  this.lib = lib;
17049
- this.viewPtr = ptr6;
17166
+ this.viewPtr = ptr3;
17050
17167
  this.editBuffer = editBuffer;
17051
17168
  }
17052
17169
  static create(editBuffer, viewportWidth, viewportHeight) {
@@ -17265,14 +17382,14 @@ class SyntaxStyle {
17265
17382
  nameCache = new Map;
17266
17383
  styleDefs = new Map;
17267
17384
  mergedCache = new Map;
17268
- constructor(lib, ptr6) {
17385
+ constructor(lib, ptr3) {
17269
17386
  this.lib = lib;
17270
- this.stylePtr = ptr6;
17387
+ this.stylePtr = ptr3;
17271
17388
  }
17272
17389
  static create() {
17273
17390
  const lib = resolveRenderLib();
17274
- const ptr6 = lib.createSyntaxStyle();
17275
- return new SyntaxStyle(lib, ptr6);
17391
+ const ptr3 = lib.createSyntaxStyle();
17392
+ return new SyntaxStyle(lib, ptr3);
17276
17393
  }
17277
17394
  static fromTheme(theme) {
17278
17395
  const style = SyntaxStyle.create();
@@ -21372,6 +21489,7 @@ var CliRenderEvents;
21372
21489
  CliRenderEvents2["FOCUSED_RENDERABLE"] = "focused_renderable";
21373
21490
  CliRenderEvents2["FOCUSED_EDITOR"] = "focused_editor";
21374
21491
  CliRenderEvents2["THEME_MODE"] = "theme_mode";
21492
+ CliRenderEvents2["PALETTE"] = "palette";
21375
21493
  CliRenderEvents2["CAPABILITIES"] = "capabilities";
21376
21494
  CliRenderEvents2["SELECTION"] = "selection";
21377
21495
  CliRenderEvents2["DEBUG_OVERLAY_TOGGLE"] = "debugOverlay:toggle";
@@ -21459,6 +21577,7 @@ class CliRenderer extends EventEmitter9 {
21459
21577
  animationRequest = new Map;
21460
21578
  resizeTimeoutId = null;
21461
21579
  capabilityTimeoutId = null;
21580
+ xtVersionWaiters = new Set;
21462
21581
  splitStartupSeedTimeoutId = null;
21463
21582
  pendingSplitStartupCursorSeed = false;
21464
21583
  resizeDebounceDelay = 100;
@@ -21508,11 +21627,11 @@ class CliRenderer extends EventEmitter9 {
21508
21627
  _openConsoleOnError = true;
21509
21628
  _paletteDetector = null;
21510
21629
  _paletteCache = new Map;
21511
- _cachedPalette = null;
21512
21630
  _paletteDetectionPromise = null;
21513
21631
  _paletteDetectionSize = 0;
21514
21632
  _paletteEpoch = 0;
21515
- _publishedPaletteSignature = null;
21633
+ _nativePaletteSignature = null;
21634
+ _emittedPaletteSignature = null;
21516
21635
  _palettePublishGeneration = 0;
21517
21636
  _onDestroy;
21518
21637
  themeModeState;
@@ -21631,6 +21750,10 @@ Captured external output:
21631
21750
  this.themeModeHandler = (sequence) => {
21632
21751
  const result = this.themeModeState.handleSequence(sequence);
21633
21752
  if (result.changedMode) {
21753
+ this.clearPaletteCache();
21754
+ if (this.shouldSyncNativePaletteState() || this.listenerCount("palette" /* PALETTE */) > 0) {
21755
+ this.refreshPalette();
21756
+ }
21634
21757
  this.emit("theme_mode" /* THEME_MODE */, result.changedMode);
21635
21758
  }
21636
21759
  return result.handled;
@@ -22797,6 +22920,7 @@ Captured external output:
22797
22920
  explicitWidthCprActive: false,
22798
22921
  startupCursorCprActive: false
22799
22922
  }, true);
22923
+ this.resolveXtVersionWaiters();
22800
22924
  }, 5000);
22801
22925
  if (this._useMouse) {
22802
22926
  this.enableMouse();
@@ -22818,7 +22942,9 @@ Captured external output:
22818
22942
  }, 120);
22819
22943
  }
22820
22944
  this.queryPixelResolution();
22821
- this.ensureNativePaletteState();
22945
+ if (this.shouldSyncNativePaletteState()) {
22946
+ this.refreshPalette();
22947
+ }
22822
22948
  }
22823
22949
  stdinListener = ((chunk) => {
22824
22950
  const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
@@ -22861,6 +22987,9 @@ Captured external output:
22861
22987
  }
22862
22988
  this.lib.processCapabilityResponse(this.rendererPtr, sequence);
22863
22989
  this._capabilities = this.lib.getTerminalCapabilities(this.rendererPtr);
22990
+ if (this._capabilities?.terminal?.from_xtversion) {
22991
+ this.resolveXtVersionWaiters();
22992
+ }
22864
22993
  if (hasStandardCapabilitySignature) {
22865
22994
  this.forceFullRepaintRequested = true;
22866
22995
  this.requestRender();
@@ -23579,9 +23708,10 @@ Captured external output:
23579
23708
  this._paletteCache.clear();
23580
23709
  this._paletteDetectionPromise = null;
23581
23710
  this._paletteDetectionSize = 0;
23582
- this._cachedPalette = null;
23583
- this._publishedPaletteSignature = null;
23711
+ this._nativePaletteSignature = null;
23712
+ this._emittedPaletteSignature = null;
23584
23713
  this._paletteEpoch = 0;
23714
+ this.resolveXtVersionWaiters();
23585
23715
  this.themeModeState.dispose();
23586
23716
  this.emit("destroy" /* DESTROY */);
23587
23717
  try {
@@ -23898,40 +24028,72 @@ Captured external output:
23898
24028
  }
23899
24029
  ensurePaletteDetector() {
23900
24030
  if (!this._paletteDetector) {
24031
+ const isTmux = Boolean(this.capabilities?.in_tmux || this.capabilities?.terminal?.name?.toLowerCase()?.includes("tmux"));
23901
24032
  const isLegacyTmux = this.capabilities?.terminal?.name?.toLowerCase()?.includes("tmux") && this.capabilities?.terminal?.version?.localeCompare("3.6") < 0;
23902
- this._paletteDetector = createTerminalPalette(this.stdin, this.stdout, (data) => this._isDestroyed ? false : this.writeOut(data), isLegacyTmux, {
23903
- subscribeOsc: this.subscribeOsc.bind(this)
23904
- }, this.clock);
24033
+ this._paletteDetector = createTerminalPalette({
24034
+ stdin: this.stdin,
24035
+ stdout: this.stdout,
24036
+ writeFn: (data) => this._isDestroyed ? false : this.writeOut(data),
24037
+ isLegacyTmux,
24038
+ isTmux,
24039
+ oscSource: {
24040
+ subscribeOsc: this.subscribeOsc.bind(this)
24041
+ },
24042
+ clock: this.clock
24043
+ });
23905
24044
  }
23906
24045
  return this._paletteDetector;
23907
24046
  }
23908
24047
  syncNativePaletteState(colors) {
23909
24048
  const signature = buildTerminalPaletteSignature(colors);
23910
- if (this._publishedPaletteSignature !== signature) {
24049
+ if (this._nativePaletteSignature !== signature) {
23911
24050
  this._paletteEpoch = this._paletteEpoch + 1 >>> 0;
23912
24051
  }
23913
- this._publishedPaletteSignature = signature;
24052
+ this._nativePaletteSignature = signature;
23914
24053
  const normalized = normalizeTerminalPalette(colors);
23915
24054
  this.lib.rendererSetPaletteState(this.rendererPtr, normalized.palette, normalized.defaultForeground, normalized.defaultBackground, this._paletteEpoch);
23916
24055
  }
23917
- ensureNativePaletteState() {
23918
- if (!this._terminalIsSetup || this._isDestroyed)
24056
+ emitPaletteChange(colors) {
24057
+ if (this.listenerCount("palette" /* PALETTE */) === 0)
24058
+ return;
24059
+ const signature = buildTerminalPaletteSignature(colors);
24060
+ if (this._emittedPaletteSignature === signature)
24061
+ return;
24062
+ this._emittedPaletteSignature = signature;
24063
+ this.emit("palette" /* PALETTE */, colors);
24064
+ }
24065
+ resolveXtVersionWaiters() {
24066
+ if (this.xtVersionWaiters.size === 0)
23919
24067
  return;
24068
+ const resolvers = [...this.xtVersionWaiters];
24069
+ this.xtVersionWaiters.clear();
24070
+ for (const resolve4 of resolvers) {
24071
+ resolve4();
24072
+ }
24073
+ }
24074
+ waitForXtVersion() {
24075
+ if (this.capabilityTimeoutId === null || this._capabilities?.terminal?.from_xtversion) {
24076
+ return Promise.resolve();
24077
+ }
24078
+ return new Promise((resolve4) => {
24079
+ this.xtVersionWaiters.add(resolve4);
24080
+ });
24081
+ }
24082
+ shouldSyncNativePaletteState() {
24083
+ return Boolean(this._terminalIsSetup && !this._isDestroyed && this._capabilities?.ansi256 && !this._capabilities?.rgb);
24084
+ }
24085
+ refreshPalette() {
23920
24086
  const publishGeneration = this._palettePublishGeneration;
23921
- this.getPalette({ size: NATIVE_PALETTE_QUERY_SIZE }).then((colors) => {
24087
+ this.getPalette({ size: NATIVE_PALETTE_QUERY_SIZE }).then(() => {
23922
24088
  if (this._isDestroyed)
23923
24089
  return;
23924
- if (this._palettePublishGeneration === publishGeneration) {
23925
- this.syncNativePaletteState(colors);
23926
- }
23927
- if (this._isDestroyed)
23928
- return;
23929
- this.requestRender();
24090
+ if (this._palettePublishGeneration === publishGeneration)
24091
+ this.requestRender();
23930
24092
  }).catch(() => {});
23931
24093
  }
23932
24094
  clearPaletteCache() {
24095
+ this._palettePublishGeneration++;
23933
24096
  this._paletteCache.clear();
23934
- this._cachedPalette = null;
23935
24097
  }
23936
24098
  async getPalette(options) {
23937
24099
  if (this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
@@ -23941,15 +24103,22 @@ Captured external output:
23941
24103
  const detectionTimeout = options?.timeout;
23942
24104
  const cachedPalette = this.getCachedPaletteBySize(requestedSize);
23943
24105
  if (cachedPalette) {
23944
- this._cachedPalette = cachedPalette;
23945
24106
  return cachedPalette;
23946
24107
  }
24108
+ const terminal = this._capabilities?.terminal;
24109
+ const hasTmuxVersion = terminal?.name?.toLowerCase() === "tmux" && Boolean(terminal.version);
24110
+ if (this._capabilities?.in_tmux && !hasTmuxVersion) {
24111
+ await this.waitForXtVersion();
24112
+ const afterCapabilityWait = this.getCachedPaletteBySize(requestedSize);
24113
+ if (afterCapabilityWait) {
24114
+ return afterCapabilityWait;
24115
+ }
24116
+ }
23947
24117
  if (this._paletteDetectionPromise) {
23948
24118
  if (this._paletteDetectionSize >= requestedSize) {
23949
24119
  return this._paletteDetectionPromise.then((palette) => {
23950
24120
  const cached = this.getCachedPaletteBySize(requestedSize);
23951
24121
  if (cached) {
23952
- this._cachedPalette = cached;
23953
24122
  return cached;
23954
24123
  }
23955
24124
  const projected = {
@@ -23957,14 +24126,12 @@ Captured external output:
23957
24126
  palette: palette.palette.slice(0, requestedSize)
23958
24127
  };
23959
24128
  this._paletteCache.set(requestedSize, projected);
23960
- this._cachedPalette = projected;
23961
24129
  return projected;
23962
24130
  });
23963
24131
  }
23964
24132
  await this._paletteDetectionPromise;
23965
24133
  const afterWait = this.getCachedPaletteBySize(requestedSize);
23966
24134
  if (afterWait) {
23967
- this._cachedPalette = afterWait;
23968
24135
  return afterWait;
23969
24136
  }
23970
24137
  }
@@ -23973,14 +24140,14 @@ Captured external output:
23973
24140
  this._paletteDetectionSize = requestedSize;
23974
24141
  this._paletteDetectionPromise = detector.detect({ ...options, timeout: detectionTimeout }).then((result) => {
23975
24142
  this._paletteCache.set(result.palette.length, result);
23976
- this._cachedPalette = result;
23977
24143
  this._paletteDetectionPromise = null;
23978
24144
  this._paletteDetectionSize = 0;
23979
24145
  if (!this._isDestroyed && this._palettePublishGeneration === publishGeneration) {
23980
- if (result.palette.length >= NATIVE_PALETTE_QUERY_SIZE) {
24146
+ this.emitPaletteChange(result);
24147
+ if (this.shouldSyncNativePaletteState() && result.palette.length >= NATIVE_PALETTE_QUERY_SIZE) {
23981
24148
  this.syncNativePaletteState(result);
23982
- } else if (this._terminalIsSetup && !this._paletteCache.has(NATIVE_PALETTE_QUERY_SIZE)) {
23983
- this.ensureNativePaletteState();
24149
+ } else if (this.shouldSyncNativePaletteState() && !this._paletteCache.has(NATIVE_PALETTE_QUERY_SIZE)) {
24150
+ this.refreshPalette();
23984
24151
  }
23985
24152
  }
23986
24153
  return result;
@@ -23991,12 +24158,11 @@ Captured external output:
23991
24158
  });
23992
24159
  const detected = await this._paletteDetectionPromise;
23993
24160
  const finalPalette = this.getCachedPaletteBySize(requestedSize) ?? detected;
23994
- this._cachedPalette = finalPalette;
23995
24161
  return finalPalette;
23996
24162
  }
23997
24163
  }
23998
24164
 
23999
- export { __export, __require, MeasureMode, exports_src, isValidBorderStyle, parseBorderStyle, BorderChars, getBorderFromSides, getBorderSides, borderCharsToArray, BorderCharArrays, KeyEvent, PasteEvent, KeyHandler, InternalKeyHandler, DEFAULT_FOREGROUND_RGB, DEFAULT_BACKGROUND_RGB, normalizeIndexedColorIndex, ansi256IndexToRgb, RGBA, normalizeColorValue, hexToRgb, rgbToHex, hsvToRgb, parseColor, fonts, measureText, getCharacterPositions, coordinateToCharacterIndex, renderFontToFrameBuffer, TextAttributes, ATTRIBUTE_BASE_BITS, ATTRIBUTE_BASE_MASK, getBaseAttributes, DebugOverlayCorner, TargetChannel, createTextAttributes, attributesWithLink, getLinkId, visualizeRenderableTree, isStyledText, StyledText, stringToStyledText, black, red, green, yellow, blue, magenta, cyan, white, brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, bold, italic, underline, strikethrough, dim, reverse, blink, fg, bg, link, t, hastToStyledText, SystemClock, nonAlphanumericKeys, terminalNamedSingleStrokeKeys, parseKeypress, LinearScrollAccel, MacOSScrollAccel, parseAlign, parseAlignItems, parseBoxSizing, parseDimension, parseDirection, parseDisplay, parseEdge, parseFlexDirection, parseGutter, parseJustify, parseLogLevel, parseMeasureMode, parseOverflow, parsePositionType, parseUnit, parseWrap, MouseParser, Selection, convertGlobalToLocalSelection, ASCIIFontSelectionHelper, envRegistry, registerEnvVar, clearEnvCache, generateEnvMarkdown, generateEnvColored, env, StdinParser, treeSitterToTextChunks, treeSitterToStyledText, addDefaultParsers, TreeSitterClient, DataPathsManager, getDataPaths, extensionToFiletype, basenameToFiletype, extToFiletype, pathToFiletype, infoStringToFiletype, main, getTreeSitterClient, ExtmarksController, createExtmarksController, TerminalPalette, createTerminalPalette, normalizeTerminalPalette, buildTerminalPaletteSignature, decodePasteBytes, stripAnsiSequences, detectLinks, TextBuffer, SpanInfoStruct, toPointer, LogLevel2 as LogLevel, setRenderLibPath, resolveRenderLib, OptimizedBuffer, h, isVNode, maybeMakeRenderable, wrapWithDelegates, instantiate, delegate, LayoutEvents, RenderableEvents, isRenderable, BaseRenderable, Renderable, RootRenderable, TextBufferView, EditBuffer, EditorView, convertThemeToStyles, SyntaxStyle, ANSI, BoxRenderable, TextBufferRenderable, CodeRenderable, isTextNodeRenderable, TextNodeRenderable, RootTextNodeRenderable, TextRenderable, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture, ConsolePosition, TerminalConsole, getObjectsInViewport, EditBufferRenderableEvents, isEditBufferRenderable, EditBufferRenderable, calculateRenderGeometry, buildKittyKeyboardFlags, MouseEvent, MouseButton, createCliRenderer, CliRenderEvents, RendererControlState, CliRenderer };
24165
+ export { __export, __require, MeasureMode, exports_src, isValidBorderStyle, parseBorderStyle, BorderChars, getBorderFromSides, getBorderSides, borderCharsToArray, BorderCharArrays, KeyEvent, PasteEvent, KeyHandler, InternalKeyHandler, DEFAULT_FOREGROUND_RGB, DEFAULT_BACKGROUND_RGB, normalizeIndexedColorIndex, ansi256IndexToRgb, RGBA, normalizeColorValue, hexToRgb, rgbToHex, hsvToRgb, parseColor, fonts, measureText, getCharacterPositions, coordinateToCharacterIndex, renderFontToFrameBuffer, TextAttributes, ATTRIBUTE_BASE_BITS, ATTRIBUTE_BASE_MASK, getBaseAttributes, DebugOverlayCorner, TargetChannel, createTextAttributes, attributesWithLink, getLinkId, visualizeRenderableTree, isStyledText, StyledText, stringToStyledText, black, red, green, yellow, blue, magenta, cyan, white, brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, bold, italic, underline, strikethrough, dim, reverse, blink, fg, bg, link, t, hastToStyledText, SystemClock, nonAlphanumericKeys, terminalNamedSingleStrokeKeys, parseKeypress, LinearScrollAccel, MacOSScrollAccel, parseAlign, parseAlignItems, parseBoxSizing, parseDimension, parseDirection, parseDisplay, parseEdge, parseFlexDirection, parseGutter, parseJustify, parseLogLevel, parseMeasureMode, parseOverflow, parsePositionType, parseUnit, parseWrap, MouseParser, Selection, convertGlobalToLocalSelection, ASCIIFontSelectionHelper, envRegistry, registerEnvVar, clearEnvCache, generateEnvMarkdown, generateEnvColored, env, StdinParser, treeSitterToTextChunks, treeSitterToStyledText, addDefaultParsers, TreeSitterClient, DataPathsManager, getDataPaths, extensionToFiletype, basenameToFiletype, extToFiletype, pathToFiletype, infoStringToFiletype, main, getTreeSitterClient, ExtmarksController, createExtmarksController, TerminalPalette, createTerminalPalette, normalizeTerminalPalette, buildTerminalPaletteSignature, decodePasteBytes, stripAnsiSequences, detectLinks, toArrayBuffer, TextBuffer, SpanInfoStruct, LogLevel2 as LogLevel, setRenderLibPath, resolveRenderLib, OptimizedBuffer, h, isVNode, maybeMakeRenderable, wrapWithDelegates, instantiate, delegate, LayoutEvents, RenderableEvents, isRenderable, BaseRenderable, Renderable, RootRenderable, TextBufferView, EditBuffer, EditorView, convertThemeToStyles, SyntaxStyle, ANSI, BoxRenderable, TextBufferRenderable, CodeRenderable, isTextNodeRenderable, TextNodeRenderable, RootTextNodeRenderable, TextRenderable, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture, ConsolePosition, TerminalConsole, getObjectsInViewport, EditBufferRenderableEvents, isEditBufferRenderable, EditBufferRenderable, calculateRenderGeometry, buildKittyKeyboardFlags, MouseEvent, MouseButton, createCliRenderer, CliRenderEvents, RendererControlState, CliRenderer };
24000
24166
 
24001
- //# debugId=C97131CABF4DEE6A64756E2164756E21
24002
- //# sourceMappingURL=index-b9g14b8c.js.map
24167
+ //# debugId=74349463B90D49D364756E2164756E21
24168
+ //# sourceMappingURL=index-jv9g79dk.js.map